answer
stringlengths
17
10.2M
package com.infinityraider.infinitylib.network; import com.infinityraider.infinitylib.InfinityLib; import io.netty.buffer.ByteBuf; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraftforge.fml.common.network.ByteBufUtils; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; import net.minecraftforge.fml.relauncher.Side; @SuppressWarnings("unused") public abstract class MessageBase<REPLY extends IMessage> implements IMessage { public MessageBase() { super(); } public abstract Side getMessageHandlerSide(); protected abstract void processMessage(MessageContext ctx); protected abstract REPLY getReply(MessageContext ctx); protected String readStringFromByteBuf(ByteBuf buf) { return ByteBufUtils.readUTF8String(buf); } protected void writeStringToByteBuf(ByteBuf buf, String string) { ByteBufUtils.writeUTF8String(buf, string); } protected EntityPlayer readPlayerFromByteBuf(ByteBuf buf) { Entity entity = readEntityFromByteBuf(buf); return (entity instanceof EntityPlayer)?(EntityPlayer) entity:null; } protected void writePlayerToByteBuf(ByteBuf buf, EntityPlayer player) { writeEntityToByteBuf(buf, player); } protected Entity readEntityFromByteBuf(ByteBuf buf) { int id = buf.readInt(); if(id < 0) { return null; } int dimension = buf.readInt(); return InfinityLib.proxy.getEntityById(dimension, id); } protected void writeEntityToByteBuf(ByteBuf buf, Entity e) { if (e == null) { buf.writeInt(-1); buf.writeInt(0); } else { buf.writeInt(e.getEntityId()); buf.writeInt(e.worldObj.provider.getDimension()); } } protected BlockPos readBlockPosFromByteBuf(ByteBuf buf) { return new BlockPos(buf.readInt(), buf.readInt(), buf.readInt()); } protected ByteBuf writeBlockPosToByteBuf(ByteBuf buf, BlockPos pos) { buf.writeInt(pos.getX()); buf.writeInt(pos.getY()); buf.writeInt(pos.getZ()); return buf; } protected Item readItemFromByteBuf(ByteBuf buf) { int itemNameLength = buf.readInt(); String itemName = new String(buf.readBytes(itemNameLength).array()); return Item.REGISTRY.getObject(new ResourceLocation(itemName)); } protected void writeItemToByteBuf(Item item, ByteBuf buf) { String itemName = item==null?"null":Item.REGISTRY.getNameForObject(item).toString(); buf.writeInt(itemName.length()); buf.writeBytes(itemName.getBytes()); } protected ItemStack readItemStackFromByteBuf(ByteBuf buf) { return ByteBufUtils.readItemStack(buf); } protected void writeItemStackToByteBuf(ByteBuf buf, ItemStack stack) { ByteBufUtils.writeItemStack(buf, stack); } protected NBTTagCompound readNBTFromByteBuf(ByteBuf buf) { return ByteBufUtils.readTag(buf); } protected void writeNBTToByteBuf(ByteBuf buf, NBTTagCompound tag) { ByteBufUtils.writeTag(buf, tag); } protected int[] readIntArrayFromByteBuf(ByteBuf buf) { int amount = buf.readInt(); int[] array = new int[amount]; for(int i = 0; i < amount; i++) { array[i] = buf.readInt(); } return array; } protected void writeIntArrayToByteBuf(ByteBuf buf, int[] array) { buf.writeInt(array.length); for(int i = 0; i < array.length; i++) { buf.writeInt(array[i]); } } }
package com.jumanjicraft.BungeeChatClient; import com.dthielke.Herochat; import com.dthielke.api.Channel; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; import org.bukkit.entity.Player; import org.bukkit.plugin.messaging.PluginMessageListener; public class BungeeChatSender implements PluginMessageListener { private final BungeeChatClient plugin; /** * * @param plugin */ public BungeeChatSender(BungeeChatClient plugin) { this.plugin = plugin; register(); } private void register() { plugin.getServer().getMessenger().registerIncomingPluginChannel(plugin, "BungeeChat", this); plugin.getServer().getMessenger().registerOutgoingPluginChannel(plugin, "BungeeChat"); } /** * * @param cm */ public void TransmitChatMessage(ChatMessage cm) { ByteArrayDataOutput out = ByteStreams.newDataOutput(); /* My custom tag */ out.writeUTF("PurpleBungeeIRC"); /* Herochat tokens */ out.writeUTF(cm.getChannel()); out.writeUTF(cm.getMessage()); out.writeUTF(cm.getSender()); out.writeUTF(cm.getHeroColor()); out.writeUTF(cm.getHeroNick()); /* Vault tokens */ out.writeUTF(cm.getPlayerPrefix()); out.writeUTF(cm.getPlayerSuffix()); out.writeUTF(cm.getGroupPrefix()); out.writeUTF(cm.getGroupSuffix()); out.writeUTF(cm.getPlayerGroup()); plugin.getServer().sendPluginMessage(plugin, "BungeeChat", out.toByteArray()); } @Override public void onPluginMessageReceived(String tag, Player player, byte[] data) { if (!tag.equalsIgnoreCase("BungeeChat")) { return; } ByteArrayDataInput in = ByteStreams.newDataInput(data); String chatchannel = in.readUTF(); String message = in.readUTF(); plugin.logDebug("chatChannel: " + chatchannel); plugin.logDebug("message: " + message); Channel channel = Herochat.getChannelManager().getChannel(chatchannel); if (channel == null) { return; } channel.sendRawMessage(message); } }
package com.mijecu25.personalbackup.visitors; import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.mijecu25.dsa.DataStructures.LinkedListQueue; import com.mijecu25.personalbackup.file.Directory; import com.mijecu25.personalbackup.file.Path; import com.mijecu25.personalbackup.file.Record; /** * Recursive file tree visitor that backs up records and directories. * * @author Miguel Velez * @version 0.1.1.4 */ public class BackupVisitor implements Runnable, FileVisitor { private static final Logger logger = LogManager.getLogger(BackupVisitor.class); private Directory source; private Directory destination; private LinkedListQueue pathsQueue; private List<Thread> children; private boolean isDone; /** * Create a new BackupManager. */ public BackupVisitor(String source, String destination) { this.source = new Directory(source); this.destination = new Directory(destination); this.pathsQueue = new LinkedListQueue(); this.children = new ArrayList<Thread>(); this.isDone = false; BackupVisitor.logger.info("Created a new BackupVisitor object"); BackupVisitor.logger.info("Source: " + this.source); BackupVisitor.logger.info("Destination: " + this.destination); // Add the source directory in the queue this.pathsQueue.enqueue(this.source); } /** * Execute the general logic of backing up files */ @Override public void run() { BackupVisitor.logger.info("Executing Backup Visitor main logic"); // Synchronize the backup manager main logic synchronized(this) { // Create holder for current path Path currentPath; // While there are more files to process while(!this.pathsQueue.isEmpty()) { try { // dequeue the next file currentPath = (Path) this.pathsQueue.dequeue(); // Pass this visitor to the current path currentPath.accept(this); Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Notify a thread waiting for the backup manager that it can continue this.notify(); // The backup manager is done executing this.isDone = true; } } /** * Starts a new thread and returns a reference to it. * * @return a reference to this thread. */ public Thread startAsThread() { // Create a new thread of this class Thread thread; thread = new Thread(this); // Start the thread thread.start(); // Return reference to thread return thread; } /** * Return a value indicating the state of the backup manager * * @return a boolean value indicating if the backup manager is done processing */ public boolean isDone() { return this.isDone; } /** * Visit a record object. Copy the record from the source to the destination. * * @param record * @return object that is returned after visiting a record. */ @Override public Object visitRecord(Record record) { BackupVisitor.logger.info(Thread.currentThread().getName() + " - " + record.getPath()); if(record.getName().equals("File2.png")) { try { System.out.println("Wiating"); Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } // We do not need to return anything return null; } /** * Visit a directory object. * * @param directory * @return object that is returned after visiting a directory. */ @Override public Object visitDirectory(Directory directory) { String newDestination = ""; // Get the child paths Path[] childPaths = directory.listPaths(); // Loop through every child for(Path child : childPaths) { // if(child.equals(this.source)) { // continue; // If the child is a record if(child instanceof Record) { // Added to the queue to process this.pathsQueue.enqueue(child); } // If the child is a directory else if(child instanceof Directory) { // Get the new destination newDestination = this.getDestinationDirectory(child.getName()); // Create a new backup visitor with the child's path and its destination BackupVisitor childVisitor = new BackupVisitor(child.getPath(), newDestination); // Add the thread to the list of children threads of this visitor this.children.add(childVisitor.startAsThread()); } } // Loop through all the threads of this visitor for(Thread thread : this.children) { try { // Wait until this thread dies thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } // We do not need to return anything return null; } /** * Get the destination directory of the source directory. * * @param source directory * * @return string that represents the new destination directory */ private String getDestinationDirectory(String source) { // The destination is the destination of this visitor + the source return this.destination + "\\" + source; } } /** This method builds the path of the file in the server. It can be * used to for files and folders. * private StringBuilder buildServerPath(File tmpFile) { StringBuilder destPath = new StringBuilder(this.getDest()); destPath = new StringBuilder(this.getDest()); destPath.append(this.getSrc().substring(this.getSrc().indexOf("/"))); destPath.append(tmpFile.getAbsolutePath().substring(this.getSrc().length()).toString()); return destPath; } private void checkDeleteFromServer(File[] tmpFiles, File[] srvFiles) throws IOException { List<String> checkList; String[] srcFiles = new String[tmpFiles.length]; String[] serverFiles = new String[srvFiles.length]; for(int i=0; i < tmpFiles.length; i++){ srcFiles[i] = tmpFiles[i].getName(); } for(int i=0; i < srvFiles.length; i++){ serverFiles[i] = srvFiles[i].getName(); } checkList = Arrays.asList(srcFiles); for(int i=0; i < serverFiles.length; i++) { if(!checkList.contains(serverFiles[i])) { this.deleteFromServer(srvFiles[i]); this.setDeletes(this.getDeletes()+1); } } } } */
package com.nigelbrown.fluxion.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FluxRecyclerView {}
package com.rarchives.ripme.ripper.rippers; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.time.*; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.security.*; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.rarchives.ripme.ripper.AbstractJSONRipper; import com.rarchives.ripme.utils.Http; import org.jsoup.Connection; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import com.rarchives.ripme.ui.RipStatusMessage; import com.rarchives.ripme.utils.Utils; import java.util.HashMap; public class InstagramRipper extends AbstractJSONRipper { String nextPageID = ""; private String qHash; private boolean rippingTag = false; private String tagName; private String userID; private String rhx_gis = null; private String csrftoken; public InstagramRipper(URL url) throws IOException { super(url); } @Override public String getHost() { return "instagram"; } @Override public String getDomain() { return "instagram.com"; } @Override public boolean canRip(URL url) { return (url.getHost().endsWith("instagram.com")); } @Override public URL sanitizeURL(URL url) throws MalformedURLException { URL san_url = new URL(url.toExternalForm().replaceAll("\\?hl=\\S*", "")); LOGGER.info("sanitized URL is " + san_url.toExternalForm()); return san_url; } @Override public String normalizeUrl(String url) { // Remove the date sig from the url return url.replaceAll("/[A-Z0-9]{8}/", "/"); } @Override public boolean hasASAPRipping() { return true; } @Override public String getGID(URL url) throws MalformedURLException { Pattern p = Pattern.compile("^https?://instagram.com/([^/]+)/?"); Matcher m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } p = Pattern.compile("^https?: m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } p = Pattern.compile("^https?: m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(2) + "_" + m.group(1); } p = Pattern.compile("^https?: m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } p = Pattern.compile("^https?: m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } p = Pattern.compile("^https?: m = p.matcher(url.toExternalForm()); if (m.matches()) { rippingTag = true; tagName = m.group(1); return m.group(1); } throw new MalformedURLException("Unable to find user in " + url); } private String stripHTMLTags(String t) { t = t.replaceAll("<html>\n" + " <head></head>\n" + " <body>", ""); t.replaceAll("</body>\n" + "</html>", ""); t = t.replaceAll("\n", ""); t = t.replaceAll("=\"\"", ""); return t; } private JSONObject getJSONFromPage(Document firstPage) throws IOException { // Check if this page is HTML + JSON or jsut json if (!firstPage.html().contains("window._sharedData =")) { return new JSONObject(stripHTMLTags(firstPage.html())); } String jsonText = ""; try { for (Element script : firstPage.select("script[type=text/javascript]")) { if (script.data().contains("window._sharedData = ")) { jsonText = script.data().replaceAll("window._sharedData = ", ""); jsonText = jsonText.replaceAll("};", "}"); } } return new JSONObject(jsonText); } catch (JSONException e) { throw new IOException("Could not get JSON from page"); } } @Override public JSONObject getFirstPage() throws IOException { Connection.Response resp = Http.url(url).response(); LOGGER.info(resp.cookies()); csrftoken = resp.cookie("csrftoken"); Document p = resp.parse(); // Get the query hash so we can download the next page qHash = getQHash(p); if (qHash == null) { throw new IOException("Unable to extract qhash from page"); } return getJSONFromPage(p); } private String getVideoFromPage(String videoID) { try { Document doc = Http.url("https: return doc.select("meta[property=og:video]").attr("content"); } catch (IOException e) { LOGGER.warn("Unable to get page " + "https: } return ""; } private String getOriginalUrl(String imageURL) { // Without this regex most images will return a 403 error imageURL = imageURL.replaceAll("vp/[a-zA-Z0-9]*/", ""); imageURL = imageURL.replaceAll("scontent.cdninstagram.com/hphotos-", "igcdn-photos-d-a.akamaihd.net/hphotos-ak-"); // Instagram returns cropped images to unauthenticated applications to maintain legacy support. // To retrieve the uncropped image, remove this segment from the URL. // Segment format: cX.Y.W.H - eg: c0.134.1080.1080 imageURL = imageURL.replaceAll("/c\\d{1,4}\\.\\d{1,4}\\.\\d{1,4}\\.\\d{1,4}", ""); imageURL = imageURL.replaceAll("\\?ig_cache_key.+$", ""); return imageURL; } public String getAfter(JSONObject json) { try { return json.getJSONObject("entry_data").getJSONArray("ProfilePage").getJSONObject(0) .getJSONObject("graphql").getJSONObject("user") .getJSONObject("edge_owner_to_timeline_media").getJSONObject("page_info").getString("end_cursor"); } catch (JSONException e) { // This is here so that when the user rips the last page they don't get a "end_cursor not a string" error try { return json.getJSONObject("data").getJSONObject("user") .getJSONObject("edge_owner_to_timeline_media").getJSONObject("page_info").getString("end_cursor"); } catch (JSONException t) { return ""; } } } @Override public List<String> getURLsFromJSON(JSONObject json) { List<String> imageURLs = new ArrayList<>(); if (!url.toExternalForm().contains("/p/")) { nextPageID = getAfter(json); } // get the rhx_gis value so we can get the next page later on if (rhx_gis == null) { try { rhx_gis = json.getString("rhx_gis"); } catch (JSONException ex) { // Instagram has removed this token, but ... LOGGER.error("Error while getting rhx_gis: " + ex.getMessage()); //... if we set it to "", the next page can still be fetched rhx_gis = ""; } } if (!url.toExternalForm().contains("/p/")) { JSONArray datas = new JSONArray(); if (!rippingTag) { // This first try only works on data from the first page try { JSONArray profilePage = json.getJSONObject("entry_data").getJSONArray("ProfilePage"); userID = profilePage.getJSONObject(0).getString("logging_page_id").replaceAll("profilePage_", ""); datas = json.getJSONObject("entry_data").getJSONArray("ProfilePage").getJSONObject(0) .getJSONObject("graphql").getJSONObject("user") .getJSONObject("edge_owner_to_timeline_media").getJSONArray("edges"); } catch (JSONException e) { datas = json.getJSONObject("data").getJSONObject("user") .getJSONObject("edge_owner_to_timeline_media").getJSONArray("edges"); } } else { try { JSONArray tagPage = json.getJSONObject("entry_data").getJSONArray("TagPage"); datas = tagPage.getJSONObject(0).getJSONObject("graphql").getJSONObject("hashtag") .getJSONObject("edge_hashtag_to_media").getJSONArray("edges"); } catch (JSONException e) { datas = json.getJSONObject("data").getJSONObject("hashtag").getJSONObject("edge_hashtag_to_media") .getJSONArray("edges"); } } for (int i = 0; i < datas.length(); i++) { JSONObject data = (JSONObject) datas.get(i); data = data.getJSONObject("node"); Long epoch = data.getLong("taken_at_timestamp"); Instant instant = Instant.ofEpochSecond(epoch); String image_date = DateTimeFormatter.ofPattern("yyyy_MM_dd_hh:mm_").format(ZonedDateTime.ofInstant(instant, ZoneOffset.UTC)); // It looks like tag pages don't have the __typename key if (!rippingTag) { if (data.getString("__typename").equals("GraphSidecar")) { try { Document slideShowDoc = Http.url(new URL("https: List<JSONObject> toAdd = getPostsFromSinglePage(getJSONFromPage(slideShowDoc)); for (int slideShowInt = 0; slideShowInt < toAdd.size(); slideShowInt++) { addDownloadFromData(toAdd.get(slideShowInt), image_date + data.getString("shortcode")); } } catch (IOException e) { LOGGER.error("Unable to download slide show"); } } } if (!data.getBoolean("is_video")) { if (imageURLs.isEmpty()) { // We add this one item to the array because either wise // the ripper will error out because we returned an empty array imageURLs.add(getOriginalUrl(data.getString("display_url"))); } } // add download from data which handles image vs video addDownloadFromData(data, image_date); if (isThisATest()) { break; } } } else { // We're ripping from a single page LOGGER.info("Ripping from single page"); List<JSONObject> posts = getPostsFromSinglePage(json); imageURLs = getImageURLsFromPosts(posts); } return imageURLs; } private List<JSONObject> getPostsFromSinglePage(JSONObject json) { List<JSONObject> posts = new ArrayList<>(); JSONArray datas; if (json.getJSONObject("entry_data").getJSONArray("PostPage") .getJSONObject(0).getJSONObject("graphql").getJSONObject("shortcode_media") .has("edge_sidecar_to_children")) { datas = json.getJSONObject("entry_data").getJSONArray("PostPage") .getJSONObject(0).getJSONObject("graphql").getJSONObject("shortcode_media") .getJSONObject("edge_sidecar_to_children").getJSONArray("edges"); for (int i = 0; i < datas.length(); i++) { JSONObject data = (JSONObject) datas.get(i); data = data.getJSONObject("node"); posts.add(data); } } else { JSONObject data = json.getJSONObject("entry_data").getJSONArray("PostPage") .getJSONObject(0).getJSONObject("graphql").getJSONObject("shortcode_media"); posts.add(data); } return posts; } private List<String> getImageURLsFromPosts(List<JSONObject> posts) { List<String> imageURLs = new ArrayList<>(); if (posts == null) { LOGGER.error("Failed to get image urls from null posts"); return imageURLs; } for (int i = 0; i < posts.size(); i++) { JSONObject post = posts.get(i); if (post.getBoolean("is_video")) { // always check if video are being ignored if (isIgnoringVideos()) { sendUpdate(RipStatusMessage.STATUS.DOWNLOAD_WARN, "Skipping video " + post.getString("shortcode")); } else { imageURLs.add(post.getString("video_url")); } } else { imageURLs.add(post.getString("display_url")); } } return imageURLs; } // attempt to add download from data, checking for video vs images private void addDownloadFromData(JSONObject data, String prefix) { if (data == null) { LOGGER.error("Failed to add download: null data"); return; } try { if (data.getBoolean("is_video")) { // always check if video are being ignored to honor the setting if (isIgnoringVideos()) { sendUpdate(RipStatusMessage.STATUS.DOWNLOAD_WARN, "Skipping video " + data.getString("shortcode")); } else { addURLToDownload(new URL(getVideoFromPage(data.getString("shortcode"))), prefix); } } else { addURLToDownload(new URL(data.getString("display_url")), prefix); } } catch (MalformedURLException e) { LOGGER.error("Malformed URL from data", e); } } private boolean isIgnoringVideos() { return Utils.getConfigBoolean("instagram.download_images_only", false); } private String getIGGis(String variables) { String stringToMD5 = rhx_gis + ":" + variables; LOGGER.debug("String to md5 is \"" + stringToMD5 + "\""); try { byte[] bytesOfMessage = stringToMD5.getBytes("UTF-8"); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] hash = md.digest(bytesOfMessage); StringBuffer sb = new StringBuffer(); for (int i = 0; i < hash.length; ++i) { sb.append(Integer.toHexString((hash[i] & 0xFF) | 0x100).substring(1,3)); } return sb.toString(); } catch(UnsupportedEncodingException e) { return null; } catch(NoSuchAlgorithmException e) { return null; } } @Override public JSONObject getNextPage(JSONObject json) throws IOException { JSONObject toreturn; java.util.Map<String, String> cookies = new HashMap<String, String>(); // This shouldn't be hardcoded and will break one day cookies.put("ig_pr", "1"); cookies.put("csrftoken", csrftoken); if (!nextPageID.equals("") && !isThisATest()) { if (rippingTag) { try { sleep(2500); String vars = "{\"tag_name\":\"" + tagName + "\",\"first\":4,\"after\":\"" + nextPageID + "\"}"; String ig_gis = getIGGis(vars); toreturn = getPage("https: "&variables=" + vars, ig_gis); // Sleep for a while to avoid a ban LOGGER.info(toreturn); if (!pageHasImages(toreturn)) { throw new IOException("No more pages"); } return toreturn; } catch (IOException e) { throw new IOException("No more pages"); } } try { // Sleep for a while to avoid a ban sleep(2500); String vars = "{\"id\":\"" + userID + "\",\"first\":12,\"after\":\"" + nextPageID + "\"}"; String ig_gis = getIGGis(vars); LOGGER.info(ig_gis); LOGGER.info("https: toreturn = getPage("https: if (!pageHasImages(toreturn)) { throw new IOException("No more pages"); } return toreturn; } catch (IOException e) { return null; } } else { throw new IOException("No more pages"); } } @Override public void downloadURL(URL url, int index) { addURLToDownload(url); } private boolean pageHasImages(JSONObject json) { int numberOfImages = json.getJSONObject("data").getJSONObject("user") .getJSONObject("edge_owner_to_timeline_media").getJSONArray("edges").length(); if (numberOfImages == 0) { return false; } return true; } private JSONObject getPage(String url, String ig_gis) { StringBuilder sb = new StringBuilder(); try { // We can't use Jsoup here because it won't download a non-html file larger than a MB // even if you set maxBodySize to 0 URLConnection connection = new URL(url).openConnection(); connection.setRequestProperty("User-Agent", USER_AGENT); connection.setRequestProperty("x-instagram-gis", ig_gis); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { sb.append(line); } in.close(); return new JSONObject(sb.toString()); } catch (MalformedURLException e) { LOGGER.info("Unable to get page, " + url + " is a malformed URL"); return null; } catch (IOException e) { LOGGER.info("Unable to get page"); LOGGER.info(e.getMessage()); return null; } } private String getQhashUrl(Document doc) { for(Element el : doc.select("link[rel=preload]")) { if (el.attr("href").contains("ProfilePageContainer") && el.attr("href").contains("js")) { return el.attr("href"); } } for(Element el : doc.select("link[rel=preload]")) { if (el.attr("href").contains("metro")) { return el.attr("href"); } } return null; } private String getQHash(Document doc) { String jsFileURL = "https: StringBuilder sb = new StringBuilder(); LOGGER.info(jsFileURL); try { // We can't use Jsoup here because it won't download a non-html file larger than a MB // even if you set maxBodySize to 0 URLConnection connection = new URL(jsFileURL).openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { sb.append(line); } in.close(); } catch (MalformedURLException e) { LOGGER.info("Unable to get query_hash, " + jsFileURL + " is a malformed URL"); return null; } catch (IOException e) { LOGGER.info("Unable to get query_hash from " + jsFileURL); LOGGER.info(e.getMessage()); return null; } if (!rippingTag) { Pattern jsP = Pattern.compile("byUserId\\.get\\(t\\)\\)\\|\\|void 0===r\\?void 0:r\\.pagination},queryId:.([a-zA-Z0-9]+)"); Matcher m = jsP.matcher(sb.toString()); if (m.find()) { return m.group(1); } else { jsP = Pattern.compile("0:s\\.pagination},queryId:.([a-zA-Z0-9]+)"); m = jsP.matcher(sb.toString()); if (m.find()) { return m.group(1); } else { jsP = Pattern.compile(",u=.([a-zA-Z0-9]+)."); m = jsP.matcher(sb.toString()); if (m.find()) { return m.group(1); } } } } else { Pattern jsP = Pattern.compile("return e.tagMedia.byTagName.get\\(t\\).pagination},queryId:.([a-zA-Z0-9]+)."); Matcher m = jsP.matcher(sb.toString()); if (m.find()) { return m.group(1); } } LOGGER.error("Could not find query_hash on " + jsFileURL); return null; } }
package com.rarchives.ripme.ripper.rippers; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.time.*; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.rarchives.ripme.ripper.AbstractJSONRipper; import com.rarchives.ripme.utils.Http; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; public class InstagramRipper extends AbstractJSONRipper { private String userID; public InstagramRipper(URL url) throws IOException { super(url); } @Override public String getHost() { return "instagram"; } @Override public String getDomain() { return "instagram.com"; } @Override public boolean canRip(URL url) { return (url.getHost().endsWith("instagram.com")); } @Override public String getGID(URL url) throws MalformedURLException { Pattern p = Pattern.compile("^https?://instagram.com/([^/]+)"); Matcher m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } throw new MalformedURLException("Unable to find user in " + url); } @Override public URL sanitizeURL(URL url) throws MalformedURLException { Pattern p = Pattern.compile("^.*instagram\\.com/([a-zA-Z0-9\\-_.]+).*$"); Matcher m = p.matcher(url.toExternalForm()); if (m.matches()) { return new URL("http://instagram.com/" + m.group(1)); } throw new MalformedURLException("Expected username in URL (instagram.com/username and not " + url); } private String getUserID(URL url) throws IOException { Pattern p = Pattern.compile("^https?://instagram\\.com/([^/]+)"); Matcher m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } throw new IOException("Unable to find userID at " + this.url); } private JSONObject getJSONFromPage(String url) throws IOException { String jsonText = ""; try { Document firstPage = Http.url(url).get(); for (Element script : firstPage.select("script[type=text/javascript]")) { if (script.data().contains("window._sharedData = ")) { jsonText = script.data().replaceAll("window._sharedData = ", ""); jsonText = jsonText.replaceAll("};", "}"); } } return new JSONObject(jsonText); } catch (JSONException e) { throw new IOException("Could not get JSON from page " + url); } } @Override public JSONObject getFirstPage() throws IOException { userID = getUserID(url); return getJSONFromPage("http://instagram.com/" + userID); } private String getVideoFromPage(String videoID) { try { Document doc = Http.url("https: return doc.select("meta[property=og:video]").attr("content"); } catch (IOException e) { logger.warn("Unable to get page " + "https: } return ""; } private String getOriginalUrl(String imageURL) { imageURL = imageURL.replaceAll("scontent.cdninstagram.com/hphotos-", "igcdn-photos-d-a.akamaihd.net/hphotos-ak-"); imageURL = imageURL.replaceAll("p150x150/", ""); imageURL = imageURL.replaceAll("p320x320/", ""); imageURL = imageURL.replaceAll("p480x480/", ""); imageURL = imageURL.replaceAll("p640x640/", ""); imageURL = imageURL.replaceAll("p720x720/", ""); imageURL = imageURL.replaceAll("p1080x1080/", ""); imageURL = imageURL.replaceAll("p2048x2048/", ""); imageURL = imageURL.replaceAll("s150x150/", ""); imageURL = imageURL.replaceAll("s320x320/", ""); imageURL = imageURL.replaceAll("s480x480/", ""); imageURL = imageURL.replaceAll("s640x640/", ""); imageURL = imageURL.replaceAll("s720x720/", ""); imageURL = imageURL.replaceAll("s1080x1080/", ""); imageURL = imageURL.replaceAll("s2048x2048/", ""); // Instagram returns cropped images to unauthenticated applications to maintain legacy support. // To retrieve the uncropped image, remove this segment from the URL. // Segment format: cX.Y.W.H - eg: c0.134.1080.1080 imageURL = imageURL.replaceAll("/c\\d{1,4}\\.\\d{1,4}\\.\\d{1,4}\\.\\d{1,4}", ""); imageURL = imageURL.replaceAll("\\?ig_cache_key.+$", ""); return imageURL; } @Override public List<String> getURLsFromJSON(JSONObject json) { String nextPageID = ""; List<String> imageURLs = new ArrayList<>(); JSONArray profilePage = json.getJSONObject("entry_data").getJSONArray("ProfilePage"); JSONArray datas = profilePage.getJSONObject(0).getJSONObject("user").getJSONObject("media").getJSONArray("nodes"); for (int i = 0; i < datas.length(); i++) { JSONObject data = (JSONObject) datas.get(i); Long epoch = data.getLong("date"); Instant instant = Instant.ofEpochSecond(epoch); String image_date = DateTimeFormatter.ofPattern("yyyy_MM_dd_hh:mm_").format(ZonedDateTime.ofInstant(instant, ZoneOffset.UTC)); try { if (!data.getBoolean("is_video")) { if (imageURLs.size() == 0) { // We add this one item to the array because either wise // the ripper will error out because we returned an empty array imageURLs.add(data.getString("thumbnail_src")); } addURLToDownload(new URL(getOriginalUrl(data.getString("thumbnail_src"))), image_date); } else { addURLToDownload(new URL(getVideoFromPage(data.getString("code"))), image_date); } } catch (MalformedURLException e) { return imageURLs; } nextPageID = data.getString("id"); if (isThisATest()) { break; } } if (!nextPageID.equals("") && !isThisATest()) { try { // Sleep for a while to avoid a ban sleep(2500); getURLsFromJSON(getJSONFromPage("https: } catch (IOException e){ return imageURLs;} } return imageURLs; } @Override public void downloadURL(URL url, int index) { addURLToDownload(url); } }
package com.rarchives.ripme.ripper.rippers; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.time.*; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.security.*; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.rarchives.ripme.ripper.AbstractHTMLRipper; import com.rarchives.ripme.utils.Http; import org.jsoup.Connection; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import com.rarchives.ripme.ui.RipStatusMessage; import com.rarchives.ripme.utils.Utils; import java.util.HashMap; public class InstagramRipper extends AbstractHTMLRipper { String nextPageID = ""; private String qHash; private boolean rippingTag = false; private String tagName; private String userID; private String rhx_gis = null; private String csrftoken; public InstagramRipper(URL url) throws IOException { super(url); } @Override public String getHost() { return "instagram"; } @Override public String getDomain() { return "instagram.com"; } @Override public boolean canRip(URL url) { return (url.getHost().endsWith("instagram.com")); } @Override public URL sanitizeURL(URL url) throws MalformedURLException { URL san_url = new URL(url.toExternalForm().replaceAll("\\?hl=\\S*", "")); logger.info("sanitized URL is " + san_url.toExternalForm()); return san_url; } @Override public String normalizeUrl(String url) { // Remove the date sig from the url return url.replaceAll("/[A-Z0-9]{8}/", "/"); } private List<String> getPostsFromSinglePage(Document Doc) { List<String> imageURLs = new ArrayList<>(); JSONArray datas; try { JSONObject json = getJSONFromPage(Doc); if (json.getJSONObject("entry_data").getJSONArray("PostPage") .getJSONObject(0).getJSONObject("graphql").getJSONObject("shortcode_media") .has("edge_sidecar_to_children")) { datas = json.getJSONObject("entry_data").getJSONArray("PostPage") .getJSONObject(0).getJSONObject("graphql").getJSONObject("shortcode_media") .getJSONObject("edge_sidecar_to_children").getJSONArray("edges"); for (int i = 0; i < datas.length(); i++) { JSONObject data = (JSONObject) datas.get(i); data = data.getJSONObject("node"); if (data.has("is_video") && data.getBoolean("is_video")) { imageURLs.add(data.getString("video_url")); } else { imageURLs.add(data.getString("display_url")); } } } else { JSONObject data = json.getJSONObject("entry_data").getJSONArray("PostPage") .getJSONObject(0).getJSONObject("graphql").getJSONObject("shortcode_media"); if (data.getBoolean("is_video")) { imageURLs.add(data.getString("video_url")); } else { imageURLs.add(data.getString("display_url")); } } return imageURLs; } catch (IOException e) { logger.error("Unable to get JSON from page " + url.toExternalForm()); return null; } } @Override public String getGID(URL url) throws MalformedURLException { Pattern p = Pattern.compile("^https?://instagram.com/([^/]+)/?"); Matcher m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } p = Pattern.compile("^https?: m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } p = Pattern.compile("^https?: m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(2) + "_" + m.group(1); } p = Pattern.compile("^https?: m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } p = Pattern.compile("^https?: m = p.matcher(url.toExternalForm()); if (m.matches()) { return m.group(1); } p = Pattern.compile("^https?: m = p.matcher(url.toExternalForm()); if (m.matches()) { rippingTag = true; tagName = m.group(1); return m.group(1); } throw new MalformedURLException("Unable to find user in " + url); } private String stripHTMLTags(String t) { t = t.replaceAll("<html>\n" + " <head></head>\n" + " <body>", ""); t.replaceAll("</body>\n" + "</html>", ""); t = t.replaceAll("\n", ""); t = t.replaceAll("=\"\"", ""); return t; } private JSONObject getJSONFromPage(Document firstPage) throws IOException { // Check if this page is HTML + JSON or jsut json if (!firstPage.html().contains("window._sharedData =")) { return new JSONObject(stripHTMLTags(firstPage.html())); } String jsonText = ""; try { for (Element script : firstPage.select("script[type=text/javascript]")) { if (script.data().contains("window._sharedData = ")) { jsonText = script.data().replaceAll("window._sharedData = ", ""); jsonText = jsonText.replaceAll("};", "}"); } } return new JSONObject(jsonText); } catch (JSONException e) { throw new IOException("Could not get JSON from page"); } } @Override public Document getFirstPage() throws IOException { Connection.Response resp = Http.url(url).response(); logger.info(resp.cookies()); csrftoken = resp.cookie("csrftoken"); Document p = resp.parse(); // Get the query hash so we can download the next page qHash = getQHash(p); return p; } private String getVideoFromPage(String videoID) { try { Document doc = Http.url("https: return doc.select("meta[property=og:video]").attr("content"); } catch (IOException e) { logger.warn("Unable to get page " + "https: } return ""; } private String getOriginalUrl(String imageURL) { // Without this regex most images will return a 403 error imageURL = imageURL.replaceAll("vp/[a-zA-Z0-9]*/", ""); imageURL = imageURL.replaceAll("scontent.cdninstagram.com/hphotos-", "igcdn-photos-d-a.akamaihd.net/hphotos-ak-"); // TODO replace this with a single regex imageURL = imageURL.replaceAll("p150x150/", ""); imageURL = imageURL.replaceAll("p320x320/", ""); imageURL = imageURL.replaceAll("p480x480/", ""); imageURL = imageURL.replaceAll("p640x640/", ""); imageURL = imageURL.replaceAll("p720x720/", ""); imageURL = imageURL.replaceAll("p1080x1080/", ""); imageURL = imageURL.replaceAll("p2048x2048/", ""); imageURL = imageURL.replaceAll("s150x150/", ""); imageURL = imageURL.replaceAll("s320x320/", ""); imageURL = imageURL.replaceAll("s480x480/", ""); imageURL = imageURL.replaceAll("s640x640/", ""); imageURL = imageURL.replaceAll("s720x720/", ""); imageURL = imageURL.replaceAll("s1080x1080/", ""); imageURL = imageURL.replaceAll("s2048x2048/", ""); // Instagram returns cropped images to unauthenticated applications to maintain legacy support. // To retrieve the uncropped image, remove this segment from the URL. // Segment format: cX.Y.W.H - eg: c0.134.1080.1080 imageURL = imageURL.replaceAll("/c\\d{1,4}\\.\\d{1,4}\\.\\d{1,4}\\.\\d{1,4}", ""); imageURL = imageURL.replaceAll("\\?ig_cache_key.+$", ""); return imageURL; } @Override public List<String> getURLsFromPage(Document doc) { List<String> imageURLs = new ArrayList<>(); JSONObject json = new JSONObject(); try { json = getJSONFromPage(doc); } catch (IOException e) { logger.warn("Unable to exact json from page"); } // get the rhx_gis value so we can get the next page later on if (rhx_gis == null) { rhx_gis = json.getString("rhx_gis"); } if (!url.toExternalForm().contains("/p/")) { JSONArray datas = new JSONArray(); if (!rippingTag) { // This first try only works on data from the first page try { JSONArray profilePage = json.getJSONObject("entry_data").getJSONArray("ProfilePage"); userID = profilePage.getJSONObject(0).getString("logging_page_id").replaceAll("profilePage_", ""); datas = profilePage.getJSONObject(0).getJSONObject("graphql").getJSONObject("user") .getJSONObject("edge_owner_to_timeline_media").getJSONArray("edges"); } catch (JSONException e) { datas = json.getJSONObject("data").getJSONObject("user") .getJSONObject("edge_owner_to_timeline_media").getJSONArray("edges"); } } else { try { JSONArray tagPage = json.getJSONObject("entry_data").getJSONArray("TagPage"); datas = tagPage.getJSONObject(0).getJSONObject("graphql").getJSONObject("hashtag") .getJSONObject("edge_hashtag_to_media").getJSONArray("edges"); } catch (JSONException e) { datas = json.getJSONObject("data").getJSONObject("hashtag").getJSONObject("edge_hashtag_to_media") .getJSONArray("edges"); } } for (int i = 0; i < datas.length(); i++) { JSONObject data = (JSONObject) datas.get(i); data = data.getJSONObject("node"); Long epoch = data.getLong("taken_at_timestamp"); Instant instant = Instant.ofEpochSecond(epoch); String image_date = DateTimeFormatter.ofPattern("yyyy_MM_dd_hh:mm_").format(ZonedDateTime.ofInstant(instant, ZoneOffset.UTC)); // It looks like tag pages don't have the __typename key if (!rippingTag) { if (data.getString("__typename").equals("GraphSidecar")) { try { Document slideShowDoc = Http.url(new URL("https: List<String> toAdd = getPostsFromSinglePage(slideShowDoc); for (int slideShowInt = 0; slideShowInt < toAdd.size(); slideShowInt++) { addURLToDownload(new URL(toAdd.get(slideShowInt)), image_date + data.getString("shortcode")); } } catch (MalformedURLException e) { logger.error("Unable to download slide show, URL was malformed"); } catch (IOException e) { logger.error("Unable to download slide show"); } } } try { if (!data.getBoolean("is_video")) { if (imageURLs.size() == 0) { // We add this one item to the array because either wise // the ripper will error out because we returned an empty array imageURLs.add(getOriginalUrl(data.getString("display_url"))); } addURLToDownload(new URL(data.getString("display_url")), image_date); } else { if (!Utils.getConfigBoolean("instagram.download_images_only", false)) { addURLToDownload(new URL(getVideoFromPage(data.getString("shortcode"))), image_date); } else { sendUpdate(RipStatusMessage.STATUS.DOWNLOAD_WARN, "Skipping video " + data.getString("shortcode")); } } } catch (MalformedURLException e) { return imageURLs; } nextPageID = data.getString("id"); if (isThisATest()) { break; } } } else { // We're ripping from a single page logger.info("Ripping from single page"); imageURLs = getPostsFromSinglePage(doc); } return imageURLs; } private String getIGGis(String variables) { String stringToMD5 = rhx_gis + ":" + variables; logger.debug("String to md5 is \"" + stringToMD5 + "\""); try { byte[] bytesOfMessage = stringToMD5.getBytes("UTF-8"); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] hash = md.digest(bytesOfMessage); StringBuffer sb = new StringBuffer(); for (int i = 0; i < hash.length; ++i) { sb.append(Integer.toHexString((hash[i] & 0xFF) | 0x100).substring(1,3)); } return sb.toString(); } catch(UnsupportedEncodingException e) { return null; } catch(NoSuchAlgorithmException e) { return null; } } @Override public Document getNextPage(Document doc) throws IOException { Document toreturn; java.util.Map<String, String> cookies = new HashMap<String, String>(); // This shouldn't be hardcoded and will break one day cookies.put("ig_pr", "1"); cookies.put("csrftoken", csrftoken); if (!nextPageID.equals("") && !isThisATest()) { if (rippingTag) { try { sleep(2500); String vars = "{\"tag_name\":\"" + tagName + "\",\"first\":4,\"after\":\"" + nextPageID + "\"}"; String ig_gis = getIGGis(vars); toreturn = Http.url("https: "&variables=" + vars).header("x-instagram-gis", ig_gis).cookies(cookies).ignoreContentType().get(); // Sleep for a while to avoid a ban logger.info(toreturn.html()); return toreturn; } catch (IOException e) { throw new IOException("No more pages"); } } try { // Sleep for a while to avoid a ban sleep(2500); String vars = "{\"id\":\"" + userID + "\",\"first\":50,\"after\":\"" + nextPageID + "\"}"; String ig_gis = getIGGis(vars); logger.info(ig_gis); toreturn = Http.url("https: ).header("x-instagram-gis", ig_gis).cookies(cookies).ignoreContentType().get(); if (!pageHasImages(toreturn)) { throw new IOException("No more pages"); } return toreturn; } catch (IOException e) { return null; } } else { throw new IOException("No more pages"); } } @Override public void downloadURL(URL url, int index) { addURLToDownload(url); } private boolean pageHasImages(Document doc) { JSONObject json = new JSONObject(stripHTMLTags(doc.html())); int numberOfImages = json.getJSONObject("data").getJSONObject("user") .getJSONObject("edge_owner_to_timeline_media").getJSONArray("edges").length(); if (numberOfImages == 0) { return false; } return true; } private String getQHash(Document doc) { String jsFileURL = "https: StringBuilder sb = new StringBuilder(); Document jsPage; try { // We can't use Jsoup here because it won't download a non-html file larger than a MB // even if you set maxBodySize to 0 URLConnection connection = new URL(jsFileURL).openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { sb.append(line); } in.close(); } catch (MalformedURLException e) { logger.info("Unable to get query_hash, " + jsFileURL + " is a malformed URL"); return null; } catch (IOException e) { logger.info("Unable to get query_hash"); logger.info(e.getMessage()); return null; } if (!rippingTag) { Pattern jsP = Pattern.compile("\\?n.pagination:n},queryId:.([a-zA-Z0-9]+)."); Matcher m = jsP.matcher(sb.toString()); if (m.find()) { return m.group(1); } } else { Pattern jsP = Pattern.compile("return e.tagMedia.byTagName.get\\(t\\).pagination},queryId:.([a-zA-Z0-9]+)."); Matcher m = jsP.matcher(sb.toString()); if (m.find()) { return m.group(1); } } logger.error("Could not find query_hash on " + jsFileURL); return null; } }
package com.scaleunlimited.yalder.tools; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.InvalidXPathException; import org.dom4j.Node; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import com.scaleunlimited.yalder.LanguageLocale; import bixo.config.UserAgent; import bixo.exceptions.BaseFetchException; import bixo.fetcher.FetchedResult; import bixo.fetcher.SimpleHttpFetcher; public class WikipediaCrawlTool { public static final Logger LOGGER = Logger.getLogger(WikipediaCrawlTool.class); private static final String XML_SUBDIR_NAME = "xml"; private static final String TEXT_SUBDIR_NAME = "text"; // Map from Wikipedia language name to ISO 639-2 language code. // Use mapWikipediaLanguage() to get the mapping, as that loads the data. private static final Map<String, String> WIKIPEDIA_TO_ISO_LANGUAGE = new HashMap<String, String>(); private WikipediaCrawlOptions _options; private Document _curPage = null; private SimpleHttpFetcher _fetcher; private Map<String, Long> _lastFetchTime; public WikipediaCrawlTool(WikipediaCrawlOptions options) { _options = options; _fetcher = new SimpleHttpFetcher(new UserAgent("yalder", "ken@transpac.com", "http://ken-blog.krugler.org")); // Some pages are > 1MB is size, yikes! _fetcher.setDefaultMaxContentSize(10 * 1024 * 1024); _lastFetchTime = new HashMap<>(); } private void displayHelp() { System.out.println("help - print this help text"); System.out.println("load - load Wikipedia page from file or URL"); System.out.println("dump - dump previously loaded page (as XML)"); System.out.println("clean - dump text extracted from previously loaded page"); System.out.println("crawl - crawl Wikipedia pages, given a list of Q-codes"); System.out.println("random - crawl random Wikipedia pages, given a list of language codes"); System.out.println("xpath - evaluate XPath expressions using previously loaded HTML document"); System.out.println("quit - quit"); } private Document loadDocument(String docName) throws IOException, DocumentException, BaseFetchException { if (docName == null) { docName = readInputLine("Enter HTML document file path or URL: "); } if (docName.length() == 0) { return null; } InputStream is; if (docName.startsWith("http: FetchedResult result = fetchPage(docName); is = new ByteArrayInputStream(result.getContent()); } else { is = new FileInputStream(docName); } HtmlParser parser = new HtmlParser("UTF-8"); return parser.parse(is); } private FetchedResult fetchPage(String pageURL) throws IOException, DocumentException, BaseFetchException { URL url = new URL(pageURL); String domain = url.getHost(); Long lastFetchTime = _lastFetchTime.get(domain); if (lastFetchTime == null) { lastFetchTime = 0L; } long curTime = System.currentTimeMillis(); long delay = (lastFetchTime + 1000L) - curTime; if (delay > 0) { try { Thread.sleep(delay); } catch (InterruptedException e) { // Ignore interrupted exception. } } FetchedResult result = _fetcher.fetch(pageURL); _lastFetchTime.put(domain, System.currentTimeMillis()); return result; } private void doDump() throws IOException { if (_curPage == null) { System.out.println("Can't dump the page if it hasn't been loaded yet!"); return; } String filename = readInputLine("Enter output file path: "); if (filename.length() == 0) { System.out.println(formatXml(_curPage)); } else { OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"); osw.write(formatXml(_curPage)); osw.close(); } } private void doClean() throws IOException { if (_curPage == null) { System.out.println("Can't output clean content for the page if it hasn't been loaded yet!"); return; } String filename = readInputLine("Enter output file path: "); if (filename.length() == 0) { System.out.println(extractContent(_curPage)); } else { OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"); osw.write(extractContent(_curPage)); osw.close(); } } /** * Given a crawl output directory (which has a text subdir), for each file we find we want * to extract and clean up the resulting text. * * @throws IOException */ private void mergeResults() throws IOException { String dirname = readInputLine("Enter crawl directory path: "); File inputDir = new File(dirname); if (!inputDir.exists()) { throw new IllegalArgumentException(String.format("The directory '%s' doesn't exist", inputDir.toString())); } if (!inputDir.isDirectory()) { throw new IllegalArgumentException(String.format("'%s' is not a directory", inputDir.toString())); } File textDir = new File(inputDir, TEXT_SUBDIR_NAME); if (!textDir.exists()) { throw new IllegalArgumentException(String.format("The directory '%s' doesn't exist", inputDir.toString())); } if (!textDir.isDirectory()) { throw new IllegalArgumentException(String.format("'%s' is not a directory", inputDir.toString())); } String outputFilename = readInputLine("Enter ouput file path: "); File outputFile = new File(outputFilename); outputFile.delete(); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"); System.out.println(String.format("Loading text lines from files in '%s'...", textDir.getCanonicalPath())); Pattern filenamePattern = Pattern.compile("(.+)_(.+).txt"); try { for (File file : FileUtils.listFiles(textDir, new String[]{"txt"}, true)) { String filename = file.getName(); Matcher m = filenamePattern.matcher(filename); if (!m.matches()) { throw new IllegalArgumentException(String.format("Found file '%s' without a language code", filename)); } String language = m.group(2); List<String> lines = FileUtils.readLines(file, "UTF-8"); for (String line : lines) { // Get rid of [ <digits> ] sequence (where there may or may not be spaces), as that's a footnote ref // that is just noise. line = line.replaceAll("\\[[ ]*\\d+[ ]*\\]", " "); // We wind up with a lot of multi-space sequences, due to markup in text always getting converted to // text by inserting a space. line = line.replaceAll("[ \t]+", " "); line = line.trim(); if (line.trim().isEmpty()) { continue; } osw.write(language); osw.write('\t'); osw.write(line); osw.write('\n'); } } } finally { osw.close(); } } private int saveWikipediaPage(Document doc, File parentFolder, String topicName, String language, boolean overwrite) throws IOException { String content = extractContent(doc); // Don't bother saving super-short pages. if (content.length() < 100) { return 0; } // Write out the original content, as XML, so we could potentially re-process it File xmlDir = new File(parentFolder, XML_SUBDIR_NAME); xmlDir.mkdirs(); File xmlFile = new File(xmlDir, String.format("%s_%s.xml", topicName, language)); if (overwrite || !xmlFile.exists()) { OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(xmlFile), "UTF-8"); osw.write(formatXml(doc)); osw.close(); } File textDir = new File(parentFolder, TEXT_SUBDIR_NAME); textDir.mkdirs(); // Now save the main content File textFile = new File(textDir, String.format("%s_%s.txt", topicName, language)); if (overwrite || !textFile.exists()) { OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(textFile), "UTF-8"); osw.write(content); osw.close(); return content.length(); } else { return 0; } } private String extractContent(Document doc) { StringBuffer mainContent = new StringBuffer(); List<Node> nodes = selectNodes(doc, "//div[@id=\"mw-content-text\"]"); if (nodes.size() != 1) { throw new IllegalStateException("No mw-content-text node in document"); } nodes = getChildrenFromNode(nodes.get(0)); for (Node node : nodes) { String nodeType = node.getName(); if (nodeType == null) { continue; } if (nodeType.equalsIgnoreCase("p") || nodeType.equalsIgnoreCase("div")) { Element e = (Element)node; String id = e.attributeValue("id"); if (nodeType.equalsIgnoreCase("div") && (id != null) && (id.equals("toc"))) { // Skip the table of contents continue; } String nodeText = getTextFromNode(node, true); if (nodeText == null) { // We hit something that tells us we're at the end of the actual content. break; } mainContent.append(nodeText); mainContent.append("\n"); } } return mainContent.toString(); } private void doRandomCrawl() throws IOException, DocumentException, BaseFetchException { String langCodes = readInputLine("Enter a comma-separated list of ISO 639-2 language codes: "); if (langCodes.trim().isEmpty()) { return; } String numCharsAsStr = readInputLine("Enter target number of chars per language: "); if (numCharsAsStr.trim().isEmpty()) { return; } int targetChars = Integer.parseInt(numCharsAsStr); String directoryName = readInputLine("Enter output directory: "); if (directoryName.length() == 0) { return; } File parentFolder = new File(directoryName); if (!parentFolder.exists()) { System.err.println("Output directory must exist"); return; } if (!parentFolder.isDirectory()) { System.err.println("Output path specified isn't a directory"); return; } for (String langCode : langCodes.split(",")) { langCode = langCode.trim(); // Figure out the Wikipedia language. First do a bogus call to load up // the data. String wikiLang = mapISOLangToWikiLang(langCode); if (wikiLang == null) { System.err.println("Unknown ISO 639-2 lang code: " + langCode); return; } int totalPages = 0; int numCharsExtracted = 0; while ((numCharsExtracted < targetChars) && (totalPages < 100)) { // Get another random page. String pageURL = String.format("https://%s.wikipedia.org/wiki/Special:Random", wikiLang); Document subPage = loadDocument(pageURL); String topic = extractTopicName(subPage); topic = URLDecoder.decode(topic, "UTF-8"); int numChars = saveWikipediaPage(subPage, parentFolder, topic, langCode, false); if (numChars > 0) { LOGGER.debug(String.format("Fetched topic '%s' with %d chars for language '%s'", topic, numChars, langCode)); numCharsExtracted += numChars; } totalPages += 1; } } } /** * Try to extract the topic name from this page, by first finding the English URL. If we * can't find that, then extract the head/title node, split that on " - ", and take the * first part. * * @param wikipediaPage * @return */ private String extractTopicName(Document wikipediaPage) { // See if there's a link to the English version. List<Node> nodes = selectNodes(wikipediaPage, "//li[contains(concat(' ', @class, ' '), ' interwiki-en ')]/a"); if (nodes.size() == 1) { String href = ((Element)nodes.get(0)).attributeValue("href"); if (href != null) { Pattern p = Pattern.compile("en.wikipedia.org/wiki/(.+)"); Matcher m = p.matcher(href); if (m.find()) { return m.group(1); } } } nodes = selectNodes(wikipediaPage, "//title"); if (nodes.size() != 1) { return "unknown"; } else { String title = nodes.get(0).getText(); // Some Wikipedias use a long dash in the title...why? return title.split(" (\\-|—) ")[0]; } } private void doCrawl() throws IOException, DocumentException, BaseFetchException { String qCodeOrCount = readInputLine("Enter a specific Q-code, or number of these to randomly select, or all: "); if (qCodeOrCount.trim().isEmpty()) { return; } int targetCharsPerLanguage = Integer.MAX_VALUE; int maxCharsPerPage = Integer.MAX_VALUE; Map<String, Integer> charsPerLanguage = new HashMap<>(); Set<String> completedLanguages = new HashSet<>(); List<String> qCodes = new ArrayList<String>(); if (qCodeOrCount.startsWith("Q")) { qCodes.add(qCodeOrCount); } else if (qCodeOrCount.equals("all")) { qCodes = readImportantQCodes(); Collections.shuffle(qCodes); String targetAsStr = readInputLine("Enter target number of characters per language: "); targetCharsPerLanguage = Integer.parseInt(targetAsStr); String perPageLimitAsStr = readInputLine("Enter max number of characters per page: "); if (perPageLimitAsStr.isEmpty()) { maxCharsPerPage = 10*1024; } else { maxCharsPerPage = Integer.parseInt(perPageLimitAsStr); } } else { int numToProcess = Integer.parseInt(qCodeOrCount); List<String> importantQCodes = readImportantQCodes(); Collections.shuffle(importantQCodes); qCodes = importantQCodes.subList(0, numToProcess); } String directoryName = readInputLine("Enter output directory: "); if (directoryName.length() == 0) { return; } File parentFolder = new File(directoryName); if (!parentFolder.exists()) { System.err.println("Output directory must exist"); return; } if (!parentFolder.isDirectory()) { System.err.println("Output path specified isn't a directory"); return; } Pattern urlPattern = Pattern.compile("https://(.+?).wikipedia.org/.+"); // TODO bail out of this loop if we process N qCodes in a row without adding any text // for a language (all that we've seen so far are complete). for (String qCode : qCodes) { // Fetch the QCode page Document page = loadDocument("https: List<Node> nodes = selectNodes(page, "//span[@class=\"wikibase-title-label\"]"); if (nodes.size() != 1) { throw new IllegalArgumentException(String.format("Wikidata page %s doesn't have a title label", qCode)); } String topic = nodes.get(0).getText(); topic = topic.replaceAll(" ", "_"); List<String> pageURLs = getWikiPagesFromWikidata(page); for (String pageURL : pageURLs) { // extract language from URL, map it to our 639-2 code. Matcher m = urlPattern.matcher(pageURL); if (!m.matches()) { LOGGER.error("Got page URL with invalid format:" + pageURL); continue; } String language = mapWikipediaLanguage(m.group(1)); if (language == null) { LOGGER.warn("Unknown Wikipedia language: " + m.group(1)); } else if (language.equals("xxx")) { // Ignore, not a language we want to process. } else if (completedLanguages.contains(language)) { // Ignore, we have enough text from this language. } else { Document subPage = loadDocument(pageURL); int numChars = saveWikipediaPage(subPage, parentFolder, topic, language, true); // When tracking chars per language, limit # we get out of each page so we // don't hit our target (e.g. 100K) with a single page. numChars = Math.min(numChars, maxCharsPerPage); Integer curChars = charsPerLanguage.get(language); if (curChars == null) { curChars = numChars; } else { curChars += numChars; } charsPerLanguage.put(language, curChars); if (curChars >= targetCharsPerLanguage) { completedLanguages.add(language); } } } } // Print some statistics for languages... for (String language : charsPerLanguage.keySet()) { System.out.println(String.format("'%s': %d chars", LanguageLocale.fromString(language), charsPerLanguage.get(language))); } } private List<String> readImportantQCodes() { List<String> result = new ArrayList<>(); try (InputStream is = WikipediaCrawlTool.class.getResourceAsStream("/wikipedia-key-articles.txt")) { List<String> lines = IOUtils.readLines(is); for (String line : lines) { line = line.trim(); if (line.isEmpty() || line.startsWith(" continue; } result.add(line); } return result; } catch (IOException e) { throw new RuntimeException("Impossible exception!", e); } } private List<String> getWikiPagesFromWikidata(Document page) throws IOException, DocumentException, BaseFetchException { List<String> result = new ArrayList<String>(); List<Node> nodes = selectNodes(page, "//div[@data-wb-sitelinks-group=\"wikipedia\"]//span[@class=\"wikibase-sitelinkview-page\"]/a"); for (Node node : nodes) { Element link = (Element)node; result.add(link.attributeValue("href")); } return result; } private String mapISOLangToWikiLang(String langCode) { loadWikiLangMap(); for (String wikiLang : WIKIPEDIA_TO_ISO_LANGUAGE.keySet()) { if (WIKIPEDIA_TO_ISO_LANGUAGE.get(wikiLang).equals(langCode)) { return wikiLang; } } return null; } private void loadWikiLangMap() { synchronized (WIKIPEDIA_TO_ISO_LANGUAGE) { if (WIKIPEDIA_TO_ISO_LANGUAGE.isEmpty()) { try (InputStream is = WikipediaCrawlTool.class.getResourceAsStream("/wikipedia-languages.txt")) { List<String> lines = IOUtils.readLines(is, "UTF-8"); for (String line : lines) { line = line.trim(); if (line.isEmpty() || line.startsWith(" continue; } // Format is rank, language name, Wikipedia language name, ISO 639-2, optional comment // 19 Serbo-Croatian sh xxx # Ignore obsolete language String[] parts = line.split("\t"); if (parts.length < 4) { throw new IllegalArgumentException(String.format("Line '%s' has invalid format", line)); } WIKIPEDIA_TO_ISO_LANGUAGE.put(parts[2], parts[3]); } } catch (IOException e) { throw new RuntimeException("Impossible exception!", e); } } } } private String mapWikipediaLanguage(String language) { loadWikiLangMap(); return WIKIPEDIA_TO_ISO_LANGUAGE.get(language); } private void doXpath() throws IOException { if (_curPage == null) { System.out.println("Can't query the page if it hasn't been loaded yet!"); return; } // Now loop, getting XPath expressions and evaluating them while (true) { System.out.println(); System.out.flush(); String xpathExpression = readInputLine("Enter XPath expression (or <return> when done): "); if (xpathExpression.length() == 0) { break; } try { List<Node> nodes = selectNodes(_curPage, xpathExpression); System.out.println(String.format("%d nodes", nodes.size())); System.out.flush(); while (true) { String xpathCmd = readInputLine("What next (a, f, e, t): "); if (xpathCmd.length() == 0) { xpathCmd = "e"; } if (xpathCmd.equalsIgnoreCase("e")) { break; } else if (xpathCmd.equalsIgnoreCase("a")) { for (Node node : nodes) { System.out.println(formatXml(node)); } } else if (xpathCmd.equalsIgnoreCase("t")) { for (Node node : nodes) { System.out.println(getTextFromNode(node, true)); } } else if (xpathCmd.equalsIgnoreCase("f")) { if (nodes.isEmpty()) { System.out.println("No first node!"); } else { System.out.println(formatXml(nodes.get(0))); System.out.println("======================="); System.out.println(nodes.get(0).getText().trim()); } } else { System.out.println("Unknown command: " + xpathCmd); } } } catch (InvalidXPathException e) { System.out.println(e.getMessage()); } catch (Exception e) { System.out.println("Error executing query: " + e.getMessage()); e.printStackTrace(System.out); } } } public static String getTextFromNode(Node node, boolean stripReturns) { if (node.getNodeType() != Node.ELEMENT_NODE) { String result = node.getText().trim(); if (stripReturns) { return result.replaceAll("[\n\r]", " "); } else { return result; } } else if (node.getName().equalsIgnoreCase("br")) { return "\n"; } else if (node.getName().equalsIgnoreCase("ol")) { Element e = (Element)node; String className = e.attributeValue("class"); if ((className != null) && (className.equals("references"))) { // We've hit the end of the main content, so exclude everything // from the top-level node down to this point too, by returning null. return null; } } StringBuilder result = new StringBuilder(); List<Node> children = getChildrenFromNode(node); for (Node child : children) { String text = getTextFromNode(child, stripReturns); if (text == null) { return null; } result.append(text); // Put space between elements. result.append(' '); } return result.toString(); } public static List<Node> getChildrenFromNode(Node node) { if (node.getNodeType() != Node.ELEMENT_NODE) { return null; } Element e = (Element)node; List<Node> result = new ArrayList<Node>(e.nodeCount()); Iterator<Node> iter = e.nodeIterator(); while (iter.hasNext()) { result.add(iter.next()); } return result; } private static void printUsageAndExit(CmdLineParser parser) { parser.printUsage(System.err); System.exit(-1); } public static void main(String[] args) { WikipediaCrawlOptions options = new WikipediaCrawlOptions(); CmdLineParser parser = new CmdLineParser(options); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); printUsageAndExit(parser); } WikipediaCrawlTool tool = new WikipediaCrawlTool(options); try { // Now loop, getting commands while (true) { String cmdName = readInputLine("Enter command (help, load, dump, clean, xpath, crawl, random, merge, quit): "); if (cmdName.equalsIgnoreCase("help")) { tool.displayHelp(); } else if (cmdName.equalsIgnoreCase("load")) { Document newDoc = tool.loadDocument(null); if (newDoc != null) { tool.setCurPage(newDoc); } } else if (cmdName.equalsIgnoreCase("dump")) { tool.doDump(); } else if (cmdName.equalsIgnoreCase("clean")) { tool.doClean(); } else if (cmdName.equalsIgnoreCase("xpath")) { tool.doXpath(); } else if (cmdName.equalsIgnoreCase("crawl")) { tool.doCrawl(); } else if (cmdName.equalsIgnoreCase("merge")) { tool.mergeResults(); } else if (cmdName.equalsIgnoreCase("random")) { tool.doRandomCrawl(); } else if (cmdName.equalsIgnoreCase("quit")) { break; } else { System.out.println("Unknown command: " + cmdName); } } } catch (Throwable t) { System.err.println("Exception running tool: " + t.getMessage()); t.printStackTrace(System.err); System.exit(-1); } } private void setCurPage(Document newDoc) { _curPage = newDoc; } /** * Read one line of input from the console, after displaying prompt * * @return Text that the user entered * @throws IOException */ private static String readInputLine(String prompt) throws IOException { System.out.print(prompt); return readInputLine(); } /** * Read one line of input from the console. * * @return Text that the user entered * @throws IOException */ private static String readInputLine() throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); return br.readLine(); } /** * Returns the given xml document as nicely formated string. * * @param node * The xml document. * @return the formated xml as string. */ private static String formatXml(Node node) { OutputFormat format = OutputFormat.createPrettyPrint(); format.setIndentSize(4); format.setTrimText(true); format.setExpandEmptyElements(true); StringWriter stringWriter = new StringWriter(); XMLWriter xmlWriter = new XMLWriter(stringWriter, format); try { xmlWriter.write(node); xmlWriter.flush(); } catch (IOException e) { // this should never happen throw new RuntimeException(e); } return stringWriter.getBuffer().toString(); } private static List<Node> selectNodes(Document doc, String xpathExpression) { return doc.selectNodes(xpathExpression); } private static class WikipediaCrawlOptions { private boolean _debugLogging = false; private boolean _traceLogging = false; private String _inputFile = null; @Option(name = "-debug", usage = "debug logging", required = false) public void setDebugLogging(boolean debugLogging) { _debugLogging = debugLogging; } @Option(name = "-trace", usage = "trace logging", required = false) public void setTraceLogging(boolean traceLogging) { _traceLogging = traceLogging; } public boolean isDebugLogging() { return _debugLogging; } public boolean isTraceLogging() { return _traceLogging; } public Level getLogLevel() { if (isTraceLogging()) { return Level.TRACE; } else if (isDebugLogging()) { return Level.DEBUG; } else { return Level.INFO; } } @Option(name = "-inputfile", usage = "input HTML file", required = false) public void setInputFile(String inputFile) { _inputFile = inputFile; } public String getInputFile() { return _inputFile; } } }
package com.tikal.jenkins.plugins.multijob; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.Util; import hudson.console.HyperlinkNote; import hudson.model.Action; import hudson.model.BallColor; import hudson.model.BuildListener; import hudson.model.DependecyDeclarer; import hudson.model.DependencyGraph; import hudson.model.DependencyGraph.Dependency; import hudson.model.Item; import hudson.model.Queue.QueueAction; import hudson.model.Result; import hudson.model.TaskListener; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.queue.QueueTaskFuture; import hudson.scm.ChangeLogSet; import hudson.scm.ChangeLogSet.Entry; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import hudson.model.Executor; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.regex.Pattern; import net.sf.json.JSONObject; import jenkins.model.Jenkins; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileNotFoundException; import org.jenkinsci.lib.envinject.EnvInjectLogger; import org.jenkinsci.plugins.envinject.EnvInjectBuilderContributionAction; import org.jenkinsci.plugins.envinject.EnvInjectBuilder; import org.jenkinsci.plugins.envinject.service.EnvInjectActionSetter; import org.jenkinsci.plugins.envinject.service.EnvInjectEnvVars; import org.jenkinsci.plugins.envinject.service.EnvInjectVariableGetter; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import com.tikal.jenkins.plugins.multijob.MultiJobBuild.SubBuild; import com.tikal.jenkins.plugins.multijob.PhaseJobsConfig.KillPhaseOnJobResultCondition; import com.tikal.jenkins.plugins.multijob.counters.CounterHelper; import com.tikal.jenkins.plugins.multijob.counters.CounterManager; import org.jenkinsci.plugins.tokenmacro.TokenMacro; import groovy.util.*; import hudson.plugins.parameterizedtrigger.AbstractBuildParameters.DontTriggerException; import java.util.concurrent.CancellationException; import jenkins.model.CauseOfInterruption; public class MultiJobBuilder extends Builder implements DependecyDeclarer { /** * The name of the parameter in the build.getBuildVariables() to enable the job build, regardless * of scm changes. */ public static final String BUILD_ALWAYS_KEY = "hudson.scm.multijob.build.always"; private String phaseName; private List<PhaseJobsConfig> phaseJobs; private ContinuationCondition continuationCondition = ContinuationCondition.SUCCESSFUL; final static Pattern PATTERN = Pattern.compile("(\\$\\{.+?\\})", Pattern.CASE_INSENSITIVE); /** * The name of the new variable which stores the status of the current job. * The state is the name of the corresponding value in {@link StatusJob} enum. * @since 1.0.0 * @see StatusJob#isBuildable() */ public static final String JOB_STATUS = "JOB_STATUS"; /** * The name of the new variable which stores if the job is buildable or not. * This value is getted from the {@link StatusJob#isBuildable()}. * The only values of this variable are <code>true</code> when the job is buildable, * or <code>false</code> when the job is not buildable. * * @since 1.0.0 * @see StatusJob#isBuildable() */ public static final String JOB_IS_BUILDABLE = "JOB_IS_BUILDABLE"; @DataBoundConstructor public MultiJobBuilder(String phaseName, List<PhaseJobsConfig> phaseJobs, ContinuationCondition continuationCondition) { this.phaseName = phaseName; this.phaseJobs = Util.fixNull(phaseJobs); this.continuationCondition = continuationCondition; } public String expandToken(String toExpand, final AbstractBuild<?,?> build, final BuildListener listener) { String expandedExpression = toExpand; try { expandedExpression = TokenMacro.expandAll(build, listener, toExpand, false, null); } catch (Exception e) { listener.getLogger().println(e.getMessage()); } return PATTERN.matcher(expandedExpression).replaceAll(""); } /** * Reports the status of the job. * <p>The sequence of the checks are the following (the first winner stops the sequence and returns):</p> * * <ol> * <li>If job is disabled * then returns <code>{@link StatusJob#IS_DISABLED}</code>.</li> * <li>If job is disabled at phase configuration * then returns <code>{@link StatusJob#IS_DISABLED_AT_PHASECONFIG}</code>.</li> * <li>If BuildOnlyIfSCMChanges is disabled * then returns <code>{@link StatusJob#BUILD_ON_SCM_CHANGES_ONLY}</code>.</li> * <li>If 'Build Always' feature is enabled * then returns <code>{@link StatusJob#BUILD_ALWAYS_IS_ENABLED}</code>.</li> * <li>If job doesn't contains lastbuild * then returns <code>{@link StatusJob#DOESNT_CONTAINS_LASTBUILD}</code>.</li> * <li>If lastbuild result of the job is worse than unstable * then returns <code>{@link StatusJob#LASTBUILD_RESULT_IS_WORSE_THAN_UNSTABLE}</code>.</li> * <li>If job's workspace is empty * then returns <code>{@link StatusJob#WORKSPACE_IS_EMPTY}</code>.</li> * <li>If job contains scm changes * then returns <code>{@link StatusJob#CHANGED_SINCE_LAST_BUILD}</code>.</li> * <li>If job's doesn't contains scm changes * then returns <code>{@link StatusJob#NOT_CHANGED_SINCE_LAST_BUILD}</code>.</li> * </ol> */ private StatusJob getScmChange(AbstractProject subjob,PhaseJobsConfig phaseConfig,AbstractBuild build, BuildListener listener,Launcher launcher) throws IOException, InterruptedException { if ( subjob.isDisabled() ) { return StatusJob.IS_DISABLED; } if( phaseConfig.isDisableJob() ) { return StatusJob.IS_DISABLED_AT_PHASECONFIG; } if ( !phaseConfig.isBuildOnlyIfSCMChanges() ){ return StatusJob.BUILD_ONLY_IF_SCM_CHANGES_DISABLED; } final boolean buildAlways = Boolean.valueOf((String)(build.getBuildVariables().get(BUILD_ALWAYS_KEY))); if ( buildAlways ) { return StatusJob.BUILD_ALWAYS_IS_ENABLED; } final AbstractBuild lastBuild = subjob.getLastBuild(); if ( lastBuild == null ) { return StatusJob.DOESNT_CONTAINS_LASTBUILD; } if ( lastBuild.getResult().isWorseThan(Result.UNSTABLE) ) { return StatusJob.LASTBUILD_RESULT_IS_WORSE_THAN_UNSTABLE; } if ( !lastBuild.getWorkspace().exists() ) { return StatusJob.WORKSPACE_IS_EMPTY; } if ( subjob.poll(listener).hasChanges() ) { return StatusJob.CHANGED_SINCE_LAST_BUILD; } return StatusJob.NOT_CHANGED_SINCE_LAST_BUILD; } public boolean evalCondition(final String condition, final AbstractBuild<?, ?> build, final BuildListener listener) { try { return (Boolean) Eval.me(expandToken(condition, build, listener).toLowerCase().trim()); } catch (Exception e) { listener.getLogger().println("Can't evaluate expression, false is assumed: " + e.toString()); } return false; } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public boolean perform(final AbstractBuild<?, ? > build, final Launcher launcher, final BuildListener listener) throws InterruptedException, IOException { boolean resume = false; Map<String, SubBuild> successBuildMap = new HashMap<String, SubBuild>(); Map<String, SubBuild> failedBuildMap = new HashMap<String, SubBuild>(); MultiJobResumeControl control = build.getAction(MultiJobResumeControl.class); if (null != control) { MultiJobBuild prevBuild = (MultiJobBuild) control.getRun(); for (SubBuild subBuild : prevBuild.getSubBuilds()) { Item item = Jenkins.getInstance().getItem(subBuild.getJobName(), prevBuild.getParent(), AbstractProject.class); if (item instanceof AbstractProject) { AbstractProject childProject = (AbstractProject) item; AbstractBuild childBuild = childProject.getBuildByNumber(subBuild.getBuildNumber()); if (null != childBuild) { if (childBuild.getResult().equals(Result.FAILURE)) { resume = true; failedBuildMap.put(childProject.getUrl(), subBuild); } else { successBuildMap.put(childProject.getUrl(), subBuild); } } } } if (!resume) { successBuildMap.clear(); } } Jenkins jenkins = Jenkins.getInstance(); MultiJobBuild multiJobBuild = (MultiJobBuild) build; MultiJobProject thisProject = multiJobBuild.getProject(); Map<PhaseSubJob, PhaseJobsConfig> phaseSubJobs = new HashMap<PhaseSubJob, PhaseJobsConfig>( phaseJobs.size()); final CounterManager phaseCounters = new CounterManager(); for (PhaseJobsConfig phaseJobConfig : phaseJobs) { Item item = jenkins.getItem(phaseJobConfig.getJobName(), multiJobBuild.getParent(), AbstractProject.class); if (item instanceof AbstractProject) { AbstractProject job = (AbstractProject) item; phaseSubJobs.put(new PhaseSubJob(job), phaseJobConfig); } } List<SubTask> subTasks = new ArrayList<SubTask>(); int index = 0; try { for (PhaseSubJob phaseSubJob : phaseSubJobs.keySet()) { index++; AbstractProject subJob = phaseSubJob.job; // To be coherent with final results, we need to do this here. PhaseJobsConfig phaseConfig = phaseSubJobs.get(phaseSubJob); StatusJob jobStatus = getScmChange(subJob,phaseConfig,multiJobBuild ,listener,launcher ); listener.getLogger().println(jobStatus.getMessage(subJob)); // We are ready to inject vars about scm status. It is useful at condition level. Map<String, String> jobScmVars = new HashMap<String, String>(); // New injected variable. It stores the status of the last job executed. It is useful at condition level. jobScmVars.put(JOB_STATUS, jobStatus.name()); // New injected variable. It reports if the job is buildable. jobScmVars.put(JOB_IS_BUILDABLE, String.valueOf(jobStatus.isBuildable())); injectEnvVars(build, listener, jobScmVars); if (jobStatus == StatusJob.IS_DISABLED) { phaseCounters.processSkipped(); listener.getLogger().println(String.format("Skipping %s. This Job has been disabled.", HyperlinkNote.encodeTo("/" + subJob.getUrl() + "/", subJob.getDisplayName()))); continue; } if (phaseConfig.getEnableCondition() && phaseConfig.getCondition() != null) { if (!evalCondition(phaseConfig.getCondition(), build, listener)) { listener.getLogger().println(String.format("[MultiJob] Skipping %s. Condition evaluates to false.", HyperlinkNote.encodeTo("/" + subJob.getUrl() + "/", subJob.getDisplayName()))); continue; } // This is needed because if no condition to eval, the legacy buildOnlyIfSCMChanges feature is still available, // so we don't need to change our job configuration. } if ( ! jobStatus.isBuildable() ) { phaseCounters.processSkipped(); continue; } reportStart(listener, subJob); List<Action> actions = new ArrayList<Action>(); if (resume) { SubBuild subBuild = failedBuildMap.get(subJob.getUrl()); if (null != subBuild) { AbstractProject prj = Jenkins.getInstance().getItem(subBuild.getJobName(), multiJobBuild.getParent(), AbstractProject.class); AbstractBuild childBuild = prj.getBuildByNumber(subBuild.getBuildNumber()); MultiJobResumeControl childControl = new MultiJobResumeControl(childBuild); actions.add(childControl); } } try { prepareActions(multiJobBuild, subJob, phaseConfig, listener, actions, index); } catch (DontTriggerException exception) { listener.getLogger().println(String.format("[MultiJob] Skipping %s.", HyperlinkNote.encodeTo("/" + subJob.getUrl() + "/", subJob.getDisplayName()))); continue; } if ( jobStatus == StatusJob.IS_DISABLED_AT_PHASECONFIG ) { phaseCounters.processSkipped(); continue; } else { boolean shouldTrigger = null == successBuildMap.get(subJob.getUrl()) ? true : false; subTasks.add(new SubTask(subJob, phaseConfig, actions, multiJobBuild, shouldTrigger)); } } if (subTasks.size() < 1) { // We inject the variables also when no jobs will be triggered. injectEnvVars(build, listener, phaseCounters.toMap()); return true; } // To listen the result of executor we add the subTasks on an ExecutorService ExecutorService executor = Executors.newFixedThreadPool(subTasks.size()); Set<Result> jobResults = new HashSet<Result>(); BlockingQueue<SubTask> queue = new ArrayBlockingQueue<SubTask>(subTasks.size()); for (SubTask subTask : subTasks) { SubBuild subBuild = successBuildMap.get(subTask.subJob.getUrl()); if (null == subBuild) { Runnable worker = new SubJobWorker(thisProject, listener, subTask, queue); executor.execute(worker); } else { AbstractBuild jobBuild = subTask.subJob.getBuildByNumber(subBuild.getBuildNumber()); updateSubBuild(multiJobBuild, thisProject, jobBuild, subBuild.getResult()); } } executor.shutdown(); int resultCounter = 0; while (!executor.isTerminated()) { SubTask subTask = queue.poll(5, TimeUnit.SECONDS); if (subTask != null) { resultCounter++; if (subTask.result != null) { jobResults.add(subTask.result); phaseCounters.process(subTask.result); if (checkPhaseTermination(subTask, subTasks, listener)) { break; } } } if (subTasks.size() <= resultCounter) { break; } } executor.shutdownNow(); injectEnvVars(build, listener, phaseCounters.toMap()); for (Result result : jobResults) { if (!continuationCondition.isContinue(result)) { return false; } } } catch (InterruptedException exception) { listener.getLogger().println("[MultiJob] Aborting all subjobs."); for (SubTask _subTask : subTasks) { listener.getLogger().println(String.format("[MultiJob] Aborting %s.", HyperlinkNote.encodeTo("/" + _subTask.multiJobBuild.getUrl() + "/", _subTask.multiJobBuild.getDisplayName()))); _subTask.cancelJob(); phaseCounters.processAborted(); } throw exception; } return true; } public final class MultijobInterruption extends CauseOfInterruption { final private AbstractBuild jobBuild; public MultijobInterruption(AbstractBuild jobBuild) { this.jobBuild = jobBuild; } @Override public String getShortDescription() { return String.format("Aborted by multijob plugin, because the parent job (%s) has been aborted.", HyperlinkNote.encodeTo("/" + jobBuild.getUrl() + "/", jobBuild.getDisplayName())); } } public final class SubJobWorker extends Thread { final private MultiJobProject multiJobProject; final private BuildListener listener; private SubTask subTask; private BlockingQueue<SubTask> queue; private List<Pattern> compiledPatterns; public SubJobWorker(MultiJobProject multiJobProject, BuildListener listener, SubTask subTask, BlockingQueue<SubTask> queue) { this.multiJobProject = multiJobProject; this.listener = listener; this.subTask = subTask; this.queue = queue; } public void run() { Result result = null; AbstractBuild jobBuild = null; try { int maxRetries = subTask.phaseConfig.getMaxRetries(); if (!subTask.phaseConfig.getEnableRetryStrategy()) { maxRetries = 0; } int retry = 0; boolean buildIsAborted = false; boolean reportStarted = false; while (retry <= maxRetries && !buildIsAborted) { retry++; QueueTaskFuture<AbstractBuild> future = (QueueTaskFuture<AbstractBuild>) subTask.future; while (true) { if (subTask.isCancelled()) { if (jobBuild != null) { Executor exect = jobBuild.getExecutor(); if (exect != null) { exect.interrupt(Result.ABORTED, new MultijobInterruption(jobBuild)); } reportFinish(listener, jobBuild, Result.ABORTED); abortSubBuild(subTask.multiJobBuild, multiJobProject, jobBuild); } buildIsAborted = true; break; } try { jobBuild = future.getStartCondition().get(5, TimeUnit.SECONDS); } catch (Exception e) { if (e instanceof TimeoutException) { continue; } else { throw e; } } updateSubBuild(subTask.multiJobBuild, multiJobProject, jobBuild); if (!reportStarted) { reportBuildStart(listener, jobBuild); reportStarted = true; } if (future.isDone() || (!jobBuild.isBuilding() && jobBuild.getResult() != null)) { break; } Thread.sleep(3000); } if (jobBuild != null && !buildIsAborted) { result = jobBuild.getResult(); reportFinish(listener, jobBuild, result); if (result.isWorseOrEqualTo(Result.FAILURE) && result.isCompleteBuild() && subTask.phaseConfig.getEnableRetryStrategy()) { if (isKnownRandomFailure(jobBuild)) { if (retry <= maxRetries) { listener.getLogger().println("[MultiJob] Known failure detected, retrying this build. Try " + retry + " of " + maxRetries + "."); updateSubBuild(subTask.multiJobBuild, multiJobProject, jobBuild, result, true); subTask.GenerateFuture(); } else { listener.getLogger().println("[MultiJob] Known failure detected, max retries (" + maxRetries + ") exceeded."); updateSubBuild(subTask.multiJobBuild, multiJobProject, jobBuild, result); } } else { listener.getLogger().println("[MultiJob] Failed the build, the failure doesn't match the rules."); updateSubBuild(subTask.multiJobBuild, multiJobProject, jobBuild, result); buildIsAborted = true; } } else { updateSubBuild(subTask.multiJobBuild, multiJobProject, jobBuild, result); buildIsAborted = true; } ChangeLogSet<Entry> changeLogSet = jobBuild.getChangeSet(); subTask.multiJobBuild.addChangeLogSet(changeLogSet); addBuildEnvironmentVariables(subTask.multiJobBuild, jobBuild, listener); subTask.result = result; } } } catch (Exception e) { if (e instanceof InterruptedException) { if (jobBuild != null) { reportFinish(listener, jobBuild, Result.ABORTED); abortSubBuild(subTask.multiJobBuild, multiJobProject, jobBuild); subTask.result = Result.ABORTED; } } else if(e instanceof CancellationException) { reportFinish(listener, multiJobProject, Result.ABORTED); abortSubBuild(subTask.multiJobBuild, multiJobProject, subTask.phaseConfig); subTask.result = Result.ABORTED; } else { listener.getLogger().println(e.toString()); e.printStackTrace(); } } if (jobBuild == null) { updateSubBuild(subTask.multiJobBuild, multiJobProject, subTask.phaseConfig); } queue.add(subTask); } private List<Pattern> getCompiledPattern() throws FileNotFoundException, InterruptedException { if (compiledPatterns == null) { compiledPatterns = new ArrayList<Pattern>(); try { listener.getLogger().println("[MultiJob] Scanning failed job console output using parsing rule file " + subTask.phaseConfig.getParsingRulesPath() + "."); final File rulesFile = new File(subTask.phaseConfig.getParsingRulesPath()); final BufferedReader reader = new BufferedReader(new FileReader(rulesFile.getAbsolutePath())); try { String line; while ((line = reader.readLine()) != null) { compiledPatterns.add(Pattern.compile(line)); } } finally { reader.close(); } } catch (Exception e) { if (e instanceof InterruptedException) { throw new InterruptedException(); } else if (e instanceof FileNotFoundException) { throw new FileNotFoundException(); } else { listener.getLogger().println(e.toString()); e.printStackTrace(); } } } return compiledPatterns; } private final class LineAnalyser extends Thread { final private BufferedReader reader; final private List<Pattern> patterns; private BlockingQueue<LineQueue> finishQueue; public LineAnalyser(BufferedReader reader, List<Pattern> patterns, BlockingQueue<LineQueue> finishQueue) { this.reader = reader; this.patterns = patterns; this.finishQueue = finishQueue; } public void run() { boolean errorFound = false; try { String line; while (reader.ready() && !errorFound) { line = reader.readLine(); if (line != null) { for (Pattern pattern : patterns) { if (pattern.matcher(line).find()) { errorFound = true; break; } } } } } catch (Exception e) { if (e instanceof IOException) { // Nothing } else { listener.getLogger().println(e.toString()); e.printStackTrace(); } } finally { finishQueue.add(new LineQueue(errorFound)); } } } private boolean isKnownRandomFailure(AbstractBuild build) throws InterruptedException { boolean failure = false; try { final List<Pattern> patterns = getCompiledPattern(); final File logFile = build.getLogFile(); final BufferedReader reader = new BufferedReader(new FileReader(logFile.getAbsolutePath())); try { int numberOfThreads = 10; // Todo : Add this in Configure section if (numberOfThreads < 0) { numberOfThreads = 1; } ExecutorService executorAnalyser = Executors.newFixedThreadPool(numberOfThreads); BlockingQueue<LineQueue> finishQueue = new ArrayBlockingQueue<LineQueue>(numberOfThreads); for (int i = 0; i < numberOfThreads; i++) { Runnable worker = new LineAnalyser(reader, patterns, finishQueue); executorAnalyser.execute(worker); } executorAnalyser.shutdown(); int resultCounter = 0; while (!executorAnalyser.isTerminated()) { resultCounter++; LineQueue lineQueue = finishQueue.take(); if (lineQueue.hasError()) { failure = true; break; } else if (numberOfThreads == resultCounter) { break; } } executorAnalyser.shutdownNow(); } finally { reader.close(); } } catch (Exception e) { if (e instanceof InterruptedException) { throw new InterruptedException(); } else if (e instanceof FileNotFoundException) { listener.getLogger().println("[MultiJob] Parser rules file not found."); failure = false; } else { listener.getLogger().println(e.toString()); e.printStackTrace(); } } return failure; } } protected boolean checkPhaseTermination(SubTask subTask, List<SubTask> subTasks, final BuildListener listener) { try { KillPhaseOnJobResultCondition killCondition = subTask.phaseConfig.getKillPhaseOnJobResultCondition(); if (killCondition.equals(KillPhaseOnJobResultCondition.NEVER) || subTask.result != Result.ABORTED) { return false; } if (killCondition.isKillPhase(subTask.result)) { if (subTask.result != Result.ABORTED || subTask.phaseConfig.getAbortAllJob()) { for (SubTask _subTask : subTasks) { _subTask.cancelJob(); } return true; } } } catch (Exception e) { listener.getLogger().printf(e.toString()); return false; } return false; } private void reportStart(BuildListener listener, AbstractProject subJob) { listener.getLogger().printf( "[MultiJob] Starting job %s.\n", HyperlinkNote.encodeTo('/' + subJob.getUrl(), subJob.getFullName())); } private void reportBuildStart(BuildListener listener, AbstractBuild jobBuild) { listener.getLogger().println( "[MultiJob] Build start : " + HyperlinkNote.encodeTo("/" + jobBuild.getUrl(), jobBuild.getDisplayName())); } private void reportFinish(BuildListener listener, AbstractBuild jobBuild, Result result) { listener.getLogger().println( "[MultiJob] Finished Build : " + HyperlinkNote.encodeTo("/" + jobBuild.getUrl() + "/", jobBuild.getDisplayName()) + " of Job : " + HyperlinkNote.encodeTo('/' + jobBuild.getProject() .getUrl(), jobBuild.getProject().getFullName()) + " with status : " + HyperlinkNote.encodeTo('/' + jobBuild.getUrl() + "/console", result.toString())); } private void reportFinish(BuildListener listener, MultiJobProject project, Result result) { listener.getLogger().println( "[MultiJob] Finished Build : Job : " + HyperlinkNote.encodeTo('/' + project.getUrl(), project.getFullName()) + " with status : " + result.toString()); } private void updateSubBuild(MultiJobBuild multiJobBuild, MultiJobProject multiJobProject, PhaseJobsConfig phaseConfig) { SubBuild subBuild = new SubBuild(multiJobProject.getName(), multiJobBuild.getNumber(), phaseConfig.getJobName(), 0, phaseName, null, BallColor.NOTBUILT.getImage(), "not built", "", null); multiJobBuild.addSubBuild(subBuild); } private void updateSubBuild(MultiJobBuild multiJobBuild, MultiJobProject multiJobProject, AbstractBuild<?, ?> jobBuild) { SubBuild subBuild = new SubBuild(multiJobProject.getName(), multiJobBuild.getNumber(), jobBuild.getProject().getName(), jobBuild.getNumber(), phaseName, null, jobBuild.getIconColor() .getImage(), jobBuild.getDurationString(), jobBuild.getUrl(), jobBuild); multiJobBuild.addSubBuild(subBuild); } private void updateSubBuild(MultiJobBuild multiJobBuild, MultiJobProject multiJobProject, AbstractBuild<?, ?> jobBuild, Result result) { SubBuild subBuild = new SubBuild(multiJobProject.getName(), multiJobBuild.getNumber(), jobBuild.getProject().getName(), jobBuild.getNumber(), phaseName, result, jobBuild.getIconColor().getImage(), jobBuild.getDurationString(), jobBuild.getUrl(), jobBuild); multiJobBuild.addSubBuild(subBuild); } private void updateSubBuild(MultiJobBuild multiJobBuild, MultiJobProject multiJobProject, AbstractBuild<?, ?> jobBuild, Result result, boolean retry) { SubBuild subBuild = new SubBuild(multiJobProject.getName(), multiJobBuild.getNumber(), jobBuild.getProject().getName(), jobBuild.getNumber(), phaseName, result, jobBuild.getIconColor().getImage(), jobBuild.getDurationString(), jobBuild.getUrl(), retry, false, jobBuild); multiJobBuild.addSubBuild(subBuild); } private void abortSubBuild(MultiJobBuild multiJobBuild, MultiJobProject multiJobProject, PhaseJobsConfig phaseConfig) { SubBuild subBuild = new SubBuild(multiJobProject.getName(), multiJobBuild.getNumber(), phaseConfig.getJobName(), 0, phaseName, Result.ABORTED, BallColor.ABORTED.getImage(), "Aborted in queue", "", null); multiJobBuild.addSubBuild(subBuild); } private void abortSubBuild(MultiJobBuild multiJobBuild, MultiJobProject multiJobProject, AbstractBuild<?, ?> jobBuild) { SubBuild subBuild = new SubBuild(multiJobProject.getName(), multiJobBuild.getNumber(), jobBuild.getProject().getName(), jobBuild.getNumber(), phaseName, Result.ABORTED, BallColor.ABORTED.getImage(), "", jobBuild.getUrl(), false, true, jobBuild); multiJobBuild.addSubBuild(subBuild); } @SuppressWarnings("rawtypes") private void addBuildEnvironmentVariables(MultiJobBuild thisBuild, AbstractBuild jobBuild, BuildListener listener) { // Env variables map Map<String, String> variables = new HashMap<String, String>(); // Fetch the map of existing environment variables try { EnvInjectLogger logger = new EnvInjectLogger(listener); EnvInjectVariableGetter variableGetter = new EnvInjectVariableGetter(); Map<String, String> previousEnvVars = variableGetter .getEnvVarsPreviousSteps(thisBuild, logger); // Get current envVars variables = new HashMap<String, String>( previousEnvVars); } catch (Throwable throwable) { listener.getLogger() .println( "[MultiJob] - [ERROR] - Problems occurs on fetching env vars as a build step: " + throwable.getMessage()); } String jobName = jobBuild.getProject().getName(); String jobNameSafe = jobName.replaceAll("[^A-Za-z0-9]", "_") .toUpperCase(); String buildNumber = Integer.toString(jobBuild.getNumber()); String buildResult = jobBuild.getResult().toString(); String buildName = jobBuild.getDisplayName().toString(); // If the job is run a second time, store the first job's number and result with unique keys if (variables.get("TRIGGERED_BUILD_RUN_COUNT_" + jobNameSafe) != null) { String runCount = Integer.toString(Integer.parseInt(variables .get("TRIGGERED_BUILD_RUN_COUNT_" + jobNameSafe))); if (runCount.equals("1")) { String firstBuildNumber = variables.get(jobNameSafe + "_BUILD_NUMBER"); String firstBuildResult = variables.get(jobNameSafe + "_BUILD_RESULT"); variables.put(jobNameSafe + "_" + runCount + "_BUILD_NUMBER", firstBuildNumber); variables.put(jobNameSafe + "_" + runCount + "_BUILD_RESULT", firstBuildResult); } } // These will always reference the last build variables.put("LAST_TRIGGERED_JOB_NAME", jobName); variables.put(jobNameSafe + "_BUILD_NUMBER", buildNumber); variables.put(jobNameSafe + "_BUILD_RESULT", buildResult); variables.put(jobNameSafe + "_BUILD_NAME", buildName); if (variables.get("TRIGGERED_JOB_NAMES") == null) { variables.put("TRIGGERED_JOB_NAMES", jobName); } else { String triggeredJobNames = variables.get("TRIGGERED_JOB_NAMES") + "," + jobName; variables.put("TRIGGERED_JOB_NAMES", triggeredJobNames); } if (variables.get("TRIGGERED_BUILD_RUN_COUNT_" + jobNameSafe) == null) { variables.put("TRIGGERED_BUILD_RUN_COUNT_" + jobNameSafe, "1"); } else { String runCount = Integer.toString(Integer.parseInt(variables .get("TRIGGERED_BUILD_RUN_COUNT_" + jobNameSafe)) + 1); variables.put("TRIGGERED_BUILD_RUN_COUNT_" + jobNameSafe, runCount); variables.put(jobNameSafe + "_" + runCount + "_BUILD_NUMBER", buildNumber); variables.put(jobNameSafe + "_" + runCount + "_BUILD_RESULT", buildResult); } // Set the new build variables map injectEnvVars(thisBuild, listener, variables); } /** * Method for properly injecting environment variables via EnvInject plugin. * Method based off logic in {@link EnvInjectBuilder#perform} */ private void injectEnvVars(AbstractBuild<?, ?> build, BuildListener listener, Map<String, String> incomingVars) { if (build != null && incomingVars != null) { EnvInjectLogger logger = new EnvInjectLogger(listener); FilePath ws = build.getWorkspace(); EnvInjectActionSetter envInjectActionSetter = new EnvInjectActionSetter( ws ); EnvInjectEnvVars envInjectEnvVarsService = new EnvInjectEnvVars( logger ); try { EnvInjectVariableGetter variableGetter = new EnvInjectVariableGetter(); Map<String, String> previousEnvVars = variableGetter .getEnvVarsPreviousSteps(build, logger); // Get current envVars Map<String, String> variables = new HashMap<String, String>(previousEnvVars); // Acumule PHASE, PHASENAME and MULTIJOB counters. // Values are in variables (current values) and incomingVars. Map<String, String> mixtured = CounterHelper.putPhaseAddMultijobAndMergeTheRest(listener, this.phaseName, incomingVars, variables); // Resolve variables final Map<String, String> resultVariables = envInjectEnvVarsService .getMergedVariables(variables, mixtured); // Set the new build variables map build.addAction(new EnvInjectBuilderContributionAction( resultVariables)); // Add or get the existing action to add new env vars envInjectActionSetter.addEnvVarsToEnvInjectBuildAction(build, resultVariables); } catch (Throwable throwable) { listener.getLogger() .println( "[MultiJob] - [ERROR] - Problems occurs on injecting env vars as a build step: " + throwable.getMessage()); throwable.printStackTrace(); } } } @SuppressWarnings("rawtypes") private void prepareActions(AbstractBuild build, AbstractProject project, PhaseJobsConfig projectConfig, BuildListener listener, List<Action> actions, int index) throws IOException, InterruptedException, DontTriggerException { List<Action> parametersActions = (List<Action>) projectConfig.getActions(build, listener, project, projectConfig.isCurrParams()); actions.addAll(parametersActions); actions.add(new MultiJobAction(build, index)); } private class MultiJobAction implements Action, QueueAction { public AbstractBuild build; public int index; public MultiJobAction(AbstractBuild build, int index) { this.build = build; this.index = index; } public boolean shouldSchedule(List<Action> actions) { boolean matches = true; for (MultiJobAction action : Util.filter(actions, MultiJobAction.class)) { if (action.index != index) { matches = false; } if (action.build.getNumber() != build.getNumber()) { matches = false; } } return !matches; } public String getIconFileName() { return null; } public String getDisplayName() { return "this shouldn't be displayed"; } public String getUrlName() { return null; } } public String getPhaseName() { return phaseName; } public void setPhaseName(String phaseName) { this.phaseName = phaseName; } public List<PhaseJobsConfig> getPhaseJobs() { return phaseJobs; } public void setPhaseJobs(List<PhaseJobsConfig> phaseJobs) { this.phaseJobs = phaseJobs; } public boolean phaseNameExist(String phaseName) { for (PhaseJobsConfig phaseJob : phaseJobs) { if (phaseJob.getDisplayName().equals(phaseName)) { return true; } } return false; } private final static class PhaseSubJob { AbstractProject job; PhaseSubJob(AbstractProject job) { this.job = job; } } @Extension public static class DescriptorImpl extends BuildStepDescriptor<Builder> { @SuppressWarnings("rawtypes") @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return jobType.equals(MultiJobProject.class); } @Override public String getDisplayName() { return "MultiJob Phase"; } @Override public Builder newInstance(StaplerRequest req, JSONObject formData) throws FormException { return req.bindJSON(MultiJobBuilder.class, formData); } @Override public boolean configure(StaplerRequest req, JSONObject formData) { save(); return true; } } @SuppressWarnings("rawtypes") public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) { Jenkins jenkins = Jenkins.getInstance(); List<PhaseJobsConfig> phaseJobsConfigs = getPhaseJobs(); if (phaseJobsConfigs == null) return; for (PhaseJobsConfig project : phaseJobsConfigs) { Item topLevelItem = jenkins.getItem(project.getJobName(), owner.getParent(), AbstractProject.class); if (topLevelItem instanceof AbstractProject) { Dependency dependency = new Dependency(owner, (AbstractProject) topLevelItem) { @Override public boolean shouldTriggerBuild(AbstractBuild build, TaskListener listener, List<Action> actions) { return false; } }; graph.addDependency(dependency); } } } public boolean onJobRenamed(String oldName, String newName) { boolean changed = false; for (Iterator i = phaseJobs.iterator(); i.hasNext();) { PhaseJobsConfig phaseJobs = (PhaseJobsConfig) i.next(); String jobName = phaseJobs.getJobName(); if (jobName.trim().equals(oldName)) { if (newName != null) { phaseJobs.setJobName(newName); changed = true; } else { i.remove(); changed = true; } } } return changed; } public boolean onJobDeleted(String oldName) { return onJobRenamed(oldName, null); } public static enum ContinuationCondition { ALWAYS("Always") { @Override public boolean isContinue(Result result) { return true; } }, SUCCESSFUL("Successful") { @Override public boolean isContinue(Result result) { return result.equals(Result.SUCCESS); } }, COMPLETED("Completed") { @Override public boolean isContinue(Result result) { return result.isCompleteBuild(); } }, UNSTABLE("Stable or Unstable but not Failed") { @Override public boolean isContinue(Result result) { return result.isBetterOrEqualTo(Result.UNSTABLE); } }, FAILURE("Failed") { @Override public boolean isContinue(Result result) { return result.isWorseOrEqualTo(Result.FAILURE); } }; abstract public boolean isContinue(Result result); private ContinuationCondition(String label) { this.label = label; } final private String label; public String getLabel() { return label; } } public ContinuationCondition getContinuationCondition() { return continuationCondition; } public void setContinuationCondition( ContinuationCondition continuationCondition) { this.continuationCondition = continuationCondition; } }
package crazypants.enderio.conduit.item; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import crazypants.enderio.conduit.ConnectionMode; import crazypants.enderio.conduit.item.filter.IItemFilter; import crazypants.enderio.config.Config; import crazypants.util.BlockCoord; import crazypants.util.InventoryWrapper; import crazypants.util.ItemUtil; import crazypants.util.RoundRobinIterator; public class NetworkedInventory { private ISidedInventory inv; IItemConduit con; ForgeDirection conDir; BlockCoord location; int inventorySide; List<Target> sendPriority = new ArrayList<Target>(); RoundRobinIterator<Target> rrIter = new RoundRobinIterator<Target>(sendPriority); private int extractFromSlot = -1; int tickDeficit; //work around for a vanilla chest changing into a double chest without doing unneeded checks all the time boolean recheckInv = false; //Hack for TiC crafting station not working correctly when setting output slot to null boolean ticHack = false; World world; ItemConduitNetwork network; NetworkedInventory(ItemConduitNetwork network, IInventory inv, IItemConduit con, ForgeDirection conDir, BlockCoord location) { this.network = network; inventorySide = conDir.getOpposite().ordinal(); this.con = con; this.conDir = conDir; this.location = location; world = con.getBundle().getWorld(); TileEntity te = world.getTileEntity(location.x, location.y, location.z); if(te.getClass().getName().equals("tconstruct.tools.logic.CraftingStationLogic")) { ticHack = true; } else if(te.getClass().getName().contains("cpw.mods.ironchest")) { recheckInv = true; } else if(te instanceof TileEntityChest) { recheckInv = true; } updateInventory(); } public boolean hasTarget(IItemConduit conduit, ForgeDirection dir) { for (Target t : sendPriority) { if(t.inv.con == conduit && t.inv.conDir == dir) { return true; } } return false; } boolean canExtract() { ConnectionMode mode = con.getConectionMode(conDir); return mode == ConnectionMode.INPUT || mode == ConnectionMode.IN_OUT; } boolean canInsert() { ConnectionMode mode = con.getConectionMode(conDir); return mode == ConnectionMode.OUTPUT || mode == ConnectionMode.IN_OUT; } boolean isSticky() { return con.getOutputFilter(conDir) != null && con.getOutputFilter(conDir).isValid() && con.getOutputFilter(conDir).isSticky(); } int getPriority() { return con.getOutputPriority(conDir); } public void onTick(long tick) { int transfered; if(tickDeficit > 0 || !canExtract() || !con.isExtractionRedstoneConditionMet(conDir)) { //do nothing } else { transferItems(); } tickDeficit if(tickDeficit < -1) { //Sleep for a second before checking again. tickDeficit = 20; } } private boolean canExtractThisTick(long tick) { if(!con.isExtractionRedstoneConditionMet(conDir)) { return false; } return true; } private int nextSlot(int numSlots) { ++extractFromSlot; if(extractFromSlot >= numSlots || extractFromSlot < 0) { extractFromSlot = 0; } return extractFromSlot; } private void setNextStartingSlot(int slot) { extractFromSlot = slot; extractFromSlot } private boolean transferItems() { if(recheckInv) { updateInventory(); } int[] slotIndices = getInventory().getAccessibleSlotsFromSide(inventorySide); if(slotIndices == null) { return false; } int numSlots = slotIndices.length; ItemStack extractItem = null; int maxExtracted = con.getMaximumExtracted(conDir); int slot = -1; int slotChecksPerTick = Math.min(numSlots, ItemConduitNetwork.MAX_SLOT_CHECK_PER_TICK); for (int i = 0; i < slotChecksPerTick; i++) { int index = nextSlot(numSlots); slot = slotIndices[index]; ItemStack item = getInventory().getStackInSlot(slot); if(canExtractItem(item)) { extractItem = item.copy(); if(getInventory().canExtractItem(slot, extractItem, inventorySide)) { if(doTransfer(extractItem, slot, maxExtracted)) { setNextStartingSlot(slot); return true; } } } } return false; } private boolean canExtractItem(ItemStack itemStack) { if(itemStack == null) { return false; } IItemFilter filter = con.getInputFilter(conDir); if(filter == null) { return true; } return filter.doesItemPassFilter(this, itemStack); } private boolean doTransfer(ItemStack extractedItem, int slot, int maxExtract) { if(extractedItem == null) { return false; } ItemStack toExtract = extractedItem.copy(); toExtract.stackSize = Math.min(maxExtract, toExtract.stackSize); int numInserted = insertIntoTargets(toExtract); if(numInserted <= 0) { return false; } ItemStack curStack = getInventory().getStackInSlot(slot); if(curStack != null) { if(ticHack) { getInventory().decrStackSize(slot, numInserted); getInventory().markDirty(); } else { curStack = curStack.copy(); curStack.stackSize -= numInserted; if(curStack.stackSize > 0) { getInventory().setInventorySlotContents(slot, curStack); getInventory().markDirty(); } else { getInventory().setInventorySlotContents(slot, null); getInventory().markDirty(); } } } con.itemsExtracted(numInserted, slot); tickDeficit = Math.round(numInserted * con.getTickTimePerItem(conDir)); return true; } int insertIntoTargets(ItemStack toExtract) { if(toExtract == null) { return 0; } int totalToInsert = toExtract.stackSize; int leftToInsert = totalToInsert; boolean matchedStickyInput = false; Iterable<Target> targets = getTargetIterator(); //for (Target target : sendPriority) { for (Target target : targets) { if(target.stickyInput && !matchedStickyInput) { IItemFilter of = target.inv.con.getOutputFilter(target.inv.conDir); matchedStickyInput = of != null && of.isValid() && of.doesItemPassFilter(this, toExtract); } if(target.stickyInput || !matchedStickyInput) { if(target.inv.recheckInv) { target.inv.updateInventory(); } int inserted = target.inv.insertItem(toExtract); if(inserted > 0) { toExtract.stackSize -= inserted; leftToInsert -= inserted; } if(leftToInsert <= 0) { return totalToInsert; } } } return totalToInsert - leftToInsert; } private Iterable<Target> getTargetIterator() { if(con.isRoundRobinEnabled(conDir)) { return rrIter; } return sendPriority; } private void updateInventory() { TileEntity te = world.getTileEntity(location.x, location.y, location.z); if(te instanceof ISidedInventory) { inv = (ISidedInventory) te; } else if(te instanceof IInventory) { inv = new InventoryWrapper((IInventory) te); } } private int insertItem(ItemStack item) { if(!canInsert() || item == null) { return 0; } IItemFilter filter = con.getOutputFilter(conDir); if(filter != null) { if(!filter.doesItemPassFilter(this, item)) { return 0; } } return ItemUtil.doInsertItem(getInventory(), item, ForgeDirection.values()[inventorySide]); } void updateInsertOrder() { sendPriority.clear(); if(!canExtract()) { return; } List<Target> result = new ArrayList<NetworkedInventory.Target>(); for (NetworkedInventory other : network.inventories) { if((con.isSelfFeedEnabled(conDir) || (other != this)) && other.canInsert() && con.getInputColor(conDir) == other.con.getOutputColor(other.conDir)) { if(Config.itemConduitUsePhyscialDistance) { sendPriority.add(new Target(other, distanceTo(other), other.isSticky(), other.getPriority())); } else { result.add(new Target(other, 9999999, other.isSticky(), other.getPriority())); } } } if(Config.itemConduitUsePhyscialDistance) { Collections.sort(sendPriority); } else { if(!result.isEmpty()) { Map<BlockCoord, Integer> visited = new HashMap<BlockCoord, Integer>(); List<BlockCoord> steps = new ArrayList<BlockCoord>(); steps.add(con.getLocation()); calculateDistances(result, visited, steps, 0); sendPriority.addAll(result); Collections.sort(sendPriority); } } } private void calculateDistances(List<Target> targets, Map<BlockCoord, Integer> visited, List<BlockCoord> steps, int distance) { if(steps == null || steps.isEmpty()) { return; } ArrayList<BlockCoord> nextSteps = new ArrayList<BlockCoord>(); for (BlockCoord bc : steps) { IItemConduit con = network.conMap.get(bc); if(con != null) { for (ForgeDirection dir : con.getExternalConnections()) { Target target = getTarget(targets, con, dir); if(target != null && target.distance > distance) { target.distance = distance; } } if(!visited.containsKey(bc)) { visited.put(bc, distance); } else { int prevDist = visited.get(bc); if(prevDist <= distance) { continue; } visited.put(bc, distance); } for (ForgeDirection dir : con.getConduitConnections()) { nextSteps.add(bc.getLocation(dir)); } } } calculateDistances(targets, visited, nextSteps, distance + 1); } private Target getTarget(List<Target> targets, IItemConduit con, ForgeDirection dir) { if(targets == null || con == null || con.getLocation() == null) { return null; } for (Target target : targets) { BlockCoord targetConLoc = null; if(target != null && target.inv != null && target.inv.con != null) { targetConLoc = target.inv.con.getLocation(); } if(targetConLoc != null && target.inv.conDir == dir && targetConLoc.equals(con.getLocation())) { return target; } } return null; } private int distanceTo(NetworkedInventory other) { return con.getLocation().distanceSquared(other.con.getLocation()); } public ISidedInventory getInventory() { return inv; } public int getInventorySide() { return inventorySide; } public void setInventorySide(int inventorySide) { this.inventorySide = inventorySide; } static class Target implements Comparable<Target> { NetworkedInventory inv; int distance; boolean stickyInput; int priority; Target(NetworkedInventory inv, int distance, boolean stickyInput, int priority) { this.inv = inv; this.distance = distance; this.stickyInput = stickyInput; this.priority = priority; } @Override public int compareTo(Target o) { if(stickyInput && !o.stickyInput) { return -1; } if(!stickyInput && o.stickyInput) { return 1; } if(priority != o.priority) { return ItemConduitNetwork.compare(o.priority, priority); } return ItemConduitNetwork.compare(distance, o.distance); } } }
package crazypants.enderio.machine.power; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import thermalexpansion.api.item.IChargeableItem; import buildcraft.api.power.PowerHandler; import buildcraft.api.power.PowerHandler.PowerReceiver; import buildcraft.api.power.PowerHandler.Type; import cofh.api.energy.IEnergyContainerItem; import crazypants.enderio.EnderIO; import crazypants.enderio.TileEntityEio; import crazypants.enderio.conduit.ConnectionMode; import crazypants.enderio.conduit.IConduitBundle; import crazypants.enderio.conduit.power.IPowerConduit; import crazypants.enderio.machine.IIoConfigurable; import crazypants.enderio.machine.IoMode; import crazypants.enderio.machine.RedstoneControlMode; import crazypants.enderio.power.BasicCapacitor; import crazypants.enderio.power.IInternalPowerReceptor; import crazypants.enderio.power.IPowerInterface; import crazypants.enderio.power.PowerHandlerUtil; import crazypants.util.BlockCoord; import crazypants.util.Util; import crazypants.vecmath.VecmathUtil; public class TileCapacitorBank extends TileEntityEio implements IInternalPowerReceptor, IInventory, IIoConfigurable { static final BasicCapacitor BASE_CAP = new BasicCapacitor(100, 500000); BlockCoord[] multiblock = null; private PowerHandler powerHandler; private PowerHandler disabledPowerHandler; private float lastSyncPowerStored; private float storedEnergy; private int maxStoredEnergy; private int maxIO; private int maxInput; private int maxOutput; private int mjBuf = 0; private boolean multiblockDirty = false; private RedstoneControlMode inputControlMode; private RedstoneControlMode outputControlMode; private boolean outputEnabled; private boolean inputEnabled; private boolean isRecievingRedstoneSignal; private boolean redstoneStateDirty = true; private List<Receptor> masterReceptors; private ListIterator<Receptor> receptorIterator; private List<Receptor> localReceptors; private boolean receptorsDirty = true; private final ItemStack[] inventory; private List<GaugeBounds> gaugeBounds; private Map<ForgeDirection, IoMode> faceModes; private boolean render = false; private boolean masterReceptorsDirty; private boolean notifyNeighbours = false; float energyAtLastRender = -1; public TileCapacitorBank() { inventory = new ItemStack[4]; storedEnergy = 0; inputControlMode = RedstoneControlMode.IGNORE; outputControlMode = RedstoneControlMode.IGNORE; maxStoredEnergy = BASE_CAP.getMaxEnergyStored(); maxIO = BASE_CAP.getMaxEnergyExtracted(); maxInput = maxIO; maxOutput = maxIO; updatePowerHandler(); } @Override public IoMode toggleIoModeForFace(ForgeDirection faceHit) { IPowerInterface rec = getReceptorForFace(faceHit); IoMode curMode = getIoMode(faceHit); if(curMode == IoMode.PULL) { setIoMode(faceHit, IoMode.PUSH, true); return IoMode.PUSH; } if(curMode == IoMode.PUSH) { setIoMode(faceHit, IoMode.DISABLED, true); return IoMode.DISABLED; } if(curMode == IoMode.DISABLED) { if(rec == null || rec.getDelegate() instanceof IConduitBundle) { setIoMode(faceHit, IoMode.NONE, true); return IoMode.NONE; } } setIoMode(faceHit, IoMode.PULL, true); return IoMode.PULL; } @Override public boolean supportsMode(ForgeDirection faceHit, IoMode mode) { IPowerInterface rec = getReceptorForFace(faceHit); if(mode == IoMode.NONE) { return rec == null || rec.getDelegate() instanceof IConduitBundle; } return true; } @Override public void setIoMode(ForgeDirection faceHit, IoMode mode) { setIoMode(faceHit, mode, true); } public void setIoMode(ForgeDirection faceHit, IoMode mode, boolean updateReceptors) { if(mode == IoMode.NONE && faceModes == null) { return; } if(faceModes == null) { faceModes = new EnumMap<ForgeDirection, IoMode>(ForgeDirection.class); } faceModes.put(faceHit, mode); if(updateReceptors) { receptorsDirty = true; getController().masterReceptorsDirty = true; notifyNeighbours = true; } render = true; } @Override public IoMode getIoMode(ForgeDirection face) { if(faceModes == null) { return IoMode.NONE; } IoMode res = faceModes.get(face); if(res == null) { return IoMode.NONE; } return res; } @Override public BlockCoord getLocation() { return new BlockCoord(this); } private IPowerInterface getReceptorForFace(ForgeDirection faceHit) { BlockCoord checkLoc = new BlockCoord(this).getLocation(faceHit); TileEntity te = worldObj.getTileEntity(checkLoc.x, checkLoc.y, checkLoc.z); if(!(te instanceof TileCapacitorBank)) { return PowerHandlerUtil.create(te); } return null; } @Override public void updateEntity() { if(worldObj == null) { // sanity check return; } if(worldObj.isRemote) { if(render) { worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); render = false; } return; } // else is server, do all logic only on the server if(multiblockDirty) { formMultiblock(); multiblockDirty = false; } if(!isContoller()) { if(notifyNeighbours) { worldObj.notifyBlockOfNeighborChange(xCoord, yCoord, zCoord, getBlockType()); notifyNeighbours = false; } return; } boolean requiresClientSync = false; requiresClientSync = chargeItems(); boolean hasSignal = isRecievingRedstoneSignal(); if(inputControlMode == RedstoneControlMode.IGNORE) { inputEnabled = true; } else if(inputControlMode == RedstoneControlMode.NEVER) { inputEnabled = false; } else { inputEnabled = (inputControlMode == RedstoneControlMode.ON && hasSignal) || (inputControlMode == RedstoneControlMode.OFF && !hasSignal); } if(outputControlMode == RedstoneControlMode.IGNORE) { outputEnabled = true; } else if(outputControlMode == RedstoneControlMode.NEVER) { outputEnabled = false; } else { outputEnabled = (outputControlMode == RedstoneControlMode.ON && hasSignal) || (outputControlMode == RedstoneControlMode.OFF && !hasSignal); } updateMasterReceptors(); if(outputEnabled) { transmitEnergy(); } //input any BC energy, yes, after output to avoid losing energy if we can if(powerHandler != null && powerHandler.getEnergyStored() > 0) { storedEnergy += powerHandler.getEnergyStored(); powerHandler.setEnergy(0); } requiresClientSync |= lastSyncPowerStored != storedEnergy && worldObj.getTotalWorldTime() % 10 == 0; if(requiresClientSync) { lastSyncPowerStored = storedEnergy; worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); markDirty(); } if(notifyNeighbours) { worldObj.notifyBlockOfNeighborChange(xCoord, yCoord, zCoord, getBlockType()); notifyNeighbours = false; } } public List<GaugeBounds> getGaugeBounds() { if(gaugeBounds == null) { gaugeBounds = GaugeBounds.calculateGaugeBounds(new BlockCoord(this), multiblock); } return gaugeBounds; } private boolean chargeItems() { boolean chargedItem = false; float available = Math.min(maxIO, storedEnergy); for (ItemStack item : inventory) { if(item != null && available > 0) { float used = 0; if(item.getItem() instanceof IEnergyContainerItem) { IEnergyContainerItem chargable = (IEnergyContainerItem) item.getItem(); float max = chargable.getMaxEnergyStored(item); float cur = chargable.getEnergyStored(item); float canUse = Math.min(available * 10, max - cur); if(cur < max) { used = chargable.receiveEnergy(item, (int) canUse, false) / 10; // TODO: I should be able to use 'used' but it is always returning 0 // ATM. used = (chargable.getEnergyStored(item) - cur) / 10; } } else if(item.getItem() instanceof IChargeableItem) { IChargeableItem chargable = (IChargeableItem) item.getItem(); float max = chargable.getMaxEnergyStored(item); float cur = chargable.getEnergyStored(item); float canUse = Math.min(available, max - cur); if(cur < max) { if(chargable.getClass().getName().startsWith("appeng") || "appeng.common.base.AppEngMultiChargeable".equals(chargable.getClass().getName())) { // 256 max limit canUse = Math.min(canUse, 256); NBTTagCompound tc = item.getTagCompound(); if(tc == null) { item.setTagCompound(tc = new NBTTagCompound()); } double newVal = (cur + canUse) * 5.0; tc.setDouble("powerLevel", newVal); used = canUse; } else { used = chargable.receiveEnergy(item, canUse, true); } } } if(used > 0) { storedEnergy = storedEnergy - used; chargedItem = true; available -= used; } } } return chargedItem; } public boolean isOutputEnabled() { return getController().outputEnabled; } public boolean isOutputEnabled(ForgeDirection direction) { IoMode mode = getIoMode(direction); return mode == IoMode.PUSH || mode == IoMode.NONE && isOutputEnabled(); } public boolean isInputEnabled() { return getController().inputEnabled; } public boolean isInputEnabled(ForgeDirection direction) { IoMode mode = getIoMode(direction); return mode == IoMode.PUSH || mode == IoMode.NONE && isInputEnabled(); } private boolean transmitEnergy() { if(storedEnergy <= 0) { return false; } float canTransmit = Math.min(storedEnergy, maxOutput); float transmitted = 0; if(!masterReceptors.isEmpty() && !receptorIterator.hasNext()) { receptorIterator = masterReceptors.listIterator(); } int appliedCount = 0; int numReceptors = masterReceptors.size(); while (receptorIterator.hasNext() && canTransmit > 0 && appliedCount < numReceptors) { Receptor receptor = receptorIterator.next(); IPowerInterface powerInterface = receptor.receptor; IoMode mode = receptor.mode; if(powerInterface != null && mode != IoMode.PULL && mode != IoMode.DISABLED && powerInterface.getMinEnergyReceived(receptor.fromDir.getOpposite()) <= canTransmit) { float used; if(receptor.receptor.getDelegate() instanceof IConduitBundle) { //All other power transfer is handled by the conduit network IConduitBundle bundle = (IConduitBundle) receptor.receptor.getDelegate(); IPowerConduit conduit = bundle.getConduit(IPowerConduit.class); if(conduit != null && conduit.getConectionMode(receptor.fromDir.getOpposite()) == ConnectionMode.INPUT) { used = powerInterface.recieveEnergy(receptor.fromDir.getOpposite(), canTransmit); } else { used = 0; } } else { used = powerInterface.recieveEnergy(receptor.fromDir.getOpposite(), canTransmit); } transmitted += used; canTransmit -= used; } if(canTransmit <= 0) { break; } if(!masterReceptors.isEmpty() && !receptorIterator.hasNext()) { receptorIterator = masterReceptors.listIterator(); } appliedCount++; } storedEnergy = storedEnergy - transmitted; return transmitted > 0; } private void updateMasterReceptors() { if(!masterReceptorsDirty && masterReceptors != null) { return; } if(masterReceptors == null) { masterReceptors = new ArrayList<Receptor>(); } masterReceptors.clear(); if(multiblock == null) { updateReceptors(); if(localReceptors != null) { masterReceptors.addAll(localReceptors); } } else { //TODO: Performance warning?? for (BlockCoord bc : multiblock) { TileEntity te = worldObj.getTileEntity(bc.x, bc.y, bc.z); if(te instanceof TileCapacitorBank) { TileCapacitorBank cb = ((TileCapacitorBank) te); cb.updateReceptors(); if(cb.localReceptors != null) { masterReceptors.addAll(cb.localReceptors); } } } } receptorIterator = masterReceptors.listIterator(); masterReceptorsDirty = false; } private void updateReceptors() { if(!receptorsDirty) { return; } if(localReceptors != null) { localReceptors.clear(); } BlockCoord bc = new BlockCoord(this); for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { IoMode mode = getIoMode(dir); if(mode != IoMode.DISABLED) { BlockCoord checkLoc = bc.getLocation(dir); TileEntity te = worldObj.getTileEntity(checkLoc.x, checkLoc.y, checkLoc.z); if(!(te instanceof TileCapacitorBank)) { IPowerInterface ph = PowerHandlerUtil.create(te); if(ph != null && ph.canConduitConnect(dir)) { if(localReceptors == null) { localReceptors = new ArrayList<Receptor>(); } Receptor r = new Receptor(ph, dir, mode); localReceptors.add(r); if(mode == IoMode.NONE && !(ph.getDelegate() instanceof IInternalPowerReceptor)) { setIoMode(dir, IoMode.PULL, false); r.mode = IoMode.PULL; worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); render = true; } } } } } receptorsDirty = false; } public int getEnergyStoredScaled(int scale) { return getController().doGetEnergyStoredScaled(scale); } public int getMaxInput() { return maxInput; } public void setMaxInput(int maxInput) { getController().doSetMaxInput(maxInput); } public int getMaxOutput() { return maxOutput; } public void setMaxOutput(int maxOutput) { getController().doSetMaxOutput(maxOutput); } public float getEnergyStored() { return getController().doGetEnergyStored(); } public float getEnergyStoredRatio() { return getController().doGetEnergyStoredRatio(); } public int getMaxEnergyStored() { return getController().doGetMaxEnergyStored(); } public int getMaxIO() { return getController().doGetMaxIO(); } public PowerHandler getPowerHandler() { return getController().doGetPowerHandler(); } @Override public PowerReceiver getPowerReceiver(ForgeDirection side) { IoMode mode = getIoMode(side); if(mode == IoMode.DISABLED) { return null; } if(mode == IoMode.PUSH) { return getDisabledPowerHandler().getPowerReceiver(); } return getPowerHandler().getPowerReceiver(); } // RF Power @Override public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { return 0; } @Override public boolean canConnectEnergy(ForgeDirection from) { return getIoMode(from) != IoMode.DISABLED; } @Override public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { IoMode mode = getIoMode(from); if(mode == IoMode.DISABLED || mode == IoMode.PUSH) { return 0; } return getController().doReceiveEnergy(from, maxReceive, simulate); } @Override public int getEnergyStored(ForgeDirection from) { return (int) (getController().doGetEnergyStored(from) * 10); } @Override public int getMaxEnergyStored(ForgeDirection from) { return getController().doGetMaxEnergyStored() * 10; } public int doReceiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { float freeSpace = maxStoredEnergy - storedEnergy; int result = (int) Math.min(maxReceive / 10, freeSpace); if(!simulate) { doAddEnergy(result); } return result * 10; } public float doGetEnergyStored(ForgeDirection from) { return storedEnergy; } public int doGetMaxEnergyStored(ForgeDirection from) { return maxStoredEnergy; } // end rf power public void addEnergy(float add) { getController().doAddEnergy(add); } private boolean isRecievingRedstoneSignal() { if(!redstoneStateDirty) { return isRecievingRedstoneSignal; } isRecievingRedstoneSignal = false; redstoneStateDirty = false; if(!isMultiblock()) { isRecievingRedstoneSignal = worldObj.getStrongestIndirectPower(xCoord, yCoord, zCoord) > 0; } else { for (BlockCoord bc : multiblock) { if(worldObj.getStrongestIndirectPower(bc.x, bc.y, bc.z) > 0) { isRecievingRedstoneSignal = true; break; } } } return isRecievingRedstoneSignal; } public RedstoneControlMode getInputControlMode() { return inputControlMode; } public void setInputControlMode(RedstoneControlMode inputControlMode) { if(!isMultiblock()) { this.inputControlMode = inputControlMode; } else { for (BlockCoord bc : multiblock) { TileCapacitorBank cp = getCapBank(bc); if(cp != null) { cp.inputControlMode = inputControlMode; } } } } public RedstoneControlMode getOutputControlMode() { return outputControlMode; } public void setOutputControlMode(RedstoneControlMode outputControlMode) { if(!isMultiblock()) { this.outputControlMode = outputControlMode; } else { for (BlockCoord bc : multiblock) { TileCapacitorBank cp = getCapBank(bc); if(cp != null) { cp.outputControlMode = outputControlMode; } } } } int doGetMaxIO() { return maxIO; } int doGetMaxEnergyStored() { return maxStoredEnergy; } PowerHandler doGetPowerHandler() { if(inputEnabled) { float space = getMaxEnergyStored() - getEnergyStored(); int canAccept = (int) Math.min(space, maxInput); if(powerHandler == null || canAccept != mjBuf) { mjBuf = canAccept; powerHandler = PowerHandlerUtil.createHandler(new BasicCapacitor(maxInput, mjBuf, maxOutput), this, Type.STORAGE); } return powerHandler; } return getDisabledPowerHandler(); } private PowerHandler getDisabledPowerHandler() { if(disabledPowerHandler == null) { disabledPowerHandler = PowerHandlerUtil.createHandler(new BasicCapacitor(0, 0), this, Type.STORAGE); } return disabledPowerHandler; } int doGetEnergyStoredScaled(int scale) { // NB: called on the client so can't use the power provider return VecmathUtil.clamp(Math.round(scale * (storedEnergy / maxStoredEnergy)), 0, scale); } float doGetEnergyStored() { return storedEnergy; } float doGetEnergyStoredRatio() { return storedEnergy / maxStoredEnergy; } void doAddEnergy(float add) { storedEnergy = Math.max(0, Math.min(maxStoredEnergy, storedEnergy + add)); } void doSetMaxInput(int in) { maxInput = Math.min(in, maxIO); maxInput = Math.max(0, maxInput); if(isMultiblock()) { for (BlockCoord bc : multiblock) { TileCapacitorBank cp = getCapBank(bc); if(cp != null) { cp.maxInput = maxInput; } } } updatePowerHandler(); } void doSetMaxOutput(int out) { maxOutput = Math.min(out, maxIO); maxOutput = Math.max(0, maxOutput); if(isMultiblock()) { for (BlockCoord bc : multiblock) { TileCapacitorBank cp = getCapBank(bc); if(cp != null) { cp.maxOutput = maxOutput; } } } updatePowerHandler(); } @Override public void doWork(PowerHandler workProvider) { } @Override public World getWorld() { return worldObj; } private void updatePowerHandler() { if(storedEnergy > maxStoredEnergy) { storedEnergy = maxStoredEnergy; } else if(storedEnergy < 0) { storedEnergy = 0; } powerHandler = null; } public void onBlockAdded() { multiblockDirty = true; } public void onNeighborBlockChange(Block block) { if(block != EnderIO.blockCapacitorBank) { receptorsDirty = true; getController().masterReceptorsDirty = true; getController().redstoneStateDirty = true; } redstoneStateDirty = true; } public void onBreakBlock() { TileCapacitorBank controller = getController(); controller.clearCurrentMultiblock(); } private void clearCurrentMultiblock() { if(multiblock == null) { return; } for (BlockCoord bc : multiblock) { TileCapacitorBank res = getCapBank(bc); if(res != null) { res.setMultiblock(null); } } multiblock = null; redstoneStateDirty = true; } private void formMultiblock() { List<TileCapacitorBank> blocks = new ArrayList<TileCapacitorBank>(); blocks.add(this); findNighbouringBanks(this, blocks); if(blocks.size() < 2) { return; } for (TileCapacitorBank cb : blocks) { cb.clearCurrentMultiblock(); } BlockCoord[] mb = new BlockCoord[blocks.size()]; for (int i = 0; i < blocks.size(); i++) { mb[i] = new BlockCoord(blocks.get(i)); } for (TileCapacitorBank cb : blocks) { cb.setMultiblock(mb); } } private void findNighbouringBanks(TileCapacitorBank tileCapacitorBank, List<TileCapacitorBank> blocks) { BlockCoord bc = new BlockCoord(tileCapacitorBank); for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { TileCapacitorBank cb = getCapBank(bc.getLocation(dir)); if(cb != null && !blocks.contains(cb)) { blocks.add(cb); findNighbouringBanks(cb, blocks); } } } private void setMultiblock(BlockCoord[] mb) { if(multiblock != null && isMaster()) { // split up current multiblock and reconfigure all the internal capacitors float powerPerBlock = storedEnergy / multiblock.length; for (BlockCoord bc : multiblock) { TileCapacitorBank cb = getCapBank(bc); if(cb != null) { cb.maxStoredEnergy = BASE_CAP.getMaxEnergyStored(); cb.maxIO = BASE_CAP.getMaxEnergyExtracted(); cb.maxInput = cb.maxIO; cb.maxOutput = cb.maxIO; cb.storedEnergy = powerPerBlock; cb.updatePowerHandler(); cb.multiblockDirty = true; } } } multiblock = mb; if(isMaster()) { List<ItemStack> invItems = new ArrayList<ItemStack>(); float totalStored = 0; int totalCap = multiblock.length * BASE_CAP.getMaxEnergyStored(); int totalIO = multiblock.length * BASE_CAP.getMaxEnergyExtracted(); for (BlockCoord bc : multiblock) { TileCapacitorBank cb = getCapBank(bc); if(cb != null) { totalStored += cb.storedEnergy; } ItemStack[] inv = cb.inventory; for (int i = 0; i < inv.length; i++) { if(inv[i] != null) { invItems.add(inv[i]); inv[i] = null; } } cb.multiblockDirty = false; } storedEnergy = totalStored; maxStoredEnergy = totalCap; maxIO = totalIO; maxInput = maxIO; maxOutput = maxIO; for (BlockCoord bc : multiblock) { TileCapacitorBank cb = getCapBank(bc); if(cb != null) { cb.maxIO = totalIO; cb.maxInput = maxIO; cb.maxOutput = maxIO; } } if(invItems.size() > inventory.length) { for (int i = inventory.length; i < invItems.size(); i++) { Util.dropItems(worldObj, invItems.get(i), xCoord, yCoord, zCoord, true); } } for (int i = 0; i < inventory.length && i < invItems.size(); i++) { inventory[i] = invItems.get(i); } updatePowerHandler(); } receptorsDirty = true; getController().masterReceptorsDirty = true; redstoneStateDirty = true; // Forces an update worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); render = true; } public TileCapacitorBank getController() { if(isMaster() || !isMultiblock()) { return this; } TileCapacitorBank res = getCapBank(multiblock[0]); return res != null ? res : this; } boolean isContoller() { return multiblock == null ? true : isMaster(); } boolean isMaster() { if(multiblock != null) { return multiblock[0].equals(xCoord, yCoord, zCoord); } return false; } public boolean isMultiblock() { return multiblock != null; } private boolean isCurrentMultiblockValid() { if(multiblock == null) { return false; } for (BlockCoord bc : multiblock) { TileCapacitorBank res = getCapBank(bc); if(res == null || !res.isMultiblock()) { return false; } } return true; } private TileCapacitorBank getCapBank(BlockCoord bc) { return getCapBank(bc.x, bc.y, bc.z); } private TileCapacitorBank getCapBank(int x, int y, int z) { if(worldObj == null) { return null; } TileEntity te = worldObj.getTileEntity(x, y, z); if(te instanceof TileCapacitorBank) { return (TileCapacitorBank) te; } return null; } @Override public int getSizeInventory() { return getController().doGetSizeInventory(); } @Override public ItemStack getStackInSlot(int i) { return getController().doGetStackInSlot(i); } @Override public ItemStack decrStackSize(int i, int j) { return getController().doDecrStackSize(i, j); } @Override public void setInventorySlotContents(int i, ItemStack itemstack) { getController().doSetInventorySlotContents(i, itemstack); } public ItemStack doGetStackInSlot(int i) { if(i < 0 || i >= inventory.length) { return null; } return inventory[i]; } public int doGetSizeInventory() { return inventory.length; } public ItemStack doDecrStackSize(int fromSlot, int amount) { if(fromSlot < 0 || fromSlot >= inventory.length) { return null; } ItemStack item = inventory[fromSlot]; if(item == null) { return null; } if(item.stackSize <= amount) { ItemStack result = item.copy(); inventory[fromSlot] = null; return result; } item.stackSize -= amount; return item.copy(); } public void doSetInventorySlotContents(int i, ItemStack itemstack) { if(i < 0 || i >= inventory.length) { return; } inventory[i] = itemstack; } @Override public ItemStack getStackInSlotOnClosing(int i) { return null; } @Override public String getInventoryName() { return EnderIO.blockCapacitorBank.getUnlocalizedName() + ".name"; } @Override public int getInventoryStackLimit() { return 1; } @Override public boolean isUseableByPlayer(EntityPlayer entityplayer) { return true; } @Override public void openInventory() { } @Override public void closeInventory() { } @Override public boolean isItemValidForSlot(int i, ItemStack itemstack) { if(itemstack == null) { return false; } return itemstack.getItem() instanceof IChargeableItem || itemstack.getItem() instanceof IEnergyContainerItem; } @Override public void readCustomNBT(NBTTagCompound nbtRoot) { float oldEnergy = storedEnergy; storedEnergy = nbtRoot.getFloat("storedEnergy"); maxStoredEnergy = nbtRoot.getInteger("maxStoredEnergy"); float newEnergy = storedEnergy; if(maxStoredEnergy != 0 && Math.abs(oldEnergy - newEnergy) / maxStoredEnergy > 0.05 || nbtRoot.hasKey("render")) { render = true; } if(energyAtLastRender != -1 && maxStoredEnergy != 0) { float change = Math.abs(energyAtLastRender - storedEnergy) / maxStoredEnergy; if(change > 0.05) { render = true; } } maxIO = nbtRoot.getInteger("maxIO"); if(nbtRoot.hasKey("maxInput")) { maxInput = nbtRoot.getInteger("maxInput"); maxOutput = nbtRoot.getInteger("maxOutput"); } else { maxInput = maxIO; maxOutput = maxIO; } inputControlMode = RedstoneControlMode.values()[nbtRoot.getShort("inputControlMode")]; outputControlMode = RedstoneControlMode.values()[nbtRoot.getShort("outputControlMode")]; updatePowerHandler(); boolean wasMulti = isMultiblock(); if(nbtRoot.getBoolean("isMultiblock")) { int[] coords = nbtRoot.getIntArray("multiblock"); multiblock = new BlockCoord[coords.length / 3]; int c = 0; for (int i = 0; i < multiblock.length; i++) { multiblock[i] = new BlockCoord(coords[c++], coords[c++], coords[c++]); } } else { multiblock = null; } for (int i = 0; i < inventory.length; i++) { inventory[i] = null; } NBTTagList itemList = (NBTTagList) nbtRoot.getTag("Items"); for (int i = 0; i < itemList.tagCount(); i++) { NBTTagCompound itemStack = itemList.getCompoundTagAt(i); byte slot = itemStack.getByte("Slot"); if(slot >= 0 && slot < inventory.length) { inventory[slot] = ItemStack.loadItemStackFromNBT(itemStack); } } if(nbtRoot.hasKey("hasFaces")) { for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { if(nbtRoot.hasKey("face" + dir.ordinal())) { setIoMode(dir, IoMode.values()[nbtRoot.getShort("face" + dir.ordinal())], false); } } } gaugeBounds = null; } @Override public void writeCustomNBT(NBTTagCompound nbtRoot) { nbtRoot.setFloat("storedEnergy", storedEnergy); nbtRoot.setInteger("maxStoredEnergy", maxStoredEnergy); nbtRoot.setInteger("maxIO", maxIO); nbtRoot.setInteger("maxInput", maxInput); nbtRoot.setInteger("maxOutput", maxOutput); nbtRoot.setShort("inputControlMode", (short) inputControlMode.ordinal()); nbtRoot.setShort("outputControlMode", (short) outputControlMode.ordinal()); nbtRoot.setBoolean("isMultiblock", isMultiblock()); if(isMultiblock()) { int[] vals = new int[multiblock.length * 3]; int i = 0; for (BlockCoord bc : multiblock) { vals[i++] = bc.x; vals[i++] = bc.y; vals[i++] = bc.z; } nbtRoot.setIntArray("multiblock", vals); } // write inventory list NBTTagList itemList = new NBTTagList(); for (int i = 0; i < inventory.length; i++) { if(inventory[i] != null) { NBTTagCompound itemStackNBT = new NBTTagCompound(); itemStackNBT.setByte("Slot", (byte) i); inventory[i].writeToNBT(itemStackNBT); itemList.appendTag(itemStackNBT); } } nbtRoot.setTag("Items", itemList); //face modes if(faceModes != null) { nbtRoot.setByte("hasFaces", (byte) 1); for (Entry<ForgeDirection, IoMode> e : faceModes.entrySet()) { nbtRoot.setShort("face" + e.getKey().ordinal(), (short) e.getValue().ordinal()); } } if(render) { nbtRoot.setBoolean("render", true); render = false; } } static class Receptor { IPowerInterface receptor; ForgeDirection fromDir; IoMode mode; private Receptor(IPowerInterface rec, ForgeDirection fromDir, IoMode mode) { this.receptor = rec; this.fromDir = fromDir; this.mode = mode; } @Override public String toString() { return "Receptor [receptor=" + receptor + ", fromDir=" + fromDir + ", mode=" + mode + "]"; } } @Override public boolean hasCustomInventoryName() { // TODO Auto-generated method stub return false; } }
package de.uni_potsdam.hpi.bpt.bp2014.jcore; import com.google.gson.Gson; import de.uni_potsdam.hpi.bpt.bp2014.database.DbActivityInstance; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.HashMap; import java.util.LinkedList; @Path( "Scenario" ) public class RestConnection { private ExecutionService executionService = new ExecutionService(); private HistoryService historyService = new HistoryService(); @GET @Path("{Scenarioname}/{Instance}/{Status}") @Produces(MediaType.APPLICATION_JSON) public Response showEnabledActivities( @PathParam("Scenarioname") int scenarioID, @PathParam("Instance") int scenarioInstanceID, @PathParam("Status") String status ){ if (status.equals("enabled")) { if (!executionService.openExistingScenarioInstance(new Integer(scenarioID), new Integer(scenarioInstanceID))){ return Response.serverError().entity("Error: not a correct scenario instance").build(); } LinkedList<Integer> enabledActivitiesIDs = executionService.getEnabledActivitiesIDsForScenarioInstance(scenarioInstanceID); HashMap<Integer, String> labels = executionService.getEnabledActivityLabelsForScenarioInstance(scenarioInstanceID); if(enabledActivitiesIDs.size() == 0) return Response.serverError().entity("Error: empty").build(); Gson gson = new Gson(); JsonHashMapIntegerString json = new JsonHashMapIntegerString(enabledActivitiesIDs, labels); String jsonRepresentation = gson.toJson(json); return Response.ok(jsonRepresentation, MediaType.APPLICATION_JSON).build(); }else if(status.equals("terminated")){ if(!executionService.existScenarioInstance(scenarioID,scenarioInstanceID)) return Response.serverError().entity("Error: not a correct scenario instance").build(); LinkedList<Integer> terminatedActivities = historyService.getTerminatedActivitysForScenarioInstance(scenarioInstanceID); HashMap<Integer, String> labels = historyService.getTerminatedActivityLabelsForScenarioInstance(scenarioInstanceID); if(terminatedActivities.size() == 0) return Response.serverError().entity("Error: empty").build(); Gson gson = new Gson(); JsonHashMapIntegerString json = new JsonHashMapIntegerString(terminatedActivities, labels); String jsonRepresentation = gson.toJson(json); return Response.ok(jsonRepresentation,MediaType.APPLICATION_JSON).build(); } return Response.serverError().entity("Error: status not clear").build(); } @GET @Path("DataObjects/{Scenarioname}/{Instance}") @Produces(MediaType.APPLICATION_JSON) public Response showDataObjects( @PathParam("Scenarioname") int scenarioID, @PathParam("Instance") int scenarioInstanceID, @PathParam("Status") String status ){ if (!executionService.openExistingScenarioInstance(new Integer(scenarioID), new Integer(scenarioInstanceID))) return Response.serverError().entity("Error: not a correct scenario instance").build(); LinkedList<Integer> dataObjects = executionService.getAllDataObjectIDs(scenarioInstanceID); HashMap<Integer, String> labels = executionService.getAllDataObjectStates(scenarioInstanceID); if(dataObjects.size() == 0) return Response.serverError().entity("Error: empty").build(); Gson gson = new Gson(); JsonHashMapIntegerString json = new JsonHashMapIntegerString(dataObjects, labels); String jsonRepresentation = gson.toJson(json); return Response.ok(jsonRepresentation,MediaType.APPLICATION_JSON).build(); } @GET @Path("Show") @Produces(MediaType.APPLICATION_JSON) public Response showScenarios(){ LinkedList<Integer> scenarioIDs = executionService.getAllScenarioIDs(); if(scenarioIDs.size() == 0) return Response.serverError().entity("Error: empty").build(); Gson gson = new Gson(); JsonIntegerList json = new JsonIntegerList(scenarioIDs); String jsonRepresentation = gson.toJson(json); return Response.ok(jsonRepresentation,MediaType.APPLICATION_JSON).build(); } @GET @Path("Get/ScenarioID/{ScenarioInstance}") @Produces(MediaType.APPLICATION_JSON) public Response getScenarioID(@PathParam("ScenarioInstance") int scenarioInstanceID){ if(!executionService.existScenarioInstance(scenarioInstanceID)) return Response.serverError().entity("Error: not a correct scenario instance").build(); int scenarioID = executionService.getScenarioIDForScenarioInstance(scenarioInstanceID); Gson gson = new Gson(); JsonInteger json = new JsonInteger(scenarioID); String jsonRepresentation = gson.toJson(json); return Response.ok(jsonRepresentation,MediaType.APPLICATION_JSON).build(); } @GET @Path("Instances/{Instance}") @Produces(MediaType.APPLICATION_JSON) public Response showScenarioInstances(@PathParam("Instance") int scenarioID){ if(!executionService.existScenario(scenarioID)) return Response.serverError().entity("Error: not a correct scenario").build(); LinkedList<Integer> scenarioIDs = executionService.listAllScenarioInstancesForScenario(scenarioID); if(scenarioIDs.size() == 0) return Response.serverError().entity("Error: empty").build(); Gson gson = new Gson(); JsonIntegerList json = new JsonIntegerList(scenarioIDs); String jsonRepresentation = gson.toJson(json); return Response.ok(jsonRepresentation,MediaType.APPLICATION_JSON).build(); } @POST @Path("{Scenarioname}/{Instance}/{Activity}/{Status}/{Comment}") public Boolean doActivity( @PathParam("Scenarioname") String scenarioID, @PathParam("Instance") int scenarioInstanceID, @PathParam("Activity") int activityInstanceID, @PathParam("Status") String status, @PathParam("Comment") String comment ){ executionService.openExistingScenarioInstance(new Integer(scenarioID),new Integer(scenarioInstanceID)); if (status.equals("begin")) { executionService.beginActivity(scenarioInstanceID, activityInstanceID); }else if(status.equals("terminate")) { executionService.terminateActivity(scenarioInstanceID, activityInstanceID); } return true; } @POST @Path("Start/{Scenarioname}") public int startNewActivity( @PathParam("Scenarioname") int scenarioID){ if(executionService.existScenario(scenarioID)) { return executionService.startNewScenarioInstance(scenarioID); }else{ return -1; } } class JsonHashMapIntegerString{ private LinkedList<Integer> ids; private HashMap<Integer, String> label; public JsonHashMapIntegerString(LinkedList<Integer> ids, HashMap<Integer, String> labels){ this.ids = ids; this.label = labels; } } class JsonIntegerList{ private LinkedList<Integer> ids; public JsonIntegerList(LinkedList<Integer> ids){ this.ids = ids; } } class JsonInteger{ private Integer id; public JsonInteger(Integer id){ this.id = id; } } }
package org.chromium.chrome.browser.contextualsearch; import android.util.Pair; import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.browser.compositor.bottombar.contextualsearch.ContextualSearchPanel.PanelState; import org.chromium.chrome.browser.compositor.bottombar.contextualsearch.ContextualSearchPanel.StateChangeReason; import org.chromium.chrome.browser.preferences.PrefServiceBridge; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Centralizes UMA data collection for Contextual Search. All calls must be made from the UI thread. */ public class ContextualSearchUma { // An invalid value for the number of taps remaining for the promo. Must be negative. private static final int PROMO_TAPS_REMAINING_INVALID = -1; // Constants to use for the original selection gesture private static final boolean LONG_PRESS = false; private static final boolean TAP = true; // Constants used to log UMA "enum" histograms about the Contextual Search's preference state. private static final int PREFERENCE_UNINITIALIZED = 0; private static final int PREFERENCE_ENABLED = 1; private static final int PREFERENCE_DISABLED = 2; private static final int PREFERENCE_HISTOGRAM_BOUNDARY = 3; // Constants used to log UMA "enum" histograms about whether search results were seen. private static final int RESULTS_SEEN = 0; private static final int RESULTS_NOT_SEEN = 1; private static final int RESULTS_SEEN_BOUNDARY = 2; // Constants used to log UMA "enum" histograms about whether the selection is valid. private static final int SELECTION_VALID = 0; private static final int SELECTION_INVALID = 1; private static final int SELECTION_BOUNDARY = 2; // Constants used to log UMA "enum" histograms about a request's outcome. private static final int REQUEST_NOT_FAILED = 0; private static final int REQUEST_FAILED = 1; private static final int REQUEST_BOUNDARY = 2; // Constants used to log UMA "enum" histograms about the panel's state transitions. // Entry code: first entry into CLOSED. private static final int ENTER_CLOSED_FROM_OTHER = 0; private static final int ENTER_CLOSED_FROM_PEEKED_BACK_PRESS = 1; private static final int ENTER_CLOSED_FROM_PEEKED_BASE_PAGE_SCROLL = 2; private static final int ENTER_CLOSED_FROM_PEEKED_TEXT_SELECT_TAP = 3; private static final int ENTER_CLOSED_FROM_EXPANDED_BACK_PRESS = 4; private static final int ENTER_CLOSED_FROM_EXPANDED_BASE_PAGE_TAP = 5; private static final int ENTER_CLOSED_FROM_EXPANDED_FLING = 6; private static final int ENTER_CLOSED_FROM_MAXIMIZED_BACK_PRESS = 7; private static final int ENTER_CLOSED_FROM_MAXIMIZED_FLING = 8; private static final int ENTER_CLOSED_FROM_MAXIMIZED_TAB_PROMOTION = 9; private static final int ENTER_CLOSED_FROM_MAXIMIZED_SERP_NAVIGATION = 10; private static final int ENTER_CLOSED_FROM_BOUNDARY = 11; // Entry code: first entry into PEEKED. private static final int ENTER_PEEKED_FROM_OTHER = 0; private static final int ENTER_PEEKED_FROM_CLOSED_TEXT_SELECT_TAP = 1; private static final int ENTER_PEEKED_FROM_CLOSED_EXT_SELECT_LONG_PRESS = 2; private static final int ENTER_PEEKED_FROM_PEEKED_TEXT_SELECT_TAP = 3; private static final int ENTER_PEEKED_FROM_PEEKED_TEXT_SELECT_LONG_PRESS = 4; private static final int ENTER_PEEKED_FROM_EXPANDED_SEARCH_BAR_TAP = 5; private static final int ENTER_PEEKED_FROM_EXPANDED_SWIPE = 6; private static final int ENTER_PEEKED_FROM_EXPANDED_FLING = 7; private static final int ENTER_PEEKED_FROM_MAXIMIZED_SWIPE = 8; private static final int ENTER_PEEKED_FROM_MAXIMIZED_FLING = 9; private static final int ENTER_PEEKED_FROM_BOUNDARY = 10; // Entry code: first entry into EXPANDED. private static final int ENTER_EXPANDED_FROM_OTHER = 0; private static final int ENTER_EXPANDED_FROM_PEEKED_SEARCH_BAR_TAP = 1; private static final int ENTER_EXPANDED_FROM_PEEKED_SWIPE = 2; private static final int ENTER_EXPANDED_FROM_PEEKED_FLING = 3; private static final int ENTER_EXPANDED_FROM_MAXIMIZED_SWIPE = 4; private static final int ENTER_EXPANDED_FROM_MAXIMIZED_FLING = 5; private static final int ENTER_EXPANDED_FROM_BOUNDARY = 6; // Entry code: first entry into MAXIMIZED. private static final int ENTER_MAXIMIZED_FROM_OTHER = 0; private static final int ENTER_MAXIMIZED_FROM_PEEKED_SWIPE = 1; private static final int ENTER_MAXIMIZED_FROM_PEEKED_FLING = 2; private static final int ENTER_MAXIMIZED_FROM_EXPANDED_SWIPE = 3; private static final int ENTER_MAXIMIZED_FROM_EXPANDED_FLING = 4; private static final int ENTER_MAXIMIZED_FROM_EXPANDED_SERP_NAVIGATION = 5; private static final int ENTER_MAXIMIZED_FROM_BOUNDARY = 6; // Exit code: first exit from CLOSED (or UNDEFINED). private static final int EXIT_CLOSED_TO_OTHER = 0; private static final int EXIT_CLOSED_TO_PEEKED_TEXT_SELECT_TAP = 1; private static final int EXIT_CLOSED_TO_PEEKED_TEXT_SELECT_LONG_PRESS = 2; private static final int EXIT_CLOSED_TO_BOUNDARY = 3; // Exit code: first exit from PEEKED. private static final int EXIT_PEEKED_TO_OTHER = 0; private static final int EXIT_PEEKED_TO_CLOSED_BACK_PRESS = 1; private static final int EXIT_PEEKED_TO_CLOSED_BASE_PAGE_SCROLL = 2; private static final int EXIT_PEEKED_TO_CLOSED_TEXT_SELECT_TAP = 3; private static final int EXIT_PEEKED_TO_PEEKED_TEXT_SELECT_TAP = 4; private static final int EXIT_PEEKED_TO_PEEKED_TEXT_SELECT_LONG_PRESS = 5; private static final int EXIT_PEEKED_TO_EXPANDED_SEARCH_BAR_TAP = 6; private static final int EXIT_PEEKED_TO_EXPANDED_SWIPE = 7; private static final int EXIT_PEEKED_TO_EXPANDED_FLING = 8; private static final int EXIT_PEEKED_TO_MAXIMIZED_SWIPE = 9; private static final int EXIT_PEEKED_TO_MAXIMIZED_FLING = 10; private static final int EXIT_PEEKED_TO_BOUNDARY = 11; // Exit code: first exit from EXPANDED. private static final int EXIT_EXPANDED_TO_OTHER = 0; private static final int EXIT_EXPANDED_TO_CLOSED_BACK_PRESS = 1; private static final int EXIT_EXPANDED_TO_CLOSED_BASE_PAGE_TAP = 2; private static final int EXIT_EXPANDED_TO_CLOSED_FLING = 3; private static final int EXIT_EXPANDED_TO_PEEKED_SEARCH_BAR_TAP = 4; private static final int EXIT_EXPANDED_TO_PEEKED_SWIPE = 5; private static final int EXIT_EXPANDED_TO_PEEKED_FLING = 6; private static final int EXIT_EXPANDED_TO_MAXIMIZED_SWIPE = 7; private static final int EXIT_EXPANDED_TO_MAXIMIZED_FLING = 8; private static final int EXIT_EXPANDED_TO_MAXIMIZED_SERP_NAVIGATION = 9; private static final int EXIT_EXPANDED_TO_BOUNDARY = 10; // Exit code: first exit from MAXIMIZED. private static final int EXIT_MAXIMIZED_TO_OTHER = 0; private static final int EXIT_MAXIMIZED_TO_CLOSED_BACK_PRESS = 1; private static final int EXIT_MAXIMIZED_TO_CLOSED_FLING = 2; private static final int EXIT_MAXIMIZED_TO_CLOSED_TAB_PROMOTION = 3; private static final int EXIT_MAXIMIZED_TO_CLOSED_SERP_NAVIGATION = 4; private static final int EXIT_MAXIMIZED_TO_PEEKED_SWIPE = 5; private static final int EXIT_MAXIMIZED_TO_PEEKED_FLING = 6; private static final int EXIT_MAXIMIZED_TO_EXPANDED_SWIPE = 7; private static final int EXIT_MAXIMIZED_TO_EXPANDED_FLING = 8; private static final int EXIT_MAXIMIZED_TO_BOUNDARY = 9; // Constants used to log UMA "enum" histograms with details about whether search results // were seen, and what the original triggering gesture was. private static final int RESULTS_SEEN_FROM_TAP = 0; private static final int RESULTS_NOT_SEEN_FROM_TAP = 1; private static final int RESULTS_SEEN_FROM_LONG_PRESS = 2; private static final int RESULTS_NOT_SEEN_FROM_LONG_PRESS = 3; private static final int RESULTS_BY_GESTURE_BOUNDARY = 4; // Constants used to log UMA "enum" histograms with details about whether search results // were seen, and what the original triggering gesture was. private static final int PROMO_ENABLED_FROM_TAP = 0; private static final int PROMO_DISABLED_FROM_TAP = 1; private static final int PROMO_UNDECIDED_FROM_TAP = 2; private static final int PROMO_ENABLED_FROM_LONG_PRESS = 3; private static final int PROMO_DISABLED_FROM_LONG_PRESS = 4; private static final int PROMO_UNDECIDED_FROM_LONG_PRESS = 5; private static final int PROMO_BY_GESTURE_BOUNDARY = 6; // Constants used to log UMA "enum" histograms with summary counts for SERP loading times. private static final int PREFETCHED_PARIALLY_LOADED = 0; private static final int PREFETCHED_FULLY_LOADED = 1; private static final int NOT_PREFETCHED = 2; private static final int PREFETCH_BOUNDARY = 3; // Constants used to log UMA "enum" histograms for HTTP / HTTPS. private static final int PROTOCOL_IS_HTTP = 0; private static final int PROTOCOL_NOT_HTTP = 1; private static final int PROTOCOL_BOUNDARY = 2; // Constants used to log UMA "enum" histograms for single / multi-word. private static final int RESOLVED_SINGLE_WORD = 0; private static final int RESOLVED_MULTI_WORD = 1; private static final int RESOLVED_BOUNDARY = 2; /** * Key used in maps from {state, reason} to state entry (exit) logging code. */ static class StateChangeKey { final PanelState mState; final StateChangeReason mReason; final int mHashCode; StateChangeKey(PanelState state, StateChangeReason reason) { mState = state; mReason = reason; mHashCode = 31 * state.hashCode() + reason.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof StateChangeKey)) { return false; } if (obj == this) { return true; } StateChangeKey other = (StateChangeKey) obj; return mState.equals(other.mState) && mReason.equals(other.mReason); } @Override public int hashCode() { return mHashCode; } } // TODO(donnd): switch from using Maps to some method that does not require creation of a key. // Entry code map: first entry into CLOSED. private static final Map<StateChangeKey, Integer> ENTER_CLOSED_STATE_CHANGE_CODES; static { Map<StateChangeKey, Integer> codes = new HashMap<StateChangeKey, Integer>(); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.BACK_PRESS), ENTER_CLOSED_FROM_PEEKED_BACK_PRESS); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.BASE_PAGE_SCROLL), ENTER_CLOSED_FROM_PEEKED_BASE_PAGE_SCROLL); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.TEXT_SELECT_TAP), ENTER_CLOSED_FROM_PEEKED_TEXT_SELECT_TAP); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.BACK_PRESS), ENTER_CLOSED_FROM_EXPANDED_BACK_PRESS); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.BASE_PAGE_TAP), ENTER_CLOSED_FROM_EXPANDED_BASE_PAGE_TAP); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.FLING), ENTER_CLOSED_FROM_EXPANDED_FLING); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.BACK_PRESS), ENTER_CLOSED_FROM_MAXIMIZED_BACK_PRESS); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.FLING), ENTER_CLOSED_FROM_MAXIMIZED_FLING); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.TAB_PROMOTION), ENTER_CLOSED_FROM_MAXIMIZED_TAB_PROMOTION); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.SERP_NAVIGATION), ENTER_CLOSED_FROM_MAXIMIZED_SERP_NAVIGATION); ENTER_CLOSED_STATE_CHANGE_CODES = Collections.unmodifiableMap(codes); } // Entry code map: first entry into PEEKED. private static final Map<StateChangeKey, Integer> ENTER_PEEKED_STATE_CHANGE_CODES; static { Map<StateChangeKey, Integer> codes = new HashMap<StateChangeKey, Integer>(); // Note: we don't distinguish entering PEEKED from UNDEFINED / CLOSED. codes.put(new StateChangeKey(PanelState.UNDEFINED, StateChangeReason.TEXT_SELECT_TAP), ENTER_PEEKED_FROM_CLOSED_TEXT_SELECT_TAP); codes.put(new StateChangeKey(PanelState.UNDEFINED, StateChangeReason.TEXT_SELECT_LONG_PRESS), ENTER_PEEKED_FROM_CLOSED_EXT_SELECT_LONG_PRESS); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.TEXT_SELECT_TAP), ENTER_PEEKED_FROM_CLOSED_TEXT_SELECT_TAP); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.TEXT_SELECT_LONG_PRESS), ENTER_PEEKED_FROM_CLOSED_EXT_SELECT_LONG_PRESS); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.TEXT_SELECT_TAP), ENTER_PEEKED_FROM_PEEKED_TEXT_SELECT_TAP); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.TEXT_SELECT_LONG_PRESS), ENTER_PEEKED_FROM_PEEKED_TEXT_SELECT_LONG_PRESS); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.SEARCH_BAR_TAP), ENTER_PEEKED_FROM_EXPANDED_SEARCH_BAR_TAP); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.SWIPE), ENTER_PEEKED_FROM_EXPANDED_SWIPE); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.FLING), ENTER_PEEKED_FROM_EXPANDED_FLING); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.SWIPE), ENTER_PEEKED_FROM_MAXIMIZED_SWIPE); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.FLING), ENTER_PEEKED_FROM_MAXIMIZED_FLING); ENTER_PEEKED_STATE_CHANGE_CODES = Collections.unmodifiableMap(codes); } // Entry code map: first entry into EXPANDED. private static final Map<StateChangeKey, Integer> ENTER_EXPANDED_STATE_CHANGE_CODES; static { Map<StateChangeKey, Integer> codes = new HashMap<StateChangeKey, Integer>(); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.SEARCH_BAR_TAP), ENTER_EXPANDED_FROM_PEEKED_SEARCH_BAR_TAP); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.SWIPE), ENTER_EXPANDED_FROM_PEEKED_SWIPE); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.FLING), ENTER_EXPANDED_FROM_PEEKED_FLING); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.SWIPE), ENTER_EXPANDED_FROM_MAXIMIZED_SWIPE); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.FLING), ENTER_EXPANDED_FROM_MAXIMIZED_FLING); ENTER_EXPANDED_STATE_CHANGE_CODES = Collections.unmodifiableMap(codes); } // Entry code map: first entry into MAXIMIZED. private static final Map<StateChangeKey, Integer> ENTER_MAXIMIZED_STATE_CHANGE_CODES; static { Map<StateChangeKey, Integer> codes = new HashMap<StateChangeKey, Integer>(); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.SWIPE), ENTER_MAXIMIZED_FROM_PEEKED_SWIPE); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.FLING), ENTER_MAXIMIZED_FROM_PEEKED_FLING); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.SWIPE), ENTER_MAXIMIZED_FROM_EXPANDED_SWIPE); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.FLING), ENTER_MAXIMIZED_FROM_EXPANDED_FLING); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.SERP_NAVIGATION), ENTER_MAXIMIZED_FROM_EXPANDED_SERP_NAVIGATION); ENTER_MAXIMIZED_STATE_CHANGE_CODES = Collections.unmodifiableMap(codes); } // Exit code map: first exit from CLOSED. private static final Map<StateChangeKey, Integer> EXIT_CLOSED_TO_STATE_CHANGE_CODES; static { Map<StateChangeKey, Integer> codes = new HashMap<StateChangeKey, Integer>(); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.TEXT_SELECT_TAP), EXIT_CLOSED_TO_PEEKED_TEXT_SELECT_TAP); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.TEXT_SELECT_LONG_PRESS), EXIT_CLOSED_TO_PEEKED_TEXT_SELECT_LONG_PRESS); EXIT_CLOSED_TO_STATE_CHANGE_CODES = Collections.unmodifiableMap(codes); } // Exit code map: first exit from PEEKED. private static final Map<StateChangeKey, Integer> EXIT_PEEKED_TO_STATE_CHANGE_CODES; static { Map<StateChangeKey, Integer> codes = new HashMap<StateChangeKey, Integer>(); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.BACK_PRESS), EXIT_PEEKED_TO_CLOSED_BACK_PRESS); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.BASE_PAGE_SCROLL), EXIT_PEEKED_TO_CLOSED_BASE_PAGE_SCROLL); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.BASE_PAGE_TAP), EXIT_PEEKED_TO_CLOSED_TEXT_SELECT_TAP); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.TEXT_SELECT_TAP), EXIT_PEEKED_TO_PEEKED_TEXT_SELECT_TAP); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.TEXT_SELECT_LONG_PRESS), EXIT_PEEKED_TO_PEEKED_TEXT_SELECT_LONG_PRESS); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.SEARCH_BAR_TAP), EXIT_PEEKED_TO_EXPANDED_SEARCH_BAR_TAP); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.SWIPE), EXIT_PEEKED_TO_EXPANDED_SWIPE); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.FLING), EXIT_PEEKED_TO_EXPANDED_FLING); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.SWIPE), EXIT_PEEKED_TO_MAXIMIZED_SWIPE); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.FLING), EXIT_PEEKED_TO_MAXIMIZED_FLING); EXIT_PEEKED_TO_STATE_CHANGE_CODES = Collections.unmodifiableMap(codes); } // Exit code map: first exit from EXPANDED. private static final Map<StateChangeKey, Integer> EXIT_EXPANDED_TO_STATE_CHANGE_CODES; static { Map<StateChangeKey, Integer> codes = new HashMap<StateChangeKey, Integer>(); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.BACK_PRESS), EXIT_EXPANDED_TO_CLOSED_BACK_PRESS); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.BASE_PAGE_TAP), EXIT_EXPANDED_TO_CLOSED_BASE_PAGE_TAP); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.FLING), EXIT_EXPANDED_TO_CLOSED_FLING); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.SEARCH_BAR_TAP), EXIT_EXPANDED_TO_PEEKED_SEARCH_BAR_TAP); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.SWIPE), EXIT_EXPANDED_TO_PEEKED_SWIPE); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.FLING), EXIT_EXPANDED_TO_PEEKED_FLING); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.SWIPE), EXIT_EXPANDED_TO_MAXIMIZED_SWIPE); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.FLING), EXIT_EXPANDED_TO_MAXIMIZED_FLING); codes.put(new StateChangeKey(PanelState.MAXIMIZED, StateChangeReason.SERP_NAVIGATION), EXIT_EXPANDED_TO_MAXIMIZED_SERP_NAVIGATION); EXIT_EXPANDED_TO_STATE_CHANGE_CODES = Collections.unmodifiableMap(codes); } // Exit code map: first exit from MAXIMIZED. private static final Map<StateChangeKey, Integer> EXIT_MAXIMIZED_TO_STATE_CHANGE_CODES; static { Map<StateChangeKey, Integer> codes = new HashMap<StateChangeKey, Integer>(); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.BACK_PRESS), EXIT_MAXIMIZED_TO_CLOSED_BACK_PRESS); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.FLING), EXIT_MAXIMIZED_TO_CLOSED_FLING); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.TAB_PROMOTION), EXIT_MAXIMIZED_TO_CLOSED_TAB_PROMOTION); codes.put(new StateChangeKey(PanelState.CLOSED, StateChangeReason.SERP_NAVIGATION), EXIT_MAXIMIZED_TO_CLOSED_SERP_NAVIGATION); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.SWIPE), EXIT_MAXIMIZED_TO_PEEKED_SWIPE); codes.put(new StateChangeKey(PanelState.PEEKED, StateChangeReason.FLING), EXIT_MAXIMIZED_TO_PEEKED_FLING); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.SWIPE), EXIT_MAXIMIZED_TO_EXPANDED_SWIPE); codes.put(new StateChangeKey(PanelState.EXPANDED, StateChangeReason.FLING), EXIT_MAXIMIZED_TO_EXPANDED_FLING); EXIT_MAXIMIZED_TO_STATE_CHANGE_CODES = Collections.unmodifiableMap(codes); } // "Seen by gesture" code map: logged on first exit from expanded panel, or promo, // broken down by gesture. private static final Map<Pair<Boolean, Boolean>, Integer> SEEN_BY_GESTURE_CODES; static { final boolean unseen = false; final boolean seen = true; Map<Pair<Boolean, Boolean>, Integer> codes = new HashMap<Pair<Boolean, Boolean>, Integer>(); codes.put(new Pair<Boolean, Boolean>(seen, TAP), RESULTS_SEEN_FROM_TAP); codes.put(new Pair<Boolean, Boolean>(unseen, TAP), RESULTS_NOT_SEEN_FROM_TAP); codes.put(new Pair<Boolean, Boolean>(seen, LONG_PRESS), RESULTS_SEEN_FROM_LONG_PRESS); codes.put(new Pair<Boolean, Boolean>(unseen, LONG_PRESS), RESULTS_NOT_SEEN_FROM_LONG_PRESS); SEEN_BY_GESTURE_CODES = Collections.unmodifiableMap(codes); } // "Promo outcome by gesture" code map: logged on exit from promo, broken down by gesture. private static final Map<Pair<Integer, Boolean>, Integer> PROMO_BY_GESTURE_CODES; static { Map<Pair<Integer, Boolean>, Integer> codes = new HashMap<Pair<Integer, Boolean>, Integer>(); codes.put(new Pair<Integer, Boolean>(PREFERENCE_ENABLED, TAP), PROMO_ENABLED_FROM_TAP); codes.put(new Pair<Integer, Boolean>(PREFERENCE_DISABLED, TAP), PROMO_DISABLED_FROM_TAP); codes.put(new Pair<Integer, Boolean>(PREFERENCE_UNINITIALIZED, TAP), PROMO_UNDECIDED_FROM_TAP); codes.put(new Pair<Integer, Boolean>(PREFERENCE_ENABLED, LONG_PRESS), PROMO_ENABLED_FROM_LONG_PRESS); codes.put(new Pair<Integer, Boolean>(PREFERENCE_DISABLED, LONG_PRESS), PROMO_DISABLED_FROM_LONG_PRESS); codes.put(new Pair<Integer, Boolean>(PREFERENCE_UNINITIALIZED, LONG_PRESS), PROMO_UNDECIDED_FROM_LONG_PRESS); PROMO_BY_GESTURE_CODES = Collections.unmodifiableMap(codes); } /** * Logs the state of the Contextual Search preference. This function should be called if the * Contextual Search feature is active, and will track the different preference settings * (disabled, enabled or uninitialized). Calling more than once is fine. */ public static void logPreferenceState() { RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchPreferenceState", getPreferenceValue(), PREFERENCE_HISTOGRAM_BOUNDARY); } /** * Logs the state of the Contextual Search preference. This function should be called if the * Contextual Search feature is active, and will track the different preference settings * (disabled, enabled or uninitialized). Calling more than once is fine. * @param promoTapsRemaining The number of taps remaining, or -1 if not applicable. */ @Deprecated public static void logPreferenceState(int promoTapsRemaining) { RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchPreferenceState", getPreferenceValue(), PREFERENCE_HISTOGRAM_BOUNDARY); if (promoTapsRemaining != PROMO_TAPS_REMAINING_INVALID) { RecordHistogram.recordCountHistogram("Search.ContextualSearchPromoTapsRemaining", promoTapsRemaining); } } /** * Logs the given number of promo taps remaining. Should be called only for users that * are still undecided. * @param promoTapsRemaining The number of taps remaining (should not be negative). */ public static void logPromoTapsRemaining(int promoTapsRemaining) { if (promoTapsRemaining >= 0) { RecordHistogram.recordCountHistogram("Search.ContextualSearchPromoTapsRemaining", promoTapsRemaining); } } /** * Logs the historic number of times that a Tap gesture triggered the peeking promo * for users that have never opened the panel. This should be called periodically for * undecided users only. * @param promoTaps The historic number of taps that have caused the peeking bar for the promo, * for users that have never opened the panel. */ public static void logPromoTapsForNeverOpened(int promoTaps) { RecordHistogram.recordCountHistogram("Search.ContextualSearchPromoTapsForNeverOpened", promoTaps); } /** * Logs the historic number of times that a Tap gesture triggered the peeking promo before * the user ever opened the panel. This should be called periodically for all users. * @param promoTaps The historic number of taps that have caused the peeking bar for the promo * before the first open of the panel, for all users that have ever opened the panel. */ public static void logPromoTapsBeforeFirstOpen(int promoTaps) { RecordHistogram.recordCountHistogram("Search.ContextualSearchPromosTapsBeforeFirstOpen", promoTaps); } /** * Records the total count of times the promo panel has *ever* been opened. This should only * be called when the user is still undecided. * @param count The total historic count of times the panel has ever been opened for the * current user. */ public static void logPromoOpenCount(int count) { RecordHistogram.recordCountHistogram("Search.ContextualSearchPromoOpenCount", count); } /** * Logs the number of taps that have been counted since the user last opened the panel, for * undecided users. * @param tapsSinceOpen The number of taps to log. */ public static void logTapsSinceOpenForUndecided(int tapsSinceOpen) { RecordHistogram.recordCountHistogram("Search.ContextualSearchTapsSinceOpenUndecided", tapsSinceOpen); } /** * Logs the number of taps that have been counted since the user last opened the panel, for * decided users. * @param tapsSinceOpen The number of taps to log. */ public static void logTapsSinceOpenForDecided(int tapsSinceOpen) { RecordHistogram.recordCountHistogram("Search.ContextualSearchTapsSinceOpenDecided", tapsSinceOpen); } /** * Logs whether the Search Term was single or multiword. * @param isSingleWord Whether the resolved search term is a single word or not. */ public static void logSearchTermResolvedWords(boolean isSingleWord) { RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchResolvedTermWords", isSingleWord ? RESOLVED_SINGLE_WORD : RESOLVED_MULTI_WORD, RESOLVED_BOUNDARY); } /** * Logs whether the base page was using the HTTP protocol or not. * @param isHttpBasePage Whether the base page was using the HTTP protocol or not (should * be false for HTTPS or other URIs). */ public static void logBasePageProtocol(boolean isHttpBasePage) { RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchBasePageProtocol", isHttpBasePage ? PROTOCOL_IS_HTTP : PROTOCOL_NOT_HTTP, PROTOCOL_BOUNDARY); } /** * Logs changes to the Contextual Search preference, aside from those resulting from the first * run flow. * @param enabled Whether the preference is being enabled or disabled. */ public static void logPreferenceChange(boolean enabled) { RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchPreferenceStateChange", enabled ? PREFERENCE_ENABLED : PREFERENCE_DISABLED, PREFERENCE_HISTOGRAM_BOUNDARY); } /** * Logs the outcome of the promo (first run flow). * Logs multiple histograms; with and without the originating gesture. * @param wasTap Whether the gesture that originally caused the panel to show was a Tap. */ public static void logPromoOutcome(boolean wasTap) { int preferenceCode = getPreferenceValue(); RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchFirstRunFlowOutcome", preferenceCode, PREFERENCE_HISTOGRAM_BOUNDARY); int preferenceByGestureCode = getPromoByGestureStateCode(preferenceCode, wasTap); RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchPromoOutcomeByGesture", preferenceByGestureCode, PROMO_BY_GESTURE_BOUNDARY); } /** * Logs the duration of a Contextual Search panel being viewed by the user. * @param wereResultsSeen Whether search results were seen. * @param isChained Whether the Contextual Search ended with the start of another. * @param durationMs The duration of the contextual search in milliseconds. */ public static void logDuration(boolean wereResultsSeen, boolean isChained, long durationMs) { if (wereResultsSeen) { RecordHistogram.recordTimesHistogram("Search.ContextualSearchDurationSeen", durationMs, TimeUnit.MILLISECONDS); } else if (isChained) { RecordHistogram.recordTimesHistogram("Search.ContextualSearchDurationUnseenChained", durationMs, TimeUnit.MILLISECONDS); } else { RecordHistogram.recordTimesHistogram("Search.ContextualSearchDurationUnseen", durationMs, TimeUnit.MILLISECONDS); } } /** * Log the duration of finishing loading the SERP after the panel is opened. * @param wasPrefetch Whether the request was prefetch-enabled or not. * @param durationMs The duration of loading the SERP till completely loaded, in milliseconds. * Note that this value will be 0 when the SERP is prefetched and the user waits a * while before opening the panel. */ public static void logSearchPanelLoadDuration(boolean wasPrefetch, long durationMs) { if (wasPrefetch) { RecordHistogram.recordMediumTimesHistogram("Search.ContextualSearchDurationPrefetched", durationMs, TimeUnit.MILLISECONDS); } else { RecordHistogram.recordMediumTimesHistogram( "Search.ContextualSearchDurationNonPrefetched", durationMs, TimeUnit.MILLISECONDS); } // Also record a summary histogram with counts for each possibility. int code = !wasPrefetch ? NOT_PREFETCHED : (durationMs == 0 ? PREFETCHED_FULLY_LOADED : PREFETCHED_PARIALLY_LOADED); RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchPrefetchSummary", code, PREFETCH_BOUNDARY); } /** * Logs whether the promo was seen. * Logs multiple histograms, with and without the original triggering gesture. * @param wasPanelSeen Whether the panel was seen. * @param wasTap Whether the gesture that originally caused the panel to show was a Tap. */ public static void logPromoSeen(boolean wasPanelSeen, boolean wasTap) { RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchFirstRunPanelSeen", wasPanelSeen ? RESULTS_SEEN : RESULTS_NOT_SEEN, RESULTS_SEEN_BOUNDARY); logHistogramByGesture(wasPanelSeen, wasTap, "Search.ContextualSearchPromoSeenByGesture"); } /** * Logs whether search results were seen. * Logs multiple histograms; with and without the original triggering gesture. * @param wasPanelSeen Whether the panel was seen. * @param wasTap Whether the gesture that originally caused the panel to show was a Tap. */ public static void logResultsSeen(boolean wasPanelSeen, boolean wasTap) { RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchResultsSeen", wasPanelSeen ? RESULTS_SEEN : RESULTS_NOT_SEEN, RESULTS_SEEN_BOUNDARY); logHistogramByGesture(wasPanelSeen, wasTap, "Search.ContextualSearchResultsSeenByGesture"); } /** * Logs whether a selection is valid. * @param isSelectionValid Whether the selection is valid. */ public static void logSelectionIsValid(boolean isSelectionValid) { RecordHistogram.recordEnumeratedHistogram("Search.ContextualSearchSelectionValid", isSelectionValid ? SELECTION_VALID : SELECTION_INVALID, SELECTION_BOUNDARY); } /** * Logs whether a normal priority search request failed. * @param isFailure Whether the request failed. */ public static void logNormalPrioritySearchRequestOutcome(boolean isFailure) { RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchNormalPrioritySearchRequestStatus", isFailure ? REQUEST_FAILED : REQUEST_NOT_FAILED, REQUEST_BOUNDARY); } /** * Logs whether a low priority search request failed. * @param isFailure Whether the request failed. */ public static void logLowPrioritySearchRequestOutcome(boolean isFailure) { RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchLowPrioritySearchRequestStatus", isFailure ? REQUEST_FAILED : REQUEST_NOT_FAILED, REQUEST_BOUNDARY); } /** * Logs whether a fallback search request failed. * @param isFailure Whether the request failed. */ public static void logFallbackSearchRequestOutcome(boolean isFailure) { RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchFallbackSearchRequestStatus", isFailure ? REQUEST_FAILED : REQUEST_NOT_FAILED, REQUEST_BOUNDARY); } /** * Logs how a state was entered for the first time within a Contextual Search. * @param fromState The state to transition from. * @param toState The state to transition to. * @param reason The reason for the state transition. */ public static void logFirstStateEntry(PanelState fromState, PanelState toState, StateChangeReason reason) { int code; switch (toState) { case CLOSED: code = getStateChangeCode(fromState, reason, ENTER_CLOSED_STATE_CHANGE_CODES, ENTER_CLOSED_FROM_OTHER); RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchEnterClosed", code, ENTER_CLOSED_FROM_BOUNDARY); break; case PEEKED: code = getStateChangeCode(fromState, reason, ENTER_PEEKED_STATE_CHANGE_CODES, ENTER_PEEKED_FROM_OTHER); RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchEnterPeeked", code, ENTER_PEEKED_FROM_BOUNDARY); break; case EXPANDED: code = getStateChangeCode(fromState, reason, ENTER_EXPANDED_STATE_CHANGE_CODES, ENTER_EXPANDED_FROM_OTHER); RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchEnterExpanded", code, ENTER_EXPANDED_FROM_BOUNDARY); break; case MAXIMIZED: code = getStateChangeCode(fromState, reason, ENTER_MAXIMIZED_STATE_CHANGE_CODES, ENTER_MAXIMIZED_FROM_OTHER); RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchEnterMaximized", code, ENTER_MAXIMIZED_FROM_BOUNDARY); break; default: break; } } /** * Logs how a state was exited for the first time within a Contextual Search. * @param fromState The state to transition from. * @param toState The state to transition to. * @param reason The reason for the state transition. */ public static void logFirstStateExit(PanelState fromState, PanelState toState, StateChangeReason reason) { int code; switch (fromState) { case UNDEFINED: case CLOSED: code = getStateChangeCode(toState, reason, EXIT_CLOSED_TO_STATE_CHANGE_CODES, EXIT_CLOSED_TO_OTHER); RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchExitClosed", code, EXIT_CLOSED_TO_BOUNDARY); break; case PEEKED: code = getStateChangeCode(toState, reason, EXIT_PEEKED_TO_STATE_CHANGE_CODES, EXIT_PEEKED_TO_OTHER); RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchExitPeeked", code, EXIT_PEEKED_TO_BOUNDARY); break; case EXPANDED: code = getStateChangeCode(toState, reason, EXIT_EXPANDED_TO_STATE_CHANGE_CODES, EXIT_EXPANDED_TO_OTHER); RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchExitExpanded", code, EXIT_EXPANDED_TO_BOUNDARY); break; case MAXIMIZED: code = getStateChangeCode(toState, reason, EXIT_MAXIMIZED_TO_STATE_CHANGE_CODES, EXIT_MAXIMIZED_TO_OTHER); RecordHistogram.recordEnumeratedHistogram( "Search.ContextualSearchExitMaximized", code, EXIT_MAXIMIZED_TO_BOUNDARY); break; default: break; } } /** * Gets the state-change code for the given parameters by doing a lookup in the given map. * @param state The panel state. * @param reason The reason the state changed. * @param stateChangeCodes The map of state and reason to code. * @param defaultCode The code to return if the given values are not found in the map. * @return The code to write into an enum histogram, based on the given map. */ private static int getStateChangeCode(PanelState state, StateChangeReason reason, Map<StateChangeKey, Integer> stateChangeCodes, int defaultCode) { Integer code = stateChangeCodes.get(new StateChangeKey(state, reason)); if (code != null) { return code; } return defaultCode; } /** * Gets the panel-seen code for the given parameters by doing a lookup in the seen-by-gesture * map. * @param wasPanelSeen Whether the panel was seen. * @param wasTap Whether the gesture that originally caused the panel to show was a Tap. * @return The code to write into a panel-seen histogram. */ private static int getPanelSeenByGestureStateCode(boolean wasPanelSeen, boolean wasTap) { return SEEN_BY_GESTURE_CODES.get(new Pair<Boolean, Boolean>(wasPanelSeen, wasTap)); } /** * Gets the promo-outcome code for the given parameter by doing a lookup in the * promo-by-gesture map. * @param preferenceValue The code for the current preference value. * @param wasTap Whether the gesture that originally caused the panel to show was a Tap. * @return The code to write into a promo-outcome histogram. */ private static int getPromoByGestureStateCode(int preferenceValue, boolean wasTap) { return PROMO_BY_GESTURE_CODES.get(new Pair<Integer, Boolean>(preferenceValue, wasTap)); } /** * @return The code for the Contextual Search preference. */ private static int getPreferenceValue() { PrefServiceBridge preferences = PrefServiceBridge.getInstance(); if (preferences.isContextualSearchUninitialized()) { return PREFERENCE_UNINITIALIZED; } else if (preferences.isContextualSearchDisabled()) { return PREFERENCE_DISABLED; } return PREFERENCE_ENABLED; } /** * Logs to a seen-by-gesture histogram of the given name. * @param wasPanelSeen Whether the panel was seen. * @param wasTap Whether the gesture that originally caused the panel to show was a Tap. * @param histogramName The full name of the histogram to log to. */ private static void logHistogramByGesture(boolean wasPanelSeen, boolean wasTap, String histogramName) { RecordHistogram.recordEnumeratedHistogram(histogramName, getPanelSeenByGestureStateCode(wasPanelSeen, wasTap), RESULTS_BY_GESTURE_BOUNDARY); } }
package ee.ut.algorithmics.image.finder; import ee.ut.algorithmics.keyword.finder.WordIncidence; import javafx.util.Pair; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class ImageSearchManager { private static final int MAX_CAPACITY = 250; private static final int NUMBER_OF_THREADS_FOR_SEARCH = 2; private static final int NUMBER_OF_THREADS_FOR_DOWNLOAD = 3; private List<WordIncidence> keyphrases; public static void main(String[] args){ ImageSearchManager imageManager = new ImageSearchManager(); List<WordIncidence> phrases = new ArrayList<>(); WordIncidence p1 = new WordIncidence("edgar", 97); WordIncidence p2 = new WordIncidence("eesti", 57); WordIncidence p3 = new WordIncidence("keskerakonna", 53); WordIncidence p4 = new WordIncidence("tallinna", 53); WordIncidence p5 = new WordIncidence("linnapea", 43); WordIncidence p6 = new WordIncidence("esimees", 39); WordIncidence p7 = new WordIncidence("riigikogu", 25); phrases.add(p1); phrases.add(p2); phrases.add(p3); phrases.add(p4); phrases.add(p5); phrases.add(p6); phrases.add(p7); imageManager.start(imageManager.limitNumberOfImages(imageManager.calculateRealWeight(phrases), 200), args[0]); } public ImageSearchManager() {} public ImageSearchManager(List<WordIncidence> keyphrases) { this.keyphrases = keyphrases; } public void downloadPictures(String targetFolder) { ImageSearchManager imageManager = new ImageSearchManager(); File dir = new File(targetFolder); dir.mkdir(); start(limitNumberOfImages(calculateRealWeight(this.keyphrases), 200), dir.getAbsolutePath()); } private List<WordIncidence> calculateRealWeight(List<WordIncidence> keyPhrases){ List<WordIncidence> newPhrases = new ArrayList<WordIncidence>(); int total = 0; for (WordIncidence item : keyPhrases){ total += item.getIncidence(); } for (WordIncidence item : keyPhrases){ newPhrases.add(new WordIncidence(item.getWord(), (int) (((float) item.getIncidence() / total) * 100))); } return newPhrases; } private List<WordIncidence> limitNumberOfImages(List<WordIncidence> keyPhrases, int limit){ int total = 0; for (WordIncidence item : keyPhrases){ total += item.getIncidence(); } List<WordIncidence> results; if (total > limit){ results = new ArrayList<>(); float multiplier = total / limit; for (WordIncidence item : keyPhrases){ results.add(new WordIncidence(item.getWord(), (int) (item.getIncidence() * multiplier))); } } else { return keyPhrases; } return results; } public static void start(List<WordIncidence> listOfPhrases, String path){ final BlockingQueue<WordIncidence> queueOfKeyPhrases = new LinkedBlockingQueue<WordIncidence>(MAX_CAPACITY); final BlockingQueue<Pair<String, String>> queueOfLinks = new LinkedBlockingQueue<Pair<String, String>>(MAX_CAPACITY); queueOfKeyPhrases.addAll(listOfPhrases); final List<ImageFinder> consumers = new ArrayList<ImageFinder>(); for (int i = 0; i < NUMBER_OF_THREADS_FOR_SEARCH; i++) { final ImageFinder consThread = new ImageFinder(queueOfKeyPhrases, queueOfLinks); consThread.start(); consumers.add(consThread); } final List<ImageDownloader> consumers1 = new ArrayList<ImageDownloader>(); for (int i = 0; i < NUMBER_OF_THREADS_FOR_DOWNLOAD + 2; i++) { final ImageDownloader consThread = new ImageDownloader(queueOfLinks, path); consThread.start(); consumers1.add(consThread); } // Wait while all threads to finish the job for (ImageFinder threat : consumers){ try { threat.join(); }catch (InterruptedException iex){ throw new RuntimeException(iex); } } queueOfLinks.add(new Pair("full_stop", "stop")); System.out.println("Search finished"); // Wait while all threads to finish the job for (ImageDownloader threat : consumers1){ try { threat.join(); }catch (InterruptedException iex){ throw new RuntimeException(iex); } } System.out.println("Download finished"); } }
package eu.newsreader.eventcoreference.objects; import com.hp.hpl.jena.query.Dataset; import com.hp.hpl.jena.rdf.model.*; import eu.kyotoproject.kaf.CorefTarget; import java.util.ArrayList; public class SemRelation { /* <semRelation id="TOPIC_44_EVENT_COREFERENCE_CORPUS/2413" predicate="semHasTime" subject="TOPIC_44_EVENT_COREFERENCE_CORPUS/e53" object="TOPIC_44_EVENT_COREFERENCE_CORPUS/t246"> <target id ="TOPIC_44_EVENT_COREFERENCE_CORPUS/TOPIC_8_EVENT_COREFERENCE_CORPUS/s19"/> </semRelation> */ private String id; private String predicate; private String subject; private String object; private ArrayList<CorefTarget> corefTargets; public void SemRelation () { } public SemRelation() { this.corefTargets = new ArrayList<CorefTarget>(); this.id = ""; this.object = ""; this.predicate = ""; this.subject = ""; } public ArrayList<CorefTarget> getCorefTarget() { return corefTargets; } public void setCorefTargets(ArrayList<CorefTarget> corefTargets) { this.corefTargets = corefTargets; } public void setCorefTargetsWithMentions(ArrayList<ArrayList<CorefTarget>> mentions) { for (int i = 0; i < mentions.size(); i++) { ArrayList<CorefTarget> targets = mentions.get(i); addCorefTargets(targets); } } public void addCorefTarget(CorefTarget corefTarget) { this.corefTargets.add(corefTarget); } public void addCorefTargets(ArrayList<CorefTarget> corefTargets) { for (int i = 0; i < corefTargets.size(); i++) { CorefTarget corefTarget = corefTargets.get(i); this.corefTargets.add(corefTarget); } } public void setCorefTargets(String baseUrl, ArrayList<CorefTarget> corefTargets) { for (int i = 0; i < corefTargets.size(); i++) { CorefTarget corefTarget = corefTargets.get(i); corefTarget.setId(baseUrl+"/"+corefTarget.getId()); } this.corefTargets = corefTargets; } public void addCorefTarget(String baseUrl, CorefTarget corefTarget) { corefTarget.setId(baseUrl+"/"+corefTarget.getId()); this.corefTargets.add(corefTarget); } public void addCorefTargets(String baseUrl, ArrayList<CorefTarget> corefTargets) { for (int i = 0; i < corefTargets.size(); i++) { CorefTarget corefTarget = corefTargets.get(i); corefTarget.setId(baseUrl+"/"+corefTarget.getId()); this.corefTargets.add(corefTarget); } } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getObject() { return object; } public void setObject(String object) { this.object = object; } public String getPredicate() { return predicate; } public void setPredicate(String predicate) { this.predicate = predicate; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public Property getSemRelationType (String type) { if (type.equalsIgnoreCase("hassemtime")) { return Sem.hasTime; } else if (type.equalsIgnoreCase("hassemplace")) { return Sem.hasPlace; } else if (type.equalsIgnoreCase("hassemactor")) { return Sem.hasActor; } else { return Sem.hasSubType; } } public void addToJenaDataSet (Dataset ds, Model provenanceModel) { Model relationModel = ds.getNamedModel("http: Resource subject = relationModel.createResource("nwr:"+this.getSubject()); Resource object = relationModel.createResource("nwr:"+this.getObject()); Property semProperty = getSemRelationType(this.getPredicate()); subject.addProperty(semProperty, object); Resource provenanceResource = provenanceModel.createResource("http: for (int i = 0; i < corefTargets.size(); i++) { CorefTarget corefTarget = corefTargets.get(i); Property property = provenanceModel.createProperty("gaf:denotedBy"); Resource targerResource = provenanceModel.createResource("nwr:"+corefTarget.getId()); provenanceResource.addProperty(property, targerResource); } } public SemRelation (SemRelation semRelation) { this.setSubject(semRelation.getSubject()); this.setObject(semRelation.getObject()); this.setPredicate(semRelation.getPredicate()); this.setCorefTargets(semRelation.getCorefTarget()); } public boolean match (SemRelation semRelation) { if (!this.getSubject().equals(semRelation.getSubject())) { return false; } if (!this.getObject().equals(semRelation.getObject())) { return false; } if (!this.getPredicate().equals(semRelation.getPredicate())) { return false; } return true; } }
package org.jlib.container.sequence; import java.util.List; /** * {@link Sequence} delegating all calls to its methods to the equivalent * methods of a delegate {@link IndexSequence}. The delegate {@link Sequence} * may be modified at any time allowing to dynamically switch to the contents * and the behavior of another {@link IndexSequence}. * * @param <Element> * type of elements held in the {@link Sequence} * * @author Igor Akkerman */ public abstract class AbstractDelegatingIndexSequence<Element> extends AbstractDelegatingSequence<Element> implements IndexSequence<Element> { /** * Creates a new {@link AbstractDelegatingIndexSequence}. */ protected AbstractDelegatingIndexSequence() { super(); } /** * Returns the {@link IndexSequence} containing the {@code Elements} of this * {@link AbstractDelegatingIndexSequence}. * * @return the delegate {@link IndexSequence} */ @Override protected abstract IndexSequence<Element> getDelegateSequence(); @Override public Element get(final int index) throws SequenceIndexOutOfBoundsException { return getDelegateSequence().get(index); } @Override public int getFirstIndex() { return getDelegateSequence().getFirstIndex(); } @Override public int getLastIndex() { return getDelegateSequence().getLastIndex(); } @Override public int getFirstIndexOf(final Element element) { return getDelegateSequence().getFirstIndexOf(element); } @Override public int getLastIndexOf(final Element element) { return getDelegateSequence().getLastIndexOf(element); } @Override public List<Element> createSubList(final int fromIndex, final int toIndex) throws IllegalArgumentException, SequenceIndexOutOfBoundsException { return getDelegateSequence().createSubList(fromIndex, toIndex); } @Override public IndexSequence<Element> createSubSequence(final int fromIndex, final int toIndex) throws IllegalArgumentException, SequenceIndexOutOfBoundsException { return getDelegateSequence().createSubSequence(fromIndex, toIndex); } @Override public IndexSequenceIterator<Element> createIterator() { return getDelegateSequence().createIterator(); } @Override public IndexSequenceIterator<Element> createIterator(final int startIndex) throws SequenceIndexOutOfBoundsException { return getDelegateSequence().createIterator(startIndex); } }
package gov.nasa.jpl.mgss.mbee.docgen.model; import java.util.ArrayList; import java.util.List; import java.util.Iterator; import org.kohsuke.rngom.binary.visitor.ChildElementFinder.Element; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Property; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Slot; import com.nomagic.uml2.ext.magicdraw.mdprofiles.Stereotype; public class TableStructure extends Table implements Iterator<List<Object>>{ //TODO decide tag options private List<String> headers; private List<Stereotype> outgoing; private List<Stereotype> incoming; private boolean skipIfNoDoc; private List<List<Object>> table; public void setSkipIfNoDoc(boolean b) { skipIfNoDoc = b; } public void setHeaders(List<String> d) { headers = d; } public void setOutgoing(List<Stereotype> s) { outgoing = s; } public void setIncoming(List<Stereotype> s) { incoming = s; } public List<String> getHeaders() { return headers; } public List<Stereotype> getOutgoing() { return outgoing; } public List<Stereotype> getIncoming() { return incoming; } public boolean isSkipIfNoDoc() { return skipIfNoDoc; } // Table Stuff private Object nullEntry = new String("no entry"); private int cLen; public TableStructure() { cLen = 0; table = new ArrayList<List<Object>>(); } public int getColumNum() { return cLen; } public List<List<Object>> getTable() { return table; } // Doesn't account for column length differences public void setTable(List<List<Object>> t) { table = t; } // Equalizes column lengths public void addColumn(List<Object> c) { if (c != null) { table.add(c); if (c.size() > cLen) cLen = c.size(); for (List<Object> x: table) while (x.size() < cLen) x.add(nullEntry); } else { table.add(new ArrayList<Object>()); } } public List<Object> getColumn(int n) { if (n < table.size() && n >= 0) return table.get(n); else return null; } // IMPORTANT INVARIANT: Assumes all columns given are equally sized public void addRow(List<Object> r) { if (table.size() < r.size()) { List<Object> empty = new ArrayList<Object>(); if (table.size() > 0) for (int i = 0; i < table.get(0).size(); i++) empty.add(nullEntry); for (int i = table.size(); i < r.size(); i++) table.add(empty); } else if (r.size() < table.size()) { for (int i = r.size(); i < table.size(); i++) r.add(0, nullEntry); } for (int i = 0; i < r.size(); i++) table.get(i).add(r.get(i)); cLen++; } // Makes same assumption as addRow public List<Object> getRow(int n) { if (table.get(0) == null || n >= table.get(0).size()) return null; List<Object> output = new ArrayList<Object>(); for (int i = 0; i < table.size(); i++) output.add(table.get(i).get(n)); return output; } // Fancy table operations String irrelevantEntry = new String(" @SuppressWarnings("unchecked") public void addSumRow() { List<Object> sumRow = new ArrayList<Object>(); double f; boolean foundSumable = false; for (List<Object> c: table) { f = 0; for (Object l: c) for (Object item: (List<Object>)l) { if (item instanceof Float || item instanceof Double || item instanceof Integer) { foundSumable = true; f += (Double)item; } } ArrayList bucket = new ArrayList<Object>(); if (foundSumable) bucket.add(f); else bucket.add(irrelevantEntry); sumRow.add(bucket); foundSumable = false; } addRow(sumRow); } // Iterator Stuff private int itercount = 0; public boolean hasNext() { return table.size()>0?(table.get(0).size() > itercount):false; } public List<Object> next() { List<Object> out = getRow(itercount); itercount++; return out; } public void remove() { return; } // Debugging relevant stuff public String toString() { //determine longest row int biggest=0; if (table != null) for (List<Object> c: table) biggest = (c.size() > biggest) ? c.size() : biggest; //add lines to the string String output = new String(); for (int n = 0; n < biggest; n++) { for (List<Object> c: table) { if (c.size() <= n) output.concat("| null\t"); else output.concat("| " + c.toString() + "\t"); } output.concat("||\n"); } return output; } // For DocBookOutputVisitor Stuff @Override public void accept(IModelVisitor v) { v.visit(this); } }
package hudson.plugins.robot.blueocean; import java.util.stream.Collectors; import hudson.Extension; import hudson.model.Run; import hudson.plugins.robot.RobotBuildAction; import hudson.plugins.robot.model.RobotCaseResult; import io.jenkins.blueocean.rest.Reachable; import io.jenkins.blueocean.rest.factory.BlueTestResultFactory; import io.jenkins.blueocean.rest.hal.Link; import io.jenkins.blueocean.rest.model.BlueTestResult; public class BlueRobotTestResult extends BlueTestResult { protected final RobotCaseResult result; public BlueRobotTestResult(RobotCaseResult result, Link parent) { super(parent); this.result = result; } @Override public String getName() { return result.getDisplayName(); } @Override public Status getStatus() { return result.isPassed() ? Status.PASSED : Status.FAILED; } @Override public State getTestState() { return State.UNKNOWN; } @Override public float getDuration() { // Blue ocean uses seconds instead of milliseconds return result.getDuration() / (float)1000; } @Override public String getErrorStackTrace() { return result.getStackTrace(); } @Override public String getErrorDetails() { return result.getErrorMsg() == null ? "" : result.getErrorMsg(); } @Override public String getUniqueId() { return result.getId(); } @Override public int getAge() { return result.getAge(); } @Override public String getStdErr() { return ""; } @Override public String getStdOut() { return ""; } @Override public boolean hasStdLog() { return false; } @Extension(optional = true) public static class FactoryImpl extends BlueTestResultFactory { @Override public Result getBlueTestResults(Run<?,?> run, final Reachable parent) { RobotBuildAction action = run.getAction(RobotBuildAction.class); if (action == null) { return Result.notFound(); } return Result.of(action.getAllTests().stream().map(t-> new BlueRobotTestResult(t, parent.getLink())).collect(Collectors.toList())); } } }
package io.reactivesw.customer.server.catalog.models; import io.swagger.annotations.Api; import io.swagger.annotations.ApiModel; @ApiModel public class Image { /** * URL of the image in its original size. * This can be used to obtain the image in different sizes. */ private String url; /** * Dimensions of the original image. * This can be used by your application e.g. to determine * whether the image is large enough to display a zoom view. */ //TODO String may not ok? private String dimensions; /** * Custom label that can be used, for example, as an image description. */ private String label; /** * Gets url. * * @return the url */ public String getUrl() { return url; } /** * Sets url. * * @param url the url */ public void setUrl(String url) { this.url = url; } /** * Gets dimensions. * * @return the dimensions */ public String getDimensions() { return dimensions; } /** * Sets dimensions. * * @param dimensions the dimensions */ public void setDimensions(String dimensions) { this.dimensions = dimensions; } /** * Gets label. * * @return the label */ public String getLabel() { return label; } /** * Sets label. * * @param label the label */ public void setLabel(String label) { this.label = label; } /** * toString method. * * @return String */ @Override public String toString() { return "Image{" + "url='" + url + '\'' + ", dimensions='" + dimensions + '\'' + ", label='" + label + '\'' + '}'; } }
package jenkins.plugins.coverity; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.LauncherDecorator; import hudson.Proc; import hudson.model.*; import hudson.remoting.Channel; import hudson.tasks.Builder; import jenkins.plugins.coverity.CoverityTool.CovBuildCompileCommand; import org.apache.commons.lang.Validate; import javax.annotation.Nonnull; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.logging.Logger; /** * This makes sure that all commands executed (when invocation assistance is enabled) are run through cov-build. */ @Extension public class CoverityLauncherDecorator extends LauncherDecorator { private static final Logger logger = Logger.getLogger(CoverityLauncherDecorator.class.getName()); /** * A ThreadLocal that is used to disable cov-build when running other Coverity tools during the build. */ public static ThreadLocal<Boolean> CoverityPostBuildAction = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; } }; public static ThreadLocal<Boolean> CoverityBuildStep = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; } }; @Override public Launcher decorate(Launcher launcher, Node node) { Executor executor = Executor.currentExecutor(); if(executor == null) { return launcher; } Queue.Executable exec = executor.getCurrentExecutable(); if(!(exec instanceof AbstractBuild)) { return launcher; } AbstractBuild build = (AbstractBuild) exec; AbstractProject project = build.getProject(); CoverityPublisher publisher = (CoverityPublisher) project.getPublishersList().get(CoverityPublisher.class); //Setting up code to allow environment variables in text fields EnvVars env; try{ env = project.getEnvironment(node,launcher.getListener()); }catch(Exception e){ throw new RuntimeException("Error getting build environment variables", e); } if(publisher == null) { return launcher; } CoverityVersion version = CheckConfig.checkNode(publisher, build, launcher, launcher.getListener()).getVersion(); TaOptionBlock ta = publisher.getTaOptionBlock(); ScmOptionBlock scm = publisher.getScmOptionBlock(); InvocationAssistance invocationAssistance = publisher.getInvocationAssistance(); boolean isUsingTA = false; boolean isUsingMisra = false; if(ta != null){ String taCheck = ta.checkTaConfig(); if(!taCheck.equals("Pass")){ throw new RuntimeException(taCheck); } isUsingTA = true; } if(invocationAssistance != null){ String taCheck = invocationAssistance.checkIAConfig(); if(!taCheck.equals("Pass")){ throw new RuntimeException(taCheck); } isUsingMisra = invocationAssistance.getIsUsingMisra(); } if(isUsingTA && isUsingMisra){ String errorText = "Errors with your \"Perform Coverity build/analyze/commit\" options: \n " + "[Error] MISRA and Test Advisor options are not compatible. \n"; throw new RuntimeException(errorText); } if(scm != null){ String scmCheck = scm.checkScmConfig(version); if(!scmCheck.equals("Pass")){ throw new RuntimeException(scmCheck); } } return new DecoratedLauncher(launcher, node); } /** * A decorated {@link Launcher} that puts the given set of arguments as a prefix to any commands that it invokes. */ public class DecoratedLauncher extends Launcher { private final Launcher decorated; private String[] prefix; private final String toolsDir; private final Node node; private EnvVars envVars; public DecoratedLauncher(Launcher decorated, Node node) { super(decorated); this.decorated = decorated; this.node = node; this.toolsDir = node.getRootPath().child("tools").getRemote(); } private String[] getPrefix() { String[] tp = prefix.clone(); if(tp.length > 0){ tp[0] = CoverityUtils.getCovBuild(decorated.getListener(), node); } return tp; } @Override public Proc launch(ProcStarter starter) throws IOException { EnvVars buildEnvVars = CoverityUtils.getBuildEnvVars(listener); if (envVars == null || envVars.isEmpty()) { envVars = buildEnvVars; } else { envVars.overrideAll(buildEnvVars); } AbstractBuild build = CoverityUtils.getBuild(); AbstractProject project = build.getProject(); CoverityPublisher publisher = (CoverityPublisher) project.getPublishersList().get(CoverityPublisher.class); // Setup(or resolve) intermediate directory setupIntermediateDirectory(build, this.getListener(), node); // Any Coverity Post-build action such as cov-analyze, cov-import-scm, etc will not be wrapped // with the cov-build. if (CoverityPostBuildAction.get()) { return decorated.launch(starter); } boolean isCoverityBuildStepEnabled = false; // Check if there are any Coverity Build Step configured. // This is required to support backward compatibility. if (project instanceof Project) { List<Builder> builders = ((Project)project).getBuilders(); for (Builder buildStep : builders) { if (buildStep.getDescriptor() instanceof CoverityBuildStep.CoverityBuildStepDescriptor) { isCoverityBuildStepEnabled = true; break; } } } // The first condition is for the case where there are no coverity build steps. // Then we want to wrap the build steps with cov-build. This is to support backward compatibility // The second condition is for the case where there are coverity build step and // the current build step is the coverity build step. if (!isCoverityBuildStepEnabled || (isCoverityBuildStepEnabled && CoverityBuildStep.get())) { InvocationAssistance invocationAssistance = CoverityUtils.getInvocationAssistance(); String home = publisher.getDescriptor().getHome(node, envVars); if(invocationAssistance != null && invocationAssistance.getSaOverride() != null) { home = new CoverityInstallation( CoverityUtils.evaluateEnvVars(invocationAssistance.getSaOverride(), envVars, invocationAssistance.getUseAdvancedParser())).forEnvironment(envVars).getHome(); } List<String> cmds = starter.cmds(); List<String> args = new CovBuildCompileCommand(build, decorated, decorated.getListener(), publisher, home, envVars).constructArguments(); prefix = args.toArray(new String[args.size()]); cmds.addAll(0, args); boolean useAdvancedParser = false; if(invocationAssistance != null && invocationAssistance.getUseAdvancedParser()){ useAdvancedParser = true; } //skip jdk installations String lastArg = cmds.get(cmds.size() - 1); if(lastArg.startsWith(toolsDir) && lastArg.endsWith(".sh")) { logger.info(lastArg + " is a tools script, skipping cov-build"); return decorated.launch(starter); } /** * Overrides environment variables on the ProcStarter. * * First, get the environment variables from the ProcStarter. Then, add more environment variables to it. * Finally, creates a new ProcStarter object identically to the first one but with overridden variables. */ String[] starterEnvVars = starter.envs(); starterEnvVars = CoverityUtils.addEnvVars(starterEnvVars, envVars); starter = starter.envs(starterEnvVars); cmds = CoverityUtils.prepareCmds(cmds, envVars, useAdvancedParser); /** * Display cov-build command on the console. Coverity's parser is used in order to resolve environment * variables on that command just for display purposes. */ getListener().getLogger().println(CoverityUtils.prepareCmds(cmds, envVars, true).toString()); starter = starter.cmds(cmds); boolean[] masks = starter.masks(); if(masks == null) { masks = new boolean[cmds.size()]; starter = starter.masks(masks); } else { starter = starter.masks(prefix(masks)); } CoverityBuildStep.set(false); } return decorated.launch(starter); } @Override public Channel launchChannel(String[] cmd, OutputStream out, FilePath workDir, Map<String, String> envVars) throws IOException, InterruptedException { String lastArg = cmd[cmd.length - 1]; if(lastArg.startsWith(toolsDir) && lastArg.endsWith(".sh")) { logger.info(lastArg + " is a tools script, skipping cov-build"); decorated.launchChannel(cmd, out, workDir, envVars); } return decorated.launchChannel(prefix(cmd), out, workDir, envVars); } /* * When running remotely, overriding this method makes sure that the platform is detected correctly. */ @Override public boolean isUnix() { return decorated.isUnix(); } @Override public void kill(Map<String, String> modelEnvVars) throws IOException, InterruptedException { decorated.kill(modelEnvVars); } private String[] prefix(String[] args) { String[] newArgs = new String[args.length + prefix.length]; System.arraycopy(getPrefix(), 0, newArgs, 0, prefix.length); System.arraycopy(args, 0, newArgs, prefix.length, args.length); return newArgs; } private boolean[] prefix(boolean[] args) { boolean[] newArgs = new boolean[args.length + prefix.length]; System.arraycopy(args, 0, newArgs, prefix.length, args.length); return newArgs; } /** * Resolves environment variables on the specified intermediate directory. If the result is a null object or the * path is empty an exception is thrown. */ public FilePath resolveIntermediateDirectory(AbstractBuild<?,?> build, TaskListener listener, Node node, String idirInput){ FilePath idirFilePath = null; try { String idir = EnvParser.interpolateRecursively(idirInput, 1, envVars); if(idir == null || idir.isEmpty()){ throw new Exception("The specified Intermediate Directory is not valid: " + idirInput); } idirFilePath = new FilePath(node.getChannel(), idir); } catch (ParseException e) { CoverityUtils.handleException(e.getMessage(), build, listener, e); } catch (Exception e){ CoverityUtils.handleException("An error occured while setting intermediate directory: " + idirInput, build, listener, e); } return idirFilePath; } /** * Sets the value of environment variable "COV_IDIR" and creates necessary directories. This variable is used as argument of "--dir" for * cov-build. * * If the environment variable has already being set then that value is used. Otherwise, the value of * this variable is set to either a temporary directory or the idir specified on the UI under the * Intermediate Directory option. * * Notice this variable must be resolved before running cov-build. Also this method creates necessary directories. */ public void setupIntermediateDirectory(@Nonnull AbstractBuild<?,?> build, @Nonnull TaskListener listener, @Nonnull Node node){ Validate.notNull(build, AbstractBuild.class.getName() + " object can't be null"); Validate.notNull(listener, TaskListener.class.getName() + " object can't be null"); Validate.notNull(node, Node.class.getName() + " object can't be null"); Validate.notNull(envVars, EnvVars.class.getName() + " object can't be null"); if(!envVars.containsKey("COV_IDIR")){ FilePath temp; InvocationAssistance invocationAssistance = CoverityUtils.getInvocationAssistance(build); try { if(invocationAssistance == null || invocationAssistance.getIntermediateDir() == null || invocationAssistance.getIntermediateDir().isEmpty()){ FilePath coverityDir = node.getRootPath().child("coverity"); coverityDir.mkdirs(); temp = coverityDir.createTempDir("temp-", null); } else { // Gets a not null nor empty intermediate directory. temp = resolveIntermediateDirectory(build, listener, node, invocationAssistance.getIntermediateDir()); temp.mkdirs(); } if(invocationAssistance != null){ build.addAction(new CoverityTempDir(temp, invocationAssistance.getIntermediateDir() == null)); } else{ build.addAction(new CoverityTempDir(temp, true)); } } catch(IOException e) { throw new RuntimeException("Error while creating temporary directory for Coverity", e); } catch(InterruptedException e) { throw new RuntimeException("Interrupted while creating temporary directory for Coverity"); } envVars.put("COV_IDIR", temp.getRemote()); } } } }
package me.stieglmaier.sphereMiners.model; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import javafx.scene.paint.Color; import me.stieglmaier.sphereMiners.main.Constants; public abstract class SphereMiners2015 { /** All owned spheres */ protected Set<Sphere> ownSpheres; private Physics physics; private Player ownAI; private Map<Player, List<MutableSphere>> allSpheres; private Map<Sphere, MutableSphere> sphereMap; private Turn currentTurn; private Constants constants; private ExecutorService threadExecutor = Executors.newSingleThreadExecutor(); /** * Set up your AI, initial values for attributes, color of your spheres, ... */ protected abstract void init(); /** * In this method your AI has to specify what it wants to do, it can either * change the moving direction of any number of spheres controlled by you, or * split a sphere into two (half) parts, or merge two spheres to a bigger one. * * Note: the or is exclusive in this case, only one of the above operations * is allowed at the same time */ protected abstract void playTurn(); /** * Sets the color of your spheres. * * @param color The color your spheres should have */ protected final void setColor(Color color) { ownAI.setColor(color); } /** * Sets your displayed name. * * @param name The name you want to have */ protected final void setName(String name) { ownAI.setName(name); } /** * Returns the Constants that are used throughout the framework. * * @return the Constants object used in the whole framework */ protected final Constants getConstants() { return constants; } /** * Changes the moving direction of a Sphere instantly, there is no kind of * friction or acceleration in between. However the speed cannot be changed * with this method, as it is dependant on the size of the Sphere and cannot * be set by a player. * * Executing this method prevents you from executing {@link SphereMiners2015#split(Sphere)} * and {@link SphereMiners2015#merge(Sphere, Sphere)} in this turn. The last * called method of these will be executed. * * @param spheres The map of spheres to their new positions (does not need to * include all spheres you own) */ protected final void changeMoveDirection(final Map<Sphere, Position> spheres) { currentTurn = () -> spheres.forEach((sphere, dir) -> sphereMap.get(sphere) .setDirection(dir)); } /** * Splits the given sphere to two equally (half) sized ones. * * Executing this method prevents you from executing {@link SphereMiners2015#changeMoveDirection(Map)} * and {@link SphereMiners2015#merge(Sphere, Sphere)} in this turn. The last * called method of these will be executed. * * @param sphere The sphere you want to split into two parts */ protected final void split(Sphere sphere) { // lists cannot be changed directly therefore we need the phyiscsmanager here currentTurn = () -> physics.split(sphereMap.get(sphere), ownAI); } /** * Merges the given spheres to one that has the accumulated size of both. * * Executing this method prevents you from executing {@link SphereMiners2015#changeMoveDirection(Map)} * and {@link SphereMiners2015#split(Sphere)} in this turn. The last * called method of these will be executed. * * @param sphere1 The sphere that should grow * @param sphere2 The sphere that should be merged into the other one */ protected final void merge(Sphere sphere1, Sphere sphere2) { // lists cannot be changed directly therefore we need the phyiscsmanager here currentTurn = () -> physics.merge(sphereMap.get(sphere1), sphereMap.get(sphere2), ownAI); } /** * Returns the enemies surrounding the given sphere in a certain distance. * * @param sphere The sphere you want to find the surrounding enemies for * @return the sourrounding enemies of the given sphere */ protected final Set<MutableSphere> getSurroundingEnemies(Sphere sphere) { // TODO implement this operation throw new UnsupportedOperationException("not implemented"); } /** * Package private, this should only be called by AIManager! * @return indicates wether the turn could be evaluated within the timelimit * or not */ boolean evaluateTurn() { currentTurn = () -> {}; Future<?> future = threadExecutor.submit(() -> playTurn()); try { future.get(constants.getAIComputationTime(), TimeUnit.MILLISECONDS); } catch (ExecutionException | TimeoutException | InterruptedException e) { future.cancel(true); // TODO proved exception information in logger (introduce logging first) return false; } currentTurn.apply(); return true; } /** * Sets the constants object for this ai. * * @param constants The constants that should be used for this ai. */ void setConstants(Constants constants) { this.constants = constants; } /** * Package private, this should only be called and set by AImanager! * * @param physics the physics instance needed for some ai interactions */ void setPhysics(Physics physics) { this.physics = physics; allSpheres = physics.getAISpheres(); sphereMap = allSpheres.get(ownAI).stream() .collect(Collectors.toMap(s -> s.toImmutableSphere(), s -> s)); ownSpheres = sphereMap.keySet(); } /** * Set the player used as identifier in maps throughout the framework * * @param player The internal representation of the player in the framework */ void setPlayer(Player player) { this.ownAI = player; } @FunctionalInterface private interface Turn { void apply(); } }
package modules; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.net.URISyntaxException; import java.util.Scanner; import bot.Message; import bot.Module; import bot.Server; import bot.info.Info; public class PastaTitle implements Module { public File file; public String topicmain = ""; public PastaTitle() { try { file = new File(this.getClass().getResource("files/pastatitle.txt").toURI()); Scanner scan = new Scanner(file); topicmain = scan.nextLine(); scan.close(); } catch (FileNotFoundException | URISyntaxException e) { } } @Override public void parse(Message m) { String target = m.param(); if(!m.param().startsWith("#")) target = m.sender(); if(m.botCommand().equals("pastatopic")){ if(Info.hasUserInfo(m.sender())){ if(Info.getChannelInfo("#pasta").has(m.sender())){ if(Info.getChannelInfo("#pasta").getModes(m.sender()).contains("~") || Info.getChannelInfo("#pasta").getModes(m.sender()).contains("&")){ topicmain = m.botParams(); write(); } else m.say(target, "You need to be at least AOP to use this command"); } } } if(m.command().equals("TOPIC")){ if(m.param().equals("#pasta")){ if(!m.trailing().startsWith(topicmain)){ Server.send("TOPIC #pasta :" + topicmain + " " + m.trailing()); } } } } private void write(){ try { PrintWriter writer = new PrintWriter(file); writer.println(topicmain); writer.close(); } catch (IOException e) {} } }
package net.imagej.ops.threshold.localSauvola; import net.imagej.ops.ComputerOp; import net.imagej.ops.OpService; import net.imagej.ops.Ops; import net.imagej.ops.Ops.Stats.Mean; import net.imagej.ops.Ops.Stats.StdDev; import net.imagej.ops.threshold.LocalThresholdMethod; import net.imglib2.type.logic.BitType; import net.imglib2.type.numeric.RealType; import net.imglib2.type.numeric.real.DoubleType; import net.imglib2.util.Pair; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; @Plugin(type = Ops.Threshold.LocalSauvola.class, name = Ops.Threshold.LocalSauvola.NAME) public class LocalSauvola<T extends RealType<T>> extends LocalThresholdMethod<T> implements Ops.Threshold.LocalSauvola { @Parameter private double k = 0.5d; @Parameter private double r = 0.5d; @Parameter private OpService ops; private ComputerOp<Iterable<T>, DoubleType> mean; private ComputerOp<Iterable<T>, DoubleType> stdDeviation; @Override public void initialize() { mean = ops().computer(Mean.class, new DoubleType(), in().getB()); stdDeviation = ops().computer(StdDev.class, new DoubleType(), in().getB()); } @Override public void compute(final Pair<T, Iterable<T>> input, final BitType output) { final DoubleType meanValue = new DoubleType(); mean.compute(input.getB(), meanValue); final DoubleType stdDevValue = new DoubleType(); stdDeviation.compute(input.getB(), stdDevValue); double threshold = meanValue.get() * (1.0d + k * ((Math.sqrt(stdDevValue.get())/r) - 1.0)); output.set(input.getA().getRealDouble() >= threshold); } }
package net.killermapper.roadstuff.common.blocks; import java.util.List; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.killermapper.roadstuff.common.RoadStuff; import net.killermapper.roadstuff.proxy.ClientProxy; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public class BlockCone extends Block { public static String[] subBlock = new String[] {"cone01", "cone02", "cone03"}; private IIcon top, sides, bottom, base, top2; public BlockCone() { super(Material.ground); this.setCreativeTab(RoadStuff.RoadStuffCreativeTabs); this.setStepSound(soundTypeMetal); } public void setBlockBoundsBasedOnState(IBlockAccess world, int x, int y, int z) { if(world.getBlockMetadata(x, y, z) == 0) { this.minX = 0.3F; this.minY = 0.0F; this.minZ = 0.3F; this.maxX = 0.7F; this.maxY = 1F; this.maxZ = 0.7F; } if(world.getBlockMetadata(x, y, z) == 2) { this.minX = 0.44F; this.minY = 0.0F; this.minZ = 0.44F; this.maxX = 0.56F; this.maxY = 1F; this.maxZ = 0.56F; } if(world.getBlockMetadata(x, y, z) == 1) { this.minX = 0.25F; this.minY = 0.0F; this.minZ = 0.25F; this.maxX = 0.75F; this.maxY = 0.875F; this.maxZ = 0.75F; } } public AxisAlignedBB getCollisionBoundingBoxFromPool(World p_149668_1_, int p_149668_2_, int p_149668_3_, int p_149668_4_) { this.setBlockBoundsBasedOnState(p_149668_1_, p_149668_2_, p_149668_3_, p_149668_4_); return super.getCollisionBoundingBoxFromPool(p_149668_1_, p_149668_2_, p_149668_3_, p_149668_4_); } public void registerBlockIcons(IIconRegister iiconRegister) { this.top = iiconRegister.registerIcon(RoadStuff.MODID + ":blockCone01Top"); this.sides = iiconRegister.registerIcon(RoadStuff.MODID + ":blockCone01"); this.bottom = iiconRegister.registerIcon(RoadStuff.MODID + ":blockConeBottom"); this.base = iiconRegister.registerIcon(RoadStuff.MODID + ":blockConeBase"); this.top2 = iiconRegister.registerIcon(RoadStuff.MODID + ":blockCone02Top"); } public int damageDropped(int metadata) { return metadata; } public void getSubBlocks(Item item, CreativeTabs tabs, List list) { for(int i = 0; i < subBlock.length; i++) { list.add(new ItemStack(item, 1, i)); } } public boolean renderAsNormalBlock() { return false; } public boolean isOpaqueCube() { return false; } @SideOnly(Side.CLIENT) public int getRenderType() { return ClientProxy.renderConeId; } @SideOnly(Side.CLIENT) public boolean shouldSideBeRendered(IBlockAccess blockAccess, int x, int y, int z, int side) { return true; } public IIcon getIcon(int side, int metadata) { if(metadata == 2) { if(side == 1) return this.base; } if(metadata == 0) { if(side == 1) return this.top; } if(metadata == 1) { if(side == 1) return this.top2; } if(side == 0) return this.bottom; return this.sides; } }
package net.snowflake.client.jdbc; import static net.snowflake.client.core.Constants.MB; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.databind.MappingJsonFactory; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.*; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import net.snowflake.client.core.*; import net.snowflake.client.jdbc.SnowflakeResultChunk.DownloadState; import net.snowflake.client.jdbc.telemetryOOB.TelemetryService; import net.snowflake.client.log.ArgSupplier; import net.snowflake.client.log.SFLogger; import net.snowflake.client.log.SFLoggerFactory; import net.snowflake.common.core.SqlState; import org.apache.arrow.memory.RootAllocator; public class SnowflakeChunkDownloader implements ChunkDownloader { // object mapper for deserialize JSON private static final ObjectMapper mapper = ObjectMapperFactory.getObjectMapper(); /** a shared JSON parser factory. */ private static final JsonFactory jsonFactory = new MappingJsonFactory(); private static final SFLogger logger = SFLoggerFactory.getLogger(SnowflakeChunkDownloader.class); private static final int STREAM_BUFFER_SIZE = MB; private static final long SHUTDOWN_TIME = 3; private final SnowflakeConnectString snowflakeConnectionString; private final OCSPMode ocspMode; // Session object, used solely for throwing exceptions. CAUTION: MAY BE NULL! private SFBaseSession session; private JsonResultChunk.ResultChunkDataCache chunkDataCache = new JsonResultChunk.ResultChunkDataCache(); private List<SnowflakeResultChunk> chunks; // index of next chunk to be consumed (it may not be ready yet) private int nextChunkToConsume = 0; // index of next chunk to be downloaded private int nextChunkToDownload = 0; // number of prefetch slots private final int prefetchSlots; // thread pool private final ThreadPoolExecutor executor; // number of millis main thread waiting for chunks from downloader private long numberMillisWaitingForChunks = 0; // is the downloader terminated private final AtomicBoolean terminated = new AtomicBoolean(false); // number of millis spent on downloading result chunks private final AtomicLong totalMillisDownloadingChunks = new AtomicLong(0); // number of millis spent on parsing result chunks private final AtomicLong totalMillisParsingChunks = new AtomicLong(0); // The query result master key private final String qrmk; private Map<String, String> chunkHeadersMap; private final int networkTimeoutInMilli; private long memoryLimit; // the current memory usage across JVM private static final AtomicLong currentMemoryUsage = new AtomicLong(); // used to track the downloading threads private Map<Integer, Future> downloaderFutures = new ConcurrentHashMap<>(); /** query result format */ private QueryResultFormat queryResultFormat; /** Arrow memory allocator for the current resultSet */ private RootAllocator rootAllocator; static long getCurrentMemoryUsage() { synchronized (currentMemoryUsage) { return currentMemoryUsage.longValue(); } } // The parameters used to wait for available memory: // starting waiting time will be BASE_WAITING_MS * WAITING_SECS_MULTIPLIER = 100 ms private long BASE_WAITING_MS = 50; private long WAITING_SECS_MULTIPLIER = 2; // the maximum waiting time private long MAX_WAITING_MS = 30 * 1000; // the default jitter ratio 10% private long WAITING_JITTER_RATIO = 10; private final ResultStreamProvider resultStreamProvider; /** Timeout that the main thread waits for downloading the current chunk */ private static final long downloadedConditionTimeoutInSeconds = HttpUtil.getDownloadedConditionTimeoutInSeconds(); private static final int MAX_NUM_OF_RETRY = 10; private static final int MAX_RETRY_JITTER = 1000; // milliseconds private static Throwable injectedDownloaderException = null; // for testing purpose // This function should only be used for testing purpose static void setInjectedDownloaderException(Throwable th) { injectedDownloaderException = th; } public OCSPMode getOCSPMode() { return ocspMode; } public ResultStreamProvider getResultStreamProvider() { return resultStreamProvider; } /** * Create a pool of downloader threads. * * @param threadNamePrefix name of threads in pool * @param parallel number of thread in pool * @return new thread pool */ private static ThreadPoolExecutor createChunkDownloaderExecutorService( final String threadNamePrefix, final int parallel) { ThreadFactory threadFactory = new ThreadFactory() { private int threadCount = 1; public Thread newThread(final Runnable r) { final Thread thread = new Thread(r); thread.setName(threadNamePrefix + threadCount++); thread.setUncaughtExceptionHandler( new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { logger.error("uncaughtException in thread: " + t + " {}", e); } }); thread.setDaemon(true); return thread; } }; return (ThreadPoolExecutor) Executors.newFixedThreadPool(parallel, threadFactory); } /** * Constructor to initialize downloader, which uses the default stream provider * * @param resultSetSerializable the result set serializable object which includes required * metadata to start chunk downloader */ public SnowflakeChunkDownloader(SnowflakeResultSetSerializableV1 resultSetSerializable) throws SnowflakeSQLException { this.snowflakeConnectionString = resultSetSerializable.getSnowflakeConnectString(); this.ocspMode = resultSetSerializable.getOCSPMode(); this.qrmk = resultSetSerializable.getQrmk(); this.networkTimeoutInMilli = resultSetSerializable.getNetworkTimeoutInMilli(); this.prefetchSlots = resultSetSerializable.getResultPrefetchThreads() * 2; this.memoryLimit = resultSetSerializable.getMemoryLimit(); this.queryResultFormat = resultSetSerializable.getQueryResultFormat(); logger.debug("qrmk = {}", this.qrmk); this.chunkHeadersMap = resultSetSerializable.getChunkHeadersMap(); // session may be null. Its only use is for in-band telemetry in this class this.session = (resultSetSerializable.getSession() != null) ? resultSetSerializable.getSession().orElse(null) : null; // create the chunks array this.chunks = new ArrayList<>(resultSetSerializable.getChunkFileCount()); this.resultStreamProvider = resultSetSerializable.getResultStreamProvider(); if (resultSetSerializable.getChunkFileCount() < 1) { throw new SnowflakeSQLLoggedException( this.session, ErrorCode.INTERNAL_ERROR, "Incorrect chunk count: " + resultSetSerializable.getChunkFileCount()); } // initialize chunks with url and row count for (SnowflakeResultSetSerializableV1.ChunkFileMetadata chunkFileMetadata : resultSetSerializable.getChunkFileMetadatas()) { SnowflakeResultChunk chunk; switch (this.queryResultFormat) { case ARROW: this.rootAllocator = resultSetSerializable.getRootAllocator(); chunk = new ArrowResultChunk( chunkFileMetadata.getFileURL(), chunkFileMetadata.getRowCount(), resultSetSerializable.getColumnCount(), chunkFileMetadata.getUncompressedByteSize(), this.rootAllocator, this.session); break; case JSON: chunk = new JsonResultChunk( chunkFileMetadata.getFileURL(), chunkFileMetadata.getRowCount(), resultSetSerializable.getColumnCount(), chunkFileMetadata.getUncompressedByteSize(), this.session); break; default: throw new SnowflakeSQLLoggedException( this.session, ErrorCode.INTERNAL_ERROR, "Invalid result format: " + queryResultFormat.name()); } logger.debug( "add chunk, url={} rowCount={} uncompressedSize={} " + "neededChunkMemory={}, chunkResultFormat={}", chunk.getScrubbedUrl(), chunk.getRowCount(), chunk.getUncompressedSize(), chunk.computeNeededChunkMemory(), queryResultFormat.name()); chunks.add(chunk); } // prefetch threads and slots from parameter settings int effectiveThreads = Math.min( resultSetSerializable.getResultPrefetchThreads(), resultSetSerializable.getChunkFileCount()); logger.debug( "#chunks: {} #threads:{} #slots:{} -> pool:{}", resultSetSerializable.getChunkFileCount(), resultSetSerializable.getResultPrefetchThreads(), prefetchSlots, effectiveThreads); // create thread pool executor = createChunkDownloaderExecutorService("result-chunk-downloader-", effectiveThreads); try { startNextDownloaders(); } catch (OutOfMemoryError outOfMemoryError) { logOutOfMemoryError(); StringWriter errors = new StringWriter(); outOfMemoryError.printStackTrace(new PrintWriter(errors)); throw new SnowflakeSQLLoggedException( this.session, ErrorCode.INTERNAL_ERROR.getMessageCode(), SqlState.INTERNAL_ERROR, errors); } } /** Submit download chunk tasks to executor. Number depends on thread and memory limit */ private void startNextDownloaders() throws SnowflakeSQLException { long waitingTime = BASE_WAITING_MS; // submit the chunks to be downloaded up to the prefetch slot capacity // and limited by memory while (nextChunkToDownload - nextChunkToConsume < prefetchSlots && nextChunkToDownload < chunks.size()) { // check if memory limit allows more prefetching final SnowflakeResultChunk nextChunk = chunks.get(nextChunkToDownload); final long neededChunkMemory = nextChunk.computeNeededChunkMemory(); // make sure memoryLimit > neededChunkMemory; otherwise, the thread hangs if (neededChunkMemory > memoryLimit) { logger.debug( "Thread {}: reset memoryLimit from {} MB to current chunk size {} MB", (ArgSupplier) () -> Thread.currentThread().getId(), (ArgSupplier) () -> memoryLimit / 1024 / 1024, (ArgSupplier) () -> neededChunkMemory / 1024 / 1024); memoryLimit = neededChunkMemory; } // try to reserve the needed memory long curMem = currentMemoryUsage.addAndGet(neededChunkMemory); // no memory allocate when memory is not enough for prefetch if (curMem > memoryLimit && nextChunkToDownload - nextChunkToConsume > 0) { // cancel the reserved memory and this downloader too currentMemoryUsage.addAndGet(-neededChunkMemory); break; } // only allocate memory when the future usage is less than the limit if (curMem <= memoryLimit) { if (queryResultFormat == QueryResultFormat.JSON) { ((JsonResultChunk) nextChunk).tryReuse(chunkDataCache); } logger.debug( "Thread {}: currentMemoryUsage in MB: {}, nextChunkToDownload: {}, " + "nextChunkToConsume: {}, newReservedMemory in B: {} ", (ArgSupplier) () -> Thread.currentThread().getId(), curMem / MB, nextChunkToDownload, nextChunkToConsume, neededChunkMemory); logger.debug( "submit chunk #{} for downloading, url={}", this.nextChunkToDownload, nextChunk.getScrubbedUrl()); Future downloaderFuture = executor.submit( getDownloadChunkCallable( this, nextChunk, qrmk, nextChunkToDownload, chunkHeadersMap, networkTimeoutInMilli, this.session)); downloaderFutures.put(nextChunkToDownload, downloaderFuture); // increment next chunk to download nextChunkToDownload++; // make sure reset waiting time waitingTime = BASE_WAITING_MS; // go to next chunk continue; } else { // cancel the reserved memory curMem = currentMemoryUsage.addAndGet(-neededChunkMemory); } // waiting when nextChunkToDownload is equal to nextChunkToConsume but reach memory limit try { waitingTime *= WAITING_SECS_MULTIPLIER; waitingTime = waitingTime > MAX_WAITING_MS ? MAX_WAITING_MS : waitingTime; long jitter = ThreadLocalRandom.current().nextLong(0, waitingTime / WAITING_JITTER_RATIO); waitingTime += jitter; if (logger.isDebugEnabled()) { logger.debug( "Thread {} waiting for {}s: currentMemoryUsage in MB: {}, neededChunkMemory in MB: {}, " + "nextChunkToDownload: {}, nextChunkToConsume: {} ", (ArgSupplier) () -> Thread.currentThread().getId(), waitingTime / 1000.0, curMem / MB, neededChunkMemory / MB, nextChunkToDownload, nextChunkToConsume); } Thread.sleep(waitingTime); } catch (InterruptedException ie) { throw new SnowflakeSQLException( SqlState.INTERNAL_ERROR, ErrorCode.INTERNAL_ERROR.getMessageCode(), "Waiting SnowflakeChunkDownloader has been interrupted."); } } // clear the cache, we can't download more at the moment // so we won't need them in the near future chunkDataCache.clear(); } /** * release the memory usage from currentMemoryUsage * * @param chunkId chunk ID * @param optionalReleaseSize if present, then release the specified size */ private void releaseCurrentMemoryUsage(int chunkId, Optional<Long> optionalReleaseSize) { long releaseSize = optionalReleaseSize.isPresent() ? optionalReleaseSize.get() : chunks.get(chunkId).computeNeededChunkMemory(); if (releaseSize > 0 && !chunks.get(chunkId).isReleased()) { // has to be before reusing the memory long curMem = currentMemoryUsage.addAndGet(-releaseSize); logger.debug( "Thread {}: currentMemoryUsage in MB: {}, released in MB: {}, " + "chunk: {}, optionalReleaseSize: {}, JVMFreeMem: {}", (ArgSupplier) () -> Thread.currentThread().getId(), (ArgSupplier) () -> curMem / MB, releaseSize, chunkId, optionalReleaseSize.isPresent(), Runtime.getRuntime().freeMemory()); chunks.get(chunkId).setReleased(); } } /** release all existing chunk memory usage before close */ private void releaseAllChunkMemoryUsage() { if (chunks == null || chunks.size() == 0) { return; } // only release the chunks has been downloading or downloaded for (int i = 0; i < nextChunkToDownload; i++) { releaseCurrentMemoryUsage(i, Optional.empty()); } } /** * The method does the following: * * <p>1. free the previous chunk data and submit a new chunk to be downloaded * * <p>2. get next chunk to consume, if it is not ready for consumption, it waits until it is ready * * @return next SnowflakeResultChunk to be consumed * @throws InterruptedException if downloading thread was interrupted * @throws SnowflakeSQLException if downloader encountered an error */ public SnowflakeResultChunk getNextChunkToConsume() throws InterruptedException, SnowflakeSQLException { // free previous chunk data and submit a new chunk for downloading if (this.nextChunkToConsume > 0) { int prevChunk = this.nextChunkToConsume - 1; // free the chunk data for previous chunk logger.debug("free chunk data for chunk #{}", prevChunk); long chunkMemUsage = chunks.get(prevChunk).computeNeededChunkMemory(); // reuse chunkcache if json result if (this.queryResultFormat == QueryResultFormat.JSON) { if (this.nextChunkToDownload < this.chunks.size()) { // Reuse the set of object to avoid reallocation // It is important to do this BEFORE starting the next download chunkDataCache.add((JsonResultChunk) this.chunks.get(prevChunk)); } else { // clear the cache if we don't need it anymore chunkDataCache.clear(); } } // Free any memory the previous chunk might hang on this.chunks.get(prevChunk).freeData(); releaseCurrentMemoryUsage(prevChunk, Optional.of(chunkMemUsage)); } // if no more chunks, return null if (this.nextChunkToConsume >= this.chunks.size()) { logger.debug("no more chunk"); return null; } // prefetch next chunks try { startNextDownloaders(); } catch (OutOfMemoryError outOfMemoryError) { logOutOfMemoryError(); StringWriter errors = new StringWriter(); outOfMemoryError.printStackTrace(new PrintWriter(errors)); throw new SnowflakeSQLLoggedException( this.session, ErrorCode.INTERNAL_ERROR.getMessageCode(), SqlState.INTERNAL_ERROR, errors); } SnowflakeResultChunk currentChunk = this.chunks.get(nextChunkToConsume); if (currentChunk.getDownloadState() == DownloadState.SUCCESS) { logger.debug("chunk #{} is ready to consume", nextChunkToConsume); nextChunkToConsume++; if (nextChunkToConsume == this.chunks.size()) { // make sure to release the last chunk releaseCurrentMemoryUsage(nextChunkToConsume - 1, Optional.empty()); } return currentChunk; } else { // the chunk we want to consume is not ready yet, wait for it currentChunk.getLock().lock(); try { logger.debug("#chunk{} is not ready to consume", nextChunkToConsume); logger.debug("consumer get lock to check chunk state"); waitForChunkReady(currentChunk); // downloader thread encountered an error if (currentChunk.getDownloadState() == DownloadState.FAILURE) { releaseAllChunkMemoryUsage(); logger.error("downloader encountered error: {}", currentChunk.getDownloadError()); if (currentChunk .getDownloadError() .contains("java.lang.OutOfMemoryError: Java heap space")) { logOutOfMemoryError(); } throw new SnowflakeSQLLoggedException( this.session, ErrorCode.INTERNAL_ERROR.getMessageCode(), SqlState.INTERNAL_ERROR, currentChunk.getDownloadError()); } logger.debug("#chunk{} is ready to consume", nextChunkToConsume); nextChunkToConsume++; // next chunk to consume is ready for consumption return currentChunk; } finally { logger.debug("consumer free lock"); boolean terminateDownloader = (currentChunk.getDownloadState() == DownloadState.FAILURE); // release the unlock always currentChunk.getLock().unlock(); if (nextChunkToConsume == this.chunks.size()) { // make sure to release the last chunk releaseCurrentMemoryUsage(nextChunkToConsume - 1, Optional.empty()); } if (terminateDownloader) { logger.debug("Download result fail. Shut down the chunk downloader"); terminate(); } } } } /** * wait for the current chunk to be ready to consume if the downloader fails then let it retry for * at most 10 times if the downloader is in progress for at most one hour or the downloader has * already retried more than 10 times, then throw an exception. * * @param currentChunk * @throws InterruptedException */ private void waitForChunkReady(SnowflakeResultChunk currentChunk) throws InterruptedException { int retry = 0; long startTime = System.currentTimeMillis(); while (currentChunk.getDownloadState() != DownloadState.SUCCESS && retry < MAX_NUM_OF_RETRY) { logger.debug( "Thread {} is waiting for #chunk{} to be ready, current" + "chunk state is: {}, retry={}", Thread.currentThread().getId(), nextChunkToConsume, currentChunk.getDownloadState(), retry); if (currentChunk.getDownloadState() != DownloadState.FAILURE) { // if the state is not failure, we should keep waiting; otherwise, we skip waiting if (!currentChunk .getDownloadCondition() .await(downloadedConditionTimeoutInSeconds, TimeUnit.SECONDS)) { // if the current chunk has not condition change over the timeout (which is rare) logger.debug( "Thread {} is timeout for waiting #chunk{} to be ready, current" + "chunk state is: {}, retry={}", Thread.currentThread().getId(), nextChunkToConsume, currentChunk.getDownloadState(), retry); currentChunk.setDownloadState(DownloadState.FAILURE); currentChunk.setDownloadError( String.format( "Timeout waiting for the download of #chunk%d" + "(Total chunks: %d) retry=%d", nextChunkToConsume, this.chunks.size(), retry)); break; } } if (currentChunk.getDownloadState() != DownloadState.SUCCESS) { // timeout or failed retry++; logger.debug( "Since downloadState is {} Thread {} decides to retry {} time(s) for #chunk{}", currentChunk.getDownloadState(), Thread.currentThread().getId(), retry, nextChunkToConsume); Future downloaderFuture = downloaderFutures.get(nextChunkToConsume); if (downloaderFuture != null) { downloaderFuture.cancel(true); } HttpUtil.closeExpiredAndIdleConnections(); chunks.get(nextChunkToConsume).getLock().lock(); try { chunks.get(nextChunkToConsume).setDownloadState(DownloadState.IN_PROGRESS); chunks.get(nextChunkToConsume).reset(); } finally { chunks.get(nextChunkToConsume).getLock().unlock(); } // random jitter before start next retry Thread.sleep(new Random().nextInt(MAX_RETRY_JITTER)); downloaderFuture = executor.submit( getDownloadChunkCallable( this, chunks.get(nextChunkToConsume), qrmk, nextChunkToConsume, chunkHeadersMap, networkTimeoutInMilli, session)); downloaderFutures.put(nextChunkToDownload, downloaderFuture); } } if (currentChunk.getDownloadState() == DownloadState.SUCCESS) { logger.debug("ready to consume #chunk{}, succeed retry={}", nextChunkToConsume, retry); } else if (retry >= MAX_NUM_OF_RETRY) { // stop retrying and report failure currentChunk.setDownloadState(DownloadState.FAILURE); currentChunk.setDownloadError( String.format( "Max retry reached for the download of #chunk%d " + "(Total chunks: %d) retry=%d, error=%s", nextChunkToConsume, this.chunks.size(), retry, chunks.get(nextChunkToConsume).getDownloadError())); } this.numberMillisWaitingForChunks += (System.currentTimeMillis() - startTime); } /** log out of memory error and provide the suggestion to avoid this error */ private void logOutOfMemoryError() { logger.error( "Dump some crucial information below:\n" + "Total milliseconds waiting for chunks: {},\n" + "Total memory used: {}, Max heap size: {}, total download time: {} millisec,\n" + "total parsing time: {} milliseconds, total chunks: {},\n" + "currentMemoryUsage in Byte: {}, currentMemoryLimit in Bytes: {} \n" + "nextChunkToDownload: {}, nextChunkToConsume: {}\n" + "Several suggestions to try to resolve the OOM issue:\n" + "1. increase the JVM heap size if you have more space; or \n" + "2. use CLIENT_MEMORY_LIMIT to reduce the memory usage by the JDBC driver " + "(https://docs.snowflake.net/manuals/sql-reference/parameters.html#client-memory-limit)" + "3. please make sure 2 * CLIENT_PREFETCH_THREADS * CLIENT_RESULT_CHUNK_SIZE < CLIENT_MEMORY_LIMIT. " + "If not, please reduce CLIENT_PREFETCH_THREADS and CLIENT_RESULT_CHUNK_SIZE too.", numberMillisWaitingForChunks, Runtime.getRuntime().totalMemory(), Runtime.getRuntime().maxMemory(), totalMillisDownloadingChunks.get(), totalMillisParsingChunks.get(), chunks.size(), currentMemoryUsage, memoryLimit, nextChunkToDownload, nextChunkToConsume); } /** * terminate the downloader * * @return chunk downloader metrics collected over instance lifetime */ @Override public DownloaderMetrics terminate() throws InterruptedException { if (!terminated.getAndSet(true)) { try { if (executor != null) { if (!executor.isShutdown()) { // cancel running downloaders downloaderFutures.forEach((k, v) -> v.cancel(true)); // shutdown executor executor.shutdown(); if (!executor.awaitTermination(SHUTDOWN_TIME, TimeUnit.SECONDS)) { logger.debug("Executor did not terminate in the specified time."); List<Runnable> droppedTasks = executor.shutdownNow(); // optional ** logger.debug( "Executor was abruptly shut down. " + droppedTasks.size() + " tasks will not be executed."); // optional ** } } // Normal flow will never hit here. This is only for testing purposes if (SnowflakeChunkDownloader.injectedDownloaderException != null && injectedDownloaderException instanceof InterruptedException) { throw (InterruptedException) SnowflakeChunkDownloader.injectedDownloaderException; } } logger.debug( "Total milliseconds waiting for chunks: {}, " + "Total memory used: {}, total download time: {} millisec, " + "total parsing time: {} milliseconds, total chunks: {}", numberMillisWaitingForChunks, Runtime.getRuntime().totalMemory(), totalMillisDownloadingChunks.get(), totalMillisParsingChunks.get(), chunks.size()); return new DownloaderMetrics( numberMillisWaitingForChunks, totalMillisDownloadingChunks.get(), totalMillisParsingChunks.get()); } finally { for (SnowflakeResultChunk chunk : chunks) { // explicitly free each chunk since Arrow chunk may hold direct memory chunk.freeData(); } if (queryResultFormat == QueryResultFormat.ARROW) { SFArrowResultSet.closeRootAllocator(rootAllocator); } else { chunkDataCache.clear(); } releaseAllChunkMemoryUsage(); chunks = null; } } return null; } /** * add download time * * @param downloadTime Time for downloading a single chunk */ private void addDownloadTime(long downloadTime) { this.totalMillisDownloadingChunks.addAndGet(downloadTime); } /** * add parsing time * * @param parsingTime Time for parsing a single chunk */ private void addParsingTime(long parsingTime) { this.totalMillisParsingChunks.addAndGet(parsingTime); } /** * Create a download callable that will be run in download thread * * @param downloader object to download the chunk * @param resultChunk object contains information about the chunk will be downloaded * @param qrmk Query Result Master Key * @param chunkIndex the index of the chunk which will be downloaded in array chunks. This is * mainly for logging purpose * @param chunkHeadersMap contains headers needed to be added when downloading from s3 * @param networkTimeoutInMilli network timeout * @return A callable responsible for downloading chunk */ private static Callable<Void> getDownloadChunkCallable( final SnowflakeChunkDownloader downloader, final SnowflakeResultChunk resultChunk, final String qrmk, final int chunkIndex, final Map<String, String> chunkHeadersMap, final int networkTimeoutInMilli, final SFBaseSession session) { ChunkDownloadContext downloadContext = new ChunkDownloadContext( downloader, resultChunk, qrmk, chunkIndex, chunkHeadersMap, networkTimeoutInMilli, session); return new Callable<Void>() { /** * Read the input stream and parse chunk data into memory * * @param inputStream * @throws SnowflakeSQLException */ private void downloadAndParseChunk(InputStream inputStream) throws SnowflakeSQLException { // remember the download time resultChunk.setDownloadTime(System.currentTimeMillis() - startTime); downloader.addDownloadTime(resultChunk.getDownloadTime()); startTime = System.currentTimeMillis(); // parse the result json try { if (downloader.queryResultFormat == QueryResultFormat.ARROW) { ((ArrowResultChunk) resultChunk).readArrowStream(inputStream); } else { parseJsonToChunkV2(inputStream, resultChunk); } } catch (Exception ex) { logger.debug( "Thread {} Exception when parsing result #chunk{}: {}", Thread.currentThread().getId(), chunkIndex, ex.getLocalizedMessage()); throw new SnowflakeSQLLoggedException( session, SqlState.INTERNAL_ERROR, ErrorCode.INTERNAL_ERROR.getMessageCode(), ex, "Exception: " + ex.getLocalizedMessage()); } finally { // close the buffer reader will close underlying stream logger.debug( "Thread {} close input stream for #chunk{}", Thread.currentThread().getId(), chunkIndex); try { inputStream.close(); } catch (IOException ex) { throw new SnowflakeSQLLoggedException( session, SqlState.INTERNAL_ERROR, ErrorCode.INTERNAL_ERROR.getMessageCode(), ex, "Exception: " + ex.getLocalizedMessage()); } } // add parsing time resultChunk.setParseTime(System.currentTimeMillis() - startTime); downloader.addParsingTime(resultChunk.getParseTime()); } private long startTime; public Void call() { resultChunk.getLock().lock(); try { resultChunk.setDownloadState(DownloadState.IN_PROGRESS); } finally { resultChunk.getLock().unlock(); } logger.debug( "Downloading #chunk{}, url={}, Thread {}", chunkIndex, resultChunk.getUrl(), Thread.currentThread().getId()); startTime = System.currentTimeMillis(); // initialize the telemetry service for this downloader thread using the main telemetry // service TelemetryService.getInstance().updateContext(downloader.snowflakeConnectionString); try { if (SnowflakeChunkDownloader.injectedDownloaderException != null) { // Normal flow will never hit here. This is only for testing purpose throw SnowflakeChunkDownloader.injectedDownloaderException; } InputStream is = downloader.getResultStreamProvider().getInputStream(downloadContext); logger.debug( "Thread {} start downloading #chunk{}", Thread.currentThread().getId(), chunkIndex); downloadAndParseChunk(is); logger.debug( "Thread {} finish downloading #chunk{}", Thread.currentThread().getId(), chunkIndex); downloader.downloaderFutures.remove(chunkIndex); logger.debug( "Finished preparing chunk data for {}, " + "total download time={}ms, total parse time={}ms", resultChunk.getScrubbedUrl(), resultChunk.getDownloadTime(), resultChunk.getParseTime()); resultChunk.getLock().lock(); try { logger.debug("get lock to change the chunk to be ready to consume"); logger.debug("wake up consumer if it is waiting for a chunk to be " + "ready"); resultChunk.setDownloadState(DownloadState.SUCCESS); resultChunk.getDownloadCondition().signal(); } finally { logger.debug("Downloaded #chunk{}, free lock", chunkIndex); resultChunk.getLock().unlock(); } } catch (Throwable th) { resultChunk.getLock().lock(); try { logger.debug("get lock to set chunk download error"); resultChunk.setDownloadState(DownloadState.FAILURE); downloader.releaseCurrentMemoryUsage(chunkIndex, Optional.empty()); StringWriter errors = new StringWriter(); th.printStackTrace(new PrintWriter(errors)); resultChunk.setDownloadError(errors.toString()); logger.debug("wake up consumer if it is waiting for a chunk to be ready"); resultChunk.getDownloadCondition().signal(); } finally { logger.debug("Failed to download #chunk{}, free lock", chunkIndex); resultChunk.getLock().unlock(); } logger.debug( "Thread {} Exception encountered ({}:{}) fetching #chunk{} from: {}, Error {}", Thread.currentThread().getId(), th.getClass().getName(), th.getLocalizedMessage(), chunkIndex, resultChunk.getScrubbedUrl(), resultChunk.getDownloadError()); } return null; } private void parseJsonToChunkV2(InputStream jsonInputStream, SnowflakeResultChunk resultChunk) throws IOException, SnowflakeSQLException { /* * This is a hand-written binary parser that * handle. * [ "c1", "c2", null, ... ], * [ null, "c2", "c3", ... ], * ... * [ "c1", "c2", "c3", ... ], * in UTF-8 * The number of rows is known and the number of expected columns * is also known. */ ResultJsonParserV2 jp = new ResultJsonParserV2(); jp.startParsing((JsonResultChunk) resultChunk, session); byte[] buf = new byte[STREAM_BUFFER_SIZE]; int len; logger.debug( "Thread {} start to read inputstream for #chunk{}", Thread.currentThread().getId(), chunkIndex); while ((len = jsonInputStream.read(buf)) != -1) { jp.continueParsing(ByteBuffer.wrap(buf, 0, len), session); } logger.debug( "Thread {} finish reading inputstream for #chunk{}", Thread.currentThread().getId(), chunkIndex); jp.endParsing(session); } }; } /** This is a No Operation chunk downloader to avoid potential null pointer exception */ public static class NoOpChunkDownloader implements ChunkDownloader { @Override public SnowflakeResultChunk getNextChunkToConsume() throws SnowflakeSQLException { return null; } @Override public DownloaderMetrics terminate() { return null; } } }
package org.apache.camel.component.hzqueue; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IQueue; import org.apache.camel.Consumer; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.component.hzqueue.utils.HzInstanceRegistry; import org.apache.camel.impl.DefaultEndpoint; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriParam; import org.apache.camel.spi.UriPath; /** * Represents a HzQueue endpoint. */ @UriEndpoint(scheme = "hz-queue", title = "HzQueue", syntax="hz-queue:name", consumerClass = HzQueueConsumer.class, label = "HzQueue") public class HzQueueEndpoint extends DefaultEndpoint { private final HazelcastInstance hzInstance; private final IQueue<Object> queue; @UriPath @Metadata(required = "true") private String name; @UriParam(defaultValue = "hz-instance-0") private String hzInstanceName = HzInstanceRegistry.defaultHzInstanceName; @UriParam(defaultValue = "10") private int concurrentConsumers = 1; @UriParam(defaultValue = "10") private int backoffIdleThreshold = 3; @UriParam(defaultValue = "10") private int backoffErrorThreshold = 3; @UriParam(defaultValue = "5") private int backoffMultiplier = 3; @UriParam(defaultValue = "1000") private int poolingInterval = 1000; @UriParam(defaultValue = "", description = "endpoint consuming backoff given idle event") private String idleBackoffEventConsumer; @UriParam(defaultValue = "", description = "endpoint consuming backoff given error event") private String errorBackoffEventConsumer; @UriParam(defaultValue = "", description = "this will be ignored. added only for compatibility") private String transacted; public HzQueueEndpoint(String uri, HzQueueComponent component, HazelcastInstance hzInstance, String targetQueue) { super(uri, component); this.hzInstance = hzInstance; this.queue = hzInstance.getQueue(targetQueue); } public Producer createProducer() throws Exception { return new HzQueueProducer(this); } public Consumer createConsumer(Processor processor) throws Exception { return new HzQueueConsumer(this, processor); } public boolean isSingleton() { return true; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setConcurrentConsumers(int concurrentConsumers) { this.concurrentConsumers = concurrentConsumers; } public int getConcurrentConsumers() { return concurrentConsumers; } public int getBackoffErrorThreshold() { return backoffErrorThreshold; } public int getBackoffIdleThreshold() { return backoffIdleThreshold; } public void setBackoffIdleThreshold(int backoffIdleThreshold) { this.backoffIdleThreshold = backoffIdleThreshold; } public void setBackoffErrorThreshold(int backoffErrorThreshold) { this.backoffErrorThreshold = backoffErrorThreshold; } public int getBackoffMultiplier() { return backoffMultiplier; } public void setBackoffMultiplier(int backoffMultiplier) { this.backoffMultiplier = backoffMultiplier; } public int getPoolingInterval() { return poolingInterval; } public void setPoolingInterval(int poolingInterval) { this.poolingInterval = poolingInterval; } public String getHzInstanceName() { return hzInstanceName; } public void setHzInstanceName(String hzInstanceName) { this.hzInstanceName = hzInstanceName; } public HazelcastInstance getHzInstance() { return hzInstance; } public IQueue<Object> getQueue() { return queue; } public String getIdleBackoffEventConsumer() { return idleBackoffEventConsumer; } public void setIdleBackoffEventConsumer(String idleBackoffEventConsumer) { this.idleBackoffEventConsumer = idleBackoffEventConsumer; } public String getErrorBackoffEventConsumer() { return errorBackoffEventConsumer; } public void setErrorBackoffEventConsumer(String errorBackoffEventConsumer) { this.errorBackoffEventConsumer = errorBackoffEventConsumer; } public String getTransacted() { return transacted; } public void setTransacted(String transacted) { this.transacted = transacted; } }
package org.edmcouncil.rdf_toolkit.runner; import static org.edmcouncil.rdf_toolkit.runner.CommandLineOption.HELP; import static org.edmcouncil.rdf_toolkit.runner.CommandLineOption.SOURCE_DIRECTORY; import static org.edmcouncil.rdf_toolkit.runner.CommandLineOption.SOURCE_DIRECTORY_PATTERN; import static org.edmcouncil.rdf_toolkit.runner.CommandLineOption.TARGET_DIRECTORY; import static org.edmcouncil.rdf_toolkit.runner.CommandLineOption.TARGET_DIRECTORY_PATTERN; import static org.edmcouncil.rdf_toolkit.runner.CommandLineOption.VERSION; import static org.edmcouncil.rdf_toolkit.runner.RunningMode.EXIT; import static org.edmcouncil.rdf_toolkit.runner.RunningMode.PRINT_AND_EXIT; import static org.edmcouncil.rdf_toolkit.runner.RunningMode.PRINT_USAGE_AND_EXIT; import static org.edmcouncil.rdf_toolkit.runner.RunningMode.RUN_ON_DIRECTORY; import static org.edmcouncil.rdf_toolkit.runner.RunningMode.RUN_ON_FILE; import com.jcabi.manifests.Manifests; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.eclipse.rdf4j.model.*; import org.eclipse.rdf4j.model.impl.TreeModel; import org.eclipse.rdf4j.rio.RDFWriter; import org.eclipse.rdf4j.rio.Rio; import org.eclipse.rdf4j.sail.memory.model.MemValueFactory; import org.edmcouncil.rdf_toolkit.RdfFormatter; import org.edmcouncil.rdf_toolkit.io.DirectoryWalker; import org.edmcouncil.rdf_toolkit.runner.exception.RdfToolkitOptionHandlingException; import org.edmcouncil.rdf_toolkit.util.Constants; import org.edmcouncil.rdf_toolkit.writer.SortedRdfWriterFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.bind.SchemaOutputResolver; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RdfToolkitRunner { private static final Logger LOGGER = LoggerFactory.getLogger(RdfToolkitRunner.class); private final Options options; private final ValueFactory valueFactory; public RdfToolkitRunner() { this.options = CommandLineOption.prepareOptions(); this.valueFactory = new MemValueFactory(); } public void run(String[] args) throws Exception { var rdfToolkitOptions = handleArguments(args); switch (rdfToolkitOptions.getRunningMode()) { case PRINT_USAGE_AND_EXIT: case EXIT: // Usage was already printed, so we don't need to do it now return; case PRINT_AND_EXIT: System.out.println(rdfToolkitOptions.getOutput()); break; case RUN_ON_DIRECTORY: // Run the serializer over a directory of files runOnDirectory(rdfToolkitOptions.getCommandLine()); break; case RUN_ON_FILE: runOnFile(rdfToolkitOptions); break; default: throw new RdfToolkitOptionHandlingException("Unknown running mode: " + rdfToolkitOptions.getRunningMode()); } } private RdfToolkitOptions handleArguments(String[] args) throws ParseException, FileNotFoundException, RdfToolkitOptionHandlingException { var rdfToolkitOptions = new RdfToolkitOptions(args); // Parse the command line options. CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); rdfToolkitOptions.setCommandLine(line); var optionHandler = new OptionHandler(rdfToolkitOptions); // Print out version, if requested. if (line.hasOption(VERSION.getShortOpt())) { rdfToolkitOptions.setOutput(getVersion()); rdfToolkitOptions.setRunningMode(PRINT_AND_EXIT); return rdfToolkitOptions; } // Print out help, if requested. if (line.hasOption(HELP.getShortOpt())) { usage(options); rdfToolkitOptions.setRunningMode(EXIT); return rdfToolkitOptions; } optionHandler.handleRunningOnDirectory(line, rdfToolkitOptions); if (rdfToolkitOptions.getRunningMode() == PRINT_USAGE_AND_EXIT) { usage(options); return rdfToolkitOptions; } if (rdfToolkitOptions.getRunningMode() == RUN_ON_DIRECTORY) { return rdfToolkitOptions; } var sourceFile = optionHandler.handleSourceFile(); optionHandler.handleTargetFile(); optionHandler.handleBaseIri(valueFactory); optionHandler.handleIriReplacementOptions(); optionHandler.handleUseDtdSubset(); optionHandler.handleInlineBlankNodes(); optionHandler.handleInferBaseIri(); optionHandler.handleLeadingComments(); optionHandler.handleTrailingComments(); optionHandler.handleStringDataTyping(); optionHandler.handleOverrideStringLanguage(); optionHandler.handleIndent(); optionHandler.handleSourceFormat(sourceFile); optionHandler.handleTargetFormat(); optionHandler.handleShortUriPref(); optionHandler.handleLineEnd(); optionHandler.handleOmitXmlnsNamespace(); rdfToolkitOptions.setRunningMode(RUN_ON_FILE); return rdfToolkitOptions; } private String getVersion() { String implementationTitle = Manifests.read("Implementation-Title"); String implementationVersion = Manifests.read("Implementation-Version"); return String.format( "%s (%s version %s)", RdfFormatter.class.getSimpleName(), implementationTitle, implementationVersion); } private void runOnFile(RdfToolkitOptions rdfToolkitOptions) throws Exception { var sourceModel = readModel(rdfToolkitOptions); // Do any URI replacements if ((rdfToolkitOptions.getIriPattern() != null) && (rdfToolkitOptions.getIriReplacement() != null)) { Model replacedModel = new TreeModel(); for (Statement st : sourceModel) { Resource replacedSubject = st.getSubject(); if (replacedSubject instanceof IRI) { replacedSubject = valueFactory.createIRI( replacedSubject.stringValue().replaceFirst( rdfToolkitOptions.getIriPattern(), rdfToolkitOptions.getIriReplacement())); } IRI replacedPredicate = st.getPredicate(); replacedPredicate = valueFactory.createIRI( replacedPredicate.stringValue().replaceFirst( rdfToolkitOptions.getIriPattern(), rdfToolkitOptions.getIriReplacement())); Value replacedObject = st.getObject(); if (replacedObject instanceof IRI) { replacedObject = valueFactory.createIRI( replacedObject.stringValue().replaceFirst( rdfToolkitOptions.getIriPattern(), rdfToolkitOptions.getIriReplacement())); } Statement replacedStatement = valueFactory.createStatement(replacedSubject, replacedPredicate, replacedObject); replacedModel.add(replacedStatement); } // Do IRI replacements in namespaces as well. Set<Namespace> namespaces = sourceModel.getNamespaces(); for (Namespace namespace : namespaces) { replacedModel.setNamespace( namespace.getPrefix(), namespace.getName().replaceFirst( rdfToolkitOptions.getIriPattern(), rdfToolkitOptions.getIriReplacement())); } sourceModel = replacedModel; // This is also the right time to do IRI replacement in the base URI, if appropriate if (rdfToolkitOptions.getBaseIri() != null) { String newBaseIriString = rdfToolkitOptions.getBaseIriString().replaceFirst( rdfToolkitOptions.getIriPattern(), rdfToolkitOptions.getIriReplacement()); rdfToolkitOptions.setBaseIriString(newBaseIriString); rdfToolkitOptions.setBaseIri(valueFactory.createIRI(newBaseIriString)); } } //Replaced language serialization Model replaceModel = new TreeModel(); for (Statement st : sourceModel) { Value modelObject = st.getObject(); if (modelObject instanceof Literal) { var predicate = st.getPredicate(); var subject = st.getSubject(); Optional<String> lang = ((Literal) modelObject).getLanguage(); if (lang.isPresent()) { String langString = lang.get(); String[] langTab = langString.split("-"); langTab[1] = langTab[1].toUpperCase(); langString = String.join("-", langTab); String label = ((Literal) modelObject).getLabel(); Value replaceObject = valueFactory.createLiteral(label, langString); Statement statement = valueFactory.createStatement(subject, predicate, replaceObject); replaceModel.add(statement); } else { replaceModel.add(st); } } else { replaceModel.add(st); } } sourceModel = replaceModel; // Infer the base URI, if requested IRI inferredBaseIri = null; if (rdfToolkitOptions.getInferBaseIri()) { LinkedList<IRI> owlOntologyIris = new LinkedList<>(); for (Statement st : sourceModel) { if ((Constants.RDF_TYPE.equals(st.getPredicate())) && (Constants.owlOntology.equals(st.getObject())) && (st.getSubject() instanceof IRI)) { owlOntologyIris.add((IRI)st.getSubject()); } } if (!owlOntologyIris.isEmpty()) { Comparator<IRI> iriComparator = Comparator.comparing(IRI::toString); owlOntologyIris.sort(iriComparator); inferredBaseIri = owlOntologyIris.getFirst(); } } if (rdfToolkitOptions.getInferBaseIri() && (inferredBaseIri != null)) { rdfToolkitOptions.setBaseIri(inferredBaseIri); } OutputStream outputStream = System.out; if (!rdfToolkitOptions.isShouldUseStandardOutputStream()) { outputStream = new FileOutputStream(rdfToolkitOptions.getTargetFile()); } Writer targetWriter = new OutputStreamWriter( outputStream, StandardCharsets.UTF_8.name()); SortedRdfWriterFactory factory = new SortedRdfWriterFactory(rdfToolkitOptions.getTargetFormat()); RDFWriter rdfWriter = factory.getWriter(targetWriter, rdfToolkitOptions.getOptions()); Rio.write(sourceModel, rdfWriter); targetWriter.flush(); targetWriter.close(); } private Model readModel(RdfToolkitOptions rdfToolkitOptions) { Model sourceModel = null; try { sourceModel = Rio.parse( rdfToolkitOptions.getSourceInputStream(), rdfToolkitOptions.getBaseIriString(), rdfToolkitOptions.getRdf4jSourceFormat()); } catch (Exception t) { LOGGER.error("{}: stopped by unexpected exception:", RdfFormatter.class.getSimpleName()); LOGGER.error("Unable to parse input file: {}", rdfToolkitOptions.getSourceFile().getAbsolutePath()); LOGGER.error("Command line arguments: {}", Arrays.toString(rdfToolkitOptions.getArgs())); LOGGER.error("{}: {}", t.getClass().getSimpleName(), t.getMessage()); StringWriter stackTraceWriter = new StringWriter(); t.printStackTrace(new PrintWriter(stackTraceWriter)); LOGGER.error(stackTraceWriter.toString()); usage(options); System.exit(1); } return sourceModel; } private void runOnDirectory(CommandLine line) throws Exception { // Construct list of common arguments passed on to every invocation of 'run' ArrayList<String> commonArgsList = new ArrayList<>(); List<String> noPassArgs = Arrays.asList( SOURCE_DIRECTORY.getShortOpt(), SOURCE_DIRECTORY_PATTERN.getShortOpt(), TARGET_DIRECTORY.getShortOpt(), TARGET_DIRECTORY_PATTERN.getShortOpt()); for (Option option : line.getOptions()) { if (noPassArgs.contains(option.getOpt())) { continue; } commonArgsList.add(String.format("-%s", option.getOpt())); if (option.hasArg()) { commonArgsList.add(option.getValue()); } } // Check the input & output directories var sourceDir = new File(line.getOptionValue(SOURCE_DIRECTORY.getShortOpt())); if (!sourceDir.exists()) { LOGGER.error("Source directory does not exist: {}", sourceDir.getAbsolutePath()); return; } if (!sourceDir.canRead()) { LOGGER.error("Source directory is not readable: {}", sourceDir.getAbsolutePath()); return; } var sourceDirPattern = Pattern.compile(line.getOptionValue("sdp")); final File targetDir = new File(line.getOptionValue("td")); if (!targetDir.exists()) { targetDir.mkdirs(); } if (!targetDir.exists()) { LOGGER.error("Target directory could not be created: {}", targetDir.getAbsolutePath()); return; } if (!targetDir.canWrite()) { LOGGER.error("Target directory is not writable: {}", targetDir.getAbsolutePath()); return; } final String targetDirPatternString = line.getOptionValue("tdp"); // Iterate through matching files. final DirectoryWalker dw = new DirectoryWalker(sourceDir, sourceDirPattern); final String[] stringArray = new String[]{}; for (DirectoryWalker.DirectoryWalkerResult sourceResult : dw.pathMatches()) { // Construct output path. final Matcher sourceMatcher = sourceDirPattern.matcher(sourceResult.getRelativePath()); final String targetRelativePath = sourceMatcher.replaceFirst(targetDirPatternString); final File targetFile = new File(targetDir, targetRelativePath); // Run serializer List<String> runArgs = new ArrayList<>(); runArgs.addAll(commonArgsList); runArgs.add("-s"); runArgs.add(sourceResult.getFile().getAbsolutePath()); runArgs.add("-t"); runArgs.add(targetFile.getAbsolutePath()); LOGGER.info("... formatting '{}' to '{}' ...", sourceResult.getRelativePath(), targetRelativePath); run(runArgs.toArray(stringArray)); } } private void usage(Options options) { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(100); formatter.printHelp(getVersion(), options); } }
package org.jboss.remoting3.remote; import static org.jboss.remoting3.remote.RemoteLogger.log; import static org.xnio.Bits.anyAreSet; import java.io.IOException; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import javax.net.ssl.SSLSession; import org.jboss.remoting3.Channel; import org.jboss.remoting3.NotOpenException; import org.jboss.remoting3.ProtocolException; import org.jboss.remoting3.RemotingOptions; import org.jboss.remoting3.ServiceOpenException; import org.jboss.remoting3._private.Equaller; import org.jboss.remoting3._private.IntIndexHashMap; import org.jboss.remoting3._private.IntIndexMap; import org.jboss.remoting3.spi.AbstractHandleableCloseable; import org.jboss.remoting3.spi.ConnectionHandler; import org.jboss.remoting3.spi.ConnectionHandlerContext; import org.wildfly.security.auth.server.SecurityIdentity; import org.xnio.Bits; import org.xnio.Cancellable; import org.xnio.IoUtils; import org.xnio.OptionMap; import org.xnio.Pooled; import org.xnio.Result; import org.xnio.channels.ConnectedMessageChannel; import org.xnio.channels.SslChannel; @SuppressWarnings("deprecation") final class RemoteConnectionHandler extends AbstractHandleableCloseable<ConnectionHandler> implements ConnectionHandler { private final ConnectionHandlerContext connectionContext; private final RemoteConnection remoteConnection; /** * Channels. Remote channel IDs are read with a "1" MSB and written with a "0" MSB. * Local channel IDs are read with a "0" MSB and written with a "1" MSB. Channel IDs here * are stored from the "write" perspective. Remote channels "0", Local channels "1" MSB. */ private final IntIndexMap<RemoteConnectionChannel> channels = new IntIndexHashMap<RemoteConnectionChannel>(RemoteConnectionChannel.INDEXER, Equaller.IDENTITY); /** * Pending channels. All have a "1" MSB. Replies are read with a "0" MSB. */ private final IntIndexMap<PendingChannel> pendingChannels = new IntIndexHashMap<PendingChannel>(PendingChannel.INDEXER, Equaller.IDENTITY); private final int maxInboundChannels; private final int maxOutboundChannels; private final String remoteEndpointName; private final int behavior; private volatile int channelState = 0; private static final AtomicIntegerFieldUpdater<RemoteConnectionHandler> channelStateUpdater = AtomicIntegerFieldUpdater.newUpdater(RemoteConnectionHandler.class, "channelState"); /** Sending close request, now shutting down the write side of all channels and refusing new channels. Once send, received = true and count == 0, shut down writes on the socket. */ private static final int SENT_CLOSE_REQ = (1 << 31); /** Received close request. Send a close req if we haven't already done so. */ private static final int RECEIVED_CLOSE_REQ = (1 << 30); private static final int OUTBOUND_CHANNELS_MASK = (1 << 15) - 1; private static final int ONE_OUTBOUND_CHANNEL = 1; private static final int INBOUND_CHANNELS_MASK = ((1 << 30) - 1) & ~OUTBOUND_CHANNELS_MASK; private static final int ONE_INBOUND_CHANNEL = (1 << 15); RemoteConnectionHandler(final ConnectionHandlerContext connectionContext, final RemoteConnection remoteConnection, final int maxInboundChannels, final int maxOutboundChannels, final String remoteEndpointName, final int behavior) { super(remoteConnection.getExecutor()); this.connectionContext = connectionContext; this.remoteConnection = remoteConnection; this.maxInboundChannels = maxInboundChannels; this.maxOutboundChannels = maxOutboundChannels; this.remoteEndpointName = remoteEndpointName; this.behavior = behavior; } /** * The socket channel was closed with or without our consent. */ void handleConnectionClose() { remoteConnection.shutdownWrites(); closePendingChannels(); closeAllChannels(); } /** * Make this method visible. */ protected void closeComplete() { super.closeComplete(); remoteConnection.getRemoteConnectionProvider().removeConnectionHandler(this); } /** * A channel was closed, locally or remotely. * * @param channel the channel that was closed */ void handleChannelClosed(RemoteConnectionChannel channel) { int channelId = channel.getChannelId(); channels.remove(channel); boolean inbound = (channelId & 0x80000000) == 0; if (inbound) { handleInboundChannelClosed(); } else { handleOutboundChannelClosed(); } } void handleInboundChannelClosed() { int oldState; oldState = incrementState(-ONE_INBOUND_CHANNEL); if (oldState == (SENT_CLOSE_REQ | RECEIVED_CLOSE_REQ)) { log.tracef("Closed inbound channel on %s (shutting down)", this); remoteConnection.shutdownWrites(); } else { log.tracef("Closed inbound channel on %s", this); } } void handleOutboundChannelClosed() { int oldState; oldState = incrementState(-ONE_OUTBOUND_CHANNEL); if (oldState == (SENT_CLOSE_REQ | RECEIVED_CLOSE_REQ)) { log.tracef("Closed outbound channel on %s (shutting down)", this); remoteConnection.shutdownWrites(); } else { log.tracef("Closed outbound channel on %s", this); } } boolean handleInboundChannelOpen() { int oldState, newState; do { oldState = channelState; int oldCount = oldState & INBOUND_CHANNELS_MASK; if (oldCount == maxInboundChannels) { log.tracef("Refused inbound channel request on %s because too many inbound channels are open", this); return false; } if ((oldState & SENT_CLOSE_REQ) != 0) { log.tracef("Refused inbound channel request on %s because close request was sent", this); return false; } newState = oldState + ONE_INBOUND_CHANNEL; } while (!casState(oldState, newState)); log.tracef("Opened inbound channel on %s", this); return true; } void handleOutboundChannelOpen() throws IOException { int oldState, newState; do { oldState = channelState; int oldCount = oldState & OUTBOUND_CHANNELS_MASK; if (oldCount == maxOutboundChannels) { log.tracef("Refused outbound channel open on %s because too many outbound channels are open", this); throw new ProtocolException("Too many channels open"); } if ((oldState & SENT_CLOSE_REQ) != 0) { log.tracef("Refused outbound channel open on %s because close request was sent", this); throw new NotOpenException("Cannot open new channel because close was initiated"); } newState = oldState + ONE_OUTBOUND_CHANNEL; } while (!casState(oldState, newState)); log.tracef("Opened outbound channel on %s", this); } /** * The remote side requests a close of the whole channel. */ void receiveCloseRequest() { int oldState, newState; do { oldState = channelState; if ((oldState & RECEIVED_CLOSE_REQ) != 0) { // ignore duplicate, weird though it may be return; } newState = oldState | RECEIVED_CLOSE_REQ | SENT_CLOSE_REQ; } while (!casState(oldState, newState)); closePendingChannels(); log.tracef("Received remote close request on %s", this); if ((oldState & SENT_CLOSE_REQ) == 0) { sendCloseRequestBody(); closeAllChannels(); } if ((oldState & (INBOUND_CHANNELS_MASK | OUTBOUND_CHANNELS_MASK)) == 0) { remoteConnection.shutdownWrites(); } } void sendCloseRequest() { int oldState, newState; do { oldState = channelState; if ((oldState & SENT_CLOSE_REQ) != 0) { // idempotent close return; } newState = oldState | SENT_CLOSE_REQ; } while (!casState(oldState, newState)); log.tracef("Sending close request on %s", this); sendCloseRequestBody(); closeAllChannels(); if ((oldState & (INBOUND_CHANNELS_MASK | OUTBOUND_CHANNELS_MASK)) == 0) { remoteConnection.shutdownWrites(); } } private int incrementState(final int count) { final int oldState = channelStateUpdater.getAndAdd(this, count); if (log.isTraceEnabled()) { final int newState = oldState + count; log.tracef("CAS %s\n\told: RS=%s WS=%s IC=%d OC=%d\n\tnew: RS=%s WS=%s IC=%d OC=%d", this, Boolean.valueOf((oldState & RECEIVED_CLOSE_REQ) != 0), Boolean.valueOf((oldState & SENT_CLOSE_REQ) != 0), Integer.valueOf((oldState & INBOUND_CHANNELS_MASK) >> Integer.numberOfTrailingZeros(ONE_INBOUND_CHANNEL)), Integer.valueOf((oldState & OUTBOUND_CHANNELS_MASK) >> Integer.numberOfTrailingZeros(ONE_OUTBOUND_CHANNEL)), Boolean.valueOf((newState & RECEIVED_CLOSE_REQ) != 0), Boolean.valueOf((newState & SENT_CLOSE_REQ) != 0), Integer.valueOf((newState & INBOUND_CHANNELS_MASK) >> Integer.numberOfTrailingZeros(ONE_INBOUND_CHANNEL)), Integer.valueOf((newState & OUTBOUND_CHANNELS_MASK) >> Integer.numberOfTrailingZeros(ONE_OUTBOUND_CHANNEL)) ); } return oldState; } private boolean casState(final int oldState, final int newState) { final boolean result = channelStateUpdater.compareAndSet(this, oldState, newState); if (result && log.isTraceEnabled()) { log.tracef("CAS %s\n\told: RS=%s WS=%s IC=%d OC=%d\n\tnew: RS=%s WS=%s IC=%d OC=%d", this, Boolean.valueOf((oldState & RECEIVED_CLOSE_REQ) != 0), Boolean.valueOf((oldState & SENT_CLOSE_REQ) != 0), Integer.valueOf((oldState & INBOUND_CHANNELS_MASK) >> Integer.numberOfTrailingZeros(ONE_INBOUND_CHANNEL)), Integer.valueOf((oldState & OUTBOUND_CHANNELS_MASK) >> Integer.numberOfTrailingZeros(ONE_OUTBOUND_CHANNEL)), Boolean.valueOf((newState & RECEIVED_CLOSE_REQ) != 0), Boolean.valueOf((newState & SENT_CLOSE_REQ) != 0), Integer.valueOf((newState & INBOUND_CHANNELS_MASK) >> Integer.numberOfTrailingZeros(ONE_INBOUND_CHANNEL)), Integer.valueOf((newState & OUTBOUND_CHANNELS_MASK) >> Integer.numberOfTrailingZeros(ONE_OUTBOUND_CHANNEL)) ); } return result; } private void sendCloseRequestBody() { sendCloseRequestBody(remoteConnection); log.tracef("Sent close request on %s", this); } static void sendCloseRequestBody(RemoteConnection remoteConnection) { final Pooled<ByteBuffer> pooled = remoteConnection.allocate(); boolean ok = false; try { final ByteBuffer buffer = pooled.getResource(); buffer.put(Protocol.CONNECTION_CLOSE); buffer.flip(); remoteConnection.send(pooled, true); ok = true; } finally { if (! ok) { pooled.free(); } } } public Cancellable open(final String serviceType, final Result<Channel> result, final OptionMap optionMap) { log.tracef("Requesting service open of type %s on %s", serviceType, this); byte[] serviceTypeBytes = serviceType.getBytes(Protocol.UTF_8); final int serviceTypeLength = serviceTypeBytes.length; if (serviceTypeLength > 255) { log.tracef("Rejecting service open of type %s on %s due to service type name being too long", serviceType, this); result.setException(new ServiceOpenException("Service type name is too long")); return IoUtils.nullCancellable(); } int id; final OptionMap connectionOptionMap = remoteConnection.getOptionMap(); // Request the maximum outbound value if none was specified. final int outboundWindowSizeOptionValue = connectionOptionMap.get(RemotingOptions.TRANSMIT_WINDOW_SIZE, RemotingOptions.OUTGOING_CHANNEL_DEFAULT_TRANSMIT_WINDOW_SIZE); final int outboundMessageCountOptionValue = connectionOptionMap.get(RemotingOptions.MAX_OUTBOUND_MESSAGES, RemotingOptions.OUTGOING_CHANNEL_DEFAULT_MAX_OUTBOUND_MESSAGES); // Restrict the inbound value to defaults if none was specified. final int inboundWindowSizeOptionValue = connectionOptionMap.get(RemotingOptions.RECEIVE_WINDOW_SIZE, RemotingOptions.OUTGOING_CHANNEL_DEFAULT_RECEIVE_WINDOW_SIZE); final int inboundMessageCountOptionValue = connectionOptionMap.get(RemotingOptions.MAX_INBOUND_MESSAGES, RemotingOptions.DEFAULT_MAX_INBOUND_MESSAGES); // Request the maximum message size to defaults if none was specified. final long outboundMessageSizeOptionValue = connectionOptionMap.get(RemotingOptions.MAX_OUTBOUND_MESSAGE_SIZE, RemotingOptions.DEFAULT_MAX_OUTBOUND_MESSAGE_SIZE); final long inboundMessageSizeOptionValue = connectionOptionMap.get(RemotingOptions.MAX_INBOUND_MESSAGE_SIZE, RemotingOptions.DEFAULT_MAX_INBOUND_MESSAGE_SIZE); final int outboundWindowSize = optionMap.get(RemotingOptions.TRANSMIT_WINDOW_SIZE, outboundWindowSizeOptionValue); final int outboundMessageCount = optionMap.get(RemotingOptions.MAX_OUTBOUND_MESSAGES, outboundMessageCountOptionValue); final int inboundWindowSize = optionMap.get(RemotingOptions.RECEIVE_WINDOW_SIZE, inboundWindowSizeOptionValue); final int inboundMessageCount = optionMap.get(RemotingOptions.MAX_INBOUND_MESSAGES, inboundMessageCountOptionValue); final long outboundMessageSize = optionMap.get(RemotingOptions.MAX_OUTBOUND_MESSAGE_SIZE, outboundMessageSizeOptionValue); final long inboundMessageSize = optionMap.get(RemotingOptions.MAX_INBOUND_MESSAGE_SIZE, inboundMessageSizeOptionValue); final IntIndexMap<PendingChannel> pendingChannels = this.pendingChannels; try { handleOutboundChannelOpen(); } catch (IOException e) { result.setException(e); return IoUtils.nullCancellable(); } boolean ok = false; try { final Random random = ProtocolUtils.randomHolder.get(); for (;;) { id = random.nextInt() | 0x80000000; if (! pendingChannels.containsKey(id)) { PendingChannel pendingChannel = new PendingChannel(id, outboundWindowSize, inboundWindowSize, outboundMessageCount, inboundMessageCount, outboundMessageSize, inboundMessageSize, result); if (pendingChannels.putIfAbsent(pendingChannel) == null) { if (log.isTraceEnabled()) { log.tracef("Outbound service request for channel %08x is configured as follows:\n" + " outbound window: option %10d, req %10d\n" + " inbound window: option %10d, req %10d\n" + " outbound msgs: option %10d, req %10d\n" + " inbound msgs: option %10d, req %10d\n" + " outbound msgsize: option %19d, req %19d\n" + " inbound msgsize: option %19d, req %19d", Integer.valueOf(id), Integer.valueOf(outboundWindowSizeOptionValue), Integer.valueOf(outboundWindowSize), Integer.valueOf(inboundWindowSizeOptionValue), Integer.valueOf(inboundWindowSize), Integer.valueOf(outboundMessageCountOptionValue), Integer.valueOf(outboundMessageCount), Integer.valueOf(inboundMessageCountOptionValue), Integer.valueOf(inboundMessageCount), Long.valueOf(outboundMessageSizeOptionValue), Long.valueOf(outboundMessageSize), Long.valueOf(inboundMessageSizeOptionValue), Long.valueOf(inboundMessageSize) ); } if (anyAreSet(channelState, RECEIVED_CLOSE_REQ | SENT_CLOSE_REQ)) { // there's a chance that the connection was closed after the channel open was registered in the map here pendingChannels.remove(pendingChannel); result.setCancelled(); return IoUtils.nullCancellable(); } Pooled<ByteBuffer> pooled = remoteConnection.allocate(); try { ByteBuffer buffer = pooled.getResource(); buffer.put(Protocol.CHANNEL_OPEN_REQUEST); buffer.putInt(id); ProtocolUtils.writeBytes(buffer, Protocol.O_SERVICE_NAME, serviceTypeBytes); ProtocolUtils.writeInt(buffer, Protocol.O_MAX_INBOUND_MSG_WINDOW_SIZE, inboundWindowSize); ProtocolUtils.writeShort(buffer, Protocol.O_MAX_INBOUND_MSG_COUNT, inboundMessageCount); ProtocolUtils.writeInt(buffer, Protocol.O_MAX_OUTBOUND_MSG_WINDOW_SIZE, outboundWindowSize); ProtocolUtils.writeShort(buffer, Protocol.O_MAX_OUTBOUND_MSG_COUNT, outboundMessageCount); if (inboundMessageSize != Long.MAX_VALUE) { ProtocolUtils.writeLong(buffer, Protocol.O_MAX_INBOUND_MSG_SIZE, inboundMessageSize); } if (outboundMessageSize != Long.MAX_VALUE) { ProtocolUtils.writeLong(buffer, Protocol.O_MAX_OUTBOUND_MSG_SIZE, outboundMessageSize); } buffer.put((byte) 0); buffer.flip(); remoteConnection.send(pooled); ok = true; log.tracef("Completed initiation of service open of type %s on %s", serviceType, this); // TODO: allow cancel return IoUtils.nullCancellable(); } finally { if (! ok) pooled.free(); } } } } } finally { if (! ok) handleOutboundChannelClosed(); } } public SSLSession getSslSession() { SslChannel sslChannel = remoteConnection.getSslChannel(); return sslChannel != null ? sslChannel.getSslSession() : null; } public String getRemoteEndpointName() { return remoteEndpointName; } public SocketAddress getLocalAddress() { return remoteConnection.getChannel().getLocalAddress(); } public SocketAddress getPeerAddress() { return remoteConnection.getChannel().getPeerAddress(); } public SecurityIdentity getLocalIdentity() { return remoteConnection.getIdentity(); } protected void closeAction() throws IOException { sendCloseRequest(); remoteConnection.shutdownWrites(); // now these guys can't send useless messages closePendingChannels(); closeAllChannels(); remoteConnection.getRemoteConnectionProvider().removeConnectionHandler(this); } private void closePendingChannels() { final ArrayList<PendingChannel> list; synchronized (remoteConnection.getLock()) { list = new ArrayList<PendingChannel>(pendingChannels); } for (PendingChannel pendingChannel : list) { pendingChannel.getResult().setCancelled(); } } private void closeAllChannels() { final ArrayList<RemoteConnectionChannel> list; synchronized (remoteConnection.getLock()) { list = new ArrayList<RemoteConnectionChannel>(channels); } for (RemoteConnectionChannel channel : list) { channel.closeAsync(); } } ConnectionHandlerContext getConnectionContext() { return connectionContext; } RemoteConnectionChannel addChannel(final RemoteConnectionChannel channel) { return channels.putIfAbsent(channel); } RemoteConnectionChannel getChannel(final int id) { return channels.get(id); } PendingChannel removePendingChannel(final int id) { return pendingChannels.removeKey(id); } void putChannel(final RemoteConnectionChannel channel) { channels.put(channel); } boolean isMessageClose() { return Bits.allAreSet(behavior, Protocol.BH_MESSAGE_CLOSE); } boolean isFaultyMessageSize() { return Bits.allAreSet(behavior, Protocol.BH_FAULTY_MSG_SIZE); } public String toString() { return String.format("Connection handler for %s", remoteConnection); } void dumpState(final StringBuilder b) { synchronized (remoteConnection.getLock()) { final int state = this.channelState; final boolean sentCloseReq = Bits.allAreSet(state, SENT_CLOSE_REQ); final boolean receivedCloseReq = Bits.allAreSet(state, RECEIVED_CLOSE_REQ); final int inboundChannels = (state & INBOUND_CHANNELS_MASK) >>> Integer.numberOfTrailingZeros(ONE_INBOUND_CHANNEL); final int outboundChannels = (state & OUTBOUND_CHANNELS_MASK) >>> Integer.numberOfTrailingZeros(ONE_OUTBOUND_CHANNEL); final ConnectedMessageChannel channel = remoteConnection.getChannel(); final SocketAddress localAddress = channel.getLocalAddress(); final SocketAddress peerAddress = channel.getPeerAddress(); b.append(" ").append("Connection ").append(localAddress).append(" <-> ").append(peerAddress).append('\n'); b.append(" ").append("Channel: ").append(channel).append('\n'); b.append(" ").append("* Flags: "); if (Bits.allAreSet(behavior, Protocol.BH_MESSAGE_CLOSE)) b.append("supports-message-close "); if (Bits.allAreSet(behavior, Protocol.BH_FAULTY_MSG_SIZE)) b.append("remote-faulty-message-size "); if (receivedCloseReq) b.append("received-close-req "); if (sentCloseReq) b.append("set-close-req "); b.append('\n'); b.append(" ").append("* ").append(inboundChannels).append(" (max ").append(maxInboundChannels).append(") inbound channels\n"); b.append(" ").append("* ").append(outboundChannels).append(" (max ").append(maxOutboundChannels).append(") outbound channels\n"); b.append(" ").append("* Channels:\n"); for (RemoteConnectionChannel connectionChannel : channels) { connectionChannel.dumpState(b); } } } }
package org.jenkinsci.plugins.codesonar; import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.*; import com.cloudbees.plugins.credentials.domains.DomainRequirement; import hudson.*; import hudson.model.*; import hudson.security.ACL; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Publisher; import hudson.tasks.Recorder; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import jenkins.tasks.SimpleBuildStep; import org.apache.commons.collections.ListUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.javatuples.Pair; import org.jenkinsci.Symbol; import org.jenkinsci.plugins.codesonar.conditions.Condition; import org.jenkinsci.plugins.codesonar.conditions.ConditionDescriptor; import org.jenkinsci.plugins.codesonar.models.CodeSonarBuildActionDTO; import org.jenkinsci.plugins.codesonar.models.analysis.Analysis; import org.jenkinsci.plugins.codesonar.models.metrics.Metrics; import org.jenkinsci.plugins.codesonar.models.procedures.Procedures; import org.jenkinsci.plugins.codesonar.services.*; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author andrius */ public class CodeSonarPublisher extends Recorder implements SimpleBuildStep { private static final Logger LOGGER = Logger.getLogger("totalWarningGraph"); private String hubAddress; private String projectName; private String protocol = "http"; private XmlSerializationService xmlSerializationService = null; private HttpService httpService = null; private AuthenticationService authenticationService = null; private IAnalysisService analysisService = null; private MetricsService metricsService = null; private ProceduresService proceduresService = null; private AnalysisServiceFactory analysisServiceFactory = null; private List<Condition> conditions; private String credentialId; @DataBoundConstructor public CodeSonarPublisher(List<Condition> conditions, String protocol, String hubAddress, String projectName, String credentialId) { this.hubAddress = hubAddress; this.projectName = projectName; this.protocol = protocol; if (conditions == null) { conditions = ListUtils.EMPTY_LIST; } this.conditions = conditions; this.credentialId = credentialId; } @Override public void perform(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener) throws InterruptedException, IOException { xmlSerializationService = getXmlSerializationService(); httpService = getHttpService(); authenticationService = getAuthenticationService(); metricsService = getMetricsService(); proceduresService = getProceduresService(); analysisServiceFactory = getAnalysisServiceFactory(); String expandedHubAddress = run.getEnvironment(listener).expand(Util.fixNull(hubAddress)); String expandedProjectName = run.getEnvironment(listener).expand(Util.fixNull(projectName)); if (expandedHubAddress.isEmpty()) { throw new AbortException("Hub address not provided"); } if (expandedProjectName.isEmpty()) { throw new AbortException("Project name not provided"); } URI baseHubUri = URI.create(String.format("%s://%s", getProtocol(), expandedHubAddress)); float hubVersion = getHubVersion(baseHubUri); LOGGER.log(Level.FINE, "hub version: {0}", hubVersion); authenticate(run, baseHubUri); analysisServiceFactory = getAnalysisServiceFactory(); analysisServiceFactory.setVersion(hubVersion); analysisService = analysisServiceFactory.getAnalysisService(httpService, xmlSerializationService); List<String> logFile = IOUtils.readLines(run.getLogReader()); String analysisUrl = analysisService.getAnalysisUrlFromLogFile(logFile); if (analysisUrl == null) { analysisUrl = analysisService.getLatestAnalysisUrlForAProject(baseHubUri, expandedProjectName); } Analysis analysisActiveWarnings = analysisService.getAnalysisFromUrlWithActiveWarnings(analysisUrl); URI metricsUri = metricsService.getMetricsUriFromAnAnalysisId(baseHubUri, analysisActiveWarnings.getAnalysisId()); Metrics metrics = metricsService.getMetricsFromUri(metricsUri); URI proceduresUri = proceduresService.getProceduresUriFromAnAnalysisId(baseHubUri, analysisActiveWarnings.getAnalysisId()); Procedures procedures = proceduresService.getProceduresFromUri(proceduresUri); Analysis analysisNewWarnings = analysisService.getAnalysisFromUrlWithNewWarnings(analysisUrl); List<Pair<String, String>> conditionNamesAndResults = new ArrayList<Pair<String, String>>(); CodeSonarBuildActionDTO buildActionDTO = new CodeSonarBuildActionDTO(analysisActiveWarnings, analysisNewWarnings, metrics, procedures, baseHubUri); run.addAction(new CodeSonarBuildAction(buildActionDTO, run)); for (Condition condition : conditions) { Result validationResult = condition.validate(run, launcher, listener); Pair<String, String> pair = Pair.with(condition.getDescriptor().getDisplayName(), validationResult.toString()); conditionNamesAndResults.add(pair); run.setResult(validationResult); listener.getLogger().println(String.format("'%s' marked the build as %s", condition.getDescriptor().getDisplayName(), validationResult.toString())); } run.getAction(CodeSonarBuildAction.class).getBuildActionDTO() .setConditionNamesAndResults(conditionNamesAndResults); authenticationService.signOut(baseHubUri); } private float getHubVersion(URI baseHubUri) throws AbortException { String info; try { info = httpService.getContentFromUrlAsString(baseHubUri.resolve("/command/anon_info/")); } catch (AbortException e) { // /command/anon_info/ is not available which means the hub is > 4.2 return 4.0f; } Pattern pattern = Pattern.compile("Version:\\s(\\d+\\.\\d+)"); Matcher matcher = pattern.matcher(info); if (matcher.find()) { return Float.valueOf(matcher.group(1)); } throw new AbortException("Hub version could not be determined"); } private void authenticate(Run<?, ?> run, URI baseHubUri) throws AbortException { StandardCredentials credentials = CredentialsMatchers.firstOrNull( CredentialsProvider.lookupCredentials(StandardCredentials.class, run.getParent(), ACL.SYSTEM, Collections.<DomainRequirement>emptyList()), CredentialsMatchers.withId(credentialId)); if (credentials instanceof StandardUsernamePasswordCredentials) { LOGGER.log(Level.FINE, "authenticating using username and password"); UsernamePasswordCredentials c = (UsernamePasswordCredentials) credentials; authenticationService.authenticate(baseHubUri, c.getUsername(), c.getPassword().getPlainText()); } if (credentials instanceof StandardCertificateCredentials) { LOGGER.log(Level.FINE, "authenticating using ssl certificate"); if (protocol.equals("http")) { throw new AbortException("[CodeSonar] Authentication using a certificate is only available while SSL is enabled."); } StandardCertificateCredentials c = (StandardCertificateCredentials) credentials; authenticationService.authenticate(baseHubUri, c.getKeyStore(), c.getPassword().getPlainText()); } } @Override public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } public List<Condition> getConditions() { return conditions; } public void setConditions(List<Condition> conditions) { this.conditions = conditions; } @Override public BuildStepDescriptor getDescriptor() { return (DescriptorImpl) super.getDescriptor(); } /** * @return the hubAddress */ public String getHubAddress() { return hubAddress; } /** * @return the protocol */ public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public void setAnalysisServiceFactory(AnalysisServiceFactory analysisServiceFactory) { this.analysisServiceFactory = analysisServiceFactory; } /** * @param hubAddress the hubAddress to set */ public void setHubAddress(String hubAddress) { this.hubAddress = hubAddress; } /** * @return the projectLocation */ public String getProjectName() { return projectName; } /** * @param projectName the projectLocation to set */ public void setProjectName(String projectName) { this.projectName = projectName; } public void setXmlSerializationService(XmlSerializationService xmlSerializationService) { this.xmlSerializationService = xmlSerializationService; } public void setHttpService(HttpService httpService) { this.httpService = httpService; } public void setAnalysisService(IAnalysisService analysisService) { this.analysisService = analysisService; } public void setMetricsService(MetricsService metricsService) { this.metricsService = metricsService; } public void setProceduresService(ProceduresService proceduresService) { this.proceduresService = proceduresService; } public void setAuthenticationService(AuthenticationService authenticationService) { this.authenticationService = authenticationService; } public String getCredentialId() { return credentialId; } public void setCredentialId(String credentialId) { this.credentialId = credentialId; } public XmlSerializationService getXmlSerializationService() { if (xmlSerializationService == null) { xmlSerializationService = new XmlSerializationService(); } return xmlSerializationService; } public HttpService getHttpService() { if (httpService == null) { httpService = new HttpService(); } return httpService; } public AuthenticationService getAuthenticationService() { if (authenticationService == null) { authenticationService = new AuthenticationService(getHttpService()); } return authenticationService; } public MetricsService getMetricsService() { if (metricsService == null) { metricsService = new MetricsService(getHttpService(), getXmlSerializationService()); } return metricsService; } public ProceduresService getProceduresService() { if (proceduresService == null) { proceduresService = new ProceduresService(getHttpService(), getXmlSerializationService()); } return proceduresService; } public AnalysisServiceFactory getAnalysisServiceFactory() { if (analysisServiceFactory == null) { analysisServiceFactory = new AnalysisServiceFactory(); } return analysisServiceFactory; } @Symbol("codesonar") @Extension public static class DescriptorImpl extends BuildStepDescriptor<Publisher> { public DescriptorImpl() { super(CodeSonarPublisher.class); load(); } @Override public boolean isApplicable(Class<? extends AbstractProject> type) { return true; } @Override public String getDisplayName() { return "Codesonar"; } public List<ConditionDescriptor<?>> getAllConditions() { DescriptorExtensionList<Condition, ConditionDescriptor<Condition>> all = Condition.getAll(); List<ConditionDescriptor<?>> list = new ArrayList<ConditionDescriptor<?>>(); for (ConditionDescriptor<?> d : all) { list.add(d); } return list; } public FormValidation doCheckHubAddress(@QueryParameter("hubAddress") String hubAddress) { if (!StringUtils.isBlank(hubAddress)) { return FormValidation.ok(); } return FormValidation.error("Hub address cannot be empty."); } public FormValidation doCheckProjectName(@QueryParameter("projectName") String projectName) { if (!StringUtils.isBlank(projectName)) { return FormValidation.ok(); } return FormValidation.error("Project name cannot be empty."); } public ListBoxModel doFillCredentialIdItems(final @AncestorInPath ItemGroup<?> context) { final List<StandardCredentials> credentials = CredentialsProvider.lookupCredentials(StandardCredentials.class, context, ACL.SYSTEM, Collections.<DomainRequirement>emptyList()); return new StandardListBoxModel() .withEmptySelection() .withMatching(CredentialsMatchers.anyOf( CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class), CredentialsMatchers.instanceOf(CertificateCredentials.class) ), credentials); } public ListBoxModel doFillProtocolItems() { ListBoxModel items = new ListBoxModel(); items.add("http", "http"); items.add("https", "https"); return items; } } }
package org.pfaa.chemica.registration; import java.util.Arrays; import java.util.function.Predicate; import org.pfaa.chemica.model.Alloy; import org.pfaa.chemica.model.Chemical; import org.pfaa.chemica.model.Compound; import org.pfaa.chemica.model.Compound.Compounds; import org.pfaa.chemica.model.Condition; import org.pfaa.chemica.model.IndustrialMaterial; import org.pfaa.chemica.model.MaterialState; import org.pfaa.chemica.model.Mixture; import org.pfaa.chemica.model.Reaction; import org.pfaa.chemica.model.SimpleMixture; import org.pfaa.chemica.model.State; import org.pfaa.chemica.processing.Alloying; import org.pfaa.chemica.processing.Combination; import org.pfaa.chemica.processing.Communition; import org.pfaa.chemica.processing.Compaction; import org.pfaa.chemica.processing.EnthalpyChange; import org.pfaa.chemica.processing.Reduction; import org.pfaa.chemica.processing.Separation; import org.pfaa.chemica.processing.Separation.Axis; import org.pfaa.chemica.processing.Smelting; import org.pfaa.chemica.processing.Stacking; import org.pfaa.chemica.processing.TemperatureLevel; public class ConversionRegistrant { private ConversionRegistry registry; public ConversionRegistrant(ConversionRegistry registry) { this.registry = registry; } public <T extends Enum<?> & IndustrialMaterial> void stack(Class<T> material) { Arrays.stream(material.getEnumConstants()).map(Stacking::of).forEach(registry::register); } public void meltAndFreeze(IndustrialMaterial material) { EnthalpyChange change = EnthalpyChange.of(material); registry.register(change.melts()); registry.register(change.freezes()); } public <T extends Enum<?> & IndustrialMaterial> void meltAndFreeze(Class<T> material) { Arrays.stream(material.getEnumConstants()).forEach(this::meltAndFreeze); } public void melt(IndustrialMaterial material) { registry.register(EnthalpyChange.of(material).melts()); } public <T extends Enum<?> & IndustrialMaterial> void melt(Class<T> material) { Arrays.stream(material.getEnumConstants()).forEach(this::melt); } public <T extends Enum<?> & IndustrialMaterial> void melt(Class<T> material, Predicate<T> predicate) { Arrays.stream(material.getEnumConstants()).filter(predicate).forEach(this::melt); } public void vaporizeAndCondense(IndustrialMaterial material) { EnthalpyChange change = EnthalpyChange.of(material); registry.register(change.vaporizes()); registry.register(change.condenses()); } public <T extends Enum<?> & IndustrialMaterial> void vaporizeAndCondense(Class<T> material) { Arrays.stream(material.getEnumConstants()).forEach(this::vaporizeAndCondense); } public <T extends Enum<?> & IndustrialMaterial> void communite(Class<T> material) { Arrays.stream(material.getEnumConstants()).map(Communition::of).forEach(registry::register); } public <T extends Enum<?> & Mixture> void reduce(Class<T> material, Predicate<T> predicate) { Arrays.stream(material.getEnumConstants()).filter(predicate).map(Reduction::of).forEach(registry::register); } public <T extends Enum<?> & IndustrialMaterial> void compact(Class<T> material) { Arrays.stream(material.getEnumConstants()).map(Compaction::of).forEach(registry::register); } public <T extends Enum<?> & IndustrialMaterial> void compact(Class<T> material, Predicate<T> predicate) { Arrays.stream(material.getEnumConstants()).filter(predicate).map(Compaction::of).forEach(registry::register); } public void smelt(TemperatureLevel temp, Compounds... compounds) { this.smeltWithFlux(temp, null, compounds); } public void smeltWithFlux(TemperatureLevel temp, IndustrialMaterial flux, Compounds... compounds) { for (Compounds compound : compounds) { Smelting smelting = Smelting.of(compound).with(flux); registry.register(smelting.yields(State.SOLID)); registry.register(smelting.yields(State.LIQUID)); } } public <T extends Enum<?> & Alloy> void alloy(Class<T> material) { Arrays.stream(material.getEnumConstants()).forEach((alloy) -> { registry.register(Alloying.yielding(State.SOLID.of(alloy))); registry.register(Alloying.yielding(State.LIQUID.of(alloy))); }); } public <T extends Enum<?> & Mixture> void mix(Class<T> material) { Arrays.stream(material.getEnumConstants()).map(Combination::yielding).forEach(registry::register); } public void dissolveAndUndissolve(Compound compound) { if (!compound.isSoluble(Condition.STP)) return; registry.register(Combination.of(compound). with(State.AQUEOUS.getVolumeFactor(), Compounds.H2O). yields(State.AQUEOUS.of(compound)). given(Chemical.MIN_SOLUBILITY / compound.getSolubility() * 10000)); registry.register(Separation.of(State.AQUEOUS.of(new SimpleMixture(compound))). extracts(MaterialState.of(compound)). by(Axis.SOLUBILITY). given(compound.getSolubility() / Chemical.MIN_SOLUBILITY)); } public <T extends Enum<?> & Compound> void dissolveAndUndissolve(Class<T> material) { Arrays.stream(material.getEnumConstants()).forEach(this::dissolveAndUndissolve); } public void decompose(Compound compound) { Reaction reaction = Reactions.decompose(compound); if (reaction == null) { return; } registry.register(reaction); } public <T extends Enum<?> & Compound> void decompose(Class<T> material) { Arrays.stream(material.getEnumConstants()).forEach(this::decompose); } public void separatePhysically(Mixture mixture) { registry.register(Separation.of(mixture).extractsAll().by(Separation.Axis.DENSITY)); } public <T extends Enum<?> & Mixture> void separatePhysically(Class<T> mixture) { Arrays.stream(mixture.getEnumConstants()).forEach(this::separatePhysically); } }
public class TestMain { static int port = 5000; static String server = "127.0.0.1"; public static void main(String args[]) { System.out.println("Running tests..."); TestClient tc = new TestClient(server, port); try { tc.runAllTests(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Finished running tests!"); } }
package org.sonar.plugins.javamelody; import java.util.ArrayList; import java.util.List; import org.sonar.api.Extension; import org.sonar.api.SonarPlugin; /** * Main class of JavaMelody Sonar Plugin * * @author Emeric Vernat */ public class SonarJavaMelodyPlugin extends SonarPlugin { public SonarJavaMelodyPlugin() { super(); System.setProperty("javamelody.no-database", "true"); } @Override public List<?> getExtensions() { final List<Class<? extends Extension>> list = new ArrayList<Class<? extends Extension>>(); try { list.add(SonarMonitoringFilter.class); list.add(MonitoringLink.class); } catch (final Throwable t) { // the plugin is installed when doing sonar analysis on a project ! // but fails to load the class javax.servlet.Filter, // so ignoring the problem in a sonar analysis } return list; } }
package org.synyx.urlaubsverwaltung.dev; import org.synyx.urlaubsverwaltung.account.AccountInteractionService; import org.synyx.urlaubsverwaltung.person.MailNotification; import org.synyx.urlaubsverwaltung.person.Person; import org.synyx.urlaubsverwaltung.person.PersonId; import org.synyx.urlaubsverwaltung.person.PersonService; import org.synyx.urlaubsverwaltung.person.Role; import org.synyx.urlaubsverwaltung.person.basedata.PersonBasedata; import org.synyx.urlaubsverwaltung.person.basedata.PersonBasedataService; import org.synyx.urlaubsverwaltung.workingtime.WorkingTimeWriteService; import java.math.BigDecimal; import java.time.Clock; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.Year; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import static java.math.BigDecimal.ZERO; import static java.time.DayOfWeek.FRIDAY; import static java.time.DayOfWeek.MONDAY; import static java.time.DayOfWeek.THURSDAY; import static java.time.DayOfWeek.TUESDAY; import static java.time.DayOfWeek.WEDNESDAY; import static java.time.Month.APRIL; import static java.time.temporal.TemporalAdjusters.lastDayOfYear; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.synyx.urlaubsverwaltung.person.MailNotification.NOTIFICATION_BOSS_ALL; import static org.synyx.urlaubsverwaltung.person.MailNotification.NOTIFICATION_DEPARTMENT_HEAD; import static org.synyx.urlaubsverwaltung.person.MailNotification.NOTIFICATION_OFFICE; import static org.synyx.urlaubsverwaltung.person.MailNotification.NOTIFICATION_SECOND_STAGE_AUTHORITY; import static org.synyx.urlaubsverwaltung.person.MailNotification.NOTIFICATION_USER; import static org.synyx.urlaubsverwaltung.person.MailNotification.OVERTIME_NOTIFICATION_OFFICE; import static org.synyx.urlaubsverwaltung.person.Role.BOSS; import static org.synyx.urlaubsverwaltung.person.Role.DEPARTMENT_HEAD; import static org.synyx.urlaubsverwaltung.person.Role.OFFICE; import static org.synyx.urlaubsverwaltung.person.Role.SECOND_STAGE_AUTHORITY; /** * Provides person demo data. */ class PersonDataProvider { private final PersonService personService; private final PersonBasedataService personBasedataService; private final WorkingTimeWriteService workingTimeWriteService; private final AccountInteractionService accountInteractionService; private final Clock clock; PersonDataProvider(PersonService personService, PersonBasedataService personBasedataService, WorkingTimeWriteService workingTimeWriteService, AccountInteractionService accountInteractionService, Clock clock) { this.personService = personService; this.personBasedataService = personBasedataService; this.workingTimeWriteService = workingTimeWriteService; this.accountInteractionService = accountInteractionService; this.clock = clock; } boolean isPersonAlreadyCreated(String username) { final Optional<Person> personByUsername = personService.getPersonByUsername(username); return personByUsername.isPresent(); } Person createTestPerson(DemoUser demoUser, int personnelNumber, String firstName, String lastName, String email) { final String username = demoUser.getUsername(); final String passwordHash = demoUser.getPasswordHash(); final Role[] roles = demoUser.getRoles(); return createTestPerson(username, personnelNumber, passwordHash, firstName, lastName, email, roles); } Person createTestPerson(String username, int personnelNumber, String passwordHash, String firstName, String lastName, String email, Role... roles) { final Optional<Person> personByUsername = personService.getPersonByUsername(username); if (personByUsername.isPresent()) { return personByUsername.get(); } final List<Role> permissions = asList(roles); final List<MailNotification> notifications = getNotificationsForRoles(permissions); final Person person = new Person(username, lastName, firstName, email); person.setPermissions(permissions); person.setNotifications(notifications); person.setPassword(passwordHash); final Person savedPerson = personService.create(person); personBasedataService.update(new PersonBasedata(new PersonId(person.getId()), String.valueOf(personnelNumber), "")); final int currentYear = Year.now(clock).getValue(); final LocalDate firstDayOfYear = Year.of(currentYear).atDay(1); final LocalDate lastDayOfYear = firstDayOfYear.with(lastDayOfYear()); final List<Integer> workingDays = Stream.of(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY).map(DayOfWeek::getValue).collect(toList()); workingTimeWriteService.touch(workingDays, firstDayOfYear.minusYears(1), savedPerson); accountInteractionService.updateOrCreateHolidaysAccount( savedPerson, firstDayOfYear, lastDayOfYear, null, LocalDate.of(currentYear, APRIL, 1), BigDecimal.valueOf(30), BigDecimal.valueOf(30), BigDecimal.valueOf(5), ZERO, null); return savedPerson; } private List<MailNotification> getNotificationsForRoles(List<Role> roles) { final List<MailNotification> notifications = new ArrayList<>(); notifications.add(NOTIFICATION_USER); if (roles.contains(DEPARTMENT_HEAD)) { notifications.add(NOTIFICATION_DEPARTMENT_HEAD); } if (roles.contains(SECOND_STAGE_AUTHORITY)) { notifications.add(NOTIFICATION_SECOND_STAGE_AUTHORITY); } if (roles.contains(BOSS)) { notifications.add(NOTIFICATION_BOSS_ALL); } if (roles.contains(OFFICE)) { notifications.add(NOTIFICATION_OFFICE); notifications.add(OVERTIME_NOTIFICATION_OFFICE); } return notifications; } }
package com.psddev.dari.db; import java.util.AbstractList; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.parser.Tag; import com.psddev.dari.util.ErrorUtils; import com.psddev.dari.util.ObjectUtils; import com.psddev.dari.util.StringUtils; /** Contains strings and references to other objects. */ public class ReferentialText extends AbstractList<Object> { private static final Tag BR_TAG = Tag.valueOf("br"); private static final Tag P_TAG = Tag.valueOf("p"); private final List<Object> list = new ArrayList<Object>(); /** * Creates an empty instance. */ public ReferentialText() { } private static void addByBoundary( List<Object> list, String html, String boundary, List<Reference> references) { int previousBoundaryAt = 0; for (int boundaryAt = previousBoundaryAt; (boundaryAt = html.indexOf(boundary, previousBoundaryAt)) >= 0; previousBoundaryAt = boundaryAt + boundary.length()) { list.add(html.substring(previousBoundaryAt, boundaryAt)); list.add(references.get(list.size() / 2)); } list.add(html.substring(previousBoundaryAt)); } /** * Creates an instance from the given {@code html}. * * @param html If {@code null}, creates an empty instance. */ public ReferentialText(String html, boolean finalDraft) { if (html == null) { return; } Document document = Jsoup.parseBodyFragment(html); Element body = document.body(); document.outputSettings().prettyPrint(false); for (Element element : body.select("*")) { String tagName = element.tagName(); if (tagName.startsWith("o:")) { element.unwrap(); } else if (tagName.equals("span")) { if (element.attributes().size() == 0 || element.attr("class").contains("Mso") || element.hasAttr("color")) { element.unwrap(); } } } // Remove editorial markups. if (finalDraft) { body.getElementsByTag("del").remove(); body.getElementsByTag("ins").unwrap(); body.select("code[data-annotations]").remove(); } // Convert '<p>text</p>' to 'text<br><br>'. for (Element p : body.getElementsByTag("p")) { if (p.hasText()) { p.appendChild(new Element(BR_TAG, "")); p.appendChild(new Element(BR_TAG, "")); p.unwrap(); // Remove empty paragraphs. } else { p.remove(); } } // Find object references. List<Reference> references = new ArrayList<Reference>(); String boundary = UUID.randomUUID().toString(); for (Element enhancement : body.getElementsByClass("enhancement")) { if (!enhancement.hasClass("state-removing")) { Reference reference = null; String referenceData = enhancement.dataset().remove("reference"); if (!StringUtils.isBlank(referenceData)) { Map<?, ?> referenceMap = (Map<?, ?>) ObjectUtils.fromJson(referenceData); UUID id = ObjectUtils.to(UUID.class, referenceMap.get("_id")); UUID typeId = ObjectUtils.to(UUID.class, referenceMap.get("_type")); ObjectType type = Database.Static.getDefault().getEnvironment().getTypeById(typeId); if (type != null) { Object referenceObject = type.createObject(id); if (referenceObject instanceof Reference) { reference = (Reference) referenceObject; } } if (reference == null) { reference = new Reference(); } for (Map.Entry<?, ?> entry : referenceMap.entrySet()) { reference.getState().put(entry.getKey().toString(), entry.getValue()); } } if (reference != null) { references.add(reference); enhancement.before(boundary); } } enhancement.remove(); } StringBuilder cleaned = new StringBuilder(); for (Node child : body.childNodes()) { cleaned.append(child.toString()); } addByBoundary(this, cleaned.toString(), boundary, references); } /** * Returns a mixed list of well-formed HTML strings and object references * that have been converted to publishable forms. * * @return Never {@code null}. */ public List<Object> toPublishables() { // Concatenate the items so that it can be fed into an HTML parser. StringBuilder html = new StringBuilder(); String boundary = UUID.randomUUID().toString(); List<Reference> references = new ArrayList<Reference>(); for (Object item : this) { if (item != null) { if (item instanceof Reference) { html.append(boundary); references.add((Reference) item); } else { html.append(item.toString()); } } } // Convert 'text<br><br>' to '<p>text</p>'. Document document = Jsoup.parseBodyFragment(html.toString()); Element body = document.body(); Element lastParagraph = null; document.outputSettings().prettyPrint(false); for (Element br : body.getElementsByTag("br")) { Element previousBr = null; // Find the closest previous <br> without any intervening content. for (Node previousNode = br; (previousNode = previousNode.previousSibling()) != null; ) { if (previousNode instanceof Element) { Element previousElement = (Element) previousNode; if (BR_TAG.equals(previousElement.tag())) { previousBr = previousElement; } break; } if (previousNode instanceof TextNode && !ObjectUtils.isBlank(((TextNode) previousNode).text())) { break; } } if (previousBr == null) { continue; } List<Node> paragraphChildren = new ArrayList<Node>(); for (Node previous = previousBr; (previous = previous.previousSibling()) != null; ) { if (previous instanceof Element && ((Element) previous).isBlock()) { break; } else { paragraphChildren.add(previous); } } lastParagraph = new Element(P_TAG, ""); for (Node child : paragraphChildren) { child.remove(); lastParagraph.prependChild(child.clone()); } br.before(lastParagraph); br.remove(); previousBr.remove(); } if (lastParagraph != null) { List<Node> paragraphChildren = new ArrayList<Node>(); for (Node next = lastParagraph; (next = next.nextSibling()) != null; ) { if (next instanceof Element && ((Element) next).isBlock()) { break; } else { paragraphChildren.add(next); } } Element paragraph = new Element(P_TAG, ""); for (Node child : paragraphChildren) { child.remove(); paragraph.appendChild(child.clone()); } lastParagraph.after(paragraph); } // Remove editorial markups. body.getElementsByTag("del").remove(); body.getElementsByTag("ins").unwrap(); // Remove empty paragraphs and stringify. StringBuilder cleaned = new StringBuilder(); for (Node child : body.childNodes()) { if (child instanceof Element) { Element childElement = (Element) child; if (P_TAG.equals(childElement.tag()) && !childElement.hasText()) { continue; } } cleaned.append(child.toString()); } List<Object> publishables = new ArrayList<Object>(); addByBoundary(publishables, cleaned.toString(), boundary, references); return publishables; } private Object checkItem(Object item) { ErrorUtils.errorIfNull(item, "item"); if (item instanceof Reference) { return item; } else if (item instanceof Map) { Reference ref = null; UUID id = ObjectUtils.to(UUID.class, ((Map<?, ?>) item).get("_id")); UUID typeId = ObjectUtils.to(UUID.class, ((Map<?, ?>) item).get("_type")); ObjectType type = Database.Static.getDefault().getEnvironment().getTypeById(typeId); if (type != null) { Object object = type.createObject(id); if (object instanceof Reference) { ref = (Reference) object; } } if (ref == null) { ref = new Reference(); } for (Map.Entry<?, ?> entry : ((Map<?, ?>) item).entrySet()) { Object key = entry.getKey(); ref.getState().put(key != null ? key.toString() : null, entry.getValue()); } return ref; } else { return item.toString(); } } @Override public void add(int index, Object item) { list.add(index, checkItem(item)); } @Override public Object get(int index) { return list.get(index); } @Override public Object remove(int index) { return list.remove(index); } @Override public Object set(int index, Object item) { return list.set(index, checkItem(item)); } @Override public int size() { return list.size(); } }
package org.vetmeduni.tools.implemented; import htsjdk.samtools.*; import htsjdk.samtools.fastq.FastqRecord; import htsjdk.samtools.fastq.FastqWriter; import htsjdk.samtools.fastq.FastqWriterFactory; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.vetmeduni.io.readers.bam.SamReaderSanger; import org.vetmeduni.io.readers.fastq.single.FastqReaderSingleInterface; import org.vetmeduni.io.readers.fastq.single.FastqReaderSingleSanger; import org.vetmeduni.io.writers.bam.ReadToolsSAMFileWriterFactory; import org.vetmeduni.tools.AbstractTool; import org.vetmeduni.tools.cmd.CommonOptions; import org.vetmeduni.utils.fastq.QualityUtils; import org.vetmeduni.utils.loggers.FastqLogger; import org.vetmeduni.utils.loggers.ProgressLoggerExtension; import org.vetmeduni.utils.misc.IOUtils; import java.io.File; import java.io.IOException; import static org.vetmeduni.tools.cmd.OptionUtils.getUniqueValue; public class StandardizeQuality extends AbstractTool { @Override protected void runThrowingExceptions(CommandLine cmd) throws Exception { File input = new File(getUniqueValue(cmd, "i")); File output = new File(getUniqueValue(cmd, "o")); boolean index = cmd.hasOption("ind"); int nThreads = CommonOptions.numberOfThreads(logger, cmd); boolean multi = nThreads != 1; logCmdLine(cmd); // first check the quality switch (QualityUtils.getFastqQualityFormat(input)) { case Standard: throw new SAMException("File is already in Sanger formatting. No conversion will be performed"); default: break; } if (IOUtils.isBamOrSam(input)) { SAMProgramRecord programRecord = getToolProgramRecord(cmd); runBam(input, output, programRecord, index, multi); } else { if (index) { logger.warn("Index could not be performed for FASTQ file"); } runFastq(input, output, multi); } } /** * Change the format in a Fastq file * * @param input the input file * @param output the output file * @param multi <code>true</code> if multi-thread output * * @throws IOException if there is some problem with the files */ private void runFastq(File input, File output, boolean multi) throws IOException { // open reader (directly converting) FastqReaderSingleInterface reader = new FastqReaderSingleSanger(input); // open factory for writer FastqWriterFactory factory = new FastqWriterFactory(); factory.setUseAsyncIo(multi); // open writer FastqWriter writer = factory.newWriter(output); // start iterations FastqLogger progress = new FastqLogger(logger); for (FastqRecord record : reader) { writer.write(record); progress.add(); } progress.logNumberOfVariantsProcessed(); reader.close(); writer.close(); } /** * Change the format in a BAM file * * @param input the input file * @param output the output file * @param programInfo the information for the program to include in the header * @param index <code>true</code> if index on the fly is requested * @param multi <code>true</code> if multi-thread output * * @throws IOException if there is some problem with the files */ private void runBam(File input, File output, SAMProgramRecord programInfo, boolean index, boolean multi) throws IOException { SamReader reader = new SamReaderSanger(input, ValidationStringency.SILENT); final SAMFileHeader header = reader.getFileHeader(); header.addProgramRecord(programInfo); SAMFileWriter writer = new ReadToolsSAMFileWriterFactory().setCreateIndex(index).setUseAsyncIo(multi) .makeSAMOrBAMWriter(header, true, output); // start iterations ProgressLoggerExtension progress = new ProgressLoggerExtension(logger); for (SAMRecord record : reader) { writer.addAlignment(record); progress.record(record); } progress.logNumberOfVariantsProcessed(); reader.close(); writer.close(); } @Override protected Options programOptions() { Option input = Option.builder("i").longOpt("input").desc("Input BAM/FASTQ to standardize the quality").hasArg() .numberOfArgs(1).argName("INPUT").required().build(); Option output = Option.builder("o").longOpt("output").desc( "Output for the coverted file. The extension determine the format SAM/BAM or FASTQ/GZIP").hasArg() .numberOfArgs(1).argName("OUTPUT").required().build(); Option index = Option.builder("ind").longOpt("index").desc("If the output is a BAM file, index it") .hasArg(false).required(false).build(); Options options = new Options(); options.addOption(input); options.addOption(output); options.addOption(index); // commmon options options.addOption(CommonOptions.parallel); return options; } }
package ro.cs.products.sentinel2; import ro.cs.products.ProductDownloader; import ro.cs.products.base.ProductDescriptor; import ro.cs.products.sentinel2.workaround.FillAnglesMethod; import ro.cs.products.sentinel2.workaround.MetadataRepairer; import ro.cs.products.util.Constants; import ro.cs.products.util.Logger; import ro.cs.products.util.NetUtils; import ro.cs.products.util.Utilities; import ro.cs.products.util.Zipper; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.regex.Pattern; /** * Simple tool to download Sentinel-2 L1C products in the SAFE format * from Amazon WS or ESA SciHub. * * @author Cosmin Cara */ public class SentinelProductDownloader extends ProductDownloader { private static final String prefix = "S2A_OPER_PRD_MSIL1C_PDMC_"; private static final Set<String> bandFiles = new LinkedHashSet<String>() {{ add("B01.jp2"); add("B02.jp2"); add("B03.jp2"); add("B04.jp2"); add("B05.jp2"); add("B06.jp2"); add("B07.jp2"); add("B08.jp2"); add("B8A.jp2"); add("B09.jp2"); add("B10.jp2"); add("B11.jp2"); add("B12.jp2"); }}; private String productsUrl; private String baseUrl; private String zipsUrl; private String odataProductPath; private String odataArchivePath; private String odataTilePath; private String odataMetadataPath; private Set<String> filteredTiles; private boolean shouldFilterTiles; private Pattern tileIdPattern; private FillAnglesMethod fillMissingAnglesMethod; private ProductStore store; private Logger.ScopeLogger productLogger; public SentinelProductDownloader(ProductStore source, String targetFolder, Properties properties) { super(targetFolder, properties); this.store = source; zipsUrl = props.getProperty("s2.aws.products.url", "http://sentinel-products-l1c.s3.amazonaws.com"); if (!zipsUrl.endsWith("/")) zipsUrl += "/"; zipsUrl += "zips/"; baseUrl = props.getProperty("s2.aws.tiles.url", "http://sentinel-products-l1c.s3-website.eu-central-1.amazonaws.com"); if (!baseUrl.endsWith("/")) baseUrl += "/"; productsUrl = baseUrl + "products/"; ODataPath odp = new ODataPath(); String scihubUrl = props.getProperty("scihub.product.url", "https://scihub.copernicus.eu/apihub/odata/v1"); if (source.equals(ProductStore.SCIHUB) && !NetUtils.isAvailable(scihubUrl)) { System.err.println(scihubUrl + " is not available!"); scihubUrl = props.getProperty("scihub.product.backup.url", "https://scihub.copernicus.eu/dhus/odata/v1"); } odataProductPath = odp.root(scihubUrl + "/Products('${UUID}')").node("${PRODUCT_NAME}.SAFE").path(); odataArchivePath = odp.root(scihubUrl + "/Products('${UUID}')").value(); odp.root(odataProductPath).node(Constants.FOLDER_GRANULE).node("${tile}"); odataTilePath = odp.path(); odataMetadataPath = odp.root(odataProductPath).node(Constants.ODATA_XML_PLACEHOLDER).value(); fillMissingAnglesMethod = FillAnglesMethod.NONE; } public void setDownloadStore(ProductStore store) { this.store = store; } public void setFilteredTiles(Set<String> tiles, boolean unpacked) { this.filteredTiles = tiles; if (shouldFilterTiles = (tiles != null && tiles.size() > 0) || unpacked) { StringBuilder text = new StringBuilder(); text.append("(?:.+)("); if (tiles != null) { int idx = 1, n = tiles.size(); for (String tile : tiles) { text.append(tile); if (idx++ < n) text.append("|"); } text.append(")(?:.+)"); tileIdPattern = Pattern.compile(text.toString()); } } } public void setFillMissingAnglesMethod(FillAnglesMethod value) { this.fillMissingAnglesMethod = value; } @Override public void setBandList(String[] bands) { if (bands != null) { this.bands = new HashSet<>(); for (String band : bands) { this.bands.add(band); if (band.substring(1).length() == 1) { this.bands.add(band.substring(0, 1) + String.format("%02d", Integer.parseInt(band.substring(1)))); } } } } @Override protected Path download(ProductDescriptor product) throws IOException { switch (store) { case AWS: return downloadFromAWS(product); case SCIHUB: default: return downloadFromSciHub(product); } } @Override protected String getMetadataUrl(ProductDescriptor descriptor) { String url = null; switch (store) { case AWS: url = getProductUrl(descriptor) + "metadata.xml"; break; case SCIHUB: String metadateFileName = ((SentinelProductDescriptor) descriptor).getMetadataFileName(); url = odataMetadataPath.replace(Constants.ODATA_UUID, descriptor.getId()) .replace(Constants.ODATA_PRODUCT_NAME, descriptor.getName()) .replace(Constants.ODATA_XML_PLACEHOLDER, metadateFileName); break; } return url; } private Path downloadFromSciHub(ProductDescriptor productDescriptor) throws IOException { Path rootPath = null; String url; SentinelProductDescriptor product = (SentinelProductDescriptor) productDescriptor; Utilities.ensureExists(Paths.get(destination)); String productName = product.getName(); if (Constants.PSD_13.equals(product.getVersion()) && !shouldFilterTiles) { currentStep = "Archive"; url = odataArchivePath.replace(Constants.ODATA_UUID, product.getId()); rootPath = Paths.get(destination, productName + ".zip"); rootPath = downloadFile(url, rootPath, NetUtils.getAuthToken()); } if (rootPath == null || !Files.exists(rootPath)) { rootPath = Utilities.ensureExists(Paths.get(destination, productName + ".SAFE")); url = getMetadataUrl(product); Path metadataFile = rootPath.resolve(product.getMetadataFileName()); currentStep = "Metadata"; downloadFile(url, metadataFile, true, NetUtils.getAuthToken()); if (Files.exists(metadataFile)) { List<String> allLines = Files.readAllLines(metadataFile); List<String> metaTileNames = Utilities.filter(allLines, "<Granule" + (Constants.PSD_13.equals(product.getVersion()) ? "s" : " ")); boolean hasTiles = updateMedatata(metadataFile, allLines); if (hasTiles) { Path tilesFolder = Utilities.ensureExists(rootPath.resolve(Constants.FOLDER_GRANULE)); Utilities.ensureExists(rootPath.resolve(Constants.FOLDER_AUXDATA)); Path dataStripFolder = Utilities.ensureExists(rootPath.resolve(Constants.FOLDER_DATASTRIP)); Map<String, String> tileNames = new HashMap<>(); String dataStripId = null; String skippedTiles = ""; for (String tileName : metaTileNames) { String tileId = tileName.substring(0, tileName.lastIndexOf(NAME_SEPARATOR)); tileId = tileId.substring(tileId.lastIndexOf(NAME_SEPARATOR) + 2); if (filteredTiles.size() == 0 || filteredTiles.contains(tileId)) { String granuleId = Utilities.getAttributeValue(tileName, Constants.XML_ATTR_GRANULE_ID); if (dataStripId == null) { dataStripId = Utilities.getAttributeValue(tileName, Constants.XML_ATTR_DATASTRIP_ID); } String granule = product.getGranuleFolder(dataStripId, granuleId); tileNames.put(granuleId, odataTilePath.replace(Constants.ODATA_UUID, product.getId()) .replace(Constants.ODATA_PRODUCT_NAME, productName) .replace("${tile}", granule)); } else { skippedTiles += tileId + " "; } } if (skippedTiles.trim().length() > 0) { getLogger().info("Skipped tiles: %s", skippedTiles); } String count = String.valueOf(tileNames.size()); int tileCounter = 1; ODataPath pathBuilder = new ODataPath(); for (Map.Entry<String, String> entry : tileNames.entrySet()) { long start = System.currentTimeMillis(); currentStep = "Tile " + String.valueOf(tileCounter++) + "/" + count; String tileUrl = entry.getValue(); String granuleId = entry.getKey(); String tileName = product.getGranuleFolder(dataStripId, granuleId); Path tileFolder = Utilities.ensureExists(tilesFolder.resolve(tileName)); Path auxData = Utilities.ensureExists(tileFolder.resolve(Constants.FOLDER_AUXDATA)); Path imgData = Utilities.ensureExists(tileFolder.resolve(Constants.FOLDER_IMG_DATA)); Path qiData = Utilities.ensureExists(tileFolder.resolve(Constants.FOLDER_QI_DATA)); String metadataName = product.getGranuleMetadataFileName(granuleId); Path tileMetaFile = downloadFile(pathBuilder.root(tileUrl).node(metadataName).value(), tileFolder.resolve(metadataName), NetUtils.getAuthToken()); if (tileMetaFile != null) { if (Files.exists(tileMetaFile)) { List<String> tileMetadataLines = MetadataRepairer.parse(tileMetaFile, this.fillMissingAnglesMethod); for (String bandFileName : bandFiles) { if (this.bands == null || this.bands.contains(bandFileName.substring(0, bandFileName.indexOf(".")))) { downloadFile(pathBuilder.root(tileUrl) .node(Constants.FOLDER_IMG_DATA) .node(product.getBandFileName(granuleId, bandFileName)) .value(), imgData.resolve(product.getBandFileName(granuleId, bandFileName)), NetUtils.getAuthToken()); } else { getLogger().info("Band %s skipped", bandFileName.substring(0, bandFileName.indexOf("."))); } } List<String> lines = Utilities.filter(tileMetadataLines, "<MASK_FILENAME"); for (String line : lines) { line = line.trim(); int firstTagCloseIdx = line.indexOf(">") + 1; int secondTagBeginIdx = line.indexOf("<", firstTagCloseIdx); String maskFileName = line.substring(firstTagCloseIdx, secondTagBeginIdx); maskFileName = maskFileName.substring(maskFileName.lastIndexOf(URL_SEPARATOR) + 1); final String mfn = maskFileName; if (this.bands == null || this.bands.stream().anyMatch(mfn::contains)) { downloadFile(pathBuilder.root(tileUrl) .node(Constants.FOLDER_QI_DATA) .node(maskFileName) .value(), qiData.resolve(maskFileName), NetUtils.getAuthToken()); } else { getLogger().info("Mask %s skipped", mfn); } } getLogger().info("Tile download completed in %s", Utilities.formatTime(System.currentTimeMillis() - start)); } else { getLogger().error("File %s was not downloaded", tileMetaFile.getFileName()); } } } if (dataStripId != null) { String dataStripPath = pathBuilder.root(odataProductPath.replace(Constants.ODATA_UUID, product.getId()) .replace(Constants.ODATA_PRODUCT_NAME, productName)) .node(Constants.FOLDER_DATASTRIP).node(product.getDatastripFolder(dataStripId)) .node(product.getDatastripMetadataFileName(dataStripId)) .value(); Path dataStrip = Utilities.ensureExists(dataStripFolder.resolve(product.getDatastripFolder(dataStripId))); String dataStripFile = product.getDatastripMetadataFileName(dataStripId); downloadFile(dataStripPath, dataStrip.resolve(dataStripFile), NetUtils.getAuthToken()); } } else { Files.deleteIfExists(metadataFile); //Files.deleteIfExists(rootPath); rootPath = null; getLogger().warn("The product %s did not contain any tiles from the tile list", productName); } } else { getLogger().warn("The product %s was not found in %s data bucket", productName, store); rootPath = null; } } if (rootPath != null && Files.exists(rootPath) && shouldCompress && !rootPath.endsWith(".zip")) { getLogger().info("Compressing product %s",product); Zipper.compress(rootPath, rootPath.getFileName().toString(), shouldDeleteAfterCompression); } return rootPath; } private Path downloadFromAWS(ProductDescriptor productDescriptor) throws IOException { SentinelProductDescriptor product = (SentinelProductDescriptor) productDescriptor; Path rootPath = null; String url; String productName = product.getName(); if (!shouldFilterTiles) { currentStep = "Archive"; url = zipsUrl + productName + ".zip"; rootPath = Paths.get(destination, product + ".zip"); productLogger = new Logger.ScopeLogger(rootPath.getParent().resolve("download.log").toString()); rootPath = downloadFile(url, rootPath); } if (rootPath == null || !Files.exists(rootPath)) { // let's try to assemble the product rootPath = Utilities.ensureExists(Paths.get(destination, productName + ".SAFE")); productLogger = new Logger.ScopeLogger(rootPath.resolve("download.log").toString()); String baseProductUrl = getProductUrl(product); url = baseProductUrl + "metadata.xml"; Path metadataFile = rootPath.resolve(product.getMetadataFileName()); //rootPath.resolve(productName.replace("PRD_MSIL1C", "MTD_SAFL1C") + ".xml"); currentStep = "Metadata"; getLogger().debug("Downloading metadata file %s", metadataFile); metadataFile = downloadFile(url, metadataFile, true); if (metadataFile != null && Files.exists(metadataFile)) { Path inspireFile = metadataFile.resolveSibling("INSPIRE.xml"); Path manifestFile = metadataFile.resolveSibling("manifest.safe"); Path previewFile = metadataFile.resolveSibling("preview.png"); List<String> allLines = Files.readAllLines(metadataFile); List<String> metaTileNames = Utilities.filter(allLines, "<Granule" + (Constants.PSD_13.equals(product.getVersion()) ? "s" : " ")); boolean hasTiles = updateMedatata(metadataFile, allLines); if (hasTiles) { downloadFile(baseProductUrl + "inspire.xml", inspireFile); downloadFile(baseProductUrl + "manifest.safe", manifestFile); downloadFile(baseProductUrl + "preview.png", previewFile); // rep_info folder and contents Path repFolder = Utilities.ensureExists(rootPath.resolve("rep_info")); Path schemaFile = repFolder.resolve("S2_User_Product_Level-1C_Metadata.xsd"); copyFromResources(String.format("S2_User_Product_Level-1C_Metadata%s.xsd", product.getVersion()), schemaFile); // HTML folder and contents Path htmlFolder = Utilities.ensureExists(rootPath.resolve("HTML")); copyFromResources("banner_1.png", htmlFolder); copyFromResources("banner_2.png", htmlFolder); copyFromResources("banner_3.png", htmlFolder); copyFromResources("star_bg.jpg", htmlFolder); copyFromResources("UserProduct_index.html", htmlFolder); copyFromResources("UserProduct_index.xsl", htmlFolder); Path tilesFolder = Utilities.ensureExists(rootPath.resolve(Constants.FOLDER_GRANULE)); Utilities.ensureExists(rootPath.resolve(Constants.FOLDER_AUXDATA)); Path dataStripFolder = Utilities.ensureExists(rootPath.resolve(Constants.FOLDER_DATASTRIP)); String productJsonUrl = baseProductUrl + "productInfo.json"; HttpURLConnection connection = null; InputStream inputStream = null; JsonReader reader = null; try { getLogger().debug("Downloading json product descriptor %s", productJsonUrl); connection = NetUtils.openConnection(productJsonUrl); inputStream = connection.getInputStream(); reader = Json.createReader(inputStream); getLogger().debug("Parsing json descriptor %s", productJsonUrl); JsonObject obj = reader.readObject(); final Map<String, String> tileNames = getTileNames(obj, metaTileNames, product.getVersion()); String dataStripId = null; String count = String.valueOf(tileNames.size()); int tileCounter = 1; for (Map.Entry<String, String> entry : tileNames.entrySet()) { currentStep = "Tile " + String.valueOf(tileCounter++) + "/" + count; String tileUrl = entry.getValue(); String tileName = entry.getKey(); Path tileFolder = Utilities.ensureExists(tilesFolder.resolve(tileName)); Path auxData = Utilities.ensureExists(tileFolder.resolve(Constants.FOLDER_AUXDATA)); Path imgData = Utilities.ensureExists(tileFolder.resolve(Constants.FOLDER_IMG_DATA)); Path qiData = Utilities.ensureExists(tileFolder.resolve(Constants.FOLDER_QI_DATA)); //String refName = tileName.substring(0, tileName.lastIndexOf(NAME_SEPARATOR)); String metadataName = product.getGranuleMetadataFileName(tileName); //refName.replace("MSI", "MTD"); getLogger().debug("Downloading tile metadata %s", tileFolder.resolve(metadataName)); Path tileMetaFile = downloadFile(tileUrl + "/metadata.xml", tileFolder.resolve(metadataName)); List<String> tileMetadataLines = MetadataRepairer.parse(tileMetaFile, this.fillMissingAnglesMethod); for (String bandFileName : bandFiles) { if (this.bands == null || this.bands.contains(bandFileName.substring(0, bandFileName.indexOf(".")))) { try { String bandFileUrl = tileUrl + URL_SEPARATOR + bandFileName; Path path = imgData.resolve(product.getBandFileName(tileName, bandFileName)); //imgData.resolve(refName + NAME_SEPARATOR + bandFileName); getLogger().debug("Downloading band raster %s from %s", path, bandFileName); downloadFile(bandFileUrl, path); } catch (IOException ex) { getLogger().warn("Download for %s failed [%s]", bandFileName, ex.getMessage()); } } else { getLogger().info("Band %s skipped", bandFileName.substring(0, bandFileName.indexOf("."))); } } List<String> lines = Utilities.filter(tileMetadataLines, "<MASK_FILENAME"); for (String line : lines) { line = line.trim(); int firstTagCloseIdx = line.indexOf(">") + 1; int secondTagBeginIdx = line.indexOf("<", firstTagCloseIdx); String maskFileName = line.substring(firstTagCloseIdx, secondTagBeginIdx); if (this.bands == null || this.bands.stream().anyMatch(maskFileName::contains)) { String remoteName; Path path; if (Constants.PSD_13.equals(product.getVersion())) { String[] tokens = maskFileName.split(NAME_SEPARATOR); remoteName = tokens[2] + NAME_SEPARATOR + tokens[3] + NAME_SEPARATOR + tokens[9] + ".gml"; path = qiData.resolve(maskFileName); } else { remoteName = maskFileName.substring(maskFileName.lastIndexOf(URL_SEPARATOR) + 1); path = rootPath.resolve(maskFileName); } try { String fileUrl = tileUrl + "/qi/" + remoteName; getLogger().debug("Downloading file %s from %s", path, fileUrl); downloadFile(fileUrl, path); } catch (IOException ex) { getLogger().warn("Download for %s failed [%s]", path, ex.getMessage()); } } else { getLogger().info("Mask %s skipped", maskFileName); } } getLogger().debug("Trying to download %s", tileUrl + "/auxiliary/ECMWFT"); downloadFile(tileUrl + "/auxiliary/ECMWFT", auxData.resolve(product.getEcmWftFileName(tileName))); //auxData.resolve(refName.replace(tilePrefix, auxPrefix))); if (dataStripId == null) { String tileJson = tileUrl + "/tileInfo.json"; //URL tileJsonUrl = new URL(tileJson); HttpURLConnection tileConnection = null; InputStream is = null; JsonReader tiReader = null; try { getLogger().debug("Downloading json tile descriptor %s", tileJson); tileConnection = NetUtils.openConnection(tileJson); is = tileConnection.getInputStream(); tiReader = Json.createReader(is); getLogger().debug("Parsing json tile descriptor %s", tileJson); JsonObject tileObj = tiReader.readObject(); dataStripId = tileObj.getJsonObject("datastrip").getString("id"); String dataStripPath = tileObj.getJsonObject("datastrip").getString("path") + "/metadata.xml"; Path dataStrip = Utilities.ensureExists(dataStripFolder.resolve(product.getDatastripFolder(dataStripId))); String dataStripFile = product.getDatastripMetadataFileName(dataStripId); Utilities.ensureExists(dataStrip.resolve(Constants.FOLDER_QI_DATA)); getLogger().debug("Downloading %s", baseUrl + dataStripPath); downloadFile(baseUrl + dataStripPath, dataStrip.resolve(dataStripFile)); } finally { if (tiReader != null) tiReader.close(); if (is != null) is.close(); if (tileConnection != null) tileConnection.disconnect(); } } } } finally { if (reader != null) reader.close(); if (inputStream != null) inputStream.close(); if (connection != null) connection.disconnect(); } } else { Files.deleteIfExists(metadataFile); //Files.deleteIfExists(rootPath); rootPath = null; getLogger().warn("The product %s did not contain any tiles from the tile list", productName); } } else { getLogger().warn("Either the product %s was not found in %s data bucket or the metadata file could not be downloaded", productName, store); rootPath = null; } } if (rootPath != null && Files.exists(rootPath) && shouldCompress) { getLogger().info("Compressing product %s", product); Zipper.compress(rootPath, rootPath.getFileName().toString(), shouldDeleteAfterCompression); } return rootPath; } @Override protected String getProductUrl(ProductDescriptor descriptor) { return productsUrl + descriptor.getProductRelativePath(); } private Map<String, String> getTileNames(JsonObject productInfo, List<String> metaTileNames, String psdVersion) { Map<String, String> ret = new HashMap<>(); String dataTakeId = productInfo.getString("datatakeIdentifier"); String[] dataTakeTokens = dataTakeId.split(NAME_SEPARATOR); JsonArray tiles = productInfo.getJsonArray("tiles"); String skippedTiles = ""; for (JsonObject result : tiles.getValuesAs(JsonObject.class)) { String tilePath = result.getString("path"); String[] tokens = tilePath.split(URL_SEPARATOR); String tileId = tokens[1] + tokens[2] + tokens[3]; if (!shouldFilterTiles || (filteredTiles.size() == 0 || filteredTiles.contains(tileId))) { tileId = "T" + tileId; String tileName = Utilities.find(metaTileNames, tileId, psdVersion); /*if (tileName == null) { tileName = tilePrefix + dataTakeTokens[1] + "_A" + dataTakeTokens[2] + NAME_SEPARATOR + tileId + NAME_SEPARATOR + dataTakeTokens[3]; }*/ ret.put(tileName, baseUrl + tilePath); } else { skippedTiles += tileId + " "; } } if (skippedTiles.length() > 0) { getLogger().info("Skipped tiles: %s", skippedTiles); } return ret; } private boolean updateMedatata(Path metaFile, List<String> originalLines) throws IOException { boolean canProceed = true; if (shouldFilterTiles) { int tileCount = 0; List<String> lines = new ArrayList<>(); for (int i = 0; i < originalLines.size(); i++) { String line = originalLines.get(i); if (line.contains("<Granule_List>")) { if (tileIdPattern.matcher(originalLines.get(i + 1)).matches()) { lines.addAll(originalLines.subList(i, i + 17)); tileCount++; } i += 16; } else { lines.add(line); } } if (canProceed = (tileCount > 0)) { Files.write(metaFile, lines, StandardCharsets.UTF_8); } } return canProceed; } private void copyFromResources(String fileName, Path file) throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(fileName)))) { String line; StringBuilder builder = new StringBuilder(); while ((line = reader.readLine()) != null) { builder.append(line).append("\n"); } if (Files.isDirectory(file)) { Utilities.ensurePermissions(Files.write(file.resolve(fileName), builder.toString().getBytes())); } else { Utilities.ensurePermissions(Files.write(file, builder.toString().getBytes())); } } } private class ODataPath { private StringBuilder buffer; ODataPath() { buffer = new StringBuilder(); } ODataPath root(String path) { buffer.setLength(0); buffer.append(path); return this; } ODataPath node(String nodeName) { buffer.append("/Nodes('").append(nodeName).append("')"); return this; } String path() { return buffer.toString(); } String value() { return buffer.toString() + "/$value"; } } }
package team.unstudio.udpl.command.anno; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Stack; import javax.annotation.Nonnull; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.PluginCommand; import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import com.google.common.collect.Lists; import team.unstudio.udpl.command.CommandHelper; import team.unstudio.udpl.util.ServerUtils; public class AnnoCommandManager implements CommandExecutor,TabCompleter{ private static final String unknownCommandMessage = ChatColor.RED+" /%1$s help ."; private static final String noPermissionMessage = ChatColor.RED+":"+ChatColor.YELLOW+" %1$s ."; private static final String noEnoughParameterMessage = ChatColor.RED+"! : %1$s"; private static final String wrongSenderMessage = ChatColor.RED+"!"; private static final String errorParameterMessage = ChatColor.RED+"! : %1$s"; private static final String runCommandFailureMessage = ChatColor.RED+", ."; private final JavaPlugin plugin; private final String name; private final CommandWrapper defaultHandler; private String usage; private String description; /** * * @param name */ public AnnoCommandManager(@Nonnull String name){ this(name,(JavaPlugin) Bukkit.getPluginCommand(name).getPlugin()); } /** * * @param name * @param plugin */ public AnnoCommandManager(@Nonnull String name,JavaPlugin plugin){ this.name = name; this.plugin = plugin; this.defaultHandler = new CommandWrapper(name,this,null); } public JavaPlugin getPlugin() { return plugin; } public String getName() { return name; } public String getUsage() { return usage; } public AnnoCommandManager setUsage(String usage) { this.usage = usage; return this; } public String getDescription() { return description; } public AnnoCommandManager setDescription(String description) { this.description = description; return this; } protected void onUnknownCommand(CommandSender sender, Command command, String label, String[] args, CommandWrapper handler){ sender.sendMessage(String.format(unknownCommandMessage,label)); } protected void onNoPermission(CommandSender sender, Command command, String label, String[] args, CommandWrapper handler){ sender.sendMessage(String.format(noPermissionMessage,handler.getPermission())); } protected void onNoEnoughParameter(CommandSender sender, Command command, String label, String[] args, CommandWrapper handler){ StringBuilder builder = new StringBuilder(ChatColor.WHITE+"/"); { Stack<String> subCommandStack = new Stack<>(); CommandWrapper wrapper = handler; while(wrapper != null){ subCommandStack.push(wrapper.getNode()); wrapper = wrapper.getParent(); } while(!subCommandStack.isEmpty()){ builder.append(subCommandStack.pop()); builder.append(" "); } } { String[] requiredUsages = handler.getRequiredUsages(); for (int i = 0, size = args.length; i < size; i++) { builder.append("<"); builder.append(requiredUsages[i]); builder.append("> "); } builder.append(ChatColor.RED); for (int i = args.length, size = requiredUsages.length; i < size; i++) { builder.append("<"); builder.append(requiredUsages[i]); builder.append("> "); } } { builder.append(ChatColor.WHITE); String[] optionalUsages = handler.getOptionalUsages(); for (int i = 0, size = optionalUsages.length; i < size; i++) { builder.append("["); builder.append(optionalUsages[i]); builder.append("] "); } } sender.sendMessage(String.format(noEnoughParameterMessage,builder.toString())); } protected void onWrongSender(CommandSender sender, Command command, String label, String[] args, CommandWrapper handler){ sender.sendMessage(wrongSenderMessage); } protected void onErrorParameter(CommandSender sender, Command command, String label, String[] args, CommandWrapper handler, int[] errorParameterIndexs){ StringBuilder builder = new StringBuilder(ChatColor.WHITE+"/"); { Stack<String> subCommandStack = new Stack<>(); CommandWrapper wrapper = handler; while(wrapper != null){ subCommandStack.push(wrapper.getNode()); wrapper = wrapper.getParent(); } while(!subCommandStack.isEmpty()){ builder.append(subCommandStack.pop()); builder.append(" "); } } List<Integer> errorParameterIndexsList = Lists.newArrayList(); for(int i:errorParameterIndexs) errorParameterIndexsList.add(i); { String[] requiredUsages = handler.getRequiredUsages(); for (int i = 0, size = requiredUsages.length; i < size; i++) { if(errorParameterIndexsList.contains(i)) builder.append(ChatColor.RED); else builder.append(ChatColor.WHITE); builder.append("<"); builder.append(requiredUsages[i]); builder.append("> "); } } { String[] optionalUsages = handler.getOptionalUsages(); for (int i = 0, size = optionalUsages.length,requiredLength = handler.getRequiredUsages().length; i < size; i++) { if(errorParameterIndexsList.contains(requiredLength+i)) builder.append(ChatColor.RED); else builder.append(ChatColor.WHITE); builder.append("["); builder.append(optionalUsages[i]); builder.append("] "); } } sender.sendMessage(String.format(errorParameterMessage,builder.toString())); } protected void onRunCommandFailure(CommandSender sender, Command command, String label, String[] args, CommandWrapper handler){ sender.sendMessage(runCommandFailureMessage); } /** * * @param clazz * @param value * @return */ @SuppressWarnings("deprecation") protected Object transformParameter(Class<?> clazz,String value){ if(value == null || value.isEmpty()) return null; else if (clazz.equals(String.class)) return value; else if (clazz.equals(int.class) || clazz.equals(Integer.class)) return Integer.parseInt(value); else if (clazz.equals(boolean.class) || clazz.equals(Boolean.class)) return Boolean.parseBoolean(value); else if (clazz.equals(float.class) || clazz.equals(Float.class)) return Float.parseFloat(value); else if (clazz.equals(double.class) || clazz.equals(Double.class)) return Double.parseDouble(value); else if (clazz.equals(long.class) || clazz.equals(Long.class)) return Long.parseLong(value); else if (clazz.equals(byte.class) || clazz.equals(Byte.class)) return Byte.parseByte(value); else if (clazz.equals(short.class) || clazz.equals(Short.class)) return Short.parseShort(value); else if (clazz.equals(Player.class)) return Bukkit.getPlayerExact(value); else if (clazz.equals(OfflinePlayer.class)) return Bukkit.getOfflinePlayer(value); else if (clazz.equals(Material.class)) return Material.valueOf(value); else return null; } public AnnoCommandManager registerCommand(){ PluginCommand command = plugin.getCommand(name); command.setExecutor(this); command.setTabCompleter(this); return this; } public AnnoCommandManager unsafeRegisterCommand(){ PluginCommand command = CommandHelper.unsafeRegisterCommand(name, plugin); command.setExecutor(this); command.setTabCompleter(this); return this; } @Override public final boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String[] toLowerCaseArgs = Arrays.stream(args).map(String::toLowerCase).toArray(String[]::new); CommandWrapper parent = defaultHandler; int i, size; for (i = 0,size = toLowerCaseArgs.length; i < size; i++) { CommandWrapper wrapper = parent.getChildren().get(toLowerCaseArgs[i]); if(wrapper == null) break; parent = wrapper; } handleCommand(parent, sender, command, label, Arrays.copyOfRange(args, i+1, args.length)); return true; } protected void handleCommand(CommandWrapper wrapper,CommandSender sender,Command command,String label,String args[]){ switch (wrapper.onCommand(sender,command,label,args)) { case UnknownCommand: onUnknownCommand(sender, command, label, args, wrapper); break; case ErrorParameter: break; case NoEnoughParameter: onNoEnoughParameter(sender, command, label, args, wrapper); break; case NoPermission: onNoPermission(sender, command, label, args, wrapper); break; case WrongSender: onWrongSender(sender, command, label, args, wrapper); break; case Failure: onRunCommandFailure(sender, command, label, args, wrapper); break; case Success: break; } } public AnnoCommandManager addCommand(Object object){ for(Method method:object.getClass().getDeclaredMethods()){ team.unstudio.udpl.command.anno.Command annoCommand = method.getAnnotation(team.unstudio.udpl.command.anno.Command.class); if(annoCommand==null) continue; createCommandWrapper(annoCommand.value()).setMethod(object, method); for(Alias annoAlias:method.getAnnotationsByType(Alias.class)) createCommandWrapper(annoAlias.value()).setMethod(object, method); } return this; } public AnnoCommandManager addAllCommand(Object ...object){ Arrays.stream(object).forEach(this::addCommand); return this; } public CommandWrapper getCommandWrapper(String[] args){ String[] toLowerCaseArgs = Arrays.stream(args).map(String::toLowerCase).toArray(String[]::new); CommandWrapper parent = defaultHandler; for (int i = 0,size = toLowerCaseArgs.length; i < size; i++) { CommandWrapper wrapper = parent.getChildren().get(toLowerCaseArgs[i]); if(wrapper == null) break; parent = wrapper; } return parent; } private CommandWrapper createCommandWrapper(String[] args){ String[] toLowerCaseArgs = Arrays.stream(args).map(String::toLowerCase).toArray(String[]::new); CommandWrapper parent = defaultHandler; for (int i = 0,size = toLowerCaseArgs.length; i < size; i++) { CommandWrapper wrapper = parent.getChildren().get(toLowerCaseArgs[i]); if(wrapper == null){ wrapper = new CommandWrapper(toLowerCaseArgs[i], this, parent); parent.getChildren().put(wrapper.getNode(),wrapper); } parent = wrapper; } return parent; } @Override public final List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) { String[] toLowerCaseArgs = Arrays.stream(args).map(String::toLowerCase).toArray(String[]::new); List<String> list = new ArrayList<>(); CommandWrapper parent = defaultHandler; int i, size; for (i = 0,size = toLowerCaseArgs.length; i < size; i++) { CommandWrapper wrapper = parent.getChildren().get(toLowerCaseArgs[i]); if(wrapper == null) break; parent = wrapper; } list.addAll(parent.onTabComplete(Arrays.copyOfRange(args, i+1, args.length))); { //Sub Commands String prefix = toLowerCaseArgs[size]; parent.getChildren().keySet().stream().filter(node->node.startsWith(prefix)).forEach(list::add); } if(list.isEmpty()){ //Players String prefix = args[size]; Collections.addAll(list, ServerUtils.getOnlinePlayerNamesWithFilter(name->name.startsWith(prefix))); } return list; } }
package uk.ac.ebi.quickgo.index.geneproduct; import uk.ac.ebi.quickgo.geneproduct.common.document.GeneProductDocument; import uk.ac.ebi.quickgo.index.common.DocumentReaderException; import com.google.common.base.Preconditions; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.springframework.batch.item.ItemProcessor; import static uk.ac.ebi.quickgo.index.common.datafile.GOADataFileParsingHelper.convertLinePropertiesToMap; import static uk.ac.ebi.quickgo.index.common.datafile.GOADataFileParsingHelper.splitValue; import static uk.ac.ebi.quickgo.index.geneproduct.GeneProductParsingHelper.*; /** * Converts a {@link GeneProduct} into an {@link uk.ac.ebi.quickgo.geneproduct.common.document.GeneProductDocument} * * @author Ricardo Antunes */ public class GeneProductDocumentConverter implements ItemProcessor<GeneProduct, GeneProductDocument> { /** * The following values define how the contents of the Gene Product properties are described. * E.g <code>db_object_type=protein|go_aspect=cellular_component|target_set=KRUK,BHF-UCL</code> * where pipes are inter-value delimiters, the equals symbol is the intra-value delimiter * to split up keys and their value and comma is the delimiter for values for a single key. */ private final String interValueDelimiter; private final String intraValueDelimiter; private final String specificValueDelimiter; public GeneProductDocumentConverter(String interValueDelimiter, String intraValueDelimiter, String specificValueDelimiter) { Preconditions.checkArgument(interValueDelimiter != null && interValueDelimiter.length() > 0, "Inter value delimiter can not be null or empty"); Preconditions.checkArgument(intraValueDelimiter != null && intraValueDelimiter.length() > 0, "Intra " + "value delimiter can not be null or empty"); Preconditions.checkArgument(specificValueDelimiter != null && specificValueDelimiter.length() > 0, "Specific " + "value delimiter can not be null or empty"); this.interValueDelimiter = interValueDelimiter; this.intraValueDelimiter = intraValueDelimiter; this.specificValueDelimiter = specificValueDelimiter; } @Override public GeneProductDocument process(GeneProduct geneProduct) throws Exception { if (geneProduct == null) { throw new DocumentReaderException("Gene product object is null"); } Map<String, String> properties = convertLinePropertiesToMap(geneProduct.properties, interValueDelimiter, intraValueDelimiter); GeneProductDocument doc = new GeneProductDocument(); doc.database = geneProduct.database; doc.id = geneProduct.id; doc.symbol = geneProduct.symbol; doc.name = geneProduct.name; doc.synonyms = convertToList(splitValue(geneProduct.synonym, interValueDelimiter)); doc.type = geneProduct.type; doc.taxonId = extractTaxonIdFromValue(geneProduct.taxonId); doc.taxonName = properties.get(TAXON_NAME_KEY); doc.parentId = geneProduct.parentId; doc.referenceProteome = properties.get(REFERENCE_PROTEOME_KEY); doc.databaseSubset = properties.get(DATABASE_SUBSET_KEY); doc.targetSet = convertToList((splitValue(properties.get(TARGET_SET_KEY), specificValueDelimiter))); doc.isCompleteProteome = isTrue(properties.get(COMPLETE_PROTEOME_KEY)); doc.isAnnotated = isTrue(properties.get(IS_ANNOTATED_KEY)); doc.isIsoform = isTrue(properties.get(IS_ISOFORM_KEY)); return doc; } private boolean isTrue(String value) { return value != null && value.equalsIgnoreCase(TRUE_STRING); } @SafeVarargs private final <T> List<T> convertToList(T... elements) { List<T> list = Arrays.stream(elements) .filter(element -> element != null) .collect(Collectors.toList()); return list.size() == 0 ? null : list; } }
package tudarmstadt.lt.ABSentiment.uimahelper; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token; import de.tudarmstadt.ukp.dkpro.core.opennlp.OpenNlpPosTagger; import de.tudarmstadt.ukp.dkpro.core.tokit.BreakIteratorSegmenter; import org.apache.uima.UIMAException; import org.apache.uima.analysis_engine.AnalysisEngine; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.fit.factory.AnalysisEngineFactory; import org.apache.uima.fit.factory.JCasFactory; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.tcas.Annotation; import org.apache.uima.resource.ResourceInitializationException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.apache.uima.fit.util.JCasUtil.select; /** * Preprocessor class that performs NLP operations using UIMA AnalysisEngines. */ public class Preprocessor { private JCas cas; private AnalysisEngine tokenizer; private AnalysisEngine postagger; private boolean lightAnalysis = false; private final String language; /** * Constructor; initializes the UIMA pipeline and the CAS. */ public Preprocessor() { // build annotation engine try { tokenizer = AnalysisEngineFactory.createEngine(BreakIteratorSegmenter.class); postagger = AnalysisEngineFactory.createEngine(OpenNlpPosTagger.class, OpenNlpPosTagger.PARAM_MODEL_LOCATION, "data/models/opennlp-de-pos-maxent.bin"); } catch (ResourceInitializationException e) { e.printStackTrace(); } // build cas try { cas = JCasFactory.createJCas(); } catch (UIMAException e) { e.printStackTrace(); } language = "de"; } /** * Constructor; initializes the UIMA pipeline and the CAS, then processes an input text * @param lightAnalysis flag to indicate light analysis, only tokenization is applied */ public Preprocessor(boolean lightAnalysis) { this(); this.lightAnalysis = lightAnalysis; } /** * Constructor; initializes the UIMA pipeline and the CAS, then processes an input text * @param input input text that is analyzed in the CAS */ public Preprocessor(String input) { this(); processText(input); } /** * Processes a new text by the NLP pipeline. Resets the CAS for fast processing. * @param input input text */ public void processText(String input) { createCas(input); try { tokenizer.process(cas); if (!lightAnalysis) { postagger.process(cas); } } catch (AnalysisEngineProcessException e) { e.printStackTrace(); } } /** * Creates the CAS from an input text * @param input input text */ private void createCas(String input) { cas.reset(); cas.setDocumentText(input); cas.setDocumentLanguage(language); } /** * Retrieves the CAS, e.g. for {@link tudarmstadt.lt.ABSentiment.featureExtractor.FeatureExtractor}s * @return the CAS object */ public JCas getCas() { return cas; } /** * Retrieves a list of tokens as Strings from a provied CAS. * @param cas the CAS, from which the tokens are extracted * @return a list of Strings */ public List<String> getTokenStrings(JCas cas) { List<String> tokenStrings = new ArrayList<>(); Collection<Token> tokens = select(cas, Token.class); for (Annotation token : tokens) { tokenStrings.add(token.getCoveredText()); } return tokenStrings; } /** * Retrieves a list of tokens as Strings from the current CAS. * @return a list of Strings */ public List<String> getTokenStrings() { return getTokenStrings(this.cas); } }
package com.airbnb.lottie; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.RestrictTo; import androidx.core.os.TraceCompat; import com.airbnb.lottie.network.DefaultLottieNetworkFetcher; import com.airbnb.lottie.network.LottieNetworkCacheProvider; import com.airbnb.lottie.network.LottieNetworkFetcher; import com.airbnb.lottie.network.NetworkCache; import com.airbnb.lottie.network.NetworkFetcher; import java.io.File; @RestrictTo(RestrictTo.Scope.LIBRARY) public class L { public static boolean DBG = false; public static final String TAG = "LOTTIE"; private static final int MAX_DEPTH = 20; private static boolean traceEnabled = false; private static String[] sections; private static long[] startTimeNs; private static int traceDepth = 0; private static int depthPastMaxDepth = 0; private static LottieNetworkFetcher fetcher; private static LottieNetworkCacheProvider cacheProvider; private static volatile NetworkFetcher networkFetcher; private static volatile NetworkCache networkCache; private L() { } public static void setTraceEnabled(boolean enabled) { if (traceEnabled == enabled) { return; } traceEnabled = enabled; if (traceEnabled) { sections = new String[MAX_DEPTH]; startTimeNs = new long[MAX_DEPTH]; } } public static void beginSection(String section) { if (!traceEnabled) { return; } if (traceDepth == MAX_DEPTH) { depthPastMaxDepth++; return; } sections[traceDepth] = section; startTimeNs[traceDepth] = System.nanoTime(); TraceCompat.beginSection(section); traceDepth++; } public static float endSection(String section) { if (depthPastMaxDepth > 0) { depthPastMaxDepth return 0; } if (!traceEnabled) { return 0; } traceDepth if (traceDepth == -1) { throw new IllegalStateException("Can't end trace section. There are none."); } if (!section.equals(sections[traceDepth])) { throw new IllegalStateException("Unbalanced trace call " + section + ". Expected " + sections[traceDepth] + "."); } TraceCompat.endSection(); return (System.nanoTime() - startTimeNs[traceDepth]) / 1000000f; } public static void setFetcher(LottieNetworkFetcher customFetcher) { fetcher = customFetcher; } public static void setCacheProvider(LottieNetworkCacheProvider customProvider) { cacheProvider = customProvider; } @NonNull public static NetworkFetcher networkFetcher(@NonNull Context context) { NetworkFetcher local = networkFetcher; if (local == null) { synchronized (NetworkFetcher.class) { local = networkFetcher; if (local == null) { networkFetcher = local = new NetworkFetcher(networkCache(context), fetcher != null ? fetcher : new DefaultLottieNetworkFetcher()); } } } return local; } @NonNull public static NetworkCache networkCache(@NonNull final Context context) { final Context appContext = context.getApplicationContext(); NetworkCache local = networkCache; if (local == null) { synchronized (NetworkCache.class) { local = networkCache; if (local == null) { networkCache = local = new NetworkCache(cacheProvider != null ? cacheProvider : new LottieNetworkCacheProvider() { @Override @NonNull public File getCacheDir() { return new File(appContext.getCacheDir(), "lottie_network_cache"); } }); } } } return local; } }
package org.intermine.dataloader; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import java.lang.reflect.Constructor; import org.intermine.metadata.CollectionDescriptor; import org.intermine.metadata.FieldDescriptor; import org.intermine.metadata.Model; import org.intermine.model.InterMineObject; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreWriter; import org.intermine.objectstore.ObjectStoreWriterFactory; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.intermine.ObjectStoreWriterInterMineImpl; import org.intermine.objectstore.proxy.ProxyReference; import org.intermine.sql.Database; import org.intermine.util.DynamicUtil; import org.intermine.util.IntPresentSet; import org.intermine.util.StringUtil; import org.intermine.util.TypeUtil; import org.apache.log4j.Logger; /** * Priority-based implementation of IntegrationWriter. Allows field values to be chosen according * to the relative priorities of the data sources that originated them. * * @author Matthew Wakeling * @author Andrew Varley */ public class IntegrationWriterDataTrackingImpl extends IntegrationWriterAbstractImpl { private static final Logger LOG = Logger.getLogger(IntegrationWriterDataTrackingImpl.class); protected DataTracker dataTracker; protected Set<Class> trackerMissingClasses; protected IntPresentSet skeletons = new IntPresentSet(); /** This is a list of the objects that did not merge with anything from a previous data * source */ protected IntPresentSet pureObjects = new IntPresentSet(); /** This is a list of the objects in the destination database that we have written to as a * non-skeleton. This is so that we can notice if we write to a given object twice, given * ignoreDuplicates, so we can tell the user if ignoreDuplicates is necessary. */ protected IntPresentSet writtenObjects = new IntPresentSet(); /** This is a list of the objects in the destination database that we have written to as a * non-skeleton more than once. */ protected IntPresentSet duplicateObjects = new IntPresentSet(); protected boolean isDuplicates = false; /** * Creates a new instance of this class, given the properties defining it. * * @param osAlias the alias of this objectstore * @param props the Properties * @return an instance of this class * @throws ObjectStoreException sometimes */ public static IntegrationWriterDataTrackingImpl getInstance(String osAlias, Properties props) throws ObjectStoreException { return getInstance(osAlias, props, IntegrationWriterDataTrackingImpl.class, DataTracker.class); } /** * Creates a new IntegrationWriter instance of the specified class and and with a specificed * DataTracker class plus properties. * * @param osAlias the alias of this objectstore * @param props the Properties * @param iwClass Class of IntegrationWriter to create - IntegrationWriterDatatrackingImpl * or a subclass. * @param trackerClass Class of DataTracker to use with IntegrationWriter * @return an instance of this class * @throws ObjectStoreException sometimes */ protected static IntegrationWriterDataTrackingImpl getInstance(String osAlias, Properties props, Class iwClass, Class trackerClass) throws ObjectStoreException { String writerAlias = props.getProperty("osw"); if (writerAlias == null) { throw new ObjectStoreException(props.getProperty("alias") + " does not have an osw" + " alias specified (check properties file)"); } String trackerMaxSizeString = props.getProperty("datatrackerMaxSize"); String trackerCommitSizeString = props.getProperty("datatrackerCommitSize"); if (trackerMaxSizeString == null) { throw new ObjectStoreException(props.getProperty("alias") + " does not have a" + " datatracker maximum size specified (check properties file)"); } if (trackerCommitSizeString == null) { throw new ObjectStoreException(props.getProperty("alias") + " does not have a" + " datatracker commit size specified (check properties file)"); } String trackerMissingClassesString = props.getProperty("datatrackerMissingClasses"); ObjectStoreWriter writer = ObjectStoreWriterFactory.getObjectStoreWriter(writerAlias); try { int maxSize = Integer.parseInt(trackerMaxSizeString); int commitSize = Integer.parseInt(trackerCommitSizeString); Database db = ((ObjectStoreWriterInterMineImpl) writer).getDatabase(); Set<Class> trackerMissingClasses = new HashSet(); if (trackerMissingClassesString != null) { String trackerMissingClassesStrings[] = StringUtil.split( trackerMissingClassesString, ","); for (String trackerMissingClassString : trackerMissingClassesStrings) { Class c = Class.forName(writer.getModel().getPackageName() + "." + trackerMissingClassString.trim()); trackerMissingClasses.add(c); } } Constructor con = trackerClass.getConstructor(new Class[] {Database.class, Integer.TYPE, Integer.TYPE}); DataTracker newDataTracker = (DataTracker) con.newInstance(new Object[] {db, new Integer(maxSize), new Integer(commitSize)}); con = iwClass.getConstructor(new Class[] {ObjectStoreWriter.class, DataTracker.class, Set.class}); return (IntegrationWriterDataTrackingImpl) con.newInstance(new Object[] {writer, newDataTracker, trackerMissingClasses}); } catch (Exception e) { IllegalArgumentException e2 = new IllegalArgumentException("Problem instantiating" + " IntegrationWriterDataTrackingImpl " + props.getProperty("alias")); e2.initCause(e); throw e2; } } /** * Constructs a new instance of IntegrationWriterDataTrackingImpl. * * @param osw an instance of an ObjectStoreWriter, which we can use to access the database * @param dataTracker an instance of DataTracker, which we can use to store data tracking * information */ public IntegrationWriterDataTrackingImpl(ObjectStoreWriter osw, DataTracker dataTracker) { super(osw); this.dataTracker = dataTracker; this.trackerMissingClasses = Collections.emptySet(); } /** * Constructs a new instance of IntegrationWriterDataTrackingImpl. * * @param osw an instance of an ObjectStoreWriter, which we can use to access the database * @param dataTracker an instance of DataTracker, which we can use to store data tracking * information * @param trackerMissingClasses a Set of classes for which DataTracker data is useless */ public IntegrationWriterDataTrackingImpl(ObjectStoreWriter osw, DataTracker dataTracker, Set<Class> trackerMissingClasses) { super(osw); this.dataTracker = dataTracker; this.trackerMissingClasses = trackerMissingClasses; } /** * Resets the IntegrationWriter, clearing the id map and the hints */ public void reset() { super.reset(); pureObjects = new IntPresentSet(); } /** * {@inheritDoc} */ public Source getMainSource(String name) { return dataTracker.stringToSource(name); } /** * {@inheritDoc} */ public Source getSkeletonSource(String name) { return dataTracker.stringToSource("skel_" + name); } /** * Returns the data tracker being used. * * @return dataTracker */ protected DataTracker getDataTracker() { return dataTracker; } /** * Returns true if the given class is NOT a subclass of any of the classes in * trackerMissingClasses. * * @param c a Class * @return a boolean */ public boolean doTrackerFor(Class c) { for (Class missing : trackerMissingClasses) { if (missing.isAssignableFrom(c)) { return false; } } return true; } private long timeSpentEquiv = 0; private long timeSpentCreate = 0; private long timeSpentPriorities = 0; private long timeSpentCopyFields = 0; private long timeSpentStore = 0; private long timeSpentDataTrackerWrite = 0; /** * {@inheritDoc} */ protected InterMineObject store(InterMineObject o, Source source, Source skelSource, int type) throws ObjectStoreException { if (o == null) { return null; } try { long time1 = System.currentTimeMillis(); Set equivObjects = getEquivalentObjects(o, source); long time2 = System.currentTimeMillis(); timeSpentEquiv += time2 - time1; if ((type != FROM_DB) && ((equivObjects.size() == 0) || ((equivObjects.size() == 1) && (o.getId() != null) && (pureObjects.contains(o.getId())) && (type == SOURCE)))) { // Take a shortcut! InterMineObject newObj = (InterMineObject) DynamicUtil.createObject(o.getClass()); Integer newId; if (equivObjects.size() == 0) { newId = getSerial(); assignMapping(o.getId(), newId); } else { newId = ((InterMineObject) equivObjects.iterator().next()).getId(); } newObj.setId(newId); if (type == SOURCE) { if (writtenObjects.contains(newId)) { // There are duplicate objects duplicateObjects.add(newId); isDuplicates = true; } else { writtenObjects.add(newId); } } time1 = System.currentTimeMillis(); timeSpentCreate += time1 - time2; Map<String, FieldDescriptor> fields = getModel().getFieldDescriptorsForClass(newObj .getClass()); Map<String, Source> trackingMap = new HashMap(); for (Map.Entry<String, FieldDescriptor> entry : fields.entrySet()) { String fieldName = entry.getKey(); FieldDescriptor field = entry.getValue(); copyField(o, newObj, source, skelSource, field, type); if (!(field instanceof CollectionDescriptor)) { trackingMap.put(fieldName, type == SOURCE ? source : skelSource); } } time2 = System.currentTimeMillis(); timeSpentCopyFields += time2 - time1; store(newObj); time1 = System.currentTimeMillis(); timeSpentStore += time1 - time2; if (doTrackerFor(newObj.getClass())) { dataTracker.clearObj(newId); for (Map.Entry<String, Source> entry : trackingMap.entrySet()) { dataTracker.setSource(newObj.getId(), entry.getKey(), entry.getValue()); } } if (type == SKELETON) { skeletons.add(newObj.getId()); } else if (skeletons.contains(newObj.getId().intValue())) { skeletons.set(newObj.getId().intValue(), false); } time2 = System.currentTimeMillis(); if (o.getId() != null) { pureObjects.add(o.getId()); } timeSpentDataTrackerWrite += time2 - time1; return newObj; } if ((equivObjects.size() >= 1) && (type == SKELETON)) { InterMineObject onlyEquivalent = (InterMineObject) equivObjects.iterator().next(); // if (onlyEquivalent instanceof ProxyReference) { //LOG.debug("store() finished trivially for object " + oText); // This onlyEquivalent object MUST have come from the ID map. //if (idMap.get(o.getId()) == null) { // LOG.error("Got a ProxyReference as the only equivalent object, but not from" // + " the ID map! o = " + o); //} else { return onlyEquivalent; } Set classes = new HashSet(); classes.addAll(DynamicUtil.decomposeClass(o.getClass())); Iterator objIter = equivObjects.iterator(); while (objIter.hasNext()) { InterMineObject obj = (InterMineObject) objIter.next(); if (obj instanceof ProxyReference) { obj = ((ProxyReference) obj).getObject(); } try { classes.addAll(DynamicUtil.decomposeClass(obj.getClass())); } catch (Exception e) { LOG.error("Broken with: " + DynamicUtil.decomposeClass(o.getClass())); throw new ObjectStoreException(e); } } InterMineObject newObj = (InterMineObject) DynamicUtil.createObject(classes); Integer newId = null; // if multiple equivalent objects in database just use id of first one Iterator equivalentIter = equivObjects.iterator(); if (equivalentIter.hasNext()) { newId = ((InterMineObject) equivalentIter.next()).getId(); newObj.setId(newId); } else { newObj.setId(getSerial()); } if (type == SOURCE) { if (writtenObjects.contains(newObj.getId())) { // There are duplicate objects duplicateObjects.add(newObj.getId()); isDuplicates = true; } else { writtenObjects.add(newObj.getId()); } } if (type != FROM_DB) { assignMapping(o.getId(), newObj.getId()); } time1 = System.currentTimeMillis(); timeSpentCreate += time1 - time2; Map trackingMap = new HashMap(); Map fieldToEquivalentObjects = new HashMap(); Model model = getModel(); Map fieldDescriptors = model.getFieldDescriptorsForClass(newObj.getClass()); Set modelFieldNames = fieldDescriptors.keySet(); Set typeUtilFieldNames = TypeUtil.getFieldInfos(newObj.getClass()).keySet(); if (!modelFieldNames.equals(typeUtilFieldNames)) { throw new ObjectStoreException("Failed to store data not in the model"); } Iterator fieldIter = fieldDescriptors.entrySet().iterator(); while (fieldIter.hasNext()) { FieldDescriptor field = (FieldDescriptor) ((Map.Entry) fieldIter.next()).getValue(); String fieldName = field.getName(); if (!"id".equals(fieldName)) { Set sortedEquivalentObjects; // always add to collections, resolve other clashes by priority if (field instanceof CollectionDescriptor) { sortedEquivalentObjects = new HashSet(); } else { Comparator compare = new SourcePriorityComparator(dataTracker, field, (type == SOURCE ? source : skelSource), o, dbIdsStored, this, source, skelSource); sortedEquivalentObjects = new TreeSet(compare); } if (model.getFieldDescriptorsForClass(o.getClass()).containsKey(fieldName)) { sortedEquivalentObjects.add(o); } objIter = equivObjects.iterator(); while (objIter.hasNext()) { InterMineObject obj = (InterMineObject) objIter.next(); Source fieldSource = dataTracker.getSource(obj.getId(), fieldName); if ((equivObjects.size() == 1) && (fieldSource != null) && (fieldSource.equals(source) || (fieldSource.equals(skelSource) && (type != SOURCE)))) { if (type == SOURCE) { if (obj instanceof ProxyReference) { obj = ((ProxyReference) obj).getObject(); } String errMessage; if (dbIdsStored.contains(obj.getId())) { errMessage = "There is already an equivalent " + "in the database from this source (" + source + ") from *this* run; new object from source: \"" + o + "\", object from database (earlier in this run): \"" + obj + "\"; noticed problem while merging field \"" + field.getName() + "\" originally read from source: " + fieldSource; } else { errMessage = "There is already an equivalent " + "in the database from this source (" + source + ") from a *previous* run; " + "object from source in this run: \"" + o + "\", object from database: \"" + obj + "\"; noticed problem while merging field \"" + field.getName() + "\" originally read from source: " + fieldSource; } if (!ignoreDuplicates) { LOG.error(errMessage); throw new IllegalArgumentException(errMessage); } } //LOG.debug("store() finished simply for object " + oText); return obj; } // materialise proxies before searching for this field if (obj instanceof ProxyReference) { ProxyReference newproxy = (ProxyReference) obj; obj = ((ProxyReference) obj).getObject(); if (obj == null) { LOG.error("obj is null o: " + o); LOG.error("proxyId " + newproxy.getId()); LOG.error("proxy " + newproxy); ObjectStore os = newproxy.getObjectStore(); os.invalidateObjectById(newproxy.getId()); obj = newproxy.getObject(); LOG.error("obj: " + obj); } } try { if (model.getFieldDescriptorsForClass(obj.getClass()) .containsKey(fieldName)) { sortedEquivalentObjects.add(obj); } } catch (RuntimeException e) { LOG.error("fieldName: " + fieldName + " o: " + o + " id: " + obj.getId() + " obj: " + obj + " obj.getClass(): " + obj.getClass() + " description: " + model. getFieldDescriptorsForClass(obj.getClass())); LOG.error("error " , e); throw e; } } fieldToEquivalentObjects.put(field, sortedEquivalentObjects); } } time2 = System.currentTimeMillis(); timeSpentPriorities += time2 - time1; Iterator fieldToEquivIter = fieldToEquivalentObjects.entrySet().iterator(); while (fieldToEquivIter.hasNext()) { Source lastSource = null; Map.Entry fieldToEquivEntry = (Map.Entry) fieldToEquivIter.next(); FieldDescriptor field = (FieldDescriptor) fieldToEquivEntry.getKey(); Set sortedEquivalentObjects = (Set) fieldToEquivEntry.getValue(); String fieldName = field.getName(); objIter = sortedEquivalentObjects.iterator(); while (objIter.hasNext()) { InterMineObject obj = (InterMineObject) objIter.next(); if (obj == o) { copyField(obj, newObj, source, skelSource, field, type); if (!(field instanceof CollectionDescriptor)) { lastSource = (type == SOURCE ? source : skelSource); } } else { if (!(field instanceof CollectionDescriptor)) { lastSource = dataTracker.getSource(obj.getId(), fieldName); if (lastSource == null) { throw new NullPointerException("Error: lastSource is null for" + " object " + obj.getId() + " and fieldName " + fieldName); } } copyField(obj, newObj, lastSource, lastSource, field, FROM_DB); } } if (!(field instanceof CollectionDescriptor)) { trackingMap.put(fieldName, lastSource); } } time1 = System.currentTimeMillis(); timeSpentCopyFields += time1 - time2; store(newObj); time2 = System.currentTimeMillis(); timeSpentStore += time2 - time1; if (doTrackerFor(newObj.getClass())) { // We have called store() on an object, and we are about to write all of its data // tracking data. We should tell the data tracker, ONLY IF THE ID OF THE OBJECT IS NEW, // so that the data tracker can cache the writes without having to ask the db if // records for that objectid already exist - we know there aren't. if (newId == null) { dataTracker.clearObj(newObj.getId()); } Iterator trackIter = trackingMap.entrySet().iterator(); while (trackIter.hasNext()) { Map.Entry trackEntry = (Map.Entry) trackIter.next(); String fieldName = (String) trackEntry.getKey(); Source lastSource = (Source) trackEntry.getValue(); dataTracker.setSource(newObj.getId(), fieldName, lastSource); } } while (equivalentIter.hasNext()) { InterMineObject objToDelete = (InterMineObject) equivalentIter.next(); delete(objToDelete); } // keep track of skeletons that are stored and remove when replaced by real object if (type == SKELETON) { skeletons.add(newObj.getId()); } else { if (skeletons.contains(newObj.getId().intValue())) { skeletons.set(newObj.getId().intValue(), false); } } time1 = System.currentTimeMillis(); timeSpentDataTrackerWrite += time1 - time2; return newObj; } catch (RuntimeException e) { LOG.error("IDMAP contents: " + idMap.toString()); LOG.error("Skeletons: " + skeletons.toString()); LOG.error("pureObjects: " + pureObjects.toString()); throw new RuntimeException("Exception while loading object " + o, e); } catch (ObjectStoreException e) { LOG.error("IDMAP contents: " + idMap.toString()); LOG.error("Skeletons: " + skeletons.toString()); LOG.error("pureObjects: " + pureObjects.toString()); throw new ObjectStoreException("Exception while loading object " + o, e); } catch (IllegalAccessException e) { throw new ObjectStoreException(e); } } /** * {@inheritDoc} public void commitTransaction() throws ObjectStoreException { osw.commitTransaction(); dataTracker.flush(); } */ /** * {@inheritDoc} */ public void close() throws ObjectStoreException { super.close(); dataTracker.close(); // There is a bug somewhere in this code that sometimes allows skeletons to // be stored without matching up with the real object object. The problem // seems to be erratic, some runs complete without a problem. Here we // throw an exception if any skeletons have been stored but never replace // by a real object to give early warning. if (!(skeletons.size() == 0)) { LOG.info("Some skeletons where not replaced by real " + "objects: " + skeletons.toString()); LOG.info("IDMAP CONTENTS:" + idMap.toString()); throw new ObjectStoreException("Some skeletons where not replaced by real " + "objects: " + skeletons.size()); } LOG.info("Time spent: Equivalent object queries: " + timeSpentEquiv + ", Create object: " + timeSpentCreate + ", Compute priorities: " + timeSpentPriorities + ", Copy fields: " + timeSpentCopyFields + ", Store object: " + timeSpentStore + ", Data tracker write: " + timeSpentDataTrackerWrite + ", recursing: " + timeSpentRecursing); if (isDuplicates) { LOG.info("There were duplicate objects, with destination IDs " + duplicateObjects); } else { LOG.info("There were no duplicate objects"); } } }
package website.automate.manager.api.client.model; public class Scenario extends AbstractEntity { private String name; private boolean fragment; public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isFragment() { return fragment; } public void setFragment(boolean fragment) { this.fragment = fragment; } }
package aptgraph.batch; import aptgraph.core.Request; import aptgraph.core.Domain; import aptgraph.core.Subnet; import aptgraph.core.TimeSimilarity; //import aptgraph.core.URLSimilarity; import aptgraph.core.DomainSimilarity; import info.debatty.java.graphs.Graph; import info.debatty.java.graphs.Neighbor; import info.debatty.java.graphs.NeighborList; import info.debatty.java.graphs.SimilarityInterface; import info.debatty.java.graphs.build.ThreadedNNDescent; import info.debatty.java.graphs.build.Brute; import info.debatty.java.graphs.build.NNDescent; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectOutputStream; import java.io.UnsupportedEncodingException; import java.util.LinkedList; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.net.URL; import java.net.MalformedURLException; import java.nio.file.Files; import java.nio.file.Path; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import org.json.JSONException; import org.json.JSONObject; /** * * @author Thibault Debatty */ public class BatchProcessor { private static final Logger LOGGER = Logger.getLogger( BatchProcessor.class.getName()); // Regex to use for the full match of the squid log private static final String REGEX = "^(\\d+\\.\\d+)\\s+(\\d+)\\s" + "([^\\s]+)\\s" + "(\\S+)\\/(\\d+)\\s(\\d+)\\s(\\S+)\\s(\\S+)\\s\\-\\s(\\S+)\\/" + "([^\\s]+)\\s(\\S+).*$"; private final Pattern pattern; public BatchProcessor() { pattern = Pattern.compile(REGEX); } /** * * @param k * @param input_file * @param output_dir * @param format * @param children_bool * @param overwrite_bool * @throws IOException if we cannot read the input file */ public final void analyze(final int k, final InputStream input_file, final Path output_dir, final String format, final boolean children_bool, final boolean overwrite_bool) throws IOException { // Parsing of the log file and Split of the log file by users LOGGER.info("Read and parse input file..."); HashMap<String, LinkedList<Request>> user_requests = computeUserLog(parseFile(input_file, format)); // Build graphs for each user ArrayList<String> user_list = new ArrayList<String>(); for (Map.Entry<String, LinkedList<Request>> entry : user_requests.entrySet()) { String user = entry.getKey(); File file = new File(output_dir.toString(), user + ".ser"); if (overwrite_bool || !file.exists()) { LinkedList<Request> requests = entry.getValue(); LinkedList<Graph<Domain>> graphs = computeUserGraphs(k, user, requests, children_bool); // Store of the list of graphs for one user on disk saveGraphs(output_dir, user, graphs); } else { LOGGER.log(Level.INFO, "User {0} has been skipped...", user); } user_list.add(user); } saveUsers(output_dir, user_list); saveSubnet(output_dir, user_list); saveK(output_dir, k); } /** * Read and parse the input file line by line. * @param file * @param format * @return LinkedList<Request> */ public final LinkedList<Request> parseFile(final InputStream file, final String format) { LinkedList<Request> requests = new LinkedList<Request>(); try { BufferedReader in = new BufferedReader( new InputStreamReader(file, "UTF-8")); String line; while ((line = in.readLine()) != null) { requests.add(parseLine(line, format)); } } catch (UnsupportedEncodingException ex) { Logger.getLogger(BatchProcessor.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(BatchProcessor.class.getName()).log(Level.SEVERE, null, ex); } return requests; } /** * Parse a given line. * @param line * @param format * @return Request */ public final Request parseLine(final String line, final String format) { Request request = null; try { if (format.equals("squid")) { request = parseLineSquid(line); } else if (format.equals("json")) { request = parseLineJson(line); } else { throw new IllegalArgumentException(); } } catch (IllegalArgumentException ex) { System.err.println(ex.getMessage()); } return request; } /** * Parse a give line encoded in squid format. * @param line * @return Request */ private Request parseLineSquid(final String line) { Matcher match = pattern.matcher(line); if (!match.matches()) { throw new IllegalArgumentException("Regex did not match " + line); } String thisdomain = null; try { thisdomain = computeDomain(match.group(8)); } catch (MalformedURLException ex) { Logger.getLogger(BatchProcessor.class.getName()) .log(Level.SEVERE, null, ex); } Request request = new Request( (long) (Double.parseDouble(match.group(1)) * 1000), Integer.parseInt(match.group(2)), match.group(3), match.group(4), Integer.parseInt(match.group(5)), Integer.parseInt(match.group(6)), match.group(7), match.group(8), thisdomain, match.group(9), match.group(10), match.group(11)); return request; } /** * Parse a given line encoded with JSON. * @param line * @return Request */ private Request parseLineJson(final String line) { JSONObject obj; try { obj = new JSONObject(line); } catch (JSONException ex) { throw new JSONException(ex + "\nJSON did not match " + line); } String thisdomain = null; try { thisdomain = computeDomain(obj.getString("tk_url")); } catch (MalformedURLException ex) { Logger.getLogger(BatchProcessor.class.getName()) .log(Level.SEVERE, null, ex); } Request request = null; try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = sdf.parse(obj.getString("@timestamp")); Long timestamp = date.getTime(); String client = "unkown"; if (obj.has("tk_client_ip")) { client = obj.getString("tk_client_ip"); } String method = "unkown"; if (obj.has("tk_operation")) { method = obj.getString("tk_operation"); } int bytes = 0; if (obj.has("tk_size")) { bytes = obj.getInt("tk_size"); } String url = "unkown"; if (obj.has("tk_url")) { url = obj.getString("tk_url"); } String peerhost = "unkown"; if (obj.has("tk_server_ip")) { peerhost = obj.getString("tk_server_ip"); } String type = "unkown"; if (obj.has("tk_mime_content")) { type = obj.getString("tk_mime_content"); } request = new Request( timestamp, 0, // info not available client, "unknown", // info not available 0, // info not available bytes, method, url, thisdomain, "unknown", // info not available peerhost, type); } catch (ParseException ex) { Logger.getLogger(BatchProcessor.class.getName()) .log(Level.SEVERE, null, ex); } return request; } /** Associate each user (String) to his requests (LinkedList<Request>). * @param requests_temp : LinkedList<Request> of the raw log file * @return user_requests : HashMap<String, LinkedList<Request> * of the log file sorted by user */ final HashMap<String, LinkedList<Request>> computeUserLog( final LinkedList<Request> requests_temp) { HashMap<String, LinkedList<Request>> user_requests = new HashMap<String, LinkedList<Request>>(); for (Request req : requests_temp) { String user = req.getClient(); LinkedList<Request> requests; if (user_requests.containsKey(user)) { requests = user_requests.get(user); } else { requests = new LinkedList<Request>(); user_requests.put(user, requests); } requests.add(req); } return user_requests; } private static String computeDomain(final String url) throws MalformedURLException { String url_temp = url; if (url_temp.startsWith("tcp: String[] url_split = url_temp.split("[:] url_temp = url_split[1]; } if (url_temp.startsWith("-: String[] url_split = url_temp.split("[:] url_temp = url_split[1]; } if (!url_temp.startsWith("http: && !url_temp.startsWith("https: url_temp = "http://" + url_temp; } if (url_temp.contains(":")) { String[] url_split = url_temp.split("[:]"); url_temp = url_split[0] + ":" + url_split[1]; } String domain = ""; try { URL myurl = new URL(url_temp); domain = myurl.getHost(); } catch (MalformedURLException ex) { Logger.getLogger(BatchProcessor.class.getName()) .log(Level.SEVERE, "URL " + url + " is a malformed URL", ex); } if (domain.startsWith("www.")) { return domain.substring(4); } return domain; } /** * Compute the feature graphs of a user. * @param k * @param user * @param requests * @param children_bool * @return LinkedList<Graph<Domain>> * @throws IOException */ final LinkedList<Graph<Domain>> computeUserGraphs( final int k, final String user, final LinkedList<Request> requests, final boolean children_bool) { LOGGER.log(Level.INFO, "Build the domains for user {0} ...", user); // Create the domain nodes // (it contains every requests of a specific domain, for each domain) HashMap<String, Domain> domains = computeDomainNodes(requests); LOGGER.log(Level.INFO, "Build the Time based graph for user {0} ...", user); Graph<Request> time_graph = computeRequestGraph(requests, k, new TimeSimilarity()); // Selection of the temporal children only if (children_bool) { time_graph = childrenSelection(time_graph); } // Compute similarity between domains and build domain graph Graph<Domain> time_domain_graph = computeSimilarityDomain(time_graph, domains); LOGGER.log(Level.INFO, "Build the Domain based graph for user {0} ...", user); Graph<Request> domain_graph = computeRequestGraph(requests, k, new DomainSimilarity()); // Selection of the temporal children only if (children_bool) { domain_graph = childrenSelection(domain_graph); } // Compute similarity between domains and build domain graph Graph<Domain> domain_domain_graph = computeSimilarityDomain(domain_graph, domains); /*LOGGER.log(Level.INFO, "Build the URL based graph for user {0} ...", user); Graph<Request> url_graph = computeRequestGraph(requests, k, new URLSimilarity()); // Selection of the temporal children only if (children_bool) { url_graph = childrenSelection(url_graph); } // Compute similarity between domains and build domain graph Graph<Domain> url_domain_graph = computeSimilarityDomain(url_graph, domains);*/ // List of graphs LinkedList<Graph<Domain>> graphs = new LinkedList<Graph<Domain>>(); graphs.add(time_domain_graph); graphs.add(domain_domain_graph); //graphs.add(url_domain_graph); return graphs; } /** * Compute the graph of requests based on given similarity definition. * @param requests * @param k * @param Similarity * @return Graph<Request> */ final Graph<Request> computeRequestGraph( final LinkedList<Request> requests, final int k, final SimilarityInterface<Request> similarity) { Graph<Request> graph; if (requests.size() < 2 * k) { Brute<Request> nndes = new Brute<Request>(); nndes.setSimilarity(similarity); nndes.setK(k); graph = nndes.computeGraph(requests); } else if (requests.size() >= 2 * k && requests.size() < 500) { NNDescent<Request> nndes = new NNDescent<Request>(); nndes.setSimilarity(similarity); nndes.setK(k); graph = nndes.computeGraph(requests); } else { ThreadedNNDescent<Request> nndes = new ThreadedNNDescent<Request>(); nndes.setSimilarity(similarity); nndes.setK(k); graph = nndes.computeGraph(requests); } return graph; } /** * Select only the temporal children. * @param graph * @return graph */ final Graph<Request> childrenSelection( final Graph<Request> graph) { Graph<Request> graph_new = new Graph<Request>(Integer.MAX_VALUE); for (Request req : graph.getNodes()) { NeighborList neighbors_new = new NeighborList(Integer.MAX_VALUE); NeighborList neighbors = graph.getNeighbors(req); for (Neighbor<Request> neighbor : neighbors) { if (req.getTime() <= neighbor.getNode().getTime()) { neighbors_new.add(neighbor); } } graph_new.put(req, neighbors_new); } return graph_new; } /** * Group the requests by domain to create domain nodes. * @param requests * @return domains */ final HashMap<String, Domain> computeDomainNodes( final LinkedList<Request> requests) { // Associate each domain_name (String) to a Domain HashMap<String, Domain> domains = new HashMap<String, Domain>(); for (Request request : requests) { String domain_name = request.getDomain(); Domain domain_node; if (domains.containsKey(domain_name)) { domain_node = domains.get(domain_name); } else { domain_node = new Domain(); domain_node.setName(domain_name); domains.put(domain_name, domain_node); } domain_node.add(request); } return domains; } /** * Compute the similarity between domains and build domain graph. * @param graph * @param domains * @return domain_graph */ final Graph<Domain> computeSimilarityDomain( final Graph<Request> graph, final HashMap<String, Domain> domains) { // A domain is (for now) a list of Request. Graph<Domain> domain_graph = new Graph<Domain>(Integer.MAX_VALUE); // For each domain for (Map.Entry<String, Domain> domain_entry : domains.entrySet()) { // The json-rpc request was probably canceled by the user if (Thread.currentThread().isInterrupted()) { return null; } String domain_name = domain_entry.getKey(); Domain domain_node = domain_entry.getValue(); HashMap<Domain, Double> other_domains_sim = new HashMap<Domain, Double>(); // For each request in this domain for (Request request_node : domain_node) { // Check each neighbor NeighborList neighbors = graph.getNeighbors(request_node); for (Neighbor<Request> neighbor : neighbors) { // Find the corresponding domain name String other_domain_name = neighbor.getNode().getDomain(); if (other_domain_name.equals(domain_name)) { continue; } Domain other_domain = domains.get(other_domain_name); double new_similarity = neighbor.getSimilarity(); if (other_domains_sim.containsKey(other_domain)) { new_similarity += other_domains_sim.get(other_domain); } if (new_similarity != 0) { other_domains_sim.put(other_domain, new_similarity); } } } NeighborList this_domain_neighbors = new NeighborList(Integer.MAX_VALUE); for (Map.Entry<Domain, Double> other_domain_entry : other_domains_sim.entrySet()) { this_domain_neighbors.add(new Neighbor( other_domain_entry.getKey(), other_domain_entry.getValue())); } domain_graph.put(domain_node, this_domain_neighbors); } return domain_graph; } /** * Save the feature graphs of a user. * @param output_dir * @param user * @param graphs * @throws IOException */ final void saveGraphs( final Path output_dir, final String user, final LinkedList<Graph<Domain>> graphs) { try { LOGGER.log(Level.INFO, "Save graphs of user {0} to disk...", user); File file = new File(output_dir.toString(), user + ".ser"); if (Files.notExists(output_dir)) { Files.createDirectory(output_dir); } FileOutputStream output_stream = new FileOutputStream(file.toString()); ObjectOutputStream output = new ObjectOutputStream( new BufferedOutputStream(output_stream)); output.writeObject(graphs); output.close(); } catch (IOException ex) { System.err.println(ex); } } /** * Save the list of the users. * @param output_dir * @param user_list */ final void saveUsers( final Path output_dir, final ArrayList<String> user_list) { try { LOGGER.log(Level.INFO, "Save list of users to disk..."); File file = new File(output_dir.toString(), "users.ser"); FileOutputStream output_stream = new FileOutputStream(file.toString()); ObjectOutputStream output = new ObjectOutputStream( new BufferedOutputStream(output_stream)); output.writeObject(Subnet.sortIPs(user_list)); output.close(); } catch (IOException ex) { System.err.println(ex); } } /** * Save the list of subnets. * @param output_dir * @param user_list */ final void saveSubnet( final Path output_dir, final ArrayList<String> user_list) { try { LOGGER.log(Level.INFO, "Save list of subnets to disk..."); File file = new File(output_dir.toString(), "subnets.ser"); FileOutputStream output_stream = new FileOutputStream(file.toString()); ObjectOutputStream output = new ObjectOutputStream( new BufferedOutputStream(output_stream)); ArrayList<String> subnet_list = Subnet.getAllSubnets(user_list); output.writeObject(subnet_list); output.close(); } catch (IOException ex) { System.err.println(ex); } } /** * Save the value of k (of k-NN Graphs). * @param output_dir * @param k */ final void saveK( final Path output_dir, final int k) { try { LOGGER.log(Level.INFO, "Save list of k value to disk..."); File file = new File(output_dir.toString(), "k.ser"); FileOutputStream output_stream = new FileOutputStream(file.toString()); ObjectOutputStream output = new ObjectOutputStream( new BufferedOutputStream(output_stream)); output.writeInt(k); output.close(); } catch (IOException ex) { System.err.println(ex); } } }
package com.intellij.compilerOutputIndex.api.indexer; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Factory; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.indexing.*; import com.intellij.util.io.DataExternalizer; import com.intellij.util.io.IOUtil; import com.intellij.util.io.KeyDescriptor; import com.intellij.util.io.PersistentHashMap; import org.jetbrains.asm4.ClassReader; import java.io.File; import java.io.IOException; import java.util.Collection; import static com.intellij.util.indexing.IndexInfrastructure.*; /** * @author Dmitry Batkovich */ public abstract class CompilerOutputBaseIndex<K, V> { public final static ExtensionPointName<CompilerOutputBaseIndex> EXTENSION_POINT_NAME = ExtensionPointName.create("com.intellij.java.compilerOutputIndex"); private final static Logger LOG = Logger.getInstance(CompilerOutputBaseIndex.class); private final KeyDescriptor<K> myKeyDescriptor; private final DataExternalizer<V> myValueExternalizer; protected volatile MapReduceIndex<K, V, ClassReader> myIndex; private volatile Project myProject; public CompilerOutputBaseIndex(final KeyDescriptor<K> keyDescriptor, final DataExternalizer<V> valueExternalizer) { myKeyDescriptor = keyDescriptor; myValueExternalizer = valueExternalizer; } public final boolean init(final Project project) { myProject = project; final MapReduceIndex<K, V, ClassReader> index; final Ref<Boolean> rewriteIndex = new Ref<Boolean>(false); try { final ID<K, V> indexId = getIndexId(); if (!IndexInfrastructure.getIndexRootDir(indexId).exists()) { rewriteIndex.set(true); } final File storageFile = getStorageFile(indexId); MapIndexStorage<K, V> indexStorage = null; for(int i = 0; i < 2; ++i) { try { indexStorage = new MapIndexStorage<K, V>(storageFile, myKeyDescriptor, myValueExternalizer, 1024); } catch (IOException ex) { if (i == 1) throw ex; IOUtil.deleteAllFilesStartingWith(storageFile); } } assert indexStorage != null; index = new MapReduceIndex<K, V, ClassReader>(indexId, getIndexer(), indexStorage); final MapIndexStorage<K, V> finalIndexStorage = indexStorage; index.setInputIdToDataKeysIndex(new Factory<PersistentHashMap<Integer, Collection<K>>>() { @Override public PersistentHashMap<Integer, Collection<K>> create() { Exception failCause = null; for (int attempts = 0; attempts < 2; attempts++) { try { return FileBasedIndexImpl.createIdToDataKeysIndex(indexId, myKeyDescriptor, new MemoryIndexStorage<K, V>(finalIndexStorage)); } catch (IOException e) { failCause = e; FileUtil.delete(getInputIndexStorageFile(getIndexId())); rewriteIndex.set(true); } } throw new RuntimeException("couldn't create index", failCause); } }); final File versionFile = getVersionFile(indexId); if (versionFile.exists()) { if (versionDiffers(versionFile, getVersion())) { rewriteVersion(versionFile, getVersion()); rewriteIndex.set(true); try { LOG.info("clearing index for updating index version"); index.clear(); } catch (StorageException e) { LOG.error("couldn't clear index for reinitializing"); throw new RuntimeException(e); } } } else if (versionFile.createNewFile()) { rewriteVersion(versionFile, getVersion()); rewriteIndex.set(true); } else { LOG.error(String.format("problems while access to index version file to index %s ", indexId)); } } catch (IOException e) { LOG.error("couldn't initialize index", e); throw new RuntimeException(e); } myIndex = index; return rewriteIndex.get(); } protected abstract ID<K, V> getIndexId(); protected abstract int getVersion(); protected abstract DataIndexer<K, V, ClassReader> getIndexer(); public final void projectClosed() { if (myIndex != null) { try { myIndex.flush(); } catch (StorageException ignored) { } myIndex.dispose(); } } public void update(final int id, final ClassReader classReader) { Boolean result = myIndex.update(id, classReader).compute(); if (result == Boolean.FALSE) throw new RuntimeException(); } public void clear() { try { myIndex.clear(); } catch (StorageException e) { throw new RuntimeException(e); } } protected final ID<K, V> generateIndexId(final String indexName) { return CompilerOutputIndexUtil.generateIndexId(indexName, myProject); } protected final ID<K, V> generateIndexId(final Class aClass) { final String className = StringUtil.getShortName(aClass); return generateIndexId(StringUtil.trimEnd(className, "Index")); } }
package org.uma.jmetal.algorithm.totrythemeasures; import org.uma.jmetal.algorithm.Algorithm; import org.uma.jmetal.operator.CrossoverOperator; import org.uma.jmetal.operator.MutationOperator; import org.uma.jmetal.operator.SelectionOperator; import org.uma.jmetal.operator.impl.crossover.SBXCrossover; import org.uma.jmetal.operator.impl.mutation.PolynomialMutation; import org.uma.jmetal.operator.impl.selection.BinaryTournamentSelection; import org.uma.jmetal.problem.Problem; import org.uma.jmetal.util.JMetalException; import org.uma.jmetal.util.evaluator.SolutionListEvaluator; import org.uma.jmetal.util.evaluator.impl.SequentialSolutionListEvaluator; import org.uma.jmetal.util.AlgorithmBuilder; public class NSGAIIMBuilder implements AlgorithmBuilder { public enum NSGAIIVariant {NSGAII, SteadyStateNSGAII} /** * NSGAIIBuilder class */ private final Problem problem; private int maxIterations; private int populationSize; private CrossoverOperator crossoverOperator; private MutationOperator mutationOperator; private SelectionOperator selectionOperator; private SolutionListEvaluator evaluator; /** * NSGAIIBuilder constructor */ public NSGAIIMBuilder(Problem problem, NSGAIIVariant variant) { this.problem = problem; maxIterations = 250; populationSize = 100; crossoverOperator = new SBXCrossover(0.9, 20.0); mutationOperator = new PolynomialMutation(1.0 / problem.getNumberOfVariables(), 20.0); selectionOperator = new BinaryTournamentSelection(); evaluator = new SequentialSolutionListEvaluator(); } /** * NSGAIIBuilder constructor */ public NSGAIIMBuilder(Problem problem) { this(problem, NSGAIIVariant.NSGAII) ; } public NSGAIIMBuilder setMaxIterations(int maxIterations) { if (maxIterations < 0) { throw new JMetalException("maxIterations is negative: " + maxIterations); } this.maxIterations = maxIterations; return this; } public NSGAIIMBuilder setPopulationSize(int populationSize) { if (populationSize < 0) { throw new JMetalException("Population size is negative: " + populationSize); } this.populationSize = populationSize; return this; } public NSGAIIMBuilder setCrossoverOperator(CrossoverOperator crossoverOperator) { if (crossoverOperator == null) { throw new JMetalException("crossoverOperator is null"); } this.crossoverOperator = crossoverOperator; return this; } public NSGAIIMBuilder setMutationOperator(MutationOperator mutationOperator) { if (mutationOperator == null) { throw new JMetalException("mutationOperator is null"); } this.mutationOperator = mutationOperator; return this; } public NSGAIIMBuilder setSelectionOperator(SelectionOperator selectionOperator) { if (selectionOperator == null) { throw new JMetalException("selectionOperator is null"); } this.selectionOperator = selectionOperator; return this; } public NSGAIIMBuilder setSolutionListEvaluator(SolutionListEvaluator evaluator) { if (evaluator == null) { throw new JMetalException("evaluator is null"); } this.evaluator = evaluator; return this; } public Algorithm build() { Algorithm algorithm ; algorithm = new NSGAIIM(problem, maxIterations, populationSize, crossoverOperator, mutationOperator, selectionOperator, evaluator); return algorithm ; } /* Getters */ public Problem getProblem() { return problem; } public int getMaxIterations() { return maxIterations; } public int getPopulationSize() { return populationSize; } public CrossoverOperator getCrossoverOperator() { return crossoverOperator; } public MutationOperator getMutationOperator() { return mutationOperator; } public SelectionOperator getSelectionOperator() { return selectionOperator; } public SolutionListEvaluator getSolutionListEvaluator() { return evaluator; } }
package nl.mpi.kinnate.svg; import java.awt.BorderLayout; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.geom.AffineTransform; import java.awt.geom.Dimension2D; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import javax.swing.JPanel; import javax.xml.parsers.DocumentBuilderFactory; import nl.mpi.arbil.data.ArbilComponentBuilder; import nl.mpi.arbil.data.ArbilDataNodeLoader; import nl.mpi.arbil.ui.ArbilWindowManager; import nl.mpi.arbil.userstorage.SessionStorage; import nl.mpi.arbil.util.BugCatcherManager; import nl.mpi.arbil.util.MessageDialogHandler; import nl.mpi.kinnate.SavePanel; import nl.mpi.kinnate.entityindexer.EntityCollection; import nl.mpi.kinnate.entityindexer.IndexerParameters; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.kindata.GraphSorter; import nl.mpi.kinnate.kintypestrings.KinTermGroup; import nl.mpi.kinnate.ui.GraphPanelContextMenu; import nl.mpi.kinnate.ui.KinDiagramPanel; import nl.mpi.kinnate.ui.MetadataPanel; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import org.apache.batik.dom.svg.SAXSVGDocumentFactory; import org.apache.batik.dom.svg.SVGDOMImplementation; import org.apache.batik.dom.util.SAXIOException; import org.apache.batik.swing.JSVGCanvas; import org.apache.batik.swing.JSVGScrollPane; import org.apache.batik.util.XMLResourceDescriptor; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.events.EventTarget; import org.w3c.dom.svg.SVGDocument; public class GraphPanel extends JPanel implements SavePanel { private JSVGScrollPane jSVGScrollPane; protected JSVGCanvas svgCanvas; protected SVGDocument doc; public MetadataPanel metadataPanel; private boolean requiresSave = false; private File svgFile = null; public GraphPanelSize graphPanelSize; protected ArrayList<UniqueIdentifier> selectedGroupId; protected String svgNameSpace = SVGDOMImplementation.SVG_NAMESPACE_URI; public DataStoreSvg dataStoreSvg; public EntitySvg entitySvg; // private URI[] egoPathsTemp = null; public SvgUpdateHandler svgUpdateHandler; public MouseListenerSvg mouseListenerSvg; private MessageDialogHandler dialogHandler; private SessionStorage sessionStorage; // private EntityCollection entityCollection; public GraphPanel(KinDiagramPanel kinDiagramPanel, final ArbilWindowManager arbilWindowManager, SessionStorage sessionStorage, EntityCollection entityCollection, ArbilDataNodeLoader dataNodeLoader) { this.dialogHandler = arbilWindowManager; this.sessionStorage = sessionStorage; // this.entityCollection = entityCollection; dataStoreSvg = new DataStoreSvg(); entitySvg = new EntitySvg(dialogHandler); dataStoreSvg.setDefaults(); svgUpdateHandler = new SvgUpdateHandler(this, kinDiagramPanel, dialogHandler); selectedGroupId = new ArrayList<UniqueIdentifier>(); graphPanelSize = new GraphPanelSize(); this.setLayout(new BorderLayout()); boolean eventsEnabled = true; boolean selectableText = false; svgCanvas = new JSVGCanvas(new GraphUserAgent(this, dialogHandler, dataNodeLoader), eventsEnabled, selectableText); // svgCanvas.setMySize(new Dimension(600, 400)); svgCanvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC); // drawNodes(); svgCanvas.setEnableImageZoomInteractor(false); svgCanvas.setEnablePanInteractor(false); svgCanvas.setEnableRotateInteractor(false); svgCanvas.setEnableZoomInteractor(false); svgCanvas.addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { if (e.isShiftDown()) { double scale = 1 - e.getUnitsToScroll() / 10.0; double tx = -e.getX() * (scale - 1); double ty = -e.getY() * (scale - 1); // System.out.println("scale: " + scale); // System.out.println("scale: " + svgCanvas.getRenderingTransform().getScaleX()); if (scale > 1 || svgCanvas.getRenderingTransform().getScaleX() > 0.01) { AffineTransform at = new AffineTransform(); at.translate(tx, ty); at.scale(scale, scale); at.concatenate(svgCanvas.getRenderingTransform()); svgCanvas.setRenderingTransform(at); } } else { // todo: add a ToolTip or StatusBar to give hints "Hold shift + mouse wheel to zoom" } } }); // svgCanvas.setEnableResetTransformInteractor(true); // svgCanvas.setDoubleBufferedRendering(true); // todo: look into reducing the noticable aliasing on the canvas mouseListenerSvg = new MouseListenerSvg(kinDiagramPanel, this, sessionStorage, dialogHandler, entityCollection); svgCanvas.addMouseListener(mouseListenerSvg); svgCanvas.addMouseMotionListener(mouseListenerSvg); jSVGScrollPane = new JSVGScrollPane(svgCanvas); // svgCanvas.setBackground(Color.LIGHT_GRAY); this.add(BorderLayout.CENTER, jSVGScrollPane); svgCanvas.setComponentPopupMenu(new GraphPanelContextMenu(kinDiagramPanel, this, entityCollection, arbilWindowManager, dataNodeLoader, sessionStorage)); } // private void zoomDrawing() { // AffineTransform scaleTransform = new AffineTransform(); // scaleTransform.scale(1 - currentZoom / 10.0, 1 - currentZoom / 10.0); // System.out.println("currentZoom: " + currentZoom); //// svgCanvas.setRenderingTransform(scaleTransform); // Rectangle canvasBounds = this.getBounds(); // SVGRect bbox = ((SVGLocatable) doc.getRootElement()).getBBox(); // if (bbox != null) { // System.out.println("previousZoomedWith: " + bbox.getWidth()); //// SVGElement rootElement = doc.getRootElement(); //// if (currentWidth < canvasBounds.width) { // float drawingCenter = (currentWidth / 2); //// float drawingCenter = (bbox.getX() + (bbox.getWidth() / 2)); // float canvasCenter = (canvasBounds.width / 2); // zoomAffineTransform = new AffineTransform(); // zoomAffineTransform.translate((canvasCenter - drawingCenter), 1); // zoomAffineTransform.concatenate(scaleTransform); // svgCanvas.setRenderingTransform(zoomAffineTransform); public void setArbilTableModel(MetadataPanel metadataPanel) { this.metadataPanel = metadataPanel; } public void readSvg(URI svgFilePath, boolean savableType) { if (savableType) { svgFile = new File(svgFilePath); } else { svgFile = null; } String parser = XMLResourceDescriptor.getXMLParserClassName(); SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser); try { doc = (SVGDocument) documentFactory.createDocument(svgFilePath.toString()); svgCanvas.setDocument(doc); dataStoreSvg = DataStoreSvg.loadDataFromSvg(doc); if (dataStoreSvg.indexParameters == null) { dataStoreSvg.setDefaults(); } requiresSave = false; entitySvg.readEntityPositions(doc.getElementById("EntityGroup")); entitySvg.readEntityPositions(doc.getElementById("LabelsGroup")); entitySvg.readEntityPositions(doc.getElementById("GraphicsGroup")); configureDiagramGroups(); dataStoreSvg.indexParameters.symbolFieldsFields.setAvailableValues(entitySvg.listSymbolNames(doc, this.svgNameSpace)); // if (dataStoreSvg.graphData == null) { // return null; } catch (SAXIOException exception) { dialogHandler.addMessageDialogToQueue("Cannot open the diagram: " + exception.getMessage(), "Open Diagram"); } catch (IOException exception) { dialogHandler.addMessageDialogToQueue("Cannot open the diagram: " + exception.getMessage(), "Open Diagram"); } // svgCanvas.setSVGDocument(doc); return; // dataStoreSvg.graphData.getDataNodes(); } private void configureDiagramGroups() { Element svgRoot = doc.getDocumentElement(); // make sure the diagram group exisits Element diagramGroup = doc.getElementById("DiagramGroup"); if (diagramGroup == null) { diagramGroup = doc.createElementNS(svgNameSpace, "g"); diagramGroup.setAttribute("id", "DiagramGroup"); // add the diagram group to the root element (the 'svg' element) svgRoot.appendChild(diagramGroup); } Element previousElement = null; // add the graphics group below the entities and relations // add the relation symbols in a group below the relation lines // add the entity symbols in a group on top of the relation lines // add the labels group on top, also added on svg load if missing for (String groupForMouseListener : new String[]{"LabelsGroup", "EntityGroup", "RelationGroup", "GraphicsGroup"}) { // add any groups that are required and add them in the required order Element parentElement = doc.getElementById(groupForMouseListener); if (parentElement == null) { parentElement = doc.createElementNS(svgNameSpace, "g"); parentElement.setAttribute("id", groupForMouseListener); diagramGroup.insertBefore(parentElement, previousElement); } else { diagramGroup.insertBefore(parentElement, previousElement); // insert the node to make sure that it is in the diagram group and not in any other location // set up the mouse listeners that were lost in the save/re-open process if (!groupForMouseListener.equals("RelationGroup")) { // do not add mouse listeners to the relation group Node currentNode = parentElement.getFirstChild(); while (currentNode != null) { ((EventTarget) currentNode).addEventListener("mousedown", mouseListenerSvg, false); currentNode = currentNode.getNextSibling(); } } } previousElement = parentElement; } } public void generateDefaultSvg() { try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); // set up a kinnate namespace so that the ego list and kin type strings can have more permanent storage places // in order to add the extra namespaces to the svg document we use a string and parse it // other methods have been tried but this is the most readable and the only one that actually works // I think this is mainly due to the way the svg dom would otherwise be constructed // others include: // doc.getDomConfig() // doc.getDocumentElement().setAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kin:version", ""); // doc.getDocumentElement().setAttribute("xmlns:" + DataStoreSvg.kinDataNameSpace, DataStoreSvg.kinDataNameSpaceLocation); // this method of declaring multiple namespaces looks to me to be wrong but it is the only method that does not get stripped out by the transformer on save // Document doc = impl.createDocument(svgNS, "svg", null); // SVGDocument doc = svgCanvas.getSVGDocument(); String templateXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<svg xmlns:xlink=\"http: + "xmlns=\"http: + " zoomAndPan=\"magnify\" contentStyleType=\"text/css\" " + "preserveAspectRatio=\"xMidYMid meet\" version=\"1.0\"/>"; // DOMImplementation impl = SVGDOMImplementation.getDOMImplementation(); // doc = (SVGDocument) impl.createDocument(svgNameSpace, "svg", null); String parser = XMLResourceDescriptor.getXMLParserClassName(); SAXSVGDocumentFactory documentFactory = new SAXSVGDocumentFactory(parser); doc = (SVGDocument) documentFactory.createDocument(svgNameSpace, new StringReader(templateXml)); entitySvg.insertSymbols(doc, svgNameSpace); configureDiagramGroups(); dataStoreSvg.indexParameters.symbolFieldsFields.setAvailableValues(entitySvg.listSymbolNames(doc, this.svgNameSpace)); svgCanvas.setSVGDocument(doc); dataStoreSvg.graphData = new GraphSorter(); } catch (IOException exception) { BugCatcherManager.getBugCatcher().logError(exception); } } private void saveSvg(File svgFilePath) { svgFile = svgFilePath; selectedGroupId.clear(); svgUpdateHandler.clearHighlights(); // make sure that any data changes such as the title/description in the kin term groups get updated into the file on save dataStoreSvg.storeAllData(doc); ArbilComponentBuilder.savePrettyFormatting(doc, svgFile); requiresSave = false; } private void printNodeNames(Node nodeElement) { System.out.println(nodeElement.getLocalName()); System.out.println(nodeElement.getNamespaceURI()); Node childNode = nodeElement.getFirstChild(); while (childNode != null) { printNodeNames(childNode); childNode = childNode.getNextSibling(); } } public String[] getKinTypeStrigs() { return dataStoreSvg.kinTypeStrings; } public void setKinTypeStrigs(String[] kinTypeStringArray) { // strip out any white space, blank lines and remove duplicates // this has set has been removed because it creates a discrepancy between what the user types and what is processed // HashSet<String> kinTypeStringSet = new HashSet<String>(); // for (String kinTypeString : kinTypeStringArray) { // if (kinTypeString != null && kinTypeString.trim().length() > 0) { // kinTypeStringSet.add(kinTypeString.trim()); // dataStoreSvg.kinTypeStrings = kinTypeStringSet.toArray(new String[]{}); dataStoreSvg.kinTypeStrings = kinTypeStringArray; } public IndexerParameters getIndexParameters() { return dataStoreSvg.indexParameters; } public KinTermGroup[] getkinTermGroups() { return dataStoreSvg.kinTermGroups; } public KinTermGroup addKinTermGroup() { ArrayList<KinTermGroup> kinTermsList = new ArrayList<KinTermGroup>(Arrays.asList(dataStoreSvg.kinTermGroups)); final KinTermGroup kinTermGroup = new KinTermGroup(); kinTermsList.add(kinTermGroup); dataStoreSvg.kinTermGroups = kinTermsList.toArray(new KinTermGroup[]{}); return kinTermGroup; } // public String[] getEgoUniquiIdentifiersList() { // return dataStoreSvg.egoIdentifierSet.toArray(new String[]{}); // public String[] getEgoIdList() { // return dataStoreSvg.egoIdentifierSet.toArray(new String[]{}); // public URI[] getEgoPaths() { // if (egoPathsTemp != null) { // return egoPathsTemp; // ArrayList<URI> returnPaths = new ArrayList<URI>(); // for (String egoId : dataStoreSvg.egoIdentifierSet) { // try { // String entityPath = getPathForElementId(egoId); //// if (entityPath != null) { // returnPaths.add(new URI(entityPath)); // } catch (URISyntaxException ex) { // GuiHelper.linorgBugCatcher.logError(ex); // // todo: warn user with a dialog // return returnPaths.toArray(new URI[]{}); // public void setRequiredEntities(URI[] egoPathArray, String[] egoIdentifierArray) { //// egoPathsTemp = egoPathArray; // egoPathsTemp is only required if the ego nodes are not already on the graph (otherwise the path can be obtained from the graph elements) // dataStoreSvg.requiredEntities = new HashSet<String>(Arrays.asList(egoIdentifierArray)); // public void addRequiredEntity(URI[] egoPathArray, String[] egoIdentifierArray) { //// egoPathsTemp = egoPathArray; // egoPathsTemp is only required if the ego nodes are not already on the graph (otherwise the path can be obtained from the graph elements) // dataStoreSvg.requiredEntities.addAll(Arrays.asList(egoIdentifierArray)); // public void removeEgo(String[] egoIdentifierArray) { // dataStoreSvg.egoIdentifierSet.removeAll(Arrays.asList(egoIdentifierArray)); public void setSelectedIds(UniqueIdentifier[] uniqueIdentifiers) { selectedGroupId.clear(); selectedGroupId.addAll(Arrays.asList(uniqueIdentifiers)); svgUpdateHandler.updateSvgSelectionHighlights(); // mouseListenerSvg.updateSelectionDisplay(); } public UniqueIdentifier[] getSelectedIds() { return selectedGroupId.toArray(new UniqueIdentifier[]{}); } public EntityData getEntityForElementId(UniqueIdentifier uniqueIdentifier) { for (EntityData entityData : dataStoreSvg.graphData.getDataNodes()) { if (uniqueIdentifier.equals(entityData.getUniqueIdentifier())) { return entityData; } } return null; } public HashMap<UniqueIdentifier, EntityData> getEntitiesById(UniqueIdentifier[] uniqueIdentifiers) { ArrayList<UniqueIdentifier> identifierList = new ArrayList<UniqueIdentifier>(Arrays.asList(uniqueIdentifiers)); HashMap<UniqueIdentifier, EntityData> returnMap = new HashMap<UniqueIdentifier, EntityData>(); for (EntityData entityData : dataStoreSvg.graphData.getDataNodes()) { if (identifierList.contains(entityData.getUniqueIdentifier())) { returnMap.put(entityData.getUniqueIdentifier(), entityData); } } return returnMap; } // public boolean selectionContainsEgo() { // for (String selectedId : selectedGroupId) { // if (dataStoreSvg.egoIdentifierSet.contains(selectedId)) { // return true; // return false; public String getPathForElementId(UniqueIdentifier elementId) { // NamedNodeMap namedNodeMap = doc.getElementById(elementId).getAttributes(); // for (int attributeCounter = 0; attributeCounter < namedNodeMap.getLength(); attributeCounter++) { // System.out.println(namedNodeMap.item(attributeCounter).getNodeName()); // System.out.println(namedNodeMap.item(attributeCounter).getNamespaceURI()); // System.out.println(namedNodeMap.item(attributeCounter).getNodeValue()); Element entityElement = doc.getElementById(elementId.getAttributeIdentifier()); if (entityElement == null) { return null; } else { return entityElement.getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "path"); } } public String getKinTypeForElementId(UniqueIdentifier elementId) { Element entityElement = doc.getElementById(elementId.getAttributeIdentifier()); if (entityElement != null) { return entityElement.getAttributeNS(DataStoreSvg.kinDataNameSpaceLocation, "kintype"); } else { return ""; } } public Dimension2D getDiagramSize() { return svgCanvas.getSVGDocumentSize(); // Element svgRoot = doc.getDocumentElement(); // String widthString = svgRoot.getAttribute("width"); // String heightString = svgRoot.getAttribute("height"); // return new Point(Integer.parseInt(widthString), Integer.parseInt(widthString)); } public void resetZoom() { // todo: this should be moved to the svg update handler and put into a runnable AffineTransform at = new AffineTransform(); at.scale(1, 1); at.setToTranslation(1, 1); svgCanvas.setRenderingTransform(at); } public void resetLayout() { // this requires that the entity data is loaded by recalculating the diagram at least once entitySvg = new EntitySvg(dialogHandler); dataStoreSvg.graphData.setEntitys(dataStoreSvg.graphData.getDataNodes()); dataStoreSvg.graphData.placeAllNodes(entitySvg.entityPositions); drawNodes(); } public UniqueIdentifier[] getDiagramUniqueIdentifiers() { return entitySvg.entityPositions.keySet().toArray(new UniqueIdentifier[0]); } public void clearEntityLocations(UniqueIdentifier[] selectedIdentifiers) { entitySvg.clearEntityLocations(selectedIdentifiers); } public void drawNodes() { requiresSave = true; selectedGroupId.clear(); svgUpdateHandler.updateEntities(); } public void drawNodes(GraphSorter graphDataLocal) { dataStoreSvg.graphData = graphDataLocal; drawNodes(); if (graphDataLocal.getDataNodes().length == 0) { // if all entities have been removed then reset the zoom so that new nodes are going to been centered // todo: it would be better to move the window to cover the drawing area but not change the zoom // resetZoom(); } } public boolean hasSaveFileName() { return svgFile != null; } public File getFileName() { return svgFile; } public boolean requiresSave() { return requiresSave; } public void setRequiresSave() { requiresSave = true; } public void saveToFile() { saveSvg(svgFile); } public void saveToFile(File saveAsFile) { saveSvg(saveAsFile); } public void updateGraph() { throw new UnsupportedOperationException("Not supported yet."); } public void doActionCommand(MouseListenerSvg.ActionCode actionCode) { throw new UnsupportedOperationException("Not supported yet."); } public GraphPanel getGraphPanel() { return this; } }
package org.junit.jupiter.params.aggregator; import static org.apiguardian.api.API.Status.INTERNAL; import static org.junit.platform.commons.util.AnnotationUtils.isAnnotated; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import org.apiguardian.api.API; /** * Collection of utilities for working with aggregating argument consumers * in parameterized tests (i.e., parameters of type {@link ArgumentsAccessor} * or annotated with {@link AggregateWith @AggregateWith}). * * @since 5.2 */ @API(status = INTERNAL, since = "5.2") public class AggregationUtils { ///CLOVER:OFF private AggregationUtils() { /* no-op */ } ///CLOVER:ON /** * Determine if the supplied {@link Method} has a <em>potentially</em> * valid signature (i.e., formal parameter declarations) with regard to * aggregators. * * <p>This method takes a best-effort approach at enforcing the following * policy for parameterized test methods that accept aggregators as arguments. * * <ol> * <li>zero or more <em>indexed arguments</em> come first.</li> * <li>zero or more <em>aggregators</em> come next.</li> * <li>zero or more arguments supplied by other {@code ParameterResolver} * implementations come last.</li> * </ol> * * @return {@code true} if the method has a potentially valid signature */ public static boolean hasPotentiallyValidSignature(Method method) { Parameter[] parameters = method.getParameters(); int indexOfPreviousAggregator = -1; for (int i = 0; i < parameters.length; i++) { if (isAggregator(parameters[i])) { if ((indexOfPreviousAggregator != -1) && (i != indexOfPreviousAggregator + 1)) { return false; } indexOfPreviousAggregator = i; } } return true; } /** * Determine if the supplied {@link Parameter} is an aggregator (i.e., of * type {@link ArgumentsAccessor} or annotated with {@link AggregateWith}). * * @return {@code true} if the parameter is an aggregator */ public static boolean isAggregator(Parameter parameter) { return ArgumentsAccessor.class.isAssignableFrom(parameter.getType()) || isAnnotated(parameter, AggregateWith.class); } /** * Determine if the supplied {@link Method} declares at least one * {@link Parameter} that is an {@linkplain #isAggregator aggregator}. * * @return {@code true} if the method has an aggregator */ public static boolean hasAggregator(Method method) { return indexOfFirstAggregator(method) != -1; } /** * Find the index of the first {@linkplain #isAggregator aggregator} * {@link Parameter} in the supplied {@link Method}. * * @return the index of the first aggregator, or {@code -1} if not found */ public static int indexOfFirstAggregator(Method method) { Parameter[] parameters = method.getParameters(); for (int i = 0; i < parameters.length; i++) { if (isAggregator(parameters[i])) { return i; } } return -1; } }
package io.digdag.cli.client; import java.io.PrintStream; import java.util.Map; import java.util.HashMap; import java.time.Instant; import com.google.inject.Injector; import com.google.inject.Scopes; import com.google.common.base.Optional; import com.beust.jcommander.Parameter; import com.beust.jcommander.DynamicParameter; import io.digdag.client.config.Config; import io.digdag.client.config.ConfigFactory; import io.digdag.core.*; import io.digdag.core.Version; import io.digdag.core.config.ConfigLoaderManager; import io.digdag.cli.SystemExitException; import io.digdag.client.DigdagClient; import io.digdag.client.api.RestProject; import io.digdag.client.api.RestSessionAttempt; import io.digdag.client.api.RestSessionAttemptRequest; import io.digdag.client.api.RestWorkflowDefinition; import io.digdag.client.api.RestWorkflowSessionTime; import io.digdag.client.api.LocalTimeOrInstant; import io.digdag.client.api.SessionTimeTruncate; import static java.util.Locale.ENGLISH; import static io.digdag.cli.Arguments.loadParams; import static io.digdag.cli.SystemExitException.systemExit; public class Start extends ClientCommand { @DynamicParameter(names = {"-p", "--param"}) Map<String, String> params = new HashMap<>(); @Parameter(names = {"-P", "--params-file"}) String paramsFile = null; @Parameter(names = {"--retry"}) String retryAttemptName = null; @Parameter(names = {"--session"}) String sessionString = null; @Parameter(names = {"--revision"}) String revision = null; @Parameter(names = {"-d", "--dry-run"}) boolean dryRun = false; public Start(Version version, PrintStream out, PrintStream err) { super(version, out, err); } @Override public void mainWithClientException() throws Exception { if (args.size() != 2) { throw usage(null); } if (sessionString == null) { throw usage("--session option is required"); } start(args.get(0), args.get(1)); } public SystemExitException usage(String error) { err.println("Usage: digdag start <project-name> <name>"); err.println(" Options:"); err.println(" --session <hourly | daily | now | \"yyyy-MM-dd[ HH:mm:ss]\"> set session_time to this time (required)"); err.println(" --revision <name> use a past revision"); err.println(" --retry NAME set retry attempt name to a new session"); err.println(" -d, --dry-run tries to start a session attempt but does nothing"); err.println(" -p, --param KEY=VALUE add a session parameter (use multiple times to set many parameters)"); err.println(" -P, --params-file PATH.yml read session parameters from a YAML file"); showCommonOptions(); err.println(""); err.println(" Examples:"); err.println(" $ digdag start myproj workflow1 --session \"2016-01-01 07:00:00\""); err.println(" $ digdag start myproj workflow1 --session hourly # use current hour's 00:00"); err.println(" $ digdag start myproj workflow1 --session daily # use current day's 00:00:00"); err.println(""); return systemExit(error); } public void start(String projName, String workflowName) throws Exception { Injector injector = new DigdagEmbed.Bootstrap() .withWorkflowExecutor(false) .withScheduleExecutor(false) .withLocalAgent(false) .addModules(binder -> { binder.bind(ConfigLoaderManager.class).in(Scopes.SINGLETON); }) .initialize() .getInjector(); final ConfigFactory cf = injector.getInstance(ConfigFactory.class); final ConfigLoaderManager loader = injector.getInstance(ConfigLoaderManager.class); Config overwriteParams = loadParams(cf, loader, loadSystemProperties(), paramsFile, params); LocalTimeOrInstant time; SessionTimeTruncate mode; switch (sessionString) { case "hourly": time = LocalTimeOrInstant.of(Instant.now()); mode = SessionTimeTruncate.HOUR; break; case "daily": time = LocalTimeOrInstant.of(Instant.now()); mode = SessionTimeTruncate.DAY; break; case "now": time = LocalTimeOrInstant.of(Instant.now()); mode = null; break; default: time = LocalTimeOrInstant.of( parseLocalTime(sessionString, "--session must be hourly, daily, now, \"yyyy-MM-dd\", or \"yyyy-MM-dd HH:mm:SS\" format")); mode = null; } DigdagClient client = buildClient(); RestProject proj = client.getProject(projName); RestWorkflowDefinition def; if (revision == null) { def = client.getWorkflowDefinition(proj.getId(), workflowName); } else { def = client.getWorkflowDefinition(proj.getId(), workflowName, revision); } RestWorkflowSessionTime truncatedTime = client.getWorkflowTruncatedSessionTime(def.getId(), time, mode); RestSessionAttemptRequest request = RestSessionAttemptRequest.builder() .workflowId(def.getId()) .sessionTime(truncatedTime.getSessionTime().toInstant()) .retryAttemptName(Optional.fromNullable(retryAttemptName)) .params(overwriteParams) .build(); if (dryRun) { ln("Session attempt:"); ln(" id: (dry run)"); ln(" uuid: (dry run)"); ln(" project: %s", def.getProject().getName()); ln(" workflow: %s", def.getName()); ln(" session time: %s", formatTime(request.getSessionTime())); ln(" retry attempt name: %s", request.getRetryAttemptName().or("")); ln(" params: %s", request.getParams()); //ln(" created at: (dry run)"); ln(""); err.println("Session attempt is not started."); } else { RestSessionAttempt newAttempt = client.startSessionAttempt(request); ln("Started a session attempt:"); ln(" id: %d", newAttempt.getId()); ln(" uuid: %s", newAttempt.getSessionUuid()); ln(" project: %s", newAttempt.getProject().getName()); ln(" workflow: %s", newAttempt.getWorkflow().getName()); ln(" session time: %s", formatTime(newAttempt.getSessionTime())); ln(" retry attempt name: %s", newAttempt.getRetryAttemptName().or("")); ln(" params: %s", newAttempt.getParams()); ln(" created at: %s", formatTime(newAttempt.getCreatedAt())); ln(""); err.println("* Use `digdag sessions` to list session attempts."); err.println(String.format(ENGLISH, "* Use `digdag task %d` and `digdag log %d` to show status.", newAttempt.getId(), newAttempt.getId())); } } }
package com.konkerlabs.platform.security.managers; import com.konkerlabs.platform.security.crypto.BCrypt; import com.konkerlabs.platform.security.exceptions.SecurityException; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.apache.commons.lang3.RandomStringUtils; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import java.math.BigInteger; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.text.MessageFormat; import java.util.Base64; import java.util.Optional; public class PasswordManager { private static final Config CONFIG = ConfigFactory.load().getConfig("password"); public static final String STORAGE_PATTERN_DELIMITER = "$"; public static final String STORAGE_PATTERN = "{0}"+ STORAGE_PATTERN_DELIMITER+"{1}" + STORAGE_PATTERN_DELIMITER+"{2,number, STORAGE_PATTERN_DELIMITER+"{3}" + STORAGE_PATTERN_DELIMITER+"{4}"; // The following constants may be changed without breaking existing hashes. public static final String QUALIFIER_PBKDF2 = "PBKDF2WithHmac"; public static final String QUALIFIER_BCRYPT = "Bcrypt"; public static final String HASH_ALGORITHM = CONFIG.getString("hash.algorithm"); public static final int SALT_BYTES = CONFIG.getInt("salt.size"); public static final int HASH_BYTES = 32; public static final int ITERATIONS = CONFIG.getInt("iterations"); private static final int HASHING_FUNCTION_INDEX = 0; private static final int ITERATION_INDEX = 2; private static final int SALT_INDEX = 3; private static final int PBKDF2_INDEX = 4; protected byte[] generateSalt() { SecureRandom random = new SecureRandom(); byte[] salt = new byte[SALT_BYTES]; random.nextBytes(salt); return salt; } /** * Generates a random string for password encoding * * @param size generated password string length * @return generated password */ public String generateRandomPassword(int size) { return RandomStringUtils.randomAlphanumeric(size); } /** * Returns a salted PBKDF2 hash of the password. * * @param password the password to hash * @return a salted PBKDF2 hash of the password * @throws SecurityException */ public String createHash(String password) throws SecurityException { return createHash(password.toCharArray()); } /** * Returns a salted PBKDF2 hash of the password. * * @param password the password to hash * @param iterations cicles to enforce * @return a salted PBKDF2 hash of the password * @throws SecurityException */ public String createHash(String password, Optional<Integer> iterations) throws SecurityException { return createHash(password.toCharArray(), iterations); } /** * Returns a salted PBKDF2 hash of the password. * @param password the password to hash * @param iterations cicles to enforce * @return a salted PBKDF2 hash of the password */ public String createHash(char[] password, Optional<Integer> iterations) throws SecurityException { try { // Generate a random salt byte[] salt = generateSalt(); // Hash the password byte[] hash = pbkdf2( password, salt, iterations.isPresent() ? iterations.get() : ITERATIONS, HASH_BYTES ); return MessageFormat.format(STORAGE_PATTERN, QUALIFIER_PBKDF2,HASH_ALGORITHM,ITERATIONS,toBase64(salt),toBase64(hash)); } catch (NoSuchAlgorithmException|InvalidKeySpecException e) { throw new SecurityException(e); } } /** * Returns a salted PBKDF2 hash of the password. * * @param password the password to hash * @return a salted PBKDF2 hash of the password */ public String createHash(char[] password) throws SecurityException { return createHash(password, Optional.empty()); } /** * Validates a password using a hash (PBKDF2 or BCrypt) * * @param password the password to check * @param goodHash the hash of the valid password * @return true if the password is correct, false if not */ public boolean validatePassword(String password, String goodHash) throws NoSuchAlgorithmException, InvalidKeySpecException { return validatePassword(password.toCharArray(), goodHash); } /** * Validates a password using a hash (PBKDF2 or BCrypt) * * @param password the password to check * @param goodHash the hash of the valid password * @return true if the password is correct, false if not */ public boolean validatePassword(char[] password, String goodHash) throws NoSuchAlgorithmException, InvalidKeySpecException { if ("userNotFoundPassword".equals(goodHash)) { return false; } else { // Decode the hash into its parameters String[] params = goodHash.split("\\"+STORAGE_PATTERN_DELIMITER); switch (params[HASHING_FUNCTION_INDEX]) { case QUALIFIER_PBKDF2: return validatePBKDF2Password(params, password); case QUALIFIER_BCRYPT: return validateBcryptPassword(goodHash, password); default: return false; } } } private boolean validateBcryptPassword(String goodHash, char[] password) { // Remove qualifier goodHash = goodHash.substring(goodHash.indexOf("$")); return BCrypt.checkpw(new String(password), goodHash); } private boolean validatePBKDF2Password(String[] params, char[] password) throws InvalidKeySpecException, NoSuchAlgorithmException { int iterations = Integer.parseInt(params[ITERATION_INDEX]); byte[] salt = fromBase64(params[SALT_INDEX]); byte[] hash = fromBase64(params[PBKDF2_INDEX]); // Compute the hash of the provided password, using the same salt, // iteration count, and hash length byte[] testHash = pbkdf2(password, salt, iterations, hash.length); // Compare the hashes in constant time. The password is correct if // both hashes match. return slowEquals(hash, testHash); } /** * Compares two byte arrays in length-constant time. This comparison method * is used so that password hashes cannot be extracted from an on-line * system using a timing attack and then attacked off-line. * * @param a the first byte array * @param b the second byte array * @return true if both byte arrays are the same, false if not */ private boolean slowEquals(byte[] a, byte[] b) { int diff = a.length ^ b.length; for(int i = 0; i < a.length && i < b.length; i++) diff |= a[i] ^ b[i]; return diff == 0; } /** * Computes the PBKDF2 hash of a password. * * @param password the password to hash. * @param salt the salt * @param iterations the iteration count (slowness factor) * @param bytes the length of the hash to compute in bytes * @return the PBDKF2 hash of the password */ private byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes) throws NoSuchAlgorithmException, InvalidKeySpecException { PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8); SecretKeyFactory skf = SecretKeyFactory.getInstance(QUALIFIER_PBKDF2 +HASH_ALGORITHM); return skf.generateSecret(spec).getEncoded(); } /** * Converts a string of hexadecimal characters into a byte array. * * @param hex the hex string * @return the hex string decoded into a byte array */ private byte[] fromHex(String hex) { byte[] binary = new byte[hex.length() / 2]; for(int i = 0; i < binary.length; i++) { binary[i] = (byte)Integer.parseInt(hex.substring(2*i, 2*i+2), 16); } return binary; } /** * Converts a string of base64 characters into a byte array. * * @param base the base64 string * @return the base64 string decoded into a byte array */ private byte[] fromBase64(String base) { return Base64.getDecoder().decode(base); } /** * Converts a byte array into a hexadecimal string. * * @param array the byte array to convert * @return a length*2 character string encoding the byte array */ private String toHex(byte[] array) { BigInteger bi = new BigInteger(1, array); String hex = bi.toString(16); int paddingLength = (array.length * 2) - hex.length(); if(paddingLength > 0) return String.format("%0" + paddingLength + "d", 0) + hex; else return hex; } /** * Converts a byte array into a base64 string. * * @param array the byte array to convert * @return a string encoding the byte array */ private String toBase64(byte[] array) { return Base64.getEncoder().encodeToString(array); } }
package demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.support.SpringBootServletInitializer; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @SpringBootApplication public class DemoApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(DemoApplication.class); } public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Configuration static class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("home"); } } }
package net.aeten.core.spi; import static javax.lang.model.SourceVersion.RELEASE_7; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Generated; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import javax.tools.FileObject; import javax.tools.StandardLocation; import net.aeten.core.logging.LogLevel; @Provider (Processor.class) @SupportedAnnotationTypes ({ "net.aeten.core.spi.Provider", "net.aeten.core.spi.Configurations", "net.aeten.core.spi.Configuration" }) @SupportedSourceVersion (RELEASE_7) public class AnnotatedProviderProcessor extends AbstractProcessor { private static final Map <String, FileObject> servicesFileObjects = Collections.synchronizedMap (new HashMap <String, FileObject> ()); @Override public synchronized void init (ProcessingEnvironment processingEnv) { super.init (processingEnv); this.logLevel = LogLevel.DEBUG; } @SuppressWarnings ("unchecked") @Override public boolean process (Set <? extends TypeElement> annotations, RoundEnvironment roundEnv) { List <Element> initializers = new ArrayList <> (); for (Element element: roundEnv.getElementsAnnotatedWith (SpiInitializer.class)) { initializers.add (element); } for (Element element: roundEnv.getElementsAnnotatedWith (Configurations.class)) { for (AnnotationMirror configurations: getAnnotationMirrors (element, Configurations.class)) { for (AnnotationValue v: (Iterable <AnnotationValue>) getAnnotationValue (configurations).getValue ()) { this.configure (element, (AnnotationMirror) v.getValue (), initializers); } } } for (Element element: roundEnv.getElementsAnnotatedWith (Configuration.class)) { for (AnnotationMirror configuration: getAnnotationMirrors (element, Configuration.class)) { this.configure (element, configuration, initializers); } } for (Element provider: roundEnv.getElementsAnnotatedWith (Provider.class)) { Element initializer = null; for (Element element: initializers) { if (element.getEnclosingElement ().getEnclosingElement ().equals (provider)) { initializer = element; } } if (initializer == null) { registerProvider (provider); } } return true; } private void registerProvider (Element provider) { String providerClassName = getProperQualifiedName ((TypeElement) provider); for (AnnotationMirror annotation: getAnnotationMirrors (provider, Provider.class)) { for (AnnotationValue value: findValue (annotation)) { String service = value.getValue ().toString (); try { FileObject fileObject; synchronized (servicesFileObjects) { fileObject = servicesFileObjects.get (service); if (fileObject == null) { try { fileObject = processingEnv.getFiler ().createResource (StandardLocation.SOURCE_OUTPUT, "", "META-INF/services/" + service); } catch (Exception exception) { fileObject = processingEnv.getFiler ().getResource (StandardLocation.CLASS_OUTPUT, "", "META-INF/services/" + service); } } servicesFileObjects.put (service, fileObject); } StringWriter copy = new StringWriter (); boolean alreadyRegistered = false; try { BufferedReader reader = getReader (fileObject); String line; try { while ( (line = reader.readLine ()) != null) { copy.write (line + "\n"); if (line.trim ().equals (providerClassName)) { alreadyRegistered = true; } } } finally { reader.close (); } } catch (FileNotFoundException exception) { fileObject = processingEnv.getFiler ().createResource (StandardLocation.CLASS_OUTPUT, "", "META-INF/services/" + service); servicesFileObjects.put (service, fileObject); } if (!alreadyRegistered) { try (PrintWriter writer = getWriter (fileObject, WriteMode.OVERRIDE, true)) { writer.write (copy.toString ()); writer.println (providerClassName); note (AnnotatedProviderProcessor.class.getSimpleName () + " add provider " + providerClassName + " for service " + service); } } } catch (IOException | IllegalArgumentException exception) { error ("Fail to add provider " + providerClassName + " for service " + service, exception, provider); } } } } @SuppressWarnings ("unchecked") private void configure (Element element, AnnotationMirror configuration, List <Element> initializers) { AnnotationValue nameAnnotationValue = getAnnotationValue (configuration, "name"); String name = getClassName (nameAnnotationValue); String pkg = processingEnv.getElementUtils ().getPackageOf (element).getQualifiedName ().toString (); note (AnnotatedProviderProcessor.class.getName () + " creates " + pkg + "." + name); TypeElement providerElement = toElement (getAnnotationValue (configuration, "provider")); List <TypeElement> services = new ArrayList <> (); for (AnnotationMirror serviceAnnotation: getAnnotationMirrors (providerElement, Provider.class)) { AnnotationValue annotationValue = getAnnotationValue (serviceAnnotation); for (AnnotationValue value: (Iterable <AnnotationValue>) annotationValue.getValue ()) { services.add (toElement (value)); } } String parser = (String) getAnnotationValue (configuration, "parser").getValue (); try { FileObject fileObject = processingEnv.getFiler ().createSourceFile (pkg + "." + name, element); try (PrintWriter writer = getWriter (fileObject, WriteMode.OVERRIDE, false)) { TypeMirror initializerType = null; Iterator <? extends TypeMirror> thrownTypes = null; for (Element enclosedElement: providerElement.getEnclosedElements ()) { if (enclosedElement.getKind () == ElementKind.CONSTRUCTOR) { ExecutableElement constructor = (ExecutableElement) enclosedElement; if (constructor.getParameters ().size () == 1 && constructor.getParameters ().get (0).getAnnotation (SpiInitializer.class) != null) { initializerType = constructor.getParameters ().get (0).asType (); thrownTypes = constructor.getThrownTypes ().iterator (); break; } } } if (initializerType == null) { error ("SpiInitializer not found in " + providerElement, element); } String initializerClassName = initializerType.toString (); int classNamePosition = initializerClassName.lastIndexOf ('.'); if (classNamePosition != -1) { initializerClassName = initializerClassName.substring (classNamePosition + 1); } writer.println ("package " + pkg + ";"); writer.println (); List <String> toImport = new ArrayList <> (); String providerPackage = getPackageOf (providerElement); String providerClassName = getClassOf (providerElement); if (!pkg.equals (providerPackage)) { toImport.add (providerPackage + "." + initializerClassName); // Import only root enclosing class if is inner String providerRootImport = getProperQualifiedName (providerElement); int inner = providerRootImport.indexOf ('$'); if (inner != -1) { providerRootImport = providerRootImport.substring (0, inner); } toImport.add (providerRootImport); } for (TypeElement service: services) { if (!getPackageOf (service).equals (pkg)) { String serviceRootImport = getProperQualifiedName (service); int inner = serviceRootImport.indexOf ('$'); if (inner != -1) { serviceRootImport = serviceRootImport.substring (0, inner); } toImport.add (serviceRootImport); } } writeImport (writer, toImport, Generated.class, Provider.class, SpiConfiguration.class); writer.println (); writer.println ("@Generated(\"" + AnnotatedProviderProcessor.class.getName () + "\")"); writer.print ("@" + Provider.class.getSimpleName () + ( (services.size () > 1)? "({": "(")); for (Iterator <TypeElement> iterator = services.iterator (); iterator.hasNext ();) { writer.print (getClassOf (iterator.next ()) + ".class"); if (iterator.hasNext ()) { writer.write (", "); } } writer.println ( ( (services.size () > 1)? "})": ")")); writer.println ("public class " + name + " extends " + providerClassName + " {"); writer.print (" public " + name + " ()"); if (thrownTypes.hasNext ()) { writer.print (" throws "); } while (thrownTypes.hasNext ()) { writer.print (thrownTypes.next ().toString ()); if (thrownTypes.hasNext ()) { writer.print (", "); } } writer.println (" {"); writer.print (" super(new " + initializerClassName + "(new SpiConfiguration("); writer.print ("\"" + pkg + "\", " + "\"" + nameAnnotationValue.getValue () + "\", " + "\"" + parser + "\", " + providerClassName + ".class"); writer.println (")));"); writer.println (" }"); writer.println ("}"); writer.flush (); } } catch (IOException | IllegalArgumentException | Error exception) { error ("Unexpected exception", exception, element); } } private static String getClassName (AnnotationValue configurationFileNameAnnotationValue) { String[] words = ((String) configurationFileNameAnnotationValue.getValue ()).split ("[-_\\.]"); String className = ""; for (int i = 0; i < words.length - 1; i++) { className += upperFirstChar (words[i].toLowerCase ()); } return className; } }
package net.maizegenetics.analysis.imputation; /* * MinorWindowViterbiImputationPlugin */ import net.maizegenetics.dna.snp.*; import net.maizegenetics.dna.snp.io.ProjectionAlignmentIO; import net.maizegenetics.plugindef.AbstractPlugin; import net.maizegenetics.plugindef.DataSet; import net.maizegenetics.analysis.popgen.DonorHypoth; import net.maizegenetics.analysis.distance.IBSDistanceMatrix; import net.maizegenetics.prefs.TasselPrefs; import net.maizegenetics.util.*; import net.maizegenetics.util.BitSet; import org.apache.commons.lang.ArrayUtils; import org.apache.log4j.Logger; import javax.swing.*; import java.awt.*; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.text.DecimalFormat; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import net.maizegenetics.dna.map.PositionList; import static net.maizegenetics.dna.snp.GenotypeTable.UNKNOWN_DIPLOID_ALLELE; import static net.maizegenetics.dna.snp.GenotypeTable.WHICH_ALLELE.Major; import static net.maizegenetics.dna.snp.GenotypeTable.WHICH_ALLELE.Minor; import static net.maizegenetics.dna.snp.GenotypeTableUtils.isHeterozygous; import static net.maizegenetics.dna.snp.NucleotideAlignmentConstants.GAP_DIPLOID_ALLELE; import net.maizegenetics.dna.snp.genotypecall.GenotypeCallTableBuilder; /** * Imputation approach that relies on nearest neighbor searches of defined haplotypes, * followed by HMM Viterbi resolution or block-based resolution. * In June 2013, it is the best approach for substantially unrelated taxa. * <p> * The algorithm relies on having a series of donor haplotypes. If phased haplotypes are * already known, they can be used directly. If they need to be reconstructed, the * {@link FindMergeHaplotypesPlugin} can be used to create haplotypes for windows * across the genome. * <p> * Imputation is done one taxon at a time using the donor haplotypes. The strategy is as * follows: * <li> Every 64 sites is considered a block (or a word in the bitset terminology - length of a long). There is * a separate initial search for nearest neighbors centered around each block. The flanks * of the scan window vary but always contain the number of minor alleles specified (a key parameter). * Minor alleles approximate the information content of the search. * <li> Calculate distance between the target taxon and the donor haplotypes for every window, and rank * the top 10 donor haplotypes for each 64 site focus block. * <li> Evaluate by Viterbi whether 1 or 2 haplotypes will explain all the sites across the * donor haplotype window. If successful, move to the next region for donor haplotypes. * <li> Resolve each focus block by nearest neighbors. If inbred NN are not close enough, * then do a hybrid search seeded with one parent being the initial 10 haplotypes. * Set bases based on what is resolved first inbred or hybrid. * *<p> * Error rates are bounded away from zero, but adding 0.5 error to all error * rates that that were observed to be zero. * <p> * TODO: * <li>Move accuracy to one method outside of setAlignmentWithDonors * * @author Edward Buckler * @author Kelly Swarts * @cite */ //@Citation("Two papers: Viterbi from Bradbury, et al (in prep) Recombination patterns in maize\n"+ // "NearestNeighborSearch Swarts,...,Buckler (in prep) Imputation with large genotyping by sequencing data\n") public class FILLINImputationPlugin extends AbstractPlugin { private String hmpFile; private String donorFile; private String outFileBase; private String errFile=null; private boolean hybridNN=true;//if true, uses combination mode in focus block, else set don't impute (default is true) private int minMinorCnt=20; private int minMajorRatioToMinorCnt=10; //refinement of minMinorCnt to account for regions with all major private int maxDonorHypotheses=20; //number of hypotheses of record from an inbred or hybrid search of a focus block private boolean isOutputProjection=false; private double maximumInbredError=0.01; //inbreds are tested first, if too much error hybrids are tested. private double maxHybridErrorRate=0.003; private int minTestSites=100; //minimum number of compared sites to find a hit //kelly options private boolean twoWayViterbi= true;//if true, the viterbi runs in both directions (the longest path length wins, if inconsistencies) private double maxHybridErrFocusHomo= .001;//max error rate for discrepacy between two haplotypes for the focus block. it's default is higher because calculating for fewer sites private double maxInbredErrFocusHomo= .003; private double maxSmashErrFocusHomo= .01; private double maxInbredErrFocusHet= .001;//the error rate for imputing one haplotype in focus block for a het taxon private double maxSmashErrFocusHet= .01; private double hetThresh= 0.02;//threshold for whether a taxon is considered heterozygous //options for masking and calculating accuracy private String maskKeyFile= null; private double propSitesMask= .001; private GenotypeTable maskKey= null; private double[] MAFClass= null;//new double[]{0,.02,.05,.10,.20,.3,.4,.5,1}; private int[] MAF= null; private static String MAFFile; private double[][][] mafAll= null;//sam as all, but first array holds MAF category private double[][] all= new double[3][5]; //arrays held ("columns"): 0-maskedMinor, 1-maskedHet, 2-maskedMajor; each array ("rows"):0-to minor, 1-to het, 2-to major, 3-unimp, 4-total for known type private GenotypeTable unimpAlign; //the unimputed alignment to be imputed, unphased private int testing=0; //level of reporting to stdout //major and minor alleles can be differ between the donor and unimp alignment private boolean isSwapMajorMinor=true; //if swapped try to fix it private boolean resolveHetIfUndercalled=false;//if true, sets genotypes called to a het to a het, even if already a homozygote //variables for tracking accuracy private int totalRight=0, totalWrong=0, totalHets=0; //global variables tracking errors on the fly private int[] siteErrors, siteCorrectCnt, taxonErrors, taxonCorrectCnt; //error recorded by sites private boolean verboseOutput=true; //initialize the transition matrix (T1) double[][] transition = new double[][] { {.999,.0001,.0003,.0001,.0005}, {.0002,.999,.00005,.00005,.0002}, {.0002,.00005,.999,.00005,.0002}, {.0002,.00005,.00005,.999,.0002}, {.0005,.0001,.0003,.0001,.999} }; //i tried to optimize the transition matrix for the focus blocks, but peter's worked the best double[][] transitionFocus = transition; // new double[][] { // {.98,.04,.08,.04,.003}, // {.02,.98,.05,.0005,.0002}, // {.0002,.0005,.98,.0005,.0002}, // {.0002,.0005,.005,.98,.0002}, // {.003,.04,.08,.04,.98} //initialize the emission matrix, states (5) in rows, observations (3) in columns double[][] emission = new double[][] { {.998,.001,.001}, {.6,.2,.2}, {.4,.2,.4}, {.2,.2,.6}, {.001,.001,.998} }; // int[] donorIndices; private static ArgsEngine engine = new ArgsEngine(); private static final Logger myLogger = Logger.getLogger(FILLINImputationPlugin.class); public FILLINImputationPlugin() { super(null, false); } public FILLINImputationPlugin(Frame parentFrame) { super(parentFrame, false); } /** * * @param donorFile should be phased haplotypes * @param unImpTargetFile sites must match exactly with donor file * @param exportFile output file of imputed sites * @param minMinorCnt determines the size of the search window, low recombination 20-30, high recombination 10-15 * @param minTestSites * @param minSitesPresent * @param maxHybridErrorRate * @param isOutputProjection * @param imputeDonorFile */ public void runMinorWindowViterbiImputation(String donorFile, String unImpTargetFile, String exportFile, int minMinorCnt, int minTestSites, int minSitesPresent, double maxHybridErrorRate, boolean isOutputProjection, boolean imputeDonorFile) { long time=System.currentTimeMillis(); TasselPrefs.putAlignmentRetainRareAlleles(false); System.out.println("Retain Rare alleles is:"+TasselPrefs.getAlignmentRetainRareAlleles()); this.minTestSites=minTestSites; this.isOutputProjection=isOutputProjection; unimpAlign=ImportUtils.readGuessFormat(unImpTargetFile); GenotypeTable[] donorAlign; if(donorFile.contains(".gX")) {donorAlign=loadDonors(donorFile, unimpAlign, minTestSites, verboseOutput);} else {donorAlign=loadDonors(donorFile, unimpAlign, minTestSites, verboseOutput);} if (maskKeyFile!=null) { System.out.println("File already masked. Use input key file for calculating accuracy"); GenotypeTable inMaskKey= ImportUtils.readGuessFormat(maskKeyFile); if (inMaskKey.positions()!=unimpAlign.positions()) maskKey= filterKey(inMaskKey, unimpAlign); else maskKey= inMaskKey; } else if (unimpAlign.depth()!=null) unimpAlign= maskFileByDepth(unimpAlign,7, 7); else unimpAlign= maskPropSites(unimpAlign,propSitesMask); OpenBitSet[][] conflictMasks=createMaskForAlignmentConflicts(unimpAlign, donorAlign, verboseOutput); siteErrors=new int[unimpAlign.numberOfSites()]; siteCorrectCnt=new int[unimpAlign.numberOfSites()]; taxonErrors=new int[unimpAlign.numberOfTaxa()]; taxonCorrectCnt=new int[unimpAlign.numberOfTaxa()]; System.out.printf("Unimputed taxa:%d sites:%d %n",unimpAlign.numberOfTaxa(),unimpAlign.numberOfSites()); System.out.println("Creating mutable alignment"); Object mna=null; if(isOutputProjection) { mna=new ProjectionBuilder(ImportUtils.readGuessFormat(donorFile)); } else { if(exportFile.contains("hmp.h5")) { mna= GenotypeTableBuilder.getTaxaIncremental(this.unimpAlign.positions(),exportFile); }else { mna= GenotypeTableBuilder.getTaxaIncremental(this.unimpAlign.positions()); } } int numThreads = Runtime.getRuntime().availableProcessors(); double notMissing= 0; double het= 0; for (int taxon = 0; taxon < unimpAlign.numberOfTaxa(); taxon++) {het+= (double)unimpAlign.heterozygousCountForTaxon(taxon); notMissing+= (double)unimpAlign.totalNonMissingForTaxon(taxon);} double avgHet= het/notMissing; double sqDif= 0; for (int taxon = 0; taxon < unimpAlign.numberOfTaxa(); taxon++) {double x= avgHet-((double)unimpAlign.heterozygousCountForTaxon(taxon)/(double)unimpAlign.totalNonMissingForTaxon(taxon)); sqDif+= (x*x);} System.out.println("Average Heterozygosity: "+avgHet+" plus/minus std error: "+Math.sqrt(sqDif/(unimpAlign.numberOfTaxa()-1))/Math.sqrt(unimpAlign.numberOfTaxa())); System.out.println("Time to read in files and generate masks: "+((System.currentTimeMillis()-time)/1000)+" sec"); ExecutorService pool = Executors.newFixedThreadPool(numThreads); if (MAFFile!=null && MAFClass!=null) {MAF= readInMAFFile(MAFFile,unimpAlign, MAFClass); mafAll= new double[MAFClass.length][3][5]; System.out.println("Calculating accuracy within supplied MAF categories.");} for (int taxon = 0; taxon < unimpAlign.numberOfTaxa(); taxon+=1) { byte[] taxonKey= maskKey.genotypeAllSites(maskKey.taxa().indexOf(unimpAlign.taxaName(taxon)));//this is sloppy, but need to figure out how to filter taxon and sites. Key file does have to be in the same ordre as unimputed but need to contain all taxa. int[] trackBlockNN= new int[5];//global variable to track number of focus blocks solved in NN search for system out; index 0 is inbred, 1 is viterbi, 2 is smash, 3 is not solved, 4 is total for all modes ImputeOneTaxon theTaxon= (((double)unimpAlign.heterozygousCountForTaxon(taxon)/(double)unimpAlign.totalNonMissingForTaxon(taxon))<hetThresh)? new ImputeOneTaxon(taxon, donorAlign, taxonKey, minSitesPresent, conflictMasks,imputeDonorFile, mna, trackBlockNN, maxInbredErrFocusHomo, maxHybridErrFocusHomo, maxSmashErrFocusHomo, true): new ImputeOneTaxon(taxon, donorAlign, taxonKey, minSitesPresent, conflictMasks,imputeDonorFile, mna, trackBlockNN, maxInbredErrFocusHet, 0, maxSmashErrFocusHet, false); // theTaxon.run(); pool.execute(theTaxon); } pool.shutdown(); try{ if (!pool.awaitTermination(48, TimeUnit.HOURS)) { System.out.println("processing threads timed out."); } }catch(Exception e) { System.out.println("Error processing threads"); } System.out.println(""); StringBuilder s=new StringBuilder(); s.append(String.format("%s %s MinMinor:%d ", donorFile, unImpTargetFile, minMinorCnt)); System.out.println(s.toString()); //double errRate=(double)totalWrong/(double)(totalRight+totalWrong); //System.out.printf("TotalRight %d TotalWrong %d TotalHets: %d ErrRateExcHet:%g %n",totalRight, totalWrong, totalHets, errRate); if(isOutputProjection) { ProjectionAlignmentIO.writeToFile(exportFile, ((ProjectionBuilder)mna).build()); } else { GenotypeTableBuilder ab=(GenotypeTableBuilder)mna; if(ab.isHDF5()) { ab.build(); } else { ExportUtils.writeToHapmap(ab.build(), false, exportFile, '\t', null); } } System.out.printf("%d %g %d %n",minMinorCnt, maximumInbredError, maxDonorHypotheses); double runtime= (double)(System.currentTimeMillis()-time)/(double)1000; accuracyOut(all, runtime); if (MAFClass!=null) accuracyMAFOut(mafAll); System.out.println("Time to read in files, impute target genotypes, and calculate accuracy: "+runtime+" seconds"); } private class ImputeOneTaxon implements Runnable{ int taxon; GenotypeTable[] donorAlign; byte[] taxonKey; int minSitesPresent; OpenBitSet[][] conflictMasks; boolean imputeDonorFile; GenotypeTableBuilder alignBuilder=null; ProjectionBuilder projBuilder=null; int[] trackBlockNN;//global variable to track number of focus blocks solved in NN search for system out; index 0 is inbred, 1 is viterbi, 2 is smash, 3 is not solved, 4 is total for all modes double focusInbredErr; //threshold for one haplotype imputation in focus block mode double focusHybridErr; //threshold for Viterbi imputation in focus block mode double focusSmashErr; //threshold for haplotype combination in focus block mode boolean hetsMiss; //for inbred lines in two haplotype combination, set hets to missing because likely error. for heterozygous, impute estimated hets in focus block mode double[][] allOneTaxon= new double[3][5]; //arrays held ("columns"): 0-maskedMinor, 1-maskedHet, 2-maskedMajor; each array ("rows"):0-to minor, 1-to het, 2-to major, 3-unimp, 4-total for known type double[][][] mafTaxon; public ImputeOneTaxon(int taxon, GenotypeTable[] donorAlign, byte[] taxonKey, int minSitesPresent, OpenBitSet[][] conflictMasks, boolean imputeDonorFile, Object mna, int[] trackBlockNN, double focusInbErr, double focusHybridErr, double focusSmashErr, boolean hetsToMissing) { this.taxon=taxon; this.donorAlign=donorAlign; this.taxonKey=taxonKey; this.minSitesPresent=minSitesPresent; this.conflictMasks=conflictMasks; this.imputeDonorFile=imputeDonorFile; this.trackBlockNN=trackBlockNN; this.focusInbredErr=focusInbErr; this.focusHybridErr=focusHybridErr; this.focusSmashErr=focusSmashErr; this.hetsMiss=hetsToMissing; if(mna instanceof GenotypeTableBuilder) {alignBuilder=(GenotypeTableBuilder)mna;} else if(mna instanceof ProjectionBuilder) {projBuilder=(ProjectionBuilder)mna;} else {throw new IllegalArgumentException("Only Aligmnent or Projection Builders may be used.");} } @Override public void run() { StringBuilder sb=new StringBuilder(); String name=unimpAlign.taxaName(taxon); ImputedTaxon impTaxon=new ImputedTaxon(taxon, unimpAlign.genotypeAllSites(taxon),isOutputProjection); boolean het= (focusHybridErr==0)?true:false; int[] unkHets=countUnknownAndHets(impTaxon.getOrigGeno()); sb.append(String.format("Imputing %d:%s AsHet:%b Mj:%d, Mn:%d Unk:%d Hets:%d... ", taxon,name,het, unimpAlign.allelePresenceForAllSites(taxon, Major).cardinality(), unimpAlign.allelePresenceForAllSites(taxon, Minor).cardinality(), unkHets[0], unkHets[1])); boolean enoughData=(unimpAlign.totalNonMissingForTaxon(taxon)>minSitesPresent); // System.out.println("Too much missing data"); // continue; int countFullLength=0; int countByFocus= 0; for (int da = 0; (da < donorAlign.length)&&enoughData ; da++) { int donorOffset=unimpAlign.siteOfPhysicalPosition(donorAlign[da].chromosomalPosition(0), donorAlign[da].chromosome(0)); int blocks=donorAlign[da].allelePresenceForAllSites(0, Major).getNumWords(); BitSet[] maskedTargetBits=arrangeMajorMinorBtwAlignments(unimpAlign, taxon, donorOffset, donorAlign[da].numberOfSites(),conflictMasks[da][0],conflictMasks[da][1]); int[] donorIndices; if(imputeDonorFile){ donorIndices=new int[donorAlign[da].numberOfTaxa()-1]; for (int i = 0; i < donorIndices.length; i++) {donorIndices[i]=i; if(i>=taxon) donorIndices[i]++;} } else { donorIndices=new int[donorAlign[da].numberOfTaxa()]; for (int i = 0; i < donorIndices.length; i++) {donorIndices[i]=i;} } DonorHypoth[][] regionHypthInbred=new DonorHypoth[blocks][maxDonorHypotheses]; calcInbredDist(impTaxon,maskedTargetBits, donorAlign[da]); for (int focusBlock = 0; focusBlock < blocks; focusBlock++) { int[] resultRange=getBlockWithMinMinorCount(maskedTargetBits[0].getBits(),maskedTargetBits[1].getBits(), focusBlock, minMinorCnt); if(resultRange==null) continue; //no data in the focus Block //search for the best inbred donors for a segment regionHypthInbred[focusBlock]=getBestInbredDonors(taxon, impTaxon, resultRange[0],resultRange[2], focusBlock, donorAlign[da], donorIndices); } impTaxon.setSegmentSolved(false); //tries to solve the entire donorAlign region with 1 or 2 donor haplotypes impTaxon=apply1or2Haplotypes(taxon, donorAlign[da], donorOffset, regionHypthInbred, impTaxon, maskedTargetBits, maxHybridErrorRate); if(impTaxon.isSegmentSolved()) { // System.out.printf("VertSolved da:%d L:%s%n",da, donorAlign[da].getLocus(0)); countFullLength++; continue;} //resorts to solving block by block, first by inbred, then by viterbi, and then by hybrid impTaxon=applyBlockNN(impTaxon, taxon, donorAlign[da], donorOffset, regionHypthInbred, hybridNN, maskedTargetBits, minMinorCnt, focusInbredErr, focusHybridErr, focusSmashErr, donorIndices, trackBlockNN, hetsMiss); if(impTaxon.isSegmentSolved()) { // System.out.printf("VertSolved da:%d L:%s%n",da, donorAlign[da].getLocus(0)); countByFocus++; continue; } else continue; } double[][] accForTaxon= taxonAccuracy(taxonKey,impTaxon.getImpGeno(),unimpAlign, MAF, MAFClass); synchronized (all) {//add per taxon accuracy to total count. This prevents problems with multithreading, I think. for (int i = 0; i < accForTaxon.length; i++) { for (int j = 0; j < accForTaxon[i].length; j++) { all[i][j]+= accForTaxon[i][j];}} } if (MAFClass!=null) synchronized (mafAll) {//same as all, but sorted by MAF class for (int i = 0; i < mafTaxon.length; i++) { for (int j = 0; j < mafTaxon[0].length; j++) { for (int k = 0; k < mafTaxon[0][0].length; k++) { mafAll[i][j][k]+= mafTaxon[i][j][k];}}} } double totalFocus= (double)trackBlockNN[3]+(double)trackBlockNN[4]; sb.append(String.format("InbredOrViterbi:%d FocusBlock:%d PropFocusInbred:%f PropFocusViterbi:%f PropFocusSmash:%f PropFocusMissing:%f BlocksSolved:%d ", countFullLength, countByFocus, (double)trackBlockNN[0]/totalFocus, (double)trackBlockNN[1]/totalFocus, (double)trackBlockNN[2]/totalFocus, (double)trackBlockNN[3]/totalFocus, impTaxon.getBlocksSolved())); //sb.append(String.format("InbredOrViterbi:%d FocusBlock:%d BlocksSolved:%d ", countFullLength, countByFocus, impTaxon.getBlocksSolved())); int[] unk=countUnknownAndHets(impTaxon.resolveGeno); sb.append(String.format("Unk:%d PropMissing:%g ", unk[0], (double) unk[0] / (double) impTaxon.getOrigGeno().length)); sb.append(String.format("Het:%d PropHet:%g ", unk[1], (double)unk[1]/(double)impTaxon.getOrigGeno().length)); if(!isOutputProjection) { alignBuilder.addTaxon(unimpAlign.taxa().get(taxon), impTaxon.resolveGeno); } else { projBuilder.addTaxon(unimpAlign.taxa().get(taxon),impTaxon.getBreakPoints()); } // double rate=(double)taxon/(double)(System.currentTimeMillis()-time); // double remaining=(unimpAlign.getSequenceCount()-taxon)/(rate*1000); // System.out.printf("TimeLeft:%.1fs %n", remaining); if(verboseOutput) System.out.println(sb.toString()); // if(isOutputProjection) { // // System.out.println(breakPoints.toString()); // ((ProjectionAlignment)mna).setCompositionOfTaxon(taxon, impTaxon.breakPoints); } public double[][] taxonAccuracy(byte[] key, byte[] imputed, GenotypeTable unimpAlign, int[] MAF, double[] MAFClass) { byte diploidN= GenotypeTable.UNKNOWN_DIPLOID_ALLELE; double[][] all= new double[3][5]; boolean use= false; boolean mafOn= false; int maf= -1; if (MAF!=null && MAFClass!=null) {mafTaxon= new double[MAFClass.length][3][5]; use= true; mafOn= true;} for (int site = 0; site < imputed.length; site++) { use= (mafOn && MAF[site] > -1)?true:false; if (use) maf= MAF[site]; byte known = key[site]; if (known == diploidN) continue; byte imp = imputed[site]; if (GenotypeTableUtils.isHeterozygous(known) == true) { all[1][4]++; if (use) mafTaxon[maf][1][4]++; if (imp == diploidN) {all[1][3]++; if (use) mafTaxon[maf][1][3]++;} else if (GenotypeTableUtils.isEqual(imp, known) == true) {all[1][1]++; if (use) mafTaxon[maf][1][1]++;} else if (GenotypeTableUtils.isHeterozygous(imp) == false && GenotypeTableUtils.isPartiallyEqual(imp, unimpAlign.minorAllele(site)) == true) {all[1][0]++; if (use) mafTaxon[maf][1][0]++;}//to minor else if (GenotypeTableUtils.isHeterozygous(imp) == false && GenotypeTableUtils.isPartiallyEqual(imp, unimpAlign.majorAllele(site)) == true) {all[1][2]++; if (use) mafTaxon[maf][1][2]++;} else {all[1][4]--; if (use) mafTaxon[maf][1][4]--;}//implies >2 allele states at given genotype } else if (known == GenotypeTableUtils.getDiploidValue(unimpAlign.minorAllele(site),unimpAlign.minorAllele(site))) { all[0][4]++; if (use) mafTaxon[maf][0][4]++; if (imp == diploidN) {all[0][3]++; if (use) mafTaxon[maf][0][3]++;} else if (GenotypeTableUtils.isEqual(imp, known) == true) {all[0][0]++; if (use) mafTaxon[maf][0][0]++;} else if (GenotypeTableUtils.isHeterozygous(imp) == true && GenotypeTableUtils.isPartiallyEqual(imp, known) == true) {all[0][1]++; if (use) mafTaxon[maf][0][1]++;} else {all[0][2]++; if (use) mafTaxon[maf][0][3]++;} } else if (known == GenotypeTableUtils.getDiploidValue(unimpAlign.majorAllele(site),unimpAlign.majorAllele(site))) { all[2][4]++; if (use) mafTaxon[maf][2][4]++; if (imp == diploidN) {all[2][3]++; if (use) mafTaxon[maf][2][3]++;} else if (GenotypeTableUtils.isEqual(imp, known) == true) {all[2][2]++; if (use) mafTaxon[maf][2][2]++;} else if (GenotypeTableUtils.isHeterozygous(imp) == true && GenotypeTableUtils.isPartiallyEqual(imp, known) == true) {all[2][1]++; if (use) mafTaxon[maf][2][1]++;} else {all[2][0]++; if (use) mafTaxon[maf][2][0]++;} } else continue; } return all; } } public static GenotypeTable[] loadDonors(String donorFileRoot, GenotypeTable unimpAlign, int minTestSites, boolean verboseOutput){ File theDF=new File(donorFileRoot); String prefilter=theDF.getName().split(".gX.")[0]+".gc"; //grabs the left side of the file String prefilterOld=theDF.getName().split("s\\+")[0]+"s"; //grabs the left side of the file ArrayList<File> d=new ArrayList<File>(); for (File file : theDF.getParentFile().listFiles()) { if(file.getName().equals(theDF.getName())) {d.add(file);} if(file.getName().startsWith(prefilter)) {d.add(file);} if(file.getName().startsWith(prefilterOld)) {d.add(file);} } ArrayList<Integer> removeDonors= new ArrayList<>(); PositionList donU= unimpAlign.positions(); GenotypeTable[] donorAlign=new GenotypeTable[d.size()]; for (int i = 0; i < donorAlign.length; i++) { if(verboseOutput) System.out.println("Starting Read"); donorAlign[i]=ImportUtils.readFromHapmap(d.get(i).getPath(), (ProgressListener)null); ArrayList<Integer> subSites= new ArrayList<>(); PositionList donP= donorAlign[i].positions(); for (int j = 0; j < donorAlign[i].numberOfSites(); j++) {if (donU.indexOf(donP.get(j)) > -1) subSites.add(j);} //if unimputed contains donorAlign position keep in donor align if (subSites.size()!=donorAlign[i].numberOfSites()){ if (subSites.size()<2) { if(verboseOutput) System.out.printf("Donor file contains <2 matching sites and will not be used:%s",d.get(i).getPath()); removeDonors.add(i); } else { donorAlign[i]= FilterGenotypeTable.getInstance(donorAlign[i], ArrayUtils.toPrimitive(subSites.toArray(new Integer[subSites.size()]))); if(verboseOutput) System.out.printf("Donor file sites filtered to match target:%s taxa:%d sites:%d %n",d.get(i).getPath(), donorAlign[i].numberOfTaxa(),donorAlign[i].numberOfSites()); } if (subSites.size() < minTestSites*2 && verboseOutput) System.out.println("This donor alignment contains marginally sufficient matching snp positions. Region unlikely to impute well."); } else if(verboseOutput) System.out.printf("Donor file shares all sites with target:%s taxa:%d sites:%d %n",d.get(i).getPath(), donorAlign[i].numberOfTaxa(),donorAlign[i].numberOfSites()); //createMaskForAlignmentConflicts(unimpAlign,donorAlign[i],true); } if (removeDonors.isEmpty()==false) for(GenotypeTable gt:donorAlign) {donorAlign= (GenotypeTable[])ArrayUtils.removeElement(donorAlign, gt);} MAFFile= donorFileRoot.substring(0, donorFileRoot.indexOf(".gX"))+"MAF.txt"; if (new File(MAFFile).isFile()==false) generateMAF(MAFFile, donorAlign); return donorAlign; } //outputs a text file with minor allele frequencies by locus and position in the donor files. for accuracy public static void generateMAF(String MAFFileName, GenotypeTable[] donorAlign) { System.out.println("Generating MAF file for input donor files"); File outputFile = new File(MAFFile); try { DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile))); DecimalFormat df = new DecimalFormat("0. for (GenotypeTable don:donorAlign) { for (int site = 0; site < don.numberOfSites(); site++) { outStream.writeBytes(don.chromosomeName(site)+"\t"+don.chromosomalPosition(site)+"\t"+df.format(don.minorAlleleFrequency(site))+"\n"); } } } catch (Exception e) { System.out.println("Problem writing MAF file"); } } //returns an array the length of key.numberOfSites() that contains the MAF class index of the donor file or -1 if not included public static int[] readInMAFFile (String donorMAFFile, GenotypeTable unimpAlign, double[] MAFClass) { int[] MAF= new int[unimpAlign.numberOfSites()]; for (int i = 0; i < MAF.length; i++) {MAF[i]= -1;} //initialize to -1 try { FileInputStream fis= new FileInputStream(donorMAFFile); Scanner scanner= new Scanner(fis); do { String next= scanner.nextLine(); if (next.isEmpty()) break; String[] vals= next.split("\t"); int site= unimpAlign.siteOfPhysicalPosition(Integer.parseInt(vals[1]),unimpAlign.chromosome(vals[0])); if (site<0) continue; int currClass= Arrays.binarySearch(MAFClass, Double.parseDouble(vals[2])); MAF[site]= currClass<0?Math.abs(currClass)-1:currClass; } while (scanner.hasNextLine()); scanner.close(); fis.close(); } catch (Exception e) { System.out.println("Problem reading in taxa names"); } return MAF; } private ImputedTaxon apply1or2Haplotypes(int taxon, GenotypeTable donorAlign, int donorOffset, DonorHypoth[][] regionHypth, ImputedTaxon impT, BitSet[] maskedTargetBits, double maxHybridErrorRate) { int blocks=maskedTargetBits[0].getNumWords(); //do flanking search if(testing==1) System.out.println("Starting complete hybrid search"); int[] d=getAllBestDonorsAcrossChromosome(regionHypth,blocks/20); //TODO DonorHypoth[] best2donors=getBestHybridDonors(taxon, maskedTargetBits[0].getBits(), maskedTargetBits[1].getBits(), 0, blocks-1, blocks/2, donorAlign, d, d, true); if(testing==1) System.out.println(Arrays.toString(best2donors)); ArrayList<DonorHypoth> goodDH=new ArrayList<DonorHypoth>(); for (DonorHypoth dh : best2donors) { if((dh!=null)&&(dh.getErrorRate()<maxHybridErrorRate)) { if(dh.isInbred()==false){ dh=getStateBasedOnViterbi(dh, donorOffset, donorAlign, twoWayViterbi, transition); } if(dh!=null) goodDH.add(dh); } } if(goodDH.isEmpty()) return impT; DonorHypoth[] vdh=new DonorHypoth[goodDH.size()]; for (int i = 0; i < vdh.length; i++) {vdh[i]=goodDH.get(i);} impT.setSegmentSolved(true); return setAlignmentWithDonors(donorAlign,vdh, donorOffset,false,impT, false, false); } /** * Create mask for all sites where major & minor are swapped in alignments * returns in this order [goodMask, swapMjMnMask, errorMask, invariantMask] */ private OpenBitSet[][] createMaskForAlignmentConflicts(GenotypeTable unimpAlign, GenotypeTable[] donorAlign, boolean print) { OpenBitSet[][] result=new OpenBitSet[donorAlign.length][4]; for (int da = 0; da < result.length; da++) { // int donorOffset=unimpAlign.siteOfPhysicalPosition(donorAlign[da].chromosomalPosition(0), donorAlign[da].chromosome(0), donorAlign[da].siteName(0)); int donorOffset=unimpAlign.positions().indexOf(donorAlign[da].positions().get(0)); OpenBitSet goodMask=new OpenBitSet(donorAlign[da].numberOfSites()); OpenBitSet swapMjMnMask=new OpenBitSet(donorAlign[da].numberOfSites()); OpenBitSet errorMask=new OpenBitSet(donorAlign[da].numberOfSites()); OpenBitSet invariantMask=new OpenBitSet(donorAlign[da].numberOfSites()); int siteConflicts=0, swaps=0, invariant=0, good=0; for (int i = 0; i < donorAlign[da].numberOfSites(); i++) { /*we have three classes of data: invariant in one alignment, conflicts about minor and minor, *swaps of major and minor. Adding the invariant reduces imputation accuracy. *the major/minor swaps should be flipped in the comparisons */ byte tMj=unimpAlign.majorAllele(i + donorOffset); byte tMn=unimpAlign.minorAllele(i + donorOffset); byte daMj=donorAlign[da].majorAllele(i); byte daMn=donorAlign[da].minorAllele(i); if(daMn==GenotypeTable.UNKNOWN_ALLELE) { invariant++; invariantMask.set(i); goodMask.set(i); } else if((daMj==tMn)&&(daMn==tMj)) { swaps++; swapMjMnMask.set(i); goodMask.set(i); } else if((daMj!=tMj)) { siteConflicts++; errorMask.set(i); goodMask.set(i); } } goodMask.not(); if(print) System.out.println("Donor:"+da+"invariant in donor:"+invariant+" swapConflicts:"+swaps+" errors:"+siteConflicts); result[da]=new OpenBitSet[] {goodMask, swapMjMnMask, errorMask, invariantMask}; } return result; } //This assumes the input key contains all of the sites in unimpAlign, plus potentially more of either private GenotypeTable filterKey(GenotypeTable maskKey, GenotypeTable unimpAlign) { System.out.println("Filtering user input key file...\nSites in original Key file: "+maskKey.numberOfSites()); String[] unimpNames= new String[unimpAlign.numberOfSites()]; for (int site = 0; site < unimpAlign.numberOfSites(); site++) {unimpNames[site]= unimpAlign.siteName(site);} ArrayList<String> keepSites= new ArrayList<>();for (int site = 0; site < maskKey.numberOfSites(); site++) { if (unimpAlign.positions().indexOf(maskKey.positions().get(site))>-1) keepSites.add(maskKey.siteName(site)); } FilterGenotypeTable filter= FilterGenotypeTable.getInstance(maskKey, keepSites.toArray(new String[keepSites.size()])); GenotypeTable newMask= GenotypeTableBuilder.getGenotypeCopyInstance(filter); System.out.println("Sites in new mask: "+newMask.numberOfSites()); return newMask; } //for depths 4 or more, requires hets to be called by more than one for less depth allele. returns 2-array whre index 0 is mask and 1 is key private GenotypeTable maskFileByDepth(GenotypeTable a, int depthToMask, int maskDenom) { System.out.println("Masking file using depth\nSite depth to mask: "+depthToMask+"Divisor for physical positions to be masked: "+maskDenom); GenotypeCallTableBuilder mask= GenotypeCallTableBuilder.getInstance(a.numberOfTaxa(), a.numberOfSites()); GenotypeCallTableBuilder key= GenotypeCallTableBuilder.getInstance(a.numberOfTaxa(), a.numberOfSites()); int cnt= 0; for (int taxon = 0; taxon < a.numberOfTaxa(); taxon++) { int taxaCnt= 0; mask.setBaseRangeForTaxon(taxon, 0, a.genotypeAllSites(taxon)); for (int site = 0; site < a.numberOfSites(); site++) { if (GenotypeTableUtils.isEqual(NucleotideGenotypeTable.UNKNOWN_DIPLOID_ALLELE, a.genotype(taxon, site))) continue; if (a.physicalPositions()[site]%maskDenom!=0) continue; int[] currD= a.depthForAlleles(taxon, site); if (currD[0]+currD[1]!=depthToMask) continue; else if ((a.isHeterozygous(taxon, site)==false) || (depthToMask > 3 && currD[0] > 1 && currD[1] > 1)|| (depthToMask < 4)) { mask.setBase(taxon, site, NucleotideGenotypeTable.UNKNOWN_DIPLOID_ALLELE); key.setBase(taxon, site, a.genotype(taxon, site)); taxaCnt++; } } System.out.println(taxaCnt+" sites masked for "+a.taxaName(taxon)); cnt+= taxaCnt; } System.out.println(cnt+" sites masked at a depth of "+depthToMask+" (site numbers that can be divided by "+maskDenom+")"); maskKey= GenotypeTableBuilder.getInstance(key.build(), a.positions(), a.taxa()); return GenotypeTableBuilder.getInstance(mask.build(), a.positions(), a.taxa()); } private GenotypeTable maskPropSites(GenotypeTable a, double propSitesMask) { System.out.println("Masking file without depth\nMasking "+propSitesMask+" proportion of sites"); GenotypeCallTableBuilder mask= GenotypeCallTableBuilder.getInstance(a.numberOfTaxa(), a.numberOfSites()); GenotypeCallTableBuilder key= GenotypeCallTableBuilder.getInstance(a.numberOfTaxa(), a.numberOfSites()); int presGenos= 0; for (int taxon = 0; taxon < a.numberOfTaxa(); taxon++) {presGenos+= a.totalNonMissingForTaxon(taxon);} int expected= (int)(propSitesMask*(double)presGenos); int cnt= 0; for (int taxon = 0; taxon < a.numberOfTaxa(); taxon++) { int taxaCnt= 0; mask.setBaseRangeForTaxon(taxon, 0, a.genotypeAllSites(taxon)); for (int site = 0; site < a.numberOfSites(); site++) { if (Math.random()<propSitesMask && GenotypeTableUtils.isEqual(NucleotideGenotypeTable.UNKNOWN_DIPLOID_ALLELE, a.genotype(taxon, site))==false) { mask.setBase(taxon, site, NucleotideGenotypeTable.UNKNOWN_DIPLOID_ALLELE); key.setBase(taxon, site, a.genotype(taxon, site)); taxaCnt++; } } cnt+= taxaCnt; } System.out.println(cnt+" sites masked randomly not based on depth ("+expected+" expected at "+propSitesMask+")"); maskKey= GenotypeTableBuilder.getInstance(key.build(), a.positions(), a.taxa()); return GenotypeTableBuilder.getInstance(mask.build(), a.positions(), a.taxa()); } //this is the sample multiple r2. private static double pearsonR2(double[][] all) { int size= 0; for (int x = 0; x < 3; x++) {size+= (all[x][4]-all[x][3]);} double[][] xy= new double[2][size]; //0 is x, 1 is y int last= 0;//the last index filled for (double x = 0; x < 3; x++) { for (double y = 0; y < 3; y++) { for (int fill = last; fill < last+all[(int)x][(int)y]; fill++) { xy[0][fill]= x; xy[1][fill]= y; } last= last+(int)all[(int)x][(int)y]; }} double meanX= 0; double meanY= 0; double varX= 0; double varY= 0; double covXY= 0; double r2= 0.0; for (int i = 0; i < xy[0].length; i++) {meanX+=xy[0][i]; meanY+= xy[1][i];} meanX= meanX/(xy[0].length-1); meanY= meanY/(xy[1].length-1); double currX, currY; for (int i = 0; i < xy[0].length; i++) { currX= xy[0][i]-meanX; currY= xy[1][i]-meanY; varX+= currX*currX; varY+= currY*currY; covXY+= currX*currY; } r2= (covXY/(Math.sqrt(varX)*Math.sqrt(varY)))*(covXY/(Math.sqrt(varX)*Math.sqrt(varY))); System.out.println("Unadjusted R2 value for "+size+" comparisons: "+r2); return r2; } private void accuracyOut(double[][] all, double time) { DecimalFormat df = new DecimalFormat("0. double r2= pearsonR2(all); try { File outputFile = new File(outFileBase.substring(0, outFileBase.indexOf(".hmp")) + "DepthAccuracy.txt"); DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile))); outStream.writeBytes("##Taxon\tTotalSitesMasked\tTotalSitesCompared\tTotalPropUnimputed\tNumMinor\tCorrectMinor\tMinorToHet\tMinorToMajor\tUnimpMinor" + "\tNumHets\tHetToMinor\tCorrectHet\tHetToMajor\tUnimpHet\tNumMajor\tMajorToMinor\tMajorToHet\tCorrectMajor\tUnimpMajor\tR2\n"); outStream.writeBytes("##TotalByImputed\t"+(all[0][4]+all[1][4]+all[2][4])+"\t"+(all[0][4]+all[1][4]+all[2][4]-all[0][3]-all[1][3]-all[2][3])+"\t"+ ((all[0][3]+all[1][3]+all[2][3])/(all[0][4]+all[1][4]+all[2][4]))+"\t"+all[0][4]+"\t"+all[0][0]+"\t"+all[0][1]+"\t"+all[0][2]+"\t"+all[0][3]+ "\t"+all[1][4]+"\t"+all[1][0]+"\t"+all[1][1]+"\t"+all[1][2]+"\t"+all[1][3]+"\t"+all[2][4]+"\t"+all[2][0]+"\t"+all[2][1]+"\t"+all[2][2]+ "\t"+all[2][3]+"\t"+r2+"\n"); outStream.writeBytes("#Minor=0,Het=1,Major=2;x is masked(known), y is predicted\nx\ty\tN\tprop\n" +0+"\t"+0+"\t"+all[0][0]+"\t"+df.format((all[0][0])/(all[0][0]+all[0][1]+all[0][2]))+"\n" +0+"\t"+.5+"\t"+all[0][1]+"\t"+df.format((all[0][1])/(all[0][0]+all[0][1]+all[0][2]))+"\n" +0+"\t"+1+"\t"+all[0][2]+"\t"+df.format((all[0][2])/(all[0][0]+all[0][1]+all[0][2]))+"\n" +.5+"\t"+0+"\t"+all[1][0]+"\t"+df.format((all[1][0])/(all[1][0]+all[1][1]+all[1][2]))+"\n" +.5+"\t"+.5+"\t"+all[1][1]+"\t"+df.format((all[1][1])/(all[1][0]+all[1][1]+all[1][2]))+"\n" +.5+"\t"+1+"\t"+all[1][2]+"\t"+df.format((all[1][2])/(all[1][0]+all[1][1]+all[1][2]))+"\n" +1+"\t"+0+"\t"+all[2][0]+"\t"+df.format((all[2][0])/(all[2][0]+all[2][1]+all[2][2]))+"\n" +1+"\t"+.5+"\t"+all[2][1]+"\t"+df.format((all[2][1])/(all[2][0]+all[2][1]+all[2][2]))+"\n" +1+"\t"+1+"\t"+all[2][2]+"\t"+df.format((all[2][2])/(all[2][0]+all[2][1]+all[2][2]))+"\n"); outStream.writeBytes("#Proportion unimputed:\n#minor <- "+all[0][3]/all[0][4]+"\n#het<- "+all[1][3]/all[1][4]+"\n#major<- "+all[2][3]/all[2][4]+"\n"); outStream.writeBytes("#Time to impute and calculate accuracy: "+time+" seconds"); System.out.println("##Taxon\tTotalSitesMasked\tTotalSitesCompared\tTotalPropUnimputed\tNumMinor\tCorrectMinor\tMinorToHet\tMinorToMajor\tUnimpMinor" + "\tNumHets\tHetToMinor\tCorrectHet\tHetToMajor\tUnimpHet\tNumMajor\tMajorToMinor\tMajorToHet\tCorrectMajor\tUnimpMajor\tR2"); System.out.println("TotalByImputed\t"+(all[0][4]+all[1][4]+all[2][4])+"\t"+(all[0][4]+all[1][4]+all[2][4]-all[0][3]-all[1][3]-all[2][3])+"\t"+ ((all[0][3]+all[1][3]+all[2][3])/(all[0][4]+all[1][4]+all[2][4]))+"\t"+all[0][4]+"\t"+all[0][0]+"\t"+all[0][1]+"\t"+all[0][2]+"\t"+all[0][3]+ "\t"+all[1][4]+"\t"+all[1][0]+"\t"+all[1][1]+"\t"+all[1][2]+"\t"+all[1][3]+"\t"+all[2][4]+"\t"+all[2][0]+"\t"+all[2][1]+"\t"+all[2][2]+ "\t"+all[2][3]+"\t"+r2); System.out.println("Proportion unimputed:\nminor: "+all[0][3]/all[0][4]+"\nhet: "+all[1][3]/all[1][4]+"\nmajor: "+all[2][3]/all[2][4]); System.out.println("#Minor=0,Het=1,Major=2;x is masked(known), y is predicted\nx\ty\tN\tprop\n" +0+"\t"+0+"\t"+all[0][0]+"\t"+(all[0][0])/(all[0][0]+all[0][1]+all[0][2])+"\n" +0+"\t"+.5+"\t"+all[0][1]+"\t"+(all[0][1])/(all[0][0]+all[0][1]+all[0][2])+"\n" +0+"\t"+1+"\t"+all[0][2]+"\t"+(all[0][2])/(all[0][0]+all[0][1]+all[0][2])+"\n" +.5+"\t"+0+"\t"+all[1][0]+"\t"+(all[1][0])/(all[1][0]+all[1][1]+all[1][2])+"\n" +.5+"\t"+.5+"\t"+all[1][1]+"\t"+(all[1][1])/(all[1][0]+all[1][1]+all[1][2])+"\n" +.5+"\t"+1+"\t"+all[1][2]+"\t"+(all[1][2])/(all[1][0]+all[1][1]+all[1][2])+"\n" +1+"\t"+0+"\t"+all[2][0]+"\t"+(all[2][0])/(all[2][0]+all[2][1]+all[2][2])+"\n" +1+"\t"+.5+"\t"+all[2][1]+"\t"+(all[2][1])/(all[2][0]+all[2][1]+all[2][2])+"\n" +1+"\t"+1+"\t"+all[2][2]+"\t"+(all[2][2])/(all[2][0]+all[2][1]+all[2][2])+"\n"); outStream.close(); } catch (Exception e) { System.out.println(e); } } private void accuracyMAFOut(double[][][] mafAll) { DecimalFormat df = new DecimalFormat("0. if (MAF!=null && MAFClass!=null) try { File outputFile = new File(outFileBase.substring(0, outFileBase.indexOf(".hmp")) + "DepthAccuracyMAF.txt"); DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile))); outStream.writeBytes("##\tMAFClass\tTotalSitesMasked\tTotalSitesCompared\tTotalPropUnimputed\tNumHets\tHetToMinor\tHetToMajor\tCorrectHet\tUnimpHet\tNumMinor\tMinorToMajor\tMinorToHet\tCorrectMinor\t" + "UnimpMinor\tNumMajor\tMajorToMinor\tMajorToHet\tCorrectMajor\tUnimputedMajor\tr2\n"); for (int i= 0; i<MAFClass.length;i++) { outStream.writeBytes("##TotalByImputed\t"+MAFClass[i]+"\t"+(mafAll[i][0][4]+mafAll[i][1][4]+mafAll[i][2][4])+"\t"+(mafAll[i][0][4]+mafAll[i][1][4]+mafAll[i][2][4]-mafAll[i][0][3]-mafAll[i][1][3]-mafAll[i][2][3])+"\t"+ ((mafAll[i][0][3]+mafAll[i][1][3]+mafAll[i][2][3])/(mafAll[i][0][4]+mafAll[i][1][4]+mafAll[i][2][4]))+"\t"+mafAll[i][0][4]+"\t"+mafAll[i][0][0]+"\t"+mafAll[i][0][1]+"\t"+mafAll[i][0][2]+"\t"+mafAll[i][0][3]+ "\t"+mafAll[i][1][4]+"\t"+mafAll[i][1][0]+"\t"+mafAll[i][1][1]+"\t"+mafAll[i][1][2]+"\t"+mafAll[i][1][3]+"\t"+mafAll[i][2][4]+"\t"+mafAll[i][2][0]+"\t"+mafAll[i][2][1]+"\t"+mafAll[i][2][2]+ "\t"+mafAll[i][2][3]+"\t"+pearsonR2(mafAll[i])+"\n"); } outStream.writeBytes("#MAFClass,Minor=0,Het=1,Major=2;x is masked(known), y is predicted\nMAF\tx\ty\tN\tprop\n"); for (int i= 0; i<MAFClass.length;i++) { outStream.writeBytes( MAFClass[i]+"\t"+0+"\t"+0+"\t"+mafAll[i][0][0]+"\t"+df.format((mafAll[i][0][0])/(mafAll[i][0][0]+mafAll[i][0][1]+mafAll[i][0][2]))+"\n" +MAFClass[i]+"\t"+0+"\t"+.5+"\t"+mafAll[i][0][1]+"\t"+df.format((mafAll[i][0][1])/(mafAll[i][0][0]+mafAll[i][0][1]+mafAll[i][0][2]))+"\n" +MAFClass[i]+"\t"+0+"\t"+1+"\t"+mafAll[i][0][2]+"\t"+df.format((mafAll[i][0][2])/(mafAll[i][0][0]+mafAll[i][0][1]+mafAll[i][0][2]))+"\n" +MAFClass[i]+"\t"+.5+"\t"+0+"\t"+mafAll[i][1][0]+"\t"+df.format((mafAll[i][1][0])/(mafAll[i][1][0]+mafAll[i][1][1]+mafAll[i][1][2]))+"\n" +MAFClass[i]+"\t"+.5+"\t"+.5+"\t"+mafAll[i][1][1]+"\t"+df.format((mafAll[i][1][1])/(mafAll[i][1][0]+mafAll[i][1][1]+mafAll[i][1][2]))+"\n" +MAFClass[i]+"\t"+.5+"\t"+1+"\t"+mafAll[i][1][2]+"\t"+df.format((mafAll[i][1][2])/(mafAll[i][1][0]+mafAll[i][1][1]+mafAll[i][1][2]))+"\n" +MAFClass[i]+"\t"+1+"\t"+0+"\t"+mafAll[i][2][0]+"\t"+df.format((mafAll[i][2][0])/(mafAll[i][2][0]+mafAll[i][2][1]+mafAll[i][2][2]))+"\n" +MAFClass[i]+"\t"+1+"\t"+.5+"\t"+mafAll[i][2][1]+"\t"+df.format((mafAll[i][2][1])/(mafAll[i][2][0]+mafAll[i][2][1]+mafAll[i][2][2]))+"\n" +MAFClass[i]+"\t"+1+"\t"+1+"\t"+mafAll[i][2][2]+"\t"+df.format((mafAll[i][2][2])/(mafAll[i][2][0]+mafAll[i][2][1]+mafAll[i][2][2]))+"\n"); } outStream.writeBytes("#Proportion unimputed:\n#MAF\tminor\thet\tmajor\n"); for (int i= 0; i<MAFClass.length;i++) { outStream.writeBytes("#"+MAFClass[i]+"\t"+mafAll[i][0][3]/mafAll[i][0][4]+"\t"+mafAll[i][1][3]/mafAll[i][1][4]+"\t"+mafAll[i][2][3]/mafAll[i][2][4]+"\n"); } outStream.flush(); outStream.close(); } catch (Exception e) { System.out.println(e); } } private int[] countUnknownAndHets(byte[] a) { int cnt=0, cntHets=0; for (int i = 0; i < a.length; i++) { if(a[i]==UNKNOWN_DIPLOID_ALLELE) {cnt++;} else if(isHeterozygous(a[i])) {cntHets++;} } return new int[]{cnt,cntHets}; } private BitSet[] arrangeMajorMinorBtwAlignments(GenotypeTable unimpAlign, int bt, int donorOffset, int donorLength, OpenBitSet goodMask, OpenBitSet swapMjMnMask) { int unimpAlignStartBlock=donorOffset/64; int shift=(donorOffset-(unimpAlignStartBlock*64)); int unimpAlignEndBlock=unimpAlignStartBlock+((donorLength+shift-1)/64); OpenBitSet mjUnImp=new OpenBitSet(unimpAlign.allelePresenceForSitesBlock(bt, Major, unimpAlignStartBlock, unimpAlignEndBlock + 1)); OpenBitSet mnUnImp=new OpenBitSet(unimpAlign.allelePresenceForSitesBlock(bt, Minor, unimpAlignStartBlock, unimpAlignEndBlock + 1)); OpenBitSet mjTbs=new OpenBitSet(donorLength); OpenBitSet mnTbs=new OpenBitSet(donorLength); for (int i = 0; i < donorLength; i++) { if(mjUnImp.fastGet(i+shift)) mjTbs.set(i); if(mnUnImp.fastGet(i+shift)) mnTbs.set(i); } OpenBitSet newmj=new OpenBitSet(mjTbs); OpenBitSet newmn=new OpenBitSet(mnTbs); mjTbs.and(goodMask); mnTbs.and(goodMask); // System.out.printf("mjTbs:%d Goodmask:%d swapMjMnMask:%d",mjTbs.getNumWords(),goodMask.getNumWords(), swapMjMnMask.getNumWords()); if(isSwapMajorMinor) { newmj.and(swapMjMnMask); newmn.and(swapMjMnMask); mjTbs.or(newmn); mnTbs.or(newmj); } // System.out.printf("Arrange shift:%d finalEnd:%d totalBits:%d DesiredLength:%d %n", shift, finalEnd, totalBits, donorLength); BitSet[] result={mjTbs,mnTbs}; return result; } /** * If the target regions has Mendelian errors that it looks for overlapping regional * solutions that are better. * TODO: This can be done much more robustly. * @param impT * @param targetTaxon * @param regionHypth */ private ImputedTaxon applyBlockNN(ImputedTaxon impT, int targetTaxon, GenotypeTable donorAlign, int donorOffset, DonorHypoth[][] regionHypth, boolean hybridMode, BitSet[] maskedTargetBits, int minMinorCnt, double focusInbredErr, double focusHybridErr, double focusSmashErr, int[] donorIndices, int[] blockNN, boolean hetsToMiss) { int[] currBlocksSolved= new int[5];//track number of focus blocks solved in NN search for system out; index 0 is inbred, 1 is viterbi, 2 is smash, 3 is not solved, 4 is total for all modes int blocks=maskedTargetBits[0].getNumWords(); for (int focusBlock = 0; focusBlock < blocks; focusBlock++) { boolean vit= false;//just if viterbi works for this block int[] d= getUniqueDonorsForBlock(regionHypth,focusBlock);//get the donor indices for that block from regionHypoth int[] resultRange=getBlockWithMinMinorCount(maskedTargetBits[0].getBits(),maskedTargetBits[1].getBits(), focusBlock, minMinorCnt); if(resultRange==null) {currBlocksSolved[3]++; continue; } //no data in the focus Block if(d==null) {currBlocksSolved[3]++; continue; } //no donors for the focus block //search for the best hybrid donors for a segment DonorHypoth[] best2donors=getBestHybridDonors(targetTaxon, maskedTargetBits[0].getBits(resultRange[0], resultRange[2]), maskedTargetBits[1].getBits(resultRange[0], resultRange[2]), resultRange[0], resultRange[2], focusBlock, donorAlign, d, d, true); if(best2donors[0]==null) {currBlocksSolved[3]++; continue; } //no good hybrid donors for the focus block //check for Viterbi and inbred ArrayList<DonorHypoth> goodDH= new ArrayList<DonorHypoth>(); //KLS0201 if (best2donors[0].getErrorRate()<focusInbredErr) { for (DonorHypoth dh : best2donors) { if((dh!=null)) { if((dh.isInbred()==false)&&(dh.getErrorRate()<focusHybridErr)){ dh=getStateBasedOnViterbi(dh, donorOffset, donorAlign, twoWayViterbi, transition); if(dh!=null) vit= true; } if(dh!=null&&(dh.getErrorRate()<focusInbredErr)) goodDH.add(dh); } } if (goodDH.size()!=0) { DonorHypoth[] vdh=new DonorHypoth[goodDH.size()]; for (int i = 0; i < vdh.length; i++) {vdh[i]=goodDH.get(i);} regionHypth[focusBlock]= vdh; impT= setAlignmentWithDonors(donorAlign, regionHypth[focusBlock], donorOffset, true, impT, false, false); impT.incBlocksSolved(); if(vit==true) {currBlocksSolved[1]++;} else {currBlocksSolved[0]++;} currBlocksSolved[4]++; continue; } } //if fails, try smash mode else if (hybridMode&&(best2donors[0].getErrorRate()<focusSmashErr)) {//smash mode goes into hybrid block NN for (DonorHypoth dh:best2donors) { if(dh!=null&&dh.getErrorRate()<focusSmashErr) { goodDH.add(dh); } if (goodDH.size()!=0) { DonorHypoth[] vdh=new DonorHypoth[goodDH.size()]; for (int i = 0; i < vdh.length; i++) {vdh[i]=goodDH.get(i);} regionHypth[focusBlock]= vdh; impT= setAlignmentWithDonors(donorAlign, regionHypth[focusBlock], donorOffset, true,impT, true, hetsToMiss);//only set donors for focus block //KLS0201 impT.incBlocksSolved(); currBlocksSolved[2]++; currBlocksSolved[4]++; continue; } } //if fails, do not impute this focus block } else currBlocksSolved[3]++; } if (currBlocksSolved[4]!=0) impT.setSegmentSolved(true); else impT.setSegmentSolved(false); int leftNullCnt=currBlocksSolved[3]; if(testing==1) System.out.printf("targetTaxon:%d hybridError:%g block:%d proportionBlocksImputed:%d null:%d inbredDone:%d viterbiDone:%d hybridDone:%d noData:%d %n", targetTaxon, focusHybridErr, blocks,currBlocksSolved[4]/blocks, leftNullCnt, currBlocksSolved[0], currBlocksSolved[1], currBlocksSolved[2], currBlocksSolved[3]); for (int i = 0; i < currBlocksSolved.length; i++) {blockNN[i]+= currBlocksSolved[i];} return impT; } private DonorHypoth getStateBasedOnViterbi(DonorHypoth dh, int donorOffset, GenotypeTable donorAlign, boolean forwardReverse, double[][] trans) { TransitionProbability tpF = new TransitionProbability(); EmissionProbability ep = new EmissionProbability(); tpF.setTransitionProbability(trans); ep.setEmissionProbability(emission); int startSite=dh.startBlock*64; int endSite=(dh.endBlock*64)+63; if(endSite>=donorAlign.numberOfSites()) endSite=donorAlign.numberOfSites()-1; int sites=endSite-startSite+1; byte[] callsF=new byte[sites]; byte[] callsR=new byte[sites]; //System.out.printf("%d %d %d %n",dh.donor1Taxon, startSite, endSite+1); byte[] d1b=donorAlign.genotypeRange(dh.donor1Taxon, startSite, endSite + 1); byte[] d2b=donorAlign.genotypeRange(dh.donor2Taxon, startSite, endSite + 1); byte[] t1b=unimpAlign.genotypeRange(dh.targetTaxon, startSite + donorOffset, endSite + 1 + donorOffset); int informSites=0, nonMendel=0; ArrayList<Byte> nonMissingObs = new ArrayList<Byte>(); ArrayList<Integer> snpPositions = new ArrayList<Integer>(); for(int cs=0; cs<sites; cs++) { if(t1b[cs]==UNKNOWN_DIPLOID_ALLELE) continue; if(d1b[cs]==UNKNOWN_DIPLOID_ALLELE) continue; if(d2b[cs]==UNKNOWN_DIPLOID_ALLELE) continue; if(t1b[cs]==GAP_DIPLOID_ALLELE) continue; if(d1b[cs]==GAP_DIPLOID_ALLELE) continue; if(d2b[cs]==GAP_DIPLOID_ALLELE) continue; if(d1b[cs]==d2b[cs]) { if(t1b[cs]!=d1b[cs]) nonMendel++; continue; } informSites++; byte state=1; if(t1b[cs]==d1b[cs]) {state=0;} else if(t1b[cs]==d2b[cs]) {state=2;} nonMissingObs.add(state); snpPositions.add(cs+startSite); } if(informSites<10) return null; double nonMendRate=(double)nonMendel/(double)informSites; if(testing==1) System.out.printf("NonMendel:%d InformSites:%d ErrorRate:%g %n",nonMendel, informSites, nonMendRate); if(nonMendRate>this.maximumInbredError*5) return null; byte[] informStatesF=new byte[informSites]; for (int i = 0; i < informStatesF.length; i++) informStatesF[i]=nonMissingObs.get(i); int[] pos=new int[informSites]; for (int i = 0; i < pos.length; i++) pos[i]=snpPositions.get(i); int chrlength = donorAlign.chromosomalPosition(endSite) - donorAlign.chromosomalPosition(startSite); tpF.setAverageSegmentLength( chrlength / sites ); tpF.setPositions(pos); double probHeterozygous=0.5; double phom = (1 - probHeterozygous) / 2; double[] pTrue = new double[]{phom, .25*probHeterozygous ,.5 * probHeterozygous, .25*probHeterozygous, phom}; ViterbiAlgorithm vaF = new ViterbiAlgorithm(informStatesF, tpF, ep, pTrue); vaF.calculate(); if(testing==1) System.out.println("Input:"+Arrays.toString(informStatesF)); byte[] resultStatesF=vaF.getMostProbableStateSequence(); if(testing==1) System.out.println("Resul:"+Arrays.toString(resultStatesF)); DonorHypoth dh2=new DonorHypoth(dh.targetTaxon,dh.donor1Taxon, dh.donor2Taxon, dh.startBlock, dh.focusBlock, dh.endBlock); int currPos=0; for(int cs=0; cs<sites; cs++) { callsF[cs]=(resultStatesF[currPos]==1)?(byte)1:(byte)(resultStatesF[currPos]/2); //converts the scale back to 0,1,2 from 0..4 if((pos[currPos]<cs+startSite)&&(currPos<resultStatesF.length-1)) currPos++; } if (forwardReverse==true) { TransitionProbability tpR = new TransitionProbability(); tpR.setTransitionProbability(transition); byte[] informStatesR= informStatesF; ArrayUtils.reverse(informStatesR); int[] posR= pos; ArrayUtils.reverse(posR); tpR.setAverageSegmentLength( chrlength / sites ); tpR.setPositions(posR); ViterbiAlgorithm vaR = new ViterbiAlgorithm(informStatesR, tpR, ep, pTrue); vaR.calculate(); byte[] resultStatesR=vaR.getMostProbableStateSequence();//this sequence is backwards/from the reverse viterbi ArrayUtils.reverse(resultStatesR); //flip the reverse viterbi calls to the same orientation as forward int currPosR=0; for(int cs=0; cs<sites; cs++) { //converts the scale back to 0,1,2 from 0..4 callsR[cs]=(resultStatesR[currPosR]==1)?(byte)1:(byte)(resultStatesR[currPosR]/2); if((pos[currPosR]<cs+startSite)&&(currPosR<resultStatesF.length-1)) currPosR++; } //compare the forward and reverse viterbi, use the one with the longest path length if they contradict byte[] callsC=callsF; for(int i= 0;i<pos.length;i++) { int cs= pos[i]-startSite; if (callsF[cs]!=callsR[cs]&&i<pos.length/2) callsC[cs]= callsR[cs]; } if (testing==1) { if (resultStatesF[0]!=resultStatesR[0]||resultStatesF[resultStatesF.length-1]!=resultStatesR[resultStatesR.length-1]) System.out.println("FR:\n"+Arrays.toString(informStatesF)+"\n"+Arrays.toString(informStatesR)+"\n"+Arrays.toString(resultStatesF)+"\n"+Arrays.toString(resultStatesR)+"\n"+Arrays.toString(callsF)+"\n"+Arrays.toString(callsR)+"\n"+Arrays.toString(callsC)); } dh2.phasedResults= callsC; return dh2; } dh2.phasedResults= callsF; return dh2; } /** * Given a start 64 site block, it expands to the left and right until it hits * the minimum Minor Site count in the target taxon * @param mnT - minor allele bit presence in a series of longs * @param focusBlock * @param minMinorCnt * @return arrays of blocks {startBlock, focusBlock, endBlock} */ private int[] getBlockWithMinMinorCount(long[] mjT, long[] mnT, int focusBlock, int minMinorCnt) { int blocks=mjT.length; int majorCnt=Long.bitCount(mjT[focusBlock]); int minorCnt=Long.bitCount(mnT[focusBlock]); int endBlock=focusBlock, startBlock=focusBlock; int minMajorCnt=minMinorCnt*minMajorRatioToMinorCnt; while((minorCnt<minMinorCnt)&&(majorCnt<minMajorCnt)) { boolean preferMoveStart=(focusBlock-startBlock<endBlock-focusBlock)?true:false; if(startBlock==0) {preferMoveStart=false;} if(endBlock==blocks-1) {preferMoveStart=true;} if((startBlock==0)&&(endBlock==blocks-1)) break; if(preferMoveStart) {//expand start startBlock minorCnt+=Long.bitCount(mnT[startBlock]); majorCnt+=Long.bitCount(mjT[startBlock]); } else { //expand end endBlock++; minorCnt+=Long.bitCount(mnT[endBlock]); majorCnt+=Long.bitCount(mjT[startBlock]); } } int[] result={startBlock, focusBlock, endBlock}; return result; } /** * Calculates an inbred distance * TODO: Should be converted to the regular same, diff, hets, & sum * @param modBitsOfTarget * @return array with sites, same count, diff count, het count */ private void calcInbredDist(ImputedTaxon impT, BitSet[] modBitsOfTarget, GenotypeTable donorAlign) { int blocks=modBitsOfTarget[0].getNumWords(); impT.allDist=new byte[donorAlign.numberOfTaxa()][4][blocks]; long[] iMj=modBitsOfTarget[0].getBits(); long[] iMn=modBitsOfTarget[1].getBits(); for (int donor1 = 0; donor1 < impT.allDist.length; donor1++) { long[] jMj=donorAlign.allelePresenceForAllSites(donor1, Major).getBits(); long[] jMn=donorAlign.allelePresenceForAllSites(donor1, Minor).getBits(); for (int i = 0; i <blocks; i++) { long same = (iMj[i] & jMj[i]) | (iMn[i] & jMn[i]); long diff = (iMj[i] & jMn[i]) | (iMn[i] & jMj[i]); long hets = same & diff; int sameCnt = BitUtil.pop(same); int diffCnt = BitUtil.pop(diff); int hetCnt = BitUtil.pop(hets); int sites = sameCnt + diffCnt - hetCnt; impT.allDist[donor1][2][i]=(byte)diffCnt; impT.allDist[donor1][3][i]=(byte)hetCnt; impT.allDist[donor1][0][i]=(byte)sites; impT.allDist[donor1][1][i]=(byte)sameCnt; } } } /** * Simple algorithm that tests every possible two donor combination to minimize * the number of unmatched informative alleles. Currently, there is litte tie * breaking, longer matches are favored. * @param targetTaxon * @param startBlock * @param endBlock * @param focusBlock * @return int[] array of {donor1, donor2, testSites} */ private DonorHypoth[] getBestInbredDonors(int targetTaxon, ImputedTaxon impT, int startBlock, int endBlock, int focusBlock, GenotypeTable donorAlign, int[] donor1indices) { TreeMap<Double,DonorHypoth> bestDonors=new TreeMap<Double,DonorHypoth>(); double lastKeytestPropUnmatched=1.0; double inc=1e-9; int donorTaxaCnt=donorAlign.numberOfTaxa(); for (int d1 : donor1indices) { int testSites=0; int sameCnt = 0, diffCnt = 0, hetCnt = 0; for (int i = startBlock; i <=endBlock; i++) { sameCnt+=impT.allDist[d1][1][i]; diffCnt+=impT.allDist[d1][2][i]; hetCnt+=impT.allDist[d1][3][i]; } testSites= sameCnt + diffCnt - hetCnt; if(testSites<minTestSites) continue; double testPropUnmatched = 1.0-(((double) (sameCnt) - (double)(0.5*hetCnt)) / (double) (testSites)); int totalMendelianErrors=(int)((double)testSites*testPropUnmatched); //prob of this given poisson with lambda=1, total Mendelian errors=k (WE SHOULD DO THIS) inc+=1e-9; //this looks strange, but makes the keys unique and ordered testPropUnmatched+=inc; //this looks strange, but makes the keys unique and ordered if(testPropUnmatched<lastKeytestPropUnmatched) { DonorHypoth theDH=new DonorHypoth(targetTaxon, d1, d1, startBlock, focusBlock, endBlock, testSites, totalMendelianErrors); DonorHypoth prev=bestDonors.put(new Double(testPropUnmatched), theDH); if(prev!=null) System.out.println("Inbred TreeMap index crash:"+testPropUnmatched); if(bestDonors.size()>maxDonorHypotheses) { bestDonors.remove(bestDonors.lastKey()); lastKeytestPropUnmatched=bestDonors.lastKey(); } } } //TODO consider reranking by Poisson. The calculating Poisson on the fly is too slow. DonorHypoth[] result=new DonorHypoth[maxDonorHypotheses]; int count=0; for (DonorHypoth dh : bestDonors.values()) { result[count]=dh; count++; } return result; } /** * Produces a sort list of most prevalent donorHypotheses across the donorAlign. * Currently it is only looking at the very best for each focus block. * @param allDH * @param minHypotheses * @return */ private int[] getAllBestDonorsAcrossChromosome(DonorHypoth[][] allDH, int minHypotheses) { TreeMap<Integer,Integer> bd=new TreeMap<Integer,Integer>(); for (int i = 0; i < allDH.length; i++) { DonorHypoth dh=allDH[i][0]; if(dh==null) continue; if(bd.containsKey(dh.donor1Taxon)) { bd.put(dh.donor1Taxon, bd.get(dh.donor1Taxon)+1); } else { bd.put(dh.donor1Taxon, 1); } } if(testing==1) System.out.println(bd.size()+":"+bd.toString()); if(testing==1) System.out.println(""); int highDonors=0; for (int i : bd.values()) {if(i>minHypotheses) highDonors++;} int[] result=new int[highDonors]; highDonors=0; for (Map.Entry<Integer,Integer> e: bd.entrySet()) { if(e.getValue()>minHypotheses) result[highDonors++]=e.getKey();} if(testing==1) System.out.println(Arrays.toString(result)); return result; } private int[] getUniqueDonorsForBlock(DonorHypoth[][] regionHypth, int block) {//change so only adding those donors that are not identical for target blocks TreeSet<Integer> donors= new TreeSet<>(); for (int h = 0; h < regionHypth[block].length; h++) { if (regionHypth[block][h]!=null) { donors.add(regionHypth[block][h].donor1Taxon); donors.add(regionHypth[block][h].donor2Taxon); } } if (donors.isEmpty()) return null; int[] result= ArrayUtils.toPrimitive(donors.toArray(new Integer[donors.size()])); return result; } /** * Simple algorithm that tests every possible two donor combination to minimize * the number of unmatched informative alleles. Currently, there is litte tie * breaking, longer matches are favored. * @param targetTaxon * @param startBlock * @param endBlock * @param focusBlock * @return int[] array of {donor1, donor2, testSites} */ private DonorHypoth[] getBestHybridDonors(int targetTaxon, long[] mjT, long[] mnT, int startBlock, int endBlock, int focusBlock, GenotypeTable donorAlign, int[] donor1Indices, int[] donor2Indices, boolean viterbiSearch) { TreeMap<Double,DonorHypoth> bestDonors=new TreeMap<Double,DonorHypoth>(); double lastKeytestPropUnmatched=1.0; double inc=1e-9; double[] donorDist; for (int d1: donor1Indices) { long[] mj1=donorAlign.allelePresenceForSitesBlock(d1, Major, startBlock, endBlock + 1); long[] mn1=donorAlign.allelePresenceForSitesBlock(d1, Minor, startBlock, endBlock + 1); for (int d2 : donor2Indices) { if((!viterbiSearch)&&(d1==d2)) continue; long[] mj2=donorAlign.allelePresenceForSitesBlock(d2, Major, startBlock, endBlock + 1); long[] mn2=donorAlign.allelePresenceForSitesBlock(d2, Minor, startBlock, endBlock + 1); if(viterbiSearch) { donorDist=IBSDistanceMatrix.computeHetBitDistances(mj1, mn1, mj2, mn2, minTestSites); if((d1!=d2)&&(donorDist[0]<this.maximumInbredError)) continue; } int[] mendErr=mendelErrorComparison(mjT, mnT, mj1, mn1, mj2, mn2); if(mendErr[1]<minTestSites) continue; double testPropUnmatched=(double)(mendErr[0])/(double)mendErr[1]; inc+=1e-9; testPropUnmatched+=inc; if(testPropUnmatched<lastKeytestPropUnmatched) { DonorHypoth theDH=new DonorHypoth(targetTaxon, d1, d2, startBlock, focusBlock, endBlock, mendErr[1], mendErr[0]); DonorHypoth prev=bestDonors.put(new Double(testPropUnmatched), theDH); if(prev!=null) { System.out.println("Hybrid TreeMap index crash:"+testPropUnmatched); } if(bestDonors.size()>maxDonorHypotheses) { bestDonors.remove(bestDonors.lastKey()); lastKeytestPropUnmatched=bestDonors.lastKey(); } } } } DonorHypoth[] result=new DonorHypoth[maxDonorHypotheses]; int count=0; for (DonorHypoth dh : bestDonors.values()) { result[count]=dh; count++; } return result; } private int[] mendelErrorComparison(long[] mjT, long[] mnT, long[] mj1, long[] mn1, long[] mj2, long[] mn2) { int mjUnmatched=0; int mnUnmatched=0; int testSites=0; for (int i = 0; i < mjT.length; i++) { long siteMask=(mjT[i]|mnT[i])&(mj1[i]|mn1[i])&(mj2[i]|mn2[i]); mjUnmatched+=Long.bitCount(siteMask&mjT[i]&(mjT[i]^mj1[i])&(mjT[i]^mj2[i])); mnUnmatched+=Long.bitCount(siteMask&mnT[i]&(mnT[i]^mn1[i])&(mnT[i]^mn2[i])); testSites+=Long.bitCount(siteMask); } int totalMendelianErrors=mjUnmatched+mnUnmatched; // double testPropUnmatched=(double)(totalMendelianErrors)/(double)testSites; return (new int[] {totalMendelianErrors, testSites}); } private ImputedTaxon setAlignmentWithDonors(GenotypeTable donorAlign, DonorHypoth[] theDH, int donorOffset, boolean setJustFocus, ImputedTaxon impT, boolean smashOn, boolean hetsMiss) { if(theDH[0].targetTaxon<0) return impT; boolean print=false; int startSite=(setJustFocus)?theDH[0].getFocusStartSite():theDH[0].startSite; int endSite=(setJustFocus)?theDH[0].getFocusEndSite():theDH[0].endSite; if(endSite>=donorAlign.numberOfSites()) endSite=donorAlign.numberOfSites()-1; // if (print) System.out.println("B:"+mna.getBaseAsStringRange(theDH[0].targetTaxon, startSite, endSite)); // int[] prevDonors; int[] prevDonors=new int[]{-1, -1}; if(theDH[0].getPhaseForSite(startSite)==0) {prevDonors=new int[]{theDH[0].donor1Taxon, theDH[0].donor1Taxon};} else if(theDH[0].getPhaseForSite(startSite)==2) {prevDonors=new int[]{theDH[0].donor2Taxon, theDH[0].donor2Taxon};} else if(theDH[0].getPhaseForSite(startSite)==1) {prevDonors=new int[]{theDH[0].donor1Taxon, theDH[0].donor2Taxon};} // if(impT.areBreakPointsEmpty()) { // prevDonors=new int[]{-1, -1}; // } else { // prevDonors=impT.breakPoints.lastEntry().getValue(); int[] currDonors=prevDonors; //this generates an alignment of the closest donors for the taxon block from the results of the hybrid donor search (to use for frequencies using 2PQ) // TreeSet<Identifier> closeDonors; // closeDonors= new TreeSet<>(); // for (DonorHypoth dh:theDH) { // closeDonors.add(donorAlign.getIdGroup().getIdentifier(dh.donor1Taxon)); closeDonors.add(donorAlign.getIdGroup().getIdentifier(dh.donor2Taxon)); // IdGroup ids= new SimpleIdGroup(closeDonors.toArray(new Identifier[closeDonors.size()])); // Alignment bestDonors= FilterAlignment.getInstance(donorAlign, ids); for(int cs=startSite; cs<=endSite; cs++) { byte donorEst=UNKNOWN_DIPLOID_ALLELE; byte neighbor=0; for (int i = 0; (i < theDH.length) && (donorEst==UNKNOWN_DIPLOID_ALLELE); i++) { neighbor++; if((theDH[i]==null)||(theDH[i].donor1Taxon<0)) continue; if(theDH[i].getErrorRate()>this.maximumInbredError) continue; byte bD1=donorAlign.genotype(theDH[i].donor1Taxon, cs); if(theDH[i].getPhaseForSite(cs)==0) { donorEst=bD1; if(i==0) currDonors=new int[]{theDH[0].donor1Taxon, theDH[0].donor1Taxon}; } else { byte bD2=donorAlign.genotype(theDH[i].donor2Taxon, cs); if(theDH[i].getPhaseForSite(cs)==2) { donorEst=bD2; if(i==0) currDonors=new int[]{theDH[0].donor2Taxon, theDH[0].donor2Taxon}; } else { donorEst=GenotypeTableUtils.getUnphasedDiploidValueNoHets(bD1, bD2); if(i==0) currDonors=new int[]{theDH[0].donor1Taxon, theDH[0].donor2Taxon}; } } } byte knownBase=impT.getOrigGeno(cs+donorOffset); String knownBaseString= NucleotideAlignmentConstants.getNucleotideIUPAC(knownBase); if(!Arrays.equals(prevDonors, currDonors)) { // impT.breakPoints.put(donorAlign.chromosomalPosition(cs), currDonors); //TODO fix this for projection prevDonors=currDonors; } if(theDH[0].phasedResults==null) {impT.chgHis[cs+donorOffset]=(byte)-neighbor;} else {impT.chgHis[cs+donorOffset]=(byte)neighbor;} impT.impGeno[cs+donorOffset]= donorEst; //predicted based on neighbor String donorEstString= NucleotideAlignmentConstants.getNucleotideIUPAC(donorEst); if(knownBase==UNKNOWN_DIPLOID_ALLELE) { if (isHeterozygous(donorEst)) { if (smashOn && hetsMiss) {//if imputing a heterozygote, just set to missing impT.resolveGeno[cs+donorOffset]= knownBase; //System.out.println("SetToMissing"+":"+theDH[0].targetTaxon+":"+cs+donorOffset+":"+knownBaseString+":"+donorEstString); } else impT.resolveGeno[cs+donorOffset]= donorEst; //if not in hybrid, set to het } else {//if not imputed to a het impT.resolveGeno[cs+donorOffset]= donorEst;} } else if (isHeterozygous(donorEst)){ if(resolveHetIfUndercalled&&GenotypeTableUtils.isPartiallyEqual(knownBase, donorEst)&&smashOn==false){//if smash off, set homozygotes imputed to het to het System.out.println("ResolveHet:"+theDH[0].targetTaxon+":"+cs+donorOffset+":"+knownBaseString+":"+donorEstString); impT.resolveGeno[cs+donorOffset]= donorEst; } } } //end of cs loop //enter a stop of the DH at the beginning of the next block int lastDApos=donorAlign.chromosomalPosition(endSite); int nextSite=unimpAlign.siteOfPhysicalPosition(lastDApos, donorAlign.chromosome(0))+1; // if(nextSite<unimpAlign.numberOfSites()) impT.breakPoints.put(unimpAlign.chromosomalPosition(nextSite), new int[]{-1,-1}); //TODO fix this for projection // if (print) System.out.println("E:"+mna.getBaseAsStringRange(theDH[0].targetTaxon, startSite, endSite)); return impT; /** * Code that records results to projectionGenotype. Some of this may be needed above. if(!Arrays.equals(prevDonors, currDonors)) { DonorHaplotypes dhaps=new DonorHaplotypes(donorAlign.chromosome(prevDonorStart), donorAlign.chromosomalPosition(prevDonorStart), donorAlign.chromosomalPosition(cs),prevDonors[0],prevDonors[1]); impT.addBreakPoint(dhaps); prevDonors=currDonors; prevDonorStart=cs; } if(theDH[0].phasedResults==null) {impT.chgHis[cs+donorOffset]=(byte)-neighbor;} else {impT.chgHis[cs+donorOffset]=(byte)neighbor;} impT.impGeno[cs+donorOffset]= donorEst; //predicted based on neighbor if(knownBase==UNKNOWN_DIPLOID_ALLELE) {impT.resolveGeno[cs+donorOffset]= donorEst;} else {if(isHeterozygous(donorEst)) { if(resolveHetIfUndercalled&&GenotypeTableUtils.isPartiallyEqual(knownBase,donorEst)) {//System.out.println(theDH[0].targetTaxon+":"+knownBase+":"+donorEst); impT.resolveGeno[cs+donorOffset]= donorEst;} }} } //end of cs loop DonorHaplotypes dhaps=new DonorHaplotypes(donorAlign.chromosome(prevDonorStart), donorAlign.chromosomalPosition(prevDonorStart), donorAlign.chromosomalPosition(endSite),prevDonors[0],prevDonors[1]); impT.addBreakPoint(dhaps); */ } private double calcErrorForTaxonAndSite(ImputedTaxon impT) { for (int cs = 0; cs < impT.getOrigGeno().length; cs++) { byte donorEst=impT.getImpGeno(cs); byte knownBase=impT.getOrigGeno(cs); if((knownBase!=UNKNOWN_DIPLOID_ALLELE)&&(donorEst!=UNKNOWN_DIPLOID_ALLELE)) { if(isHeterozygous(donorEst)||isHeterozygous(knownBase)) { totalHets++; } else if(knownBase==donorEst) { totalRight++; siteCorrectCnt[cs]++; taxonCorrectCnt[impT.taxon()]++; } else { totalWrong++; siteErrors[cs]++; taxonErrors[impT.taxon()]++; } } } return (double)taxonErrors[impT.taxon()]/(double)(taxonCorrectCnt[impT.taxon()]+taxonErrors[impT.taxon()]); } public static int[] compareAlignment(String origFile, String maskFile, String impFile, boolean noMask) { boolean taxaOut=false; GenotypeTable oA=ImportUtils.readGuessFormat(origFile); System.out.printf("Orig taxa:%d sites:%d %n",oA.numberOfTaxa(),oA.numberOfSites()); GenotypeTable mA=null; if(noMask==false) {mA=ImportUtils.readGuessFormat(maskFile); System.out.printf("Mask taxa:%d sites:%d %n",mA.numberOfTaxa(),mA.numberOfSites()); } GenotypeTable iA=ImportUtils.readGuessFormat(impFile); System.out.printf("Imp taxa:%d sites:%d %n",iA.numberOfTaxa(),iA.numberOfSites()); int correct=0; int errors=0; int unimp=0; int hets=0; int gaps=0; for (int t = 0; t < iA.numberOfTaxa(); t++) { int e=0,c=0,u=0,h=0; int oATaxa=oA.taxa().indexOf(iA.taxaName(t)); for (int s = 0; s < iA.numberOfSites(); s++) { if(noMask||(oA.genotype(oATaxa, s)!=mA.genotype(t, s))) { byte ib=iA.genotype(t, s); byte ob=oA.genotype(oATaxa, s); if((ib==UNKNOWN_DIPLOID_ALLELE)||(ob==UNKNOWN_DIPLOID_ALLELE)) {unimp++; u++;} else if(ib==GAP_DIPLOID_ALLELE) {gaps++;} else if(ib==ob) { correct++; c++; } else { if(isHeterozygous(ob)||isHeterozygous(ib)) {hets++; h++;} else {errors++; e++; // if(t==0) System.out.printf("%d %d %s %s %n",t,s,oA.getBaseAsString(oATaxa, s), iA.getBaseAsString(t, s)); } } } } if(taxaOut) System.out.printf("%s %d %d %d %d %n",iA.taxaName(t),u,h,c,e); } System.out.println("MFile\tIFile\tGap\tUnimp\tUnimpHets\tCorrect\tErrors"); System.out.printf("%s\t%s\t%d\t%d\t%d\t%d\t%d%n",maskFile, impFile, gaps, unimp,hets,correct,errors); return new int[]{gaps, unimp,hets,correct,errors}; } @Override public void setParameters(String[] args) { if (args.length == 0) { printUsage(); throw new IllegalArgumentException("\n\nPlease use the above arguments/options.\n\n"); } engine.add("-hmp", "-hmpFile", true); engine.add("-o", "--outFile", true); engine.add("-d", "--donorH", true); engine.add("-maskKeyFile", "--maskKeyFile", true); engine.add("-propSitesMask", "--propSitesMask", true); engine.add("-mxHet", "--hetThresh", true); engine.add("-sC", "--startChrom", false); //TODO why set to false engine.add("-eC", "--endChrom", false); //TODO why set to false engine.add("-minMnCnt", "--minMnCnt", true); engine.add("-mxInbErr", "--mxInbErr", true); engine.add("-mxHybErr", "--mxHybErr", true); engine.add("-mxVitFocusErr", "--mxVitFocusErr", true); engine.add("-mxInbFocusErr", "--mbIndFocusErr", true); engine.add("-mxComFocusErr", "--mxComFocusErr", true); engine.add("-mxInbFocusErrHet", "--mxInbFocusErrHet", true); engine.add("-mxComFocusErrHet", "--mxComFocusErrHet", true); engine.add("-hybNNOff", "--hybNNOff", true); engine.add("-mxDonH", "--mxDonH", true); engine.add("-mnTestSite", "--mnTestSite", true); engine.add("-projA", "--projAlign", false); engine.add("-runChrMode", "--runChrMode", false); engine.add("-nV", "--nonVerbose",false); engine.parse(args); hmpFile = engine.getString("-hmp"); outFileBase = engine.getString("-o"); donorFile = engine.getString("-d"); maskKeyFile = engine.getString("-maskKeyFile"); if(engine.getBoolean("-mxHet")) { hetThresh = Double.parseDouble(engine.getString("-mxHet")); } if(engine.getBoolean("-mxHet")) { propSitesMask = Double.parseDouble(engine.getString("-propSitesMask")); } if (engine.getBoolean("-mxInbErr")) { maximumInbredError = Double.parseDouble(engine.getString("-mxInbErr")); } if (engine.getBoolean("-mxHybErr")) { maxHybridErrorRate = Double.parseDouble(engine.getString("-mxHybErr")); } if (engine.getBoolean("-mxVitFocusErr")) { maxHybridErrFocusHomo = Double.parseDouble(engine.getString("-mxVitFocusErr")); } if (engine.getBoolean("-mxInbFocusErr")) { maxInbredErrFocusHomo = Double.parseDouble(engine.getString("-mxInbFocusErr")); } if (engine.getBoolean("-mxComFocusErr")) { maxSmashErrFocusHomo = Double.parseDouble(engine.getString("-mxComFocusErr")); } if (engine.getBoolean("-mxInbFocusErrHet")) { maxInbredErrFocusHet = Double.parseDouble(engine.getString("-mxInbFocusErrHet")); } if (engine.getBoolean("-mxComFocusErrHet")) { maxSmashErrFocusHet = Double.parseDouble(engine.getString("-mxComFocusErrHet")); } if (engine.getBoolean("-minMnCnt")) { minMinorCnt = Integer.parseInt(engine.getString("-minMnCnt")); } if (engine.getBoolean("-hybNNOff")) hybridNN=false; if (engine.getBoolean("-mxDonH")) { maxDonorHypotheses = Integer.parseInt(engine.getString("-mxDonH")); } if (engine.getBoolean("-mnTestSite")) { minTestSites = Integer.parseInt(engine.getString("-mnTestSite")); } if (engine.getBoolean("-projA")) isOutputProjection=true; if (engine.getBoolean("-nV")) verboseOutput=false; } private void printUsage() { myLogger.info( "\n\n\nAvailable options for the FILLINImputationPlugin are as follows:\n" + "-hmp Input HapMap file of target genotypes to impute. Accepts all file types supported by TASSEL5\n" + "-d Donor haplotype files from output of FILLINFindHaplotypesPlugin. Use “.gX” in the input filename to denote the substring “.gc + "-o Output file; hmp.txt.gz and .hmp.h5 accepted. Required\n" + "-maskKeyFile An optional key file to indicate that file is already masked for accuracy calculation. Non-missing genotypes indicate masked sites. Else, will generate own mask\n" + "-propSitesMask The proportion of non missing sites to mask for accuracy calculation if depth is not available (default:"+propSitesMask+"\n" + "-mxHet Threshold per taxon heterozygosity for treating taxon as heterozygous (no Viterbi, het thresholds). (default:"+hetThresh+"\n" + "-minMnCnt Minimum number of informative minor alleles in the search window (or "+minMajorRatioToMinorCnt+"X major)\n" + "-mxInbErr Maximum error rate for applying one haplotype to entire site window (default:"+maximumInbredError+"\n" + "-mxHybErr Maximum error rate for applying Viterbi with to haplotypes to entire site window (default:"+maxHybridErrorRate+"\n" + "-mxVitFocusErr Maximum error rate for applying Viterbi with to haplotypes to entire site window (default:"+maxHybridErrFocusHomo+")\n" + "-mxInbFocusErr Maximum error rate to apply one haplotype for inbred (heterozygosity below mxHet) taxon for 64-site focus blocks (default:"+maxInbredErrFocusHomo+")\n" + "-mxComFocusErr Maximum error rate to apply two haplotypes modeled as a heterozygote for inbred (heterozygosity below mxHet) taxon for 64-site focus blocks (default:"+maxSmashErrFocusHomo+")\n" + "-mxInbFocusErrHet Maximum error rate to apply one haplotype for outbred (heterozygosity above mxHet) taxon for 64-site focus blocks (default:"+maxInbredErrFocusHet+")\n" + "-mxComFocusErrHet Maximum error rate to apply two haplotypes modeled as a heterozygote for outbred (heterozygosity above mxHet) taxon for 64-site focus blocks (default:"+maxSmashErrFocusHet+")\n" + "-hybNNOff Whether to model two haplotypes as heterozygotic for focus blocks (default:"+hybridNN+")\n" + "-mxDonH Maximum number of donor hypotheses to be explored (default: "+maxDonorHypotheses+")\n" + "-mnTestSite Minimum number of sites to test for IBS between haplotype and target in focus block (default:"+minTestSites+")\n" + "-projA Create a projection alignment for high density markers (default off)\n" ); } @Override public DataSet performFunction(DataSet input) { runMinorWindowViterbiImputation(donorFile, hmpFile, outFileBase, minMinorCnt, minTestSites, 100, maxHybridErrorRate, isOutputProjection, false); return null; } @Override public ImageIcon getIcon() { return null; } @Override public String getButtonName() { return "ImputeByFILLIN"; } @Override public String getToolTipText() { return "Imputation that relies on a combination of HMM and Nearest Neighbor"; } }
package net.maizegenetics.analysis.imputation; import net.maizegenetics.analysis.distance.IBSDistanceMatrix; import net.maizegenetics.analysis.popgen.DonorHypoth; import net.maizegenetics.dna.map.DonorHaplotypes; import net.maizegenetics.dna.map.PositionList; import net.maizegenetics.dna.snp.*; import net.maizegenetics.dna.snp.io.ProjectionGenotypeIO; import net.maizegenetics.plugindef.AbstractPlugin; import net.maizegenetics.plugindef.DataSet; import net.maizegenetics.prefs.TasselPrefs; import net.maizegenetics.util.ArgsEngine; import net.maizegenetics.util.BitSet; import net.maizegenetics.util.OpenBitSet; import net.maizegenetics.util.ProgressListener; import org.apache.commons.lang.ArrayUtils; import org.apache.log4j.Logger; import javax.swing.*; import java.awt.*; import java.io.File; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static net.maizegenetics.dna.snp.GenotypeTable.UNKNOWN_DIPLOID_ALLELE; import static net.maizegenetics.dna.snp.GenotypeTable.WHICH_ALLELE.Major; import static net.maizegenetics.dna.snp.GenotypeTable.WHICH_ALLELE.Minor; import static net.maizegenetics.dna.snp.GenotypeTableUtils.isHeterozygous; import static net.maizegenetics.dna.snp.NucleotideAlignmentConstants.GAP_DIPLOID_ALLELE; /** * FILLIN imputation relies on a libary of haplotypes and uses nearest neighbor searches * followed by HMM Viterbi resolution or block-based resolution. * It is the best approach for substantially unrelated taxa in TASSEL. BEAGLE4 is a better * approach currently for landraces, while FILLIN outperforms if there is a good reference * set of haplotypes. * <p></p> * The algorithm relies on having a series of donor haplotypes. If phased haplotypes are * already known, they can be used directly. If they need to be reconstructed, the * {@link FindMergeHaplotypesPlugin} can be used to create haplotypes for windows * across the genome. * <p></p> * Imputation is done one taxon at a time using the donor haplotypes. The strategy is as * follows: * <li></li>Every 64 sites is considered a block (or a word in the bitset terminology - length of a long). There is * a separate initial search for nearest neighbors centered around each block. The flanks * of the scan window vary but always contain the number of minor alleles specified (a key parameter). * Minor alleles approximate the information content of the search. * <li></li> Calculate distance between the target taxon and the donor haplotypes for every window, and rank * the top 10 donor haplotypes for each 64 site focus block. * <li></li> Evaluate by Viterbi whether 1 or 2 haplotypes will explain all the sites across the * donor haplotype window. If successful, move to the next region for donor haplotypes. * <li></li> Resolve each focus block by nearest neighbors. If inbred NN are not close enough, * then do a hybrid search seeded with one parent being the initial 10 haplotypes. * Set bases based on what is resolved first inbred or hybrid. * *<p></p> * Error rates are bounded away from zero, but adding 0.5 error to all error * rates that that were observed to be zero. * <p></p> * @author Edward Buckler * @author Kelly Swarts * @cite */ //@Citation("Two papers: Viterbi from Bradbury, et al (in prep) Recombination patterns in maize\n"+ // "NearestNeighborSearch Swarts,...,Buckler (in prep) Imputation with large genotyping by sequencing data\n") public class FILLINImputationPlugin extends AbstractPlugin { private String hmpFile; private String donorFile; private String outFileBase; private String errFile=null; private boolean hybridNN=true;//if true, uses combination mode in focus block, else set don't impute (default is true) private int minMinorCnt=20; private int minMajorRatioToMinorCnt=10; //refinement of minMinorCnt to account for regions with all major private int maxDonorHypotheses=20; //number of hypotheses of record from an inbred or hybrid search of a focus block private boolean isOutputProjection=false; private double maximumInbredError=0.01; //inbreds are tested first, if too much error hybrids are tested. private double maxHybridErrorRate=0.003; private int minTestSites=100; //minimum number of compared sites to find a hit //kelly options private boolean twoWayViterbi= true;//if true, the viterbi runs in both directions (the longest path length wins, if inconsistencies) private double minimumHybridDonorDistance=maximumInbredError*5; //options for focus blocks private double maxHybridErrFocusHomo= .3333*maxHybridErrorRate;////max error rate for discrepacy between two haplotypes for the focus block. it's default is higher because calculating for fewer sites private double maxInbredErrFocusHomo= .3*maximumInbredError;//.003; private double maxSmashErrFocusHomo= maximumInbredError; private double maxInbredErrFocusHet= .1*maximumInbredError;//.001;//the error rate for imputing one haplotype in focus block for a het taxon private double maxSmashErrFocusHet= maximumInbredError; private double hetThresh= 0.02;//threshold for whether a taxon is considered heterozygous //options for masking and calculating accuracy private boolean accuracyOn= true; private String maskKeyFile= null; private double propSitesMask= .001; private GenotypeTable maskKey= null; private double[] MAFClass= null;//new double[]{0,.02,.05,.10,.20,.3,.4,.5,1}; public static GenotypeTable unimpAlign; //the unimputed alignment to be imputed, unphased private int testing=0; //level of reporting to stdout //major and minor alleles can be differ between the donor and unimp alignment private boolean isSwapMajorMinor=true; //if swapped try to fix it private boolean resolveHetIfUndercalled=false;//if true, sets genotypes called to a het to a het, even if already a homozygote //variables for tracking accuracy private int totalRight=0, totalWrong=0, totalHets=0; //global variables tracking errors on the fly private int[] siteErrors, siteCorrectCnt, taxonErrors, taxonCorrectCnt; //error recorded by sites private boolean verboseOutput=true; //initialize the transition matrix (T1) double[][] transition = new double[][] { {.999,.0001,.0003,.0001,.0005}, {.0002,.999,.00005,.00005,.0002}, {.0002,.00005,.999,.00005,.0002}, {.0002,.00005,.00005,.999,.0002}, {.0005,.0001,.0003,.0001,.999} }; //initialize the emission matrix, states (5) in rows, observations (3) in columns double[][] emission = new double[][] { {.998,.001,.001}, {.6,.2,.2}, {.4,.2,.4}, {.2,.2,.6}, {.001,.001,.998} }; private static ArgsEngine engine = new ArgsEngine(); private static final Logger myLogger = Logger.getLogger(FILLINImputationPlugin.class); public FILLINImputationPlugin() { super(null, false); } public FILLINImputationPlugin(Frame parentFrame) { super(parentFrame, false); } /** * * @param donorFile should be phased haplotypes * @param unImpTargetFile sites must match exactly with donor file * @param exportFile output file of imputed sites * @param minMinorCnt determines the size of the search window, low recombination 20-30, high recombination 10-15 * @param minTestSites * @param minSitesPresent * @param maxHybridErrorRate * @param isOutputProjection * @param imputeDonorFile */ public void runMinorWindowViterbiImputation(String donorFile, String unImpTargetFile, String exportFile, int minMinorCnt, int minTestSites, int minSitesPresent, double maxHybridErrorRate, boolean isOutputProjection, boolean imputeDonorFile) { long time=System.currentTimeMillis(); TasselPrefs.putAlignmentRetainRareAlleles(false); System.out.println("Retain Rare alleles is:"+TasselPrefs.getAlignmentRetainRareAlleles()); this.minTestSites=minTestSites; this.isOutputProjection=isOutputProjection; unimpAlign=ImportUtils.readGuessFormat(unImpTargetFile); GenotypeTable[] donorAlign= null; try { if (donorFile.contains(".gX")) {donorAlign=loadDonors(donorFile, unimpAlign, minTestSites, verboseOutput);} else if(true) {donorAlign=loadDonors(donorFile, unimpAlign, minTestSites, 4000,true);} //todo add option for size //todo break into lots of little alignments else throw new IllegalArgumentException(); } catch (IllegalArgumentException e){ throw new IllegalArgumentException("Incorrect donor file supplied. Must contain '.gX' within the file name,\nand match a set of files output from FILLINFindHaplotypesPlugin()"); } OpenBitSet[][] conflictMasks=createMaskForAlignmentConflicts(unimpAlign, donorAlign, verboseOutput); siteErrors=new int[unimpAlign.numberOfSites()]; siteCorrectCnt=new int[unimpAlign.numberOfSites()]; taxonErrors=new int[unimpAlign.numberOfTaxa()]; taxonCorrectCnt=new int[unimpAlign.numberOfTaxa()]; System.out.printf("Unimputed taxa:%d sites:%d %n",unimpAlign.numberOfTaxa(),unimpAlign.numberOfSites()); System.out.println("Creating Export GenotypeTable:"+exportFile); Object mna=null; if(isOutputProjection) { mna=new ProjectionBuilder(ImportUtils.readGuessFormat(donorFile)); } else { if(exportFile.contains("hmp.h5")) { mna= GenotypeTableBuilder.getTaxaIncremental(this.unimpAlign.positions(),exportFile); }else { mna= GenotypeTableBuilder.getTaxaIncremental(this.unimpAlign.positions()); } } characterizeHeterozygosity(); int numThreads = Runtime.getRuntime().availableProcessors(); System.out.println("Time to read in files and generate masks: "+((System.currentTimeMillis()-time)/1000)+" sec"); ExecutorService pool = Executors.newFixedThreadPool(numThreads); for (int taxon = 0; taxon < unimpAlign.numberOfTaxa(); taxon+=1) { int[] trackBlockNN= new int[5];//global variable to track number of focus blocks solved in NN search for system out; index 0 is inbred, 1 is viterbi, 2 is smash, 3 is not solved, 4 is total for all modes ImputeOneTaxon theTaxon= (((double)unimpAlign.heterozygousCountForTaxon(taxon)/(double)unimpAlign.totalNonMissingForTaxon(taxon))<hetThresh)? new ImputeOneTaxon(taxon, donorAlign, minSitesPresent, conflictMasks,imputeDonorFile, mna, trackBlockNN, maxInbredErrFocusHomo, maxHybridErrFocusHomo, maxSmashErrFocusHomo, true): new ImputeOneTaxon(taxon, donorAlign, minSitesPresent, conflictMasks,imputeDonorFile, mna, trackBlockNN, maxInbredErrFocusHet, 0, maxSmashErrFocusHet, false); // theTaxon.run(); //retained to provide a quick way to debug. uncomment to help in debugging. pool.execute(theTaxon); } pool.shutdown(); try{ if (!pool.awaitTermination(48, TimeUnit.HOURS)) { System.out.println("processing threads timed out."); } }catch(Exception e) { System.out.println("Error processing threads"); } System.out.println(""); StringBuilder s=new StringBuilder(); s.append(String.format("%s %s MinMinor:%d ", donorFile, unImpTargetFile, minMinorCnt)); System.out.println(s.toString()); double runtime= (double)(System.currentTimeMillis()-time)/(double)1000; if(isOutputProjection) { ProjectionGenotypeIO.writeToFile(exportFile, ((ProjectionBuilder) mna).build()); } else { GenotypeTableBuilder ab=(GenotypeTableBuilder)mna; if(ab.isHDF5()) { ab.build(); } else { ExportUtils.writeToHapmap(ab.build(), false, exportFile, '\t', null); } } System.out.printf("%d %g %d %n",minMinorCnt, maximumInbredError, maxDonorHypotheses); System.out.println("Time to read in files, impute target genotypes, and calculate accuracy: "+runtime+" seconds"); } private class ImputeOneTaxon implements Runnable{ int taxon; GenotypeTable[] donorAlign; int minSitesPresent; OpenBitSet[][] conflictMasks; boolean imputeDonorFile; GenotypeTableBuilder alignBuilder=null; ProjectionBuilder projBuilder=null; int[] trackBlockNN;//global variable to track number of focus blocks solved in NN search for system out; index 0 is inbred, 1 is viterbi, 2 is smash, 3 is not solved, 4 is total for all modes double focusInbredErr; //threshold for one haplotype imputation in focus block mode double focusHybridErr; //threshold for Viterbi imputation in focus block mode double focusSmashErr; //threshold for haplotype combination in focus block mode boolean hetsMiss; //for inbred lines in two haplotype combination, set hets to missing because likely error. for heterozygous, impute estimated hets in focus block mode public ImputeOneTaxon(int taxon, GenotypeTable[] donorAlign, int minSitesPresent, OpenBitSet[][] conflictMasks, boolean imputeDonorFile, Object mna, int[] trackBlockNN, double focusInbErr, double focusHybridErr, double focusSmashErr, boolean hetsToMissing) { this.taxon=taxon; this.donorAlign=donorAlign; this.minSitesPresent=minSitesPresent; this.conflictMasks=conflictMasks; this.imputeDonorFile=imputeDonorFile; this.trackBlockNN=trackBlockNN; this.focusInbredErr=focusInbErr; this.focusHybridErr=focusHybridErr; this.focusSmashErr=focusSmashErr; this.hetsMiss=hetsToMissing; if(mna instanceof GenotypeTableBuilder) {alignBuilder=(GenotypeTableBuilder)mna;} else if(mna instanceof ProjectionBuilder) {projBuilder=(ProjectionBuilder)mna;} else {throw new IllegalArgumentException("Only Aligmnent or Projection Builders may be used.");} } @Override public void run() { StringBuilder sb=new StringBuilder(); String name=unimpAlign.taxaName(taxon); ImputedTaxon impTaxon=new ImputedTaxon(taxon, unimpAlign.genotypeAllSites(taxon),isOutputProjection); boolean het= (focusHybridErr==0)?true:false; int[] unkHets=countUnknownAndHets(impTaxon.getOrigGeno()); sb.append(String.format("Imputing %d:%s AsHet:%b Mj:%d, Mn:%d Unk:%d Hets:%d... ", taxon,name,het, unimpAlign.allelePresenceForAllSites(taxon, Major).cardinality(), unimpAlign.allelePresenceForAllSites(taxon, Minor).cardinality(), unkHets[0], unkHets[1])); boolean enoughData=(unimpAlign.totalNonMissingForTaxon(taxon)>minSitesPresent); int countFullLength=0; int countByFocus= 0; for (int da = 0; (da < donorAlign.length)&&enoughData ; da++) { int donorOffset=unimpAlign.siteOfPhysicalPosition(donorAlign[da].chromosomalPosition(0), donorAlign[da].chromosome(0)); int blocks=donorAlign[da].allelePresenceForAllSites(0, Major).getNumWords(); BitSet[] maskedTargetBits=arrangeMajorMinorBtwAlignments(unimpAlign, taxon, donorOffset, donorAlign[da].numberOfSites(),conflictMasks[da][0],conflictMasks[da][1]); //if imputing the donor file, these donor indices prevent self imputation int[] donorIndices; if(imputeDonorFile){ donorIndices=new int[donorAlign[da].numberOfTaxa()-1]; for (int i = 0; i < donorIndices.length; i++) {donorIndices[i]=i; if(i>=taxon) donorIndices[i]++;} } else { donorIndices=new int[donorAlign[da].numberOfTaxa()]; for (int i = 0; i < donorIndices.length; i++) {donorIndices[i]=i;} } //Finds the best haplotype donors for each focus block within a donorGenotypeTable DonorHypoth[][] regionHypthInbred=new DonorHypoth[blocks][maxDonorHypotheses]; byte[][][] targetToDonorDistances=FILLINImputationUtils.calcAllelePresenceCountsBtwTargetAndDonors(maskedTargetBits, donorAlign[da]); for (int focusBlock = 0; focusBlock < blocks; focusBlock++) { int[] resultRange=getBlockWithMinMinorCount(maskedTargetBits[0].getBits(),maskedTargetBits[1].getBits(), focusBlock, minMinorCnt); if(resultRange==null) continue; //no data in the focus Block //search for the best inbred donors for a segment regionHypthInbred[focusBlock]=FILLINImputationUtils.findHomozygousDonorHypoth(taxon, resultRange[0], resultRange[2], focusBlock, donorIndices, targetToDonorDistances, minTestSites, maxDonorHypotheses); } impTaxon.setSegmentSolved(false); //tries to solve the entire donorAlign region with 1 or 2 donor haplotypes by Virterbi impTaxon=apply1or2Haplotypes(taxon, donorAlign[da], donorOffset, regionHypthInbred, impTaxon, maskedTargetBits, maxHybridErrorRate, targetToDonorDistances); if(impTaxon.isSegmentSolved()) { // System.out.printf("VertSolved da:%d L:%s%n",da, donorAlign[da].getLocus(0)); countFullLength++; continue;} //resorts to solving block by block, first by inbred, then by viterbi, and then by hybrid impTaxon=applyBlockNN(impTaxon, taxon, donorAlign[da], donorOffset, regionHypthInbred, hybridNN, maskedTargetBits, minMinorCnt, focusInbredErr, focusHybridErr, focusSmashErr, donorIndices, trackBlockNN, hetsMiss); if(impTaxon.isSegmentSolved()) { // System.out.printf("VertSolved da:%d L:%s%n",da, donorAlign[da].getLocus(0)); countByFocus++; continue; } else continue; } double totalFocus= (double)trackBlockNN[3]+(double)trackBlockNN[4]; sb.append(String.format("InbredOrViterbi:%d FocusBlock:%d PropFocusInbred:%f PropFocusViterbi:%f PropFocusSmash:%f PropFocusMissing:%f BlocksSolved:%d ", countFullLength, countByFocus, (double)trackBlockNN[0]/totalFocus, (double)trackBlockNN[1]/totalFocus, (double)trackBlockNN[2]/totalFocus, (double)trackBlockNN[3]/totalFocus, impTaxon.getBlocksSolved())); //sb.append(String.format("InbredOrViterbi:%d FocusBlock:%d BlocksSolved:%d ", countFullLength, countByFocus, impTaxon.getBlocksSolved())); int[] unk=countUnknownAndHets(impTaxon.resolveGeno); sb.append(String.format("Unk:%d PropMissing:%g ", unk[0], (double) unk[0] / (double) impTaxon.getOrigGeno().length)); sb.append(String.format("Het:%d PropHet:%g ", unk[1], (double)unk[1]/(double)impTaxon.getOrigGeno().length)); sb.append(" BreakPoints:"+impTaxon.getBreakPoints().size()); if(!isOutputProjection) { alignBuilder.addTaxon(unimpAlign.taxa().get(taxon), impTaxon.resolveGeno); } else { projBuilder.addTaxon(unimpAlign.taxa().get(taxon),impTaxon.getBreakPoints()); } if(verboseOutput) System.out.println(sb.toString()); } } private void characterizeHeterozygosity() { double notMissing= 0; double het= 0; for (int taxon = 0; taxon < unimpAlign.numberOfTaxa(); taxon++) { het+= (double)unimpAlign.heterozygousCountForTaxon(taxon); notMissing+= (double)unimpAlign.totalNonMissingForTaxon(taxon);} double avgHet= het/notMissing; double sqDif= 0; for (int taxon = 0; taxon < unimpAlign.numberOfTaxa(); taxon++) { double x= avgHet-((double)unimpAlign.heterozygousCountForTaxon(taxon)/(double)unimpAlign.totalNonMissingForTaxon(taxon)); sqDif+= (x*x);} System.out.println("Average Heterozygosity: "+avgHet+" plus/minus std error: "+Math.sqrt(sqDif/(unimpAlign.numberOfTaxa()-1))/Math.sqrt(unimpAlign.numberOfTaxa())); } private static GenotypeTable[] loadDonors(String donorFileRoot, GenotypeTable unimpAlign, int minTestSites, boolean verboseOutput){ File theDF=new File(donorFileRoot); String prefilter=theDF.getName().split(".gX.")[0]+".gc"; //grabs the left side of the file String prefilterOld=theDF.getName().split("s\\+")[0]+"s"; //grabs the left side of the file ArrayList<File> d=new ArrayList<File>(); for (File file : theDF.getParentFile().listFiles()) { if(file.getName().equals(theDF.getName())) {d.add(file);} if(file.getName().startsWith(prefilter)) {d.add(file);} if(file.getName().startsWith(prefilterOld)) {d.add(file);} } ArrayList<Integer> removeDonors= new ArrayList<>(); PositionList donU= unimpAlign.positions(); GenotypeTable[] donorAlign=new GenotypeTable[d.size()]; for (int i = 0; i < donorAlign.length; i++) { if(verboseOutput) System.out.println("Starting Read"); donorAlign[i]=ImportUtils.readFromHapmap(d.get(i).getPath(), (ProgressListener)null); ArrayList<Integer> subSites= new ArrayList<>(); PositionList donP= donorAlign[i].positions(); //for (int j = 0; j < donorAlign[i].numberOfSites(); j++) {if (donU.indexOf(donP.get(j)) > -1) subSites.add(j);} //if unimputed contains donorAlign position keep in donor align for (int j = 0; j < donorAlign[i].numberOfSites(); j++) {if (donU.siteOfPhysicalPosition(donP.physicalPositions()[j], donP.chromosome(j)) > -1) subSites.add(j);} //if unimputed contains donorAlign position keep in donor align if (subSites.size()!=donorAlign[i].numberOfSites()){ if (subSites.size()<2) { if(verboseOutput) System.out.printf("Donor file contains <2 matching sites and will not be used:%s",d.get(i).getPath()); removeDonors.add(i); } else { donorAlign[i]= FilterGenotypeTable.getInstance(donorAlign[i], ArrayUtils.toPrimitive(subSites.toArray(new Integer[subSites.size()]))); if(verboseOutput) System.out.printf("Donor file sites filtered to match target:%s taxa:%d sites:%d %n",d.get(i).getPath(), donorAlign[i].numberOfTaxa(),donorAlign[i].numberOfSites()); } if (subSites.size() < minTestSites*2 && verboseOutput) System.out.println("This donor alignment contains marginally sufficient matching snp positions. Region unlikely to impute well."); } else if(verboseOutput) System.out.printf("Donor file shares all sites with target:%s taxa:%d sites:%d %n",d.get(i).getPath(), donorAlign[i].numberOfTaxa(),donorAlign[i].numberOfSites()); //createMaskForAlignmentConflicts(unimpAlign,donorAlign[i],true); } if (removeDonors.isEmpty()==false) for(GenotypeTable gt:donorAlign) {donorAlign= (GenotypeTable[])ArrayUtils.removeElement(donorAlign, gt);} return donorAlign; } private static GenotypeTable[] loadDonors(String donorFile, GenotypeTable unimpAlign, int minTestSites, int appoxSitesPerHaplotype, boolean verboseOutput){ GenotypeTable donorMasterGT=ImportUtils.readGuessFormat(donorFile); donorMasterGT=GenotypeTableBuilder.getHomozygousInstance(donorMasterGT); int[][] donorFirstLastSites=FILLINFindHaplotypesPlugin.divideChromosome(donorMasterGT,appoxSitesPerHaplotype,true); PositionList donU= unimpAlign.positions(); GenotypeTable[] donorAlign=new GenotypeTable[donorFirstLastSites.length]; for (int i = 0; i < donorAlign.length; i++) { if(verboseOutput) System.out.println("Starting Read"); donorAlign[i]=FilterGenotypeTable.getInstance(donorMasterGT,donorFirstLastSites[i][0],donorFirstLastSites[i][1]); } return donorAlign; } /** * Solve the entire donor alignment window with either one or two haplotypes. Generally, it is solved with the * HMM Viterbi algorithm. The Viterbi algorithm is relatively slow the big choice is how to choose the potential * donors. * * * @param taxon * @param donorAlign * @param donorOffset * @param regionHypoth * @param impT * @param maskedTargetBits * @param maxHybridErrorRate * @return */ private ImputedTaxon apply1or2Haplotypes(int taxon, GenotypeTable donorAlign, int donorOffset, DonorHypoth[][] regionHypoth, ImputedTaxon impT, BitSet[] maskedTargetBits, double maxHybridErrorRate, byte[][][] targetToDonorDistances) { int blocks=maskedTargetBits[0].getNumWords(); if(testing==1) System.out.println("Starting complete hybrid search"); //create a list of the best donors based on showing up frequently high in many focus blocks //in the test data set the best results achieved with on the best hypothesis recovered. // int[] d=FILLINImputationUtils.mostFrequentDonorsAcrossFocusBlocks(regionHypoth, maxDonorHypotheses); //Alternative test is find best donors int[] d=FILLINImputationUtils.bestDonorsAcrossEntireRegion(targetToDonorDistances, minTestSites,maxDonorHypotheses); int[] testList=FILLINImputationUtils.fillInc(0,donorAlign.numberOfTaxa()-1); int[] bestDonorList=Arrays.copyOfRange(d,0,Math.min(d.length,5)); DonorHypoth[] bestDBasedOnBest=FILLINImputationUtils.findHeterozygousDonorHypoth(taxon, maskedTargetBits[0].getBits(), maskedTargetBits[1].getBits(), 0, blocks-1, blocks/2, donorAlign, bestDonorList, testList, maxDonorHypotheses, minTestSites); //make all combination of best donor and find the the pairs that minimize errors //with the true switch also will make inbreds DonorHypoth[] best2Dsearchdonors=FILLINImputationUtils.findHeterozygousDonorHypoth(taxon, maskedTargetBits[0].getBits(), maskedTargetBits[1].getBits(), 0, blocks-1, blocks/2, donorAlign, d, d, maxDonorHypotheses, minTestSites); DonorHypoth[] best2donors=FILLINImputationUtils.combineDonorHypothArrays(maxDonorHypotheses,bestDBasedOnBest,best2Dsearchdonors); if(testing==1) System.out.println(Arrays.toString(best2donors)); ArrayList<DonorHypoth> goodDH=new ArrayList<DonorHypoth>(); for (DonorHypoth dh : best2donors) { if((dh!=null)&&(dh.getErrorRate()<maxHybridErrorRate)) { if(dh.isInbred()==false){ //if not inbred then Virterbi is needed to determine segments dh=getStateBasedOnViterbi(dh, donorOffset, donorAlign, twoWayViterbi, transition); } if(dh!=null) goodDH.add(dh); } } if(goodDH.isEmpty()) { // System.out.printf("%s %s SS:%d LS:%d %s %s %n",unimpAlign.taxaName(taxon),donorAlign.chromosome(0).getName(), // donorAlign.chromosomalPosition(0),donorAlign.chromosomalPosition(donorAlign.numberOfSites()-1), // Arrays.toString(d), Arrays.toString(d1)); // for (DonorHypoth donorHypoth : bestDBasedOnBest) { // System.out.println(donorHypoth.toString()); return impT; } DonorHypoth[] vdh=new DonorHypoth[goodDH.size()]; for (int i = 0; i < vdh.length; i++) {vdh[i]=goodDH.get(i);} impT.setSegmentSolved(true); return setAlignmentWithDonors(donorAlign,vdh, donorOffset,false,impT, false, false); } /** * Create mask for all sites where major & minor are swapped in alignments * returns in this order [goodMask, swapMjMnMask, errorMask, invariantMask] */ private OpenBitSet[][] createMaskForAlignmentConflicts(GenotypeTable unimpAlign, GenotypeTable[] donorAlign, boolean print) { OpenBitSet[][] result=new OpenBitSet[donorAlign.length][4]; for (int da = 0; da < result.length; da++) { // int donorOffset=unimpAlign.siteOfPhysicalPosition(donorAlign[da].chromosomalPosition(0), donorAlign[da].chromosome(0), donorAlign[da].siteName(0)); int donorOffset=unimpAlign.positions().siteOfPhysicalPosition(donorAlign[da].positions().physicalPositions()[0], donorAlign[da].positions().chromosome(0)); OpenBitSet goodMask=new OpenBitSet(donorAlign[da].numberOfSites()); OpenBitSet swapMjMnMask=new OpenBitSet(donorAlign[da].numberOfSites()); OpenBitSet errorMask=new OpenBitSet(donorAlign[da].numberOfSites()); OpenBitSet invariantMask=new OpenBitSet(donorAlign[da].numberOfSites()); int siteConflicts=0, swaps=0, invariant=0, good=0; for (int i = 0; i < donorAlign[da].numberOfSites(); i++) { /*we have three classes of data: invariant in one alignment, conflicts about minor and minor, *swaps of major and minor. Adding the invariant reduces imputation accuracy. *the major/minor swaps should be flipped in the comparisons */ byte tMj=unimpAlign.majorAllele(i + donorOffset); byte tMn=unimpAlign.minorAllele(i + donorOffset); byte daMj=donorAlign[da].majorAllele(i); byte daMn=donorAlign[da].minorAllele(i); if(daMn==GenotypeTable.UNKNOWN_ALLELE) { invariant++; invariantMask.set(i); goodMask.set(i); } else if((daMj==tMn)&&(daMn==tMj)) { swaps++; swapMjMnMask.set(i); goodMask.set(i); } else if((daMj!=tMj)) { siteConflicts++; errorMask.set(i); goodMask.set(i); } } goodMask.not(); if(print) System.out.println("Donor:"+da+"invariant in donor:"+invariant+" swapConflicts:"+swaps+" errors:"+siteConflicts); result[da]=new OpenBitSet[] {goodMask, swapMjMnMask, errorMask, invariantMask}; } return result; } private int[] countUnknownAndHets(byte[] a) { int cnt=0, cntHets=0; for (int i = 0; i < a.length; i++) { if(a[i]==UNKNOWN_DIPLOID_ALLELE) {cnt++;} else if(isHeterozygous(a[i])) {cntHets++;} } return new int[]{cnt,cntHets}; } /* Major and minor allele get swapped between alignment. This method flips these, and sets the bad sites to missing */ private BitSet[] arrangeMajorMinorBtwAlignments(GenotypeTable unimpAlign, int bt, int donorOffset, int donorLength, OpenBitSet goodMask, OpenBitSet swapMjMnMask) { int unimpAlignStartBlock=donorOffset/64; int shift=(donorOffset-(unimpAlignStartBlock*64)); int unimpAlignEndBlock=unimpAlignStartBlock+((donorLength+shift-1)/64); OpenBitSet mjUnImp=new OpenBitSet(unimpAlign.allelePresenceForSitesBlock(bt, Major, unimpAlignStartBlock, unimpAlignEndBlock + 1)); OpenBitSet mnUnImp=new OpenBitSet(unimpAlign.allelePresenceForSitesBlock(bt, Minor, unimpAlignStartBlock, unimpAlignEndBlock + 1)); OpenBitSet mjTbs=new OpenBitSet(donorLength); OpenBitSet mnTbs=new OpenBitSet(donorLength); for (int i = 0; i < donorLength; i++) { if(mjUnImp.fastGet(i+shift)) mjTbs.set(i); if(mnUnImp.fastGet(i+shift)) mnTbs.set(i); } OpenBitSet newmj=new OpenBitSet(mjTbs); OpenBitSet newmn=new OpenBitSet(mnTbs); mjTbs.and(goodMask); mnTbs.and(goodMask); // System.out.printf("mjTbs:%d Goodmask:%d swapMjMnMask:%d",mjTbs.getNumWords(),goodMask.getNumWords(), swapMjMnMask.getNumWords()); if(isSwapMajorMinor) { newmj.and(swapMjMnMask); newmn.and(swapMjMnMask); mjTbs.or(newmn); mnTbs.or(newmj); } // System.out.printf("Arrange shift:%d finalEnd:%d totalBits:%d DesiredLength:%d %n", shift, finalEnd, totalBits, donorLength); BitSet[] result={mjTbs,mnTbs}; return result; } /** * If the target regions has Mendelian errors that it looks for overlapping regional * solutions that are better. * TODO: This can be done much more robustly. * @param impT * @param targetTaxon * @param regionHypth */ private ImputedTaxon applyBlockNN(ImputedTaxon impT, int targetTaxon, GenotypeTable donorAlign, int donorOffset, DonorHypoth[][] regionHypth, boolean hybridMode, BitSet[] maskedTargetBits, int minMinorCnt, double focusInbredErr, double focusHybridErr, double focusSmashErr, int[] donorIndices, int[] blockNN, boolean hetsToMiss) { int[] currBlocksSolved= new int[5];//track number of focus blocks solved in NN search for system out; index 0 is inbred, 1 is viterbi, 2 is smash, 3 is not solved, 4 is total for all modes int blocks=maskedTargetBits[0].getNumWords(); for (int focusBlock = 0; focusBlock < blocks; focusBlock++) { boolean vit= false;//just if viterbi works for this block int[] d= getUniqueDonorsForBlock(regionHypth,focusBlock);//get the donor indices for that block from regionHypoth int[] resultRange=getBlockWithMinMinorCount(maskedTargetBits[0].getBits(),maskedTargetBits[1].getBits(), focusBlock, minMinorCnt); if(resultRange==null) {currBlocksSolved[3]++; continue; } //no data in the focus Block if(d==null) {currBlocksSolved[3]++; continue; } //no donors for the focus block //search for the best hybrid donors for a segment DonorHypoth[] best2donors=getBestHybridDonors(targetTaxon, maskedTargetBits[0].getBits(resultRange[0], resultRange[2]), maskedTargetBits[1].getBits(resultRange[0], resultRange[2]), resultRange[0], resultRange[2], focusBlock, donorAlign, d, d, true); if(best2donors[0]==null) {currBlocksSolved[3]++; continue; } //no good hybrid donors for the focus block //check for Viterbi and inbred ArrayList<DonorHypoth> goodDH= new ArrayList<DonorHypoth>(); //KLS0201 if (best2donors[0].getErrorRate()<focusInbredErr) { for (DonorHypoth dh : best2donors) { if((dh!=null)) { if((dh.isInbred()==false)&&(dh.getErrorRate()<focusHybridErr)){ dh=getStateBasedOnViterbi(dh, donorOffset, donorAlign, twoWayViterbi, transition); if(dh!=null) vit= true; } if(dh!=null&&(dh.getErrorRate()<focusInbredErr)) goodDH.add(dh); } } if (goodDH.size()!=0) { DonorHypoth[] vdh=new DonorHypoth[goodDH.size()]; for (int i = 0; i < vdh.length; i++) {vdh[i]=goodDH.get(i);} regionHypth[focusBlock]= vdh; impT= setAlignmentWithDonors(donorAlign, regionHypth[focusBlock], donorOffset, true, impT, false, false); impT.incBlocksSolved(); if(vit==true) {currBlocksSolved[1]++;} else {currBlocksSolved[0]++;} currBlocksSolved[4]++; continue; } } //if fails, try smash mode else if (hybridMode&&(best2donors[0].getErrorRate()<focusSmashErr)) {//smash mode goes into hybrid block NN for (DonorHypoth dh:best2donors) { if(dh!=null&&dh.getErrorRate()<focusSmashErr) { goodDH.add(dh); } if (goodDH.size()!=0) { DonorHypoth[] vdh=new DonorHypoth[goodDH.size()]; for (int i = 0; i < vdh.length; i++) {vdh[i]=goodDH.get(i);} regionHypth[focusBlock]= vdh; impT= setAlignmentWithDonors(donorAlign, regionHypth[focusBlock], donorOffset, true,impT, true, hetsToMiss);//only set donors for focus block //KLS0201 impT.incBlocksSolved(); currBlocksSolved[2]++; currBlocksSolved[4]++; continue; } } //if fails, do not impute this focus block } else currBlocksSolved[3]++; } if (currBlocksSolved[4]!=0) impT.setSegmentSolved(true); else impT.setSegmentSolved(false); int leftNullCnt=currBlocksSolved[3]; if(testing==1) System.out.printf("targetTaxon:%d hybridError:%g block:%d proportionBlocksImputed:%d null:%d inbredDone:%d viterbiDone:%d hybridDone:%d noData:%d %n", targetTaxon, focusHybridErr, blocks,currBlocksSolved[4]/blocks, leftNullCnt, currBlocksSolved[0], currBlocksSolved[1], currBlocksSolved[2], currBlocksSolved[3]); for (int i = 0; i < currBlocksSolved.length; i++) {blockNN[i]+= currBlocksSolved[i];} return impT; } private DonorHypoth getStateBasedOnViterbi(DonorHypoth dh, int donorOffset, GenotypeTable donorAlign, boolean forwardReverse, double[][] trans) { TransitionProbability tpF = new TransitionProbability(); EmissionProbability ep = new EmissionProbability(); tpF.setTransitionProbability(trans); ep.setEmissionProbability(emission); int startSite=dh.startBlock*64; int endSite=(dh.endBlock*64)+63; if(endSite>=donorAlign.numberOfSites()) endSite=donorAlign.numberOfSites()-1; int sites=endSite-startSite+1; byte[] callsF=new byte[sites]; byte[] callsR=new byte[sites]; //System.out.printf("%d %d %d %n",dh.donor1Taxon, startSite, endSite+1); byte[] d1b=donorAlign.genotypeRange(dh.donor1Taxon, startSite, endSite + 1); byte[] d2b=donorAlign.genotypeRange(dh.donor2Taxon, startSite, endSite + 1); byte[] t1b=unimpAlign.genotypeRange(dh.targetTaxon, startSite + donorOffset, endSite + 1 + donorOffset); //Selects only the informatives sites for the Viterbi algorithm //Perhaps hets should be removed from the donor int informSites=0, nonMendel=0; ArrayList<Byte> nonMissingObs = new ArrayList<Byte>(); ArrayList<Integer> snpPositions = new ArrayList<Integer>(); for(int cs=0; cs<sites; cs++) { if(t1b[cs]==UNKNOWN_DIPLOID_ALLELE) continue; if(d1b[cs]==UNKNOWN_DIPLOID_ALLELE) continue; if(d2b[cs]==UNKNOWN_DIPLOID_ALLELE) continue; if(t1b[cs]==GAP_DIPLOID_ALLELE) continue; if(d1b[cs]==GAP_DIPLOID_ALLELE) continue; if(d2b[cs]==GAP_DIPLOID_ALLELE) continue; if(isHeterozygous(d1b[cs]) || isHeterozygous(d2b[cs])) continue; if(d1b[cs]==d2b[cs]) { if(t1b[cs]!=d1b[cs]) nonMendel++; continue; } informSites++; byte state=1; if(t1b[cs]==d1b[cs]) {state=0;} else if(t1b[cs]==d2b[cs]) {state=2;} nonMissingObs.add(state); snpPositions.add(cs+startSite); } if(informSites<10) return null; double nonMendRate=(double)nonMendel/(double)informSites; if(testing==1) System.out.printf("NonMendel:%d InformSites:%d ErrorRate:%g %n",nonMendel, informSites, nonMendRate); if(nonMendRate>this.maximumInbredError*5) return null; byte[] informStatesF=new byte[informSites]; for (int i = 0; i < informStatesF.length; i++) informStatesF[i]=nonMissingObs.get(i); int[] pos=new int[informSites]; for (int i = 0; i < pos.length; i++) pos[i]=snpPositions.get(i); int chrlength = donorAlign.chromosomalPosition(endSite) - donorAlign.chromosomalPosition(startSite); tpF.setAverageSegmentLength( chrlength / sites ); tpF.setPositions(pos); double probHeterozygous=0.5; double phom = (1 - probHeterozygous) / 2; double[] pTrue = new double[]{phom, .25*probHeterozygous ,.5 * probHeterozygous, .25*probHeterozygous, phom}; ViterbiAlgorithm vaF = new ViterbiAlgorithm(informStatesF, tpF, ep, pTrue); vaF.calculate(); if(testing>0) System.out.println("Input:"+Arrays.toString(informStatesF)+" Swaps"+countSwaps(informStatesF)); byte[] resultStatesF=vaF.getMostProbableStateSequence(); if(testing>0) System.out.println("Resul:"+Arrays.toString(resultStatesF)+" Swaps"+countSwaps(resultStatesF)); DonorHypoth dh2=new DonorHypoth(dh.targetTaxon,dh.donor1Taxon, dh.donor2Taxon, dh.startBlock, dh.focusBlock, dh.endBlock); int currPos=0; for(int cs=0; cs<sites; cs++) { //converts to informative states back to all states callsF[cs]=(resultStatesF[currPos]==1)?(byte)1:(byte)(resultStatesF[currPos]/2); //converts the scale back to 0,1,2 from 0..4 if((pos[currPos]<cs+startSite)&&(currPos<resultStatesF.length-1)) currPos++; } if(testing>1) System.out.println("callsF:"+Arrays.toString(callsF)+" Swaps"+countSwaps(callsF)); if (forwardReverse==true) { TransitionProbability tpR = new TransitionProbability(); tpR.setTransitionProbability(transition); byte[] informStatesR=Arrays.copyOf(informStatesF,informStatesF.length); ArrayUtils.reverse(informStatesR); int[] posR= Arrays.copyOf(pos,pos.length); ArrayUtils.reverse(posR); tpR.setAverageSegmentLength( chrlength / sites ); tpR.setPositions(posR); ViterbiAlgorithm vaR = new ViterbiAlgorithm(informStatesR, tpR, ep, pTrue); vaR.calculate(); byte[] resultStatesR=vaR.getMostProbableStateSequence();//this sequence is backwards/from the reverse viterbi ArrayUtils.reverse(resultStatesR); //flip the reverse viterbi calls to the same orientation as forward int currPosR=0; for(int cs=0; cs<sites; cs++) { //converts the scale back to 0,1,2 from 0..4 callsR[cs]=(resultStatesR[currPosR]==1)?(byte)1:(byte)(resultStatesR[currPosR]/2); if((pos[currPosR]<cs+startSite)&&(currPosR<resultStatesF.length-1)) currPosR++; } if(testing>1) System.out.println("callsR:"+Arrays.toString(callsR)+" Swaps"+countSwaps(callsR)); //compare the forward and reverse viterbi, use the one with the longest path length if they contradict byte[] callsC=Arrays.copyOf(callsF,callsF.length); //this does not copy it is just a pointer assignment for(int i= 0;i<pos.length;i++) { int cs= pos[i]-startSite; if (callsF[cs]!=callsR[cs]&&i<pos.length/2) callsC[cs]= callsR[cs]; } if (testing>0) { if (resultStatesF[0]!=resultStatesR[0]||resultStatesF[resultStatesF.length-1]!=resultStatesR[resultStatesR.length-1]) { System.out.println("FR:\n"+Arrays.toString(informStatesF)+"\n"+Arrays.toString(informStatesR)+"\n"+ Arrays.toString(resultStatesF)+"\n"+Arrays.toString(resultStatesR)+"\n"+Arrays.toString(callsF)+"\n"+ Arrays.toString(callsR)+"\n"+Arrays.toString(callsC)); } } if(testing>1) System.out.println("callsC:"+Arrays.toString(callsC)+" Swaps"+countSwaps(callsC)); if(testing>1) System.out.println("DonorOffset:"+donorOffset+" Reverse:"+countSwaps(callsC)+" dh:"+dh.toString()); dh2.phasedResults= callsC; return dh2; } System.out.println("Forward:"+countSwaps(callsF)+" dh:"+dh.toString()); dh2.phasedResults= callsF; return dh2; } /** * Given a start 64 site block, it expands to the left and right until it hits * the minimum Minor Site count in the target taxon * @param mnT - minor allele bit presence in a series of longs * @param focusBlock * @param minMinorCnt * @return arrays of blocks {startBlock, focusBlock, endBlock} */ private int[] getBlockWithMinMinorCount(long[] mjT, long[] mnT, int focusBlock, int minMinorCnt) { int blocks=mjT.length; int majorCnt=Long.bitCount(mjT[focusBlock]); int minorCnt=Long.bitCount(mnT[focusBlock]); int endBlock=focusBlock, startBlock=focusBlock; int minMajorCnt=minMinorCnt*minMajorRatioToMinorCnt; while((minorCnt<minMinorCnt)&&(majorCnt<minMajorCnt)) { boolean preferMoveStart=(focusBlock-startBlock<endBlock-focusBlock)?true:false; if(startBlock==0) {preferMoveStart=false;} if(endBlock==blocks-1) {preferMoveStart=true;} if((startBlock==0)&&(endBlock==blocks-1)) break; if(preferMoveStart) {//expand start startBlock minorCnt+=Long.bitCount(mnT[startBlock]); majorCnt+=Long.bitCount(mjT[startBlock]); } else { //expand end endBlock++; minorCnt+=Long.bitCount(mnT[endBlock]); majorCnt+=Long.bitCount(mjT[startBlock]); } } int[] result={startBlock, focusBlock, endBlock}; return result; } private int[] getUniqueDonorsForBlock(DonorHypoth[][] regionHypth, int block) {//change so only adding those donors that are not identical for target blocks TreeSet<Integer> donors= new TreeSet<>(); for (int h = 0; h < regionHypth[block].length; h++) { if (regionHypth[block][h]!=null) { donors.add(regionHypth[block][h].donor1Taxon); donors.add(regionHypth[block][h].donor2Taxon); } } if (donors.isEmpty()) return null; int[] result= ArrayUtils.toPrimitive(donors.toArray(new Integer[donors.size()])); return result; } /** * Simple algorithm that tests every possible two donor combination to minimize * the number of unmatched informative alleles. Currently, there is little tie * breaking, longer matches are favored. * @param targetTaxon * @param startBlock * @param endBlock * @param focusBlock * @return int[] array of {donor1, donor2, testSites} sorted by testPropUnmatched */ private DonorHypoth[] getBestHybridDonors(int targetTaxon, long[] mjT, long[] mnT, int startBlock, int endBlock, int focusBlock, GenotypeTable donorAlign, int[] donor1Indices, int[] donor2Indices, boolean viterbiSearch) { TreeMap<Double,DonorHypoth> bestDonors=new TreeMap<Double,DonorHypoth>(); Set<Long> testedDonorPairs=new HashSet<>(); double lastKeytestPropUnmatched=1.0; double inc=1e-9; double[] donorDist; for (int d1: donor1Indices) { long[] mj1=donorAlign.allelePresenceForSitesBlock(d1, Major, startBlock, endBlock + 1); long[] mn1=donorAlign.allelePresenceForSitesBlock(d1, Minor, startBlock, endBlock + 1); for (int d2 : donor2Indices) { if((!viterbiSearch)&&(d1==d2)) continue; if(testedDonorPairs.contains(((long)d1<<32)+(long)d2)) continue; if(testedDonorPairs.contains(((long)d2<<32)+(long)d1)) continue; testedDonorPairs.add(((long)d1<<32)+(long)d2); long[] mj2=donorAlign.allelePresenceForSitesBlock(d2, Major, startBlock, endBlock + 1); long[] mn2=donorAlign.allelePresenceForSitesBlock(d2, Minor, startBlock, endBlock + 1); if(viterbiSearch) { donorDist=IBSDistanceMatrix.computeHetBitDistances(mj1, mn1, mj2, mn2, minTestSites); if((d1!=d2)&&(donorDist[0]<this.minimumHybridDonorDistance)) continue; } int[] mendErr=mendelErrorComparison(mjT, mnT, mj1, mn1, mj2, mn2); if(mendErr[1]<minTestSites) continue; double testPropUnmatched=(double)(mendErr[0])/(double)mendErr[1]; inc+=1e-9; testPropUnmatched+=inc; if(testPropUnmatched<lastKeytestPropUnmatched) { DonorHypoth theDH=new DonorHypoth(targetTaxon, d1, d2, startBlock, focusBlock, endBlock, mendErr[1], mendErr[0]); DonorHypoth prev=bestDonors.put(new Double(testPropUnmatched), theDH); if(prev!=null) { System.out.println("Hybrid TreeMap index crash:"+testPropUnmatched); } if(bestDonors.size()>maxDonorHypotheses) { bestDonors.remove(bestDonors.lastKey()); lastKeytestPropUnmatched=bestDonors.lastKey(); } } } } DonorHypoth[] result=new DonorHypoth[maxDonorHypotheses]; int count=0; for (DonorHypoth dh : bestDonors.values()) { result[count]=dh; count++; } return result; } private int[] mendelErrorComparison(long[] mjT, long[] mnT, long[] mj1, long[] mn1, long[] mj2, long[] mn2) { int mjUnmatched=0; int mnUnmatched=0; int testSites=0; for (int i = 0; i < mjT.length; i++) { long siteMask=(mjT[i]|mnT[i])&(mj1[i]|mn1[i])&(mj2[i]|mn2[i]); mjUnmatched+=Long.bitCount(siteMask&mjT[i]&(mjT[i]^mj1[i])&(mjT[i]^mj2[i])); mnUnmatched+=Long.bitCount(siteMask&mnT[i]&(mnT[i]^mn1[i])&(mnT[i]^mn2[i])); testSites+=Long.bitCount(siteMask); } int totalMendelianErrors=mjUnmatched+mnUnmatched; // double testPropUnmatched=(double)(totalMendelianErrors)/(double)testSites; return (new int[] {totalMendelianErrors, testSites}); } private ImputedTaxon setAlignmentWithDonors(GenotypeTable donorAlign, DonorHypoth[] theDH, int donorOffset, boolean setJustFocus, ImputedTaxon impT, boolean smashOn, boolean hetsMiss) { if(theDH[0].targetTaxon<0) return impT; boolean print=false; int startSite=(setJustFocus)?theDH[0].getFocusStartSite():theDH[0].startSite; int endSite=(setJustFocus)?theDH[0].getFocusEndSite():theDH[0].endSite; if(endSite>=donorAlign.numberOfSites()) endSite=donorAlign.numberOfSites()-1; //prevDonors is used to track recombination breakpoint start and stop int[] prevDonors=new int[]{-1, -1}; if(theDH[0].getPhaseForSite(startSite)==0) {prevDonors=new int[]{theDH[0].donor1Taxon, theDH[0].donor1Taxon};} else if(theDH[0].getPhaseForSite(startSite)==2) {prevDonors=new int[]{theDH[0].donor2Taxon, theDH[0].donor2Taxon};} else if(theDH[0].getPhaseForSite(startSite)==1) {prevDonors=new int[]{theDH[0].donor1Taxon, theDH[0].donor2Taxon};} int prevDonorStart=startSite; int[] currDonors=prevDonors; for(int cs=startSite; cs<=endSite; cs++) { byte donorEst=UNKNOWN_DIPLOID_ALLELE; byte neighbor=0; //site imputation will try to use all donor hypotheses; breakpoints only use the best (e.g. i==0 tests) for (int i = 0; (i < theDH.length) && (donorEst==UNKNOWN_DIPLOID_ALLELE); i++) { neighbor++; if((theDH[i]==null)||(theDH[i].donor1Taxon<0)) continue; if(theDH[i].getErrorRate()>this.maximumInbredError) continue; byte bD1=donorAlign.genotype(theDH[i].donor1Taxon, cs); if(theDH[i].getPhaseForSite(cs)==0) { donorEst=bD1; if(i==0) currDonors=new int[]{theDH[0].donor1Taxon, theDH[0].donor1Taxon}; } else { byte bD2=donorAlign.genotype(theDH[i].donor2Taxon, cs); if(theDH[i].getPhaseForSite(cs)==2) { donorEst=bD2; if(i==0) currDonors=new int[]{theDH[0].donor2Taxon, theDH[0].donor2Taxon}; } else { donorEst=GenotypeTableUtils.getUnphasedDiploidValueNoHets(bD1, bD2); if(i==0) currDonors=new int[]{theDH[0].donor1Taxon, theDH[0].donor2Taxon}; } } } byte knownBase=impT.getOrigGeno(cs+donorOffset); //record recombination breakpoint if it changes if(!Arrays.equals(prevDonors, currDonors)) { DonorHaplotypes dhaps=new DonorHaplotypes(donorAlign.chromosome(prevDonorStart), donorAlign.chromosomalPosition(prevDonorStart), donorAlign.chromosomalPosition(cs),prevDonors[0],prevDonors[1]); impT.addBreakPoint(dhaps); prevDonors=currDonors; prevDonorStart=cs; } //chgHis records the section of the imputation pipeline that made the change, Viterbi negative, blockNN positive if(theDH[0].phasedResults==null) {impT.chgHis[cs+donorOffset]=(byte)-neighbor;} else {impT.chgHis[cs+donorOffset]=(byte)neighbor;} impT.impGeno[cs+donorOffset]= donorEst; //predicted based on neighbor //if genotype is unknown or het undercall then resolves //todo there is currently not an option if the predicted disagrees with a homozygous call if(knownBase==UNKNOWN_DIPLOID_ALLELE) { if (isHeterozygous(donorEst)) { if (smashOn && hetsMiss) {//if imputing a heterozygote, just set to missing impT.resolveGeno[cs+donorOffset]= knownBase; } else impT.resolveGeno[cs+donorOffset]= donorEst; //if not in hybrid, set to het } else {//if not imputed to a het impT.resolveGeno[cs+donorOffset]= donorEst;} } else if (isHeterozygous(donorEst)){ if(resolveHetIfUndercalled&&GenotypeTableUtils.isPartiallyEqual(knownBase, donorEst)&&smashOn==false){//if smash off, set homozygotes imputed to het to het //System.out.println("ResolveHet:"+theDH[0].targetTaxon+":"+cs+donorOffset+":"+knownBaseString+":"+donorEstString); impT.resolveGeno[cs+donorOffset]= donorEst; } } } //end of cs loop //enter a stop of the DH at the beginning of the next block DonorHaplotypes dhaps=new DonorHaplotypes(donorAlign.chromosome(prevDonorStart), donorAlign.chromosomalPosition(prevDonorStart), donorAlign.chromosomalPosition(endSite),prevDonors[0],prevDonors[1]); impT.addBreakPoint(dhaps); return impT; } private int countSwaps(byte[] swaps) { int nSwap=0; byte lastValue=swaps[0]; for (byte swap : swaps) { if(lastValue!=swap) { nSwap++; lastValue=swap; } } return nSwap; } private double calcErrorForTaxonAndSite(ImputedTaxon impT) { for (int cs = 0; cs < impT.getOrigGeno().length; cs++) { byte donorEst=impT.getImpGeno(cs); byte knownBase=impT.getOrigGeno(cs); if((knownBase!=UNKNOWN_DIPLOID_ALLELE)&&(donorEst!=UNKNOWN_DIPLOID_ALLELE)) { if(isHeterozygous(donorEst)||isHeterozygous(knownBase)) { totalHets++; } else if(knownBase==donorEst) { totalRight++; siteCorrectCnt[cs]++; taxonCorrectCnt[impT.taxon()]++; } else { totalWrong++; siteErrors[cs]++; taxonErrors[impT.taxon()]++; } } } return (double)taxonErrors[impT.taxon()]/(double)(taxonCorrectCnt[impT.taxon()]+taxonErrors[impT.taxon()]); } @Override public void setParameters(String[] args) { if (args.length == 0) { printUsage(); throw new IllegalArgumentException("\n\nPlease use the above arguments/options.\n\n"); } engine.add("-hmp", "-hmpFile", true); engine.add("-o", "--outFile", true); engine.add("-d", "--donorH", true); engine.add("-accuracyOff", "--accuracyOff", true); engine.add("-maskKeyFile", "--maskKeyFile", true); engine.add("-propSitesMask", "--propSitesMask", true); engine.add("-mxHet", "--hetThresh", true); engine.add("-minMnCnt", "--minMnCnt", true); engine.add("-mxInbErr", "--mxInbErr", true); engine.add("-mxHybErr", "--mxHybErr", true); engine.add("-mxVitFocusErr", "--mxVitFocusErr", true); engine.add("-mxInbFocusErr", "--mbIndFocusErr", true); engine.add("-mxComFocusErr", "--mxComFocusErr", true); engine.add("-mxInbFocusErrHet", "--mxInbFocusErrHet", true); engine.add("-mxComFocusErrHet", "--mxComFocusErrHet", true); engine.add("-hybNNOff", "--hybNNOff", true); engine.add("-mxDonH", "--mxDonH", true); engine.add("-mnTestSite", "--mnTestSite", true); engine.add("-projA", "--projAlign", false); engine.add("-runChrMode", "--runChrMode", false); engine.add("-nV", "--nonVerbose",false); engine.parse(args); hmpFile = engine.getString("-hmp"); outFileBase = engine.getString("-o"); donorFile = engine.getString("-d"); maskKeyFile = engine.getString("-maskKeyFile"); if(engine.getBoolean("-mxHet")) { hetThresh = Double.parseDouble(engine.getString("-mxHet")); } if(engine.getBoolean("-propSitesMask")) { propSitesMask = Double.parseDouble(engine.getString("-propSitesMask")); } if (engine.getBoolean("-mxInbErr")) { maximumInbredError = Double.parseDouble(engine.getString("-mxInbErr")); } if (engine.getBoolean("-mxHybErr")) { maxHybridErrorRate = Double.parseDouble(engine.getString("-mxHybErr")); } if (engine.getBoolean("-mxVitFocusErr")) { maxHybridErrFocusHomo = Double.parseDouble(engine.getString("-mxVitFocusErr")); } if (engine.getBoolean("-mxInbFocusErr")) { maxInbredErrFocusHomo = Double.parseDouble(engine.getString("-mxInbFocusErr")); } if (engine.getBoolean("-mxComFocusErr")) { maxSmashErrFocusHomo = Double.parseDouble(engine.getString("-mxComFocusErr")); } if (engine.getBoolean("-mxInbFocusErrHet")) { maxInbredErrFocusHet = Double.parseDouble(engine.getString("-mxInbFocusErrHet")); } if (engine.getBoolean("-mxComFocusErrHet")) { maxSmashErrFocusHet = Double.parseDouble(engine.getString("-mxComFocusErrHet")); } if (engine.getBoolean("-minMnCnt")) { minMinorCnt = Integer.parseInt(engine.getString("-minMnCnt")); } if (engine.getBoolean("-hybNNOff")) hybridNN=false; if (engine.getBoolean("-mxDonH")) { maxDonorHypotheses = Integer.parseInt(engine.getString("-mxDonH")); } if (engine.getBoolean("-mnTestSite")) { minTestSites = Integer.parseInt(engine.getString("-mnTestSite")); } if (engine.getBoolean("-accuracyOff")) accuracyOn=false; if (engine.getBoolean("-projA")) isOutputProjection=true; if (engine.getBoolean("-nV")) verboseOutput=false; maxHybridErrFocusHomo= .3333*maxHybridErrorRate; maxInbredErrFocusHomo= .3*maximumInbredError; maxSmashErrFocusHomo= maximumInbredError; maxInbredErrFocusHet= .1*maximumInbredError; maxSmashErrFocusHet= maximumInbredError; } private void printUsage() { myLogger.info( "\n\n\nAvailable options for the FILLINImputationPlugin are as follows:\n" + "-hmp Input HapMap file of target genotypes to impute. Accepts all file types supported by TASSEL5\n" + "-d Donor haplotype files from output of FILLINFindHaplotypesPlugin. Use .gX in the input filename to denote the substring .gc#s# found in donor files\n" + "-o Output file; hmp.txt.gz and .hmp.h5 accepted. Required\n" + "-maskKeyFile An optional key file to indicate that file is already masked for accuracy calculation. Non-missing genotypes indicate masked sites. Else, will generate own mask\n" + "-propSitesMask The proportion of non missing sites to mask for accuracy calculation if depth is not available (default:"+propSitesMask+"\n" + "-mxHet Threshold per taxon heterozygosity for treating taxon as heterozygous (no Viterbi, het thresholds). (default:"+hetThresh+"\n" + "-minMnCnt Minimum number of informative minor alleles in the search window (or "+minMajorRatioToMinorCnt+"X major)\n" + "-mxInbErr Maximum error rate for applying one haplotype to entire site window (default:"+maximumInbredError+"\n" + "-mxHybErr Maximum error rate for applying Viterbi with to haplotypes to entire site window (default:"+maxHybridErrorRate+"\n" + "-hybNNOff Whether to model two haplotypes as heterozygotic for focus blocks (default:"+hybridNN+")\n" + "-mxDonH Maximum number of donor hypotheses to be explored (default: "+maxDonorHypotheses+")\n" + "-mnTestSite Minimum number of sites to test for IBS between haplotype and target in focus block (default:"+minTestSites+")\n" + "-accuracyOff Do not calculate accuracy for imputation (default on)\n" + "-projA Create a projection alignment for high density markers (default off)\n" ); } @Override public DataSet performFunction(DataSet input) { runMinorWindowViterbiImputation(donorFile, hmpFile, outFileBase, minMinorCnt, minTestSites, 100, maxHybridErrorRate, isOutputProjection, false); return null; } @Override public ImageIcon getIcon() { return null; } @Override public String getButtonName() { return "ImputeByFILLIN"; } @Override public String getToolTipText() { return "Imputation that relies on a combination of HMM and Nearest Neighbor"; } }
package net.sf.mzmine.userinterface.components; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.text.NumberFormat; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.ListCellRenderer; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.table.TableCellRenderer; import org.jfree.ui.OverlayLayout; /** * Simple table cell renderer that renders Numbers using given NumberFormat */ public class FormattedCellRenderer implements TableCellRenderer, ListCellRenderer { private Font font; private NumberFormat format; public FormattedCellRenderer(NumberFormat format) { this.format = format; } /** * @param font */ public FormattedCellRenderer(NumberFormat format, Font font) { this.format = format; this.font = font; } /** * @see javax.swing.table.TableCellRenderer#getTableCellRendererComponent(javax.swing.JTable, * java.lang.Object, boolean, boolean, int, int) */ public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JPanel newPanel = new JPanel(new OverlayLayout()); Color bgColor; if (isSelected) bgColor = table.getSelectionBackground(); else bgColor = table.getBackground(); newPanel.setBackground(bgColor); if (hasFocus) { Border border = null; if (isSelected) border = UIManager.getBorder("Table.focusSelectedCellHighlightBorder"); if (border == null) border = UIManager.getBorder("Table.focusCellHighlightBorder"); newPanel.setBorder(border); } if (value != null) { String text; if (value instanceof Number) text = format.format((Number) value); else text = value.toString(); JLabel newLabel = new JLabel(text, JLabel.RIGHT); if (font != null) newLabel.setFont(font); else if (table.getFont() != null) newLabel.setFont(table.getFont()); newPanel.add(newLabel); } return newPanel; } /** * @see javax.swing.ListCellRenderer#getListCellRendererComponent(javax.swing.JList, * java.lang.Object, int, boolean, boolean) */ public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean hasFocus) { JPanel newPanel = new JPanel(new OverlayLayout()); Color bgColor; if (isSelected) bgColor = list.getSelectionBackground(); else bgColor = list.getBackground(); newPanel.setBackground(bgColor); if (hasFocus) { Border border = null; if (isSelected) border = UIManager.getBorder("List.focusSelectedCellHighlightBorder"); if (border == null) border = UIManager.getBorder("List.focusCellHighlightBorder"); newPanel.setBorder(border); } if (value != null) { String text; if (value instanceof Number) text = format.format((Number) value); else text = value.toString(); JLabel newLabel = new JLabel(text); if (font != null) newLabel.setFont(font); else if (list.getFont() != null) newLabel.setFont(list.getFont()); newPanel.add(newLabel); } return newPanel; } }
package novoda.lib.sqliteprovider.provider; import novoda.lib.sqliteprovider.sqlite.ExtendedSQLiteOpenHelper2; import novoda.lib.sqliteprovider.sqlite.ExtendedSQLiteQueryBuilder; import novoda.lib.sqliteprovider.util.Log.Provider; import novoda.lib.sqliteprovider.util.UriUtils; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import android.os.IBinder; import android.util.Log; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; public class SQLiteContentProviderImpl extends SQLiteContentProvider { private static final String ID = "_id"; private static final String GROUP_BY = "groupBy"; private static final String HAVING = "having"; private static final String LIMIT = "limit"; private static final String EXPAND = "expand"; @Override protected SQLiteOpenHelper getDatabaseHelper(Context context) { try { return new ExtendedSQLiteOpenHelper2(context); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException(e.getMessage()); } } @Override protected Uri insertInTransaction(Uri uri, ContentValues values) { ContentValues insertValues = (values != null) ? new ContentValues(values) : new ContentValues(); if (UriUtils.hasParent(uri)) { if (!insertValues.containsKey(UriUtils.getParentId(uri) + "_id")) { insertValues.put(UriUtils.getParentColumnName(uri) + "_id", UriUtils.getParentId(uri)); } } int update = 0; long rowId = 0; if (values.containsKey("_id")) { update = getWritableDatabase().update(UriUtils.getItemDirID(uri), values, "_id=?", new String[] { values.getAsString("_id") }); } else { Log.w("SQL", "inserting without a _id could have wtf effect"); } // Upsert if (update == 0) { rowId = getWritableDatabase().insert(UriUtils.getItemDirID(uri), null, insertValues); } else { rowId = values.getAsLong("_id"); } if (rowId > 0) { Uri newUri = ContentUris.withAppendedId(uri, rowId); notifyUriChange(newUri); return newUri; } throw new SQLException("Failed to insert row into " + uri); } protected SQLiteDatabase getWritableDatabase() { return getDatabaseHelper().getWritableDatabase(); } protected SQLiteDatabase getReadableDatabase() { return getDatabaseHelper().getReadableDatabase(); } @Override protected int updateInTransaction(Uri uri, ContentValues values, String selection, String[] selectionArgs) { ContentValues insertValues = (values != null) ? new ContentValues(values) : new ContentValues(); int rowId = getWritableDatabase().update(UriUtils.getItemDirID(uri), insertValues, selection, selectionArgs); if (rowId > 0) { Uri insertUri = ContentUris.withAppendedId(uri, rowId); notifyUriChange(insertUri); return rowId; } throw new SQLException("Failed to update row into " + uri); } @Override protected int deleteInTransaction(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase database = getWritableDatabase(); int count = database.delete(UriUtils.getItemDirID(uri), selection, selectionArgs); notifyUriChange(uri); return count; } @Override protected void notifyChange() { } public void notifyUriChange(Uri uri) { getContext().getContentResolver().notifyChange(uri, null); } @Override public String getType(Uri uri) { return null; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (Provider.verboseLoggingEnabled()) { Provider.v("==================== start of query ======================="); Provider.v("Uri: " + uri.toString()); } final ExtendedSQLiteQueryBuilder builder = getSQLiteQueryBuilder(); final List<String> expands = uri.getQueryParameters(EXPAND); final String groupBy = uri.getQueryParameter(GROUP_BY); final String having = uri.getQueryParameter(HAVING); final String limit = uri.getQueryParameter(LIMIT); final StringBuilder tableName = new StringBuilder(UriUtils.getItemDirID(uri)); builder.setTables(tableName.toString()); Map<String, String> autoproj = null; if (expands.size() > 0) { builder.addInnerJoin(expands.toArray(new String[] {})); ExtendedSQLiteOpenHelper2 helper = (ExtendedSQLiteOpenHelper2) getDatabaseHelper(); autoproj = helper.getProjectionMap(tableName.toString(), expands.toArray(new String[] {})); builder.setProjectionMap(autoproj); } if (UriUtils.isItem(uri)) { if (Provider.verboseLoggingEnabled()) { Provider.v("Appending to where clause: " + ID + "=" + uri.getLastPathSegment()); } builder.appendWhere(ID + "=" + uri.getLastPathSegment()); } else { if (UriUtils.hasParent(uri)) { if (Provider.verboseLoggingEnabled()) { Provider.v("Appending to where clause: " + UriUtils.getParentColumnName(uri) + ID + "=" + UriUtils.getParentId(uri)); } builder.appendWhereEscapeString(UriUtils.getParentColumnName(uri) + ID + "=" + UriUtils.getParentId(uri)); } } if (Provider.verboseLoggingEnabled()) { Provider.v("table: " + builder.getTables()); if (projection != null) Provider.v("projection:" + Arrays.toString(projection)); if (selection != null) Provider.v("selection: " + selection + " with arguments " + Arrays.toString(selectionArgs)); Provider.v("extra args: " + groupBy + " ,having: " + having + " ,sort order: " + sortOrder + " ,limit: " + limit); if (autoproj != null) Provider.v("projectionAutomated: " + autoproj); Provider.v("==================== end of query ======================="); } return builder.query(getReadableDatabase(), projection, selection, selectionArgs, groupBy, having, sortOrder, limit); } private ExtendedSQLiteQueryBuilder getSQLiteQueryBuilder() { return new ExtendedSQLiteQueryBuilder(); } }
package org.transtruct.cmthunes.ircbot.applets; import java.io.*; import java.net.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.Pattern; import org.jsoup.*; import org.jsoup.nodes.*; import org.jsoup.select.Elements; import org.transtruct.cmthunes.irc.*; import org.transtruct.cmthunes.util.URLBuilder; public class UrbanDictionaryApplet implements BotApplet { private String textWithBreaks(Element element) { StringBuilder buffer = new StringBuilder(); for(Node node : element.childNodes()) { if(node instanceof TextNode) { buffer.append(((TextNode) node).text().replace("\n", "")); } else if(node instanceof Element) { if(((Element) node).tagName().equals("br")) { buffer.append("\n"); } else { buffer.append(this.textWithBreaks(((Element) node))); } } } return buffer.toString(); } public void run(IRCChannel channel, IRCUser from, String command, String[] args, String unparsed) { Document doc; URLBuilder url; int definitionIndex = 0; boolean random = false; if(unparsed.trim().length() == 0) { random = true; } if(args.length == 1 && args[0].equals("-r")) { random = true; } if(args.length >= 2 && args[0].startsWith("-")) { String s = args[0].substring(1); try { definitionIndex = Integer.valueOf(s) - 1; unparsed = unparsed.replaceFirst(Pattern.quote(args[0]), ""); } catch(NumberFormatException e) { } } try { Connection con; if(random) { url = new URLBuilder("http: } else { url = new URLBuilder("http: url.setParameter("term", unparsed); } while(true) { con = Jsoup.connect(url.toString()); con.followRedirects(false); con.execute(); if(con.response().statusCode() == 200) { doc = con.response().parse(); break; } else if(con.response().statusCode() == 302) { url = new URLBuilder(con.response().header("Location")); } else { channel.write("Error loading page"); return; } } } catch (IOException e) { channel.write("Unknown error occured"); e.printStackTrace(); return; } if(!doc.select("div#not_defined_yet").isEmpty()) { channel.write("No definitions found"); } else { try { Elements elements = doc.select("div.definition"); if(elements.size() > definitionIndex) { Element def = elements.get(definitionIndex); String definition = this.textWithBreaks(def); String[] lines = definition.split("\n"); String longestLine = lines[0]; String response; for(int i = 1; i < lines.length && longestLine.length() < 15; i++) { if(lines[i].length() > longestLine.length()) { longestLine = lines[i]; } } response = url.getQueryParameter("term") + ": " + longestLine; channel.writeMultiple(BotAppletUtil.blockFormat(response, 400, 10)); } else { channel.write("Can not get definition"); } } catch(Exception e) { e.printStackTrace(); } } } }
package som.interpreter.nodes.specialized; import som.interpreter.InlinerAdaptToEmbeddedOuterContext; import som.interpreter.InlinerForLexicallyEmbeddedMethods; import som.interpreter.Invokable; import som.interpreter.SplitterForLexicallyEmbeddedCode; import som.interpreter.nodes.ExpressionNode; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.dsl.NodeChild; import com.oracle.truffle.api.dsl.NodeChildren; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.FrameSlot; import com.oracle.truffle.api.frame.FrameSlotKind; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.nodes.RootNode; import com.oracle.truffle.api.source.SourceSection; @NodeChildren({ @NodeChild(value = "from", type = ExpressionNode.class), @NodeChild(value = "to", type = ExpressionNode.class)}) public abstract class IntToDoInlinedLiteralsNode extends ExpressionNode { @Child protected ExpressionNode body; // In case we need to revert from this optimistic optimization, keep the // original node around private final ExpressionNode bodyActualNode; private final FrameSlot loopIndex; public abstract ExpressionNode getFrom(); public abstract ExpressionNode getTo(); public IntToDoInlinedLiteralsNode(final ExpressionNode body, final FrameSlot loopIndex, final ExpressionNode originalBody, final SourceSection sourceSection) { super(sourceSection); this.body = body; this.loopIndex = loopIndex; this.bodyActualNode = originalBody; // and, we can already tell the loop index that it is going to be long loopIndex.setKind(FrameSlotKind.Long); } @Specialization public final long doIntToDo(final VirtualFrame frame, final long from, final long to) { if (CompilerDirectives.inInterpreter()) { try { doLooping(frame, from, to); } finally { reportLoopCount((int) to - from); } } else { doLooping(frame, from, to); } return from; } @Specialization public final long doIntToDo(final VirtualFrame frame, final long from, final double to) { if (CompilerDirectives.inInterpreter()) { try { doLooping(frame, from, (long) to); } finally { reportLoopCount((int) to - from); } } else { doLooping(frame, from, (long) to); } return from; } protected final void doLooping(final VirtualFrame frame, final long from, final long to) { if (from <= to) { frame.setLong(loopIndex, from); body.executeGeneric(frame); } for (long i = from + 1; i <= to; i++) { frame.setLong(loopIndex, i); body.executeGeneric(frame); } } private void reportLoopCount(final long count) { if (count < 1) { return; } CompilerAsserts.neverPartOfCompilation("reportLoopCount"); Node current = getParent(); while (current != null && !(current instanceof RootNode)) { current = current.getParent(); } if (current != null) { ((Invokable) current).propagateLoopCountThroughoutMethodScope(count); } } @Override public void replaceWithLexicallyEmbeddedNode( final InlinerForLexicallyEmbeddedMethods inliner) { IntToDoInlinedLiteralsNode node = IntToDoInlinedLiteralsNodeGen.create(body, inliner.addLocalSlot(loopIndex.getIdentifier()), bodyActualNode, getSourceSection(), getFrom(), getTo()); replace(node); // create loopIndex in new context... } @Override public void replaceWithIndependentCopyForInlining( final SplitterForLexicallyEmbeddedCode inliner) { FrameSlot inlinedLoopIdx = inliner.getLocalFrameSlot(loopIndex.getIdentifier()); replace(IntToDoInlinedLiteralsNodeGen.create(body, inlinedLoopIdx, bodyActualNode, getSourceSection(), getFrom(), getTo())); } @Override public void replaceWithCopyAdaptedToEmbeddedOuterContext( final InlinerAdaptToEmbeddedOuterContext inliner) { // NOOP: This node has a FrameSlot, but it is local, so does not need to be updated. } }
package com.akiban.cserver.store; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import junit.framework.TestCase; import org.junit.Ignore; import org.junit.Test; import com.akiban.ais.ddl.DDLSource; import com.akiban.ais.model.AkibaInformationSchema; import com.akiban.cserver.CServerConstants; import com.akiban.cserver.IndexDef; import com.akiban.cserver.InvalidOperationException; import com.akiban.cserver.RowData; import com.akiban.cserver.RowDef; import com.akiban.cserver.RowDefCache; import com.akiban.cserver.service.ServiceManagerImpl; import com.akiban.message.ErrorCode; import com.akiban.util.ByteBufferFactory; import com.persistit.Exchange; import com.persistit.KeyState; import com.persistit.TransactionRunnable; import com.persistit.Tree; import com.persistit.Volume; import com.persistit.exception.RollbackException; public class PersistitStoreWithAISTest extends TestCase implements CServerConstants { private final static String DDL_FILE_NAME = "src/test/resources/data_dictionary_test.ddl"; private final static String SCHEMA = "data_dictionary_test"; private final static String GROUP_SCHEMA = "akiba_objects"; private PersistitStore store; private RowDefCache rowDefCache; private interface RowVisitor { void visit(final int depth) throws Exception; } private RowDef userRowDef(final String name) { return rowDefCache.getRowDef(SCHEMA + "." + name); } private RowDef groupRowDef(final String name) { return rowDefCache.getRowDef(GROUP_SCHEMA + "." + name); } class TestData { final RowDef defC = userRowDef("customer"); final RowDef defO = userRowDef("order"); final RowDef defI = userRowDef("item"); final RowDef defA = userRowDef("address"); final RowDef defX = userRowDef("component"); final RowDef defCOI = groupRowDef("_akiba_customer"); final RowData rowC = new RowData(new byte[256]); final RowData rowO = new RowData(new byte[256]); final RowData rowI = new RowData(new byte[256]); final RowData rowA = new RowData(new byte[256]); final RowData rowX = new RowData(new byte[256]); final int customers; final int ordersPerCustomer; final int itemsPerOrder; final int componentsPerItem; long cid; long oid; long iid; long xid; long elapsed; long count = 0; TestData(final int customers, final int ordersPerCustomer, final int itemsPerOrder, final int componentsPerItem) { this.customers = customers; this.ordersPerCustomer = ordersPerCustomer; this.itemsPerOrder = itemsPerOrder; this.componentsPerItem = componentsPerItem; } void insertTestRows() throws Exception { elapsed = System.nanoTime(); int unique = 0; for (int c = 0; ++c <= customers;) { cid = c; rowC.reset(0, 256); rowC.createRow(defC, new Object[] { cid, "Customer_" + cid }); store.writeRow(rowC); for (int o = 0; ++o <= ordersPerCustomer;) { oid = cid * 1000 + o; rowO.reset(0, 256); rowO.createRow(defO, new Object[] { oid, cid, 12345 }); store.writeRow(rowO); for (int i = 0; ++i <= itemsPerOrder;) { iid = oid * 1000 + i; rowI.reset(0, 256); rowI.createRow(defI, new Object[] { oid, iid, 123456, 654321 }); store.writeRow(rowI); for (int x = 0; ++x <= componentsPerItem;) { xid = iid * 1000 + x; rowX.reset(0, 256); rowX.createRow(defX, new Object[] { iid, xid, c, ++unique, "Description_" + unique }); store.writeRow(rowX); } } } for (int a = 0; a < (c % 3); a++) { rowA.reset(0, 256); rowA.createRow(defA, new Object[] { c, a, "addr1_" + c, "addr2_" + c, "addr3_" + c }); store.writeRow(rowA); } } elapsed = System.nanoTime() - elapsed; } void visitTestRows(final RowVisitor visitor) throws Exception { elapsed = System.nanoTime(); int unique = 0; for (int c = 0; ++c <= customers;) { cid = c; rowC.reset(0, 256); rowC.createRow(defC, new Object[] { cid, "Customer_" + cid }); visitor.visit(0); for (int o = 0; ++o <= ordersPerCustomer;) { oid = cid * 1000 + o; rowO.reset(0, 256); rowO.createRow(defO, new Object[] { oid, cid, 12345 }); visitor.visit(1); for (int i = 0; ++i <= itemsPerOrder;) { iid = oid * 1000 + i; rowI.reset(0, 256); rowI.createRow(defI, new Object[] { oid, iid, 123456, 654321 }); visitor.visit(2); for (int x = 0; ++x <= componentsPerItem;) { xid = iid * 1000 + x; rowX.reset(0, 256); rowX.createRow(defX, new Object[] { iid, xid, c, ++unique, "Description_" + unique }); visitor.visit(3); } } } } elapsed = System.nanoTime() - elapsed; } int totalRows() { return totalCustomerRows() + totalOrderRows() + totalItemRows() + totalComponentRows(); } int totalCustomerRows() { return customers; } int totalOrderRows() { return customers * ordersPerCustomer; } int totalItemRows() { return customers * ordersPerCustomer * itemsPerOrder; } int totalComponentRows() { return customers * ordersPerCustomer * itemsPerOrder * componentsPerItem; } void start() { elapsed = System.nanoTime(); } void end() { elapsed = System.nanoTime() - elapsed; } } @Override public void setUp() throws Exception { store = ServiceManagerImpl.getStoreForUnitTests(); rowDefCache = store.getRowDefCache(); final AkibaInformationSchema ais = new DDLSource() .buildAIS(DDL_FILE_NAME); rowDefCache.setAIS(ais); store.fixUpOrdinals(); } @Override public void tearDown() throws Exception { store.stop(); store = null; rowDefCache = null; } @Test public void testWriteCOIrows() throws Exception { final TestData td = new TestData(10, 10, 10, 10); td.insertTestRows(); System.out.println("testWriteCOIrows: inserted " + td.totalRows() + " rows in " + (td.elapsed / 1000L) + "us"); } @Test public void testScanCOIrows() throws Exception { final TestData td = new TestData(1000, 10, 3, 2); td.insertTestRows(); System.out.println("testScanCOIrows: inserted " + td.totalRows() + " rows in " + (td.elapsed / 1000L) + "us"); { // simple test - get all I rows td.start(); int scanCount = 0; td.rowI.createRow(td.defI, new Object[] { null, null, null }); final byte[] columnBitMap = new byte[] { 0xF }; final int indexId = 0; final RowCollector rc = store.newRowCollector( td.defI.getRowDefId(), indexId, 0, td.rowI, td.rowI, columnBitMap); final ByteBuffer payload = ByteBufferFactory.allocate(256); while (rc.hasMore()) { payload.clear(); while (rc.collectNextRow(payload)) ; payload.flip(); RowData rowData = new RowData(payload.array(), payload.position(), payload.limit()); for (int p = rowData.getBufferStart(); p < rowData .getBufferEnd();) { rowData.prepareRow(p); p = rowData.getRowEnd(); scanCount++; } } assertEquals(td.totalItemRows(), scanCount); td.end(); System.out.println("testScanCOIrows: scanned " + scanCount + " rows in " + (td.elapsed / 1000L) + "us"); } { // select item by IID in user table `item` td.start(); int scanCount = 0; td.rowI.createRow(td.defI, new Object[] { null, Integer.valueOf(1001001), null, null }); final byte[] columnBitMap = new byte[] { (byte) 0x3 }; final int indexId = td.defI.getPKIndexDef().getId(); final RowCollector rc = store.newRowCollector( td.defI.getRowDefId(), indexId, 0, td.rowI, td.rowI, columnBitMap); final ByteBuffer payload = ByteBufferFactory.allocate(256); while (rc.hasMore()) { payload.clear(); while (rc.collectNextRow(payload)) ; payload.flip(); RowData rowData = new RowData(payload.array(), payload.position(), payload.limit()); for (int p = rowData.getBufferStart(); p < rowData .getBufferEnd();) { rowData.prepareRow(p); p = rowData.getRowEnd(); scanCount++; } } assertEquals(1, scanCount); td.end(); System.out.println("testScanCOIrows: scanned " + scanCount + " rows in " + (td.elapsed / 1000L) + "us"); } { // select items in COI table by index values on Order td.start(); int scanCount = 0; final RowData start = new RowData(new byte[256]); final RowData end = new RowData(new byte[256]); // C has 2 columns, A has 5 columns, O has 3 columns, I has 4 // columns, CC has 5 columns start.createRow(td.defCOI, new Object[] { null, null, null, null, null, null, null, 1004, null, null, null, null, null, null, null, null, null, null, null }); end.createRow(td.defCOI, new Object[] { null, null, null, null, null, null, null, 1007, null, null, null, null, null, null, null, null, null, null, null }); final byte[] columnBitMap = projection(new RowDef[] { td.defC, td.defO, td.defI }, td.defCOI.getFieldCount()); int indexId = findIndexId(td.defCOI, td.defO, 0); final RowCollector rc = store.newRowCollector( td.defCOI.getRowDefId(), indexId, 0, start, end, columnBitMap); final ByteBuffer payload = ByteBufferFactory.allocate(256); // Expect all the C, O and I rows for orders 1004 through 1007, // inclusive // Total of 40 while (rc.hasMore()) { payload.clear(); while (rc.collectNextRow(payload)) ; payload.flip(); RowData rowData = new RowData(payload.array(), payload.position(), payload.limit()); for (int p = rowData.getBufferStart(); p < rowData .getBufferEnd();) { rowData.prepareRow(p); System.out.println(rowData.toString(rowDefCache)); p = rowData.getRowEnd(); scanCount++; } } assertEquals(rc.getDeliveredRows(), scanCount); assertEquals(17, scanCount - rc.getRepeatedRows()); td.end(); System.out.println("testScanCOIrows: scanned " + scanCount + " rows in " + (td.elapsed / 1000L) + "us"); } } int findIndexId(final RowDef groupRowDef, final RowDef userRowDef, final int fieldIndex) { int indexId = -1; final int findField = fieldIndex + userRowDef.getColumnOffset(); for (final IndexDef indexDef : groupRowDef.getIndexDefs()) { if (indexDef.getFields().length == 1 && indexDef.getFields()[0] == findField) { indexId = indexDef.getId(); } } return indexId; } final byte[] projection(final RowDef[] rowDefs, final int width) { final byte[] bitMap = new byte[(width + 7) / 8]; for (final RowDef rowDef : rowDefs) { for (int bit = rowDef.getColumnOffset(); bit < rowDef .getColumnOffset() + rowDef.getFieldCount(); bit++) { bitMap[bit / 8] |= (1 << (bit % 8)); } } return bitMap; } @Test public void testDropTable() throws Exception { final TestData td = new TestData(5, 5, 5, 5); td.insertTestRows(); Volume volume = store.getDb().getVolume(PersistitStore.VOLUME_NAME); assertNotNull(volume.getTree(td.defCOI.getTreeName(), false)); assertNotNull(volume.getTree(td.defO.getPkTreeName(), false)); assertNotNull(volume.getTree(td.defI.getPkTreeName(), false)); store.dropTable(td.defO.getRowDefId()); assertTrue(store.getTableManager() .getTableStatus(td.defO.getRowDefId()).isDeleted()); assertNotNull(volume.getTree(td.defO.getPkTreeName(), false)); store.dropTable(td.defI.getRowDefId()); assertNotNull(volume.getTree(td.defI.getPkTreeName(), false)); assertTrue(store.getTableManager() .getTableStatus(td.defI.getRowDefId()).isDeleted()); store.dropTable(td.defA.getRowDefId()); assertNotNull(volume.getTree(td.defA.getPkTreeName(), false)); assertTrue(store.getTableManager() .getTableStatus(td.defA.getRowDefId()).isDeleted()); store.dropTable(td.defC.getRowDefId()); assertTrue(store.getTableManager() .getTableStatus(td.defC.getRowDefId()).isDeleted()); store.dropTable(td.defO.getRowDefId()); assertNotNull(volume.getTree(td.defO.getPkTreeName(), false)); assertTrue(store.getTableManager() .getTableStatus(td.defO.getRowDefId()).isDeleted()); store.dropTable(td.defX.getRowDefId()); assertTrue(isGone(td.defCOI.getTreeName())); assertTrue(isGone(td.defO.getPkTreeName())); assertTrue(isGone(td.defI.getPkTreeName())); assertTrue(isGone(td.defX.getPkTreeName())); assertTrue(isGone(td.defA.getPkTreeName())); } // public void testDropSchema() throws Exception { // Volume volume = store.getDb().getVolume(PersistitStore.VOLUME_NAME); // for (int loop = 0; loop < 20; loop++) { // final TestData td = new TestData(10, 10, 10, 10); // td.insertTestRows(); // store.dropSchema(SCHEMA); // assertTrue(isGone(td.defCOI.getTreeName())); // assertTrue(isGone(td.defO.getPkTreeName())); // assertTrue(isGone(td.defI.getPkTreeName())); @Test public void testBug47() throws Exception { Volume volume = store.getDb().getVolume(PersistitStore.VOLUME_NAME); for (int loop = 0; loop < 20; loop++) { final TestData td = new TestData(10, 10, 10, 10); td.insertTestRows(); store.dropTable(td.defI.getRowDefId()); store.dropTable(td.defO.getRowDefId()); store.dropTable(td.defC.getRowDefId()); store.dropTable(td.defCOI.getRowDefId()); store.dropTable(td.defA.getRowDefId()); store.dropTable(td.defX.getRowDefId()); store.dropSchema(SCHEMA); assertTrue(isGone(td.defCOI.getTreeName())); assertTrue(isGone(td.defO.getPkTreeName())); assertTrue(isGone(td.defI.getPkTreeName())); } } @Test public void testUniqueIndexes() throws Exception { final TestData td = new TestData(5, 5, 5, 5); td.insertTestRows(); td.rowX.createRow(td.defX, new Object[] { 1002003, 23890345, 123, 44, "test1" }); ErrorCode actual = null; try { store.writeRow(td.rowX); } catch (InvalidOperationException e) { actual = e.getCode(); } assertEquals(ErrorCode.DUPLICATE_KEY, actual); td.rowX.createRow(td.defX, new Object[] { 1002003, 23890345, 123, 44444, "test2" }); store.writeRow(td.rowX); } @Test public void testUpdateRows() throws Exception { final TestData td = new TestData(5, 5, 5, 5); td.insertTestRows(); long cid = 3; long oid = cid * 1000 + 2; long iid = oid * 1000 + 4; long xid = iid * 1000 + 3; td.rowX.createRow(td.defX, new Object[] { iid, xid, null, null }); final byte[] columnBitMap = new byte[] { (byte) 0x1F }; final ByteBuffer payload = ByteBufferFactory.allocate(1024); RowCollector rc; rc = store.newRowCollector(td.defX.getRowDefId(), td.defX .getPKIndexDef().getId(), 0, td.rowX, td.rowX, columnBitMap); payload.clear(); assertTrue(rc.collectNextRow(payload)); payload.flip(); RowData oldRowData = new RowData(payload.array(), payload.position(), payload.limit()); oldRowData.prepareRow(oldRowData.getBufferStart()); RowData newRowData = new RowData(new byte[256]); newRowData.createRow(td.defX, new Object[] { iid, xid, 4, 424242, "Description_424242" }); store.updateRow(oldRowData, newRowData); rc = store.newRowCollector(td.defX.getRowDefId(), td.defX .getPKIndexDef().getId(), 0, td.rowX, td.rowX, columnBitMap); payload.clear(); assertTrue(rc.collectNextRow(payload)); payload.flip(); RowData updateRowData = new RowData(payload.array(), payload.position(), payload.limit()); updateRowData.prepareRow(updateRowData.getBufferStart()); System.out.println(updateRowData.toString(store.getRowDefCache())); // Now attempt to update a leaf table's PK field. newRowData = new RowData(new byte[256]); newRowData.createRow(td.defX, new Object[] { iid, -xid, 4, 545454, "Description_545454" }); store.updateRow(updateRowData, newRowData); rc = store.newRowCollector(td.defX.getRowDefId(), td.defX .getPKIndexDef().getId(), 0, updateRowData, updateRowData, columnBitMap); payload.clear(); assertTrue(!rc.collectNextRow(payload)); rc = store.newRowCollector(td.defX.getRowDefId(), td.defX .getPKIndexDef().getId(), 0, newRowData, newRowData, columnBitMap); assertTrue(rc.collectNextRow(payload)); payload.flip(); updateRowData = new RowData(payload.array(), payload.position(), payload.limit()); updateRowData.prepareRow(updateRowData.getBufferStart()); System.out.println(updateRowData.toString(store.getRowDefCache())); // TODO: // Hand-checked the index tables. Need SELECT on secondary indexes to // verify them automatically. } @Test public void testDeleteRows() throws Exception { final TestData td = new TestData(5, 5, 5, 5); td.insertTestRows(); td.count = 0; final RowVisitor visitor = new RowVisitor() { public void visit(final int depth) throws Exception { ErrorCode expectedError = null; ErrorCode actualError = null; try { switch (depth) { case 0: // TODO - for now we can't do cascading DELETE so we // expect an error expectedError = ErrorCode.FK_CONSTRAINT_VIOLATION; store.deleteRow(td.rowC); break; case 1: // TODO - for now we can't do cascading DELETE so we // expect an error expectedError = ErrorCode.FK_CONSTRAINT_VIOLATION; store.deleteRow(td.rowO); break; case 2: // TODO - for now we can't do cascading DELETE so we // expect an error expectedError = ErrorCode.FK_CONSTRAINT_VIOLATION; store.deleteRow(td.rowI); break; case 3: expectedError = null; if (td.xid % 2 == 0) { store.deleteRow(td.rowX); td.count++; } break; default: throw new Exception("depth = " + depth); } } catch (InvalidOperationException e) { actualError = e.getCode(); } assertEquals("at depth " + depth, expectedError, actualError); } }; td.visitTestRows(visitor); int scanCount = 0; td.rowX.createRow(td.defX, new Object[0]); final byte[] columnBitMap = new byte[] { (byte) 0x1F }; final RowCollector rc = store.newRowCollector(td.defX.getRowDefId(), td.defX.getPKIndexDef().getId(), 0, td.rowX, td.rowX, columnBitMap); final ByteBuffer payload = ByteBufferFactory.allocate(256); while (rc.hasMore()) { payload.clear(); while (rc.collectNextRow(payload)) ; payload.flip(); RowData rowData = new RowData(payload.array(), payload.position(), payload.limit()); for (int p = rowData.getBufferStart(); p < rowData.getBufferEnd();) { rowData.prepareRow(p); p = rowData.getRowEnd(); scanCount++; } } assertEquals(td.totalComponentRows() - td.count, scanCount); // TODO: // Hand-checked the index tables. Need SELECT on secondary indexes to // verify them automatically. } @Test public void testFetchRows() throws Exception { final TestData td = new TestData(5, 5, 5, 5); td.insertTestRows(); { final List<RowData> list = store.fetchRows("data_dictionary_test", "item", "part_id", 1001001, 1001005, "item"); assertEquals(5, list.size()); } { final List<RowData> list = store.fetchRows("data_dictionary_test", "customer", "customer_id", 1, 1, "item"); assertEquals(31, list.size()); } { final List<RowData> list = store.fetchRows("data_dictionary_test", "customer", "customer_id", 1, 2, "address"); assertEquals(5, list.size()); } { final List<RowData> list = store.fetchRows("data_dictionary_test", "customer", "customer_id", 1, 1, null); for (final RowData rowData : list) { System.out.println(rowData.toString(rowDefCache)); } assertEquals(157, list.size()); } } @Test public void testCommittedUpdateListener() throws Exception { final Map<Integer, AtomicInteger> counts = new HashMap<Integer, AtomicInteger>(); final CommittedUpdateListener listener = new CommittedUpdateListener() { @Override public void updated(KeyState keyState, RowDef rowDef, RowData oldRowData, RowData newRowData) { ai(rowDef).addAndGet(1000000); } @Override public void inserted(KeyState keyState, RowDef rowDef, RowData rowData) { ai(rowDef).addAndGet(1); } @Override public void deleted(KeyState keyState, RowDef rowDef, RowData rowData) { ai(rowDef).addAndGet(1000); } AtomicInteger ai(final RowDef rowDef) { AtomicInteger ai = counts.get(rowDef.getRowDefId()); if (ai == null) { ai = new AtomicInteger(); counts.put(rowDef.getRowDefId(), ai); } return ai; } }; store.addCommittedUpdateListener(listener); final TestData td = new TestData(5, 5, 5, 5); td.insertTestRows(); assertEquals(5, counts.get(td.defC.getRowDefId()).intValue()); assertEquals(25, counts.get(td.defO.getRowDefId()).intValue()); assertEquals(125, counts.get(td.defI.getRowDefId()).intValue()); assertEquals(625, counts.get(td.defX.getRowDefId()).intValue()); // Now delete or change every other X rows int scanCount = 0; td.rowX.createRow(td.defX, new Object[0]); final byte[] columnBitMap = new byte[] { (byte) 0x1F }; final RowCollector rc = store.newRowCollector(td.defX.getRowDefId(), td.defX.getPKIndexDef().getId(), 0, td.rowX, td.rowX, columnBitMap); final ByteBuffer payload = ByteBufferFactory.allocate(256); while (rc.hasMore()) { payload.clear(); while (rc.collectNextRow(payload)) ; payload.flip(); RowData rowData = new RowData(payload.array(), payload.position(), payload.limit()); for (int p = rowData.getBufferStart(); p < rowData.getBufferEnd();) { rowData.prepareRow(p); if (scanCount++ % 2 == 0) { store.deleteRow(rowData); } else { store.updateRow(rowData, rowData); } p = rowData.getRowEnd(); } } assertEquals(5, counts.get(td.defC.getRowDefId()).intValue()); assertEquals(25, counts.get(td.defO.getRowDefId()).intValue()); assertEquals(125, counts.get(td.defI.getRowDefId()).intValue()); assertEquals(312313625, counts.get(td.defX.getRowDefId()).intValue()); } @Test public void testDeferIndex() throws Exception { final TestData td = new TestData(3, 3, 0, 0); store.setDeferIndexes(true); td.insertTestRows(); final StringWriter a, b, c, d; dumpIndexes(new PrintWriter(a = new StringWriter())); store.flushIndexes(); dumpIndexes(new PrintWriter(b = new StringWriter())); store.deleteIndexes(""); dumpIndexes(new PrintWriter(c = new StringWriter())); store.buildIndexes(""); dumpIndexes(new PrintWriter(d = new StringWriter())); assertTrue(!a.toString().equals(b.toString())); assertEquals(a.toString(), c.toString()); assertEquals(b.toString(), d.toString()); } @Test public void testRebuildIndex() throws Exception { final TestData td = new TestData(3, 3, 3, 3); td.insertTestRows(); final StringWriter a, b, c; dumpIndexes(new PrintWriter(a = new StringWriter())); store.deleteIndexes(""); dumpIndexes(new PrintWriter(b = new StringWriter())); store.buildIndexes(""); dumpIndexes(new PrintWriter(c = new StringWriter())); assertTrue(!a.toString().equals(b.toString())); assertEquals(a.toString(), c.toString()); } @Ignore @Test public void testBug283() throws Exception { // Creates the index tables ahead of the h-table. This // is contrived to affect the Transaction commit order. // store.getDb().getTransaction().run(new TransactionRunnable() { // public void runTransaction() throws RollbackException { // for (int index = 1; index < 13; index++) { // final String treeName = "_akiba_customer$$" + index; // try { // final Exchange exchange = store.getExchange(treeName); // exchange.to("testBug283").store(); // store.releaseExchange(exchange); // } catch (Exception e) { // throw new RollbackException(e); // final TestData td = new TestData(1, 1, 1, 1); // td.insertTestRows(); // final AtomicBoolean broken = new AtomicBoolean(false); // final long expires = System.nanoTime() + 10000000000L; // 10 seconds // final AtomicInteger lastInserted = new AtomicInteger(); // final AtomicInteger scanCount = new AtomicInteger(); // final Thread thread1 = new Thread(new Runnable() { // public void run() { // for (int xid = 1001001002; System.nanoTime() < expires // && !broken.get(); xid++) { // td.rowX.createRow(td.defX, new Object[] { 1001001, xid, // 123, xid - 100100100, "part " + xid }); // try { // store.writeRow(td.rowX); // lastInserted.set(xid); // } catch (Exception e) { // e.printStackTrace(); // broken.set(true); // break; // }, "INSERTER"); // final Thread thread2 = new Thread(new Runnable() { // public void run() { // final RowData start = new RowData(new byte[256]); // final RowData end = new RowData(new byte[256]); // final byte[] columnBitMap = new byte[] { (byte) 0xF }; // final ByteBuffer payload = ByteBufferFactory.allocate(100000); // while (System.nanoTime() < expires && !broken.get()) { // int xid = lastInserted.get(); // start.createRow(td.defX, new Object[] { 1001001, xid, null, // null }); // end.createRow(td.defX, new Object[] { 1001001, xid + 10000, // null, null }); // final int indexId = td.defX.getPKIndexDef().getId(); // try { // final RowCollector rc = store.newRowCollector( // td.defX.getRowDefId(), indexId, 0, start, end, // columnBitMap); // while (rc.hasMore()) { // payload.clear(); // while (rc.collectNextRow(payload)) // payload.flip(); // RowData rowData = new RowData(payload.array(), // payload.position(), payload.limit()); // for (int p = rowData.getBufferStart(); p < rowData.getBufferEnd();) { // rowData.prepareRow(p); // p = rowData.getRowEnd(); // scanCount.incrementAndGet(); // // } catch (InvalidOperationException ioe) { // // broken.set(true); // // break; // } catch (Exception e) { // e.printStackTrace(); // broken.set(true); // break; // }, "SCANNER"); // thread1.start(); // thread2.start(); // thread1.join(); // thread2.join(); // // For some reason the @Ignore above isn't preventing this test from failing. // // Am commenting out the assertTrue until but 283 is fixed. // // assertTrue(!broken.get()); } private void dumpIndexes(final PrintWriter pw) throws Exception { for (final RowDef rowDef : rowDefCache.getRowDefs()) { pw.println(rowDef); for (final IndexDef indexDef : rowDef.getIndexDefs()) { pw.println(indexDef); dumpIndex(indexDef, pw); } } pw.flush(); } private void dumpIndex(final IndexDef indexDef, final PrintWriter pw) throws Exception { final Exchange ex = store.getExchange(indexDef.getRowDef(), indexDef); ex.clear(); while (ex.next(true)) { pw.println(ex.getKey()); } pw.flush(); } private boolean isGone(final String treeName) throws Exception { Volume volume = store.getDb().getVolume(PersistitStore.VOLUME_NAME); final Tree tree = volume.getTree(treeName, false); if (tree == null) { return true; } final Exchange exchange = store.getExchange(treeName); exchange.clear(); return !exchange.hasChildren(); } }
package com.datalogics.pdf.samples.rendering; import static com.datalogics.pdf.samples.util.Matchers.bufferedImageHasChecksum; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import com.datalogics.pdf.samples.SampleTest; import org.apache.commons.lang3.SystemUtils; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.net.URL; import java.util.ArrayList; import javax.imageio.ImageIO; /** * Test the RenderPdf sample. */ @RunWith(Parameterized.class) public class RenderPdfTest extends SampleTest { private static final String CLASS_NAME = MethodHandles.lookup().lookupClass().getSimpleName(); private static final int RESOLUTION = 72; private static Boolean renderDone; /** * Generate a list of parameters for the test. These are a combination of file names and checksums. * * @return the list of parameters for the parameterized tests. */ @Parameters(name = "{0}") public static Iterable<Object[]> parameters() throws IOException { return new ArrayList<Object[]>() { private static final long serialVersionUID = 7576159003442840992L; private void add(final String filename, final String checksum) throws IOException { final File file = newOutputFileWithDelete(filename); add(new Object[] { filename, file, checksum }); } { if (SystemUtils.IS_JAVA_1_8) { add(CLASS_NAME + ".1.png", "359806f590dee0e642a10b9b5043e46fd74fa3ce"); add(CLASS_NAME + ".2.png", "3192548a1abf89fec8de8d8b38f906d8717613b8"); add(CLASS_NAME + ".1.jpg", "bff446bb308a9bf45fa698c087515dc33454e5cd"); add(CLASS_NAME + ".2.jpg", "284ddfc066d209f7b1705f63c8a08eb6289d205a"); } else { add(CLASS_NAME + ".1.png", "1992474437f5b1ee5a885322fb089915a57fe8c9"); add(CLASS_NAME + ".2.png", "560bae832b056507eac24c81d6f6ef65d2685667"); add(CLASS_NAME + ".1.jpg", "387a2721566553d92a936f75d3024faf83fc4430"); add(CLASS_NAME + ".2.jpg", "453730cfbb8e556feb532e0110fc580c2dff6a77"); } } }; } @Parameter public String fileName; @Parameter(1) public File outputFile; @Parameter(2) public String checksum; @BeforeClass public static void setUpClass() { renderDone = false; } private static void ensureRender() throws Exception { if (renderDone) { return; } final URL inputUrl = RenderPdf.class.getResource(RenderPdf.DEFAULT_INPUT); // This is the base filename, to which will be appended the page number and the .png extension final URL outputUrl = newOutputFile(CLASS_NAME).toURI().toURL(); RenderPdf.renderPdf(inputUrl, RESOLUTION, outputUrl); renderDone = true; } /** * Check that the image checksum for a page matches. * * @throws Exception a general exception was thrown */ @Test public void imageChecksumMatches() throws Exception { ensureRender(); // Make sure the Output file exists. assertTrue(outputFile.getPath() + " must exist after run", outputFile.exists()); // and has the correct checksum final BufferedImage image = ImageIO.read(outputFile); assertThat("File " + fileName + " has correct checksum", image, bufferedImageHasChecksum(checksum)); } }
package com.deutscheboerse.risk.dave; import com.deutscheboerse.risk.dave.persistence.CountdownPersistenceService; import com.deutscheboerse.risk.dave.persistence.PersistenceService; import io.vertx.core.DeploymentOptions; import io.vertx.core.Vertx; import io.vertx.core.eventbus.MessageConsumer; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import io.vertx.serviceproxy.ProxyHelper; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(VertxUnitRunner.class) public class PersistenceVerticleIT { private static Vertx vertx; @BeforeClass public static void setUp(TestContext context) { PersistenceVerticleIT.vertx = Vertx.vertx(); } @Test public void checkPersistenceServiceInitialized(TestContext context) { // Async async = context.async(); // CountdownPersistenceService persistenceService = new CountdownPersistenceService(vertx, async); // MessageConsumer<JsonObject> serviceMessageConsumer = ProxyHelper.registerService(PersistenceService.class, vertx, persistenceService, PersistenceService.SERVICE_ADDRESS); // DeploymentOptions options = new DeploymentOptions().setConfig(new JsonObject()); // PersistenceVerticleIT.vertx.deployVerticle(PersistenceVerticle.class.getName(), options, context.asyncAssertSuccess()); // context.assertTrue(persistenceService.isInitialized()); } @AfterClass public static void tearDown(TestContext context) { PersistenceVerticleIT.vertx.close(context.asyncAssertSuccess()); } }
package com.github.sormuras.beethoven.unit; import static javax.lang.model.element.Modifier.ABSTRACT; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.expectThrows; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import javax.lang.model.element.Modifier; import org.junit.jupiter.api.Test; class ModifiableTest implements Modifiable { private final Set<Modifier> modifiers = new TreeSet<>(); @Test void addModifiers() { addModifier(ABSTRACT); assertTrue(getModifiers().equals(EnumSet.of(ABSTRACT))); assertFalse(isPublic()); assertFalse(isStatic()); addModifiers(PUBLIC, STATIC); assertTrue(getModifiers().equals(EnumSet.of(ABSTRACT, PUBLIC, STATIC))); assertTrue(isPublic()); assertTrue(isStatic()); addModifiers(List.of(FINAL)); assertTrue(getModifiers().equals(EnumSet.of(ABSTRACT, FINAL, PUBLIC, STATIC))); assertTrue(isPublic()); assertTrue(isStatic()); setModifiers(Collections.emptySet()); assertFalse(isPublic()); assertFalse(isStatic()); } @Test void addModifiersFails() { Modifier invalid = Modifier.VOLATILE; Exception e = expectThrows(IllegalArgumentException.class, () -> addModifier(invalid)); assertTrue(e.getMessage().contains(invalid.toString())); } @Test void emptyOnCreation() { assertFalse(isStatic()); assertTrue(getModifiers().isEmpty()); } @Override public Set<Modifier> getModifiers() { return modifiers; } @Override public Set<Modifier> getModifierValidationSet() { return EnumSet.of(ABSTRACT, FINAL, PUBLIC, STATIC); } @Override public boolean isModified() { return !modifiers.isEmpty(); } @Test void validationSetDefaultsToAllEnumConstants() { Set<Modifier> set = Modifiable.super.getModifierValidationSet(); assertTrue(set.containsAll(EnumSet.allOf(Modifier.class))); assertTrue(set.equals(EnumSet.allOf(Modifier.class))); } @Test void validationThrowsNullPointerException() { expectThrows(NullPointerException.class, () -> validateModifiers(null, null)); } @Test void modifiers() { assertEquals("[strictfp]", Modifiable.modifiers(java.lang.reflect.Modifier.STRICT).toString()); assertEquals("[transient]", Modifiable.modifiers(java.lang.reflect.Modifier.TRANSIENT).toString()); assertEquals("[volatile]", Modifiable.modifiers(java.lang.reflect.Modifier.VOLATILE).toString()); } }
package com.maestrano.connec; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.junit.Before; import org.junit.Test; import com.maestrano.Maestrano; import com.maestrano.net.ConnecClient; public class CnOrganizationIntegrationTest { private Properties props = new Properties(); private String groupId; @Before public void beforeEach() { props.setProperty("app.environment", "test"); props.setProperty("api.id", "app-1"); props.setProperty("api.key", "gfcmbu8269wyi0hjazk4t7o1sndpvrqxl53e1"); Maestrano.configure(props); this.groupId = "cld-3"; } @Test public void create_itCreatesAnOrganization() throws Exception { Map<String, Object> attrsMap = new HashMap<String, Object>(); attrsMap.put("name", "Doe Pty Ltd"); attrsMap.put("industry", "Banking"); CnOrganization entity = CnOrganization.create(this.groupId, attrsMap, CnOrganization.class); assertFalse(entity.getId() == null); assertEquals(this.groupId,entity.getGroupId()); assertEquals("Doe Pty Ltd",entity.getName()); assertEquals("Banking",entity.getIndustry()); } @Test public void all_itRetrievesAllOrganizations() throws Exception { List<CnOrganization> entities = CnOrganization.all(groupId, CnOrganization.class); CnOrganization entity = entities.get(0); assertTrue(entity.getId() != null); assertEquals(this.groupId,entity.getGroupId()); } @Test public void retrieve_itRetrievesASingleOrganization() throws Exception { CnOrganization entity = CnOrganization.retrieve(groupId, "8aabb850-8394-0132-a4d1-2623376cdffe", CnOrganization.class); assertTrue(entity.getId() != null); assertEquals(this.groupId,entity.getGroupId()); } @Test public void save_itUpdatesAnOrganization() throws Exception { CnOrganization entity = CnOrganization.retrieve(groupId, "8aabb850-8394-0132-a4d1-2623376cdffe", CnOrganization.class); String newName = entity.getName() + "a"; entity.setName(newName); assertTrue(entity.save()); assertTrue(entity.getId() != null); assertEquals(newName,entity.getName()); assertEquals(this.groupId,entity.getGroupId()); } @Test public void crud_UsingMaps() throws Exception { String groupId = "cld-3"; // Fetch all organizations Map<String, Object> organizations = ConnecClient.all("organizations", groupId); // System.out.println("Fetched organizations: " + organizations); // Fetched organizations: {organizations=[{name=Doe Corp Inc., id=8afd71e0-8394-0132-a4d2-2623376cdffe, group_id=cld-3, type=organizations}, ... } // Retrieve first organization List<Map<String, Object>> organizationsHashes = (List<Map<String, Object>>) organizations.get("organizations"); String firstOrganizationId = (String) organizationsHashes.get(0).get("id"); Map<String, Object> organization = (Map<String, Object>) ConnecClient.retrieve("organizations", groupId, firstOrganizationId).get("organizations"); // System.out.println("Retrieved first organization: " + organization); // Retrieved first organization: {name=Doe Corp Inc., id=8afd71e0-8394-0132-a4d2-2623376cdffe, group_id=cld-3, type=organizations} // Create a new organization Map<String, Object> newOrganization = new HashMap<String, Object>(); newOrganization.put("name", "New Organization"); organization = (Map<String, Object>) ConnecClient.create("organizations", groupId, newOrganization).get("organizations"); // System.out.println("Created new organization: " + organization); // Created new organization: {name=New Organization, id=347e0fa0-cfaf-0132-4f1a-42f46dd33bd3, group_id=cld-3, type=organizations} // Update an organization organization.put("industry", "Hardware"); String organizationId = (String) organization.get("id"); Map<String, Object> updatedOrganization = (Map<String, Object>) ConnecClient.update("organizations", groupId, organizationId, organization).get("organizations"); // System.out.println("Updated organization: " + updatedOrganization); // Updated organization: {name=New Organization, id=347e0fa0-cfaf-0132-4f1a-42f46dd33bd3, group_id=cld-3, industry=Hardware, type=organizations} } }
package com.wizzardo.tools.collections; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; public class CollectionToolsTest { @Test public void each() { List<Integer> list = new ArrayList<Integer>() {{ add(1); add(2); add(3); }}; final AtomicInteger counter = new AtomicInteger(); CollectionTools.each(list, new CollectionTools.Closure<Void, Integer>() { @Override public Void execute(Integer it) { counter.addAndGet(it); return null; } }); Assert.assertEquals(6, counter.get()); } @Test public void eachWithIndex() { List<Integer> list = new ArrayList<Integer>() {{ add(1); add(2); add(3); }}; final AtomicInteger counter = new AtomicInteger(); CollectionTools.eachWithIndex(list, new CollectionTools.Closure2<Void, Integer, Integer>() { @Override public Void execute(Integer i, Integer value) { counter.addAndGet(value * i); return null; } }); Assert.assertEquals(8, counter.get()); } @Test public void collect() { List<Integer> list = new ArrayList<Integer>() {{ add(1); add(2); add(3); }}; List<Integer> result = CollectionTools.collect(list, new CollectionTools.Closure<Integer, Integer>() { @Override public Integer execute(Integer it) { return it * 2; } }); Assert.assertEquals(3, result.size()); Assert.assertNotSame(list, result); Assert.assertEquals((Integer) 2, result.get(0)); Assert.assertEquals((Integer) 4, result.get(1)); Assert.assertEquals((Integer) 6, result.get(2)); } @Test public void grep() { List<Integer> list = new ArrayList<Integer>() {{ add(1); add(2); add(3); }}; List<Integer> result = CollectionTools.grep(list, new CollectionTools.Closure<Boolean, Integer>() { @Override public Boolean execute(Integer it) { return it % 2 == 0; } }); Assert.assertEquals(1, result.size()); Assert.assertNotSame(list, result); Assert.assertEquals((Integer) 2, result.get(0)); } @Test public void findAll() { List<Integer> list = new ArrayList<Integer>() {{ add(1); add(2); add(3); }}; List<Integer> result = CollectionTools.findAll(list, new CollectionTools.Closure<Boolean, Integer>() { @Override public Boolean execute(Integer it) { return it % 2 == 0; } }); Assert.assertEquals(1, result.size()); Assert.assertNotSame(list, result); Assert.assertEquals((Integer) 2, result.get(0)); } @Test public void find() { List<Integer> list = new ArrayList<Integer>() {{ add(1); add(2); add(3); }}; Integer result = CollectionTools.find(list, new CollectionTools.Closure<Boolean, Integer>() { @Override public Boolean execute(Integer it) { return it % 2 == 0; } }); Assert.assertEquals((Integer) 2, result); } @Test public void remove() { List<Integer> list = new ArrayList<Integer>() {{ add(1); add(2); add(3); }}; Integer result = CollectionTools.remove(list, new CollectionTools.Closure<Boolean, Integer>() { @Override public Boolean execute(Integer it) { return it % 2 == 0; } }); Assert.assertEquals((Integer) 2, result); Assert.assertEquals(2, list.size()); Assert.assertEquals((Integer) 1, list.get(0)); Assert.assertEquals((Integer) 3, list.get(1)); } @Test public void removeAll() { List<Integer> list = new ArrayList<Integer>() {{ add(1); add(2); add(3); }}; List<Integer> result = CollectionTools.removeAll(list, new CollectionTools.Closure<Boolean, Integer>() { @Override public Boolean execute(Integer it) { return it % 2 == 0; } }); Assert.assertEquals(2, result.size()); Assert.assertSame(list, result); Assert.assertEquals((Integer) 1, list.get(0)); Assert.assertEquals((Integer) 3, list.get(1)); } @Test public void group() { List<Integer> list = new ArrayList<Integer>() {{ add(1); add(2); add(3); add(4); add(5); }}; Map<Boolean, List<Integer>> groups = CollectionTools.group(list, new CollectionTools.Closure<Boolean, Integer>() { @Override public Boolean execute(Integer it) { return it % 2 == 0; } }, new CollectionTools.Closure<Integer, Integer>() { @Override public Integer execute(Integer it) { return it; } }); Assert.assertEquals(2, groups.size()); Assert.assertEquals(2, groups.get(true).size()); Assert.assertEquals(3, groups.get(false).size()); } }
package marubinotto.piggydb.model.fragment; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import marubinotto.piggydb.impl.InMemoryDatabase; import marubinotto.piggydb.model.Fragment; import marubinotto.piggydb.model.FragmentRepository; import marubinotto.piggydb.model.Tag; import marubinotto.piggydb.model.TagRepository; import marubinotto.piggydb.model.User; import marubinotto.piggydb.model.entity.RawFragment; import marubinotto.piggydb.model.exception.DuplicateException; import marubinotto.piggydb.model.exception.InvalidTagNameException; import marubinotto.piggydb.model.exception.InvalidTaggingException; import marubinotto.piggydb.model.exception.InvalidTitleException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Enclosed; @RunWith(Enclosed.class) public class TagFragmentTest { private static class TestBase { protected FragmentRepository fragmentRepository = new InMemoryDatabase().getFragmentRepository(); protected TagRepository tagRepository = fragmentRepository.getTagRepository(); protected User normalUser = new User("normal"); } public static class NewInstanceTest extends TestBase { private RawFragment object = new RawFragment(); @Test public void isNotTagByDefault() throws Exception { assertEquals(false, this.object.isTag()); assertNull(this.object.getTagId()); assertNull(this.object.asTag()); } @Test public void validateTagRole() throws Exception { this.object.validateTagRole(this.normalUser, this.tagRepository); } @Test(expected = InvalidTitleException.class) public void newTagFragmentShouldHaveTitle() throws Exception { this.object.setAsTagByUser(true, this.normalUser); this.object.validateTagRole(this.normalUser, this.tagRepository); } @Test(expected = InvalidTagNameException.class) public void invalidTagName() throws Exception { this.object.setTitleByUser("a", this.normalUser); this.object.setAsTagByUser(true, this.normalUser); this.object.validateTagRole(this.normalUser, this.tagRepository); } @Test(expected = DuplicateException.class) public void duplicateTagName() throws Exception { this.tagRepository.register(this.tagRepository.newInstance("test", this.normalUser)); this.object.setTitleByUser("test", this.normalUser); this.object.setAsTagByUser(true, this.normalUser); this.object.validateTagRole(this.normalUser, this.tagRepository); } @Test(expected = InvalidTaggingException.class) public void loopTagging() throws Exception { this.tagRepository.register(this.tagRepository.newInstance("test", this.normalUser)); this.object.setTitleByUser("test", this.normalUser); this.object.setAsTagByUser(true, this.normalUser); this.object.addTagByUser("test", this.tagRepository, this.normalUser); this.object.validateTagRole(this.normalUser, this.tagRepository); } @Test public void newTagRole() throws Exception { this.object.setTitleByUser("test", this.normalUser); this.object.setAsTagByUser(true, this.normalUser); this.object.addTagByUser("parent", this.tagRepository, this.normalUser); this.object.validateTagRole(this.normalUser, this.tagRepository); Tag tag = this.object.asTag(); assertEquals("test", tag.getName()); assertEquals("normal", tag.getCreator()); assertEquals("(parent)", tag.getClassification().toString()); } } public static class StoredTagFragmentTest extends TestBase { private Fragment object; private Tag tag; @Before public void given() throws Exception { RawFragment fragment = new RawFragment(); fragment.setTitleByUser("test", this.normalUser); fragment.setAsTagByUser(true, this.normalUser); fragment.addTagByUser("parent", this.tagRepository, this.normalUser); fragment.validateTagRole(this.normalUser, this.tagRepository); long id = this.fragmentRepository.register(fragment); this.object = this.fragmentRepository.get(id); this.tag = this.tagRepository.getByName("test"); } @Test public void name() throws Exception { assertEquals("test", this.object.getTitle()); assertEquals("test", this.tag.getName()); } @Test public void classification() throws Exception { assertEquals("(parent)", this.object.getClassification().toString()); assertEquals("(parent)", tag.getClassification().toString()); } @Test public void mutualIdRef() throws Exception { assertEquals(this.tag.getId(), this.object.getTagId()); assertEquals(this.object.getId(), this.tag.getFragmentId()); } @Test public void setTagRoleToFragment() throws Exception { this.object.validateTagRole(this.normalUser, this.tagRepository); Tag tagRole = this.object.asTag(); assertEquals(this.tag.getId(), tagRole.getId()); assertEquals("test", tagRole.getName()); assertEquals("(parent)", tagRole.getClassification().toString()); } @Test public void getFragmentViaTag() throws Exception { Fragment fragment = this.fragmentRepository.asFragment(this.tag); assertEquals(this.object.getId(), fragment.getId()); assertEquals("test", fragment.getTitle()); assertEquals(this.tag.getId(), fragment.getTagId()); assertEquals("(parent)", fragment.getClassification().toString()); } @Test public void updateViaFragment() throws Exception { this.object.setTitleByUser("test2", this.normalUser); this.object.addTagByUser("parent2", this.tagRepository, this.normalUser); this.object.validateTagRole(this.normalUser, this.tagRepository); this.fragmentRepository.update(this.object); Fragment fragment = this.fragmentRepository.get(this.object.getId()); assertEquals("test2", fragment.getTitle()); fragment.validateTagRole(this.normalUser, this.tagRepository); Tag tagRole = fragment.asTag(); assertEquals("test2", tagRole.getName()); assertEquals("(parent, parent2)", tagRole.getClassification().toString()); } @Test public void updateViaTag() throws Exception { this.tag.setNameByUser("test2", this.normalUser); this.tag.addTagByUser("parent2", this.tagRepository, this.normalUser); this.fragmentRepository.update(this.tag, this.normalUser); Fragment fragment = this.fragmentRepository.get(this.object.getId()); assertEquals("test2", fragment.getTitle()); assertEquals("(parent, parent2)", fragment.getClassification().toString()); fragment.validateTagRole(this.normalUser, this.tagRepository); Tag tagRole = fragment.asTag(); assertEquals("test2", tagRole.getName()); assertEquals("(parent, parent2)", tagRole.getClassification().toString()); } @Test public void deleteTagRoleViaFragment() throws Exception { this.object.setAsTagByUser(false, this.normalUser); this.object.validateTagRole(this.normalUser, this.tagRepository); this.fragmentRepository.update(this.object); Fragment fragment = this.fragmentRepository.get(this.object.getId()); assertEquals(null, fragment.getTagId()); assertEquals(false, this.tagRepository.containsName("test")); } @Test public void deleteTagRoleViaTag() throws Exception { Fragment fragment1 = this.fragmentRepository.delete(this.tag, this.normalUser); assertEquals(this.object.getId(), fragment1.getId()); assertEquals(null, fragment1.getTagId()); Fragment fragment2 = this.fragmentRepository.get(this.object.getId()); assertEquals(null, fragment2.getTagId()); assertEquals(false, this.tagRepository.containsName("test")); } } }
package com.google.inject; import static com.google.inject.Asserts.assertContains; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Target; import junit.framework.TestCase; /** * Tests the error messages produced by Guice. * * @author Kevin Bourrillion */ public class ErrorMessagesTest extends TestCase { private class InnerClass {} public void testInjectInnerClass() throws Exception { Injector injector = Guice.createInjector(); try { injector.getInstance(InnerClass.class); fail(); } catch (Exception expected) { // TODO(kevinb): why does the source come out as unknown?? assertContains(expected.getMessage(), "Injecting into inner classes is not supported."); } } public void testInjectLocalClass() throws Exception { class LocalClass {} Injector injector = Guice.createInjector(); try { injector.getInstance(LocalClass.class); fail(); } catch (Exception expected) { // TODO(kevinb): why does the source come out as unknown?? assertContains(expected.getMessage(), "Injecting into inner classes is not supported."); } } public void testExplicitBindingOfAnAbstractClass() { try { Guice.createInjector(new AbstractModule() { protected void configure() { bind(AbstractClass.class); } }); fail(); } catch(CreationException expected) { assertContains(expected.getMessage(), "Injecting into abstract types is not supported."); } } public void testGetInstanceOfAnAbstractClass() { Injector injector = Guice.createInjector(); try { injector.getInstance(AbstractClass.class); fail(); } catch(ConfigurationException expected) { assertContains(expected.getMessage(), "Injecting into abstract types is not supported."); } } static abstract class AbstractClass { @Inject AbstractClass() { } } public void testScopingAnnotationsOnAbstractTypes() { try { Guice.createInjector(new AbstractModule() { protected void configure() { bind(A.class).to(AImpl.class); } }); fail(); } catch (CreationException expected) { assertContains(expected.getMessage(), "Scope annotations on abstract types are not supported."); } } /** Demonstrates issue 64, when setAccessible() fails. */ public void testGetUninjectableClass() { try { Guice.createInjector(new AbstractModule() { protected void configure() { bind(Class.class); } }); fail(); } catch (CreationException expected) { assertContains(expected.getMessage(), "Failed to inject java.lang.Class"); assertTrue(expected.getCause() instanceof SecurityException); } } @Singleton interface A {} class AImpl implements A {} public void testBindingAnnotationsOnMethodsAndConstructors() { try { Guice.createInjector().getInstance(B.class); fail(); } catch (CreationException expected) { assertContains(expected.getMessage(), "Binding annotations on injected methods are not supported. " + "Annotate the parameter instead?"); } try { Guice.createInjector().getInstance(C.class); fail(); } catch (CreationException expected) { assertContains(expected.getMessage(), "Binding annotations on injected constructors are not supported. " + "Annotate the parameter instead?"); } } static class B { @Inject @Green void injectMe(String greenString) {} } static class C { @Inject @Green C(String greenString) {} } @Retention(RUNTIME) @Target({ FIELD, PARAMETER, CONSTRUCTOR, METHOD }) @BindingAnnotation @interface Green {} // TODO(kevinb): many many more }
package org.jitsi.meet.test.pageobjects.web; import org.jitsi.meet.test.util.*; import org.jitsi.meet.test.web.*; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.*; import java.util.*; public class SettingsDialog { /** * Selectors to be used for finding WebElements within the * {@link SettingsDialog}. While most are CSS selectors, some are XPath * selectors, and prefixed as such, due to the extra functionality XPath * provides. */ private final static String CANCEL_BUTTON = "#modal-dialog-cancel-button"; private final static String DISPLAY_NAME_FIELD = "#setDisplayName"; private final static String EMAIL_FIELD = "#setEmail"; private final static String FOLLOW_ME_CHECKBOX = "[name='follow-me'] ~ div"; private final static String MORE_TAB_CONTENT = ".more-tab"; private final static String OK_BUTTON = "#modal-dialog-ok-button"; private final static String SETTINGS_DIALOG = ".settings-dialog"; private final static String SETTINGS_DIALOG_CONTENT = ".settings-pane"; private final static String START_AUDIO_MUTED_CHECKBOX = "[name='start-audio-muted'] ~ div"; private final static String START_VIDEO_MUTED_CHECKBOX = "[name='start-video-muted'] ~ div"; private final static String X_PATH_MORE_TAB /** * The participant. */ private final WebParticipant participant; /** * Initializes a new {@link SettingsDialog} instance. * @param participant the participant for this {@link SettingsDialog}. */ public SettingsDialog(WebParticipant participant) { this.participant = Objects.requireNonNull(participant, "participant"); } /** * Clicks the cancel button on the settings dialog to close the dialog * without saving any changes. */ public void close() { participant.getDriver() .findElement(By.cssSelector(CANCEL_BUTTON)) .click(); } /** * Returns the participant's display name displayed in the settings dialog. * * @return {@code string} The display name displayed in the settings dialog. */ public String getDisplayName() { openProfileTab(); return participant.getDriver() .findElement(By.cssSelector(DISPLAY_NAME_FIELD)) .getAttribute("value"); } /** * Returns the participant's email displayed in the settings dialog. * * @return {@code string} The email displayed in the settings dialog. */ public String getEmail() { openProfileTab(); return participant.getDriver() .findElement(By.cssSelector(EMAIL_FIELD)) .getAttribute("value"); } /** * Returns whether or not the Follow Me checkbox is visible to the user in * the settings dialog. * * @return {@code boolean} True if the Follow Me checkbox is visible to the * user. */ public boolean isFollowMeDisplayed() { openMoreTab(); WebDriver driver = participant.getDriver(); List<WebElement> followMeCheckboxes = driver.findElements(By.cssSelector(FOLLOW_ME_CHECKBOX)); return followMeCheckboxes.size() > 0; } /** * Selects the More tab to be displayed. */ public void openMoreTab() { openTab(X_PATH_MORE_TAB); TestUtils.waitForElementBy( participant.getDriver(), By.cssSelector(MORE_TAB_CONTENT), 5); } /** * Selects the Profile tab to be displayed. */ public void openProfileTab() { openTab(X_PATH_PROFILE_TAB); } /** * Enters the passed in email into the email field. */ public void setEmail(String email) { openProfileTab(); WebDriver driver = participant.getDriver(); driver.findElement(By.cssSelector(EMAIL_FIELD)).sendKeys(email); } /** * Sets the option for having other participants automatically perform the * actions performed by the local participant. */ public void setFollowMe(boolean enable) { openMoreTab(); setCheckbox(FOLLOW_ME_CHECKBOX, enable); } /** * Sets the option for having participants join as audio muted. */ public void setStartAudioMuted(boolean enable) { openMoreTab(); setCheckbox(START_AUDIO_MUTED_CHECKBOX, enable); } /** * Sets the option for having participants join as video muted. */ public void setStartVideoMuted(boolean enable) { openMoreTab(); setCheckbox(START_VIDEO_MUTED_CHECKBOX, enable); } /** * Clicks the OK button on the settings dialog to close the dialog * and save any changes made. */ public void submit() { participant.getDriver() .findElement(By.cssSelector(OK_BUTTON)) .click(); } /** * Waits for the settings dialog to be visible. */ public void waitForDisplay() { TestUtils.waitForElementBy( participant.getDriver(), By.cssSelector(SETTINGS_DIALOG), 5); TestUtils.waitForElementBy( participant.getDriver(), By.cssSelector(SETTINGS_DIALOG_CONTENT), 5); } /** * Displays a specific tab in the settings dialog. */ private void openTab(String xPathSelectorForTab) { WebDriver driver = participant.getDriver(); TestUtils.waitForElementBy(driver, By.xpath(xPathSelectorForTab), 5); WebDriverWait wait = new WebDriverWait(driver, 10); WebElement element = wait.until(ExpectedConditions.elementToBeClickable( By.xpath(xPathSelectorForTab))); element.click(); } /** * Sets the state checked/selected of a checkbox in the settings dialog. */ private void setCheckbox(String cssSelector, boolean check) { WebDriver driver = participant.getDriver(); TestUtils.waitForElementBy(driver, By.cssSelector(cssSelector), 5); WebElement checkbox = driver.findElement(By.cssSelector(cssSelector)); boolean isChecked = checkbox.isSelected(); if (check != isChecked) { checkbox.click(); } } }
package org.lightmare.utils.libraries; import org.junit.Test; public class ClassLoaderUtilsTest { @Test public void javaVedotCheckTest() { try { System.out.println(); System.out .println("==========JVM and Java Platform properties=================="); System.out.println(); System.out.println("========================================="); System.out.println("========================================="); System.out.println(System.getProperty("java.vendor")); System.out.println(System.getProperty("java.vendor.url")); System.out.println(System.getProperty("java.version")); System.out.println(System.getProperty("java.vm.vendor")); System.out.println("========================================="); System.out.println("========================================="); System.out.println("========================================="); System.out.println(System.getProperty("os.arch")); System.out.println(); System.out .println("==========JVM and Java Platform properties=================="); System.out.println(); System.out.println("========================================="); System.out.println(); } catch (Exception ex) { ex.printStackTrace(); } } }
package io.github.tatools.sunshine.core; /** * @author Dmytro Serdiuk (dmytro.serdiuk@gmail.com) * @since 22.04.2017 */ public interface Rule { // @todo #82:30m Review all implementations and make sure all of them have proper names. boolean pass(String identity); class Fake implements Rule { private final boolean answer; public Fake(boolean answer) { this.answer = answer; } @Override public boolean pass(String identity) { return answer; } } }
package etomica.cavity; import etomica.action.BoxImposePbc; import etomica.action.BoxInflate; import etomica.action.activity.ActivityIntegrate; import etomica.atom.AtomType; import etomica.box.Box; import etomica.config.ConfigurationLattice; import etomica.data.*; import etomica.data.meter.MeterPressureHard; import etomica.data.meter.MeterRDF; import etomica.data.meter.MeterWidomInsertion; import etomica.data.types.DataDouble; import etomica.data.types.DataFunction; import etomica.data.types.DataGroup; import etomica.graphics.DisplayPlot; import etomica.graphics.DisplayTextBoxesCAE; import etomica.graphics.SimulationGraphic; import etomica.integrator.IntegratorHard; import etomica.integrator.IntegratorListenerAction; import etomica.lattice.LatticeCubicFcc; import etomica.lattice.LatticeOrthorhombicHexagonal; import etomica.nbr.list.NeighborListManager; import etomica.nbr.list.PotentialMasterList; import etomica.potential.P2HardSphere; import etomica.potential.PotentialMaster; import etomica.potential.PotentialMasterMonatomic; import etomica.simulation.Simulation; import etomica.space3d.Space3D; import etomica.species.SpeciesSpheresMono; import etomica.units.dimensions.Energy; import etomica.units.dimensions.Null; import etomica.util.ParameterBase; import etomica.util.ParseArgs; /** * Hard sphere simulation that allows one pair of atoms to overlap, which * allows the cavity function to be measured. * * @author Andrew Schultz */ public class HSMDWidom extends Simulation { public final ActivityIntegrate activityIntegrate; /** * The Box holding the atoms. */ public final Box box; /** * The Integrator performing the dynamics. */ public final IntegratorHard integrator; /** * The single hard-sphere species. */ public final SpeciesSpheresMono species; /** * The hard-sphere potential governing the interactions. */ public final P2HardSphere potential; public final PotentialMaster potentialMaster; /** * Makes a simulation according to the specified parameters. * * @param params Parameters as defined by the inner class CavityParam */ public HSMDWidom(HSMDParam params) { super(Space3D.getInstance()); species = new SpeciesSpheresMono(this, space); species.setIsDynamic(true); addSpecies(species); box = this.makeBox(); double neighborRangeFac = 1.6; double sigma = 1.0; potentialMaster = params.useNeighborLists ? new PotentialMasterList(this, sigma * neighborRangeFac, space) : new PotentialMasterMonatomic(this); int numAtoms = params.nAtoms; integrator = new IntegratorHard(this, potentialMaster, box); integrator.setIsothermal(false); integrator.setTimeStep(0.005); activityIntegrate = new ActivityIntegrate(integrator); getController().addAction(activityIntegrate); potential = new P2HardSphere(space); AtomType leafType = species.getLeafType(); potentialMaster.addPotential(potential, new AtomType[]{leafType, leafType}); box.setNMolecules(species, numAtoms); BoxInflate inflater = new BoxInflate(box, space); inflater.setTargetDensity(params.density); inflater.actionPerformed(); if (space.D() == 3) { new ConfigurationLattice(new LatticeCubicFcc(space), space).initializeCoordinates(box); } else { new ConfigurationLattice(new LatticeOrthorhombicHexagonal(space), space).initializeCoordinates(box); } if (params.useNeighborLists) { NeighborListManager nbrManager = ((PotentialMasterList) potentialMaster).getNeighborManager(box); integrator.getEventManager().addListener(nbrManager); } else { integrator.getEventManager().addListener(new IntegratorListenerAction(new BoxImposePbc(box, space))); } } public static void main(String[] args) { final String APP_NAME = "HSMD"; HSMDParam params = new HSMDParam(); if (args.length > 0) { ParseArgs.doParseArgs(params, args); } else { params.doGraphics = false; params.steps = 1000000; } final HSMDWidom sim = new HSMDWidom(params); int nBins = 500; double L = sim.box.getBoundary().getBoxSize().getX(0); int xMax = (int) (L * 0.5); double L3 = L * Math.sqrt(3); if (params.mappingCut < L3) L3 = 2 * params.mappingCut; int nBinsLong = (int) Math.ceil(nBins * L3 * 0.5); double xMaxMap = nBinsLong / ((double) nBins); if (params.mappingCut > 0 && params.mappingCut < xMaxMap) xMaxMap = params.mappingCut; MeterRDF meterRDF = new MeterRDF(sim.space); meterRDF.getXDataSource().setNValues(nBins * xMax); meterRDF.getXDataSource().setXMax(xMax); meterRDF.setBox(sim.box); meterRDF.setResetAfterData(true); DataFork forkRDF = new DataFork(); MeterWidomInsertion meterWidom = new MeterWidomInsertion(sim.space, sim.getRandom()); meterWidom.setIntegrator(sim.integrator); meterWidom.setNInsert(params.nAtoms / 5); meterWidom.setSpecies(sim.species); DataProcessorGContactP dpPContact = new DataProcessorGContactP(sim.box); DataProcessorPContactG dpGContact = new DataProcessorPContactG(sim.box); MeterWidomCavity meterWC = new MeterWidomCavity(sim.box, sim.getRandom(), sim.potentialMaster); meterWC.setSpecies(sim.species); meterWC.setNInsert(params.nAtoms / 5); double[] r; if (params.doGraphics) { r = new double[params.nWidomCavity + 1]; for (int ir = 0; ir < r.length; ir++) r[ir] = ir * (params.widomCavityMax / params.nWidomCavity); } else { r = new double[params.nWidomCavity]; for (int ir = 0; ir < r.length; ir++) r[ir] = (ir + 1) * (params.widomCavityMax / params.nWidomCavity); } meterWC.setInsertionDistances(r); if (params.doGraphics) { final SimulationGraphic simGraphic = new SimulationGraphic(sim, SimulationGraphic.TABBED_PANE, APP_NAME, 100); DisplayTextBoxesCAE displayPfromGC = null; DisplayTextBoxesCAE displayGCMap = null; DisplayPlot gPlot = null; DataPumpListener pumpRDF = null; if (params.doRDF || params.doMappingRDF) { gPlot = new DisplayPlot(); gPlot.setLabel("g(r)"); simGraphic.add(gPlot); } DataProcessorExtract0 gCExtractor = null; if (params.doRDF) { int rdfInterval = (5 * 200 + params.nAtoms - 1) / params.nAtoms; sim.integrator.getEventManager().addListener(new IntegratorListenerAction(meterRDF, rdfInterval)); AccumulatorAverageFixed accRDF = new AccumulatorAverageFixed(100); accRDF.setPushInterval(1); forkRDF.addDataSink(accRDF); accRDF.addDataSink(gPlot.getDataSet().makeDataSink(), new AccumulatorAverage.StatType[]{accRDF.AVERAGE}); DataProcessorFit dpFit = new DataProcessorFit("g(r) fit", 100, 3, false, 1, 1.1); accRDF.addDataSink(dpFit, new AccumulatorAverage.StatType[]{accRDF.AVERAGE, accRDF.ERROR}); dpFit.setDataSink(gPlot.getDataSet().makeDataSink()); gCExtractor = new DataProcessorExtract0("g(sigma)", true); gCExtractor.setErrorSource(dpFit); dpFit.addDataSink(gCExtractor); DisplayTextBoxesCAE gCDisplay = new DisplayTextBoxesCAE(); gCExtractor.addDataSink(gCDisplay); gCDisplay.setDoShowCurrent(false); simGraphic.add(gCDisplay); if (params.doMappingRDF) { displayGCMap = new DisplayTextBoxesCAE(); displayGCMap.setDoShowCurrent(false); simGraphic.add(displayGCMap); } gCExtractor.addDataSink(dpGContact); displayPfromGC = new DisplayTextBoxesCAE(); dpGContact.addDataSink(displayPfromGC); displayPfromGC.setDoShowCurrent(false); displayPfromGC.setLabel("P from g(sigma)"); pumpRDF = new DataPumpListener(meterRDF, forkRDF, 100); sim.integrator.getEventManager().addListener(pumpRDF); } else if (params.doMappingRDF) { displayGCMap = new DisplayTextBoxesCAE(); displayGCMap.setDoShowCurrent(false); simGraphic.add(displayGCMap); } MeterPressureHard meterP = new MeterPressureHard(sim.integrator); MeterPressureCollisionCount meterPCC = new MeterPressureCollisionCount(sim.integrator); AccumulatorAverageCollapsing accP = new AccumulatorAverageCollapsing(200); DataPumpListener pumpP = new DataPumpListener(meterP, accP, 100); sim.integrator.getEventManager().addListener(pumpP); DisplayTextBoxesCAE displayP = new DisplayTextBoxesCAE(); displayP.setAccumulator(accP); displayP.setDoShowCurrent(false); displayP.setDoShowCorrelation(true); accP.addDataSink(dpPContact, new AccumulatorAverage.StatType[]{accP.MOST_RECENT, accP.AVERAGE, accP.ERROR}); DisplayTextBoxesCAE displayContact = new DisplayTextBoxesCAE(); dpPContact.addDataSink(displayContact); displayContact.setLabel("g(sigma) from P"); displayContact.setDoShowCurrent(false); simGraphic.add(displayContact); simGraphic.add(displayP); if (params.doRDF) simGraphic.add(displayPfromGC); AccumulatorAverageCollapsing accPCC = new AccumulatorAverageCollapsing(200); DataPumpListener pumpPCC = new DataPumpListener(meterPCC, accPCC, 100); sim.integrator.getEventManager().addListener(pumpPCC); DisplayTextBoxesCAE displayPCC = new DisplayTextBoxesCAE(); displayPCC.setDoShowCurrent(false); displayPCC.setDoShowCorrelation(true); displayPCC.setAccumulator(accPCC); simGraphic.add(displayPCC); DataProcessorExtract0 gMapCExtractor = null; if (params.doMappingRDF) { MeterRDFMapped meterRDFMapped = new MeterRDFMapped(sim.integrator); meterRDFMapped.getXDataSource().setNValues(xMax * nBins + 1); meterRDFMapped.getXDataSource().setXMax(xMax); meterRDFMapped.reset(); meterRDFMapped.setResetAfterData(true); AccumulatorAverageFixed accRDFMapped = new AccumulatorAverageFixed(1); accRDFMapped.setPushInterval(1); DataPumpListener pumpRDFMapped = new DataPumpListener(meterRDFMapped, accRDFMapped, 10000); accRDFMapped.addDataSink(gPlot.getDataSet().makeDataSink(), new AccumulatorAverage.StatType[]{accRDFMapped.AVERAGE}); sim.integrator.getEventManager().addListener(pumpRDFMapped); DataProcessorErrorBar rdfMappedError = new DataProcessorErrorBar("mapped g(r)+"); accRDFMapped.addDataSink(rdfMappedError, new AccumulatorAverage.StatType[]{accRDFMapped.AVERAGE, accRDFMapped.ERROR}); rdfMappedError.setDataSink(gPlot.getDataSet().makeDataSink()); gMapCExtractor = new DataProcessorExtract0("mapped g(sigma)", true); accRDFMapped.addDataSink(gMapCExtractor, new AccumulatorAverage.StatType[]{accRDFMapped.MOST_RECENT, accRDFMapped.AVERAGE, accRDFMapped.ERROR}); gMapCExtractor.addDataSink(displayGCMap); simGraphic.getController().getDataStreamPumps().add(pumpRDFMapped); } if (params.doRDF) simGraphic.getController().getDataStreamPumps().add(pumpRDF); simGraphic.getController().getDataStreamPumps().add(pumpP); if (params.doWidom) { AccumulatorAverageCollapsing accWidom = new AccumulatorAverageCollapsing(200); DataPumpListener pumpWidom = new DataPumpListener(meterWidom, accWidom, 10); DisplayTextBoxesCAE displayWidom = new DisplayTextBoxesCAE(); displayWidom.setAccumulator(accWidom); displayWidom.setDoShowCurrent(false); displayWidom.setDoShowCorrelation(true); simGraphic.add(displayWidom); sim.integrator.getEventManager().addListener(pumpWidom); DataProcessorForked widomProcessor = new DataProcessorForked() { DataGroup data = new DataGroup(new DataDouble[]{new DataDouble(), new DataDouble(), new DataDouble()}); @Override protected IData processData(IData inputData) { ((DataDouble) data.getData(0)).x = Double.NaN; ((DataDouble) data.getData(1)).x = -Math.log(inputData.getValue(0)); ((DataDouble) data.getData(2)).x = inputData.getValue(1) / inputData.getValue(0); return data; } @Override protected IDataInfo processDataInfo(IDataInfo inputDataInfo) { DataDouble.DataInfoDouble subDataInfo = new DataDouble.DataInfoDouble("stuff", Null.DIMENSION); dataInfo = new DataGroup.DataInfoGroup("chemical potential", Energy.DIMENSION, new IDataInfo[]{subDataInfo, subDataInfo, subDataInfo}); dataInfo.addTag(tag); return dataInfo; } }; accWidom.addDataSink(widomProcessor, new AccumulatorAverage.StatType[]{accWidom.AVERAGE, accWidom.ERROR}); DisplayTextBoxesCAE displayMu = new DisplayTextBoxesCAE(); widomProcessor.addDataSink(displayMu); displayMu.setLabel("Chemical Potential"); displayMu.setDoShowCurrent(false); simGraphic.add(displayMu); simGraphic.getController().getDataStreamPumps().add(pumpWidom); } if (params.doWidomCavity) { AccumulatorAverageFixed accWC = new AccumulatorAverageFixed(200); DataPumpListener pumpWC = new DataPumpListener(meterWC, accWC, 10); sim.integrator.getEventManager().addListener(pumpWC); DisplayPlot yPlot = new DisplayPlot(); accWC.addDataSink(yPlot.getDataSet().makeDataSink(), new AccumulatorAverage.StatType[]{accWC.AVERAGE}); DataProcessorErrorBar dpErrorWC = new DataProcessorErrorBar("y(r)+"); accWC.addDataSink(dpErrorWC, new AccumulatorAverage.StatType[]{accWC.AVERAGE, accWC.ERROR}); dpErrorWC.setDataSink(yPlot.getDataSet().makeDataSink()); yPlot.setLabel("y(r)"); simGraphic.add(yPlot); yPlot.getPlot().setYLog(true); if (params.doMappingRDF || params.doRDF) { DataProcessorWidomContact dpwc = new DataProcessorWidomContact(); accWC.addDataSink(dpwc, new AccumulatorAverage.StatType[]{accWC.AVERAGE, accWC.ERROR}); if (params.doMappingRDF) { gMapCExtractor.addDataSink(dpwc.makeGContactSink()); } else { gCExtractor.addDataSink(dpwc.makeGContactSink()); } DisplayTextBoxesCAE displayWC = new DisplayTextBoxesCAE(); displayWC.setDoShowCurrent(false); dpwc.setDataSink(displayWC); simGraphic.add(displayWC); } } simGraphic.makeAndDisplayFrame(APP_NAME); return; } System.out.println("N: " + params.nAtoms); System.out.println("steps: " + params.steps); System.out.println("density: " + params.density); long steps = params.steps; sim.activityIntegrate.setMaxSteps(steps / 10); sim.activityIntegrate.actionPerformed(); sim.integrator.resetStepCount(); AccumulatorAverageFixed accRDFMapped = new AccumulatorAverageFixed(1); if (params.doMappingRDF) { MeterRDFMapped meterRDFMapped = new MeterRDFMapped(sim.integrator); meterRDFMapped.foobar = params.doMappingFoobar; if (params.mappingCut > 0) meterRDFMapped.setMappingCut(params.mappingCut); meterRDFMapped.getXDataSource().setNValues(nBinsLong + 1); meterRDFMapped.getXDataSource().setXMax(xMaxMap); meterRDFMapped.reset(); meterRDFMapped.setResetAfterData(true); DataPumpListener pumpRDFMapped = new DataPumpListener(meterRDFMapped, null, (int) (steps / 100)); meterRDFMapped.setRawSink(accRDFMapped); sim.integrator.getEventManager().addListener(pumpRDFMapped); } AccumulatorAverageFixed accRDF = new AccumulatorAverageFixed(1); if (params.doRDF) { int rdfInterval = (30 * params.nAtoms + 199) / 200; if (params.rdfInterval > 0) rdfInterval = params.rdfInterval; int stepsPerBlock = (int) (steps / 100); while (rdfInterval > stepsPerBlock && (steps % (stepsPerBlock * 2) == 0)) stepsPerBlock *= 2; while (stepsPerBlock % rdfInterval != 0) rdfInterval System.out.println("RDF interval: " + rdfInterval); System.out.println("steps per block: " + stepsPerBlock); sim.integrator.getEventManager().addListener(new IntegratorListenerAction(meterRDF, rdfInterval)); DataPumpListener pumpRDF = new DataPumpListener(meterRDF, accRDF, stepsPerBlock); sim.integrator.getEventManager().addListener(pumpRDF); } AccumulatorAverageFixed accWidom = null; if (params.doWidom) { accWidom = new AccumulatorAverageFixed((int) (steps / 1000)); DataPumpListener pumpWidom = new DataPumpListener(meterWidom, accWidom, 10); sim.integrator.getEventManager().addListener(pumpWidom); } AccumulatorAverageFixed accWC = null; if (params.doWidomCavity) { accWC = new AccumulatorAverageFixed((int) (steps / 1000)); DataPumpListener pumpWC = new DataPumpListener(meterWC, accWC, 10); sim.integrator.getEventManager().addListener(pumpWC); } MeterPressureHard meterP = new MeterPressureHard(sim.integrator); MeterPressureCollisionCount meterPCC = new MeterPressureCollisionCount(sim.integrator); AccumulatorAverageFixed accP = new AccumulatorAverageFixed(1); DataPumpListener pumpP = new DataPumpListener(meterP, accP, (int) (steps / 100)); sim.integrator.getEventManager().addListener(pumpP); AccumulatorAverageFixed accPCC = new AccumulatorAverageFixed(1); DataPumpListener pumpPCC = new DataPumpListener(meterPCC, accPCC, (int) (steps / 100)); sim.integrator.getEventManager().addListener(pumpPCC); long t1 = System.nanoTime(); sim.activityIntegrate.setMaxSteps(steps); sim.activityIntegrate.actionPerformed(); long t2 = System.nanoTime(); double avgP = accP.getData(accP.AVERAGE).getValue(0); double errP = accP.getData(accP.ERROR).getValue(0); double corP = accP.getData(accP.BLOCK_CORRELATION).getValue(0); System.out.println("Pressure: " + avgP + " err: " + errP + " cor: " + corP); double avgPCC = accPCC.getData(accPCC.AVERAGE).getValue(0); double errPCC = accPCC.getData(accPCC.ERROR).getValue(0); double corPCC = accPCC.getData(accPCC.BLOCK_CORRELATION).getValue(0); System.out.println("Pressure(CC): " + avgPCC + " err: " + errPCC + " cor: " + corPCC); if (params.doRDF) { IData rData = ((DataFunction.DataInfoFunction) ((DataGroup.DataInfoGroup) accRDF.getDataInfo()).getSubDataInfo(0)).getXDataSource().getIndependentData(0); IData rdfDataAvg = accRDF.getData(accRDF.AVERAGE); IData rdfDataErr = accRDF.getData(accRDF.ERROR); IData rdfDataCor = accRDF.getData(accRDF.BLOCK_CORRELATION); System.out.println("\nRDF"); for (int i = 0; i < rData.getLength(); i++) { System.out.println(rData.getValue(i) + " " + rdfDataAvg.getValue(i) + " " + rdfDataErr.getValue(i) + " " + rdfDataCor.getValue(i)); } } if (params.doMappingRDF) { IData rData = ((DataFunction.DataInfoFunction) ((DataGroup.DataInfoGroup) accRDFMapped.getDataInfo()).getSubDataInfo(0)).getXDataSource().getIndependentData(0); IData rdfDataAvg = accRDFMapped.getData(accRDFMapped.AVERAGE); IData rdfDataErr = accRDFMapped.getData(accRDFMapped.ERROR); IData rdfDataCor = accRDFMapped.getData(accRDFMapped.BLOCK_CORRELATION); System.out.println("\nmapped RDF"); for (int i = 0; i < rData.getLength(); i++) { System.out.println(rData.getValue(i) + " " + rdfDataAvg.getValue(i) + " " + rdfDataErr.getValue(i) + " " + rdfDataCor.getValue(i)); } } if (params.doWidom) { double avgExp = accWidom.getData(accWidom.AVERAGE).getValue(0); double errExp = accWidom.getData(accWidom.ERROR).getValue(0); double corExp = accWidom.getData(accWidom.BLOCK_CORRELATION).getValue(0); System.out.println("Widom exp: " + avgExp + " err: " + errExp + " cor: " + corExp); double mu = -Math.log(avgExp); double errMu = errExp / avgExp; System.out.println("Widom mu: " + mu + " err: " + errMu); } if (params.doWidomCavity) { IData rData = ((DataFunction.DataInfoFunction) ((DataGroup.DataInfoGroup) accWC.getDataInfo()).getSubDataInfo(0)).getXDataSource().getIndependentData(0); IData wcDataAvg = accWC.getData(accWC.AVERAGE); IData wcDataErr = accWC.getData(accWC.ERROR); IData wcDataCor = accWC.getData(accWC.BLOCK_CORRELATION); System.out.println("\nWidom cavity"); for (int i = 0; i < rData.getLength(); i++) { System.out.println(rData.getValue(i) + " " + wcDataAvg.getValue(i) + " " + wcDataErr.getValue(i) + " " + wcDataCor.getValue(i)); } } System.out.println("\ntime: " + (t2 - t1) / 1e9); } /** * Inner class for parameters understood by the HSMDCavity constructor */ public static class HSMDParam extends ParameterBase { public long steps = 1000000; public int nAtoms = 256; public double density = 0.6; public int mappingCut = 0; public boolean useNeighborLists = true; public boolean doGraphics = false; public boolean doWidom = false; public boolean doRDF = false; public int rdfInterval = 0; public boolean doMappingRDF = false; public boolean doMappingFoobar = false; public boolean doWidomCavity = false; public int nWidomCavity = 10; public double widomCavityMax = 1; } }
package io.spacedog.examples; import java.util.Optional; import java.util.Random; import org.junit.Test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.spacedog.client.SpaceClient; import io.spacedog.client.SpaceRequest; import io.spacedog.client.SpaceTarget; import io.spacedog.utils.DataPermission; import io.spacedog.utils.Json; import io.spacedog.utils.JsonGenerator; import io.spacedog.utils.Schema; public class Caremen extends SpaceClient { static final Backend DEV = new Backend( "caredev", "caredev", "hi caredev", "david@spacedog.io"); private Backend backend; private JsonGenerator generator = new JsonGenerator(); private Random random = new Random(); @Test public void initCaremenBackend() { backend = DEV; SpaceRequest.configuration().target(SpaceTarget.production); // resetBackend(backend); // initInstallations(); // initVehiculeTypes(); // resetSchema(buildCourseSchema(), backend); // resetSchema(buildDriverSchema(), backend); // resetSchema(buildCustomerSchema(), backend); // resetSchema(buildDriverLogSchema(), backend); // createCustomers(); // createDrivers(); } void createCustomers() { Schema schema = buildCustomerSchema(); createCustomer("flavien", schema); createCustomer("aurelien", schema); createCustomer("david", schema); createCustomer("philippe", schema); } User createCustomer(String username, Schema schema) { String password = "hi " + username; String email = "david@spacedog.io"; Optional<User> optional = SpaceClient.login(backend.backendId, username, password, 200, 401); User credentials = optional.isPresent() ? optional.get() : SpaceClient.newCredentials(backend, username, password, email); SpaceRequest.put("/1/credentials/" + credentials.id + "/roles/customer") .adminAuth(backend).go(200); ObjectNode customer = generator.gen(schema, 0); customer.put("credentialsId", credentials.id); customer.put("firstname", credentials.username); customer.put("lastname", credentials.username.charAt(0) + "."); customer.put("phone", "0033662627520"); SpaceRequest.post("/1/data/customer").userAuth(credentials).body(customer).go(201); return credentials; } static Schema buildCustomerSchema() { return Schema.builder("customer") .acl("customer", DataPermission.create, DataPermission.search, DataPermission.update) .acl("admin", DataPermission.search, DataPermission.update_all, DataPermission.delete_all) .string("credentialsId").examples("khljgGFJHfvlkHMhjh") .string("firstname").examples("Robert") .string("lastname").examples("Morgan") .string("phone").examples("+ 33 6 42 01 67 56") .object("billing") .text("name").french().examples("In-tact SARL") .text("street").french().examples("9 rue Titon") .string("zipcode").examples("75011") .text("town").examples("Paris") .close() .close() .build(); } void initInstallations() { SpaceRequest.delete("/1/schema/installation").adminAuth(backend).go(200, 404); SpaceRequest.put("/1/schema/installation").adminAuth(backend).go(201); Schema schema = SpaceClient.getSchema("installation", backend); schema.acl("key", DataPermission.create, DataPermission.read, DataPermission.update, DataPermission.delete); schema.acl("user", DataPermission.create, DataPermission.read, DataPermission.update, DataPermission.delete); schema.acl("admin", DataPermission.search, DataPermission.update_all, DataPermission.delete_all); SpaceClient.setSchema(schema, backend); } static Schema buildCourseSchema() { return Schema.builder("course") .acl("customer", DataPermission.create, DataPermission.read, DataPermission.search, DataPermission.update) .acl("driver", DataPermission.search, DataPermission.update_all) .acl("admin", DataPermission.create, DataPermission.search, DataPermission.update_all, DataPermission.delete_all) .string("status").examples("requested") .string("customerId").examples("david") .string("requestedVehiculeType").examples("classic") .timestamp("requestedPickupTimestamp").examples("2016-07-12T14:00:00.000Z") .timestamp("pickupTimestamp").examples("2016-07-12T14:00:00.000Z") .timestamp("dropoffTimestamp").examples("2016-07-12T14:00:00.000Z") .floatt("fare").examples(23.82)// in euros .longg("time").examples(1234567)// in millis .integer("distance").examples(12345)// in meters .object("from") .text("address").french().examples("8 rue Titon 75011 Paris") .geopoint("geopoint") .close() .object("to") .text("address").french().examples("8 rue Pierre Dupont 75010 Paris") .geopoint("geopoint") .close() .object("driver") .string("driverId").examples("robert") .floatt("gain").examples("10.23") .string("firstname").examples("Robert") .string("lastname").examples("Morgan") .string("phone").examples("+ 33 6 42 01 67 56") .string("photo") .examples("http://s3-eu-west-1.amazonaws.com/spacedog-artefact/SpaceDog-Logo-Transp-130px.png")// .object("vehicule") .string("type").examples("classic") .string("brand").examples("Peugeot", "Renault") .string("model").examples("508", "Laguna", "Talisman") .string("color").examples("black", "white", "pink") .close() .close() .build(); } void createDrivers() { Schema schema = buildDriverSchema(); createDriver("marcel", schema); createDriver("gerard", schema); createDriver("robert", schema); createDriver("suzanne", schema); } void createDriver(String username, Schema schema) { String password = "hi " + username; String email = (username.startsWith("driver") ? "driver" : username) + "@caremen.com"; Optional<User> optional = SpaceClient.login(backend.backendId, username, password, 200, 401); User credentials = optional.isPresent() ? optional.get() : SpaceClient.newCredentials(backend, username, password, email); SpaceRequest.put("/1/credentials/" + credentials.id + "/roles/driver").adminAuth(backend).go(200); ObjectNode driver = generator.gen(schema, 0); driver.put("status", "working"); driver.put("credentialsId", credentials.id); driver.put("firstname", credentials.username); driver.put("lastname", credentials.username.charAt(0) + "."); JsonNode where = Json.object("lat", 48.844 + (random.nextFloat() / 10), "lon", 2.282 + (random.nextFloat() / 10)); Json.set(driver, "lastLocation.where", where); SpaceRequest.post("/1/data/driver").adminAuth(backend).body(driver).go(201); } static Schema buildDriverSchema() { return Schema.builder("driver") .acl("customer", DataPermission.search) .acl("driver", DataPermission.search, DataPermission.update_all) .acl("admin", DataPermission.create, DataPermission.search, DataPermission.update_all, DataPermission.delete_all) .string("credentialsId").examples("khljgGFJHfvlkHMhjh") .string("status").examples("working") .string("firstname").examples("Robert") .string("lastname").examples("Morgan") .text("homeAddress").french().examples("52 rue Michel Ange 75016 Paris") .string("phone").examples("+ 33 6 42 01 67 56") .string("photo") .examples("http://s3-eu-west-1.amazonaws.com/spacedog-artefact/SpaceDog-Logo-Transp-130px.png")// .object("lastLocation") .geopoint("where") .timestamp("when") .close() .object("vehicule") .string("type").examples("classic") .string("brand").examples("Peugeot", "Renault") .string("model").examples("508", "Laguna", "Talisman") .string("color").examples("black", "white", "pink") .close() .object("RIB") .text("bankName").french().examples("Société Générale") .string("bankCode").examples("SOGEFRPP") .string("accountIBAN").examples("FR568768757657657689") .close() .close() .build(); } static Schema buildDriverLogSchema() { return Schema.builder("driverlog") .acl("driver", DataPermission.create) .acl("admin", DataPermission.create, DataPermission.search, DataPermission.delete_all) .string("driverId").examples("robert") .geopoint("where") .object("course") .string("id").examples("robert") .string("statusUpdatedTo").examples("accepted", "waiting") .string("statusUpdatedFrom").examples("requested", "accepted") .close() .close() .build(); } void initVehiculeTypes() { ArrayNode node = Json.arrayBuilder() .object() .put("type", "classic") .put("name", "Berline Classic") .put("description", "Standard") .put("minimumPrice", 10) .put("passengers", 4) .end() .object() .put("type", "premium") .put("name", "Berline Premium") .put("description", "Haut de gamme") .put("minimumPrice", 15) .put("passengers", 4) .end() .object() .put("type", "green") .put("name", "GREEN BERLINE") .put("description", "Electric cars") .put("minimumPrice", 15) .put("passengers", 4) .end() .object() .put("type", "break") .put("name", "BREAK") .put("description", "Grand coffre") .put("minimumPrice", 15) .put("passengers", 4) .end() .object() .put("type", "van") .put("name", "VAN") .put("description", "Mini bus") .put("minimumPrice", 15) .put("passengers", 6) .end() .build(); SpaceRequest.put("/1/settings/carTypes") .adminAuth(backend).body(node).go(201); } }
package org.sagebionetworks.bridge.dynamodb; import static org.junit.Assert.assertEquals; import java.util.Set; import java.util.TreeSet; import org.junit.Test; import com.google.common.collect.Sets; public class StringSetMarshallerTest { private static final StringSetMarshaller MARSHALLER = new StringSetMarshaller(); @Test public void serializationTest() { TreeSet<String> orderedSet = new TreeSet<>(); orderedSet.add("Paris"); orderedSet.add("Brussels"); orderedSet.add("London"); String ser = MARSHALLER.convert(orderedSet); assertEquals("[\"Brussels\",\"London\",\"Paris\"]", ser); Set<String> deser = MARSHALLER.unconvert(ser); assertEquals(orderedSet, deser); } @Test public void serializeEmptySet() { String ser = MARSHALLER.convert(Sets.newHashSet()); assertEquals("[]", ser); Set<String> deser = MARSHALLER.unconvert(ser); assertEquals(Sets.newHashSet(), deser); } }
import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.Before; import org.junit.rules.ExpectedException; import static org.junit.Assert.assertEquals; public final class WordProblemSolverTest { @Rule public ExpectedException expectedException = ExpectedException.none(); WordProblemSolver solver; @Before public void setup() { solver = new WordProblemSolver(); } @Test public void testSingleAddition1() { assertEquals(2, solver.solve("What is 1 plus 1?")); } @Ignore @Test public void testSingleAddition2() { assertEquals(55, solver.solve("What is 53 plus 2?")); } @Ignore @Test public void testSingleAdditionWithNegativeNumbers() { assertEquals(-11, solver.solve("What is -1 plus -10?")); } @Ignore @Test public void testSingleAdditionOfLargeNumbers() { assertEquals(45801, solver.solve("What is 123 plus 45678?")); } @Ignore @Test public void testSingleSubtraction() { assertEquals(16, solver.solve("What is 4 minus -12?")); } @Ignore @Test public void testSingleMultiplication() { assertEquals(-75, solver.solve("What is -3 multiplied by 25?")); } @Ignore @Test public void testSingleDivision() { assertEquals(-11, solver.solve("What is 33 divided by -3?")); } @Ignore @Test public void testMultipleAdditions() { assertEquals(3, solver.solve("What is 1 plus 1 plus 1?")); } @Ignore @Test public void testAdditionThenSubtraction() { assertEquals(8, solver.solve("What is 1 plus 5 minus -2?")); } @Ignore @Test public void testMultipleSubtractions() { assertEquals(3, solver.solve("What is 20 minus 4 minus 13?")); } @Ignore @Test public void testSubtractionThenAddition() { assertEquals(14, solver.solve("What is 17 minus 6 plus 3?")); } @Ignore @Test public void testMultipleMultiplications() { assertEquals(-12, solver.solve("What is 2 multiplied by -2 multiplied by 3?")); } @Ignore @Test public void testAdditionThenMultiplication() { assertEquals(-8, solver.solve("What is -3 plus 7 multiplied by -2?")); } @Ignore @Test public void testMultipleDivisions() { assertEquals(2, solver.solve("What is -12 divided by 2 divided by -3?")); } @Ignore @Test public void testUnknownOperation() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("I'm sorry, I don't understand the question!"); solver.solve("What is 52 cubed?"); } @Ignore @Test public void testInvalidQuestionFormat() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("I'm sorry, I don't understand the question!"); solver.solve("Who is the President of the United States?"); } }
package org.encog.util; import junit.framework.TestCase; public class TestErrorCalculation extends TestCase { public void testErrorCalculation() { double ideal[][] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16} }; double actual_good[][] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16} }; double actual_bad[][] = { {1,2,3,5}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16} }; ErrorCalculation error = new ErrorCalculation(); for(int i=0;i<ideal.length;i++) { error.updateError(actual_good[i], ideal[i]); } TestCase.assertEquals(0.0,error.calculateRMS()); error.reset(); for(int i=0;i<ideal.length;i++) { error.updateError(actual_bad[i], ideal[i]); } TestCase.assertEquals(250,(int)(error.calculateRMS()*1000)); } }
package cgeo.geocaching.utils.expressions; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.BooleanUtils; import org.junit.Test; import static org.assertj.core.api.Java6Assertions.assertThat; public class ExpressionConfigTest { private static final List<String> stringListSingle = new ArrayList<>(Arrays.asList("singleValue")); private static final List<String> stringListMulti = new ArrayList<>(Arrays.asList("value1", "value2", "value3")); private static final String keyString = "testKey"; /** * Put list with multi entries as default. * Try to get default list returns this list. */ @Test public void testDefaultList() { final ExpressionConfig config = new ExpressionConfig(); config.putDefaultList(stringListMulti); final List<String> defaultList = config.getDefaultList(); assertThat(defaultList).isEqualTo(stringListMulti); } /** * Empty expression config. * Try to get default list returns empty list. */ @Test public void testEmptyDefaultList() { final ExpressionConfig config = new ExpressionConfig(); final List<String> defaultList = config.getDefaultList(); assertThat(defaultList).isNotNull(); assertThat(defaultList.size()).isEqualTo(0); } /** * Put list with multi entries as default. * Add single value to default list. * Try to get default list returns entries from multi-list plus the single value. */ @Test public void testAddToDefaultList() { final ExpressionConfig config = new ExpressionConfig(); config.putDefaultList(stringListMulti); final int sizeBefore = stringListMulti.size(); config.addToDefaultList("newValue"); final List<String> defaultList = config.getDefaultList(); assertThat(defaultList.size()).isEqualTo(sizeBefore + 1); } /** * Put list with single entries as default. * Try to get single value returns value of list. */ @Test public void testGetSingleValueListSingle() { final ExpressionConfig config = new ExpressionConfig(); config.putDefaultList(stringListSingle); final String singleValue = config.getSingleValue(); assertThat(singleValue).isNotNull(); assertThat(singleValue).isEqualTo(stringListSingle.get(0)); } /** * Put list with multi entries as default. * Try to get single value returns null. */ @Test public void testGetSingleValueListMulti() { final ExpressionConfig config = new ExpressionConfig(); config.putDefaultList(stringListMulti); final String singleValue = config.getSingleValue(); assertThat(singleValue).isNull(); } /** * Add value to config 'keyString'. * Try to get value from config. */ @Test public void testGetKeyValue() { final ExpressionConfig config = new ExpressionConfig(); config.put(keyString, stringListMulti); final List<String> value = config.get(keyString); assertThat(value).isNotNull(); assertThat(value).isEqualTo(stringListMulti); } /** * Add single value to config 'keyString'. * Try to get first value. */ @Test public void testGetFirstValue() { final ExpressionConfig config = new ExpressionConfig(); config.putList(keyString, "true"); final boolean firstValue = config.getFirstValue(keyString, false, BooleanUtils::toBoolean); assertThat(firstValue).isTrue(); } /** * Add single value to config 'keyString', which is not valid for the converter. * Try to get first value returns default value. */ @Test public void testGetFirstValueDefault() { final ExpressionConfig config = new ExpressionConfig(); config.putList(keyString, "value"); final boolean firstValue = config.getFirstValue(keyString, false, BooleanUtils::toBoolean); assertThat(firstValue).isFalse(); } /** * Add value to config 'keyString'. * Create SubConfig from 'keyString' returns config with value from 'keyString' in defaultList. */ @Test public void testGetSubConfig() { final ExpressionConfig config = new ExpressionConfig(); config.put(keyString, stringListMulti); final ExpressionConfig subConfig = config.getSubConfig(keyString); assertThat(subConfig).isNotNull(); final List<String> defaultList = subConfig.getDefaultList(); assertThat(defaultList).isEqualTo(stringListMulti); } }
package edu.umd.cs.findbugs.cloud; import java.awt.GraphicsEnvironment; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.prefs.Preferences; import java.util.regex.Pattern; import javax.annotation.CheckForNull; import edu.umd.cs.findbugs.BugAnnotation; import edu.umd.cs.findbugs.BugCollection; import edu.umd.cs.findbugs.BugDesignation; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugRanker; import edu.umd.cs.findbugs.ClassAnnotation; import edu.umd.cs.findbugs.I18N; import edu.umd.cs.findbugs.PluginLoader; import edu.umd.cs.findbugs.ProjectPackagePrefixes; import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.Version; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.SourceFile; import edu.umd.cs.findbugs.gui2.MainFrame; import edu.umd.cs.findbugs.internalAnnotations.SlashedClassName; import edu.umd.cs.findbugs.util.Multiset; import edu.umd.cs.findbugs.util.Util; /** * @author pwilliam */ public class DBCloud extends AbstractCloud { final static long minimumTimestamp = 1000000000000L; Mode mode = Mode.VOTING; public Mode getMode() { return mode; } public void setMode(Mode mode) { this.mode = mode; } class BugData { final String instanceHash; public BugData(String instanceHash) { this.instanceHash = instanceHash; } int id; boolean inDatabase; long firstSeen; String bugLink = NONE; String filedBy; String bugStatus; String bugAssignedTo; String bugComponentName; long bugFiled; SortedSet<BugDesignation> designations = new TreeSet<BugDesignation>(); Collection<BugInstance> bugs = new LinkedHashSet<BugInstance>(); @CheckForNull BugDesignation getPrimaryDesignation() { BugDesignation primaryDesignation = mode.getPrimaryDesignation(findbugsUser, designations); return primaryDesignation; } @CheckForNull BugDesignation getUserDesignation() { for(BugDesignation d : designations) if (findbugsUser.equals(d.getUser())) return new BugDesignation(d); return null; } Iterable<BugDesignation> getUniqueDesignations() { if (designations.isEmpty()) return Collections.emptyList(); HashSet<String> reviewers = new HashSet<String>(); ArrayList<BugDesignation> result = new ArrayList<BugDesignation>(designations.size()); for(BugDesignation d : designations) if (reviewers.add(d.getUser())) result.add(d); return result; } Set<String> getReviewers() { HashSet<String> reviewers = new HashSet<String>(); for(BugDesignation bd : designations) reviewers.add(bd.getUser()); reviewers.remove(""); reviewers.remove(null); return reviewers; } boolean isClaimed() { Set<String> users = new HashSet<String>(); for(BugDesignation bd : designations) { if (users.add(bd.getUser()) && bd.getDesignationKey().equals(UserDesignation.I_WILL_FIX.name())) return true; } return false; } BugDesignation getNonnullUserDesignation() { BugDesignation d = getUserDesignation(); if (d != null) return d; d = new BugDesignation(UserDesignation.UNCLASSIFIED.name(), System.currentTimeMillis(), "", findbugsUser); return d; } /**filebug * @return */ public boolean canSeeCommentsByOthers() { switch(mode) { case SECRET: return false; case COMMUNAL : return true; case VOTING : return hasVoted(); } throw new IllegalStateException(); } public boolean hasVoted() { for(BugDesignation bd : designations) if (findbugsUser.equals(bd.getUser())) return true; return false; } } int updatesSentToDatabase; Date lastUpdate = new Date(); Map<String, BugData> instanceMap = new HashMap<String, BugData>(); Map<Integer, BugData> idMap = new HashMap<Integer, BugData>(); IdentityHashMap<BugDesignation, Integer> bugDesignationId = new IdentityHashMap<BugDesignation, Integer>(); BugData getBugData(String instanceHash) { BugData bd = instanceMap.get(instanceHash); if (bd == null) { bd = new BugData(instanceHash); instanceMap.put(instanceHash, bd); } return bd; } BugData getBugData(BugInstance bug) { BugData bugData = getBugData(bug.getInstanceHash()); bugData.bugs.add(bug); return bugData; } void loadDatabaseInfo(String hash, int id, long firstSeen) { BugData bd = instanceMap.get(hash); if (bd == null) return; if (idMap.containsKey(id)) { assert bd == idMap.get(id); assert bd.id == id; assert bd.firstSeen == firstSeen; } else { bd.id = id; bd.firstSeen = firstSeen; bd.inDatabase = true; bd.bugFiled = Long.MAX_VALUE; idMap.put(id, bd); } } DBCloud(BugCollection bugs) { super(bugs); } static final Pattern FORBIDDEN_PACKAGE_PREFIXES = Pattern.compile(SystemProperties.getProperty("findbugs.forbiddenPackagePrefixes", " none ").replace(',','|')); int sessionId = -1; public void bugsPopulated() { String commonPrefix = null; for (BugInstance b : bugCollection.getCollection()) if (!skipBug(b)) { commonPrefix = Util.commonPrefix(commonPrefix, b.getPrimaryClass().getClassName()); getBugData(b.getInstanceHash()).bugs.add(b); } if (commonPrefix == null) commonPrefix = "<no bugs>"; else if (commonPrefix.length() > 128) commonPrefix = commonPrefix.substring(0, 128); try { long startTime = System.currentTimeMillis(); Connection c = getConnection(); PreparedStatement ps = c.prepareStatement("SELECT id, hash, firstSeen FROM findbugs_issue"); ResultSet rs = ps.executeQuery(); while (rs.next()) { int col = 1; int id = rs.getInt(col++); String hash = rs.getString(col++); Timestamp firstSeen = rs.getTimestamp(col++); loadDatabaseInfo(hash, id, firstSeen.getTime()); } rs.close(); ps.close(); ps = c.prepareStatement("SELECT id, issueId, who, designation, comment, time FROM findbugs_evaluation"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; int id = rs.getInt(col++); int issueId = rs.getInt(col++); String who = rs.getString(col++); String designation = rs.getString(col++); String comment = rs.getString(col++); Timestamp when = rs.getTimestamp(col++); BugData data = idMap.get(issueId); if (data != null) { BugDesignation bd = new BugDesignation(designation, when.getTime(), comment, who); bugDesignationId.put(bd, id); data.designations.add(bd); } } rs.close(); ps.close(); ps = c.prepareStatement("SELECT hash, bugReportId, whoFiled, whenFiled, status, assignedTo, componentName FROM findbugs_bugreport"); rs = ps.executeQuery(); while (rs.next()) { int col = 1; String hash = rs.getString(col++); String bugReportId = rs.getString(col++); String whoFiled = rs.getString(col++); Timestamp whenFiled = rs.getTimestamp(col++); String status = rs.getString(col++); String assignedTo = rs.getString(col++); String componentName = rs.getString(col++); BugData data = instanceMap.get(hash); if (data != null) { data.bugLink = bugReportId; data.filedBy = whoFiled; data.bugFiled = whenFiled.getTime(); data.bugAssignedTo = assignedTo; data.bugStatus = status; data.bugComponentName = componentName; } } rs.close(); ps.close(); long initialSyncTime = System.currentTimeMillis() - startTime; PreparedStatement insertSession = c.prepareStatement("INSERT INTO findbugs_invocation (who, entryPoint, dataSource, fbVersion, initialSyncTime, numIssues, startTime, commonPrefix)" + " VALUES (?,?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); Timestamp now = new Timestamp(startTime); int col = 1; insertSession.setString(col++, findbugsUser); insertSession.setString(col++, ""); insertSession.setString(col++,""); insertSession.setString(col++, Version.RELEASE); insertSession.setLong(col++, initialSyncTime); insertSession.setInt(col++, bugCollection.getCollection().size()); insertSession.setTimestamp(col++, now); insertSession.setString(col++, commonPrefix); int rowCount = insertSession.executeUpdate(); rs = insertSession.getGeneratedKeys(); if (rs.next()) { sessionId = rs.getInt(1); } insertSession.close(); rs.close(); c.close(); } catch (Exception e) { e.printStackTrace(); displayMessage("problem bulk loading database", e); } for (BugInstance b : bugCollection.getCollection()) if (!skipBug(b)) { BugData bd = getBugData(b.getInstanceHash()); if (!bd.inDatabase) { storeNewBug(b); } else { issuesBulkHandled++; long firstVersion = b.getFirstVersion(); long firstSeen = bugCollection.getAppVersionFromSequenceNumber(firstVersion).getTimestamp(); if (firstSeen < minimumTimestamp) { displayMessage("Got timestamp of " + firstSeen + " which is equal to " + new Date(firstSeen)); } else if (firstSeen < bd.firstSeen) { bd.firstSeen = firstSeen; storeFirstSeen(bd); } long lastVersion = b.getLastVersion(); if (lastVersion != -1) { long lastSeen = bugCollection.getAppVersionFromSequenceNumber(firstVersion).getTimestamp(); } BugDesignation designation = bd.getPrimaryDesignation(); if (designation != null) b.setUserDesignation(new BugDesignation(designation)); } } } int issuesBulkHandled = 0; private String getProperty(String propertyName) { return SystemProperties.getProperty("findbugs.jdbc." + propertyName); } String url, dbUser, dbPassword, findbugsUser, dbName; @CheckForNull Pattern sourceFileLinkPattern; String sourceFileLinkFormat; String sourceFileLinkFormatWithLine; String sourceFileLinkToolTip; ProjectPackagePrefixes projectMapping = new ProjectPackagePrefixes(); Map<String,String> prefixBugComponentMapping = new HashMap<String,String>(); private Connection getConnection() throws SQLException { return DriverManager.getConnection(url, dbUser, dbPassword); } public boolean initialize() { String sp = SystemProperties.getProperty("findbugs.sourcelink.pattern"); String sf = SystemProperties.getProperty("findbugs.sourcelink.format"); String sfwl = SystemProperties.getProperty("findbugs.sourcelink.formatWithLine"); String stt = SystemProperties.getProperty("findbugs.sourcelink.tooltip"); if (sp != null && sf != null) { try { this.sourceFileLinkPattern = Pattern.compile(sp); this.sourceFileLinkFormat = sf; this.sourceFileLinkToolTip = stt; this.sourceFileLinkFormatWithLine = sfwl; } catch (RuntimeException e) { AnalysisContext.logError("Could not compile pattern " + sp, e); } } String sqlDriver = getProperty("dbDriver"); url = getProperty("dbUrl"); dbName = getProperty("dbName"); dbUser = getProperty("dbUser"); dbPassword = getProperty("dbPassword"); findbugsUser = getProperty("findbugsUser"); if (sqlDriver == null || dbUser == null || url == null || dbPassword == null) return false; if (findbugsUser == null) { findbugsUser = System.getProperty("user.name", ""); if (false) try { findbugsUser += "@" + InetAddress.getLocalHost().getHostName(); } catch (Exception e) {} } loadBugComponents(); try { Class.forName(sqlDriver); Connection c = getConnection(); Statement stmt = c.createStatement(); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) from findbugs_issue"); boolean result = false; if (rs.next()) { int count = rs.getInt(1); result = findbugsUser != null; } rs.close(); stmt.close(); c.close(); if (result) { runnerThread.setDaemon(true); runnerThread.start(); } return result; } catch (Exception e) { displayMessage("Unable to connect to database", e); return false; } } private String getBugComponent(@SlashedClassName String className) { int longestMatch = -1; String result = null; for(Map.Entry<String,String> e : prefixBugComponentMapping.entrySet()) { String key = e.getKey(); if (className.startsWith(key) && longestMatch < key.length()) { longestMatch = key.length(); result = e.getValue(); } } return result; } private void loadBugComponents(){ try { URL u = PluginLoader.getCoreResource("bugComponents.properties"); if (u != null) { BufferedReader in = new BufferedReader(new InputStreamReader(u.openStream())); while(true) { String s = in.readLine(); if (s == null) break; if (s.trim().length() == 0) continue; int x = s.indexOf(' '); if (x == -1) prefixBugComponentMapping.put("", s); else prefixBugComponentMapping.put(s.substring(x+1), s.substring(0,x)); } in.close(); } } catch (IOException e) { AnalysisContext.logError("Unable to load bug component properties", e); } } final LinkedBlockingQueue<Update> queue = new LinkedBlockingQueue<Update>(); volatile boolean shutdown = false; final DatabaseSyncTask runner = new DatabaseSyncTask(); final Thread runnerThread = new Thread(runner, "Database synchronization thread"); @Override public void shutdown() { queue.add(new ShutdownTask()); try { Connection c = getConnection(); PreparedStatement setEndTime = c.prepareStatement("UPDATE findbugs_invocation SET endTime = ? WHERE id = ?"); Timestamp date = new Timestamp(System.currentTimeMillis()); int col = 1; setEndTime.setTimestamp(col++, date); setEndTime.setInt(col++, sessionId); setEndTime.execute(); } catch (SQLException e) { // we're in shutdown mode, not going to complain assert true; } if (!queue.isEmpty() && runnerThread.isAlive()) { setErrorMsg("waiting for synchronization to complete before shutdown"); for (int i = 0; i < 100; i++) { if (queue.isEmpty() || !runnerThread.isAlive()) break; try { Thread.sleep(30); } catch (InterruptedException e) { break; } } } shutdown = true; runnerThread.interrupt(); } public void storeNewBug(BugInstance bug) { queue.add(new StoreNewBug(bug)); updatedStatus(); } public void storeFirstSeen(final BugData bd) { queue.add(new Update(){ public void execute(DatabaseSyncTask t) throws SQLException { t.storeFirstSeen(bd); }}); updatedStatus(); } public void storeUserAnnotation(BugData data, BugDesignation bd) { queue.add(new StoreUserAnnotation(data, bd)); updatedStatus(); if (firstTimeDoing(HAS_CLASSIFIED_ISSUES)) { String msg = "Classification and comments have been sent to database.\n" + "You'll only see this message the first time your classifcations/comments are sent\n" + "to the database."; if (mode == Mode.VOTING) msg += "\nOnce you've classified an issue, you can see how others have classified it."; msg += "\nYour classification and comments are independent from filing a bug using an external\n" + "bug reporting system."; bugCollection.getProject().getGuiCallback().showMessageDialog(msg); } } private boolean skipBug(BugInstance bug) { return bug.getBugPattern().getCategory().equals("NOISE") || bug.isDead() || BugRanker.findRank(bug) > 12; } private static final String PENDING = "-- pending --"; private static final String NONE = "none"; class DatabaseSyncTask implements Runnable { int handled; Connection c; public void establishConnection() throws SQLException { if (c != null) return; c = getConnection(); } public void closeConnection() throws SQLException { if (c == null) return; c.close(); c = null; } public void run() { try { while (!shutdown) { Update u = queue.poll(10, TimeUnit.SECONDS); if (u == null) { closeConnection(); continue; } establishConnection(); u.execute(this); if ((handled++) % 100 == 0 || queue.isEmpty()) { updatedStatus(); } } } catch (DatabaseSyncShutdownException e) { assert true; } catch (RuntimeException e) { displayMessage("Runtime exception; database connection shutdown", e); } catch (SQLException e) { displayMessage("SQL exception; database connection shutdown", e); } catch (InterruptedException e) { assert true; } try { closeConnection(); } catch (SQLException e) { } } public void newEvaluation(BugData data, BugDesignation bd) { if (!data.inDatabase) return; try { data.designations.add(bd); if (bd.getUser() == null) bd.setUser(findbugsUser); if (bd.getAnnotationText() == null) bd.setAnnotationText(""); PreparedStatement insertEvaluation = c.prepareStatement("INSERT INTO findbugs_evaluation (issueId, who, designation, comment, time) VALUES (?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); Timestamp date = new Timestamp(bd.getTimestamp()); int col = 1; insertEvaluation.setInt(col++, data.id); insertEvaluation.setString(col++, bd.getUser()); insertEvaluation.setString(col++, bd.getDesignationKey()); insertEvaluation.setString(col++, bd.getAnnotationText()); insertEvaluation.setTimestamp(col++, date); insertEvaluation.executeUpdate(); ResultSet rs = insertEvaluation.getGeneratedKeys(); if (rs.next()) { int id = rs.getInt(1); bugDesignationId.put(bd, id); } rs.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } lastUpdate = new Date(); updatesSentToDatabase++; } public void newBug(BugInstance b, long timestamp) { try { BugData bug = getBugData(b.getInstanceHash()); if (bug.inDatabase) return; PreparedStatement insertBugData = c.prepareStatement("INSERT INTO findbugs_issue (firstSeen, lastSeen, hash, bugPattern, priority, primaryClass) VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); Timestamp date = new Timestamp(timestamp); int col = 1; insertBugData.setTimestamp(col++, date); insertBugData.setTimestamp(col++, date); insertBugData.setString(col++, bug.instanceHash); insertBugData.setString(col++, b.getBugPattern().getType()); insertBugData.setInt(col++, b.getPriority()); insertBugData.setString(col++, b.getPrimaryClass().getClassName()); insertBugData.executeUpdate(); ResultSet rs = insertBugData.getGeneratedKeys(); if (rs.next()) { bug.id = rs.getInt(1); bug.inDatabase = true; } rs.close(); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } public void storeFirstSeen(BugData bug) { try { PreparedStatement insertBugData = c.prepareStatement("UPDATE findbugs_issue SET firstSeen = ? WHERE id = ?"); Timestamp date = new Timestamp(bug.firstSeen); int col = 1; insertBugData.setTimestamp(col++, date); insertBugData.setInt(col++, bug.id); insertBugData.executeUpdate(); insertBugData.close(); } catch (Exception e) { displayMessage("Problems looking up user annotations", e); } } /** * @param bd */ public void fileBug(BugData bug) { try { PreparedStatement insert = c .prepareStatement("INSERT INTO findbugs_bugreport (hash, bugReportId, whoFiled, whenFiled)" + " VALUES (?, ?, ?, ?)"); Timestamp date = new Timestamp(bug.bugFiled); int col = 1; insert.setString(col++, bug.instanceHash); insert.setString(col++, PENDING); insert.setString(col++, bug.filedBy); insert.setTimestamp(col++, date); int count = insert.executeUpdate(); insert.close(); if (count == 0) { PreparedStatement updateBug = c.prepareStatement("UPDATE findbugs_bugreport SET whoFiled = ? and whenFiled = ? WHERE hash = ? and bugReportId = ?"); col = 1; updateBug.setString(col++, bug.filedBy); updateBug.setTimestamp(col++, date); updateBug.setString(col++, bug.instanceHash); updateBug.setString(col++, PENDING); count = updateBug.executeUpdate(); updateBug.close(); } } catch (Exception e) { displayMessage("Problem filing bug", e); } lastUpdate = new Date(); updatesSentToDatabase++; } } static interface Update { void execute(DatabaseSyncTask t) throws SQLException; } static class ShutdownTask implements Update { public void execute(DatabaseSyncTask t) { throw new DatabaseSyncShutdownException(); } } static class DatabaseSyncShutdownException extends RuntimeException { } boolean bugAlreadyFiled(BugInstance b) { BugData bd = getBugData(b.getInstanceHash()); if (bd == null || !bd.inDatabase) throw new IllegalArgumentException(); return bd.bugLink != null && !bd.bugLink.equals(NONE) && !bd.bugLink.equals(PENDING); } class FileBug implements Update { public FileBug(BugInstance bug) { this.bd = getBugData(bug.getInstanceHash()); if (bd == null || !bd.inDatabase) throw new IllegalArgumentException(); bd.bugFiled = System.currentTimeMillis(); bd.bugLink = PENDING; bd.filedBy = findbugsUser; } final BugData bd; public void execute(DatabaseSyncTask t) throws SQLException { t.fileBug(bd); } } class StoreNewBug implements Update { public StoreNewBug(BugInstance bug) { this.bug = bug; } final BugInstance bug; public void execute(DatabaseSyncTask t) throws SQLException { BugData data = getBugData(bug.getInstanceHash()); if (data.inDatabase) return; long timestamp = bugCollection.getAppVersionFromSequenceNumber(bug.getFirstVersion()).getTimestamp(); t.newBug(bug, timestamp); data.inDatabase = true; } } static class StoreUserAnnotation implements Update { public StoreUserAnnotation(BugData data, BugDesignation designation) { super(); this.data = data; this.designation = designation; } public void execute(DatabaseSyncTask t) throws SQLException { t.newEvaluation(data, new BugDesignation(designation)); } final BugData data; final BugDesignation designation; } private void displayMessage(String msg, Exception e) { AnalysisContext.logError(msg, e); if (!GraphicsEnvironment.isHeadless() && bugCollection.getProject().isGuiAvaliable()) { StringWriter stackTraceWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stackTraceWriter); e.printStackTrace(printWriter); bugCollection.getProject().getGuiCallback().showMessageDialog( String.format("%s - %s\n%s", msg, e.getMessage(), stackTraceWriter.toString())); } else { System.err.println(msg); e.printStackTrace(System.err); } } private void displayMessage(String msg) { if (!GraphicsEnvironment.isHeadless() && bugCollection.getProject().isGuiAvaliable()) { bugCollection.getProject().getGuiCallback().showMessageDialog(msg); } else { System.err.println(msg); } } public String getUser() { return findbugsUser; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getFirstSeen(edu.umd.cs.findbugs.BugInstance) */ public long getFirstSeen(BugInstance b) { return getBugData(b).firstSeen; } public boolean overallClassificationIsNotAProblem(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return false; int isAProblem = 0; int notAProblem = 0; for(BugDesignation d : bd.getUniqueDesignations() ) switch(UserDesignation.valueOf(d.getDesignationKey())) { case I_WILL_FIX: case MUST_FIX: case SHOULD_FIX: isAProblem++; break; case BAD_ANALYSIS: case NOT_A_BUG: case MOSTLY_HARMLESS: case OBSOLETE_CODE: notAProblem++; break; } return notAProblem > isAProblem; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getUser() */ public UserDesignation getUserDesignation(BugInstance b) { BugDesignation bd = getBugData(b).getPrimaryDesignation(); if (bd == null) return UserDesignation.UNCLASSIFIED; return UserDesignation.valueOf(bd.getDesignationKey()); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getUserEvaluation(edu.umd.cs.findbugs.BugInstance) */ public String getUserEvaluation(BugInstance b) { BugDesignation bd = getBugData(b).getPrimaryDesignation(); if (bd == null) return ""; return bd.getAnnotationText(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getUserTimestamp(edu.umd.cs.findbugs.BugInstance) */ public long getUserTimestamp(BugInstance b) { BugDesignation bd = getBugData(b).getPrimaryDesignation(); if (bd == null) return Long.MAX_VALUE; return bd.getTimestamp(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#setUserDesignation(edu.umd.cs.findbugs.BugInstance, edu.umd.cs.findbugs.cloud.UserDesignation, long) */ public void setUserDesignation(BugInstance b, UserDesignation u, long timestamp) { BugData data = getBugData(b); BugDesignation bd = data.getUserDesignation(); if (bd == null) { if (u == UserDesignation.UNCLASSIFIED) return; bd = data.getNonnullUserDesignation(); } bd.setDesignationKey(u.name()); if (bd.isDirty()) { bd.setTimestamp(timestamp); storeUserAnnotation(data, bd); } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#setUserEvaluation(edu.umd.cs.findbugs.BugInstance, java.lang.String, long) */ public void setUserEvaluation(BugInstance b, String e, long timestamp) { BugData data = getBugData(b); BugDesignation bd = data.getUserDesignation(); if (bd == null) { if (e.length() == 0) return; bd = data.getNonnullUserDesignation(); } bd.setAnnotationText(e); if (bd.isDirty()) { bd.setTimestamp(timestamp); storeUserAnnotation(data, bd); } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#setUserTimestamp(edu.umd.cs.findbugs.BugInstance, long) */ public void setUserTimestamp(BugInstance b, long timestamp) { BugData data = getBugData(b); BugDesignation bd = data.getNonnullUserDesignation(); bd.setTimestamp(timestamp); storeUserAnnotation(data, bd); } static final String BUG_NOTE = SystemProperties.getProperty("findbugs.bugnote"); String getBugReportHead(BugInstance b) { StringWriter stringWriter = new StringWriter(); PrintWriter out = new PrintWriter(stringWriter); out.println("Bug report generated from FindBugs"); out.println(b.getMessageWithoutPrefix()); out.println(); ClassAnnotation primaryClass = b.getPrimaryClass(); for (BugAnnotation a : b.getAnnotations()) { if (a == primaryClass) out.println(a); else out.println(" " + a.toString(primaryClass)); } URL link = getSourceLink(b); if (link != null) { out.println(); out.println(sourceFileLinkToolTip + ": " + link); out.println(); } if (BUG_NOTE != null) { out.println(BUG_NOTE); if (POSTMORTEM_NOTE != null && BugRanker.findRank(b) <= POSTMORTEM_RANK && !overallClassificationIsNotAProblem(b)) out.println(POSTMORTEM_NOTE); out.println(); } Collection<String> projects = projectMapping.getProjects(primaryClass.getClassName()); if (projects != null && !projects.isEmpty()) { String projectList = projects.toString(); projectList = projectList.substring(1, projectList.length() - 1); out.println("Possibly part of: " + projectList); out.println(); } out.close(); return stringWriter.toString(); } String getBugPatternExplanation(BugInstance b) { String detailPlainText = b.getBugPattern().getDetailPlainText(); return "Bug pattern explanation:\n" + detailPlainText + "\n\n"; } String getBugPatternExplanationLink(BugInstance b) { return "Bug pattern explanation: http://findbugs.sourceforge.net/bugDescriptions.html#" + b.getBugPattern().getType() + "\n"; } private String getLineTerminatedUserEvaluation(BugInstance b) { String result = getUserEvaluation(b); if (result.length() == 0) return ""; return result.trim()+"\n"; } String getBugReport(BugInstance b) { return getBugReportHead(b) + getBugReportSourceCode(b) + getLineTerminatedUserEvaluation(b) + getBugPatternExplanation(b) + getBugReportTail(b); } String getBugReportShorter(BugInstance b) { return getBugReportHead(b) + getBugReportSourceCode(b) + getLineTerminatedUserEvaluation(b) + getBugPatternExplanationLink(b) + getBugReportTail(b); } String getBugReportAbridged(BugInstance b) { return getBugReportHead(b) + getBugPatternExplanationLink(b) + getBugReportTail(b); } String getBugReportSourceCode(BugInstance b) { if (!MainFrame.isAvailable()) return ""; StringWriter stringWriter = new StringWriter(); PrintWriter out = new PrintWriter(stringWriter); ClassAnnotation primaryClass = b.getPrimaryClass(); int firstLine = Integer.MAX_VALUE; int lastLine = Integer.MIN_VALUE; for (BugAnnotation a : b.getAnnotations()) if (a instanceof SourceLineAnnotation) { SourceLineAnnotation s = (SourceLineAnnotation) a; if (s.getClassName().equals(primaryClass.getClassName()) && s.getStartLine() > 0) { firstLine = Math.min(firstLine, s.getStartLine()); lastLine = Math.max(lastLine, s.getEndLine()); } } SourceLineAnnotation primarySource = primaryClass.getSourceLines(); if (primarySource.isSourceFileKnown() && firstLine >= 1 && firstLine <= lastLine && lastLine - firstLine < 50) { try { SourceFile sourceFile = MainFrame.getInstance().getSourceFinder().findSourceFile(primarySource); BufferedReader in = new BufferedReader(new InputStreamReader(sourceFile.getInputStream())); int lineNumber = 1; String commonWhiteSpace = null; List<SourceLine> source = new ArrayList<SourceLine>(); while (lineNumber <= lastLine + 4) { String txt = in.readLine(); if (txt == null) break; if (lineNumber >= firstLine - 4) { String trimmed = txt.trim(); if (trimmed.length() == 0) { if (lineNumber > lastLine) break; txt = trimmed; } source.add(new SourceLine(lineNumber, txt)); commonWhiteSpace = commonLeadingWhitespace(commonWhiteSpace, txt); } lineNumber++; } in.close(); out.println("\nRelevant source code:"); for(SourceLine s : source) { if (s.text.length() == 0) out.printf("%5d: \n", s.line); else out.printf("%5d: %s\n", s.line, s.text.substring(commonWhiteSpace.length())); } out.println(); } catch (IOException e) { assert true; } out.close(); String result = stringWriter.toString(); return result; } return ""; } String commonLeadingWhitespace(String soFar, String txt) { if (txt.length() == 0) return soFar; if (soFar == null) return txt; soFar = Util.commonPrefix(soFar, txt); for(int i = 0; i < soFar.length(); i++) { if (!Character.isWhitespace(soFar.charAt(i))) return soFar.substring(0,i); } return soFar; } static class SourceLine { public SourceLine(int line, String text) { this.line = line; this.text = text; } final int line; final String text; } String getBugReportTail(BugInstance b) { return "\nFindBugs issue identifier (do not modify or remove): " + b.getInstanceHash(); } static String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { assert false; return "No utf-8 encoding"; } } public Set<String> getReviewers(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return Collections.emptySet(); return bd.getReviewers(); } public boolean isClaimed(BugInstance b) { BugData bd = getBugData(b); if (bd == null) return false; return bd.isClaimed(); } static final int MAX_URL_LENGTH = 1999; private static final String HAS_FILED_BUGS = "has_filed_bugs"; private static final String HAS_CLASSIFIED_ISSUES = "has_classified_issues"; private static boolean firstTimeDoing(String activity) { Preferences prefs = Preferences.userNodeForPackage(DBCloud.class); if (!prefs.getBoolean(activity, false)) { prefs.putBoolean(activity, true); return true; } return false; } private static void alreadyDone(String activity) { Preferences prefs = Preferences.userNodeForPackage(DBCloud.class); prefs.putBoolean(activity, true); } private boolean firstBugRequest = true; static final String POSTMORTEM_NOTE = SystemProperties.getProperty("findbugs.postmortem.note"); static final int POSTMORTEM_RANK = SystemProperties.getInteger("findbugs.postmortem.rank", 4); static final String BUG_LINK_FORMAT = SystemProperties.getProperty("findbugs.filebug.link"); @Override @CheckForNull public URL getBugLink(BugInstance b) { try { BugData bd = getBugData(b); String bugNumber = bd.bugLink; BugFilingStatus status = getBugLinkStatus(b); switch (status) { case VIEW_BUG: { String viewLinkPattern = SystemProperties.getProperty("findbugs.viewbug.link"); if (viewLinkPattern == null) return null; firstBugRequest = false; String u = String.format(viewLinkPattern, bugNumber); return new URL(u); } case FILE_BUG: { URL u = getBugFilingLink(b); if (u != null && firstTimeDoing(HAS_FILED_BUGS)) bugCollection.getProject().getGuiCallback().showMessageDialog( "This looks like the first time you've filed a bug from this machine. Please:\n" + " * Please check the component the issue is assigned to; we sometimes get it wrong.\n" + " * Try to figure out the right person to assign it to.\n" + " * Provide the information needed to understand the issue.\n" + "Note that classifying an issue is distinct from (and lighter weight than) filing a bug."); } case FILE_AGAIN: alreadyDone(HAS_FILED_BUGS); return getBugFilingLink(b); } } catch (Exception e) { } return null; } /** * @param b * @return * @throws MalformedURLException */ private URL getBugFilingLink(BugInstance b) throws MalformedURLException { { if (BUG_LINK_FORMAT == null) return null; String report = getBugReport(b); String component = getBugComponent(b.getPrimaryClass().getClassName().replace('.', '/')); String summary = b.getMessageWithoutPrefix() + " in " + b.getPrimaryClass().getSourceFileName(); int maxURLLength = MAX_URL_LENGTH; if (firstBugRequest) maxURLLength = maxURLLength *2/3; firstBugRequest = false; String u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); if (u.length() > MAX_URL_LENGTH) { report = getBugReportShorter(b); u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); if (u.length() > MAX_URL_LENGTH) { report = getBugReportAbridged(b); u = String.format(BUG_LINK_FORMAT, component, urlEncode(summary), urlEncode(report)); String supplemental = "[Can't squeeze this information into the URL used to prepopulate the bug entry\n" +" please cut and paste into the bug report as appropriate]\n\n" + getBugReportSourceCode(b) + getLineTerminatedUserEvaluation(b) + getBugPatternExplanation(b); bugCollection.getProject().getGuiCallback().displayNonmodelMessage( "Cut and paste as needed into bug entry", supplemental); } } return new URL(u); } } @Override public boolean supportsCloudReports() { return true; } @Override public boolean supportsBugLinks() { return BUG_LINK_FORMAT != null; } @Override public String getCloudReport(BugInstance b) { SimpleDateFormat format = new SimpleDateFormat("MM/dd"); StringBuilder builder = new StringBuilder(); BugData bd = getBugData(b); long firstSeen = bd.firstSeen; if (firstSeen < Long.MAX_VALUE) { builder.append(String.format("First seen %s\n", format.format(new Timestamp(firstSeen)))); } BugDesignation primaryDesignation = bd.getPrimaryDesignation(); I18N i18n = I18N.instance(); boolean canSeeCommentsByOthers = bd.canSeeCommentsByOthers(); if (canSeeCommentsByOthers) { if (bd.bugStatus != null) { builder.append(bd.bugComponentName); if (bd.bugAssignedTo == null) builder.append("\nBug status is " + bd.bugStatus); else builder.append("\nBug assigned to " + bd.bugAssignedTo + ", status is " + bd.bugStatus); builder.append("\n\n"); } } for(BugDesignation d : bd.getUniqueDesignations()) if (findbugsUser.equals(d.getUser())|| canSeeCommentsByOthers ) { builder.append(String.format("%s @ %s: %s\n", d.getUser(), format.format(new Timestamp(d.getTimestamp())), i18n.getUserDesignation(d.getDesignationKey()))); if (d.getAnnotationText().length() > 0) { builder.append(d.getAnnotationText()); builder.append("\n\n"); } } return builder.toString(); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#storeUserAnnotation(edu.umd.cs.findbugs.BugInstance) */ public void storeUserAnnotation(BugInstance bugInstance) { storeUserAnnotation(getBugData(bugInstance), bugInstance.getNonnullUserDesignation()); } @Override public boolean supportsSourceLinks() { return sourceFileLinkPattern != null; } @Override public @CheckForNull URL getSourceLink(BugInstance b) { if (sourceFileLinkPattern == null) return null; SourceLineAnnotation src = b.getPrimarySourceLineAnnotation(); String fileName = src.getSourcePath(); int startLine = src.getStartLine(); java.util.regex.Matcher m = sourceFileLinkPattern.matcher(fileName); boolean isMatch = m.matches(); if (isMatch) try { URL link; if (startLine > 0) link = new URL(String.format(sourceFileLinkFormatWithLine, m.group(1), startLine, startLine - 10)); else link = new URL(String.format(sourceFileLinkFormat, m.group(1))); return link; } catch (MalformedURLException e) { AnalysisContext.logError("Error generating source link for " + src, e); } return null; } @Override public String getSourceLinkToolTip(BugInstance b) { return sourceFileLinkToolTip; } @Override public BugFilingStatus getBugLinkStatus(BugInstance b) { BugData bd = getBugData(b); String link = bd.bugLink; if (link == null || link.length() == 0 || link.equals(NONE)) return BugFilingStatus.FILE_BUG; if (link.equals(PENDING)) { if (findbugsUser.equals(bd.filedBy)) return BugFilingStatus.FILE_AGAIN; else if (System.currentTimeMillis() - bd.bugFiled > 2*60*60*1000L) return BugFilingStatus.FILE_BUG; else return BugFilingStatus.BUG_PENDING; } try { Integer.parseInt(link); return BugFilingStatus.VIEW_BUG; } catch (RuntimeException e) { assert true; } return BugFilingStatus.NA; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#bugFiled(edu.umd.cs.findbugs.BugInstance, java.lang.Object) */ public void bugFiled(BugInstance b, Object bugLink) { if (bugAlreadyFiled(b)) { BugData bd = getBugData(b.getInstanceHash()); return; } queue.add(new FileBug(b)); updatedStatus(); } String errorMsg; long errorTime = 0; void setErrorMsg(String msg) { errorMsg = msg; errorTime = System.currentTimeMillis(); updatedStatus(); } void clearErrorMsg() { errorMsg = null; updatedStatus(); } @Override public String getStatusMsg() { if (errorMsg != null) { if (errorTime + 2 * 60 * 1000 > System.currentTimeMillis()) { errorMsg = null; } else return errorMsg +"; " + getStatusMsg0(); } return getStatusMsg0(); } public String getStatusMsg0() { SimpleDateFormat format = new SimpleDateFormat("h:mm a"); int numToSync = queue.size(); int handled = this.issuesBulkHandled + runner.handled; if (numToSync > 0) return String.format("%d remain to be synchronized", numToSync); else if (updatesSentToDatabase == 0) return String.format("%d issues synchronized with database", idMap.size()); else return String.format("%d classifications/bug filings sent to db, last updated at %s", updatesSentToDatabase, format.format(lastUpdate)); } @Override public void printCloudSummary(Iterable<BugInstance> bugs, PrintWriter w) { Multiset<String> evaluations = new Multiset<String>(); Multiset<String> designations = new Multiset<String>(); Multiset<String> bugStatus = new Multiset<String>(); int issuesWithThisManyReviews [] = new int[100]; I18N i18n = I18N.instance(); Set<String> hashCodes = new HashSet<String>(); for(BugInstance b : bugs) { hashCodes.add(b.getInstanceHash()); } int count = 0; int notInCloud = 0; for(String hash : hashCodes) { BugData bd = instanceMap.get(hash); if (bd == null) { notInCloud++; continue; } count++; HashSet<String> reviewers = new HashSet<String>(); if (bd.bugStatus != null) bugStatus.add(bd.bugStatus); for(BugDesignation d : bd.designations) if (reviewers.add(d.getUser())) { evaluations.add(d.getUser()); designations.add(i18n.getUserDesignation(d.getDesignationKey())); } int numReviews = Math.min( reviewers.size(), issuesWithThisManyReviews.length -1); issuesWithThisManyReviews[numReviews]++; } if (count == 0) { w.printf("None of the %d issues in the current view are in the cloud\n\n", notInCloud); return; } if (notInCloud == 0) { w.printf("Summary for %d issues that are in the current view\n\n", count); }else { w.printf("Summary for %d issues that are in the current view and cloud (%d not in cloud)\n\n", count, notInCloud); } w.println("People who have performed the most reviews"); printLeaderBoard(w, evaluations, 5, findbugsUser, true, "reviewer"); w.println("\nDistribution of evaluations"); printLeaderBoard(w, designations, 100, " --- ", false, "designation"); w.println("\nDistribution of bug status"); printLeaderBoard(w, bugStatus, 100, " --- ", false, "status of filed bug"); w.println("\nDistribution of number of reviews"); for(int i = 0; i < issuesWithThisManyReviews.length; i++) if (issuesWithThisManyReviews[i] > 0) { w.printf("%4d with %3d review", issuesWithThisManyReviews[i], i); if (i != 1) w.print("s"); w.println(); } } /** * @param w * @param evaluations * @param listRank TODO * @param title TODO */ private void printLeaderBoard(PrintWriter w, Multiset<String> evaluations, int maxRows, String alwaysPrint, boolean listRank, String title) { int row = 1; int position = 0; int previousScore = -1; boolean foundAlwaysPrint = false; if (listRank) w.printf("%3s %3s %s\n", "rnk", "num", title); else w.printf("%3s %s\n", "num", title); for(Map.Entry<String,Integer> e : evaluations.entriesInDecreasingFrequency()) { int num = e.getValue(); if (num != previousScore) { position = row; previousScore = num; } String key = e.getKey(); boolean shouldAlwaysPrint = key.equals(alwaysPrint); if (row <= maxRows || shouldAlwaysPrint) { if (listRank) w.printf("%3d %3d %s\n", position, num, key); else w.printf("%3d %s\n", num, key); } if (shouldAlwaysPrint) foundAlwaysPrint = true; row++; if (foundAlwaysPrint && row >= maxRows) { w.printf("Total of %d %ss\n", evaluations.numKeys(), title); break; } } } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getIWillFix(edu.umd.cs.findbugs.BugInstance) */ @Override public boolean getIWillFix(BugInstance b) { if (super.getIWillFix(b)) return true; BugData bd = getBugData(b); return bd != null && findbugsUser.equals(bd.bugAssignedTo); } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#supportsCloudSummaries() */ public boolean supportsCloudSummaries() { return true; } }
package edu.umd.cs.findbugs.cloud; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.TreeMap; import java.util.TreeSet; import edu.umd.cs.findbugs.PluginLoader; import edu.umd.cs.findbugs.util.MergeMap; import edu.umd.cs.findbugs.util.Multiset; /** * @author pwilliam */ public class DBStats { static Timestamp bucketByHour(Timestamp t) { Timestamp result = new Timestamp(t.getTime()); result.setSeconds(0); result.setMinutes(0); result.setNanos(0); return result; } static class TimeSeries<K, V extends Comparable<? super V>> implements Comparable<TimeSeries<K,V>>{ final K k; final int keyHash; final V v; public TimeSeries(K k, V v) { this.k = k; this.keyHash = System.identityHashCode(k); this.v = v; } public String toString() { return v + " " + k; } public int compareTo(TimeSeries<K, V> o) { if (o == this) return 0; int result = v.compareTo(o.v); if (result != 0) return result; if (keyHash < o.keyHash) return -1; return 1; } } public static void main(String args[]) throws Exception { Map<String,String> officeLocation = new HashMap<String,String>(); URL u = PluginLoader.getCoreResource("offices.properties"); if (u != null) { BufferedReader in = new BufferedReader(new InputStreamReader(u.openStream())); while(true) { String s = in.readLine(); if (s == null) break; if (s.trim().length() == 0) continue; int x = s.indexOf(':'); if (x == -1) continue; String office = s.substring(0,x); for(String person : s.substring(x+1).split(" ")) officeLocation.put(person, office); } in.close(); } DBCloud cloud = new DBCloud(null); cloud.initialize(); Connection c = cloud.getConnection(); PreparedStatement ps = c.prepareStatement("SELECT who, entryPoint, dataSource, fbVersion, jvmLoadTime, findbugsLoadTime, analysisLoadTime, initialSyncTime, numIssues, startTime, commonPrefix" + " FROM findbugs_invocation"); MergeMap.MinMap <String, Timestamp> firstUse = new MergeMap.MinMap<String,Timestamp>(); MergeMap.MinMap <String, Timestamp> reviewers = new MergeMap.MinMap<String,Timestamp>(); MergeMap.MinMap <String, Timestamp> uniqueReviews = new MergeMap.MinMap<String,Timestamp>(); HashSet<String> participants = new HashSet<String>(); Multiset<String> participantsPerOffice = new Multiset<String>(); ResultSet rs = ps.executeQuery(); while (rs.next()) { int col = 1; String who = rs.getString(col++); String entryPoint = rs.getString(col++); String dataSource = rs.getString(col++); String fbVersion = rs.getString(col++); int jvmLoad = rs.getInt(col++); int fbLoad = rs.getInt(col++); int analysisLoad = rs.getInt(col++); int dbSync = rs.getInt(col++); int numIssues = rs.getInt(col++); Timestamp when = rs.getTimestamp(col++); firstUse.put(who, when); if (participants.add(who)) { String office = officeLocation.get(who); if (office == null) office = "unknown"; participantsPerOffice.add(office); } } rs.close(); ps.close(); ps = c.prepareStatement("SELECT id, issueId, who, designation, comment, time FROM findbugs_evaluation ORDER BY time DESC"); rs = ps.executeQuery(); Multiset<String> issueReviewedBy = new Multiset<String>(); Multiset<String> allIssues = new Multiset<String>(); Multiset<String> scariestIssues = new Multiset<String>(); Multiset<String> scaryIssues = new Multiset<String>(); Multiset<String> troublingIssues = new Multiset<String>(); HashSet<String> issueReviews = new HashSet<String>(); while (rs.next()) { int col = 1; int id = rs.getInt(col++); int issueId = rs.getInt(col++); String who = rs.getString(col++); String designation = rs.getString(col++); String comment = rs.getString(col++); Timestamp when = rs.getTimestamp(col++); reviewers.put(who, when); String issueReviewer = who+"-" + issueId; if (issueReviews.add(issueReviewer)) { uniqueReviews.put(issueReviewer, when); allIssues.add(designation); issueReviewedBy.add(who); } } rs.close(); c.close(); printTimeSeries("Unique users", firstUse); printTimeSeries("Unique reviewers", reviewers); printTimeSeries("Total reviews", uniqueReviews); System.out.println("Designations"); for(Map.Entry<String, Integer> e : allIssues.entrySet()) System.out.printf("%s,%d\n", e.getKey(), e.getValue()); System.out.println(); System.out.println("Participants by office"); for(Map.Entry<String, Integer> e : participantsPerOffice.entrySet()) System.out.printf("%s,%d\n", e.getKey(), e.getValue()); System.out.println(); PrintWriter w = new PrintWriter(System.out); DBCloud.printLeaderBoard(w, issueReviewedBy, 6, "", true, "num issues reviewed"); w.flush(); } private static void printTimeSeries(String title, MergeMap.MinMap<String, Timestamp> firstUse) { System.out.println(title); TreeSet<TimeSeries<String, Timestamp>> series = new TreeSet<TimeSeries<String, Timestamp>>(); for(Map.Entry<String, Timestamp> e : firstUse.entrySet()) { series.add(new TimeSeries<String,Timestamp>(e.getKey(), e.getValue())); } Multiset<Timestamp> counter = new Multiset<Timestamp>(new TreeMap<Timestamp, Integer>()); for(TimeSeries<String, Timestamp> t : series) { counter.add(bucketByHour(t.v)); } int total = 0; SimpleDateFormat format = new SimpleDateFormat("h a EEE"); for(Map.Entry<Timestamp, Integer> e : counter.entrySet()) { total += e.getValue(); System.out.printf("%4d, %s\n", total, format.format(e.getKey())); } System.out.println(); } }
package se.sics.cooja.contikimote; import java.awt.*; import java.awt.event.*; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.util.regex.*; import javax.swing.*; import javax.swing.event.*; import org.apache.log4j.Logger; import se.sics.cooja.*; import se.sics.cooja.dialogs.MessageList; import se.sics.cooja.dialogs.ProjectDirectoriesDialog; /** * A dialog for configuring Contiki mote types and compiling Contiki mote type * libraries. Allows user to change mote type specific data such as * descriptions, which processes should be started at mote initialization and * which interfaces the type should support. * * The dialog takes a Contiki mote type as argument and pre-selects the values * already set in that mote type before showing the dialog. Any changes made to * the settings are written to the mote type if the compilation is successful * and the user presses OK. * * This dialog uses external tools to scan for sources and compile libraries. * * @author Fredrik Osterlind */ public class ContikiMoteTypeDialog extends JDialog { private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(ContikiMoteTypeDialog.class); private MoteTypeEventHandler myEventHandler = new MoteTypeEventHandler(); private Thread compilationThread; /** * Suggested mote type identifier prefix */ public static final String ID_PREFIX = "mtype"; private final static int LABEL_WIDTH = 170; private final static int LABEL_HEIGHT = 15; private ContikiMoteType myMoteType = null; private JTextField textID, textOutputFiles, textDescription, textContikiDir, textCoreDir, textProjectDirs; private JButton createButton, testButton, rescanButton; private JCheckBox symbolsCheckBox; private JPanel processPanel; // Holds process checkboxes private JPanel sensorPanel; // Holds sensor checkboxes private JPanel moteInterfacePanel; // Holds mote interface checkboxes private JPanel coreInterfacePanel; // Holds core interface checkboxes private JPanel entireSensorPane; // Holds entire sensor pane (can be hidden) private JPanel entireCoreInterfacePane; // Holds entire core interface pane // (can be hidden) private boolean settingsOK = false; // Do all settings seem correct? private boolean compilationSucceded = false; // Did compilation succeed? private boolean libraryCreatedOK = false; // Was a library created? private ProjectConfig newMoteTypeConfig = null; // Mote type project config private Vector<File> moteTypeProjectDirs = new Vector<File>(); // Mote type project directories private Vector<File> compilationFiles = null; private Vector<MoteType> allOtherTypes = null; // Used to check for // conflicting parameters private GUI myGUI = null; private ContikiMoteTypeDialog myDialog; /** * Shows a dialog for configuring a Contiki mote type and compiling the shared * library it uses. * * @param parentFrame * Parent frame for dialog * @param simulation * Simulation holding (or that will hold) mote type * @param moteTypeToConfigure * Mote type to configure * @return True if compilation succeded and library is ready to be loaded */ public static boolean showDialog(Frame parentFrame, Simulation simulation, ContikiMoteType moteTypeToConfigure) { final ContikiMoteTypeDialog myDialog = new ContikiMoteTypeDialog( parentFrame); myDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); myDialog.myMoteType = moteTypeToConfigure; myDialog.myGUI = simulation.getGUI(); myDialog.allOtherTypes = simulation.getMoteTypes(); // Set identifier of mote type if (moteTypeToConfigure.getIdentifier() != null) { // Identifier already preset, assuming recompilation of mote type library // Use preset identifier (read-only) myDialog.textID.setText(moteTypeToConfigure.getIdentifier()); myDialog.textID.setEditable(false); myDialog.textID.setEnabled(false); // Change title to indicate this is a recompilation myDialog.setTitle("Recompile Mote Type"); } else { // Suggest new identifier int counter = 0; String testIdentifier = ""; boolean identifierOK = false; while (!identifierOK) { counter++; testIdentifier = ID_PREFIX + counter; identifierOK = true; // Check if identifier is already used by some other type for (MoteType existingMoteType : myDialog.allOtherTypes) { if (existingMoteType != myDialog.myMoteType && existingMoteType.getIdentifier().equals(testIdentifier)) { identifierOK = false; break; } } // Check if library file with given identifier has already been loaded if (identifierOK && CoreComm.hasLibraryFileBeenLoaded(new File( ContikiMoteType.tempOutputDirectory, testIdentifier + ContikiMoteType.librarySuffix))) { identifierOK = false; } } myDialog.textID.setText(testIdentifier); } // Set preset description of mote type if (moteTypeToConfigure.getDescription() != null) { myDialog.textDescription.setText(moteTypeToConfigure.getDescription()); } else { // Suggest unique description int counter = 0; String testDescription = ""; boolean descriptionOK = false; while (!descriptionOK) { counter++; testDescription = "Contiki Mote #" + counter; descriptionOK = true; // Check if identifier is already used by some other type for (MoteType existingMoteType : myDialog.allOtherTypes) { if (existingMoteType != myDialog.myMoteType && existingMoteType.getDescription().equals(testDescription)) { descriptionOK = false; break; } } } myDialog.textDescription.setText(testDescription); } // Set preset Contiki base directory of mote type if (moteTypeToConfigure.getContikiBaseDir() != null) { myDialog.textContikiDir.setText(moteTypeToConfigure.getContikiBaseDir()); } // Set preset Contiki core directory of mote type if (moteTypeToConfigure.getContikiCoreDir() != null) { myDialog.textCoreDir.setText(moteTypeToConfigure.getContikiCoreDir()); } // Set preset project directories of mote type if (moteTypeToConfigure.getProjectDirs() != null) { myDialog.moteTypeProjectDirs = moteTypeToConfigure .getProjectDirs(); String projectText = null; for (File projectDir : myDialog.moteTypeProjectDirs) { if (projectText == null) projectText = "'" + projectDir.getPath() + "'"; else projectText += ", '" + projectDir.getPath() + "'"; } myDialog.textProjectDirs.setText(projectText); } // Set preset "use symbols" if (moteTypeToConfigure.hasSystemSymbols()) { myDialog.symbolsCheckBox.setSelected(true); } // Scan directories for processes, sensors and core interfaces // TODO Really do this without starting a separate thread? myDialog.updateVisualFields(); myDialog.rescanDirectories(); // Select preset processes of mote type if (moteTypeToConfigure.getProcesses() != null) { for (String presetProcess : moteTypeToConfigure.getProcesses()) { // Try to find process in current list boolean foundAndSelectedProcess = false; for (Component processCheckBox : myDialog.processPanel.getComponents()) { if (presetProcess.equals(((JCheckBox) processCheckBox).getText())) { ((JCheckBox) processCheckBox).setSelected(true); foundAndSelectedProcess = true; break; } } // Warn if not found if (!foundAndSelectedProcess) { // Let user choose whether to add process Object[] options = { "Add", "Cancel" }; String question = "The configuration file contains a process " + "(" + presetProcess + ") not found during scan." + "\nDo you want to include this anyway?"; String title = "Add process?"; int answer = JOptionPane.showOptionDialog(myDialog, question, title, JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (answer == JOptionPane.YES_OPTION) { // Create new check box JCheckBox newCheckBox = new JCheckBox(presetProcess, true); myDialog.processPanel.add(newCheckBox); } } } } // Select preset sensors if (moteTypeToConfigure.getSensors() != null) { // Deselect all sensors already automatically selected for (Component coreInterfaceCheckBox : myDialog.sensorPanel .getComponents()) { ((JCheckBox) coreInterfaceCheckBox).setSelected(false); } for (String presetSensor : moteTypeToConfigure.getSensors()) { // Try to find sensor in current list boolean foundAndSelectedSensor = false; for (Component sensorCheckBox : myDialog.sensorPanel.getComponents()) { if (presetSensor.equals(((JCheckBox) sensorCheckBox).getText())) { ((JCheckBox) sensorCheckBox).setSelected(true); foundAndSelectedSensor = true; break; } } // Warn if not found if (!foundAndSelectedSensor) { // Let user choose whether to add sensor Object[] options = { "Add", "Cancel" }; String question = "The configuration file contains a sensor " + "(" + presetSensor + ") not found during scan." + "\nDo you want to include this anyway?"; String title = "Add sensor?"; int answer = JOptionPane.showOptionDialog(myDialog, question, title, JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (answer == JOptionPane.YES_OPTION) { // Create new check box JCheckBox newCheckBox = new JCheckBox(presetSensor, true); myDialog.sensorPanel.add(newCheckBox); } } } } // Select preset core interfaces if (moteTypeToConfigure.getCoreInterfaces() != null) { // Deselect all core interfaces already automatically selected for (Component coreInterfaceCheckBox : myDialog.coreInterfacePanel .getComponents()) { ((JCheckBox) coreInterfaceCheckBox).setSelected(false); } for (String presetCoreInterface : moteTypeToConfigure.getCoreInterfaces()) { // Try to find core interface in current list boolean foundAndSelectedCoreInterface = false; for (Component coreInterfaceCheckBox : myDialog.coreInterfacePanel .getComponents()) { if (presetCoreInterface.equals(((JCheckBox) coreInterfaceCheckBox) .getText())) { ((JCheckBox) coreInterfaceCheckBox).setSelected(true); foundAndSelectedCoreInterface = true; break; } } // Warn if not found if (!foundAndSelectedCoreInterface) { // Let user choose whether to add interface Object[] options = { "Add", "Cancel" }; String question = "The configuration file contains a core interface " + "(" + presetCoreInterface + ") not found during scan." + "\nDo you want to include this anyway?"; String title = "Add core interface?"; int answer = JOptionPane.showOptionDialog(myDialog, question, title, JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (answer == JOptionPane.YES_OPTION) { // Create new check box JCheckBox newCheckBox = new JCheckBox(presetCoreInterface, true); myDialog.coreInterfacePanel.add(newCheckBox); } } } } // Select preset mote interfaces if (moteTypeToConfigure.getMoteInterfaces() != null) { // Deselect all mote interfaces already automatically selected for (Component moteInterfaceCheckBox : myDialog.moteInterfacePanel .getComponents()) { ((JCheckBox) moteInterfaceCheckBox).setSelected(false); } for (Class presetMoteInterface : moteTypeToConfigure.getMoteInterfaces()) { // Try to find mote interface in current list boolean foundAndSelectedMoteInterface = false; for (Component moteInterfaceCheckBox : myDialog.moteInterfacePanel .getComponents()) { Class moteInterfaceClass = (Class) ((JCheckBox) moteInterfaceCheckBox) .getClientProperty("class"); if (presetMoteInterface == moteInterfaceClass) { ((JCheckBox) moteInterfaceCheckBox).setSelected(true); foundAndSelectedMoteInterface = true; break; } } // Warn if not found if (!foundAndSelectedMoteInterface) { logger.warn("Mote interface was not found in current environment: " + presetMoteInterface); } } } // Set position and focus of dialog myDialog.pack(); myDialog.setLocationRelativeTo(parentFrame); myDialog.textDescription.requestFocus(); myDialog.textDescription.select(0, myDialog.textDescription.getText() .length()); Rectangle maxSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); if (maxSize != null && (myDialog.getSize().getWidth() > maxSize.getWidth() || myDialog.getSize().getHeight() > maxSize.getHeight())) { Dimension newSize = new Dimension(); newSize.height = Math.min((int) maxSize.getHeight(), (int) myDialog.getSize().getHeight()); newSize.width = Math.min((int) maxSize.getWidth(), (int) myDialog.getSize().getWidth()); logger.info("Resizing dialog: " + myDialog.getSize() + " -> " + newSize); myDialog.setSize(newSize); } myDialog.setVisible(true); if (myDialog.myMoteType != null) { // Library was compiled and loaded return true; } return false; } private ContikiMoteTypeDialog(Frame frame) { super(frame, "Add Mote Type", true); myDialog = this; JLabel label; JPanel mainPane = new JPanel(); mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.Y_AXIS)); JPanel smallPane; JTextField textField; JButton button; // BOTTOM BUTTON PART JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); button = new JButton("Cancel"); button.setActionCommand("cancel"); button.addActionListener(myEventHandler); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(button); buttonPane.add(Box.createHorizontalGlue()); button = new JButton("Clean intermediate files"); button.setActionCommand("clean"); button.addActionListener(myEventHandler); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(button); button = new JButton("Compile & Test"); button.setActionCommand("testsettings"); button.addActionListener(myEventHandler); testButton = button; this.getRootPane().setDefaultButton(button); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(button); button = new JButton("Create"); button.setEnabled(libraryCreatedOK); button.setActionCommand("create"); button.addActionListener(myEventHandler); createButton = button; buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(button); // MAIN PART // Identifier smallPane = new JPanel(); smallPane.setAlignmentX(Component.LEFT_ALIGNMENT); smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS)); label = new JLabel("Identifier"); label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT)); textField = new JTextField(); textField.setText(""); textField.getDocument().addDocumentListener(myEventHandler); textID = textField; label.setLabelFor(textField); smallPane.add(label); smallPane.add(Box.createHorizontalStrut(10)); smallPane.add(Box.createHorizontalGlue()); smallPane.add(textField); mainPane.add(smallPane); mainPane.add(Box.createRigidArea(new Dimension(0, 5))); // Output filenames smallPane = new JPanel(); smallPane.setAlignmentX(Component.LEFT_ALIGNMENT); smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS)); label = new JLabel("Output files"); label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT)); textField = new JTextField(); textField.setText(ContikiMoteType.tempOutputDirectory.getPath() + File.separatorChar + textID.getText() + ContikiMoteType.mapSuffix + ", " + ContikiMoteType.tempOutputDirectory.getPath() + File.separatorChar + textID.getText() + ContikiMoteType.librarySuffix + ", " + ContikiMoteType.tempOutputDirectory.getPath() + File.separatorChar + textID.getText() + ContikiMoteType.dependSuffix); textField.setEnabled(false); textOutputFiles = textField; label.setLabelFor(textField); smallPane.add(label); smallPane.add(Box.createHorizontalStrut(10)); smallPane.add(Box.createHorizontalGlue()); smallPane.add(textField); mainPane.add(smallPane); mainPane.add(Box.createRigidArea(new Dimension(0, 5))); // Description smallPane = new JPanel(); smallPane.setAlignmentX(Component.LEFT_ALIGNMENT); smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS)); label = new JLabel("Description"); label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT)); textField = new JTextField(); textField.setBackground(Color.GREEN); textField.setText("[enter description here]"); textField.getDocument().addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) { if (myDialog.isVisible()) javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { updateVisualFields(); } }); } public void removeUpdate(DocumentEvent e) { if (myDialog.isVisible()) javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { updateVisualFields(); } }); } public void changedUpdate(DocumentEvent e) { if (myDialog.isVisible()) javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { updateVisualFields(); } }); } }); textDescription = textField; label.setLabelFor(textField); smallPane.add(label); smallPane.add(Box.createHorizontalStrut(10)); smallPane.add(Box.createHorizontalGlue()); smallPane.add(textField); mainPane.add(smallPane); mainPane.add(Box.createRigidArea(new Dimension(0, 5))); // Contiki dir smallPane = new JPanel(); smallPane.setAlignmentX(Component.LEFT_ALIGNMENT); smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS)); label = new JLabel("Contiki 2.x OS path"); label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT)); textField = new JTextField(); textField.setText(GUI.getExternalToolsSetting("PATH_CONTIKI")); textField.getDocument().addDocumentListener(myEventHandler); textContikiDir = textField; label.setLabelFor(textField); button = new JButton("Browse"); button.setActionCommand("browsecontiki"); button.addActionListener(myEventHandler); smallPane.add(label); smallPane.add(Box.createHorizontalStrut(10)); smallPane.add(Box.createHorizontalGlue()); smallPane.add(textField); smallPane.add(button); mainPane.add(smallPane); mainPane.add(Box.createRigidArea(new Dimension(0, 5))); // COOJA core platform dir smallPane = new JPanel(); smallPane.setAlignmentX(Component.LEFT_ALIGNMENT); smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS)); label = new JLabel("Core platform path"); label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT)); textField = new JTextField(); textField.setText(textContikiDir.getText() + GUI.getExternalToolsSetting("PATH_COOJA_CORE_RELATIVE")); textField.setEditable(false); textCoreDir = textField; label.setLabelFor(textField); smallPane.add(label); smallPane.add(Box.createHorizontalStrut(10)); smallPane.add(Box.createHorizontalGlue()); smallPane.add(textField); mainPane.add(smallPane); mainPane.add(Box.createRigidArea(new Dimension(0, 5))); // COOJA project directory smallPane = new JPanel(); smallPane.setAlignmentX(Component.LEFT_ALIGNMENT); smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS)); label = new JLabel("Mote type project directories"); label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT)); textField = new JTextField(); textField.setText(""); textField.setEditable(false); textProjectDirs = textField; label.setLabelFor(textField); button = new JButton("Manage"); button.setActionCommand("manageprojectdirs"); button.addActionListener(myEventHandler); smallPane.add(label); smallPane.add(Box.createHorizontalStrut(10)); smallPane.add(Box.createHorizontalGlue()); smallPane.add(textField); smallPane.add(button); mainPane.add(smallPane); mainPane.add(Box.createRigidArea(new Dimension(0, 5))); // Include symbols selection smallPane = new JPanel(); smallPane.setAlignmentX(Component.LEFT_ALIGNMENT); smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS)); label = new JLabel("System symbols"); label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT)); symbolsCheckBox = new JCheckBox("Include"); symbolsCheckBox.setSelected(false); symbolsCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { pathsWereUpdated(); } }); smallPane.add(label); smallPane.add(Box.createHorizontalStrut(10)); smallPane.add(Box.createHorizontalGlue()); smallPane.add(symbolsCheckBox); mainPane.add(smallPane); mainPane.add(Box.createRigidArea(new Dimension(0, 5))); // Separator mainPane.add(new JSeparator()); mainPane.add(Box.createRigidArea(new Dimension(0, 5))); // Rescan button smallPane = new JPanel(); smallPane.setAlignmentX(Component.LEFT_ALIGNMENT); smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS)); label = new JLabel("Scan after entering above information"); rescanButton = new JButton("Scan now"); rescanButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { rescanDirectories(); } }); smallPane.add(label); smallPane.add(Box.createHorizontalStrut(10)); smallPane.add(Box.createHorizontalGlue()); smallPane.add(rescanButton); mainPane.add(smallPane); mainPane.add(Box.createRigidArea(new Dimension(0, 5))); // Separator mainPane.add(new JSeparator()); mainPane.add(Box.createRigidArea(new Dimension(0, 5))); // Processes smallPane = new JPanel(); smallPane.setAlignmentX(Component.LEFT_ALIGNMENT); smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS)); label = new JLabel("Processes"); label.setAlignmentX(Component.LEFT_ALIGNMENT); label.setAlignmentY(Component.TOP_ALIGNMENT); label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT)); JPanel processHolder = new JPanel(new BorderLayout()); processHolder.setAlignmentX(Component.LEFT_ALIGNMENT); processHolder.setAlignmentY(Component.TOP_ALIGNMENT); button = new JButton("Add process name"); button.setActionCommand("addprocess"); button.addActionListener(myEventHandler); processHolder.add(BorderLayout.SOUTH, button); processPanel = new JPanel(); processPanel.setLayout(new BoxLayout(processPanel, BoxLayout.Y_AXIS)); JScrollPane tempPane = new JScrollPane(processPanel); tempPane.setPreferredSize(new Dimension(300, 200)); processHolder.add(BorderLayout.WEST, tempPane); label.setLabelFor(processPanel); smallPane.add(label); smallPane.add(Box.createHorizontalStrut(10)); smallPane.add(Box.createHorizontalGlue()); smallPane.add(processHolder); mainPane.add(smallPane); mainPane.add(Box.createRigidArea(new Dimension(0, 5))); // Mote interfaces smallPane = new JPanel(); smallPane.setAlignmentX(Component.LEFT_ALIGNMENT); smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS)); label = new JLabel("Mote Interfaces"); label.setAlignmentX(Component.LEFT_ALIGNMENT); label.setAlignmentY(Component.TOP_ALIGNMENT); label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT)); JPanel moteInterfaceHolder = new JPanel(new BorderLayout()); moteInterfaceHolder.setAlignmentX(Component.LEFT_ALIGNMENT); moteInterfaceHolder.setAlignmentY(Component.TOP_ALIGNMENT); moteInterfacePanel = new JPanel(); moteInterfacePanel.setLayout(new BoxLayout(moteInterfacePanel, BoxLayout.Y_AXIS)); tempPane = new JScrollPane(moteInterfacePanel); tempPane.setPreferredSize(new Dimension(300, 200)); moteInterfaceHolder.add(BorderLayout.WEST, tempPane); label.setLabelFor(moteInterfacePanel); smallPane.add(label); smallPane.add(Box.createHorizontalStrut(10)); smallPane.add(Box.createHorizontalGlue()); smallPane.add(moteInterfaceHolder); mainPane.add(smallPane); mainPane.add(Box.createRigidArea(new Dimension(0, 5))); // Separator with show advanced checkbox JCheckBox showAdvancedCheckBox = new JCheckBox("Show advanced settings"); showAdvancedCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (((JCheckBox) e.getSource()).isSelected()) { if (entireCoreInterfacePane != null) entireCoreInterfacePane.setVisible(true); if (entireSensorPane != null) entireSensorPane.setVisible(true); } else { if (entireCoreInterfacePane != null) entireCoreInterfacePane.setVisible(false); if (entireSensorPane != null) entireSensorPane.setVisible(false); } } }); mainPane.add(new JSeparator()); mainPane.add(showAdvancedCheckBox); mainPane.add(Box.createRigidArea(new Dimension(0, 5))); // Core sensors smallPane = new JPanel(); smallPane.setAlignmentX(Component.LEFT_ALIGNMENT); smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS)); label = new JLabel("Sensors"); label.setAlignmentX(Component.LEFT_ALIGNMENT); label.setAlignmentY(Component.TOP_ALIGNMENT); label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT)); JPanel sensorHolder = new JPanel(new BorderLayout()); sensorHolder.setAlignmentX(Component.LEFT_ALIGNMENT); sensorHolder.setAlignmentY(Component.TOP_ALIGNMENT); // button = new JButton(GUI.lang.getString("motetype_scansens")); // button.setActionCommand("scansensors"); // button.addActionListener(myEventHandler); // sensorHolder.add(BorderLayout.NORTH, button); button = new JButton("Add sensor name"); button.setActionCommand("addsensor"); button.addActionListener(myEventHandler); sensorHolder.add(BorderLayout.SOUTH, button); sensorPanel = new JPanel(); sensorPanel.setLayout(new BoxLayout(sensorPanel, BoxLayout.Y_AXIS)); JScrollPane tempPane2 = new JScrollPane(sensorPanel); tempPane2.setPreferredSize(new Dimension(300, 200)); sensorHolder.add(BorderLayout.WEST, tempPane2); label.setLabelFor(sensorPanel); smallPane.add(label); smallPane.add(Box.createHorizontalStrut(10)); smallPane.add(Box.createHorizontalGlue()); smallPane.add(sensorHolder); mainPane.add(smallPane); entireSensorPane = smallPane; entireSensorPane.setVisible(false); mainPane.add(Box.createRigidArea(new Dimension(0, 5))); // Core interfaces smallPane = new JPanel(); smallPane.setAlignmentX(Component.LEFT_ALIGNMENT); smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.X_AXIS)); label = new JLabel("Core Interfaces"); label.setAlignmentX(Component.LEFT_ALIGNMENT); label.setAlignmentY(Component.TOP_ALIGNMENT); label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT)); JPanel interfaceHolder = new JPanel(new BorderLayout()); interfaceHolder.setAlignmentX(Component.LEFT_ALIGNMENT); interfaceHolder.setAlignmentY(Component.TOP_ALIGNMENT); button = new JButton("Add interface name"); button.setActionCommand("addinterface"); button.addActionListener(myEventHandler); interfaceHolder.add(BorderLayout.SOUTH, button); coreInterfacePanel = new JPanel(); coreInterfacePanel.setLayout(new BoxLayout(coreInterfacePanel, BoxLayout.Y_AXIS)); JScrollPane tempPane3 = new JScrollPane(coreInterfacePanel); tempPane3.setPreferredSize(new Dimension(300, 200)); interfaceHolder.add(BorderLayout.WEST, tempPane3); label.setLabelFor(coreInterfacePanel); smallPane.add(label); smallPane.add(Box.createHorizontalStrut(10)); smallPane.add(Box.createHorizontalGlue()); smallPane.add(interfaceHolder); mainPane.add(smallPane); entireCoreInterfacePane = smallPane; entireCoreInterfacePane.setVisible(false); mainPane.add(Box.createRigidArea(new Dimension(0, 5))); // Add everything! mainPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); Container contentPane = getContentPane(); JScrollPane mainScrollPane = new JScrollPane(mainPane); // mainScrollPane.setPreferredSize(new Dimension( // mainPane.getPreferredSize().width + 50, 500)); contentPane.add(mainScrollPane, BorderLayout.CENTER); contentPane.add(buttonPane, BorderLayout.SOUTH); addWindowListener(new WindowListener() { public void windowDeactivated(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowOpened(WindowEvent e) { } public void windowClosed(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowClosing(WindowEvent e) { myMoteType = null; dispose(); } }); } /** * Checks which core interfaces are needed by the currently selected mote * interfaces, and selects only them. */ private void recheckInterfaceDependencies() { // Unselect all core interfaces for (Component checkBox : coreInterfacePanel.getComponents()) { ((JCheckBox) checkBox).setSelected(false); } // Loop through all mote interfaces for (Component checkBox : moteInterfacePanel.getComponents()) { JCheckBox moteIntfCheckBox = (JCheckBox) checkBox; // If the mote interface is selected, select needed core interfaces if (moteIntfCheckBox.isSelected()) { String[] neededCoreInterfaces = null; // Get needed core interfaces (if any) try { Class moteInterfaceClass = (Class) moteIntfCheckBox .getClientProperty("class"); if (ContikiMoteInterface.class.isAssignableFrom(moteInterfaceClass)) { Method m = moteInterfaceClass.getDeclaredMethod( "getCoreInterfaceDependencies", (Class[]) null); neededCoreInterfaces = (String[]) m.invoke(null, (Object[]) null); } } catch (NoSuchMethodException e) { logger.warn("Can't read core interface dependencies of " + moteIntfCheckBox.getText() + ", assuming no core dependencies"); } catch (InvocationTargetException e) { logger.warn("Can't read core interface dependencies of " + moteIntfCheckBox.getText() + ": " + e); } catch (IllegalAccessException e) { logger.warn("Can't read core interface dependencies of " + moteIntfCheckBox.getText() + ": " + e); } // If needed core interfaces found, select them if (neededCoreInterfaces != null) { // Loop through all needed core interfaces for (String neededCoreInterface : neededCoreInterfaces) { int coreInterfacePosition = -1; // Check that the core interface actually exists for (int j = 0; j < coreInterfacePanel.getComponentCount(); j++) { JCheckBox coreCheckBox = (JCheckBox) coreInterfacePanel .getComponent(j); if (coreCheckBox.getText().equals(neededCoreInterface)) { coreInterfacePosition = j; coreCheckBox.setSelected(true); break; } } // Was the core interface found? if (coreInterfacePosition < 0) { logger.warn("Warning! " + moteIntfCheckBox.getText() + " needs non-existing core interface " + neededCoreInterface + " (rescan?)"); } } } } } } /** * Tries to compile library using current settings. */ public void doTestSettings() { libraryCreatedOK = false; JPanel progressPanel = new JPanel(new BorderLayout()); final JDialog progressDialog = new JDialog(myDialog, (String) null); JProgressBar progressBar; JButton button; final MessageList taskOutput; progressDialog.setLocationRelativeTo(myDialog); progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setStringPainted(true); progressBar.setIndeterminate(true); taskOutput = new MessageList(); button = new JButton("Close/Abort"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (compilationThread != null && compilationThread.isAlive()) { compilationThread.interrupt(); } if (progressDialog != null && progressDialog.isVisible()) { progressDialog.dispose(); } } }); progressPanel.add(BorderLayout.CENTER, new JScrollPane(taskOutput)); progressPanel.add(BorderLayout.NORTH, progressBar); progressPanel.add(BorderLayout.SOUTH, button); progressPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); progressPanel.setVisible(true); progressDialog.getContentPane().add(progressPanel); progressDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); progressDialog.pack(); progressDialog.getRootPane().setDefaultButton(button); progressDialog.setVisible(true); // Create temp output directory if not already exists if (!ContikiMoteType.tempOutputDirectory.exists()) ContikiMoteType.tempOutputDirectory.mkdir(); // Parse selected sensors Vector<String> sensors = new Vector<String>(); for (Component checkBox : sensorPanel.getComponents()) { if (((JCheckBox) checkBox).isSelected()) { sensors.add(((JCheckBox) checkBox).getText()); } } // Parse selected core interfaces Vector<String> coreInterfaces = new Vector<String>(); for (Component checkBox : coreInterfacePanel.getComponents()) { if (((JCheckBox) checkBox).isSelected()) { coreInterfaces.add(((JCheckBox) checkBox).getText()); } } // Parse selected user processes Vector<String> userProcesses = new Vector<String>(); for (Component checkBox : processPanel.getComponents()) { if (((JCheckBox) checkBox).isSelected()) { userProcesses.add(((JCheckBox) checkBox).getText()); } } // Generate main contiki source file String filename = null; try { filename = generateSourceFile(textID.getText(), sensors, coreInterfaces, userProcesses); } catch (Exception e) { libraryCreatedOK = false; progressBar.setBackground(Color.ORANGE); progressBar.setString(e.getMessage()); progressBar.setIndeterminate(false); progressBar.setValue(0); createButton.setEnabled(libraryCreatedOK); return; } // Test compile shared library progressBar.setString("..compiling.."); final File contikiDir = new File(textContikiDir.getText()); final String identifier = textID.getText(); File libFile = new File(ContikiMoteType.tempOutputDirectory, identifier + ContikiMoteType.librarySuffix); File mapFile = new File(ContikiMoteType.tempOutputDirectory, identifier + ContikiMoteType.mapSuffix); File depFile = new File(ContikiMoteType.tempOutputDirectory, identifier + ContikiMoteType.dependSuffix); if (libFile.exists()) { libFile.delete(); } if (depFile.exists()) { depFile.delete(); } if (mapFile.exists()) { mapFile.delete(); } compilationThread = new Thread(new Runnable() { public void run() { // Add all project directories compilationFiles = (Vector<File>) myGUI .getProjectDirs().clone(); compilationFiles.addAll(moteTypeProjectDirs); // Add source files from project configs String[] projectSourceFiles = newMoteTypeConfig.getStringArrayValue( ContikiMoteType.class, "C_SOURCES"); for (String projectSourceFile : projectSourceFiles) { if (!projectSourceFile.equals("")) { File file = new File(projectSourceFile); if (file.getParent() != null) { // Find which project directory added this file File projectDir = newMoteTypeConfig.getUserProjectDefining( ContikiMoteType.class, "C_SOURCES", projectSourceFile); if (projectDir != null) { // We found a project directory; add it to path compilationFiles.add(new File(projectDir.getPath(), file .getParent())); } } compilationFiles.add(new File(file.getName())); } } // Add selected process source files for (Component checkBox : processPanel.getComponents()) { if (((JCheckBox) checkBox).isSelected()) { String processName = ((JCheckBox) checkBox).getToolTipText(); if (processName != null) { compilationFiles.add(new File(processName)); } } } compilationSucceded = ContikiMoteTypeDialog.compileLibrary(identifier, contikiDir, compilationFiles, symbolsCheckBox.isSelected(), taskOutput.getInputStream(MessageList.NORMAL), taskOutput.getInputStream(MessageList.ERROR)); } }, "compilation thread"); compilationThread.start(); while (compilationThread.isAlive()) { try { Thread.sleep(100); } catch (InterruptedException e) { // NOP } } if (!compilationSucceded) { if (libFile.exists()) { libFile.delete(); } if (depFile.exists()) { depFile.delete(); } if (mapFile.exists()) { mapFile.delete(); } libraryCreatedOK = false; } else { libraryCreatedOK = true; if (!libFile.exists() || !depFile.exists() || !mapFile.exists()) libraryCreatedOK = false; } if (libraryCreatedOK) { progressBar.setBackground(Color.GREEN); progressBar.setString("compilation succeded"); button.grabFocus(); myDialog.getRootPane().setDefaultButton(createButton); } else { progressBar.setBackground(Color.ORANGE); progressBar.setString("compilation failed"); myDialog.getRootPane().setDefaultButton(testButton); } progressBar.setIndeterminate(false); progressBar.setValue(0); createButton.setEnabled(libraryCreatedOK); } /** * Generates new source file by reading default source template and replacing * fields with sensors, core interfaces and processes. Also includes default * processes from GUI external configuration. * * @param id * Mote type ID (decides name of new source file) * @param sensors * Names of sensors * @param coreInterfaces * Names of core interfaces * @param userProcesses * Names of user processes * @return New filename * @throws Exception * If any error occurs */ public static String generateSourceFile(String id, Vector<String> sensors, Vector<String> coreInterfaces, Vector<String> userProcesses) throws Exception { // SENSORS String sensorString = ""; String externSensorDefs = ""; for (String sensor : sensors) { if (!sensorString.equals("")) sensorString += ", "; sensorString += "&" + sensor; externSensorDefs += "extern const struct sensors_sensor " + sensor + ";\n"; } if (!sensorString.equals("")) sensorString = "SENSORS(" + sensorString + ");"; else sensorString = "SENSORS(NULL);"; // CORE INTERFACES String interfaceString = ""; String externInterfaceDefs = ""; for (String coreInterface : coreInterfaces) { if (!interfaceString.equals("")) interfaceString += ", "; interfaceString += "&" + coreInterface; externInterfaceDefs += "SIM_INTERFACE_NAME(" + coreInterface + ");\n"; } if (!interfaceString.equals("")) interfaceString = "SIM_INTERFACES(" + interfaceString + ");"; else interfaceString = "SIM_INTERFACES(NULL);"; // PROCESSES (including any default processes) String userProcessString = ""; String externProcessDefs = ""; for (String process : userProcesses) { if (!userProcessString.equals("")) userProcessString += ", "; userProcessString += "&" + process; externProcessDefs += "PROCESS_NAME(" + process + ");\n"; } String defaultProcessString = ""; String defaultProcesses[] = GUI.getExternalToolsSetting( "CONTIKI_STANDARD_PROCESSES").split(";"); for (String process : defaultProcesses) { if (!defaultProcessString.equals("")) defaultProcessString += ", "; defaultProcessString += "&" + process; } if (userProcessString.equals("")) { logger .warn("No application processes specified! Sure you don't want any?"); } String processString; if (!defaultProcessString.equals("")) processString = "PROCINIT(" + defaultProcessString + ");"; else processString = "PROCINIT(NULL);"; if (!userProcessString.equals("")) processString += "\nAUTOSTART_PROCESSES(" + userProcessString + ");"; else processString += "\nAUTOSTART_PROCESSES(NULL);"; // CHECK JNI CLASS AVAILABILITY String libString = CoreComm.getAvailableClassName(); if (libString == null) { logger.fatal("No more libraries can be loaded!"); throw new Exception("Maximum number of mote types already exist"); } // GENERATE NEW FILE BufferedWriter destFile = null; BufferedReader sourceFile = null; String destFilename = null; try { Reader reader; String mainTemplate = GUI .getExternalToolsSetting("CONTIKI_MAIN_TEMPLATE_FILENAME"); if ((new File(mainTemplate)).exists()) { reader = new FileReader(mainTemplate); } else { InputStream input = ContikiMoteTypeDialog.class .getResourceAsStream('/' + mainTemplate); if (input == null) { throw new FileNotFoundException(mainTemplate + " not found"); } reader = new InputStreamReader(input); } sourceFile = new BufferedReader(reader); destFilename = ContikiMoteType.tempOutputDirectory.getPath() + File.separatorChar + id + ".c"; destFile = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(destFilename))); // Replace special fields in template String line; while ((line = sourceFile.readLine()) != null) { line = line .replaceFirst("\\[PROCESS_DEFINITIONS\\]", externProcessDefs); line = line.replaceFirst("\\[PROCESS_ARRAY\\]", processString); line = line.replaceFirst("\\[SENSOR_DEFINITIONS\\]", externSensorDefs); line = line.replaceFirst("\\[SENSOR_ARRAY\\]", sensorString); line = line.replaceFirst("\\[INTERFACE_DEFINITIONS\\]", externInterfaceDefs); line = line.replaceFirst("\\[INTERFACE_ARRAY\\]", interfaceString); line = line.replaceFirst("\\[CLASS_NAME\\]", libString); destFile.write(line + "\n"); } destFile.close(); sourceFile.close(); } catch (Exception e) { try { if (destFile != null) destFile.close(); if (sourceFile != null) sourceFile.close(); } catch (Exception e2) { } // Forward exception throw e; } return destFilename; } /** * Compiles a mote type shared library using the standard Contiki makefile. * * @param identifier * Mote type identifier * @param contikiDir * Contiki base directory * @param sourceFiles * Source files and directories to include in compilation * @param includeSymbols * Generate and include symbols in library file * @param outputStream * Output stream from compilation (optional) * @param errorStream * Error stream from compilation (optional) * @return True if compilation succeded, false otherwise */ public static boolean compileLibrary(String identifier, File contikiDir, Vector<File> sourceFiles, boolean includeSymbols, final PrintStream outputStream, final PrintStream errorStream) { File libFile = new File(ContikiMoteType.tempOutputDirectory, identifier + ContikiMoteType.librarySuffix); File mapFile = new File(ContikiMoteType.tempOutputDirectory, identifier + ContikiMoteType.mapSuffix); File depFile = new File(ContikiMoteType.tempOutputDirectory, identifier + ContikiMoteType.dependSuffix); // Recheck that contiki path exists if (!contikiDir.exists()) { if (errorStream != null) errorStream.println("Bad Contiki OS path"); logger.fatal("Contiki path does not exist"); return false; } if (!contikiDir.isDirectory()) { if (errorStream != null) errorStream.println("Bad Contiki OS path"); logger.fatal("Contiki path is not a directory"); return false; } if (libFile.exists()) { if (errorStream != null) errorStream.println("Bad output filenames"); logger.fatal("Could not overwrite already existing library"); return false; } if (CoreComm.hasLibraryFileBeenLoaded(libFile)) { if (errorStream != null) errorStream.println("Bad output filenames"); logger .fatal("A library has already been loaded with the same name before"); return false; } if (depFile.exists()) { if (errorStream != null) errorStream.println("Bad output filenames"); logger.fatal("Could not overwrite already existing dependency file"); return false; } if (mapFile.exists()) { if (errorStream != null) errorStream.println("Bad output filenames"); logger.fatal("Could not overwrite already existing map file"); return false; } try { // Let Contiki 2.x regular make file compile String[] cmd = new String[]{ GUI.getExternalToolsSetting("PATH_MAKE"), libFile.getPath().replace(File.separatorChar, '/'), "-f", contikiDir.getPath().replace(File.separatorChar, '/') + "/Makefile.include"}; String sourceDirs = System.getProperty("PROJECTDIRS", ""); String sourceFileNames = ""; String ccFlags = GUI.getExternalToolsSetting("COMPILER_ARGS", ""); for (File sourceFile : sourceFiles) { if (sourceFile.isDirectory()) { // Add directory to search path sourceDirs += " " + sourceFile.getPath().replace(File.separatorChar, '/'); ccFlags += " -I" + sourceFile.getPath().replace(File.separatorChar, '/'); } else if (sourceFile.isFile()) { // Add both file name and directory if (sourceFile.getParent() != null) { sourceDirs += " " + sourceFile.getParent().replace(File.separatorChar, '/'); } sourceFileNames += " " + sourceFile.getName(); } else { // Add filename and hope Contiki knows where to find it... sourceFileNames += " " + sourceFile.getName(); } } logger.info("-- Compiling --"); logger.info("Project dirs: " + sourceDirs); logger.info("Project sources: " + sourceFileNames); logger.info("Compiler flags: " + ccFlags); String[] env = new String[]{ "CONTIKI=" + contikiDir.getPath().replace(File.separatorChar, '/'), "TARGET=cooja", "TYPEID=" + identifier, "LD_ARGS_1=" + GUI.getExternalToolsSetting("LINKER_ARGS_1", ""), "LD_ARGS_2=" + GUI.getExternalToolsSetting("LINKER_ARGS_2", ""), "EXTRA_CC_ARGS=" + ccFlags, "SYMBOLS=" + (includeSymbols?"1":""), "CC=" + GUI.getExternalToolsSetting("PATH_C_COMPILER"), "LD=" + GUI.getExternalToolsSetting("PATH_LINKER"), "PROJECTDIRS=" + sourceDirs, "PROJECT_SOURCEFILES=" + sourceFileNames, "PATH=" + System.getenv("PATH")}; Process p = Runtime.getRuntime().exec(cmd, env, null); final BufferedReader input = new BufferedReader(new InputStreamReader(p .getInputStream())); final BufferedReader err = new BufferedReader(new InputStreamReader(p .getErrorStream())); Thread readInput = new Thread(new Runnable() { public void run() { String readLine; try { while ((readLine = input.readLine()) != null) { if (outputStream != null && readLine != null) outputStream.println(readLine); } } catch (IOException e) { logger.warn("Error while reading from process"); } } }, "read input stream thread"); Thread readError = new Thread(new Runnable() { public void run() { String readLine; try { while ((readLine = err.readLine()) != null) { if (errorStream != null && readLine != null) errorStream.println(readLine); } } catch (IOException e) { logger.warn("Error while reading from process"); } } }, "read input stream thread"); readInput.start(); readError.start(); while (readInput.isAlive() || readError.isAlive()) { Thread.sleep(100); } input.close(); err.close(); p.waitFor(); if (p.exitValue() != 0) { logger.fatal("Make file returned error: " + p.exitValue()); return false; } } catch (Exception e) { logger.fatal("Error while compiling library: " + e); return false; } return true; } /** * Scans a directory for sourcefiles which defines a Contiki process. * * @param rootDirectory * Top directory to search in * @return Process definitions found under rootDirectory, {sourcefile, * processname} */ public static Vector<String[]> scanForProcesses(File rootDirectory) { if (!rootDirectory.isDirectory()) { logger.fatal("Not a directory: " + rootDirectory); return null; } if (!rootDirectory.exists()) { logger.fatal("Does not exist: " + rootDirectory); return null; } Vector<String[]> processes = new Vector<String[]>(); // Scan in rootDirectory try { String line; String cmdString = GUI.getExternalToolsSetting("CMD_GREP_PROCESSES") + " '" + rootDirectory.getPath().replace(File.separatorChar, '/') /** * Scans a directory and all subdirectories for sourcefiles which defines a * Contiki sensor. * * @param rootDirectory * Top directory to search in * @return Sensor definitions found under rootDirectory, {sourcefile, * sensorname} */ public static Vector<String[]> scanForSensors(File rootDirectory) { if (!rootDirectory.isDirectory()) { logger.fatal("Not a directory: " + rootDirectory); return null; } if (!rootDirectory.exists()) { logger.fatal("Does not exist: " + rootDirectory); return null; } Vector<String[]> sensors = new Vector<String[]>(); // Scan in rootDirectory try { String line; String cmdString = GUI.getExternalToolsSetting("CMD_GREP_SENSORS") + " '" + rootDirectory.getPath().replace(File.separatorChar, '/') + "'"; Pattern pattern = Pattern.compile(GUI .getExternalToolsSetting("REGEXP_PARSE_SENSORS")); String[] cmd = new String[3]; cmd[0] = GUI.getExternalToolsSetting("PATH_SHELL"); cmd[1] = "-c"; cmd[2] = cmdString; Process p = Runtime.getRuntime().exec(cmd); BufferedReader input = new BufferedReader(new InputStreamReader(p .getInputStream())); while ((line = input.readLine()) != null) { Matcher matcher = pattern.matcher(line); if (matcher.find()) { sensors.add(new String[]{matcher.group(1), matcher.group(2)}); } } input.close(); BufferedReader err = new BufferedReader(new InputStreamReader(p .getErrorStream())); if (err.ready()) logger.warn("Error occured during scan:"); while ((line = err.readLine()) != null) { logger.warn(line); } err.close(); } catch (IOException err) { logger.fatal("Error while scanning for sensors: " + err); err.printStackTrace(); } catch (Exception err) { logger.fatal("Error while scanning for sensors: " + err); err.printStackTrace(); } return sensors; } /** * Scans a directory and all subdirectories for sourcefiles which defines a * COOJA core interface. * * @param rootDirectory * Top directory to search in * @return Core interface definitions found under rootDirectory, {sourcefile, * interfacename} */ public static Vector<String[]> scanForInterfaces(File rootDirectory) { if (!rootDirectory.isDirectory()) { logger.fatal("Not a directory: " + rootDirectory); return null; } if (!rootDirectory.exists()) { logger.fatal("Does not exist: " + rootDirectory); return null; } Vector<String[]> interfaces = new Vector<String[]>(); // Scan in rootDirectory try { String line; String cmdString = GUI.getExternalToolsSetting("CMD_GREP_INTERFACES") + " '" + rootDirectory.getPath().replace(File.separatorChar, '/') + "'"; Pattern pattern = Pattern.compile(GUI .getExternalToolsSetting("REGEXP_PARSE_INTERFACES")); String[] cmd = new String[3]; cmd[0] = GUI.getExternalToolsSetting("PATH_SHELL"); cmd[1] = "-c"; cmd[2] = cmdString; Process p = Runtime.getRuntime().exec(cmd); BufferedReader input = new BufferedReader(new InputStreamReader(p .getInputStream())); while ((line = input.readLine()) != null) { Matcher matcher = pattern.matcher(line); if (matcher.find()) { interfaces.add(new String[]{matcher.group(1), matcher.group(2)}); } } input.close(); BufferedReader err = new BufferedReader(new InputStreamReader(p .getErrorStream())); if (err.ready()) logger.warn("Error occured during scan:"); while ((line = err.readLine()) != null) { logger.warn(line); } err.close(); } catch (IOException err) { logger.fatal("Error while scanning for interfaces: " + err); err.printStackTrace(); } catch (Exception err) { logger.fatal("Error while scanning for interfaces: " + err); err.printStackTrace(); } return interfaces; } /** * Scans given file for an autostart expression and returns all process names * found. * * @param sourceFile * Source file to scan * @return Autostart process names or null * @throws FileNotFoundException * Given file not found * @throws IOException * IO Exception */ public static Vector<String> parseAutostartProcesses(File sourceFile) throws FileNotFoundException, IOException { // Open file for reading BufferedReader sourceFileReader = new BufferedReader(new FileReader( sourceFile)); // Find which processes were set to autostart String line; String autostartExpression = "^AUTOSTART_PROCESSES([^$]*)$"; Pattern pattern = Pattern.compile(autostartExpression); Vector<String> foundProcesses = new Vector<String>(); while ((line = sourceFileReader.readLine()) != null) { Matcher matcher = pattern.matcher(line); if (matcher.find()) { // Parse autostart processes String[] allProcesses = matcher.group(1).split(","); for (String autostartProcess : allProcesses) { foundProcesses.add(autostartProcess.replaceAll("[&; \\(\\)]", "")); } } } return foundProcesses; } private boolean autoSelectDependencyProcesses(String processName, String sourceFilename, boolean confirmSelection) { // Locate source file File sourceFile = new File(textCoreDir.getText(), sourceFilename); boolean foundFile = sourceFile.exists(); if (!foundFile) for (File projectDir : myGUI.getProjectDirs()) { sourceFile = new File(projectDir, sourceFilename); if (foundFile = sourceFile.exists()) break; } if (!foundFile) for (File projectDir : moteTypeProjectDirs) { sourceFile = new File(projectDir, sourceFilename); if (foundFile = sourceFile.exists()) break; } if (!foundFile) { // Die quietly return false; } Vector<String> autostartProcesses = null; try { autostartProcesses = parseAutostartProcesses(sourceFile); } catch (Exception e) { return false; } if (autostartProcesses == null || autostartProcesses.isEmpty()) { // Die quietly return true; } for (String autostartProcess : autostartProcesses) { // Does this process already exist? boolean processAlreadySelected = false; for (Component checkBox : processPanel.getComponents()) { JCheckBox checkBox2 = (JCheckBox) checkBox; String existingProcess = checkBox2.getText(); boolean selected = checkBox2.isSelected(); if (existingProcess.equals(autostartProcess) && selected) { processAlreadySelected = true; } } if (!processAlreadySelected) { boolean processShouldBeSelected = false; if (confirmSelection) { // Let user choose whether to add process Object[] options = { "Add", "Cancel" }; String question = "The process " + processName + " depends on the following process: " + autostartProcess + "\nDo you want to select this as well?"; String title = "Select dependency process?"; int answer = JOptionPane.showOptionDialog(myDialog, question, title, JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (answer == JOptionPane.YES_OPTION) { processShouldBeSelected = true; } } else { // Add process processShouldBeSelected = true; } if (processShouldBeSelected) { // Get checkbox to select JCheckBox processToSelectCheckBox = null; for (Component checkBox : processPanel.getComponents()) { JCheckBox checkBox2 = (JCheckBox) checkBox; if (checkBox2.getText().equals(autostartProcess)) { processToSelectCheckBox = checkBox2; break; } } if (processToSelectCheckBox == null) { // Create new check box processToSelectCheckBox = new JCheckBox(autostartProcess, true); processToSelectCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT); processToSelectCheckBox.setActionCommand("process_clicked: " + autostartProcess); processToSelectCheckBox.addActionListener(myEventHandler); processPanel.add(processToSelectCheckBox); } processToSelectCheckBox.setSelected(true); processPanel.invalidate(); processPanel.revalidate(); } } } return true; } private void pathsWereUpdated() { updateVisualFields(); // Remove all prevously scanned entries coreInterfacePanel.removeAll(); moteInterfacePanel.removeAll(); processPanel.removeAll(); sensorPanel.removeAll(); coreInterfacePanel.revalidate(); coreInterfacePanel.repaint(); moteInterfacePanel.revalidate(); moteInterfacePanel.repaint(); processPanel.revalidate(); processPanel.repaint(); sensorPanel.revalidate(); sensorPanel.repaint(); createButton.setEnabled(libraryCreatedOK = false); settingsOK = false; testButton.setEnabled(settingsOK); } private void updateVisualFields() { settingsOK = true; // Check for non-unique identifier textID.setBackground(Color.WHITE); textID.setToolTipText(null); for (MoteType otherType : allOtherTypes) { if (otherType != myMoteType && otherType.getIdentifier().equalsIgnoreCase(textID.getText())) { textID.setBackground(Color.RED); textID.setToolTipText("Conflicting name - must be unique"); settingsOK = false; break; } } // Check for non-unique description textDescription.setBackground(Color.WHITE); textDescription.setToolTipText(null); for (MoteType otherType : allOtherTypes) { if (otherType != myMoteType && otherType.getDescription().equals(textDescription.getText())) { textDescription.setBackground(Color.RED); textDescription.setToolTipText("Conflicting name - must be unique"); settingsOK = false; break; } } // Warn if spaces in Contiki path textContikiDir.setBackground(Color.WHITE); textContikiDir.setToolTipText(null); if (textContikiDir.getText().contains(" ")) { textContikiDir.setBackground(Color.ORANGE); textContikiDir .setToolTipText("Compilation may not work correctly with spaced paths"); } textCoreDir.setText(textContikiDir.getText() + GUI.getExternalToolsSetting("PATH_COOJA_CORE_RELATIVE")); textCoreDir.setBackground(Color.WHITE); textCoreDir.setToolTipText(null); if (textCoreDir.getText().contains(" ")) { textCoreDir.setBackground(Color.ORANGE); textCoreDir .setToolTipText("Compilation may not work correctly with spaced paths"); } // Warn if spaces in a project directory path textProjectDirs.setBackground(Color.WHITE); textProjectDirs.setToolTipText(null); for (File projectDir : moteTypeProjectDirs) { if (projectDir.getPath().contains(" ")) { textProjectDirs.setBackground(Color.ORANGE); textProjectDirs .setToolTipText("Compilation may not work correctly with spaced paths"); } } // Update output text field textOutputFiles.setText(ContikiMoteType.tempOutputDirectory.getPath() + File.separatorChar + textID.getText() + ContikiMoteType.mapSuffix + ", " + ContikiMoteType.tempOutputDirectory.getPath() + File.separatorChar + textID.getText() + ContikiMoteType.librarySuffix + ", " + ContikiMoteType.tempOutputDirectory.getPath() + File.separatorChar + textID.getText() + ContikiMoteType.dependSuffix); createButton.setEnabled(libraryCreatedOK = false); testButton.setEnabled(settingsOK); } /** * Scans Contiki base + (optional) project directories for Contiki processes, * sensors and core interfaces. The new mote type config is recreated every * time this method is run. If any project directories are specified, it reads * the configuration files, and appends it to the new mote type config. * By reading those configs all available mote interfaces are parsed - * which will all be selected initially. This method also selects the core * interfaces needed by the mote interfaces. * * Finally any pre-specified processes (via shortcut start) will be selected. */ private void rescanDirectories() { boolean pathErrorFound = false; // Check that Contiki path is correct if (!new File(myDialog.textContikiDir.getText()).isDirectory()) { // Contiki path specified does not exist textContikiDir.setBackground(Color.RED); textContikiDir.setToolTipText("Incorrect path"); pathErrorFound = true; } // Check that Cooja main platform path is correct if (!new File(myDialog.textCoreDir.getText()).isDirectory()) { // Cooja main platform specified does not exist textContikiDir.setBackground(Color.RED); textContikiDir.setToolTipText("Incorrect path"); textCoreDir.setBackground(Color.RED); textCoreDir.setToolTipText("Incorrect path"); pathErrorFound = true; } // Check that all project directories are valid for (File projectDir : moteTypeProjectDirs) { File userProjectConfig = new File(projectDir.getPath(), GUI.PROJECT_CONFIG_FILENAME); if (!userProjectConfig.exists()) { textProjectDirs.setBackground(Color.RED); textProjectDirs.setToolTipText("Invalid project directory: " + projectDir); pathErrorFound = true; } } if (pathErrorFound) { // Remove all prevously scanned entries coreInterfacePanel.removeAll(); processPanel.removeAll(); sensorPanel.removeAll(); coreInterfacePanel.revalidate(); coreInterfacePanel.repaint(); processPanel.revalidate(); processPanel.repaint(); sensorPanel.revalidate(); sensorPanel.repaint(); testButton.setEnabled(settingsOK = false); createButton.setEnabled(libraryCreatedOK = false); return; } // Scan for mote interfaces (+ recreate node type class configuration) myEventHandler.actionPerformed(new ActionEvent(myDialog.createButton, ActionEvent.ACTION_PERFORMED, "scanmoteinterfaces")); // Scan for processes myEventHandler.actionPerformed(new ActionEvent(myDialog.createButton, ActionEvent.ACTION_PERFORMED, "scanprocesses")); // Scan for sensors myDialog.myEventHandler.actionPerformed(new ActionEvent( myDialog.createButton, ActionEvent.ACTION_PERFORMED, "scansensors")); // Scan for core interfaces myDialog.myEventHandler.actionPerformed(new ActionEvent( myDialog.createButton, ActionEvent.ACTION_PERFORMED, "scancoreinterfaces")); // Recheck dependencies between selected mote interfaces and available // core interfaces myDialog.myEventHandler.actionPerformed(new ActionEvent( myDialog.createButton, ActionEvent.ACTION_PERFORMED, "recheck_interface_dependencies")); settingsOK = true; testButton.setEnabled(settingsOK); } private class MoteTypeEventHandler implements ActionListener, DocumentListener { public void insertUpdate(DocumentEvent e) { if (myDialog.isVisible()) javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { pathsWereUpdated(); } }); } public void removeUpdate(DocumentEvent e) { if (myDialog.isVisible()) javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { pathsWereUpdated(); } }); } public void changedUpdate(DocumentEvent e) { if (myDialog.isVisible()) javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { pathsWereUpdated(); } }); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("cancel")) { // Cancel creation of mote type myMoteType = null; dispose(); } else if (e.getActionCommand().equals("clean")) { // Delete any created intermediate files File objectDir = ContikiMoteType.tempOutputDirectory; if (objectDir.exists() && objectDir.isDirectory()) { File[] objectFiles = objectDir.listFiles(); for (File objectFile : objectFiles) objectFile.delete(); objectDir.delete(); } } else if (e.getActionCommand().equals("create")) { // Create mote type and set various data myMoteType.doInit(textID.getText()); myMoteType.setDescription(textDescription.getText()); myMoteType.setContikiBaseDir(textContikiDir.getText()); myMoteType.setContikiCoreDir(textCoreDir.getText()); myMoteType.setProjectDirs(moteTypeProjectDirs); myMoteType.setCompilationFiles(compilationFiles); myMoteType.setConfig(newMoteTypeConfig); // Set startup processes Vector<String> processes = new Vector<String>(); for (Component checkBox : processPanel.getComponents()) { if (((JCheckBox) checkBox).isSelected()) { processes.add(((JCheckBox) checkBox).getText()); } } myMoteType.setProcesses(processes); // Set registered sensors Vector<String> sensors = new Vector<String>(); for (Component checkBox : sensorPanel.getComponents()) { if (((JCheckBox) checkBox).isSelected()) { sensors.add(((JCheckBox) checkBox).getText()); } } myMoteType.setSensors(sensors); // Set registered core interfaces Vector<String> coreInterfaces = new Vector<String>(); for (Component checkBox : coreInterfacePanel.getComponents()) { if (((JCheckBox) checkBox).isSelected()) { coreInterfaces.add(((JCheckBox) checkBox).getText()); } } myMoteType.setCoreInterfaces(coreInterfaces); // Set registered mote interfaces Vector<Class<? extends MoteInterface>> moteInterfaces = new Vector<Class<? extends MoteInterface>>(); for (Component checkBox : moteInterfacePanel.getComponents()) { JCheckBox interfaceCheckBox = (JCheckBox) checkBox; if (interfaceCheckBox.isSelected()) { moteInterfaces .add((Class<? extends MoteInterface>) interfaceCheckBox .getClientProperty("class")); } } myMoteType.setMoteInterfaces(moteInterfaces); // Set "using symbols" myMoteType.setHasSystemSymbols(symbolsCheckBox.isSelected()); dispose(); } else if (e.getActionCommand().equals("testsettings")) { testButton.requestFocus(); Thread testSettingsThread = new Thread(new Runnable() { public void run() { doTestSettings(); } }, "test settings thread"); testSettingsThread.start(); } else if (e.getActionCommand().equals("browsecontiki")) { JFileChooser fc = new JFileChooser(); fc.setCurrentDirectory(new java.io.File(".")); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setDialogTitle("Contiki OS base directory"); if (fc.showOpenDialog(myDialog) == JFileChooser.APPROVE_OPTION) { textContikiDir.setText(fc.getSelectedFile().getPath()); } createButton.setEnabled(libraryCreatedOK = false); pathsWereUpdated(); } else if (e.getActionCommand().equals("manageprojectdirs")) { Vector<File> newProjectDirs = ProjectDirectoriesDialog.showDialog( ContikiMoteTypeDialog.this, moteTypeProjectDirs, myGUI .getProjectDirs()); if (newProjectDirs != null) { moteTypeProjectDirs = newProjectDirs; String projectDirText = null; for (File projectDir : newProjectDirs) { if (projectDirText == null) projectDirText = "'" + projectDir.getPath() + "'"; else projectDirText += " + '" + projectDir.getPath() + "'"; } textProjectDirs.setText(projectDirText); createButton.setEnabled(libraryCreatedOK = false); pathsWereUpdated(); } } else if (e.getActionCommand().equals("scanprocesses")) { // Clear process panel processPanel.removeAll(); Vector<String[]> processes = new Vector<String[]>(); // Scan core platform for processes processes.addAll(ContikiMoteTypeDialog.scanForProcesses(new File( textCoreDir.getText()))); // If project directories exists, scan those too for (File projectDir : myGUI.getProjectDirs()) { processes .addAll(ContikiMoteTypeDialog.scanForProcesses(projectDir)); } if (moteTypeProjectDirs != null) { for (File projectDir : moteTypeProjectDirs) { processes.addAll(ContikiMoteTypeDialog .scanForProcesses(projectDir)); } } if (processes != null) { for (String[] processInfo : processes) { JCheckBox processCheckBox = new JCheckBox(processInfo[1], false); processCheckBox.setToolTipText(processInfo[0]); processCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT); processCheckBox.setActionCommand("process_clicked: " + processInfo[1]); processCheckBox.addActionListener(myEventHandler); processPanel.add(processCheckBox); } } else { logger.warn("No processes found during scan"); testButton.setEnabled(settingsOK = false); } processPanel.revalidate(); processPanel.repaint(); createButton.setEnabled(libraryCreatedOK = false); } else if (e.getActionCommand().equals("scansensors")) { // Clear sensor panel sensorPanel.removeAll(); Vector<String[]> sensors = new Vector<String[]>(); // Scan core platform for sensors sensors.addAll(ContikiMoteTypeDialog.scanForSensors(new File( textCoreDir.getText()))); // If project directories exists, scan those too for (File projectDir : myGUI.getProjectDirs()) { sensors.addAll(ContikiMoteTypeDialog.scanForSensors(projectDir)); } if (moteTypeProjectDirs != null) { for (File projectDir : moteTypeProjectDirs) { sensors.addAll(ContikiMoteTypeDialog.scanForSensors(projectDir)); } } if (sensors != null) { for (String[] sensorInfo : sensors) { JCheckBox sensorCheckBox = new JCheckBox(sensorInfo[1], true); sensorCheckBox.setToolTipText(sensorInfo[0]); sensorCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT); sensorPanel.add(sensorCheckBox); } } else { logger.warn("No sensors found during scan"); testButton.setEnabled(settingsOK = false); } sensorPanel.revalidate(); sensorPanel.repaint(); createButton.setEnabled(libraryCreatedOK = false); } else if (e.getActionCommand().equals("scancoreinterfaces")) { // Clear core interface panel coreInterfacePanel.removeAll(); Vector<String[]> interfaces = new Vector<String[]>(); // Scan core platform for core interfaces interfaces.addAll(ContikiMoteTypeDialog.scanForInterfaces(new File( textCoreDir.getText()))); // If project directories exists, scan those too for (File projectDir : myGUI.getProjectDirs()) { interfaces.addAll(ContikiMoteTypeDialog .scanForInterfaces(projectDir)); } if (moteTypeProjectDirs != null) { for (File projectDir : moteTypeProjectDirs) { interfaces.addAll(ContikiMoteTypeDialog .scanForInterfaces(projectDir)); } } if (interfaces != null) { for (String[] interfaceInfo : interfaces) { JCheckBox interfaceCheckBox = new JCheckBox(interfaceInfo[1], false); interfaceCheckBox.setToolTipText(interfaceInfo[0]); interfaceCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT); coreInterfacePanel.add(interfaceCheckBox); } } else { logger.warn("No core interfaces found during scan"); testButton.setEnabled(settingsOK = false); } recheckInterfaceDependencies(); coreInterfacePanel.revalidate(); coreInterfacePanel.repaint(); createButton.setEnabled(libraryCreatedOK = false); } else if (e.getActionCommand().equals("scanmoteinterfaces")) { // Clear core interface panel moteInterfacePanel.removeAll(); // Clone general simulator config newMoteTypeConfig = myGUI.getProjectConfig().clone(); // Merge with all project directory configs (if any) for (File projectDir : moteTypeProjectDirs) { try { newMoteTypeConfig.appendProjectDir(projectDir); } catch (Exception ex) { logger.fatal("Error when parsing project directory config: " + ex); return; } } // Get all mote interfaces available from config String[] moteInterfaces = newMoteTypeConfig.getStringArrayValue( ContikiMoteType.class, "MOTE_INTERFACES"); Vector<Class<? extends MoteInterface>> moteIntfClasses = new Vector<Class<? extends MoteInterface>>(); ClassLoader classLoader = myGUI .createProjectDirClassLoader(moteTypeProjectDirs); // Find and load the mote interface classes for (String moteInterface : moteInterfaces) { try { Class<? extends MoteInterface> newMoteInterfaceClass = classLoader .loadClass(moteInterface).asSubclass(MoteInterface.class); moteIntfClasses.add(newMoteInterfaceClass); // logger.info("Loaded mote interface: " + newMoteInterfaceClass); } catch (Exception ce) { logger.warn("Failed to load mote interface: " + moteInterface); } } // Create and add checkboxes for all mote interfaces if (moteIntfClasses.size() > 0) { for (Class<? extends MoteInterface> moteIntfClass : moteIntfClasses) { JCheckBox interfaceCheckBox = new JCheckBox(GUI .getDescriptionOf(moteIntfClass), true); interfaceCheckBox.putClientProperty("class", moteIntfClass); interfaceCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT); interfaceCheckBox .setActionCommand("recheck_interface_dependencies"); interfaceCheckBox.addActionListener(myEventHandler); moteInterfacePanel.add(interfaceCheckBox); } } else { logger .warn("Error occured during parsing of mote interfaces (no found)"); testButton.setEnabled(settingsOK = false); } moteInterfacePanel.revalidate(); moteInterfacePanel.repaint(); createButton.setEnabled(libraryCreatedOK = false); } else if (e.getActionCommand().equals("addprocess")) { String newProcessName = JOptionPane.showInputDialog(myDialog, "Enter process name"); if (newProcessName != null) { JCheckBox processCheckBox = new JCheckBox(newProcessName, false); processCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT); processCheckBox.setSelected(true); processCheckBox .setActionCommand("process_clicked: " + newProcessName); processCheckBox.addActionListener(myEventHandler); processPanel.add(processCheckBox); processPanel.revalidate(); processPanel.repaint(); } } else if (e.getActionCommand().equals("addsensor")) { String newSensorName = JOptionPane.showInputDialog(myDialog, "Enter sensor name"); if (newSensorName != null) { JCheckBox sensorCheckBox = new JCheckBox(newSensorName, false); sensorCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT); sensorCheckBox.setSelected(true); sensorPanel.add(sensorCheckBox); sensorPanel.revalidate(); sensorPanel.repaint(); } } else if (e.getActionCommand().equals("addinterface")) { String newInterfaceName = JOptionPane.showInputDialog(myDialog, "Enter interface name"); if (newInterfaceName != null) { JCheckBox interfaceCheckBox = new JCheckBox(newInterfaceName, false); interfaceCheckBox.setAlignmentX(Component.LEFT_ALIGNMENT); interfaceCheckBox.setSelected(true); coreInterfacePanel.add(interfaceCheckBox); coreInterfacePanel.revalidate(); coreInterfacePanel.repaint(); } } else if (e.getActionCommand().equals("recheck_interface_dependencies")) { recheckInterfaceDependencies(); } else if (e.getActionCommand().startsWith("process_clicked")) { boolean processWasSelected = false; String sourceFilename = null; String processName = e.getActionCommand().split(": ")[1].trim(); // Was the process selected or unselected? for (Component checkBox : processPanel.getComponents()) { JCheckBox processCheckbox = (JCheckBox) checkBox; if (processCheckbox.isSelected() && processCheckbox.getText().equals(processName)) { processWasSelected = true; sourceFilename = ((JCheckBox) checkBox).getToolTipText(); break; } } if (!processWasSelected || sourceFilename == null) return; autoSelectDependencyProcesses(processName, sourceFilename, true); } else logger.warn("Unhandled action: " + e.getActionCommand()); createButton.setEnabled(libraryCreatedOK = false); } } }
package org.trianacode.config; import org.trianacode.TrianaInstance; import java.io.*; import java.util.Enumeration; import java.util.Properties; /** * The TrianaProperties class stores the properties for a Triana instance. Triana properties * are propagated through all the relevant Triana classes so that oneset of properties can be * used per triana instance. TrianaProperties also contains a default configuration that is * packaged with Triana as shipped. These properties can be altered by any third party * application to configure the look and feel and locations for the various toolboxes, * templates etc. */ public class TrianaProperties extends Properties { public static String DEFAULT_COMMENTS = "This is the property configuration for Triana\n" + "To change properties use the GUI, set properties using the command line\n" + " or edit this file directly. However, there is a defined order for property\n" + "overriding, which needs to be taken into account\n"; public static String DOMAIN = "org.trianacode"; public static String VERSION = DOMAIN + ".version"; // SEARCH PATHS comma separated file list of property files. public static final String PROPERTY_SEARCH_PATH_PROPERTY = DOMAIN + ".property.search.path"; public static final String TOOLBOX_SEARCH_PATH_PROPERTY = DOMAIN + ".toolbox.search.path"; public static final String MODULE_SEARCH_PATH_PROPERTY = DOMAIN + ".module.search.path"; public static final String TEMPLATE_SEARCH_PATH_PROPERTY = DOMAIN + ".template.search.path"; // List of property files that can contains properties (1 or more). Default is DEFAULT_PROPERTY_FILE // but this list overides the default. Comma separated list of files. public static final String PROPERTY_FILE_LIST_PROPERTY = DOMAIN + ".property.file.list"; public static final String TOOLBOXES_DESCRIPTION_TEMPLATE_PROPERTY = DOMAIN + ".toolboxes.description.template"; public static final String TOOLS_DESCRIPTION_TEMPLATE_PROPERTY = DOMAIN + ".tools.description.template"; public static final String TOOLBOX_DESCRIPTION_TEMPLATE_PROPERTY = DOMAIN + ".toolbox.description.template"; public static final String TOOL_DESCRIPTION_TEMPLATE_PROPERTY = DOMAIN + ".tool.description.template"; public static final String CREATE_TOOL_INSTANCE_PROPERTY = DOMAIN + ".create.tool.instance"; public static final String TOOL_INSTANCE_PROPERTY = DOMAIN + ".tool.instance"; public static final String TOOL_PARAMETER_WINDOW_TEMPLATE_PROPERTY = DOMAIN + ".tool.parameter.window.template"; public static final String FORM_TEMPLATE_PROPERTY = DOMAIN + ".form.template"; public static final String CHECKBOX_TEMPLATE_PROPERTY = DOMAIN + ".checkbox.template"; public static final String TOOL_COMPLETED_TEMPLATE_PROPERTY = DOMAIN + ".tool.completed.template"; public static final String TRIANA_TEMPLATE_PROPERTY = DOMAIN + ".triana.template"; public static final String HEADER_TEMPLATE_PROPERTY = DOMAIN + ".header.template"; public static final String FOOTER_TEMPLATE_PROPERTY = DOMAIN + ".footer.template"; public static final String NOHELP_TEMPLATE_PROPERTY = DOMAIN + ".nohelp.template"; public static final String TOOL_CP_XML_TEMPLATE_PROPERTY = DOMAIN + ".tool.cp.xml.template"; public static final String TOOL_CP_HTML_TEMPLATE_PROPERTY = DOMAIN + ".tool.cp.html.template"; // NOT USED at present: public static final String WEB_TEMPLATE_PROPERTY = DOMAIN + ".web.template"; public static final String WEB_TOOL_TEMPLATE_PROPERTY = DOMAIN + ".web.tool.template"; public static final String TOOL_HELP_TEMPLATE_PROPERTY = DOMAIN + ".tool.help.template"; private TrianaInstance engine; public TrianaProperties(TrianaInstance engine) { this(engine, null); } /** * Initialises the properties giving the defaults * * @param initValues */ public TrianaProperties(TrianaInstance engine, Properties initValues) { this.engine = engine; this.putAll(getDefaultConfiguration()); if (initValues != null) { putAll(initValues); } } public void overrideUsingSystemProperties() { // copy system properties to OVERWRITE any of the defaults i.e. these are // specified and should over-ride all default variables or those specified from // config files. Properties systemprops = System.getProperties(); Enumeration propNames = systemprops.keys(); while (propNames.hasMoreElements()) { String prop = (String) propNames.nextElement(); String value = systemprops.getProperty(prop); if ((value != null) && (value.contains(DOMAIN))) { setProperty(prop, value); } } } public static Properties getDefaultConfiguration() { Properties properties = new Properties(); properties.put(VERSION, "4"); properties.put(Locations.DEFAULT_PROPERTY_FILE, Locations.getApplicationDataDir() + "/" + DOMAIN + ".properties"); // PROPERTY_FILE_LIST is null properties.put(TOOLBOX_SEARCH_PATH_PROPERTY, Locations.getDefaultToolboxRoot()); properties.put(MODULE_SEARCH_PATH_PROPERTY, Locations.getDefaultModuleRoot()); // should we do this??? // ANDREW: No - these will be on the classpath if classes/ is used or is in a jar // ANDREW: CHANGED THIS AND TOOLBOX SEARCH. THEY WERE MESSED UP AND CREATED DEPENDENCIES ON THE BUILD // STRUCTURE - NO GOOD FOR DISTRIBUTION. properties.put(TEMPLATE_SEARCH_PATH_PROPERTY, Locations.getDefaultTemplateRoot()); properties.put(TOOL_PARAMETER_WINDOW_TEMPLATE_PROPERTY, "/templates/tool-params.tpl"); properties.put(CREATE_TOOL_INSTANCE_PROPERTY, "/templates/tool-create.tpl"); properties.put(TOOL_COMPLETED_TEMPLATE_PROPERTY, "/templates/tool-complete.tpl"); properties.put(TOOL_INSTANCE_PROPERTY, "/templates/tool-instance.tpl"); properties.put(TOOL_DESCRIPTION_TEMPLATE_PROPERTY, "/templates/tool-description.tpl"); properties.put(TOOLS_DESCRIPTION_TEMPLATE_PROPERTY, "/templates/tools-description.tpl"); properties.put(TOOLBOX_DESCRIPTION_TEMPLATE_PROPERTY, "/templates/toolbox-description.tpl"); properties.put(TOOLBOXES_DESCRIPTION_TEMPLATE_PROPERTY, "/templates/toolboxes-description.tpl"); properties.put(TRIANA_TEMPLATE_PROPERTY, "/templates/triana.tpl"); properties.put(FORM_TEMPLATE_PROPERTY, "/templates/form.tpl"); properties.put(CHECKBOX_TEMPLATE_PROPERTY, "/templates/checkbox.tpl"); properties.put(HEADER_TEMPLATE_PROPERTY, "/templates/header.tpl"); properties.put(FOOTER_TEMPLATE_PROPERTY, "/templates/footer.tpl"); properties.put(NOHELP_TEMPLATE_PROPERTY, "/templates/nohelp.tpl"); properties.put(TOOL_CP_XML_TEMPLATE_PROPERTY, "/templates/cp.xml.tpl"); properties.put(TOOL_CP_HTML_TEMPLATE_PROPERTY, "/templates/cp.html.tpl"); return properties; } /** * Creates a string version of the current property configuration * * @return a String of the properties. */ public String toString() { Writer stringWriter = new StringWriter(); String contents = null; try { this.store(stringWriter, DEFAULT_COMMENTS); stringWriter.flush(); contents = stringWriter.toString(); stringWriter.close(); } catch (IOException e) { // is this possible? return null; } return contents; } /** * Saves the current properties to App_Dir/org.trianacode.properties * * @throws IOException */ public void saveProperties() throws IOException { saveProperties(DEFAULT_COMMENTS); } /** * Saves the properties to the default config file */ public void saveProperties(String comments) throws IOException { File file = new File(Locations.getDefaultConfigFile()); OutputStream outstream = new FileOutputStream(file); this.store(outstream, comments); outstream.flush(); outstream.close(); } public TrianaInstance getEngine() { return engine; } }
package edu.yu.einstein.wasp.viewpanel; /** * @author aj * */ public class GridColumn { private String header; private String dataIndex; private Integer width = null; private Integer flex = 0; private boolean sortable = false; private boolean hideable = false; private String align = "right"; private String style = "text-align:left"; /** * @return the header */ public String getHeader() { return header; } /** * @param header the header to set */ public void setHeader(String header) { this.header = header; } /** * @return the width */ public Integer getWidth() { return width; } /** * @param width the width to set */ public void setWidth(Integer width) { this.width = width; this.flex = 0; } /** * @return the dataIndex */ public String getDataIndex() { return dataIndex; } /** * @param dataIndex the dataIndex to set */ public void setDataIndex(String dataIndex) { this.dataIndex = dataIndex; } /** * @return the flex */ public Integer getFlex() { return flex; } /** * @param flex the flex to set */ public void setFlex(Integer flex) { this.flex = flex; if (flex > 0) { this.width = null; } } /** * @return the sortable */ public boolean isSortable() { return sortable; } /** * @param sortable the sortable to set */ public void setSortable(boolean sortable) { this.sortable = sortable; } /** * @return the hideable */ public boolean isHideable() { return hideable; } /** * @param hideable the hideable to set */ public void setHideable(boolean hideable) { this.hideable = hideable; } /** * @return the align */ public String getAlign() { return align; } /** * @param align the align to set */ public void setAlign(String align) { this.align = align; } /** * @return the style */ public String getStyle() { return style; } /** * @param style the style to set */ public void setStyle(String style) { this.style = style; } /** * @param header * @param dataIndex */ public GridColumn(String header, String dataIndex) { this.header = header; this.dataIndex = dataIndex; } /** * @param header * @param width * @param dataIndex */ public GridColumn(String header, String dataIndex, Integer width, Integer flex) { this.header = header; this.dataIndex = dataIndex; this.width = width; } /** * @param header * @param dataIndex * @param flex */ public GridColumn(String header, String dataIndex, Integer flex) { this.header = header; this.dataIndex = dataIndex; this.flex = flex; } /** * @param header * @param width * @param dataIndex * @param flex * @param sortable * @param hideable */ public GridColumn(String header, String dataIndex, Integer width, Integer flex, boolean sortable, boolean hideable) { this.header = header; this.width = width; this.dataIndex = dataIndex; this.flex = flex; this.sortable = sortable; this.hideable = hideable; } }
package org.jboss.as.web.deployment; // $Id: JBossContextConfig.java 104399 2010-05-03 20:50:38Z remy.maucherat@jboss.com $ import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.HttpConstraintElement; import javax.servlet.HttpMethodConstraintElement; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.ServletSecurityElement; import javax.servlet.annotation.ServletSecurity.EmptyRoleSemantic; import javax.servlet.annotation.ServletSecurity.TransportGuarantee; import org.apache.catalina.Container; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleEvent; import org.apache.catalina.Wrapper; import org.apache.catalina.core.StandardContext; import org.apache.catalina.deploy.Multipart; import org.apache.catalina.deploy.jsp.FunctionInfo; import org.apache.catalina.deploy.jsp.TagAttributeInfo; import org.apache.catalina.deploy.jsp.TagFileInfo; import org.apache.catalina.deploy.jsp.TagInfo; import org.apache.catalina.deploy.jsp.TagLibraryInfo; import org.apache.catalina.deploy.jsp.TagLibraryValidatorInfo; import org.apache.catalina.deploy.jsp.TagVariableInfo; import org.apache.catalina.startup.ContextConfig; import org.apache.naming.resources.FileDirContext; import org.apache.naming.resources.ProxyDirContext; import org.jboss.annotation.javaee.Icon; import org.jboss.as.deployment.unit.DeploymentUnitContext; import org.jboss.logging.Logger; import org.jboss.metadata.javaee.spec.DescriptionGroupMetaData; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.javaee.spec.SecurityRoleMetaData; import org.jboss.metadata.javaee.spec.SecurityRoleRefMetaData; import org.jboss.metadata.javaee.spec.SecurityRoleRefsMetaData; import org.jboss.metadata.javaee.spec.SecurityRolesMetaData; import org.jboss.metadata.web.jboss.JBossAnnotationsMetaData; import org.jboss.metadata.web.jboss.JBossServletMetaData; import org.jboss.metadata.web.jboss.JBossServletsMetaData; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.metadata.web.spec.AnnotationMetaData; import org.jboss.metadata.web.spec.AttributeMetaData; import org.jboss.metadata.web.spec.AuthConstraintMetaData; import org.jboss.metadata.web.spec.CookieConfigMetaData; import org.jboss.metadata.web.spec.DispatcherType; import org.jboss.metadata.web.spec.ErrorPageMetaData; import org.jboss.metadata.web.spec.FilterMappingMetaData; import org.jboss.metadata.web.spec.FilterMetaData; import org.jboss.metadata.web.spec.FiltersMetaData; import org.jboss.metadata.web.spec.FunctionMetaData; import org.jboss.metadata.web.spec.HttpMethodConstraintMetaData; import org.jboss.metadata.web.spec.JspConfigMetaData; import org.jboss.metadata.web.spec.JspPropertyGroupMetaData; import org.jboss.metadata.web.spec.ListenerMetaData; import org.jboss.metadata.web.spec.LocaleEncodingMetaData; import org.jboss.metadata.web.spec.LocaleEncodingsMetaData; import org.jboss.metadata.web.spec.LoginConfigMetaData; import org.jboss.metadata.web.spec.MimeMappingMetaData; import org.jboss.metadata.web.spec.MultipartConfigMetaData; import org.jboss.metadata.web.spec.SecurityConstraintMetaData; import org.jboss.metadata.web.spec.ServletMappingMetaData; import org.jboss.metadata.web.spec.ServletSecurityMetaData; import org.jboss.metadata.web.spec.SessionConfigMetaData; import org.jboss.metadata.web.spec.SessionTrackingModeType; import org.jboss.metadata.web.spec.TagFileMetaData; import org.jboss.metadata.web.spec.TagMetaData; import org.jboss.metadata.web.spec.TaglibMetaData; import org.jboss.metadata.web.spec.TldMetaData; import org.jboss.metadata.web.spec.TransportGuaranteeType; import org.jboss.metadata.web.spec.VariableMetaData; import org.jboss.metadata.web.spec.WebResourceCollectionMetaData; import org.jboss.metadata.web.spec.WebResourceCollectionsMetaData; import org.jboss.metadata.web.spec.WelcomeFileListMetaData; import org.jboss.vfs.VirtualFile; /** * @author Remy Maucherat */ public class JBossContextConfig extends ContextConfig { private static Logger log = Logger.getLogger(JBossContextConfig.class); private DeploymentUnitContext deploymentUnitContext = null; private Set<String> overlays = new HashSet<String>(); private boolean runDestroy = false; /** * <p> * Creates a new instance of {@code JBossContextConfig}. * </p> */ public JBossContextConfig(DeploymentUnitContext deploymentUnitContext) { super(); this.deploymentUnitContext = deploymentUnitContext; try { Map authMap = this.getAuthenticators(); if (authMap.size() > 0) customAuthenticators = authMap; } catch (Exception e) { log.debug("Failed to load the customized authenticators", e); } // FIXME: Get that from config somewhere ? // runDestroy = deployerConfig.get().isDeleteWorkDirs(); } public void lifecycleEvent(LifecycleEvent event) { if (event.getType().equals(Lifecycle.AFTER_START_EVENT)) { // Invoke ServletContainerInitializer final ScisMetaData scisMetaData = deploymentUnitContext.getAttachment(ScisMetaData.ATTACHMENT_KEY); if (scisMetaData != null) { for (ServletContainerInitializer sci : scisMetaData.getScis()) { try { sci.onStartup(scisMetaData.getHandlesTypes().get(sci), context.getServletContext()); } catch (Throwable t) { log.error("Error calling onStartup for servlet container initializer: " + sci.getClass().getName(), t); ok = false; } } } // Post order final WarMetaData warMetaData = deploymentUnitContext.getAttachment(WarMetaData.ATTACHMENT_KEY); List<String> order = warMetaData.getOrder(); if (!warMetaData.isNoOrder()) { context.getServletContext().setAttribute(ServletContext.ORDERED_LIBS, order); } } super.lifecycleEvent(event); } protected void applicationWebConfig() { final WarMetaData warMetaData = deploymentUnitContext.getAttachment(WarMetaData.ATTACHMENT_KEY); processWebMetaData(warMetaData.getMergedJBossWebMetaData()); // processContextParameters(); } protected void defaultWebConfig() { JBossWebMetaData sharedJBossWebMetaData = new JBossWebMetaData(); final WarMetaData warMetaData = deploymentUnitContext.getAttachment(WarMetaData.ATTACHMENT_KEY); // FIXME: Default jboss-web.xml config sharedJBossWebMetaData.merge(null, warMetaData.getSharedWebMetaData()); processWebMetaData(sharedJBossWebMetaData); } protected void processWebMetaData(JBossWebMetaData metaData) { if (context instanceof StandardContext) { ((StandardContext) context).setReplaceWelcomeFiles(true); } // TODO remove that is a system propety in the next jbossweb version... context.setCrossContext(true); // Version context.setVersion(metaData.getVersion()); // SetPublicId if (metaData.is30()) context.setPublicId("/javax/servlet/resources/web-app_3_0.dtd"); else if (metaData.is25()) context.setPublicId("/javax/servlet/resources/web-app_2_5.dtd"); else if (metaData.is24()) context.setPublicId("/javax/servlet/resources/web-app_2_4.dtd"); else if (metaData.is23()) context.setPublicId(org.apache.catalina.startup.Constants.WebDtdPublicId_23); else context.setPublicId(org.apache.catalina.startup.Constants.WebDtdPublicId_22); // Display name DescriptionGroupMetaData dg = metaData.getDescriptionGroup(); if (dg != null) { String displayName = dg.getDisplayName(); if (displayName != null) { context.setDisplayName(displayName); } } // Distributable if (metaData.getDistributable() != null) context.setDistributable(true); // Context params List<ParamValueMetaData> contextParams = metaData.getContextParams(); if (contextParams != null) { for (ParamValueMetaData param : contextParams) { context.addParameter(param.getParamName(), param.getParamValue()); } } // Error pages List<ErrorPageMetaData> errorPages = metaData.getErrorPages(); if (errorPages != null) { for (ErrorPageMetaData value : errorPages) { org.apache.catalina.deploy.ErrorPage errorPage = new org.apache.catalina.deploy.ErrorPage(); errorPage.setErrorCode(value.getErrorCode()); errorPage.setExceptionType(value.getExceptionType()); errorPage.setLocation(value.getLocation()); context.addErrorPage(errorPage); } } // Filter definitions FiltersMetaData filters = metaData.getFilters(); if (filters != null) { for (FilterMetaData value : filters) { org.apache.catalina.deploy.FilterDef filterDef = new org.apache.catalina.deploy.FilterDef(); filterDef.setFilterName(value.getName()); filterDef.setFilterClass(value.getFilterClass()); if (value.getInitParam() != null) for (ParamValueMetaData param : value.getInitParam()) { filterDef.addInitParameter(param.getParamName(), param.getParamValue()); } filterDef.setAsyncSupported(value.isAsyncSupported()); context.addFilterDef(filterDef); } } // Filter mappings List<FilterMappingMetaData> filtersMappings = metaData.getFilterMappings(); if (filtersMappings != null) { for (FilterMappingMetaData value : filtersMappings) { org.apache.catalina.deploy.FilterMap filterMap = new org.apache.catalina.deploy.FilterMap(); filterMap.setFilterName(value.getFilterName()); List<String> servletNames = value.getServletNames(); if (servletNames != null) { for (String name : servletNames) filterMap.addServletName(name); } List<String> urlPatterns = value.getUrlPatterns(); if (urlPatterns != null) { for (String pattern : urlPatterns) filterMap.addURLPattern(pattern); } List<DispatcherType> dispatchers = value.getDispatchers(); if (dispatchers != null) { for (DispatcherType type : dispatchers) filterMap.setDispatcher(type.name()); } context.addFilterMap(filterMap); } } // Listeners List<ListenerMetaData> listeners = metaData.getListeners(); if (listeners != null) { for (ListenerMetaData value : listeners) { context.addApplicationListener(value.getListenerClass()); } } // Login configuration LoginConfigMetaData loginConfig = metaData.getLoginConfig(); if (loginConfig != null) { org.apache.catalina.deploy.LoginConfig loginConfig2 = new org.apache.catalina.deploy.LoginConfig(); loginConfig2.setAuthMethod(loginConfig.getAuthMethod()); loginConfig2.setRealmName(loginConfig.getRealmName()); if (loginConfig.getFormLoginConfig() != null) { loginConfig2.setLoginPage(loginConfig.getFormLoginConfig().getLoginPage()); loginConfig2.setErrorPage(loginConfig.getFormLoginConfig().getErrorPage()); } context.setLoginConfig(loginConfig2); } // MIME mappings List<MimeMappingMetaData> mimes = metaData.getMimeMappings(); if (mimes != null) { for (MimeMappingMetaData value : mimes) { context.addMimeMapping(value.getExtension(), value.getMimeType()); } } // Security constraints List<SecurityConstraintMetaData> scs = metaData.getSecurityConstraints(); if (scs != null) { for (SecurityConstraintMetaData value : scs) { org.apache.catalina.deploy.SecurityConstraint constraint = new org.apache.catalina.deploy.SecurityConstraint(); TransportGuaranteeType tg = value.getTransportGuarantee(); constraint.setUserConstraint(tg.name()); AuthConstraintMetaData acmd = value.getAuthConstraint(); constraint.setAuthConstraint(acmd != null); if (acmd != null) { if (acmd.getRoleNames() != null) for (String role : acmd.getRoleNames()) { constraint.addAuthRole(role); } } WebResourceCollectionsMetaData wrcs = value.getResourceCollections(); if (wrcs != null) { for (WebResourceCollectionMetaData wrc : wrcs) { org.apache.catalina.deploy.SecurityCollection collection2 = new org.apache.catalina.deploy.SecurityCollection(); collection2.setName(wrc.getName()); List<String> methods = wrc.getHttpMethods(); if (methods != null) { for (String method : wrc.getHttpMethods()) { collection2.addMethod(method); } } List<String> methodOmissions = wrc.getHttpMethodOmissions(); if (methodOmissions != null) { for (String method : wrc.getHttpMethodOmissions()) { collection2.addMethodOmission(method); } } List<String> patterns = wrc.getUrlPatterns(); if (patterns != null) { for (String pattern : patterns) { collection2.addPattern(pattern); } } constraint.addCollection(collection2); } } context.addConstraint(constraint); } } // Security roles SecurityRolesMetaData roles = metaData.getSecurityRoles(); if (roles != null) { for (SecurityRoleMetaData value : roles) { context.addSecurityRole(value.getRoleName()); } } // Servlet JBossServletsMetaData servlets = metaData.getServlets(); if (servlets != null) { for (JBossServletMetaData value : servlets) { org.apache.catalina.Wrapper wrapper = context.createWrapper(); wrapper.setName(value.getName()); wrapper.setServletClass(value.getServletClass()); if (value.getJspFile() != null) { wrapper.setJspFile(value.getJspFile()); } wrapper.setLoadOnStartup(value.getLoadOnStartupInt()); if (value.getRunAs() != null) { wrapper.setRunAs(value.getRunAs().getRoleName()); } List<ParamValueMetaData> params = value.getInitParam(); if (params != null) { for (ParamValueMetaData param : params) { wrapper.addInitParameter(param.getParamName(), param.getParamValue()); } } SecurityRoleRefsMetaData refs = value.getSecurityRoleRefs(); if (refs != null) { for (SecurityRoleRefMetaData ref : refs) { wrapper.addSecurityReference(ref.getRoleName(), ref.getRoleLink()); } } wrapper.setAsyncSupported(value.isAsyncSupported()); wrapper.setEnabled(value.isEnabled()); // Multipart configuration if (value.getMultipartConfig() != null) { MultipartConfigMetaData multipartConfigMetaData = value.getMultipartConfig(); Multipart multipartConfig = new Multipart(); multipartConfig.setLocation(multipartConfigMetaData.getLocation()); multipartConfig.setMaxRequestSize(multipartConfigMetaData.getMaxRequestSize()); multipartConfig.setMaxFileSize(multipartConfigMetaData.getMaxFileSize()); multipartConfig.setFileSizeThreshold(multipartConfigMetaData.getFileSizeThreshold()); wrapper.setMultipartConfig(multipartConfig); } context.addChild(wrapper); } } // Servlet mapping List<ServletMappingMetaData> smappings = metaData.getServletMappings(); if (smappings != null) { for (ServletMappingMetaData value : smappings) { List<String> urlPatterns = value.getUrlPatterns(); if (urlPatterns != null) { for (String pattern : urlPatterns) context.addServletMapping(pattern, value.getServletName()); } } } // JSP Config JspConfigMetaData config = metaData.getJspConfig(); if (config != null) { // JSP Property groups List<JspPropertyGroupMetaData> groups = config.getPropertyGroups(); if (groups != null) { for (JspPropertyGroupMetaData group : groups) { org.apache.catalina.deploy.JspPropertyGroup jspPropertyGroup = new org.apache.catalina.deploy.JspPropertyGroup(); for (String pattern : group.getUrlPatterns()) { jspPropertyGroup.addUrlPattern(pattern); } jspPropertyGroup.setElIgnored(group.getElIgnored()); jspPropertyGroup.setPageEncoding(group.getPageEncoding()); jspPropertyGroup.setScriptingInvalid(group.getScriptingInvalid()); jspPropertyGroup.setIsXml(group.getIsXml()); if (group.getIncludePreludes() != null) { for (String includePrelude : group.getIncludePreludes()) { jspPropertyGroup.addIncludePrelude(includePrelude); } } if (group.getIncludeCodas() != null) { for (String includeCoda : group.getIncludeCodas()) { jspPropertyGroup.addIncludeCoda(includeCoda); } } jspPropertyGroup.setDeferredSyntaxAllowedAsLiteral(group.getDeferredSyntaxAllowedAsLiteral()); jspPropertyGroup.setTrimDirectiveWhitespaces(group.getTrimDirectiveWhitespaces()); jspPropertyGroup.setDefaultContentType(group.getDefaultContentType()); jspPropertyGroup.setBuffer(group.getBuffer()); jspPropertyGroup.setErrorOnUndeclaredNamespace(group.getErrorOnUndeclaredNamespace()); context.addJspPropertyGroup(jspPropertyGroup); } } // Taglib List<TaglibMetaData> taglibs = config.getTaglibs(); if (taglibs != null) { for (TaglibMetaData taglib : taglibs) { context.addTaglib(taglib.getTaglibUri(), taglib.getTaglibLocation()); } } } // Locale encoding mapping LocaleEncodingsMetaData locales = metaData.getLocalEncodings(); if (locales != null) { for (LocaleEncodingMetaData value : locales.getMappings()) { context.addLocaleEncodingMappingParameter(value.getLocale(), value.getEncoding()); } } // Welcome files WelcomeFileListMetaData welcomeFiles = metaData.getWelcomeFileList(); if (welcomeFiles != null) { for (String value : welcomeFiles.getWelcomeFiles()) context.addWelcomeFile(value); } // Session timeout SessionConfigMetaData scmd = metaData.getSessionConfig(); if (scmd != null) { context.setSessionTimeout(scmd.getSessionTimeout()); if (scmd.getSessionTrackingModes() != null) { for (SessionTrackingModeType stmt : scmd.getSessionTrackingModes()) { context.addSessionTrackingMode(stmt.toString()); } } if (scmd.getCookieConfig() != null) { CookieConfigMetaData value = scmd.getCookieConfig(); org.apache.catalina.deploy.SessionCookie cookieConfig = new org.apache.catalina.deploy.SessionCookie(); cookieConfig.setName(value.getName()); cookieConfig.setDomain(value.getDomain()); cookieConfig.setPath(value.getPath()); cookieConfig.setComment(value.getComment()); cookieConfig.setHttpOnly(value.getHttpOnly()); cookieConfig.setSecure(value.getSecure()); cookieConfig.setMaxAge(value.getMaxAge()); context.setSessionCookie(cookieConfig); } } } /** * <p> * Retrieves the map of authenticators according to the settings made * available by {@code TomcatService}. * </p> * * @return a {@code Map} containing the authenticator that must be used for * each authentication method. * @throws Exception if an error occurs while getting the authenticators. */ protected Map getAuthenticators() throws Exception { Map authenticators = new HashMap(); ClassLoader tcl = Thread.currentThread().getContextClassLoader(); Properties authProps = this.getAuthenticatorsFromJndi(); if (authProps != null) { Set keys = authProps.keySet(); Iterator iter = keys != null ? keys.iterator() : null; while (iter != null && iter.hasNext()) { String key = (String) iter.next(); String authenticatorStr = (String) authProps.get(key); Class authClass = tcl.loadClass(authenticatorStr); authenticators.put(key, authClass.newInstance()); } } if (log.isTraceEnabled()) log.trace("Authenticators plugged in::" + authenticators); return authenticators; } /** * <p> * Get the key-pair of authenticators from the JNDI. * </p> * * @return a {@code Properties} object containing the authenticator class * name for each authentication method. * @throws NamingException if an error occurs while looking up the JNDI. */ private Properties getAuthenticatorsFromJndi() throws NamingException { return (Properties) new InitialContext().lookup("TomcatAuthenticators"); } /** * Process the context parameters. Let a user application override the * sharedMetaData values. */ // FIXME: Make sure processContextParameters is really useless ... /** * Process a "init" event for this Context. */ protected void init() { context.setConfigured(false); ok = true; if (!context.getOverride()) { processContextConfig("context.xml", false); processContextConfig(getHostConfigPath(org.apache.catalina.startup.Constants.HostContextXml), false); } // This should come from the deployment unit processContextConfig("WEB-INF/context.xml", true); } protected void processContextConfig(String resourceName, boolean local) { // FIXME: Implement context.xml again ? } protected void destroy() { if (runDestroy) { super.destroy(); } } /** * Migrate TLD metadata to Catalina. This is separate, and is not subject to * the order defined. */ protected void applicationTldConfig() { final TldsMetaData tldsMetaData = deploymentUnitContext.getAttachment(TldsMetaData.ATTACHMENT_KEY); if (tldsMetaData == null) { return; } Map<String, TldMetaData> localTlds = tldsMetaData.getTlds(); List<TldMetaData> sharedTlds = tldsMetaData.getSharedTlds(); ArrayList<TagLibraryInfo> tagLibraries = new ArrayList<TagLibraryInfo>(); for (String location : localTlds.keySet()) { processTld(tagLibraries, location, localTlds.get(location)); } for (TldMetaData sharedTld : sharedTlds) { processTld(tagLibraries, null, sharedTld); } // Add additional TLDs URIs from explicit web config String[] taglibs = context.findTaglibs(); for (int i = 0; i < taglibs.length; i++) { String uri = taglibs[i]; String path = context.findTaglib(taglibs[i]); String location = ""; if (path.indexOf(':') == -1 && !path.startsWith("/")) { path = "/WEB-INF/" + path; } if (path.endsWith(".jar")) { location = path; path = "META-INF/taglib.tld"; } for (int j = 0; j < tagLibraries.size(); j++) { TagLibraryInfo tagLibraryInfo = tagLibraries.get(j); if (tagLibraryInfo.getLocation().equals(location) && tagLibraryInfo.getPath().equals(path)) { context.addJspTagLibrary(uri, tagLibraryInfo); } } } } protected void processTld(ArrayList<TagLibraryInfo> tagLibraries, String location, TldMetaData tldMetaData) { String relativeLocation = location; String jarPath = null; if (relativeLocation.startsWith("/WEB-INF/lib/")) { int pos = relativeLocation.indexOf('/', "/WEB-INF/lib/".length()); if (pos > 0) { jarPath = relativeLocation.substring(pos); if (jarPath.startsWith("/")) { jarPath = jarPath.substring(1); } relativeLocation = relativeLocation.substring(0, pos); } } TagLibraryInfo tagLibraryInfo = new TagLibraryInfo(); tagLibraryInfo.setTlibversion(tldMetaData.getTlibVersion()); if (tldMetaData.getJspVersion() == null) tagLibraryInfo.setJspversion(tldMetaData.getVersion()); else tagLibraryInfo.setJspversion(tldMetaData.getJspVersion()); tagLibraryInfo.setShortname(tldMetaData.getShortName()); tagLibraryInfo.setUri(tldMetaData.getUri()); if (tldMetaData.getDescriptionGroup() != null) { tagLibraryInfo.setInfo(tldMetaData.getDescriptionGroup().getDescription()); } // Listener if (tldMetaData.getListeners() != null) { for (ListenerMetaData listener : tldMetaData.getListeners()) { tagLibraryInfo.addListener(listener.getListenerClass()); } } // Validator if (tldMetaData.getValidator() != null) { TagLibraryValidatorInfo tagLibraryValidatorInfo = new TagLibraryValidatorInfo(); tagLibraryValidatorInfo.setValidatorClass(tldMetaData.getValidator().getValidatorClass()); if (tldMetaData.getValidator().getInitParams() != null) { for (ParamValueMetaData paramValueMetaData : tldMetaData.getValidator().getInitParams()) { tagLibraryValidatorInfo.addInitParam(paramValueMetaData.getParamName(), paramValueMetaData.getParamValue()); } } tagLibraryInfo.setValidator(tagLibraryValidatorInfo); } // Tag if (tldMetaData.getTags() != null) { for (TagMetaData tagMetaData : tldMetaData.getTags()) { TagInfo tagInfo = new TagInfo(); tagInfo.setTagName(tagMetaData.getName()); tagInfo.setTagClassName(tagMetaData.getTagClass()); tagInfo.setTagExtraInfo(tagMetaData.getTeiClass()); if (tagMetaData.getBodyContent() != null) tagInfo.setBodyContent(tagMetaData.getBodyContent().toString()); tagInfo.setDynamicAttributes(tagMetaData.getDynamicAttributes()); // Description group if (tagMetaData.getDescriptionGroup() != null) { DescriptionGroupMetaData descriptionGroup = tagMetaData.getDescriptionGroup(); if (descriptionGroup.getIcons() != null && descriptionGroup.getIcons().value() != null && (descriptionGroup.getIcons().value().length > 0)) { Icon icon = descriptionGroup.getIcons().value()[0]; tagInfo.setLargeIcon(icon.largeIcon()); tagInfo.setSmallIcon(icon.smallIcon()); } tagInfo.setInfoString(descriptionGroup.getDescription()); tagInfo.setDisplayName(descriptionGroup.getDisplayName()); } // Variable if (tagMetaData.getVariables() != null) { for (VariableMetaData variableMetaData : tagMetaData.getVariables()) { TagVariableInfo tagVariableInfo = new TagVariableInfo(); tagVariableInfo.setNameGiven(variableMetaData.getNameGiven()); tagVariableInfo.setNameFromAttribute(variableMetaData.getNameFromAttribute()); tagVariableInfo.setClassName(variableMetaData.getVariableClass()); tagVariableInfo.setDeclare(variableMetaData.getDeclare()); if (variableMetaData.getScope() != null) tagVariableInfo.setScope(variableMetaData.getScope().toString()); tagInfo.addTagVariableInfo(tagVariableInfo); } } // Attribute if (tagMetaData.getAttributes() != null) { for (AttributeMetaData attributeMetaData : tagMetaData.getAttributes()) { TagAttributeInfo tagAttributeInfo = new TagAttributeInfo(); tagAttributeInfo.setName(attributeMetaData.getName()); tagAttributeInfo.setType(attributeMetaData.getType()); tagAttributeInfo.setReqTime(attributeMetaData.getRtexprvalue()); tagAttributeInfo.setRequired(attributeMetaData.getRequired()); tagAttributeInfo.setFragment(attributeMetaData.getFragment()); if (attributeMetaData.getDeferredValue() != null) { tagAttributeInfo.setDeferredValue("true"); tagAttributeInfo.setExpectedTypeName(attributeMetaData.getDeferredValue().getType()); } else { tagAttributeInfo.setDeferredValue("false"); } if (attributeMetaData.getDeferredMethod() != null) { tagAttributeInfo.setDeferredMethod("true"); tagAttributeInfo.setMethodSignature(attributeMetaData.getDeferredMethod().getMethodSignature()); } else { tagAttributeInfo.setDeferredMethod("false"); } tagInfo.addTagAttributeInfo(tagAttributeInfo); } } tagLibraryInfo.addTagInfo(tagInfo); } } // Tag files if (tldMetaData.getTagFiles() != null) { for (TagFileMetaData tagFileMetaData : tldMetaData.getTagFiles()) { TagFileInfo tagFileInfo = new TagFileInfo(); tagFileInfo.setName(tagFileMetaData.getName()); tagFileInfo.setPath(tagFileMetaData.getPath()); tagLibraryInfo.addTagFileInfo(tagFileInfo); } } // Function if (tldMetaData.getFunctions() != null) { for (FunctionMetaData functionMetaData : tldMetaData.getFunctions()) { FunctionInfo functionInfo = new FunctionInfo(); functionInfo.setName(functionMetaData.getName()); functionInfo.setFunctionClass(functionMetaData.getFunctionClass()); functionInfo.setFunctionSignature(functionMetaData.getFunctionSignature()); tagLibraryInfo.addFunctionInfo(functionInfo); } } if (jarPath == null && relativeLocation == null) { context.addJspTagLibrary(tagLibraryInfo); } else if (jarPath == null) { tagLibraryInfo.setLocation(""); tagLibraryInfo.setPath(relativeLocation); tagLibraries.add(tagLibraryInfo); context.addJspTagLibrary(tagLibraryInfo); context.addJspTagLibrary(relativeLocation, tagLibraryInfo); } else { tagLibraryInfo.setLocation(relativeLocation); tagLibraryInfo.setPath(jarPath); tagLibraries.add(tagLibraryInfo); context.addJspTagLibrary(tagLibraryInfo); if (jarPath.equals("META-INF/taglib.tld")) { context.addJspTagLibrary(relativeLocation, tagLibraryInfo); } } } public void applicationServletContainerInitializerConfig() { // Do nothing here } protected void createFragmentsOrder() { // Do nothing here } protected void applicationExtraDescriptorsConfig() { // Do nothing here } protected void resolveAnnotations(JBossAnnotationsMetaData annotations) { if (annotations != null) { for (AnnotationMetaData annotation : annotations) { String className = annotation.getClassName(); Container[] wrappers = context.findChildren(); for (int i = 0; i < wrappers.length; i++) { Wrapper wrapper = (Wrapper) wrappers[i]; if (className.equals(wrapper.getServletClass())) { // Merge @RunAs if (annotation.getRunAs() != null && wrapper.getRunAs() == null) { wrapper.setRunAs(annotation.getRunAs().getRoleName()); } // Merge @MultipartConfig if (annotation.getMultipartConfig() != null && wrapper.getMultipartConfig() == null) { MultipartConfigMetaData multipartConfigMetaData = annotation.getMultipartConfig(); Multipart multipartConfig = new Multipart(); multipartConfig.setLocation(multipartConfigMetaData.getLocation()); multipartConfig.setMaxRequestSize(multipartConfigMetaData.getMaxRequestSize()); multipartConfig.setMaxFileSize(multipartConfigMetaData.getMaxFileSize()); multipartConfig.setFileSizeThreshold(multipartConfigMetaData.getFileSizeThreshold()); wrapper.setMultipartConfig(multipartConfig); } // Merge @ServletSecurity if (annotation.getServletSecurity() != null && wrapper.getServletSecurity() == null) { ServletSecurityMetaData servletSecurityAnnotation = annotation.getServletSecurity(); Collection<HttpMethodConstraintElement> methodConstraints = null; EmptyRoleSemantic emptyRoleSemantic = EmptyRoleSemantic.PERMIT; if (servletSecurityAnnotation.getEmptyRoleSemantic() != null) { emptyRoleSemantic = EmptyRoleSemantic.valueOf(servletSecurityAnnotation.getEmptyRoleSemantic() .toString()); } TransportGuarantee transportGuarantee = TransportGuarantee.NONE; if (servletSecurityAnnotation.getTransportGuarantee() != null) { transportGuarantee = TransportGuarantee.valueOf(servletSecurityAnnotation .getTransportGuarantee().toString()); } String[] roleNames = servletSecurityAnnotation.getRolesAllowed().toArray(new String[0]); HttpConstraintElement constraint = new HttpConstraintElement(emptyRoleSemantic, transportGuarantee, roleNames); if (servletSecurityAnnotation.getHttpMethodConstraints() != null) { methodConstraints = new HashSet<HttpMethodConstraintElement>(); for (HttpMethodConstraintMetaData annotationMethodConstraint : servletSecurityAnnotation .getHttpMethodConstraints()) { emptyRoleSemantic = EmptyRoleSemantic.PERMIT; if (annotationMethodConstraint.getEmptyRoleSemantic() != null) { emptyRoleSemantic = EmptyRoleSemantic.valueOf(annotationMethodConstraint .getEmptyRoleSemantic().toString()); } transportGuarantee = TransportGuarantee.NONE; if (annotationMethodConstraint.getTransportGuarantee() != null) { transportGuarantee = TransportGuarantee.valueOf(annotationMethodConstraint .getTransportGuarantee().toString()); } roleNames = annotationMethodConstraint.getRolesAllowed().toArray(new String[0]); HttpConstraintElement constraint2 = new HttpConstraintElement(emptyRoleSemantic, transportGuarantee, roleNames); HttpMethodConstraintElement methodConstraint = new HttpMethodConstraintElement( annotationMethodConstraint.getMethod(), constraint2); methodConstraints.add(methodConstraint); } } ServletSecurityElement servletSecurity = new ServletSecurityElement(constraint, methodConstraints); wrapper.setServletSecurity(servletSecurity); } } } } } } // FIXME: Support JBoss managers ... protected void completeConfig() { final WarMetaData warMetaData = deploymentUnitContext.getAttachment(WarMetaData.ATTACHMENT_KEY); JBossWebMetaData metaData = warMetaData.getMergedJBossWebMetaData(); // Process Servlet API related annotations that were dependent on // Servlet declarations if (ok && (metaData != null)) { // Resolve type specific annotations to their corresponding Servlet // components metaData.resolveAnnotations(); // Same process for Catalina resolveAnnotations(metaData.getAnnotations()); } if (ok) { resolveServletSecurity(); } if (ok) { validateSecurityRoles(); } if (ok && (metaData != null)) { // Resolve run as metaData.resolveRunAs(); } // Configure an authenticator if we need one if (ok) { authenticatorConfig(); } // Find and configure overlays if (ok) { Set<VirtualFile> overlays = warMetaData.getOverlays(); if (overlays != null) { if (context.getResources() instanceof ProxyDirContext) { ProxyDirContext resources = (ProxyDirContext) context.getResources(); for (VirtualFile overlay : overlays) { FileDirContext dirContext = new FileDirContext(); try { dirContext.setDocBase(overlay.getPhysicalFile().getAbsolutePath()); resources.addOverlay(dirContext); } catch (IOException e) { log.error(sm.getString("contextConfig.noOverlay", context.getName()), e); ok = false; break; } } } else if (overlays.size() > 0) { // Error, overlays need a ProxyDirContext to compose results log.error(sm.getString("contextConfig.noOverlay", context.getName())); ok = false; } } } // Add other overlays, if any if (ok) { for (String overlay : overlays) { if (context.getResources() instanceof ProxyDirContext) { ProxyDirContext resources = (ProxyDirContext) context.getResources(); FileDirContext dirContext = new FileDirContext(); dirContext.setDocBase(overlay); resources.addOverlay(dirContext); } } } // Make our application unavailable if problems were encountered if (!ok) { log.error(sm.getString("contextConfig.unavailable")); context.setConfigured(false); } } }
package org.zanata.common; import java.io.Serializable; public class TransUnitWords implements Serializable { private static final long serialVersionUID = 1L; private int approved; private int needReview; private int untranslated; public TransUnitWords() { } public TransUnitWords(int approved, int needReview, int untranslated) { this.approved = approved; this.needReview = needReview; this.untranslated = untranslated; } public void increment(ContentState state, int count) { set(state, get(state) + count); } public void decrement(ContentState state, int count) { set(state, get(state) - count); } public void set(ContentState state, int value) { switch (state) { case Approved: approved = value; break; case NeedReview: needReview = value; break; case New: untranslated = value; break; default: throw new RuntimeException("not implemented for state " + state.name()); } } public int get(ContentState state) { switch (state) { case Approved: return approved; case NeedReview: return needReview; case New: return untranslated; default: throw new RuntimeException("not implemented for state " + state.name()); } } public void add(TransUnitWords other) { this.approved += other.approved; this.needReview += other.needReview; this.untranslated += other.untranslated; } public void set(TransUnitWords other) { this.approved = other.approved; this.needReview = other.needReview; this.untranslated = other.untranslated; } public int getTotal() { return approved + needReview + untranslated; } public int getApproved() { return approved; } public int getNeedReview() { return needReview; } public int getUntranslated() { return untranslated; } public int getNotApproved() { return untranslated + needReview; } public int getPer() { int total = getTotal(); if (total <= 0) { return 0; } else { double per = 100 * approved / total; return (int) Math.ceil(per); } } }
package dao; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.RollbackException; public class JpaUtil { public static final String PERSISTENCE_UNIT_NAME = "XXXXXXXXX-Moodle-PU"; private static EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME); private static final ThreadLocal<EntityManager> threadLocalEntityManager = new ThreadLocal<EntityManager>() { @Override protected EntityManager initialValue() { return null; } }; // Pause (sans exception) private static void pause(long milliseconds) { try { Thread.sleep(milliseconds); } catch (InterruptedException ex) { } } // Log sur la console private static void log(String message) { System.out.flush(); pause(5); System.err.println("[JpaUtil:Log] " + message); System.err.flush(); pause(5); } public static synchronized void init() { log("Initialisation de la factory de contexte de persistance"); if (entityManagerFactory != null) { entityManagerFactory.close(); } entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME); } public static synchronized void destroy() { log("Libération de la factory de contexte de persistance"); if (entityManagerFactory != null) { entityManagerFactory.close(); entityManagerFactory = null; } } public static void creerEntityManager() { log("Création du contexte de persistance"); threadLocalEntityManager.set(entityManagerFactory.createEntityManager()); } public static void fermerEntityManager() { log("Fermeture du contexte de persistance"); EntityManager em = threadLocalEntityManager.get(); em.close(); threadLocalEntityManager.set(null); } public static void ouvrirTransaction() { log("Début de la transaction"); EntityManager em = threadLocalEntityManager.get(); if (em.getTransaction().isActive()) { log("ATTENTION: la transaction est déjà ouverte"); } em.getTransaction().begin(); } public static void validerTransaction() throws RollbackException { log("Validation (commit) de la transaction"); EntityManager em = threadLocalEntityManager.get(); if (!em.getTransaction().isActive()) { log("ATTENTION: la transaction N'est PAS ouverte"); } em.getTransaction().commit(); } public static void annulerTransaction() { log("Annulation (rollback) de la transaction"); EntityManager em = threadLocalEntityManager.get(); if (!em.getTransaction().isActive()) { log("ATTENTION: la transaction N'est PAS ouverte => annulation ignorée par JpaUtil"); } else { em.getTransaction().rollback(); } } public static EntityManager obtenirEntityManager() { log("Obtention du contexte de persistance"); return threadLocalEntityManager.get(); } }
package org.usfirst.frc4915.ArcadeDriveRobot; /** * * @author Tarkan */ public class Version { private static final String VERSION = "v1.08.10"; // Adds IntakeDown and IntakeUp commands // Adds Magnetic Switch // Changed buttons on Joystick to activate the Intake Down and Intake Up instead of Extend/Retract Pneumatics // Fixed exceptions when there is no gyroscope (again) // Added turnPID(double angle) which turns the robot using PID control (fixes) // Testable turnPID(angle) // Version system changed // PID ratios altered // Throttle values updated when robot is stopped public static String getVersion() { return VERSION; } }
package org.xdi.oxauth.ws.rs; import org.testng.Assert; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import org.xdi.oxauth.BaseTest; import org.xdi.oxauth.client.BaseRequest; import org.xdi.oxauth.client.service.ClientFactory; import org.xdi.oxauth.client.service.IntrospectionService; import org.xdi.oxauth.client.uma.wrapper.UmaClient; import org.xdi.oxauth.model.common.IntrospectionResponse; import org.xdi.oxauth.model.uma.wrapper.Token; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; /** * @author Yuriy Zabrovarnyy * @version 0.9, 17/09/2013 */ public class IntrospectionWsHttpTest extends BaseTest { @Test @Parameters({"umaPatClientId", "umaPatClientSecret"}) public void bearer(final String umaPatClientId, final String umaPatClientSecret) throws Exception { final Token authorization = UmaClient.requestPat(tokenEndpoint, umaPatClientId, umaPatClientSecret); final Token tokenToIntrospect = UmaClient.requestPat(tokenEndpoint, umaPatClientId, umaPatClientSecret); final IntrospectionService introspectionService = ClientFactory.instance().createIntrospectionService(introspectionEndpoint); final IntrospectionResponse introspectionResponse = introspectionService.introspectToken("Bearer " + authorization.getAccessToken(), tokenToIntrospect.getAccessToken()); Assert.assertTrue(introspectionResponse != null && introspectionResponse.isActive()); } @Test @Parameters({"umaPatClientId", "umaPatClientSecret"}) public void basicAuthentication(final String umaPatClientId, final String umaPatClientSecret) throws Exception { final Token tokenToIntrospect = UmaClient.requestPat(tokenEndpoint, umaPatClientId, umaPatClientSecret, clientExecutor(true)); final IntrospectionService introspectionService = ClientFactory.instance().createIntrospectionService(introspectionEndpoint, clientExecutor(true)); final IntrospectionResponse introspectionResponse = introspectionService.introspectToken("Basic " + BaseRequest.getEncodedCredentials(umaPatClientId, umaPatClientSecret), tokenToIntrospect.getAccessToken()); Assert.assertTrue(introspectionResponse != null && introspectionResponse.isActive()); } @Test @Parameters({"umaPatClientId", "umaPatClientSecret"}) public void introspectWithValidAuthorizationButInvalidTokenShouldReturnActiveFalse(final String umaPatClientId, final String umaPatClientSecret) throws Exception { final Token authorization = UmaClient.requestPat(tokenEndpoint, umaPatClientId, umaPatClientSecret, clientExecutor(true)); final IntrospectionService introspectionService = ClientFactory.instance().createIntrospectionService(introspectionEndpoint, clientExecutor(true)); final IntrospectionResponse introspectionResponse = introspectionService.introspectToken("Bearer " + authorization.getAccessToken(), "invalid_token"); assertNotNull(introspectionResponse); assertFalse(introspectionResponse.isActive()); } }
package ru.matevosyan; public class EvenNumber implements ArrayIterator { private int index = 0; private int j = 0; private final int[] array; /** * EvenNumber constructor. * @param array an array. */ public EvenNumber(int[] array) { this.array = array; } /** * Override the next() method to iterate each element from an array. * @return even numbers from an array. */ @Override public int next() { int value = 0; for (int i = index++; i < array.length; i++) { if (array[i] % 2 == 0) { value = i; break; } else { index++; } } return array[value]; } /** * Override hasNext() method to check if eny of elements are in array to read, looking to next() pointer. * @return true if there are any elements to read, else return false. */ @Override public boolean hasNext() { return array.length > index; } }
package org.glob3.mobile.generated; // MarksRenderer.cpp // G3MiOSSDK // MarksRenderer.hpp // G3MiOSSDK //class Mark; //class Camera; //class MarkTouchListener; public class MarksRenderer extends LeafRenderer { private final boolean _readyWhenMarksReady; private java.util.ArrayList<Mark> _marks = new java.util.ArrayList<Mark>(); private G3MContext _context; private Camera _lastCamera; private MarkTouchListener _markTouchListener; private boolean _autoDeleteMarkTouchListener; private long _downloadPriority = 1000000; public MarksRenderer(boolean readyWhenMarksReady) { _readyWhenMarksReady = readyWhenMarksReady; _context = null; _lastCamera = null; _markTouchListener = null; _autoDeleteMarkTouchListener = false; } public final void setMarkTouchListener(MarkTouchListener markTouchListener, boolean autoDelete) { if (_autoDeleteMarkTouchListener) { if (_markTouchListener != null) _markTouchListener.dispose(); } _markTouchListener = markTouchListener; _autoDeleteMarkTouchListener = autoDelete; } public void dispose() { int marksSize = _marks.size(); for (int i = 0; i < marksSize; i++) { if (_marks.get(i) != null) _marks.get(i).dispose(); } if (_autoDeleteMarkTouchListener) { if (_markTouchListener != null) _markTouchListener.dispose(); } _markTouchListener = null; } public void initialize(G3MContext context) { _context = context; int marksSize = _marks.size(); for (int i = 0; i < marksSize; i++) { Mark mark = _marks.get(i); mark.initialize(context, _downloadPriority); } } public void render(G3MRenderContext rc, GLState parentState) { // rc.getLogger()->logInfo("MarksRenderer::render()"); // Saving camera for use in onTouchEvent _lastCamera = rc.getCurrentCamera(); GL gl = rc.getGL(); GLState state = new GLState(parentState); state.disableDepthTest(); state.enableBlend(); state.enableTextures(); state.enableTexture2D(); state.enableVerticesPosition(); gl.setState(state); Vector2D textureTranslation = new Vector2D(0.0, 0.0); Vector2D textureScale = new Vector2D(1.0, 1.0); gl.transformTexCoords(textureScale, textureTranslation); gl.setBlendFuncSrcAlpha(); final Camera camera = rc.getCurrentCamera(); gl.startBillBoardDrawing(camera.getWidth(), camera.getHeight()); final int marksSize = _marks.size(); for (int i = 0; i < marksSize; i++) { Mark mark = _marks.get(i); //rc->getLogger()->logInfo("Rendering Mark: \"%s\"", mark->getName().c_str()); if (mark.isReady()) { mark.render(rc); } } gl.stopBillBoardDrawing(); } public final void addMark(Mark mark) { _marks.add(mark); if (_context != null) { mark.initialize(_context, _downloadPriority); } } public final void removeMark(Mark mark) { int pos = -1; final int marksSize = _marks.size(); for (int i = 0; i < marksSize; i++) { if (_marks.get(i) == mark) { pos = i; break; } } if (pos != -1) { _marks.remove(pos); } } public final void removeAllMarks() { final int marksSize = _marks.size(); for (int i = 0; i < marksSize; i++) { if (_marks.get(i) != null) _marks.get(i).dispose(); } _marks.clear(); } public final boolean onTouchEvent(G3MEventContext ec, TouchEvent touchEvent) { boolean handled = false; if ((touchEvent.getType() == TouchEventType.Down) && (touchEvent.getTouchCount() == 1)) { if (_lastCamera != null) { final Vector2I touchedPixel = touchEvent.getTouch(0).getPos(); final Planet planet = ec.getPlanet(); double minSqDistance = IMathUtils.instance().maxDouble(); Mark nearestMark = null; final int marksSize = _marks.size(); for (int i = 0; i < marksSize; i++) { Mark mark = _marks.get(i); if (!mark.isReady()) { continue; } if (!mark.isRendered()) { continue; } final int textureWidth = mark.getTextureWidth(); if (textureWidth <= 0) { continue; } final int textureHeight = mark.getTextureHeight(); if (textureHeight <= 0) { continue; } final Vector3D cartesianMarkPosition = mark.getCartesianPosition(planet); final Vector2I markPixel = _lastCamera.point2Pixel(cartesianMarkPosition); final RectangleI markPixelBounds = new RectangleI(markPixel._x - (textureWidth / 2), markPixel._y - (textureHeight / 2), textureWidth, textureHeight); if (markPixelBounds.contains(touchedPixel._x, touchedPixel._y)) { final double distance = markPixel.sub(touchedPixel).squaredLength(); if (distance < minSqDistance) { nearestMark = mark; minSqDistance = distance; } } } if (nearestMark != null) { handled = nearestMark.touched(); if (!handled) { if (_markTouchListener != null) { handled = _markTouchListener.touchedMark(nearestMark); } } } } } return handled; } public final void onResizeViewportEvent(G3MEventContext ec, int width, int height) { } public final boolean isReadyToRender(G3MRenderContext rc) { if (_readyWhenMarksReady) { int marksSize = _marks.size(); for (int i = 0; i < marksSize; i++) { if (!_marks.get(i).isReady()) { return false; } } } return true; } public final void start() { } public final void stop() { } public final void onResume(G3MContext context) { _context = context; } public final void onPause(G3MContext context) { } public final void onDestroy(G3MContext context) { } /** Change the download-priority used by Marks (for downloading textures). Default value is 1000000 */ public final void setDownloadPriority(long downloadPriority) { _downloadPriority = downloadPriority; } public final long getDownloadPriority() { return _downloadPriority; } }
package com.parrot.arsdk.ardiscovery; import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; import com.parrot.arsdk.arsal.ARSALPrint; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.os.Handler; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.content.BroadcastReceiver; import android.annotation.TargetApi; public class ARDiscoveryBLEDiscoveryImpl implements ARDiscoveryBLEDiscovery { private static final String TAG = ARDiscoveryBLEDiscoveryImpl.class.getSimpleName(); private static final int ARDISCOVERY_BT_VENDOR_ID = 0x0043; /* Parrot Company ID registered by Bluetooth SIG (Bluetooth Specification v4.0 Requirement) */ private static final int ARDISCOVERY_USB_VENDOR_ID = 0x19cf; /* official Parrot USB Vendor ID */ private final Set<ARDISCOVERY_PRODUCT_ENUM> supportedProducts; private boolean bleIsAvailable; private BluetoothAdapter bluetoothAdapter; private BLEScanner bleScanner; private HashMap<String, ARDiscoveryDeviceService> bleDeviceServicesHmap; private Object leScanCallback;/*< Device scan callback. (BluetoothAdapter.LeScanCallback) */ private IntentFilter networkStateChangedFilter; private BroadcastReceiver networkStateIntentReceiver; private Handler mHandler; private ARDiscoveryService broadcaster; private Context context; private boolean opened; private Boolean isLeDiscovering = false; private Boolean askForLeDiscovering = false; public ARDiscoveryBLEDiscoveryImpl(Set<ARDISCOVERY_PRODUCT_ENUM> supportedProducts) { ARSALPrint.w(TAG,"ARDiscoveryBLEDiscoveryImpl new !!!!"); this.supportedProducts = supportedProducts; opened = false; bleDeviceServicesHmap = new HashMap<String, ARDiscoveryDeviceService> (); networkStateChangedFilter = new IntentFilter(); networkStateChangedFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); networkStateIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { ARSALPrint.d(TAG,"BroadcastReceiver onReceive"); if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { ARSALPrint.d(TAG,"ACTION_STATE_CHANGED"); if (bleIsAvailable) { int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); switch (state) { case BluetoothAdapter.STATE_ON: if (askForLeDiscovering) { bleConnect(); askForLeDiscovering = false; } break; case BluetoothAdapter.STATE_TURNING_OFF: /* remove all BLE services */ bleDeviceServicesHmap.clear(); /* broadcast the new deviceServiceList */ if(broadcaster != null) { broadcaster.broadcastDeviceServiceArrayUpdated (); } if(isLeDiscovering) { askForLeDiscovering = true; } bleDisconnect(); /* remove all BLE services */ bleDeviceServicesHmap.clear(); /* broadcast the new deviceServiceList */ if(broadcaster != null) { broadcaster.broadcastDeviceServiceArrayUpdated (); } break; } } } } }; } @Override public synchronized void open(ARDiscoveryService broadcaster, Context c) { ARSALPrint.d(TAG, "Open BLE"); this.broadcaster = broadcaster; this.context = c; if (opened) { return; } mHandler = new Handler(); bleDeviceServicesHmap = new HashMap<String, ARDiscoveryDeviceService> (); bleIsAvailable = false; getBLEAvailability(); if (bleIsAvailable) { initBLE(); } context.registerReceiver(networkStateIntentReceiver, networkStateChangedFilter); opened = true; } @Override public synchronized void close() { ARSALPrint.d(TAG, "Close BLE"); if (! opened) { return; } mHandler.removeCallbacksAndMessages(null); context.unregisterReceiver(networkStateIntentReceiver); if (this.bleIsAvailable) { bleDisconnect(); } this.context = null; this.broadcaster = null; opened = false; } private void update() { if ((bleIsAvailable == true) && bluetoothAdapter.isEnabled()) { bleConnect(); } else { bleDisconnect(); } } @Override public void start() { if (!isLeDiscovering) { if ((bleIsAvailable == true) && bluetoothAdapter.isEnabled()) { bleConnect(); isLeDiscovering = true; } else { askForLeDiscovering = true; } } } @Override public void stop() { if (isLeDiscovering) { /* Stop BLE scan */ bleDisconnect(); isLeDiscovering = false; } } private void getBLEAvailability() { /* check whether BLE is supported on the device */ if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { ARSALPrint.d(TAG,"BLE Is NOT Available"); bleIsAvailable = false; } else { ARSALPrint.d(TAG,"BLE Is Available"); bleIsAvailable = true; } } @TargetApi(18) private void initBLE() { /* Initializes Bluetooth adapter. */ final BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter = bluetoothManager.getAdapter(); bleScanner = new BLEScanner(); leScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { ARSALPrint.d(TAG,"onLeScan"); bleScanner.bleCallback(device, rssi, scanRecord); } }; } /* BLE */ private void bleConnect() { if (bleIsAvailable) { bleScanner.start(); } } private void bleDisconnect() { if (bleIsAvailable) { bleScanner.stop(); } } @TargetApi(18) private class BLEScanner { private static final long ARDISCOVERY_BLE_SCAN_PERIOD = 10000; private static final long ARDISCOVERY_BLE_SCAN_DURATION = 4000; public static final long ARDISCOVERY_BLE_TIMEOUT_DURATION = ARDISCOVERY_BLE_SCAN_PERIOD + ARDISCOVERY_BLE_SCAN_DURATION+6000; private boolean isStart; private boolean scanning; private Handler startBLEHandler; private Handler stopBLEHandler; private Runnable startScanningRunnable; private Runnable stopScanningRunnable; private HashMap<String, ARDiscoveryDeviceService> newBLEDeviceServicesHmap; private static final int ARDISCOVERY_BLE_MANUFACTURER_DATA_LENGTH_OFFSET = 3; private static final int ARDISCOVERY_BLE_MANUFACTURER_DATA_ADTYPE_OFFSET = 4; private static final int ARDISCOVERY_BLE_MANUFACTURER_DATA_LENGTH_WITH_ADTYPE = 9; private static final int ARDISCOVERY_BLE_MANUFACTURER_DATA_ADTYPE = 0xFF; public BLEScanner() { ARSALPrint.d(TAG,"BLEScanningTask constructor"); startBLEHandler = new Handler() ; stopBLEHandler = new Handler() ; startScanningRunnable = new Runnable() { @Override public void run() { startScanLeDevice(); } }; stopScanningRunnable = new Runnable() { @Override public void run() { periodScanLeDeviceEnd(); } }; } public void start() { if (! isStart) { isStart = true; startScanningRunnable.run(); } } private void startScanLeDevice() { /* reset newDeviceServicesHmap */ newBLEDeviceServicesHmap = new HashMap<String, ARDiscoveryDeviceService>(); /* Stops scanning after a pre-defined scan duration. */ stopBLEHandler.postDelayed( stopScanningRunnable , ARDISCOVERY_BLE_SCAN_DURATION); scanning = true; bluetoothAdapter.startLeScan((BluetoothAdapter.LeScanCallback)leScanCallback); /* restart scanning after a pre-defined scan period. */ startBLEHandler.postDelayed (startScanningRunnable, ARDISCOVERY_BLE_SCAN_PERIOD); } public void bleCallback (BluetoothDevice bleService, int rssi, byte[] scanRecord) { ARSALPrint.v(TAG,"bleCallback : found BluetoothDevice : " + bleService + " (" + bleService.getName() + ")"); int productID = getParrotProductID (scanRecord); if (productID != 0) { ARDiscoveryDeviceBLEService deviceBLEService = new ARDiscoveryDeviceBLEService(bleService); deviceBLEService.setSignal(rssi); /* add the service in the array*/ ARDiscoveryDeviceService deviceService = new ARDiscoveryDeviceService (bleService.getName(), deviceBLEService, productID); newBLEDeviceServicesHmap.put(deviceService.getName(), deviceService); } } /** * @brief get the parrot product id from the BLE scanRecord * @param scanRecord BLE scanRecord * @return the product ID of the parrot BLE device. return "0" if it is not a parrot device */ private int getParrotProductID (byte[] scanRecord) { /* read the scanRecord to check if it is a PARROT Delos device with the good version */ int parrotProductID = 0; final int MASK = 0xFF; /* get the length of the manufacturerData */ byte[] data = (byte[]) Arrays.copyOfRange(scanRecord, ARDISCOVERY_BLE_MANUFACTURER_DATA_LENGTH_OFFSET, ARDISCOVERY_BLE_MANUFACTURER_DATA_LENGTH_OFFSET + 1); int manufacturerDataLenght = (MASK & data[0]); /* check if it is the length expected */ if (manufacturerDataLenght == ARDISCOVERY_BLE_MANUFACTURER_DATA_LENGTH_WITH_ADTYPE) { /* get the manufacturerData */ data = (byte[]) Arrays.copyOfRange(scanRecord, ARDISCOVERY_BLE_MANUFACTURER_DATA_ADTYPE_OFFSET , ARDISCOVERY_BLE_MANUFACTURER_DATA_ADTYPE_OFFSET + manufacturerDataLenght); int adType = (MASK & data[0]); /* check if it is the AD Type expected */ if (adType == ARDISCOVERY_BLE_MANUFACTURER_DATA_ADTYPE) { int btVendorID = (data[1] & MASK) + ((data[2] & MASK) << 8); int usbVendorID = (data[3] & MASK) + ((data[4] & MASK) << 8); int usbProductID = (data[5] & MASK) + ((data[6] & MASK) << 8); /* check the vendorID, the usbVendorID end the productID */ if ((btVendorID == ARDISCOVERY_BT_VENDOR_ID) && (usbVendorID == ARDISCOVERY_USB_VENDOR_ID)) { if (supportedProducts.contains(ARDiscoveryService.getProductFromProductID(usbProductID))) { parrotProductID = usbProductID; } } } } return parrotProductID; } private void periodScanLeDeviceEnd() { ARSALPrint.d(TAG,"periodScanLeDeviceEnd"); notificationBLEServiceDeviceUpDate (newBLEDeviceServicesHmap); stopScanLeDevice(); } private void stopScanLeDevice() { ARSALPrint.d(TAG,"ScanLeDeviceAsyncTask stopLeScan"); scanning = false; bluetoothAdapter.stopLeScan((BluetoothAdapter.LeScanCallback)leScanCallback); } public void stop() { ARSALPrint.w(TAG,"BLEScanningTask stop"); if (leScanCallback != null) { try { bluetoothAdapter.stopLeScan((BluetoothAdapter.LeScanCallback)leScanCallback); } catch (NullPointerException e) { ARSALPrint.e(TAG, "Cannot stop scan. Unexpected NPE."); e.printStackTrace(); } } startBLEHandler.removeCallbacks(startScanningRunnable); stopBLEHandler.removeCallbacks(stopScanningRunnable); scanning = false; isStart = false; } public Boolean IsScanning() { return scanning; } public Boolean IsStart() { return isStart; } }; @TargetApi(18) private void notificationBLEServiceDeviceUpDate( HashMap<String, ARDiscoveryDeviceService> newBLEDeviceServicesHmap ) { ARSALPrint.d(TAG,"notificationBLEServiceDeviceUpDate : " + newBLEDeviceServicesHmap); mHandler.removeCallbacksAndMessages(null); /* if the BLEDeviceServices List has changed */ if (bleServicesListHasChanged(newBLEDeviceServicesHmap)) { /* get the new BLE Device Services list */ bleDeviceServicesHmap = newBLEDeviceServicesHmap; /* broadcast the new deviceServiceList */ broadcaster.broadcastDeviceServiceArrayUpdated (); } mHandler.postDelayed(new Runnable() { @Override public void run() { ARSALPrint.d(TAG,"BLE scan timeout ! clear BLE devices"); bleDeviceServicesHmap.clear(); /* broadcast the new deviceServiceList */ broadcaster.broadcastDeviceServiceArrayUpdated(); } }, BLEScanner.ARDISCOVERY_BLE_TIMEOUT_DURATION); } private boolean bleServicesListHasChanged ( HashMap<String, ARDiscoveryDeviceService> newBLEDeviceServicesHmap ) { /* check is the list of BLE devices has changed */ ARSALPrint.d(TAG,"bleServicesListHasChanged"); boolean res = false; if (bleDeviceServicesHmap.size() != newBLEDeviceServicesHmap.size()) { /* if the number of devices has changed */ res = true; } else if (!bleDeviceServicesHmap.keySet().equals(newBLEDeviceServicesHmap.keySet())) { /* if the names of devices has changed */ res = true; } else { for (ARDiscoveryDeviceService bleDevice : bleDeviceServicesHmap.values()) { /* check from the MAC address */ if (!newBLEDeviceServicesHmap.containsValue(bleDevice)) { /* if one of the old devices is not present is the new list */ res = true; } } } return res; } @Override public List<ARDiscoveryDeviceService> getDeviceServicesArray() { return new ArrayList<ARDiscoveryDeviceService> (bleDeviceServicesHmap.values()); } }
package org.jacorb.idl; import java.io.PrintWriter; import java.util.Enumeration; import java.util.Set; import alma.tools.idlgen.AcsXmlNamingExpert; /** * This class encapsulates printing of an {@link Interface} in the ACS-xml way. * It assumes that the interface is already renamed to end in "J". * <p> * We (re-)use the jacorb package <code>org.jacorb.idl</code> to access protected methods, * which is an attempt to not duplicate even more jacorb code. * It is a pity that JacORB does not use a level of indirection when instantiating * the Interface objects in CUP$actions, which would allow us to use a custom Interface type. * * @author hsommer * @author jschwarz */ public class AcsInterfacePrinter { private final Interface interfce; private final Set<AliasTypeSpec> entityTypes; private final Set<StructType> xmlAwareStructs; private final Set<Interface> xmlAwareIFs; private final AcsXmlNamingExpert namingExpert; public AcsInterfacePrinter(Interface interfce, final Set<AliasTypeSpec> entityTypes, final Set<StructType> xmlAwareStructs, final Set<Interface> xmlAwareIFs, final AcsXmlNamingExpert namingExpert) { this.interfce = interfce; this.entityTypes = entityTypes; this.xmlAwareStructs = xmlAwareStructs; this.xmlAwareIFs = xmlAwareIFs; this.namingExpert = namingExpert; } /** * Todo: * - Substitute types in operations parameters and returns * * The code was copied from {@link Interface#printOperations()} * and then modified to not append "Operations" * (plus "interfce." scope resolution to fix compile errors) */ public void printAcsJInterface() { PrintWriter ps = interfce.openOutput(interfce.name); if (ps == null) { return; } interfce.printPackage(ps); interfce.printSuperclassImports(ps); interfce.printImport(ps); // TODO: Print ACS comment interfce.printClassComment(/*"interface",*/ interfce.name, ps); ps.println("public interface " + interfce.name); if (interfce.inheritanceSpec.v.size() > 0) { ps.print("\textends "); Enumeration e = interfce.inheritanceSpec.v.elements(); do { ScopedName sne = (ScopedName) e.nextElement(); // See description of abstractInterfaces for logic here. if (interfce.abstractInterfaces != null && interfce.abstractInterfaces.contains(sne.toString())) { ps.print(sne); } else { if (sne.resolvedTypeSpec() instanceof ReplyHandlerTypeSpec && parser.generate_ami_callback) { ps.print(sne + "Operations"); } else { ConstrTypeSpec ts = unwindTypedefs(sne); ps.print(ts + "Operations"); } } if (e.hasMoreElements()) { ps.print(" , "); } } while (e.hasMoreElements()); // TODO-jacorb33 ps.print(AcsAdapterForOldJacorb.getEnvironmentNL()); //Environment.NL); } ps.println("{"); if (interfce.body != null) { // forward declaration interfce.body.printConstants(ps); // ACS hack // interfce.body.printOperationSignatures(ps); printOperationSignatures(interfce.body, ps); // end ACS hack } ps.println("}"); ps.close(); } /** * Copied from {@link Interface#unwindTypedefs}, without ACS changes except "interfce." resolution. * @param scopedName * @return */ private ConstrTypeSpec unwindTypedefs(ScopedName scopedName) { TypeSpec resolvedTSpec = scopedName.resolvedTypeSpec(); //unwind any typedefs while (resolvedTSpec instanceof AliasTypeSpec ) { resolvedTSpec = ((AliasTypeSpec)resolvedTSpec).originalType(); } if (! (resolvedTSpec instanceof ConstrTypeSpec)) { if (interfce.logger.isDebugEnabled()) { interfce.logger.debug("Illegal inheritance spec in Interface.unwindTypeDefs, not a constr. type but " + resolvedTSpec.getClass() + ", name " + scopedName ); } parser.fatal_error("Illegal inheritance spec in Interface.unwindTypeDefs (not a constr. type): " + interfce.inheritanceSpec, interfce.token); } return (ConstrTypeSpec) resolvedTSpec; } /** * Copied from {@link InterfaceBody#printOperationSignatures(PrintWriter)}. * We probably don't need this if we can modify the OpDecl objects before generating interface code. * @param ps */ void printOperationSignatures(InterfaceBody ifb, PrintWriter ps ) { if( ifb.v.size() > 0 ) { ps.println( "\t/* operations */" ); } for( Enumeration<Definition> e = ifb.v.elements(); e.hasMoreElements(); ) { Definition d = e.nextElement(); if( d.get_declaration() instanceof OpDecl ) { // ( (OpDecl)d.get_declaration() ).printSignature( ps ); OpDecl opdecl = (OpDecl)d.get_declaration(); printSignature( ps, opdecl ); } else if( d.get_declaration() instanceof AttrDecl ) { for( Enumeration m = ( (AttrDecl)d.get_declaration() ).getOperations(); m.hasMoreElements(); ) { ( (Operation)m.nextElement() ).printSignature( ps ); } } } } public void printSignature( PrintWriter ps, OpDecl opdecl ) { printSignature( ps, false, opdecl ); } /** * @param printModifiers whether "public abstract" should be added */ public void printSignature( PrintWriter ps, boolean printModifiers, OpDecl opdecl ) { ps.print( "\t" ); if( printModifiers ) ps.print( "public abstract " ); else ps.print("public "); TypeSpec ts = opdecl.opTypeSpec; sanitizeOpNames(ps, opdecl, ts); for( Enumeration e = opdecl.paramDecls.elements(); e.hasMoreElements(); ) { printParam( ps, (ParamDecl)e.nextElement() ); if( e.hasMoreElements() ) ps.print( ", " ); } ps.print( ")" ); opdecl.raisesExpr.print( ps ); ps.println( ";" ); } private void sanitizeOpNames(PrintWriter ps, OpDecl opdecl, TypeSpec ts) { String acsTypeName = namingExpert.getAcsTypeName(ts, entityTypes, xmlAwareStructs, xmlAwareIFs); ps.print(acsTypeName + " " + opdecl.name + "("); } private void printParam( PrintWriter ps, ParamDecl pdecl ) { TypeSpec ts = pdecl.paramTypeSpec; switch( pdecl.paramAttribute ) { case ParamDecl.MODE_IN: // The following line is copied from AcsStructPrinter to fix the type used for struct parameters, // where the trailing J was missing in case of xml-aware structs. // This change also fixes an issue with forward declared interfaces as we had it // in XmlOffshootReferencingOffshootJ from xmltest.idl. String acsTypeName = namingExpert.getAcsTypeName(ts, entityTypes, xmlAwareStructs, xmlAwareIFs); ps.print(acsTypeName + " " + pdecl.name); break; case ParamDecl.MODE_OUT: case ParamDecl.MODE_INOUT: if (pdecl.paramTypeSpec instanceof AliasTypeSpec && entityTypes.contains(pdecl.paramTypeSpec)) { AliasTypeSpec alias = (AliasTypeSpec)pdecl.paramTypeSpec; String theHolderName = namingExpert.getHolderClassNameForXmlTypedef(alias); ps.print(theHolderName); } else if (pdecl.paramTypeSpec instanceof ConstrTypeSpec && ((ConstrTypeSpec)pdecl.paramTypeSpec).c_type_spec instanceof StructType && xmlAwareStructs.contains(((ConstrTypeSpec)pdecl.paramTypeSpec).c_type_spec)){ StructType stype = (StructType)(((ConstrTypeSpec)pdecl.paramTypeSpec).c_type_spec); ps.print(namingExpert.getJavaPackageForStruct(stype)+"."+ namingExpert.getHolderClassNameForStruct(stype)); } else ps.print( pdecl.paramTypeSpec.holderName() ); // TODO replace & merge w/rest of if stmt break; } ps.print(" "); ps.print(pdecl.simple_declarator); } /** * Exposes {@link Interface#javaName()} to other packages, * to be used by {@link AcsXmlNamingExpert}. */ public static String java_name(Interface interfce) { return interfce.javaName(); } }
package alma.acs.logging; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; import org.omg.CORBA.ORB; import org.omg.DsLogAdmin.LogOperations; import org.slf4j.impl.ACSLoggerFactory; import si.ijs.maci.Manager; import alma.Logging.AcsLogServiceHelper; import alma.Logging.AcsLogServiceOperations; import alma.acs.logging.config.LogConfig; import alma.acs.logging.config.LogConfigException; import alma.acs.logging.config.LogConfigSubscriber; import alma.acs.logging.formatters.AcsBinLogFormatter; import alma.acs.logging.formatters.AcsXMLLogFormatter; import alma.acs.logging.formatters.ConsoleLogFormatter; import alma.acs.logging.level.AcsLogLevelDefinition; import alma.maciErrType.CannotGetComponentEx; import alma.maciErrType.ComponentConfigurationNotFoundEx; import alma.maciErrType.ComponentNotAlreadyActivatedEx; import alma.maciErrType.NoPermissionEx; /** * This class provides methods for getting the loggers for components and containers. * Both the loggers and the handlers are organized in a hierarchical namespace so that * children may inherit some properties from their parents in the namespace. * <p> * To set the policy for remote logging, either {@link #initRemoteLogging(ORB, Manager, int, boolean)} * or {@link #suppressRemoteLogging()} must be called. * As long as none of these methods are called, it is assumed that remote logging will be initialized * at some point later, and all log messages that are meant for remote logging will be stored in * a queue. <code>suppressRemoteLogging</code> will throw away this queue, while <code>initRemoteLogging</code> * will send all queued log records to the remote logger. * <p> * Since ACS 7.0, this class acts pretty much as a replacement for the JDK's {@link LogManager} * and the {@linkplain AcsLogManager} subclass. <br> * If needed, we should investigate how to support the JMX logger management * via {@linkplain java.util.logging.LoggingMXBean} which is useless now. * * @author hsommer */ public class ClientLogManager implements LogConfigSubscriber { public enum LoggerOwnerType { ContainerLogger, ComponentLogger, OrbLogger, OtherLogger, UnknownLogger } /** instance of a singleton */ private volatile static ClientLogManager s_instance; /** The logging configurator shared by various classes of this package */ private final LogConfig sharedLogConfig; /** The (CORBA-) name of the remote logging service to which logs will be sent */ private volatile String logServiceName; /** The time in seconds between the periodic log queue flushings */ private volatile int flushPeriodSeconds; private static class AcsLoggerInfo { AcsLogger logger; AcsLoggingHandler remoteHandler; StdOutConsoleHandler localHandler; LoggerOwnerType loggerOwnerType = LoggerOwnerType.UnknownLogger; boolean needsProcessNameUpdate = false; } /** * We store all loggers in this map instead of giving them to * {@link LogManager} which does not allow to remove loggers * and would thus prevent component loggers from being garbage collected. */ private final Map<String, AcsLoggerInfo> loggers = new HashMap<String, AcsLoggerInfo>(); /** * Parent logger of all remote loggers. * Not really needed any more now that handlers are not shared. */ private Logger parentRemoteLogger; /** * The log queue can be null if remote logging has been suppressed. Otherwise it is non-null even if remote logging * is not active, because it stores the records to be sent off later. */ protected volatile DispatchingLogQueue logQueue; private final ReentrantLock logQueueLock = new ReentrantLock(); /** * The log dispatcher object serves as a flag for whether remote logging has been activated via * {@link #initRemoteLogging(ORB, Manager, int, boolean)}. */ private RemoteLogDispatcher logDispatcher; /** * Logger used by the classes in this logging package. * TODO: allow container or client to replace this logger with their own * logger, because these classes belong to their respective process. */ private final Logger m_internalLogger; /** for testing */ private boolean DEBUG = Boolean.getBoolean("alma.acs.logging.verbose"); private boolean LOG_BIN_TYPE = Boolean.getBoolean("ACS.loggingBin"); /** * The process name gets used as a data field in the log record, and also * gets appended to the name for the Corba logger, * so that different ORB instances in the system can be distinguished. */ private String processName; private final ReentrantLock processNameLock = new ReentrantLock(); /** * If true then the Corba (ORB) logger will not send logs to the Log service. */ private volatile boolean suppressCorbaRemoteLogging = false; /** * Singleton accessor. * <p> * TODO: rename, because now that we have class {@link AcsLogManager}, this method name is confusing. * @return ClientLogManager */ public static synchronized ClientLogManager getAcsLogManager() { if (s_instance == null) { s_instance = new ClientLogManager(); } return s_instance; } protected ClientLogManager() { sharedLogConfig = new LogConfig(); sharedLogConfig.addSubscriber(this); try { sharedLogConfig.initialize(false); // will determine the default values and call #configureLogging } catch (LogConfigException ex) { System.err.println("Failed to configure logging: " + ex.toString()); } // parentRemoteLogger is not removed in method disableRemoteLogging, and thus does not need to be // (re-) created in method prepareRemoteLogging (unlike the queue and the handler). // Therefore we can create it once here in the ctor. parentRemoteLogger = Logger.getLogger("AcsRemoteLogger"); parentRemoteLogger.setUseParentHandlers(false); // otherwise the default log handler on the root logger will dump all logs to stderr prepareRemoteLogging(); m_internalLogger = getAcsLogger("alma.acs.logging", LoggerOwnerType.OtherLogger); sharedLogConfig.setInternalLogger(m_internalLogger); if (DEBUG) { m_internalLogger.fine("ClientLogManager instance is created."); } } /** * @see alma.acs.logging.config.LogConfigSubscriber#configureLogging(alma.acs.logging.LogConfig) */ public void configureLogging(LogConfig logConfig) { if (!logConfig.getCentralizedLogger().equals(logServiceName)) { if (logServiceName == null) { logServiceName = logConfig.getCentralizedLogger(); } else { m_internalLogger.warning("Dynamic switching of Log service not yet supported!"); // @TODO: switch connection to new log service } } flushPeriodSeconds = logConfig.getFlushPeriodSeconds(); logQueueLock.lock(); try { if (logQueue != null) { // don't call this while logQueue is not ready for remote dispatching, because it would produce an ugly error message. if (logQueue.hasRemoteDispatcher()) { logQueue.setPeriodicFlushing(flushPeriodSeconds * 1000); } // Set the log queue size. logQueue.setMaxQueueSize(logConfig.getMaxLogQueueSize()); } } finally { logQueueLock.unlock(); } } /** * Gets the <code>LogConfig</code> object that is shared between the ClientLogManager singleton and any other * objects in the process (e.g. Java container or manager classes, Loggers, Handlers). */ public LogConfig getLogConfig() { return sharedLogConfig; } /** * If not done already, sets up remote handlers for all loggers using a shared queue. */ protected void prepareRemoteLogging() { logQueueLock.lock(); //System.out.println("ClientLogManager#prepareRemoteLogging got the logQueue lock"); try { if (logQueue == null) { logQueue = new DispatchingLogQueue(); logQueue.setMaxQueueSize(getLogConfig().getMaxLogQueueSize()); } } finally { logQueueLock.unlock(); //System.out.println("ClientLogManager#prepareRemoteLogging released the logQueue lock."); } synchronized (loggers) { // attach remote handlers to all loggers for (String loggerName : loggers.keySet()) { AcsLoggerInfo loggerInfo = loggers.get(loggerName); AcsLogger logger = loggerInfo.logger; // sanity check on loggerName: map key vs. Logger if (logger.getLoggerName() == null || !logger.getLoggerName().equals(loggerName)) { logger.setLoggerName(loggerName); logger.info("Logging name mismatch resolved for '" + loggerName + "'. Should be reported to ACS developers"); } addRemoteHandler(logger); } } } /** * Removes, closes, and nulls all remote handlers, so that no more records are put into the queue, and queue and * remote handlers can be garbage collected. * <p> * GC of the queue can be an advantage when logs have been queued for remote sending, but then instead of connecting * to the remote logger, we get a call to {@link #suppressRemoteLogging()}. All messages have been logged locally * anyway, so in this case we want to clean up all these <code>LogRecord</code>s. */ protected void disableRemoteLogging() { synchronized (loggers) { for (String loggerName : loggers.keySet()) { try { AcsLoggerInfo loggerInfo = loggers.get(loggerName); AcsLogger logger = loggerInfo.logger; if (loggerInfo.remoteHandler != null) { logger.removeHandler(loggerInfo.remoteHandler); loggerInfo.remoteHandler.close(); // also unsubscribes from sharedLogConfig loggerInfo.remoteHandler = null; } } catch (Throwable thr) { // better just print to stderr because remote logging may be in a delicate state System.err.println("Unexpected exception while disabling remote logging for '" + loggerName + "': " + thr.toString()); } } } } /** * Attaches a remote log handler to the given logger, if remote logging has not been suppressed. * * Note that this method does not require <code>logger</code> to be * already registered in {@linkplain #loggers}, but if it is, * then the new AcsLoggingHandler is set in the map's AcsLoggerInfo as well. * * @param logger logger to be set up for remote logging * @return the remote handler that was added to the logger. */ private AcsLoggingHandler addRemoteHandler(AcsLogger logger) { AcsLoggingHandler remoteHandler = null; synchronized (loggers) { String loggerName = logger.getLoggerName(); AcsLoggerInfo loggerInfo = loggers.get(loggerName); // logQueue == null serves as indicator for remote log suppression if (logQueue != null) { // try to find an existing handler for (Handler handler : logger.getHandlers()) { if (handler instanceof AcsLoggingHandler) { remoteHandler = (AcsLoggingHandler) handler; if (loggerInfo != null && !remoteHandler.equals(loggerInfo.remoteHandler)) { logger.info("Remote logging handler mismatch resolved for '" + loggerName + "'. Should be reported to ACS developers"); } break; } } if (remoteHandler == null) { remoteHandler = new AcsLoggingHandler(logQueue, sharedLogConfig, loggerName); // subscribes to sharedLogConfig logger.addHandler(remoteHandler); if (loggerInfo != null && loggerInfo.remoteHandler != null) { logger.info("Logging handler mismatch resolved for '" + loggerName + "'. Should be reported to ACS developers"); } } } if (loggerInfo != null) { loggerInfo.remoteHandler = remoteHandler; } } return remoteHandler; } /** * Adds a local logging handler to the provided logger. * Unlike with remote handlers in {@link #prepareRemoteLogging()}, for local handlers * we don't allow removing and re-adding the handlers later. * <p> * Note that this method does not require <code>logger</code> to be * already registered in {@linkplain #loggers}, but if it is, * then the new StdOutConsoleHandler is set in the map's AcsLoggerInfo as well. * * @param logger logger to be set up for local logging * @return the local handler that was added to the logger. */ private StdOutConsoleHandler addLocalHandler(AcsLogger logger) { StdOutConsoleHandler localHandler = null; synchronized (loggers) { String loggerName = logger.getLoggerName(); AcsLoggerInfo loggerInfo = loggers.get(loggerName); // try to find an existing handler (should not happen) for (Handler handler : logger.getHandlers()) { if (handler instanceof StdOutConsoleHandler) { localHandler = (StdOutConsoleHandler) handler; if (loggerInfo != null && !localHandler.equals(loggerInfo.localHandler)) { logger.info("Stdout logging handler mismatch resolved for '" + loggerName + "'. Should be reported to ACS developers"); } break; } } if (localHandler == null) { localHandler = new StdOutConsoleHandler(sharedLogConfig, loggerName); // subscribes to sharedLogConfig localHandler.setFormatter(new ConsoleLogFormatter()); logger.addHandler(localHandler); if (loggerInfo != null && loggerInfo.localHandler != null) { logger.info("Logging handler mismatch resolved for '" + loggerName + "'. Should be reported to ACS developers"); } } if (loggerInfo != null) { loggerInfo.localHandler = localHandler; } } return localHandler; } private AcsLogger getAcsLogger(String loggerName, LoggerOwnerType loggerOwnerType) { if (loggerName == null || loggerName.trim().isEmpty()) { throw new IllegalArgumentException("loggerName must not be null or empty"); } AcsLoggerInfo loggerInfo = null; // just to make sure we never throw an exception try { synchronized (loggers) { loggerInfo = loggers.get(loggerName); // try to reuse existing logger // avoid false "reuse" by making new logger name unique int counter = 2; // that is to make "name" into "name_2" while (loggerInfo != null && loggerOwnerType != loggerInfo.loggerOwnerType) { // the current loggerName exists already for a different logger type. // Try a different logger name. int lastIndexUnderscore = loggerName.lastIndexOf('_'); if (lastIndexUnderscore > 0 && loggerName.length() > lastIndexUnderscore + 1) { try { int oldCounter = Integer.parseInt(loggerName.substring(lastIndexUnderscore + 1)); counter = Math.max(counter, oldCounter+1); loggerName = loggerName.substring(0, lastIndexUnderscore+1) + counter; loggerInfo = loggers.get(loggerName); continue; } catch (NumberFormatException ex) { // we had an '_' but no number behind it. Same as no '_' at all. } } loggerName += "_" + counter; loggerInfo = loggers.get(loggerName); } if (loggerInfo == null) { // not yet in cache, so we create the logger loggerInfo = new AcsLoggerInfo(); loggerInfo.logger = new AcsLogger(loggerName, null, sharedLogConfig); // ctor registers itself in loggers map loggerInfo.logger.setParent(parentRemoteLogger); loggerInfo.logger.setUseParentHandlers(false); // since ACS 7.0 all AcsLoggers have their own handlers // set the value for the "ProcessName" and "SourceObject" fields in the produced log records loggerInfo.logger.setProcessName(this.processName); if (loggerOwnerType == LoggerOwnerType.ComponentLogger || loggerOwnerType == LoggerOwnerType.OrbLogger) { loggerInfo.logger.setSourceObject(loggerName); } else { // TODO: check why we don't always use the logger name as SourceObject loggerInfo.logger.setSourceObject(this.processName); } loggerInfo.localHandler = addLocalHandler(loggerInfo.logger); loggerInfo.remoteHandler = addRemoteHandler(loggerInfo.logger); // may be null loggerInfo.loggerOwnerType = loggerOwnerType; loggers.put(loggerName, loggerInfo); } if (DEBUG) { System.out.println("created remote logger '" + loggerName + "' (level " + loggerInfo.logger.getLevel() + ") and separate local handler."); } } } catch (Throwable thr) { System.err.println("failed to create logger '" + loggerName + "'."); } return loggerInfo.logger; } /** * Enables loggers to send log records to the central ACS logger service. * Tries to connect to the log service using the supplied ACS manager. * As long as this connection fails, this method can sleep for 10 seconds and then try to connect again, * if the parameter <code>retry</code> is <code>true</code>. Total retries are limited to 5, * to detect a permanent problem before the log queue overflows. * <p> * Execution time can be significant, so consider calling this method in a separate thread * (which has no negative effect on the logging since all log records are cached and automatically sent off * once the log service is available). * Use a daemon thread to avoid shutdown problems if this method still hangs in the login loop. * <p> * When the log service is obtained, the log queue used for remote logging will be flushed periodically * to the log service unless an otherwise triggered flush has done this already. * The default period is 10 seconds, but can be overridden in the CDB. <br> * * @param orb the ORB used in this JVM * @param manager the ACS manager * @param managerHandle handle assigned by the ACS Manager for this client * @param retry if true, a failing connection to the log service will trigger up to 5 other attempts, every 10 seconds. * @return true if remote logging was initialized successfully * @see #shutdown(boolean) */ public boolean initRemoteLogging(ORB orb, Manager manager, int managerHandle, boolean retry) { if (logDispatcher != null) { System.err.println("Ignoring call to ClientLogManager#init: already initialized!"); // todo: or is there a case where we want to retrieve the log service again? return false; } if (orb == null) { System.err.println("Given ORB is null."); return false; } if (manager == null || managerHandle <= 0) { System.err.println("can't connect to log service: manager is null, or invalid handle " + managerHandle); return false; } AcsLogServiceOperations logService = null; int count = 0; String errMsg; do { errMsg = null; count++; try { // normally there will be a remote handler and log queue already, which has captured all log records produced so far. // However, if suppressRemoteLogging was called, we need to set up remote logging from scratch. prepareRemoteLogging(); logService = getLogService(manager, managerHandle); if (logService == null) { errMsg = "Failed to obtain central log service '" + logServiceName + "': reference is 'null'. "; } else { logQueueLock.lock(); // we keep the above get_service call outside this locked section in order to not block shutdown() too long //System.out.println("ClientLogManager#initRemoteLogging got the logQueue lock"); try { if (logQueue == null) { // this can happen if shutdown or suppressRemoteLogging is called concurrently System.out.println("Will abort ClientLogManager#initRemoteLogging because remote logging seems no longer needed."); return false; } if (count > 1) { // all is fine, but we report the difficulty m_internalLogger.info("Connected to central log service after initial failure. "); } // make log service available to our dispatcher, and flush the records collected so far if (LOG_BIN_TYPE){ logDispatcher = new RemoteLogDispatcher(orb, logService, new AcsBinLogFormatter()); } else { logDispatcher = new RemoteLogDispatcher(orb, logService, new AcsXMLLogFormatter()); } logQueue.setRemoteLogDispatcher(logDispatcher); logQueue.flushAllAndWait(); logQueue.setPeriodicFlushing(flushPeriodSeconds * 1000); } finally { logQueueLock.unlock(); // System.out.println("ClientLogManager#initRemoteLogging released the logQueue lock"); } } } catch (Throwable thr) { errMsg = "Failed to connect to central log service with exception " + thr.toString(); // as this message must go repeatedly to the command line output regardless of local log level, // we don't want to print the multi-line exception stack, but just the original location. StackTraceElement[] trace = thr.getStackTrace(); if (trace != null && trace.length > 0) { StackTraceElement traceOrigin = trace[0]; errMsg += " in file " + traceOrigin.getFileName() + ", line " + traceOrigin.getLineNumber(); } errMsg += ". "; } if (errMsg != null) { // can't use the loggers, so println is ok here if (retry) { System.err.println(errMsg + "Will try again in 10 seconds."); try { Thread.sleep(10000); } catch (InterruptedException e) { System.err.println("Abandoning ClientLogManager#initRemoteLogging retries because of thread interruption."); retry = false; } } else { System.err.println(errMsg); } } } while (retry && count <= 5 && errMsg != null); return (errMsg == null); } /** * This method is broken out from {@link #initRemoteLogging(ORB, Manager, int, boolean)} to allow mock implementation by tests * without a functional manager object. Note that module acsjlog comes before jmanager. * <p> * Since ACS 8.0.1 we use an ACS-specific subtype of {@link LogOperations} to avoid the marshalling to Corba Any. */ protected AcsLogServiceOperations getLogService(Manager manager, int managerHandle) throws ComponentNotAlreadyActivatedEx, CannotGetComponentEx, NoPermissionEx, ComponentConfigurationNotFoundEx { return AcsLogServiceHelper.narrow(manager.get_service(managerHandle, logServiceName, true)); } /** * Suppresses remote logging. If log messages destined for remote logging have not been sent to the central log * service yet (e.g. because {@link #initRemoteLogging(ORB, Manager, int, boolean) initRemoteLogging} has not been * called, or because of sending failures), these log messages will be lost for remote logging. Log messages * produced after this call will not even be queued for remote logging. * <p> * This method should only be called by special ALMA applications such as the Observation Preparation tool, which * runs stand-alone, with all containers, managers, etc. in one JVM. In this case, no central logger is available, * and all loggers which normally send their output to the central logger should be limited to local logging * (stdout). * <p> * It is possible (probably not useful in real life) to re-enable remote logging later, by calling * <code>initRemoteLogging</code>. */ public void suppressRemoteLogging() { logQueueLock.lock(); try { System.out.println("suppressRemoteLogging called"); disableRemoteLogging(); logQueue = null; } finally { logQueueLock.unlock(); } } /** * Allows to suppress remote logging of Corba/ORB logger(s). Internally this suppression is handled using log level * changes that cannot be undone by other log level changes. Generally remote logging remains enabled though, which * makes this method quite different from {@linkplain #suppressRemoteLogging()}. * <p> * <strong>Application code such as components must not call this method!<strong> */ public void suppressCorbaRemoteLogging() { suppressCorbaRemoteLogging = true; synchronized (loggers) { for (AcsLoggerInfo loggerInfo : loggers.values()) { if (loggerInfo.loggerOwnerType == LoggerOwnerType.OrbLogger) { sharedLogConfig.setAndLockMinLogLevel(AcsLogLevelDefinition.OFF, loggerInfo.logger.getLoggerName()); } } } } /** * Gets a logger to be used by ORB and POA classes, or by hibernate. * The logger is connected to the central ACS logger. * <p> * @TODO rename this method to accommodate non-corba frameworks into which we insert ACS loggers, such as hibernate, * see {@link org.slf4j.impl.ACSLoggerFactory}. * <p> * For hibernate loggers, the logger automatically receives an initial custom log level configuration, * to avoid jamming the log system with hibernate logs. * The applied custom log level is the maximum of the default log level and WARNING. * Note that the hibernate logger can still be set to a more verbose level by giving it a custom log config * in the CDB, or dynamically using logLevelGUI etc. * <p> * @TODO Instead of this hard coded and probably confusing application of a custom log level, * the CDB should offer a central configuration option for all jacorb, hibernate etc loggers, * independently of the process (container or manager etc). * <p> * @param corbaName * e.g. <code>jacorb</code>. * @param autoConfigureContextName * if true, the context (e.g. container name) will be appended to this logger's name as soon as it is * available, changing the logger name to something like <code>jacorb@frodoContainer</code>. */ public AcsLogger getLoggerForCorba(String corbaName, boolean autoConfigureContextName) { String loggerName = corbaName; AcsLogger corbaLogger = null; processNameLock.lock(); try { // if the process name is not known yet (e.g. during startup), then we need to schedule its update if (autoConfigureContextName && processName != null) { // if the process name is already known, we can even use it for the regular logger name instead of using a later workaround loggerName += "@" + processName; } corbaLogger = getAcsLogger(loggerName, LoggerOwnerType.OrbLogger); // Suppress logs inside the call to the Log service, which could happen e.g. when policies are set and jacorb-debug is enabled. // As of ACS 8, that trashy log message would be "get_policy_overrides returns 1 policies" corbaLogger.addIgnoreLogs("org.omg.DsLogAdmin._LogStub", "write_records"); corbaLogger.addIgnoreLogs("alma.Logging._AcsLogServiceStub", "write_records"); corbaLogger.addIgnoreLogs("alma.Logging._AcsLogServiceStub", "writeRecords"); if (autoConfigureContextName && processName == null) { // mark this logger for process name update AcsLoggerInfo loggerInfo = loggers.get(loggerName); loggerInfo.needsProcessNameUpdate = true; } } finally { processNameLock.unlock(); } // fix levels if we suppress corba remote logging if (suppressCorbaRemoteLogging) { sharedLogConfig.setAndLockMinLogLevel(AcsLogLevelDefinition.OFF, loggerName); } else if (corbaName.startsWith(ACSLoggerFactory.HIBERNATE_LOGGER_NAME_PREFIX) && !sharedLogConfig.hasCustomConfig(loggerName)) { // Since ACS 8.1 hibernate classes are given an ACS logger via this method, see javadoc. AcsLogLevelDefinition minCustomLevel = AcsLogLevelDefinition.WARNING; AcsLogLevelDefinition customLevel = ( minCustomLevel.compareTo(sharedLogConfig.getDefaultMinLogLevel()) > 0 ? minCustomLevel : sharedLogConfig.getDefaultMinLogLevel() ); sharedLogConfig.setMinLogLevel(customLevel, loggerName); AcsLogLevelDefinition customLevelLocal = ( minCustomLevel.compareTo(sharedLogConfig.getDefaultMinLogLevelLocal()) > 0 ? minCustomLevel : sharedLogConfig.getDefaultMinLogLevelLocal() ); sharedLogConfig.setMinLogLevelLocal(customLevelLocal, loggerName); m_internalLogger.info("Logger " + loggerName + " created with custom log levels local=" + customLevelLocal.name + ", remote=" + customLevel.name + " to avoid hibernate log jams due to careless default log level settings."); } return corbaLogger; } /** * Gets a logger to be used by the Java container classes. The logger is connected to the central ACS logger. */ public AcsLogger getLoggerForContainer(String containerName) { setProcessName(containerName); return getAcsLogger(containerName, LoggerOwnerType.ContainerLogger); } /** * Gets a logger object to be used by a component. * <p> * This method is not supposed to be accessed directly in the component implementation. * Instead, the implementation of <code>alma.acs.container.ContainerServices</code> * should call this method. * * @param componentName component name (sufficiently qualified to be unique in the system or log domain) * @return AcsLogger */ public AcsLogger getLoggerForComponent(String componentName) { return getAcsLogger(componentName, LoggerOwnerType.ComponentLogger); } /** * Gets a logger for an application (which is not an ACS component itself), e.g. a GUI application using the ACS ComponentClient. * @param loggerName the logger name, should identify the application or the particular logger that gets requested. * @param enableRemoteLogging if true (generally recommended), the returned logger is set up to send the logs to the remote log service, * as it always happens for container and component loggers. * <emph>This will only work if {@link #initRemoteLogging(ORB, Manager, int, boolean)} is also called, * which happens automatically in <code>ComponentClient</code>. * For a standalone application that is not ACS-aware (no manager known etc), remote logging is not available * even with enableRemoteLogging == true.</emph> * @return a configured Logger */ public AcsLogger getLoggerForApplication(String loggerName, boolean enableRemoteLogging) { if (loggerName == null || loggerName.trim().length() == 0) { loggerName = "unknownClientApplication"; } else { setProcessName(loggerName); } AcsLogger logger = null; if (enableRemoteLogging) { logger = getAcsLogger(loggerName, LoggerOwnerType.OtherLogger); } else { logger = AcsLogger.createUnconfiguredLogger(loggerName, null); logger.setUseParentHandlers(false); addLocalHandler(logger); logger.configureLevels(sharedLogConfig.getNamedLoggerConfig(loggerName)); } return logger; } /** * Takes the process name and overwrites previous names, * and updates all Loggers which are waiting to get their overly simple name enriched. * The new name will be the old name + @ + processName. * <p> * The update mechanism ensures that the process name will eventually be set also on loggers * which were created before the process name was known, e.g. component logger created before container logger. * @TODO check if we still need the process name appended to the logger name, now that we have a separate field for it in AcsLogger. * * @param name */ private void setProcessName(String processName) { if (processName != null) { processNameLock.lock(); try { this.processName = processName; synchronized (loggers) { for (String oldLoggerName : new ArrayList<String>(loggers.keySet())) { // iterate over copy to avoid ConcurrentModif.Ex AcsLoggerInfo loggerInfo = loggers.get(oldLoggerName); if (loggerInfo.needsProcessNameUpdate) { String newLoggerName = oldLoggerName + "@" + processName; loggerInfo.logger.setLoggerName(newLoggerName); loggerInfo.logger.setProcessName(processName); loggerInfo.needsProcessNameUpdate = false; AcsLoggerInfo gonner = loggers.put(newLoggerName, loggerInfo); if (gonner != null) { m_internalLogger.info("Process name update on logger '" + newLoggerName + "' overwrote an existing logger. This should be reported to the ACS developers."); } loggers.remove(oldLoggerName); } } } } finally { processNameLock.unlock(); } } } /** * Shuts down remote ACS logging. * The loggers can still be used, but will only log locally. * @param wait */ public void shutdown(boolean wait) { if (DEBUG) { System.out.println("ClientLogManager#shutdown(" + wait + ") called."); } // clean up remote logging, if it's still active logQueueLock.lock(); try { if (logQueue != null) { // stop adding more log records for remote logging disableRemoteLogging(); if (wait) { flushAll(); } else { // trigger one last flush, which may itself attempt to trigger more flushes, // but only until shutDown prohibits further scheduling. Future<Boolean> flushFuture = logQueue.flush(); // wait at most 200 milliseconds, to give the flush a chance to reach the central log service. // we don't care about the result. try { flushFuture.get(200, TimeUnit.MILLISECONDS); } catch (Exception e) { e.printStackTrace(); } } logQueue.shutDown(); logQueue = null; } // junit classloaders don't manage to reload this class between tests, so we explicitly null the instance s_instance = null; // todo: check if we should release the Log service with the manager // (probably not since currently it doesn't even require us to be logged in to access the Log service). } finally { logQueueLock.unlock(); } } /** * Flushes the remote log queue completely and returns only when it's done. */ public void flushAll() { if (logQueue != null) { logQueue.flushAllAndWait(); } } }
package VASL.build.module.map.boardPicker; import java.awt.Component; import java.awt.Image; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.awt.image.FilteredImageSource; import java.awt.image.RGBImageFilter; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StreamTokenizer; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.StringTokenizer; import java.util.Vector; import java.util.Map.Entry; import VASSAL.build.GameModule; import VASSAL.tools.DataArchive; public class SSRFilter extends RGBImageFilter { /* * * A class to swap colors according to specified rules * A set of color names is read from an input file with the * format * White 255,255,255 * Black 0,0,0 * * The swapping rules are read from an input file with the format: * * <key> * <color>=<color> * <color>=<color> * <color>=<color> * There can be any number of color entries per key. * * The color entries are names of colors as defined in the color file * Example: * * WoodsToBrush * WoodsGreen=BrushL0 * * WoodsBlack=BrushL0 */ private Map<Integer, Integer> mappings; private String saveRules; private Map<String, Integer> colorValues; private List<SSROverlay> overlays; private File archiveFile; private DataArchive archive; private ASLBoard board; public SSRFilter(String listOfRules, File archiveFile, ASLBoard board) throws BoardException { canFilterIndexColorModel = true; saveRules = listOfRules; this.archiveFile = archiveFile; try { archive = new DataArchive(archiveFile.getPath()); archive.getInputStream("data"); } catch (IOException ex) { throw new BoardException("Board does not support terrain alterations"); } this.board = board; readAllRules(); } private static InputStream getStream(String name) { try { return GameModule.getGameModule().getDataArchive().getInputStream(name); } catch (IOException ex) { return null; } } public Iterable<SSROverlay> getOverlays() { return overlays; } public int filterRGB(int x, int y, int rgb) { return ((0xff000000 & rgb) | newValue(rgb & 0xffffff)); } private int newValue(int rgb) { /* * * Maps the color to it's transformed value by going through * the rules. All rules are applied in sequence. */ int rval = rgb; Integer mappedValue = mappings.get(rgb); if (mappedValue != null) { rval = mappedValue; } return rval; } public String toString() { return saveRules; } private int parseRGB(String s) { /* * * Calculate integer value from rr,gg,bb or 40a38f format */ int rval = -1; try { Integer test = (Integer) colorValues.get(s); if (test != null) { rval = test.intValue(); } else if (s.indexOf(',') >= 0) { StringTokenizer st = new StringTokenizer(s, ","); if (st.countTokens() == 3) { int red, green, blue; red = Integer.parseInt(st.nextToken()); green = Integer.parseInt(st.nextToken()); blue = Integer.parseInt(st.nextToken()); if ((red >= 0 && red <= 255) && (green >= 0 && green <= 255) && (blue >= 0 && blue <= 255)) { rval = (red << 16) + (green << 8) + blue; } } } else if (s.length() == 6) { rval = Integer.parseInt(s, 16); } } catch (Exception e) { rval = -1; } return rval; } public void readAllRules() { // Build the list of rules in use Vector rules = new Vector(); StringTokenizer st = new StringTokenizer(saveRules); while (st.hasMoreTokens()) { String s = st.nextToken(); if (!rules.contains(s)) { rules.addElement(s); } } mappings = new HashMap<Integer, Integer>(); colorValues = new HashMap<String, Integer>(); overlays = new Vector(); // Read board-specific colors last to override defaults readColorValues(getStream("boardData/colors")); try { readColorValues(archive.getInputStream("colors")); } catch (IOException ex) { } // Read board-specific rules first to be applied before defaults try { readColorRules(archive.getInputStream("colorSSR"), rules); } catch (IOException ex) { } readColorRules(getStream("boardData/colorSSR"), rules); overlays.clear(); // SSR Overlays are applied in reverse order to the order they're listed // in the overlaySSR file. Therefore, reading board-specific // overlay rules first will override defaults try { readOverlayRules(archive.getInputStream("overlaySSR")); } catch (IOException ex) { } readOverlayRules(getStream("boardData/overlaySSR")); } protected void readColorValues(InputStream in) { /* * * Add to the list of color definitions, as read from input file */ if (in == null) return; BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StreamTokenizer st = new StreamTokenizer(reader); st.resetSyntax(); st.wordChars((int) ' ', 0xff); st.commentChar((int) '/'); st.whitespaceChars((int) ' ', (int) ' '); st.whitespaceChars((int) '\n', (int) '\n'); st.whitespaceChars((int) '\t', (int) '\t'); st.slashSlashComments(true); st.slashStarComments(true); st.eolIsSignificant(false); try { for (String s = reader.readLine(); s != null; s = reader.readLine()) { if (s.startsWith("/")) continue; StringTokenizer st2 = new StringTokenizer(s); if (st2.countTokens() < 2) continue; String s1 = st2.nextToken(); int rgb = parseRGB(st2.nextToken()); if (rgb >= 0) { colorValues.put(s1, new Integer(rgb)); } else { System.err.println("Invalid color alias: " + s); } } } catch (Exception e) { System.err.println("Caught " + e + " reading colors"); } } public void readColorRules(InputStream in, Vector rules) { /* * * Define the color transformations defined by each rule * as read in from input file */ if (in == null) return; StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(in))); st.resetSyntax(); st.wordChars((int) ' ', 0xff); st.commentChar((int) '/'); st.whitespaceChars((int) ' ', (int) ' '); st.whitespaceChars((int) '\n', (int) '\n'); st.whitespaceChars((int) '\t', (int) '\t'); st.slashSlashComments(true); st.slashStarComments(true); st.eolIsSignificant(false); boolean inCategory = false; /* are we in a "selected" category */ try { while (st.nextToken() != StreamTokenizer.TT_EOF) { String s = st.sval; if (s == null) { continue; } int n = s.indexOf('='); if (n < 0) { if (s.charAt(0) == '+') { inCategory = rules.contains(s.substring(1)); } else { inCategory = rules.removeElement(s); } } else if (inCategory) { int len = s.length(); boolean valid = true; if (n + 1 == len) { valid = false; } else { String sfrom = s.substring(0, n); String sto = s.substring(n + 1, len); int ifrom = parseRGB(sfrom); int ito = parseRGB(sto); if (ifrom >= 0 && ito >= 0) { mappings.put(ifrom, ito); /* * Also apply this mapping to previous mappings */ if (mappings.containsValue(ifrom)) { for(Iterator<Entry<Integer,Integer>> it = mappings.entrySet().iterator(); it.hasNext(); ) { Entry<Integer,Integer> e = it.next(); if (e.getValue() == ifrom) e.setValue(ito); } } } else { valid = false; System.err.println("Invalid color mapping: " + s + " mapped to " + ifrom + "=" + ito); } } if (!valid) { System.err.println("Invalid color mapping: " + s); } } } } catch (Exception e) { } } public void readOverlayRules(InputStream in) { if (in == null) return; try { BufferedReader file; file = new BufferedReader(new InputStreamReader(in)); String s; while ((s = file.readLine()) != null) { if (s.trim().length() == 0) continue; if (saveRules.indexOf(s.trim()) >= 0) { while ((s = file.readLine()) != null) { if (s.length() == 0) break; else if (s.toLowerCase().startsWith("underlay")) { try { StringTokenizer st = new StringTokenizer(s); st.nextToken(); String underImage = st.nextToken(); st = new StringTokenizer(st.nextToken(), ","); int trans[] = new int[st.countTokens()]; int n = 0; while (st.hasMoreTokens()) { trans[n++] = ((Integer) colorValues.get(st.nextToken())).intValue(); } overlays.add(new Underlay(underImage, trans, archive, board)); } catch (NoSuchElementException end) { } } else overlays.add(new SSROverlay(s.trim(),archiveFile)); } } } } catch (Exception e) { System.err.println("Error opening rules file " + e); } } public Image recolor(Image oldImage, Component observer) { return Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(oldImage.getSource(), this)); } public void transform(BufferedImage image) { if (!mappings.isEmpty()) { final int h = image.getHeight(); final int[] row = new int[image.getWidth()]; for (int y = 0; y < h; ++y) { image.getRGB(0, y, row.length, 1, row, 0, row.length); for (int x = 0; x < row.length; ++x) { row[x] = filterRGB(x, y, row[x]); } image.setRGB(0, y, row.length, 1, row, 0, row.length); } } } @Override public boolean equals(Object obj) { return obj instanceof SSRFilter && saveRules.equals(((SSRFilter) obj).saveRules); } @Override public int hashCode() { return saveRules.hashCode(); } }
package ch.unizh.ini.jaer.chip.cochlea; import java.util.ArrayList; import java.util.prefs.PreferenceChangeEvent; import javax.swing.undo.UndoableEditSupport; import net.sf.jaer.biasgen.*; import net.sf.jaer.biasgen.IPotArray; import net.sf.jaer.biasgen.VDAC.DAC; import net.sf.jaer.biasgen.VDAC.VPot; import net.sf.jaer.chip.*; import net.sf.jaer.graphics.ChipRendererDisplayMethod; import net.sf.jaer.graphics.DisplayMethod; import net.sf.jaer.graphics.FrameAnnotater; import net.sf.jaer.graphics.SpaceTimeEventDisplayMethod; import net.sf.jaer.hardwareinterface.*; import com.sun.opengl.util.GLUT; import java.awt.Graphics2D; import java.beans.PropertyChangeSupport; import java.util.Arrays; import java.util.Iterator; import java.util.Observable; import java.util.Observer; import java.util.prefs.PreferenceChangeListener; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.swing.JPanel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import net.sf.jaer.hardwareinterface.usb.cypressfx2.CypressFX2; import net.sf.jaer.util.RemoteControlCommand; import net.sf.jaer.util.RemoteControlled; /** * Extends Shih-Chii's AMS cochlea AER chip to * add bias generator interface, * to be used when using the on-chip bias generator and the on-board DACs. Also implemements ConfigBits, Scanner, and Equalizer configuration. * @author tobi */ public class CochleaAMS1b extends CochleaAMSNoBiasgen { public static String getDescription(){ return "A binaural AER silicon cochlea with 64 channels and 8 ganglion cells of two types per channel";} // // biasgen components implement this interface to send their own messages // interface ConfigurationSender { // void sendConfiguration(); final GLUT glut = new GLUT(); /** Creates a new instance of CochleaAMSWithBiasgen */ public CochleaAMS1b() { super(); setBiasgen(new CochleaAMS1b.Biasgen(this)); getCanvas().setBorderSpacePixels(40); for (DisplayMethod m : getCanvas().getDisplayMethods()) { if (m instanceof ChipRendererDisplayMethod || m instanceof SpaceTimeEventDisplayMethod) { m.addAnnotator(new FrameAnnotater() { public void setAnnotationEnabled(boolean yes) { } public boolean isAnnotationEnabled() { return true; } public void annotate(float[][][] frame) { } public void annotate(Graphics2D g) { } // renders the string starting at x,y,z with angleDeg angle CCW from horizontal in degrees void renderStrokeFontString(GL gl, float x, float y, float z, float angleDeg, String s) { final int font = GLUT.STROKE_ROMAN; final float scale = 2f / 104f; // chars will be about 1 pixel wide gl.glPushMatrix(); gl.glTranslatef(x, y, z); gl.glRotatef(angleDeg, 0, 0, 1); gl.glScalef(scale, scale, scale); gl.glLineWidth(2); for (char c : s.toCharArray()) { glut.glutStrokeCharacter(font, c); } gl.glPopMatrix(); } // chars about 104 model units wide final float xlen = glut.glutStrokeLength(glut.STROKE_ROMAN, "channel"), ylen = glut.glutStrokeLength(glut.STROKE_ROMAN, "cell type"); public void annotate(GLAutoDrawable drawable) { GL gl = drawable.getGL(); // gl.glBegin(GL.GL_LINES); // gl.glColor3f(.5f, .5f, 0); // gl.glVertex2f(0, 0); // gl.glVertex2f(getSizeX() - 1, getSizeY() - 1); // gl.glEnd(); gl.glPushMatrix(); { gl.glColor3f(1, 1, 1); // must set color before raster position (raster position is like glVertex) renderStrokeFontString(gl, -1, 16 / 2 - 5, 0, 90, "cell type"); renderStrokeFontString(gl, sizeX / 2 - 4, -3, 0, 0, "channel"); renderStrokeFontString(gl, 0, -3, 0, 0, "hi fr"); renderStrokeFontString(gl, sizeX - 15, -3, 0, 0, "low fr"); } gl.glPopMatrix(); } }); } } } /** overrides the Chip setHardware interface to construct a biasgen if one doesn't exist already. * Sets the hardware interface and the bias generators hardware interface *@param hardwareInterface the interface */ @Override public void setHardwareInterface(final HardwareInterface hardwareInterface) { this.hardwareInterface = hardwareInterface; try { if (getBiasgen() == null) { setBiasgen(new CochleaAMS1b.Biasgen(this)); } else { getBiasgen().setHardwareInterface((BiasgenHardwareInterface) hardwareInterface); // from blank device we get bare CypressFX2 which is not BiasgenHardwareInterface so biasgen hardware interface is not set yet } } catch (ClassCastException e) { System.err.println(e.getMessage() + ": probably this chip object has a biasgen but the hardware interface doesn't, ignoring"); } } /** * Describes IPots on tmpdiff128 retina chip. These are configured by a shift register as shown here: *<p> *<img src="doc-files/tmpdiff128biasgen.gif" alt="tmpdiff128 shift register arrangement"/> <p> This bias generator also offers an abstracted ChipControlPanel interface that is used for a simplified user interface. * * @author tobi */ public class Biasgen extends net.sf.jaer.biasgen.Biasgen implements ChipControlPanel { private ArrayList<HasPreference> hasPreferencesList = new ArrayList<HasPreference>(); /** The DAC on the board. Specified with 5V reference even though Vdd=3.3 because the internal 2.5V reference is used and so that the VPot controls display correct voltage. */ protected final DAC dac = new DAC(32, 12, 0, 5f, 3.3f); // the DAC object here is actually 2 16-bit DACs daisy-chained on the Cochlea board; both corresponding values need to be sent to change one value IPotArray ipots = new IPotArray(this); PotArray vpots = new PotArray(this); // private IPot diffOn, diffOff, refr, pr, sf, diff; private CypressFX2 cypress = null; // tobi changed config bits on rev1 board since e3/4 control maxim mic preamp attack/release and gain now private ConfigBit aerKillBit, vResetBit, yBit, selAER, selIn, powerDown, /* resCtrBit1, resCtrBit2, */ preampAR, preampGain; volatile ConfigBit[] configBits = { powerDown = new ConfigBit("d5", "powerDown", "turns off on-chip biases (1=turn off, 0=normal)"), // resCtrBit2=new ConfigBit("e4", "resCtrBit2", "preamp gain bit 1 (msb) (0=lower gain, 1=higher gain)"), // resCtrBit1=new ConfigBit("e3", "resCtrBit1", "preamp gain bit 0 (lsb) (0=lower gain, 1=higher gain)"), preampAR = new TriStateableConfigBit("e4", "preampAR", "preamp attack/release (0=attack/release ratio=1:500, 1=A/R=1:2000, HiZ=A/R=1:4000 (may not work))"), // may not work for 1:4000 because spec is to connect pin to BIAS preampGain = new TriStateableConfigBit("e3", "preampGain", "preamp gain bit (1=gain=40dB, 0=gain=50dB, HiZ=60dB if preamp threshold \"PreampAGCThreshold (TH)\"is set above 2V)"), vResetBit = new ConfigBit("e5", "Vreset", "global latch reset (1=reset, 0=run)"), selIn = new ConfigBit("e6", "selIn", "Parallel (1) or Cascaded (0) Arch"), selAER = new ConfigBit("d3", "selAER", "Chooses whether lpf (0) or rectified (1) lpf output drives lpf neurons"), yBit = new ConfigBit("d2", "YBit", "Used to select which neurons to kill"), aerKillBit = new ConfigBit("d6", "AERKillBit", "Set high to kill channel"), /* #define DataSel 1 // selects data shift register path (bitIn, clock, latch) #define AddrSel 2 // selects channel selection shift register path #define BiasGenSel 4 // selects biasgen shift register path #define ResCtr1 8 // a preamp feedback resistor selection bitmask #define ResCtr2 16 // another microphone preamp feedback resistor selection bitmask #define Vreset 32 // (1) to reset latch states #define SelIn 64 // Parallel (0) or Cascaded (1) Arch #define Ybit 128 // Chooses whether lpf (0) or bpf (1) neurons to be killed, use in conjunction with AddrSel and AERKillBit */}; Scanner scanner = new Scanner(); Equalizer equalizer = new Equalizer(); BufferIPot bufferIPot = new BufferIPot(); boolean dacPowered = getPrefs().getBoolean("CochleaAMS1b.Biasgen.DAC.powered", true); // private PropertyChangeSupport support = new PropertyChangeSupport(this); /** Creates a new instance of Biasgen for Tmpdiff128 with a given hardware interface *@param chip the chip this biasgen belongs to */ public Biasgen(Chip chip) { super(chip); setName("CochleaAMSWithBiasgen"); scanner.addObserver(this); equalizer.addObserver(this); bufferIPot.addObserver(this); for (ConfigBit b : configBits) { b.addObserver(this); } // public IPot(Biasgen biasgen, String name, int shiftRegisterNumber, final Type type, Sex sex, int bitValue, int displayPosition, String tooltipString) { potArray = new IPotArray(this); //construct IPotArray whit shift register stuff ipots.addPot(new IPot(this, "VAGC", 0, IPot.Type.NORMAL, IPot.Sex.N, 0, 1, "Sets reference for AGC diffpair in SOS")); // second to list bits loaded, just before buffer bias bits. displayed first in GUI ipots.addPot(new IPot(this, "Curstartbpf", 1, IPot.Type.NORMAL, IPot.Sex.P, 0, 2, "Sets master current to local DACs for BPF Iq")); ipots.addPot(new IPot(this, "DacBufferNb", 2, IPot.Type.NORMAL, IPot.Sex.N, 0, 3, "Sets bias current of amp in local DACs")); ipots.addPot(new IPot(this, "Vbp", 3, IPot.Type.NORMAL, IPot.Sex.P, 0, 4, "Sets bias for readout amp of BPF")); ipots.addPot(new IPot(this, "Ibias20OpAmp", 4, IPot.Type.NORMAL, IPot.Sex.P, 0, 5, "Bias current for preamp")); ipots.addPot(new IPot(this, "N.C.", 5, IPot.Type.NORMAL, IPot.Sex.N, 0, 6, "not used")); ipots.addPot(new IPot(this, "Vsetio", 6, IPot.Type.CASCODE, IPot.Sex.P, 0, 7, "Sets 2I0 and I0 for LPF time constant")); ipots.addPot(new IPot(this, "Vdc1", 7, IPot.Type.NORMAL, IPot.Sex.P, 0, 8, "Sets DC shift for close end of cascade")); ipots.addPot(new IPot(this, "NeuronRp", 8, IPot.Type.NORMAL, IPot.Sex.P, 0, 9, "Sets bias current of neuron")); ipots.addPot(new IPot(this, "Vclbtgate", 9, IPot.Type.NORMAL, IPot.Sex.P, 0, 10, "Bias gate of CLBT")); ipots.addPot(new IPot(this, "Vioff", 10, IPot.Type.NORMAL, IPot.Sex.P, 0, 11, "Sets DC shift input to LPF")); ipots.addPot(new IPot(this, "Vbias2", 11, IPot.Type.NORMAL, IPot.Sex.P, 0, 12, "Sets lower cutoff freq for cascade")); ipots.addPot(new IPot(this, "Ibias10OpAmp", 12, IPot.Type.NORMAL, IPot.Sex.P, 0, 13, "Bias current for preamp")); ipots.addPot(new IPot(this, "Vthbpf2", 13, IPot.Type.CASCODE, IPot.Sex.P, 0, 14, "Sets high end of threshold current for bpf neurons")); ipots.addPot(new IPot(this, "Follbias", 14, IPot.Type.NORMAL, IPot.Sex.N, 0, 15, "Bias for PADS")); ipots.addPot(new IPot(this, "pdbiasTX", 15, IPot.Type.NORMAL, IPot.Sex.N, 0, 16, "pulldown for AER TX")); ipots.addPot(new IPot(this, "Vrefract", 16, IPot.Type.NORMAL, IPot.Sex.N, 0, 17, "Sets refractory period for AER neurons")); ipots.addPot(new IPot(this, "VbampP", 17, IPot.Type.NORMAL, IPot.Sex.P, 0, 18, "Sets bias current for input amp to neurons")); ipots.addPot(new IPot(this, "Vcascode", 18, IPot.Type.CASCODE, IPot.Sex.N, 0, 19, "Sets cascode voltage")); ipots.addPot(new IPot(this, "Vbpf2", 19, IPot.Type.NORMAL, IPot.Sex.P, 0, 20, "Sets lower cutoff freq for BPF")); ipots.addPot(new IPot(this, "Ibias10OTA", 20, IPot.Type.NORMAL, IPot.Sex.N, 0, 21, "Bias current for OTA in preamp")); ipots.addPot(new IPot(this, "Vthbpf1", 21, IPot.Type.CASCODE, IPot.Sex.P, 0, 22, "Sets low end of threshold current to bpf neurons")); ipots.addPot(new IPot(this, "Curstart ", 22, IPot.Type.NORMAL, IPot.Sex.P, 0, 23, "Sets master current to local DACs for SOS Vq")); ipots.addPot(new IPot(this, "Vbias1", 23, IPot.Type.NORMAL, IPot.Sex.P, 0, 24, "Sets higher cutoff freq for SOS")); ipots.addPot(new IPot(this, "NeuronVleak", 24, IPot.Type.NORMAL, IPot.Sex.P, 0, 25, "Sets leak current for neuron")); ipots.addPot(new IPot(this, "Vioffbpfn", 25, IPot.Type.NORMAL, IPot.Sex.N, 0, 26, "Sets DC level for input to bpf")); ipots.addPot(new IPot(this, "Vcasbpf", 26, IPot.Type.CASCODE, IPot.Sex.P, 0, 27, "Sets cascode voltage in cm BPF")); ipots.addPot(new IPot(this, "Vdc2", 27, IPot.Type.NORMAL, IPot.Sex.P, 0, 28, "Sets DC shift for SOS at far end of cascade")); ipots.addPot(new IPot(this, "Vterm", 28, IPot.Type.CASCODE, IPot.Sex.N, 0, 29, "Sets bias current of terminator xtor in diffusor")); ipots.addPot(new IPot(this, "Vclbtcasc", 29, IPot.Type.CASCODE, IPot.Sex.P, 0, 30, "Sets cascode voltage in CLBT")); ipots.addPot(new IPot(this, "reqpuTX", 30, IPot.Type.NORMAL, IPot.Sex.P, 0, 31, "Sets pullup bias for AER req ckts")); ipots.addPot(new IPot(this, "Vbpf1", 31, IPot.Type.NORMAL, IPot.Sex.P, 0, 32, "Sets higher cutoff freq for BPF")); // first bits loaded, at end of shift register // public VPot(Chip chip, String name, DAC dac, int channel, Type type, Sex sex, int bitValue, int displayPosition, String tooltipString) { // top dac in schem/layout, first 16 channels of 32 total vpots.addPot(new VPot(CochleaAMS1b.this, "Vterm", dac, 0, Pot.Type.NORMAL, Pot.Sex.N, 0, 0, "Sets bias current of terminator xtor in diffusor")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vrefhres", dac, 1, Pot.Type.NORMAL, Pot.Sex.N, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "VthAGC", dac, 2, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vrefreadout", dac, 3, Pot.Type.NORMAL, Pot.Sex.N, 0, 0, "test dac bias")); // vpots.addPot(new VPot(CochleaAMS1b.this, "Vbpf2x", dac, 4, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "BiasDACBufferNBias", dac, 4, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "DAC buffer bias for ???")); // vpots.addPot(new VPot(CochleaAMS1b.this, "Vbias2x", dac, 5, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vrefract", dac, 5, Pot.Type.NORMAL, Pot.Sex.N, 0, 0, "test dac bias")); // vpots.addPot(new VPot(CochleaAMS1b.this, "Vbpf1x", dac, 6, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "PreampAGCThreshold (TH)", dac, 6, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "Threshold for microphone preamp AGC gain reduction turn-on")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vrefpreamp", dac, 7, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); // vpots.addPot(new VPot(CochleaAMS1b.this, "Vbias1x", dac, 8, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "NeuronRp", dac, 8, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "Sets bias current of neuron - overrides onchip bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vthbpf1x", dac, 9, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vioffbpfn", dac, 10, Pot.Type.NORMAL, Pot.Sex.N, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "NeuronVleak", dac, 11, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "Sets leak current for neuron - not connected on board")); vpots.addPot(new VPot(CochleaAMS1b.this, "DCOutputLevel", dac, 12, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "Microphone DC output level to cochlea chip")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vthbpf2x", dac, 13, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "DACSpOut2", dac, 14, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "DACSpOut1", dac, 15, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); // bot DAC in schem/layout, 2nd 16 channels vpots.addPot(new VPot(CochleaAMS1b.this, "Vth4", dac, 16, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vcas2x", dac, 17, Pot.Type.NORMAL, Pot.Sex.N, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vrefo", dac, 18, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vrefn2", dac, 19, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vq", dac, 20, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vcassyni", dac, 21, Pot.Type.NORMAL, Pot.Sex.N, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vgain", dac, 22, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vrefn", dac, 23, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "VAI0", dac, 24, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vdd1", dac, 25, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vth1", dac, 26, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vref", dac, 27, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vtau", dac, 28, Pot.Type.NORMAL, Pot.Sex.P, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "VcondVt", dac, 29, Pot.Type.NORMAL, Pot.Sex.N, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vpm", dac, 30, Pot.Type.NORMAL, Pot.Sex.N, 0, 0, "test dac bias")); vpots.addPot(new VPot(CochleaAMS1b.this, "Vhm", dac, 31, Pot.Type.NORMAL, Pot.Sex.N, 0, 0, "test dac bias")); loadPreferences(); // Pot.setModificationTrackingEnabled(true); } @Override public void loadPreferences() { super.loadPreferences(); if (ipots != null) { ipots.loadPreferences(); } if (vpots != null) { vpots.loadPreferences(); } if (hasPreferencesList != null) { for (HasPreference hp : hasPreferencesList) { hp.loadPreference(); } } } @Override public void storePreferences() { super.storePreferences(); ipots.storePreferences(); vpots.storePreferences(); for (HasPreference hp : hasPreferencesList) { hp.storePreference(); } } @Override public JPanel buildControlPanel() { CochleaAMS1bControlPanel myControlPanel = new CochleaAMS1bControlPanel(CochleaAMS1b.this); return myControlPanel; } @Override public void setHardwareInterface(BiasgenHardwareInterface hw) { // super.setHardwareInterface(hardwareInterface); // don't delegrate to super, handle entire configuration sending here if (hw == null) { cypress = null; hardwareInterface = null; return; } if (hw instanceof CochleaAMS1bHardwareInterface) { hardwareInterface = hw; cypress = (CypressFX2) hardwareInterface; log.info("set hardwareInterface CochleaAMS1bHardwareInterface=" + hardwareInterface.toString()); sendConfiguration(); resetAERComm(); } } final short CMD_IPOT = 1, CMD_RESET_EQUALIZER = 2, CMD_SCANNER = 3, CMD_EQUALIZER = 4, CMD_SETBIT = 5, CMD_VDAC = 6, CMD_INITDAC = 7; final byte[] emptyByteArray = new byte[0]; /** Does special reset cycle, in background thread */ void resetAERComm() { Runnable r = new Runnable() { public void run() { yBit.set(true); aerKillBit.set(false); // after kill bit changed, must wait vResetBit.set(true); // yBit.set(true); // aerKillBit.set(false); // after kill bit changed, must wait try { Thread.sleep(50); } catch (InterruptedException e) { } vResetBit.set(false); aerKillBit.set(true); try { Thread.sleep(50); } catch (InterruptedException e) { } yBit.set(false); aerKillBit.set(false); log.info("AER communication reset by toggling configuration bits"); sendConfiguration(); } }; Thread t = new Thread(r, "ResetAERComm"); t.start(); } // convenience method void sendCmd(int cmd, int index, byte[] bytes) throws HardwareInterfaceException { if (bytes == null) { bytes = emptyByteArray; } // log.info(String.format("sending command vendor request cmd=%d, index=%d, and %d bytes", cmd, index, bytes.length)); if (cypress != null) { cypress.sendVendorRequest(CypressFX2.VENDOR_REQUEST_SEND_BIAS_BYTES, (short) (0xffff & cmd), (short) (0xffff & index), bytes); // & to prevent sign extension for negative shorts } } // no data phase, just value, index void sendCmd(int cmd, int index) throws HardwareInterfaceException { sendCmd(cmd, index, emptyByteArray); } /** The central point for communication with HW from biasgen. All objects in Biasgen are Observables and add Biasgen.this as Observer. They then call notifyObservers when their state changes. * @param observable IPot, Scanner, etc * @param object not used at present */ @Override synchronized public void update(Observable observable, Object object) { // thread safe to ensure gui cannot retrigger this while it is sending something // log.info(observable + " sent " + object); if (cypress == null) { return; } // sends a vendor request depending on type of update // vendor request is always VR_CONFIG // value is the type of update // index is sometimes used for 16 bitmask updates // bytes are the rest of data try { if (observable instanceof IPot || observable instanceof BufferIPot) { // must send all IPot values and set the select to the ipot shift register, this is done by the cypress byte[] bytes = new byte[1 + ipots.getNumPots() * ipots.getPots().get(0).getNumBytes()]; int ind = 0; Iterator itr = ((IPotArray) ipots).getShiftRegisterIterator(); while (itr.hasNext()) { IPot p = (IPot) itr.next(); // iterates in order of shiftregister index, from Vbpf to VAGC byte[] b = p.getBinaryRepresentation(); System.arraycopy(b, 0, bytes, ind, b.length); ind += b.length; } bytes[ind] = (byte) bufferIPot.getValue(); // get 8 bitmask buffer bias value, this is *last* byte sent because it is at start of biasgen shift register sendCmd(CMD_IPOT, 0, bytes); // the usual packing of ipots } else if (observable instanceof VPot) { // There are 2 16-bit AD5391 DACs daisy chained; we need to send data for both // to change one of them. We can send all zero bytes to the one we're not changing and it will not affect any channel // on that DAC. We also take responsibility to formatting all the bytes here so that they can just be piped out // surrounded by nSync low during the 48 bit write on the controller. VPot p = (VPot) observable; sendDAC(p); }else if (observable instanceof TriStateableConfigBit) { // tristateable should come first before configbit since it is subclass TriStateableConfigBit b = (TriStateableConfigBit) observable; byte[] bytes = {(byte)((b.get() ? (byte) 1 : (byte) 0)|(b.isHiZEnabled()? (byte)2: (byte)0))}; sendCmd(CMD_SETBIT, b.portbit, bytes); // sends value=CMD_SETBIT, index=portbit with (port(b=0,d=1,e=2)<<8)|bitmask(e.g. 00001000) in MSB/LSB, byte[0]= OR of value (1,0), hiZ=2/0, bit is set if tristate, unset if driving port } else if (observable instanceof ConfigBit) { ConfigBit b = (ConfigBit) observable; byte[] bytes = {b.get() ? (byte) 1 : (byte) 0}; sendCmd(CMD_SETBIT, b.portbit, bytes); // sends value=CMD_SETBIT, index=portbit with (port(b=0,d=1,e=2)<<8)|bitmask(e.g. 00001000) in MSB/LSB, byte[0]=value (1,0) } else if (observable instanceof Scanner) { byte[] bytes = new byte[1]; int index = 0; if (scanner.isContinuousScanningEnabled()) { // only one scanner so don't need to get it bytes[0] = (byte) (0xFF & scanner.getPeriod()); // byte is unsigned char on fx2 and we make sure the sign bit is left unsigned index = 1; } else { bytes[0] = (byte) (scanner.getCurrentStage() & 0xFF); // don't do something funny casting to signed byte index = 0; } sendCmd(CMD_SCANNER, index, bytes); // sends CMD_SCANNER as value, index=1 for continuous index=0 for channel. if index=0, byte[0] has channel, if index=1, byte[0] has period } else if (observable instanceof Equalizer.EqualizerChannel) { // sends 0 byte message (no data phase for speed) Equalizer.EqualizerChannel c = (Equalizer.EqualizerChannel) observable; int value = (c.channel << 8) + CMD_EQUALIZER; // value has cmd in LSB, channel in MSB int index = c.qsos + (c.qbpf << 5) + (c.lpfkilled ? 1 << 10 : 0) + (c.bpfkilled ? 1 << 11 : 0); // index has b11=bpfkilled, b10=lpfkilled, b9:5=qbpf, b4:0=qsos sendCmd(value, index); // System.out.println(String.format("channel=%50s value=%16s index=%16s",c.toString(),Integer.toBinaryString(0xffff&value),Integer.toBinaryString(0xffff&index))); // killed byte has 2 lsbs with bitmask 1=lpfkilled, bitmask 0=bpf killed, active high (1=kill, 0=alive) } else if (observable instanceof Equalizer) { // TODO everything is in the equalizer channel, nothing yet in equalizer (e.g global settings) }else { super.update(observable, object); // super (Biasgen) handles others, e.g. maasterbias } } catch (HardwareInterfaceException e) { log.warning(e.toString()); } } void sendConfiguration() { try { if (!isOpen()) { open(); } } catch (HardwareInterfaceException e) { log.warning("opening device to send configuration: " + e); return; } log.info("sending complete configuration"); update(ipots.getPots().get(0), null); for (Pot v : vpots.getPots()) { update(v, v); } try { setDACPowered(isDACPowered()); } catch (HardwareInterfaceException ex) { log.warning("setting power state of DACs: " + ex); } for (ConfigBit b : configBits) { update(b, b); } update(scanner, scanner); for (Equalizer.EqualizerChannel c : equalizer.channels) { update(c, null); } } // sends VR to init DAC public void initDAC() throws HardwareInterfaceException { sendCmd(CMD_INITDAC, 0); } void sendDAC(VPot pot) throws HardwareInterfaceException { int chan = pot.getChannel(); int value = pot.getBitValue(); byte[] b = new byte[6]; // 2*24=48 bits // original firmware code // unsigned char dat1 = 0x00; //00 00 0000; // unsigned char dat2 = 0xC0; //Reg1=1 Reg0=1 : Write output data // unsigned char dat3 = 0x00; // dat1 |= (address & 0x0F); // dat2 |= ((msb & 0x0F) << 2) | ((lsb & 0xC0)>>6) ; // dat3 |= (lsb << 2) | 0x03; // DEBUG; the last 2 bits are actually don't care byte msb = (byte) (0xff & ((0xf00 & value) >> 8)); byte lsb = (byte) (0xff & value); byte dat1 = 0; byte dat2 = (byte) 0xC0; byte dat3 = 0; dat1 |= (0xff & ((chan % 16) & 0xf)); dat2 |= ((msb & 0xf) << 2) | ((0xff & (lsb & 0xc0) >> 6)); dat3 |= (0xff & ((lsb << 2))); if (chan < 16) { // these are first VPots in list; they need to be loaded first to get to the second DAC in the daisy chain b[0] = dat1; b[1] = dat2; b[2] = dat3; b[3] = 0; b[4] = 0; b[5] = 0; } else { // second DAC VPots, loaded second to end up at start of daisy chain shift register b[0] = 0; b[1] = 0; b[2] = 0; b[3] = dat1; b[4] = dat2; b[5] = dat3; } // System.out.print(String.format("value=%-6d channel=%-6d ",value,chan)); // for(byte bi:b) System.out.print(String.format("%2h ", bi&0xff)); // System.out.println(); sendCmd(CMD_VDAC, 0, b); // value=CMD_VDAC, index=0, bytes as above } /** Sets the VDACs on the board to be powered or high impedance output. This is a global operation. * * @param yes true to power up DACs * @throws net.sf.jaer.hardwareinterface.HardwareInterfaceException */ public void setDACPowered(boolean yes) throws HardwareInterfaceException { putPref("CochleaAMS1b.Biasgen.DAC.powered", yes); byte[] b = new byte[6]; Arrays.fill(b, (byte) 0); final byte up = (byte) 9, down = (byte) 8; if (yes) { b[0] = up; b[3] = up; // sends 09 00 00 to each DAC which is soft powerup } else { b[0] = down; b[3] = down; } sendCmd(CMD_VDAC, 0, b); } /** Returns the DAC powered state * * @return true if powered up */ public boolean isDACPowered() { return dacPowered; } // public PropertyChangeSupport getSupport() { // return support; class BufferIPot extends Observable implements RemoteControlled, PreferenceChangeListener, HasPreference { final int max = 63; // 8 bits private volatile int value; private final String key = "CochleaAMS1b.Biasgen.BufferIPot.value"; BufferIPot() { if (getRemoteControl() != null) { getRemoteControl().addCommandListener(this, "setbufferbias bitvalue", "Sets the buffer bias value"); } loadPreference(); getPrefs().addPreferenceChangeListener(this); hasPreferencesList.add(this); } public int getValue() { return value; } public void setValue(int value) { if (value > max) { value = max; } else if (value < 0) { value = 0; } this.value = value; setChanged(); notifyObservers(); } @Override public String toString() { return String.format("BufferIPot with max=%d, value=%d", max, value); } public String processRemoteControlCommand(RemoteControlCommand command, String input) { String[] tok = input.split("\\s"); if (tok.length < 2) { return "bufferbias " + getValue() + "\n"; } else { try { int val = Integer.parseInt(tok[1]); setValue(val); } catch (NumberFormatException e) { return "?\n"; } } return "bufferbias " + getValue() + "\n"; } public void preferenceChange(PreferenceChangeEvent e) { if (e.getKey().equals(key)) { setValue(Integer.parseInt(e.getNewValue())); } } public void loadPreference() { setValue(getPrefs().getInt(key, max / 2)); } public void storePreference() { putPref(key, value); } } /** A single bitmask of digital configuration */ class ConfigBit extends Observable implements PreferenceChangeListener, HasPreference { int port; short portbit; // has port as char in MSB, bitmask in LSB int bitmask; private volatile boolean value; String name, tip; String key; String portBitString; ConfigBit(String portBit, String name, String tip) { if (portBit == null || portBit.length() != 2) { throw new Error("BitConfig portBit=" + portBit + " but must be 2 characters"); } String s = portBit.toLowerCase(); if (!(s.startsWith("c") || s.startsWith("d") || s.startsWith("e"))) { throw new Error("BitConfig portBit=" + portBit + " but must be 2 characters and start with C, D, or E"); } portBitString = portBit; char ch = s.charAt(0); switch (ch) { case 'c': port = 0; break; case 'd': port = 1; break; case 'e': port = 2; break; default: throw new Error("BitConfig portBit=" + portBit + " but must be 2 characters and start with C, D, or E"); } bitmask = 1 << Integer.valueOf(s.substring(1, 2)); portbit = (short) (0xffff & ((port << 8) + (0xff & bitmask))); this.name = name; this.tip = tip; key = "CochleaAMS1b.Biasgen.BitConfig." + name; loadPreference(); getPrefs().addPreferenceChangeListener(this); hasPreferencesList.add(this); } void set(boolean value) { this.value = value; // log.info("set " + this + " to value=" + value+" notifying "+countObservers()+" observers"); setChanged(); notifyObservers(); } boolean get() { return value; } @Override public String toString() { return String.format("ConfigBit name=%s portbit=%s value=%s", name, portBitString, Boolean.toString(value)); } @Override public void preferenceChange(PreferenceChangeEvent e) { if (e.getKey().equals(key)) { // log.info(this+" preferenceChange(): event="+e+" key="+e.getKey()+" newValue="+e.getNewValue()); boolean newv = Boolean.parseBoolean(e.getNewValue()); set(newv); } } @Override public void loadPreference() { set(getPrefs().getBoolean(key, false)); } @Override public void storePreference() { putPref(key, value); // will eventually call pref change listener which will call set again } } /** Adds a hiZ state to the bit to set port bit to input */ class TriStateableConfigBit extends ConfigBit { private volatile boolean hiZEnabled = false; String hiZKey; TriStateableConfigBit(String portBit, String name, String tip) { super(portBit, name, tip); hiZKey = "CochleaAMS1b.Biasgen.BitConfig." + name + ".hiZEnabled"; loadPreference(); } /** * @return the hiZEnabled */ public boolean isHiZEnabled() { return hiZEnabled; } /** * @param hiZEnabled the hiZEnabled to set */ public void setHiZEnabled(boolean hiZEnabled) { this.hiZEnabled = hiZEnabled; setChanged(); notifyObservers(); } @Override public String toString() { return String.format("TriStateableConfigBit name=%s portbit=%s value=%s hiZEnabled=%s", name, portBitString, Boolean.toString(get()), hiZEnabled); } public void loadPreference() { super.loadPreference(); setHiZEnabled(getPrefs().getBoolean(key, false)); } public void storePreference() { super.storePreference(); putPref(key, hiZEnabled); // will eventually call pref change listener which will call set again } } class Scanner extends Observable implements PreferenceChangeListener, HasPreference { Scanner() { loadPreference(); getPrefs().addPreferenceChangeListener(this); hasPreferencesList.add(this); } int nstages = 64; private volatile int currentStage; private volatile boolean continuousScanningEnabled; private volatile int period; int minPeriod = 10; // to avoid FX2 getting swamped by interrupts for scanclk int maxPeriod = 255; public int getCurrentStage() { return currentStage; } public void setCurrentStage(int currentStage) { this.currentStage = currentStage; continuousScanningEnabled = false; setChanged(); notifyObservers(); } public boolean isContinuousScanningEnabled() { return continuousScanningEnabled; } public void setContinuousScanningEnabled(boolean continuousScanningEnabled) { this.continuousScanningEnabled = continuousScanningEnabled; setChanged(); notifyObservers(); } public int getPeriod() { return period; } public void setPeriod(int period) { if (period < minPeriod) { period = 10; // too small and interrupts swamp the FX2 } if (period > maxPeriod) { period = (byte) (maxPeriod); // unsigned char } this.period = period; setChanged(); notifyObservers(); } public void preferenceChange(PreferenceChangeEvent e) { if (e.getKey().equals("CochleaAMS1b.Biasgen.Scanner.currentStage")) { setCurrentStage(Integer.parseInt(e.getNewValue())); } else if (e.getKey().equals("CochleaAMS1b.Biasgen.Scanner.currentStage")) { setContinuousScanningEnabled(Boolean.parseBoolean(e.getNewValue())); } } public void loadPreference() { setCurrentStage(getPrefs().getInt("CochleaAMS1b.Biasgen.Scanner.currentStage", 0)); setContinuousScanningEnabled(getPrefs().getBoolean("CochleaAMS1b.Biasgen.Scanner.continuousScanningEnabled", false)); setPeriod(getPrefs().getInt("CochleaAMS1b.Biasgen.Scanner.period", 50)); // 50 gives about 80kHz } public void storePreference() { putPref("CochleaAMS1b.Biasgen.Scanner.period", period); putPref("CochleaAMS1b.Biasgen.Scanner.continuousScanningEnabled", continuousScanningEnabled); putPref("CochleaAMS1b.Biasgen.Scanner.currentStage", currentStage); } } class Equalizer extends Observable { // describes the local gain and Q registers and the kill bits final int numChannels = 128, maxValue = 31; // private int globalGain = 15; // private int globalQuality = 15; EqualizerChannel[] channels = new EqualizerChannel[numChannels]; Equalizer() { for (int i = 0; i < numChannels; i++) { channels[i] = new EqualizerChannel(i); channels[i].addObserver(Biasgen.this); // CochleaAMS1b.Biasgen observes each equalizer channel } } // public int getGlobalGain() { // return globalGain; // public void setGlobalGain(int globalGain) { // this.globalGain = globalGain; // for(EqualizerChannel c:channels){ // c.setQBPF(globalGain); // public int getGlobalQuality() { // return globalQuality; // public void setGlobalQuality(int globalQuality) { // this.globalQuality = globalQuality; // for(EqualizerChannel c:channels){ // c.setQBPF(globalGain); class EqualizerChannel extends Observable implements ChangeListener, PreferenceChangeListener, HasPreference { final int max = 31; int channel; private String prefsKey; private volatile int qsos; private volatile int qbpf; private volatile boolean bpfkilled, lpfkilled; EqualizerChannel(int n) { channel = n; prefsKey = "CochleaAMS1b.Biasgen.Equalizer.EqualizerChannel." + channel + "."; loadPreference(); getPrefs().addPreferenceChangeListener(this); hasPreferencesList.add(this); } @Override public String toString() { return String.format("EqualizerChannel: channel=%-3d qbpf=%-2d qsos=%-2d bpfkilled=%-6s lpfkilled=%-6s", channel, qbpf, qsos, Boolean.toString(bpfkilled), Boolean.toString(lpfkilled)); } public int getQSOS() { return qsos; } public void setQSOS(int qsos) { if (this.qsos != qsos) { setChanged(); } this.qsos = qsos; notifyObservers(); } public int getQBPF() { return qbpf; } public void setQBPF(int qbpf) { if (this.qbpf != qbpf) { setChanged(); } this.qbpf = qbpf; notifyObservers(); } public boolean isLpfKilled() { return lpfkilled; } public void setLpfKilled(boolean killed) { if (killed != this.lpfkilled) { setChanged(); } this.lpfkilled = killed; notifyObservers(); } public boolean isBpfkilled() { return bpfkilled; } public void setBpfKilled(boolean bpfkilled) { if (bpfkilled != this.bpfkilled) { setChanged(); } this.bpfkilled = bpfkilled; notifyObservers(); } public void stateChanged(ChangeEvent e) { if (e.getSource() instanceof CochleaAMS1bControlPanel.EqualizerSlider) { CochleaAMS1bControlPanel.EqualizerSlider s = (CochleaAMS1bControlPanel.EqualizerSlider) e.getSource(); if (s instanceof CochleaAMS1bControlPanel.QSOSSlider) { s.channel.setQSOS(s.getValue()); } if (s instanceof CochleaAMS1bControlPanel.QBPFSlider) { s.channel.setQBPF(s.getValue()); } setChanged(); notifyObservers(); } else if (e.getSource() instanceof CochleaAMS1bControlPanel.KillBox) { CochleaAMS1bControlPanel.KillBox b = (CochleaAMS1bControlPanel.KillBox) e.getSource(); if (b instanceof CochleaAMS1bControlPanel.LPFKillBox) { b.channel.setLpfKilled(b.isSelected()); // System.out.println("LPF: "+b.channel.toString()); } else { b.channel.setBpfKilled(b.isSelected()); // System.out.println("BPF: "+b.channel.toString()); } setChanged(); notifyObservers(); } } public void preferenceChange(PreferenceChangeEvent e) { if (e.getKey().equals(prefsKey + "qsos")) { setQSOS(Integer.parseInt(e.getNewValue())); } else if (e.getKey().equals(prefsKey + "qbpf")) { setQBPF(Integer.parseInt(e.getNewValue())); } else if (e.getKey().equals(prefsKey + "bpfkilled")) { setBpfKilled(Boolean.parseBoolean(e.getNewValue())); } else if (e.getKey().equals(prefsKey + "lpfkilled")) { setLpfKilled(Boolean.parseBoolean(e.getNewValue())); } } public void loadPreference() { qsos = getPrefs().getInt(prefsKey + "qsos", 15); qbpf = getPrefs().getInt(prefsKey + "qbpf", 15); bpfkilled = getPrefs().getBoolean(prefsKey + "bpfkilled", false); lpfkilled = getPrefs().getBoolean(prefsKey + "lpfkilled", false); setChanged(); notifyObservers(); } public void storePreference() { putPref(prefsKey + "bpfkilled", bpfkilled); putPref(prefsKey + "lpfkilled", lpfkilled); putPref(prefsKey + "qbpf", qbpf); putPref(prefsKey + "qsos", qsos); } } } } }
package codechicken.nei.recipe; import codechicken.nei.ItemList; import codechicken.nei.NEIClientUtils; import codechicken.nei.NEIServerUtils; import codechicken.nei.PositionedStack; import net.minecraft.block.Block; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.gui.inventory.GuiFurnace; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraft.tileentity.TileEntityFurnace; import java.awt.*; import java.util.*; import java.util.List; import java.util.Map.Entry; public class FurnaceRecipeHandler extends TemplateRecipeHandler { public class SmeltingPair extends CachedRecipe { public SmeltingPair(ItemStack ingred, ItemStack result) { ingred.stackSize = 1; this.ingred = new PositionedStack(ingred, 51, 6); this.result = new PositionedStack(result, 111, 24); } public List<PositionedStack> getIngredients() { return getCycledIngredients(cycleticks / 48, Arrays.asList(ingred)); } public PositionedStack getResult() { return result; } public PositionedStack getOtherStack() { return afuels.get((cycleticks / 48) % afuels.size()).stack; } PositionedStack ingred; PositionedStack result; } public static class FuelPair { public FuelPair(ItemStack ingred, int burnTime) { this.stack = new PositionedStack(ingred, 51, 42, false); this.burnTime = burnTime; } public PositionedStack stack; public int burnTime; } public static ArrayList<FuelPair> afuels; public static HashSet<Block> efuels; @Override public void loadTransferRects() { transferRects.add(new RecipeTransferRect(new Rectangle(50, 23, 18, 18), "fuel")); transferRects.add(new RecipeTransferRect(new Rectangle(74, 23, 24, 18), "smelting")); } @Override public Class<? extends GuiContainer> getGuiClass() { return GuiFurnace.class; } @Override public String getRecipeName() { return NEIClientUtils.translate("recipe.furnace"); } @Override public TemplateRecipeHandler newInstance() { if (afuels == null || afuels.isEmpty()) findFuels(); return super.newInstance(); } @Override public void loadCraftingRecipes(String outputId, Object... results) { if (outputId.equals("smelting") && getClass() == FurnaceRecipeHandler.class) {//don't want subclasses getting a hold of this Map<ItemStack, ItemStack> recipes = (Map<ItemStack, ItemStack>) FurnaceRecipes.smelting().getSmeltingList(); for (Entry<ItemStack, ItemStack> recipe : recipes.entrySet()) arecipes.add(new SmeltingPair(recipe.getKey(), recipe.getValue())); } else super.loadCraftingRecipes(outputId, results); } @Override public void loadCraftingRecipes(ItemStack result) { Map<ItemStack, ItemStack> recipes = (Map<ItemStack, ItemStack>) FurnaceRecipes.smelting().getSmeltingList(); for (Entry<ItemStack, ItemStack> recipe : recipes.entrySet()) if (NEIServerUtils.areStacksSameType(recipe.getValue(), result)) arecipes.add(new SmeltingPair(recipe.getKey(), recipe.getValue())); } @Override public void loadUsageRecipes(String inputId, Object... ingredients) { if (inputId.equals("fuel") && getClass() == FurnaceRecipeHandler.class)//don't want subclasses getting a hold of this loadCraftingRecipes("smelting"); else super.loadUsageRecipes(inputId, ingredients); } @Override public void loadUsageRecipes(ItemStack ingredient) { Map<ItemStack, ItemStack> recipes = (Map<ItemStack, ItemStack>) FurnaceRecipes.smelting().getSmeltingList(); for (Entry<ItemStack, ItemStack> recipe : recipes.entrySet()) if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getKey(), ingredient)) { SmeltingPair arecipe = new SmeltingPair(recipe.getKey(), recipe.getValue()); arecipe.setIngredientPermutation(Arrays.asList(arecipe.ingred), ingredient); arecipes.add(arecipe); } } @Override public String getGuiTexture() { return "textures/gui/container/furnace.png"; } @Override public void drawExtras(int recipe) { drawProgressBar(51, 25, 176, 0, 14, 14, 48, 7); drawProgressBar(74, 23, 176, 14, 24, 16, 48, 0); } private static Set<Item> excludedFuels() { Set<Item> efuels = new HashSet<Item>(); efuels.add(Item.getItemFromBlock(Blocks.brown_mushroom)); efuels.add(Item.getItemFromBlock(Blocks.red_mushroom)); efuels.add(Item.getItemFromBlock(Blocks.standing_sign)); efuels.add(Item.getItemFromBlock(Blocks.wall_sign)); efuels.add(Item.getItemFromBlock(Blocks.wooden_door)); efuels.add(Item.getItemFromBlock(Blocks.trapped_chest)); return efuels; } private static void findFuels() { afuels = new ArrayList<FuelPair>(); Set<Item> efuels = excludedFuels(); for (ItemStack item : ItemList.items) if (!efuels.contains(item.getItem())) { int burnTime = TileEntityFurnace.getItemBurnTime(item); if (burnTime > 0) afuels.add(new FuelPair(item.copy(), burnTime)); } } @Override public String getOverlayIdentifier() { return "smelting"; } }
package com.anuragkapur.ds.graph; import java.util.Deque; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; public class BFSAdjacencyMatrix { public int[] printNodesInBFSOrder(int graph[][], int startingNode) { // to track visited nodes Set<Integer> visitedSet = new HashSet<>(); Deque<Integer> queue = new LinkedList<>(); queue.add(startingNode); visitedSet.add(startingNode); int result[] = new int[graph.length]; int runner = 0; while (!queue.isEmpty()) { int current = queue.poll(); result[runner ++] = current; for (int i=0; i<graph[current].length; i++) { // check if edge exists if (graph[current][i] == 1) { // check if already visited if (visitedSet.add(i)) { queue.add(i); } } } } return result; } }
package com.bitsofproof.supernode.core; import java.util.ArrayList; import java.util.List; import org.bouncycastle.util.encoders.Hex; import org.springframework.stereotype.Component; import com.bitsofproof.supernode.model.Blk; import com.bitsofproof.supernode.model.Tx; import com.bitsofproof.supernode.model.TxIn; import com.bitsofproof.supernode.model.TxOut; @Component ("satoshiChain") public class SatoshiChain extends ChainImpl { public static final byte[] SATOSHI_KEY = Hex .decode ("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284"); public SatoshiChain () { super (60001, 0xD9B4BEF9L, 8333, 0, 128, 2015, 1209600, SATOSHI_KEY, new String[] { "dnsseed.bluematt.me", // Matt Corallo "bitseed.xf2.org", // Jeff Garzik "seed.bitcoin.sipa.be", // Pieter Wuille "dnsseed.bitcoin.dashjr.org", // Luke Dashjr }); } @Override public Blk getGenesis () { Blk block = new Blk (); block.setChainWork (1); block.setHeight (1); block.setVersion (1); block.setCreateTime (1231006505L); block.setDifficultyTarget (0x1d00ffffL); block.setNonce (2083236893); block.setPrevious (null); List<Tx> transactions = new ArrayList<Tx> (); block.setTransactions (transactions); Tx t = new Tx (); transactions.add (t); t.setVersion (1); List<TxIn> inputs = new ArrayList<TxIn> (); t.setInputs (inputs); TxIn input = new TxIn (); input.setTransaction (t); inputs.add (input); input.setSource (null); input.setSequence (0xFFFFFFFFL); input.setScript (Hex.decode ("04" + // mimic public key structure "ffff001d" + // difficulty target "010445" + // text: "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks" "5468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73")); List<TxOut> outputs = new ArrayList<TxOut> (); t.setOutputs (outputs); TxOut output = new TxOut (); output.setTransaction (t); outputs.add (output); output.setValue (5000000000L); output.setScript (Hex .decode ("4104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac")); block.computeHash (); return block; } }
package com.blarg.gdx.graphics; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.g3d.decals.Decal; import com.badlogic.gdx.graphics.g3d.decals.DecalBatch; import com.badlogic.gdx.graphics.g3d.decals.DecalMaterial; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; /*** * <p> * Wrapper over libgdx's included {@link DecalBatch} with automatic easy management of * {@link Decal} objects. This is intended to make "on the fly" rendering of decals/billboards * as easy as rendering 2D sprites is with SpriteBatch / DelayedSpriteBatch. * </p> */ public class BillboardSpriteBatch { public enum Type { Spherical, Cylindrical, ScreenAligned } static final Vector3 temp = new Vector3(); static final int CAPACITY_INCREMENT = 128; Array<Decal> sprites; int pointer; boolean hasBegun; DecalBatch decalBatch; Camera camera; public BillboardSpriteBatch() { sprites = new Array<Decal>(true, CAPACITY_INCREMENT, Decal.class); pointer = 0; addNewSprites(CAPACITY_INCREMENT); hasBegun = false; decalBatch = null; } public void begin(DecalBatch decalBatch, Camera camera) { if (hasBegun) throw new IllegalStateException("Cannot be called within an existing begin/end block."); if (decalBatch == null) throw new IllegalArgumentException(); if (camera == null) throw new IllegalArgumentException(); this.decalBatch = decalBatch; this.camera = camera; hasBegun = true; pointer = 0; } public void draw(Type type, Texture texture, float x, float y, float z, float width, float height) { draw(type, texture, x, y, z, width, height, Color.WHITE); } public void draw(Type type, Texture texture, float x, float y, float z, float width, float height, Color tint) { Decal sprite = nextUsable(); TextureRegion textureRegion = sprite.getTextureRegion(); textureRegion.setRegion(texture); sprite.setTextureRegion(textureRegion); sprite.setWidth(width); sprite.setHeight(height); sprite.setPosition(x, y, z); setTintAndBlending(sprite, tint); rotateDecal(sprite, type); } public void draw(Type type, Texture texture, float x, float y, float z, float width, float height, float u, float v, float u2, float v2) { draw(type, texture, x, y, z, width, height, u, v, u2, v2, Color.WHITE); } public void draw(Type type, Texture texture, float x, float y, float z, float width, float height, float u, float v, float u2, float v2, Color tint) { Decal sprite = nextUsable(); TextureRegion textureRegion = sprite.getTextureRegion(); textureRegion.setRegion(texture); textureRegion.setRegion(u, v, u2, v2); sprite.setTextureRegion(textureRegion); sprite.setWidth(width); sprite.setHeight(height); sprite.setPosition(x, y, z); setTintAndBlending(sprite, tint); rotateDecal(sprite, type); } public void flush() { if (!hasBegun) throw new IllegalStateException("Cannot call outside of a begin/end block."); for (int i = 0; i < pointer; ++i) { Decal sprite = sprites.items[i]; decalBatch.add(sprite); } decalBatch.flush(); // don't want to hang on to Texture object references // TODO: is this overkill? does this really make a big difference? for (int i = 0; i < pointer; ++i) sprites.items[i].getTextureRegion().setTexture(null); pointer = 0; } public void end() { if (!hasBegun) throw new IllegalStateException("Must call begin() first."); flush(); hasBegun = false; // don't need to hold on to these references anymore decalBatch = null; camera = null; } private void rotateDecal(Decal decal, Type type) { switch (type) { case Spherical: decal.lookAt(camera.position, Vector3.Y); break; case Cylindrical: temp.set(camera.position) .sub(decal.getPosition()) .nor(); temp.y = 0.0f; decal.setRotation(temp, Vector3.Y); break; case ScreenAligned: temp.set(camera.direction) .scl(-1.0f, -1.0f, -1.0f); // opposite direction to the camera facing dir (point directly out of the screen) decal.setRotation(temp, Vector3.Y); break; } } private void setTintAndBlending(Decal decal, Color tint) { int srcFactor = DecalMaterial.NO_BLEND; int destFactor = DecalMaterial.NO_BLEND; if (tint.a > 0.0f && tint.a < 1.0f) { srcFactor = GL10.GL_SRC_ALPHA; destFactor = GL10.GL_ONE_MINUS_SRC_ALPHA; } decal.setColor(tint); decal.setBlending(srcFactor, destFactor); } private void increaseCapacity() { int newCapacity = sprites.items.length + CAPACITY_INCREMENT; sprites.ensureCapacity(newCapacity); addNewSprites(CAPACITY_INCREMENT); } private void addNewSprites(int count) { for (int i = 0; i < count; ++i) sprites.add(Decal.newDecal(new TextureRegion())); } private int getRemainingSpace() { return sprites.size - pointer; } private Decal nextUsable() { if (getRemainingSpace() == 0) increaseCapacity(); Decal usable = sprites.items[pointer]; pointer++; return usable; } }
package com.haxademic.core.hardware.midi; import com.haxademic.core.app.P; import com.haxademic.core.debug.DebugView; import themidibus.MidiBus; import themidibus.MidiListener; import themidibus.SimpleMidiListener; public class MidiDevice { public MidiBus midiBus; public static MidiDevice instance; public static boolean listedDevices = false; public static MidiDevice init(int midiDeviceInIndex, int midiDeviceOutIndex) { if(instance != null) return instance; instance = new MidiDevice(midiDeviceInIndex, midiDeviceOutIndex, null); return instance; } public static MidiDevice init(int midiDeviceInIndex, int midiDeviceOutIndex, SimpleMidiListener delegate) { if(instance != null) return instance; instance = new MidiDevice(midiDeviceInIndex, midiDeviceOutIndex, delegate); return instance; } public static MidiDevice init(String midiDeviceName) { if(instance != null) return instance; instance = new MidiDevice(midiDeviceName, null); return instance; } public static MidiDevice init(String midiDeviceName, SimpleMidiListener delegate) { if(instance != null) return instance; instance = new MidiDevice(midiDeviceName, delegate); return instance; } public static MidiDevice instance() { return instance; } public static void printDevices() { if(!listedDevices) { MidiBus.list(); listedDevices = true; } } public MidiDevice(int midiDeviceInIndex, int midiDeviceOutIndex, SimpleMidiListener delegate) { printDevices(); new Thread(new Runnable() { public void run() { midiBus = new MidiBus(this, midiDeviceInIndex, midiDeviceOutIndex); midiBus.addMidiListener((MidiListener) MidiState.instance()); if(delegate != null) { midiBus.addMidiListener(delegate); } }}).start(); } public MidiDevice(String midiDeviceName, SimpleMidiListener delegate) { printDevices(); new Thread(new Runnable() { public void run() { midiBus = new MidiBus(this, midiDeviceName, midiDeviceName); midiBus.addMidiListener((MidiListener) MidiState.instance()); if(delegate != null) { midiBus.addMidiListener(delegate); } }}).start(); } public void sendMidiOut(boolean isNoteOn, int channel, int note, int velocity) { if(midiBus == null) { DebugView.setValue("MidiDevice.midiBus not ready", P.p.frameCount); return; } if(isNoteOn) { midiBus.sendNoteOn(channel, note, velocity); } else { midiBus.sendNoteOff(channel, note, velocity); } } }
package com.hp.hpl.jena.graph.test; import java.util.List; import junit.framework.TestSuite; import com.hp.hpl.jena.graph.*; import com.hp.hpl.jena.graph.impl.*; import com.hp.hpl.jena.graph.query.*; import com.hp.hpl.jena.mem.GraphMem; import com.hp.hpl.jena.shared.*; import com.hp.hpl.jena.util.iterator.*; import com.hp.hpl.jena.vocabulary.RDF; public class TestBasicReifier extends AbstractTestReifier { protected final Class graphClass; protected final ReificationStyle style; public TestBasicReifier( Class graphClass, String name, ReificationStyle style ) { super( name ); this.graphClass = graphClass; this.style = style; } public static TestSuite suite() { TestSuite result = new TestSuite(); result.addTest( MetaTestGraph.suite( TestBasicReifier.class, BasicReifierGraph.class ) ); return result; } public Graph getGraph() { return getGraph( style ); } public Graph getGraph( ReificationStyle style ) { return new BasicReifierGraph( new GraphMem( Standard ), style ); } public static final class BasicReifierGraph extends WrappedGraph { protected final ReificationStyle style; public BasicReifierGraph( Graph base, ReificationStyle style ) { super( base ); this.style = style; this.reifier = new BasicReifier( this, style ); } public Graph getBase() { return base; } public void forceAddTriple( Triple t ) { base.add( t ); } public void forceDeleteTriple( Triple t ) { base.delete( t ); } public int size() { return base.size() - reifier.size(); } } public static class BasicReifier implements Reifier { protected final ReificationStyle style; protected final BasicReifierGraph graph; public BasicReifier( Graph graph, ReificationStyle style ) { this.style = style; this.graph = (BasicReifierGraph) graph; } public ExtendedIterator allNodes() { throw new BrokenException( "this reifier operation" ); } public ExtendedIterator allNodes( Triple t ) { throw new BrokenException( "this reifier operation" ); } public void close() { /* nothing to do */ } public ExtendedIterator find( TripleMatch m ) { return style.conceals() ? NullIterator.instance : graph.getBase().find( m ).filterKeep( isReificationTriple ) ; } private static final Filter isReificationTriple = new Filter() { public boolean accept( Object o ) { return isReificationTriple( (Triple) o ); } }; public ExtendedIterator findEither( TripleMatch m, boolean showHidden ) { throw new BrokenException( "this reifier operation" ); } public ExtendedIterator findExposed( TripleMatch m ) { return find( m ); } public Graph getParentGraph() { return graph; } public ReificationStyle getStyle() { return style; } public boolean handledAdd( Triple t ) { graph.forceAddTriple( t ); return isReificationTriple( t ); } public boolean handledRemove( Triple t ) { throw new BrokenException( "this reifier operation" ); } public boolean hasTriple( Node n ) { return getTriple( n ) != null; } public Node reifyAs( Node n, Triple t ) { SimpleReifier.graphAddQuad( graph, n, t ); return n; } public void remove( Node n, Triple t ) { throw new BrokenException( "this reifier operation" ); } public void remove( Triple t ) { throw new BrokenException( "this reifier operation" ); } public int size() { return style.conceals() ? count( find() ) : 0; } private int count( ExtendedIterator find ) { int result = 0; while (find.hasNext()) { result += 1; find.next(); } return result; } private ExtendedIterator find() { return graph.find( Node.ANY, RDF.Nodes.subject, Node.ANY ) .andThen( graph.find( Node.ANY, RDF.Nodes.predicate, Node.ANY ) ) .andThen( graph.find( Node.ANY, RDF.Nodes.object, Node.ANY ) ) .andThen( graph.find( Node.ANY, RDF.Nodes.type, RDF.Nodes.Statement ) ) ; } public boolean hasTriple( Triple t ) { // CHECK: there's one match AND it matches the triple t. Node R = node( "?r" ), S = node( "?s" ), P = node( "?p" ), O = node( "?o" ); Query q = new Query() .addMatch( R, RDF.Nodes.subject, S ) .addMatch( R, RDF.Nodes.predicate, P ) .addMatch( R, RDF.Nodes.object, O ); List bindings = graph.queryHandler().prepareBindings( q, new Node[] {R, S, P, O} ).executeBindings().toList(); return bindings.size() == 1 && t.equals( tripleFrom( (Domain) bindings.get( 0 ) ) ); } private Triple tripleFrom( Domain domain ) { return Triple.create ( (Node) domain.get(1), (Node) domain.get(2), (Node) domain.get(3) ); } public Triple getTriple( Node n ) { Node S = node( "?s" ), P = node( "?p" ), O = node( "?o" ); Query q = new Query() .addMatch( n, RDF.Nodes.subject, S ) .addMatch( n, RDF.Nodes.predicate, P ) .addMatch( n, RDF.Nodes.object, O ) .addMatch( n, RDF.Nodes.type, RDF.Nodes.Statement ); List bindings = graph.queryHandler().prepareBindings( q, new Node[] {S, P, O} ).executeBindings().toList(); return bindings.size() == 1 ? triple( (Domain) bindings.get(0) ) : null; } private Triple triple( Domain d ) { return Triple.create( d.getElement( 0 ), d.getElement( 1 ), d.getElement( 2 ) ); } private static boolean isReificationTriple( Triple t ) { return Reifier.Util.isReificationPredicate( t.getPredicate() ) || Reifier.Util.isReificationType( t.getPredicate(), t.getObject() ) ; } } }
package com.littlepanpc.download.widgets; import java.util.HashMap; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import com.littlepanpc.download.services.DownloadTask; import com.littlepanpc.download.utils.NetworkUtils; import com.littlepanpc.android_download_manager.R; public class ViewHolder { public static final int KEY_URL = 0; public static final int KEY_SPEED = 1; public static final int KEY_PROGRESS = 2; public static final int KEY_IS_PAUSED = 3; public TextView titleText; public ProgressBar progressBar; public TextView speedText; public Button pauseButton; public Button deleteButton; public Button continueButton; private boolean hasInited = false; public ViewHolder(View parentView) { if (parentView != null) { titleText = (TextView) parentView.findViewById(R.id.title); speedText = (TextView) parentView.findViewById(R.id.speed); progressBar = (ProgressBar) parentView .findViewById(R.id.progress_bar); pauseButton = (Button) parentView.findViewById(R.id.btn_pause); deleteButton = (Button) parentView.findViewById(R.id.btn_delete); continueButton = (Button) parentView .findViewById(R.id.btn_continue); hasInited = true; } } @SuppressLint("UseSparseArrays") public static HashMap<Integer, String> getItemDataMap(String url, String speed, String progress, String isPaused) { HashMap<Integer, String> item = new HashMap<Integer, String>(); item.put(KEY_URL, url); item.put(KEY_SPEED, speed); item.put(KEY_PROGRESS, progress); item.put(KEY_IS_PAUSED, isPaused); return item; } public void setData(HashMap<Integer, String> item) { if (hasInited) { titleText .setText(NetworkUtils.getFileNameFromUrl(item.get(KEY_URL))); speedText.setText(item.get(KEY_SPEED)); String progress = item.get(KEY_PROGRESS); if (TextUtils.isEmpty(progress)) { progressBar.setProgress(0); } else { progressBar.setProgress(Integer.parseInt(progress)); } if (Boolean.parseBoolean(item.get(KEY_IS_PAUSED))) { onPause(); } } } public void onPause() { if (hasInited) { pauseButton.setVisibility(View.GONE); continueButton.setVisibility(View.VISIBLE); } } public void setData(String url, String speed, String progress) { setData(url, speed, progress, false + ""); } public void setData(String url, String speed, String progress, String isPaused) { if (hasInited) { HashMap<Integer, String> item = getItemDataMap(url, speed, progress, isPaused); titleText .setText(NetworkUtils.getFileNameFromUrl(item.get(KEY_URL))); speedText.setText(speed); if (TextUtils.isEmpty(progress)) { progressBar.setProgress(0); } else { progressBar .setProgress(Integer.parseInt(item.get(KEY_PROGRESS))); } } } public void bindTask(DownloadTask task) { if (hasInited) { titleText.setText(NetworkUtils.getFileNameFromUrl(task.getUrl())); speedText.setText(task.getDownloadSpeed() + "kbps | " + task.getDownloadSize() + " / " + task.getTotalSize()); progressBar.setProgress((int) task.getDownloadPercent()); if (task.isInterrupted()) { onPause(); } } } }
package com.topsradiance.anonymeyes.backend; public class Cleaner extends Thread { @Override public void run() { while(true) { try { long cTime = System.currentTimeMillis(); for(Long id : Server.handlerMap.keySet()) { Handler h = Server.handlerMap.get(id); if(cTime - h.lastMessage >= 5000) { h.exit(); } } try { Thread.sleep(2500); } catch(InterruptedException e) {} } catch(Exception e) { e.printStackTrace(); } } } }
package nallar.tickthreading.patcher; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Splitter; import javassist.CannotCompileException; import javassist.ClassMap; import javassist.CtBehavior; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtField; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.CtPrimitiveType; import javassist.Modifier; import javassist.NotFoundException; import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.AttributeInfo; import javassist.bytecode.BadBytecode; import javassist.bytecode.ClassFile; import javassist.bytecode.CodeAttribute; import javassist.bytecode.CodeIterator; import javassist.bytecode.ConstPool; import javassist.bytecode.Descriptor; import javassist.bytecode.DuplicateMemberException; import javassist.bytecode.MethodInfo; import javassist.bytecode.Mnemonic; import javassist.bytecode.Opcode; import javassist.expr.Cast; import javassist.expr.ConstructorCall; import javassist.expr.ExprEditor; import javassist.expr.FieldAccess; import javassist.expr.Handler; import javassist.expr.Instanceof; import javassist.expr.MethodCall; import javassist.expr.NewArray; import javassist.expr.NewExpr; import nallar.insecurity.ThisIsNotAnError; import nallar.tickthreading.Log; import nallar.tickthreading.mappings.MethodDescription; import nallar.tickthreading.util.CollectionsUtil; import nallar.tickthreading.util.MappingUtil; import nallar.tickthreading.util.ReflectUtil; import nallar.unsafe.UnsafeUtil; import org.omg.CORBA.IntHolder; @SuppressWarnings ({"MethodMayBeStatic", "ObjectAllocationInLoop"}) public class Patches { private final PatchManager patchManager; private final ClassRegistry classRegistry; public Patches(PatchManager patchManager, ClassRegistry classRegistry) { this.patchManager = patchManager; this.classRegistry = classRegistry; } @SuppressWarnings ("EmptyMethod") @Patch public void markDirty(CtClass ctClass) { // A NOOP patch to make sure META-INF is removed } @Patch public void remove(CtMethod ctMethod) { ctMethod.setName(ctMethod.getName() + "_rem"); } @Patch ( requiredAttributes = "code" ) public void newMethod(CtClass ctClass, Map<String, String> attributes) throws CannotCompileException { try { ctClass.addMethod(CtNewMethod.make(attributes.get("code"), ctClass)); } catch (DuplicateMemberException e) { if (!attributes.containsKey("ignoreDuplicate")) { throw e; } } } @Patch ( requiredAttributes = "type,field" ) public void changeFieldType(final CtClass ctClass, Map<String, String> attributes) throws CannotCompileException, NotFoundException { final String field = attributes.get("field"); CtField oldField = ctClass.getDeclaredField(field); oldField.setName(field + "_old"); String newType = attributes.get("type"); CtField ctField = new CtField(classRegistry.getClass(newType), field, ctClass); ctField.setModifiers(oldField.getModifiers()); ctClass.addField(ctField); Set<CtBehavior> allBehaviours = new HashSet<CtBehavior>(); Collections.addAll(allBehaviours, ctClass.getDeclaredConstructors()); Collections.addAll(allBehaviours, ctClass.getDeclaredMethods()); CtBehavior initialiser = ctClass.getClassInitializer(); if (initialiser != null) { allBehaviours.add(initialiser); } final boolean remove = attributes.containsKey("remove"); for (CtBehavior ctBehavior : allBehaviours) { ctBehavior.instrument(new ExprEditor() { @Override public void edit(FieldAccess fieldAccess) throws CannotCompileException { if (fieldAccess.getClassName().equals(ctClass.getName()) && fieldAccess.getFieldName().equals(field)) { if (fieldAccess.isReader()) { if (remove) { fieldAccess.replace("$_ = null;"); } else { fieldAccess.replace("$_ = $0." + field + ';'); } } else if (fieldAccess.isWriter()) { if (remove) { fieldAccess.replace("$_ = null;"); } else { fieldAccess.replace("$0." + field + " = $1;"); } } } } }); } } @Patch ( requiredAttributes = "from,to" ) public void replaceConstants(CtClass ctClass, Map<String, String> attributes) { String from = attributes.get("from"); String to = attributes.get("to"); ConstPool constPool = ctClass.getClassFile().getConstPool(); for (int i = 0; true; i++) { String utf8Info; try { utf8Info = constPool.getUtf8Info(i); } catch (ClassCastException ignored) { continue; } catch (NullPointerException e) { break; } if (utf8Info.equals(from)) { Object o = ReflectUtil.call(constPool, "getItem", i); try { ReflectUtil.getField(Class.forName("javassist.bytecode.ConstPool$Utf8Info"), "string").set(o, to); } catch (Exception e) { Log.severe("Couldn't set constant value", e); } } } } @Patch ( requiredAttributes = "field", emptyConstructor = false ) public void replaceInitializer(final Object o, Map<String, String> attributes) throws CannotCompileException, NotFoundException { final String field = attributes.get("field"); CtClass ctClass = o instanceof CtClass ? (CtClass) o : null; CtBehavior ctBehavior = null; if (ctClass == null) { ctBehavior = (CtBehavior) o; ctClass = ctBehavior.getDeclaringClass(); } String ctFieldClass = attributes.get("fieldClass"); if (ctFieldClass != null) { if (ctClass == o) { Log.info("Must set methods to run on if using fieldClass."); return; } ctClass = classRegistry.getClass(ctFieldClass); } final CtField ctField = ctClass.getDeclaredField(field); String code = attributes.get("code"); String clazz = attributes.get("class"); if (code == null && clazz == null) { throw new NullPointerException("Must give code or class"); } final String newInitialiser = code == null ? "$_ = new " + clazz + "();" : code; Set<CtBehavior> allBehaviours = new HashSet<CtBehavior>(); if (ctBehavior == null) { Collections.addAll(allBehaviours, ctClass.getDeclaredConstructors()); CtBehavior initialiser = ctClass.getClassInitializer(); if (initialiser != null) { allBehaviours.add(initialiser); } } else { allBehaviours.add(ctBehavior); } final IntHolder replaced = new IntHolder(); for (CtBehavior ctBehavior_ : allBehaviours) { final Map<Integer, String> newExprType = new HashMap<Integer, String>(); ctBehavior_.instrument(new ExprEditor() { NewExpr lastNewExpr; int newPos = 0; @Override public void edit(NewExpr e) { lastNewExpr = null; newPos++; try { if (classRegistry.getClass(e.getClassName()).subtypeOf(ctField.getType())) { lastNewExpr = e; } } catch (NotFoundException ignored) { } } @Override public void edit(FieldAccess e) { NewExpr myLastNewExpr = lastNewExpr; lastNewExpr = null; if (myLastNewExpr != null && e.getFieldName().equals(field)) { newExprType.put(newPos, classSignatureToName(e.getSignature())); } } @Override public void edit(MethodCall e) { lastNewExpr = null; } @Override public void edit(NewArray e) { lastNewExpr = null; } @Override public void edit(Cast e) { lastNewExpr = null; } @Override public void edit(Instanceof e) { lastNewExpr = null; } @Override public void edit(Handler e) { lastNewExpr = null; } @Override public void edit(ConstructorCall e) { lastNewExpr = null; } }); ctBehavior_.instrument(new ExprEditor() { int newPos = 0; @Override public void edit(NewExpr e) throws CannotCompileException { newPos++; if (newExprType.containsKey(newPos)) { String assignedType = newExprType.get(newPos); String block = '{' + newInitialiser + '}'; Log.fine(assignedType + " at " + e.getFileName() + ':' + e.getLineNumber() + " replaced with " + block); e.replace(block); replaced.value++; } } }); } if (replaced.value == 0 && !attributes.containsKey("silent")) { Log.severe("No field initializers found for replacement"); } } @Patch public void replaceNew(Object o, Map<String, String> attributes) throws CannotCompileException, NotFoundException { final String type = attributes.get("oldClass"); final String code = attributes.get("code"); final String clazz = attributes.get("newClass"); if (code == null && clazz == null) { throw new NullPointerException("Must give code or class"); } final String newInitialiser = code == null ? "$_ = new " + clazz + "();" : code; final Set<CtBehavior> allBehaviours = new HashSet<CtBehavior>(); if (o instanceof CtClass) { CtClass ctClass = (CtClass) o; Collections.addAll(allBehaviours, ctClass.getDeclaredConstructors()); final CtBehavior initialiser = ctClass.getClassInitializer(); if (initialiser != null) { allBehaviours.add(initialiser); } } else { allBehaviours.add((CtBehavior) o); } final IntHolder done = new IntHolder(); for (CtBehavior ctBehavior : allBehaviours) { ctBehavior.instrument(new ExprEditor() { @Override public void edit(NewExpr e) throws CannotCompileException { if (e.getClassName().equals(type)) { e.replace(newInitialiser); done.value++; } } }); } if (done.value == 0) { Log.severe("No new expressions found for replacement."); } } @Patch public void profile(CtMethod ctMethod, Map<String, String> attributes) throws CannotCompileException, NotFoundException { CtClass ctClass = ctMethod.getDeclaringClass(); CtMethod replacement = CtNewMethod.copy(ctMethod, ctClass, null); int i = 0; String deobf = attributes.get("deobf"); if (deobf == null) { deobf = ctMethod.getDeclaringClass().getName() + '/' + ctMethod.getName(); } String suffix = '_' + deobf.replace('/', '_').replace('.', '_') + "_p"; try { //noinspection InfiniteLoopStatement for (; true; i++) { ctClass.getDeclaredMethod(ctMethod.getName() + suffix + i, ctMethod.getParameterTypes()); } } catch (NotFoundException ignored) { } ctMethod.setName(ctMethod.getName() + suffix + i); if (ctMethod.getReturnType() == CtPrimitiveType.voidType) { replacement.setBody("{ boolean timings = nallar.tickthreading.minecraft.profiling.Timings.enabled; long st = 0; if (timings) { st = System.nanoTime(); } " + ctMethod.getName() + "($$); if (timings) { nallar.tickthreading.minecraft.profiling.Timings.record(\"" + deobf + "\", System.nanoTime() - st); } }"); } else { replacement.setBody("{ boolean timings = nallar.tickthreading.minecraft.profiling.Timings.enabled; long st = 0; if (timings) { st = System.nanoTime(); } try { return " + ctMethod.getName() + "($$); } finally { if (timings) { nallar.tickthreading.minecraft.profiling.Timings.record(\"" + deobf + "\", System.nanoTime() - st); } } }"); } ctClass.addMethod(replacement); } @Patch ( name = "volatile", requiredAttributes = "field" ) public void volatile_(CtClass ctClass, Map<String, String> attributes) throws NotFoundException { String field = attributes.get("field"); if (field == null) { for (CtField ctField : ctClass.getDeclaredFields()) { if (ctField.getType().isPrimitive()) { ctField.setModifiers(ctField.getModifiers() | Modifier.VOLATILE); } } } else { CtField ctField = ctClass.getDeclaredField(field); ctField.setModifiers(ctField.getModifiers() | Modifier.VOLATILE); } } @Patch ( requiredAttributes = "field" ) public void unvolatile(CtClass ctClass, Map<String, String> attributes) throws NotFoundException { String field = attributes.get("field"); if (field == null) { for (CtField ctField : ctClass.getDeclaredFields()) { if (ctField.getType().isPrimitive()) { ctField.setModifiers(ctField.getModifiers() & ~Modifier.VOLATILE); } } } else { CtField ctField = ctClass.getDeclaredField(field); ctField.setModifiers(ctField.getModifiers() & ~Modifier.VOLATILE); } } @Patch ( name = "final" ) public void final_(CtClass ctClass, Map<String, String> attributes) throws NotFoundException { String field = attributes.get("field"); if (field == null) { for (CtField ctField : ctClass.getDeclaredFields()) { if (ctField.getType().isPrimitive()) { ctField.setModifiers(ctField.getModifiers() | Modifier.FINAL); } } } else { CtField ctField = ctClass.getDeclaredField(field); ctField.setModifiers(ctField.getModifiers() | Modifier.FINAL); } } @Patch public void disable(CtMethod ctMethod, Map<String, String> attributes) throws NotFoundException, CannotCompileException { ctMethod.setBody("{ }"); } @Patch ( requiredAttributes = "class" ) public CtClass replace(CtClass clazz, Map<String, String> attributes) throws NotFoundException, CannotCompileException, BadBytecode { String fromClass = attributes.get("class"); String oldName = clazz.getName(); clazz.setName(oldName + "_old"); CtClass newClass = classRegistry.getClass(fromClass); ClassFile classFile = newClass.getClassFile2(); if (classFile.getSuperclass().equals(oldName)) { classFile.setSuperclass(null); for (CtConstructor ctBehavior : newClass.getDeclaredConstructors()) { javassist.bytecode.MethodInfo methodInfo = ctBehavior.getMethodInfo2(); CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); if (codeAttribute != null) { CodeIterator iterator = codeAttribute.iterator(); int pos = iterator.skipSuperConstructor(); if (pos >= 0) { int mref = iterator.u16bitAt(pos + 1); ConstPool constPool = codeAttribute.getConstPool(); iterator.write16bit(constPool.addMethodrefInfo(constPool.addClassInfo("java.lang.Object"), "<init>", "()V"), pos + 1); String desc = constPool.getMethodrefType(mref); int num = Descriptor.numOfParameters(desc) + 1; pos = iterator.insertGapAt(pos, num, false).position; Descriptor.Iterator i$ = new Descriptor.Iterator(desc); for (i$.next(); i$.isParameter(); i$.next()) { iterator.writeByte(i$.is2byte() ? Opcode.POP2 : Opcode.POP, pos++); } } methodInfo.rebuildStackMapIf6(newClass.getClassPool(), newClass.getClassFile2()); } } } newClass.setName(oldName); newClass.setModifiers(newClass.getModifiers() & ~Modifier.ABSTRACT); publicInnerClasses(fromClass); return newClass; } @Patch public void publicInnerClasses(String outer) { boolean exists = true; for (int i = 1; exists; i++) { try { String innerName = outer + '$' + i; CtClass innerClass = classRegistry.getClass(innerName); public_(innerClass, Collections.<String, String>emptyMap()); Log.info("Made " + innerName + " public."); patchManager.patchingClasses.put(innerName, innerClass); } catch (NotFoundException e) { exists = false; } } } @Patch public void replaceMethod(CtBehavior method, Map<String, String> attributes) throws NotFoundException, CannotCompileException, BadBytecode { String fromClass = attributes.get("fromClass"); String code = attributes.get("code"); String field = attributes.get("field"); if (field != null) { code = code.replace("$field", field); } if (fromClass != null) { String fromMethod = attributes.get("fromMethod"); CtMethod replacingMethod = fromMethod == null ? classRegistry.getClass(fromClass).getDeclaredMethod(method.getName(), method.getParameterTypes()) : MethodDescription.fromString(fromClass, fromMethod).inClass(classRegistry.getClass(fromClass)); replaceMethod((CtMethod) method, replacingMethod); } else if (code != null) { method.setBody(code); } else { Log.severe("Missing required attributes for replaceMethod"); } } private void replaceMethod(CtMethod oldMethod, CtMethod newMethod) throws CannotCompileException, BadBytecode { ClassMap classMap = new ClassMap(); classMap.put(newMethod.getDeclaringClass().getName(), oldMethod.getDeclaringClass().getName()); oldMethod.setBody(newMethod, classMap); oldMethod.getMethodInfo().rebuildStackMap(classRegistry.classes); oldMethod.getMethodInfo().rebuildStackMapForME(classRegistry.classes); } @Patch ( requiredAttributes = "field" ) public void replaceFieldUsage(final CtBehavior ctBehavior, Map<String, String> attributes) throws CannotCompileException { final String field = attributes.get("field"); final String readCode = attributes.get("readCode"); final String writeCode = attributes.get("writeCode"); final String clazz = attributes.get("class"); final boolean removeAfter = attributes.containsKey("removeAfter"); if (readCode == null && writeCode == null) { throw new IllegalArgumentException("readCode or writeCode must be set"); } final IntHolder replaced = new IntHolder(); try { ctBehavior.instrument(new ExprEditor() { @Override public void edit(FieldAccess fieldAccess) throws CannotCompileException { String fieldName; try { fieldName = fieldAccess.getFieldName(); } catch (ClassCastException e) { Log.warning("Can't examine field access at " + fieldAccess.getLineNumber() + " which is a r: " + fieldAccess.isReader() + " w: " + fieldAccess.isWriter()); return; } if ((clazz == null || fieldAccess.getClassName().equals(clazz)) && fieldName.equals(field)) { if (removeAfter) { try { removeAfterIndex(ctBehavior, fieldAccess.indexOfBytecode()); } catch (BadBytecode badBytecode) { throw UnsafeUtil.throwIgnoreChecked(badBytecode); } throw new ThisIsNotAnError(); } if (fieldAccess.isWriter() && writeCode != null) { fieldAccess.replace(writeCode); } else if (fieldAccess.isReader() && readCode != null) { fieldAccess.replace(readCode); Log.info("Replaced in " + ctBehavior + ' ' + fieldName + " read with " + readCode); } replaced.value++; } } }); } catch (ThisIsNotAnError ignored) { } if (replaced.value == 0 && !attributes.containsKey("silent")) { Log.severe("Didn't replace any field accesses."); } } @Patch public void replaceMethodCall(final CtBehavior ctBehavior, Map<String, String> attributes) throws CannotCompileException { String method_ = attributes.get("method"); if (method_ == null) { method_ = ""; } String className_ = null; int dotIndex = method_.lastIndexOf('.'); if (dotIndex != -1) { className_ = method_.substring(0, dotIndex); method_ = method_.substring(dotIndex + 1); } if ("self".equals(className_)) { className_ = ctBehavior.getDeclaringClass().getName(); } String index_ = attributes.get("index"); if (index_ == null) { index_ = "-1"; } final String method = method_; final String className = className_; final String newMethod = attributes.get("newMethod"); String code_ = attributes.get("code"); if (code_ == null) { code_ = "$_ = $0." + newMethod + "($$);"; } final String code = code_; final IntHolder replaced = new IntHolder(); final int index = Integer.valueOf(index_); final boolean removeAfter = attributes.containsKey("removeAfter"); try { ctBehavior.instrument(new ExprEditor() { private int currentIndex = 0; @Override public void edit(MethodCall methodCall) throws CannotCompileException { if ((className == null || methodCall.getClassName().equals(className)) && (method.isEmpty() || methodCall.getMethodName().equals(method)) && (index == -1 || currentIndex++ == index)) { if (newMethod != null) { try { CtMethod oldMethod = methodCall.getMethod(); oldMethod.getDeclaringClass().getDeclaredMethod(newMethod, oldMethod.getParameterTypes()); } catch (NotFoundException e) { return; } } replaced.value++; Log.info("Replaced call to " + methodCall.getClassName() + '/' + methodCall.getMethodName() + " in " + ctBehavior.getLongName()); if (removeAfter) { try { removeAfterIndex(ctBehavior, methodCall.indexOfBytecode()); } catch (BadBytecode badBytecode) { throw UnsafeUtil.throwIgnoreChecked(badBytecode); } throw new ThisIsNotAnError(); } methodCall.replace(code); } } }); } catch (ThisIsNotAnError ignored) { } if (replaced.value == 0 && !attributes.containsKey("silent")) { Log.warning("Didn't find any method calls to replace"); } } @Patch ( requiredAttributes = "code,return,name" ) public void addMethod(CtClass ctClass, Map<String, String> attributes) throws NotFoundException, CannotCompileException { String name = attributes.get("name"); String return_ = attributes.get("return"); String code = attributes.get("code"); String parameterNamesList = attributes.get("parameters"); parameterNamesList = parameterNamesList == null ? "" : parameterNamesList; List<CtClass> parameterList = new ArrayList<CtClass>(); for (String parameterName : Splitter.on(',').trimResults().omitEmptyStrings().split(parameterNamesList)) { parameterList.add(classRegistry.getClass(parameterName)); } CtMethod newMethod = new CtMethod(classRegistry.getClass(return_), name, parameterList.toArray(new CtClass[parameterList.size()]), ctClass); newMethod.setBody('{' + code + '}'); ctClass.addMethod(newMethod); } @Patch ( requiredAttributes = "opcode" ) public void removeUntilOpcode(CtBehavior ctBehavior, Map<String, String> attributes) throws BadBytecode { int opcode = Arrays.asList(Mnemonic.OPCODE).indexOf(attributes.get("opcode").toLowerCase()); String removeIndexString = attributes.get("index"); int removeIndex = removeIndexString == null ? -1 : Integer.parseInt(removeIndexString); int currentIndex = 0; Log.info("Removing until " + attributes.get("opcode") + ':' + opcode + " at " + removeIndex); CtClass ctClass = ctBehavior.getDeclaringClass(); MethodInfo methodInfo = ctBehavior.getMethodInfo2(); CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); if (codeAttribute != null) { CodeIterator iterator = codeAttribute.iterator(); while (iterator.hasNext()) { int index = iterator.next(); int op = iterator.byteAt(index); if (op == opcode && (removeIndex == -1 || removeIndex == ++currentIndex)) { for (int i = 0; i <= index; i++) { iterator.writeByte(Opcode.NOP, i); } } } methodInfo.rebuildStackMapIf6(ctClass.getClassPool(), ctClass.getClassFile2()); } } private void removeAfterIndex(CtBehavior ctBehavior, int index) throws BadBytecode { Log.info("Removed after " + index + " in " + ctBehavior.getLongName()); CtClass ctClass = ctBehavior.getDeclaringClass(); MethodInfo methodInfo = ctBehavior.getMethodInfo2(); CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); if (codeAttribute != null) { CodeIterator iterator = codeAttribute.iterator(); int i, length = iterator.getCodeLength() - 1; for (i = index; i < length; i++) { iterator.writeByte(Opcode.NOP, i); } iterator.writeByte(Opcode.RETURN, i); methodInfo.rebuildStackMapIf6(ctClass.getClassPool(), ctClass.getClassFile2()); } } @Patch ( requiredAttributes = "fromClass" ) public void addAll(CtClass ctClass, Map<String, String> attributes) throws NotFoundException, CannotCompileException, BadBytecode { String fromClass = attributes.get("fromClass"); CtClass from = classRegistry.getClass(fromClass); ClassMap classMap = new ClassMap(); classMap.put(fromClass, ctClass.getName()); for (CtField ctField : from.getDeclaredFields()) { if (!ctField.getName().isEmpty() && ctField.getName().charAt(ctField.getName().length() - 1) == '_') { ctField.setName(ctField.getName().substring(0, ctField.getName().length() - 1)); } CtClass expectedType = ctField.getType(); boolean expectStatic = (ctField.getModifiers() & Modifier.STATIC) == Modifier.STATIC; String fieldName = ctField.getName(); try { CtClass type = ctClass.getDeclaredField(fieldName).getType(); if (type != expectedType) { Log.severe("Field " + fieldName + " already exists, but as a different type. Exists: " + type + ", expected: " + expectedType); removeField(ctClass, CollectionsUtil.<String, String>map("field", fieldName)); throw new NotFoundException(""); } boolean isStatic = (ctField.getModifiers() & Modifier.STATIC) == Modifier.STATIC; if (isStatic != expectStatic) { Log.severe("Can't add field " + fieldName + " as it already exists, but it is static: " + isStatic + " and we expected: " + expectStatic); } } catch (NotFoundException ignored) { ctClass.addField(new CtField(ctField, ctClass)); } if (expectStatic) { CtBehavior initializer = ctClass.getClassInitializer(); if (initializer != null) { removeInitializers(initializer, ctField); } } } for (CtMethod newMethod : from.getDeclaredMethods()) { if ((newMethod.getName().startsWith("construct") || newMethod.getName().startsWith("staticConstruct"))) { try { ctClass.getDeclaredMethod(newMethod.getName()); boolean found = true; int i = 0; String name = newMethod.getName(); while (found) { i++; try { ctClass.getDeclaredMethod(name + i); } catch (NotFoundException e2) { found = false; } } newMethod.setName(name + i); } catch (NotFoundException ignored) { // Not found - no need to change the name } } } for (CtMethod newMethod : from.getDeclaredMethods()) { try { CtMethod oldMethod = ctClass.getDeclaredMethod(newMethod.getName(), newMethod.getParameterTypes()); replaceMethod(oldMethod, newMethod); if (Modifier.isSynchronized(newMethod.getModifiers())) { oldMethod.setModifiers(oldMethod.getModifiers() | Modifier.SYNCHRONIZED); } } catch (NotFoundException ignored) { CtMethod added = CtNewMethod.copy(newMethod, ctClass, classMap); ctClass.addMethod(added); MethodInfo addedMethodInfo = added.getMethodInfo2(); String addedDescriptor = addedMethodInfo.getDescriptor(); String newDescriptor = newMethod.getMethodInfo2().getDescriptor(); if (!newDescriptor.equals(addedDescriptor)) { addedMethodInfo.setDescriptor(newDescriptor); } replaceMethod(added, newMethod); if (added.getName().startsWith("construct")) { try { insertSuper(added); } catch (CannotCompileException ignore) { } CtMethod runConstructors; try { runConstructors = ctClass.getMethod("runConstructors", "()V"); } catch (NotFoundException e) { runConstructors = CtNewMethod.make("public void runConstructors() { }", ctClass); ctClass.addMethod(runConstructors); try { ctClass.getField("isConstructed"); } catch (NotFoundException ignore) { ctClass.addField(new CtField(classRegistry.getClass("boolean"), "isConstructed", ctClass)); } for (CtBehavior ctBehavior : ctClass.getDeclaredConstructors()) { ctBehavior.insertAfter("{ if(!this.isConstructed) { this.isConstructed = true; this.runConstructors(); } }"); } } try { ctClass.getSuperclass().getMethod(added.getName(), "()V"); } catch (NotFoundException ignore) { runConstructors.insertAfter(added.getName() + "();"); } } if (added.getName().startsWith("staticConstruct")) { ctClass.makeClassInitializer().insertAfter("{ " + added.getName() + "(); }"); } } } for (CtClass CtInterface : from.getInterfaces()) { ctClass.addInterface(CtInterface); } CtConstructor initializer = from.getClassInitializer(); if (initializer != null) { ctClass.addMethod(initializer.toMethod("patchStaticInitializer", ctClass)); ctClass.makeClassInitializer().insertAfter("patchStaticInitializer();"); } publicInnerClasses(fromClass); } private void removeInitializers(CtBehavior ctBehavior, final CtField ctField) throws CannotCompileException, NotFoundException { replaceInitializer(ctBehavior, CollectionsUtil.<String, String>map( "field", ctField.getName(), "code", "{ $_ = null; }", "silent", "true")); replaceFieldUsage(ctBehavior, CollectionsUtil.<String, String>map( "field", ctField.getName(), "writeCode", "{ }", "readCode", "{ }", "silent", "true")); } @Patch ( requiredAttributes = "field,threadLocalField,type" ) public void threadLocal(CtClass ctClass, Map<String, String> attributes) throws CannotCompileException { final String field = attributes.get("field"); final String threadLocalField = attributes.get("threadLocalField"); final String type = attributes.get("type"); String setExpression_ = attributes.get("setExpression"); final String setExpression = setExpression_ == null ? '(' + type + ") $1" : setExpression_; Log.info(field + " -> " + threadLocalField); ctClass.instrument(new ExprEditor() { @Override public void edit(FieldAccess e) throws CannotCompileException { if (e.getFieldName().equals(field)) { if (e.isReader()) { e.replace("{ $_ = (" + type + ") " + threadLocalField + ".get(); }"); } else if (e.isWriter()) { e.replace("{ " + threadLocalField + ".set(" + setExpression + "); }"); } } } }); } @Patch ( requiredAttributes = "field,threadLocalField" ) public void threadLocalBoolean(CtClass ctClass, Map<String, String> attributes) throws CannotCompileException { final String field = attributes.get("field"); final String threadLocalField = attributes.get("threadLocalField"); Log.info(field + " -> " + threadLocalField); for (CtConstructor ctConstructor : ctClass.getDeclaredConstructors()) { ctConstructor.instrument(new ExprEditor() { @Override public void edit(FieldAccess e) throws CannotCompileException { if (e.getFieldName().equals(field)) { if (e.isWriter()) { e.replace("{ }"); } } } }); } ctClass.instrument(new ExprEditor() { @Override public void edit(FieldAccess e) throws CannotCompileException { if (e.getFieldName().equals(field)) { if (e.isReader()) { e.replace("{ $_ = ((Boolean) " + threadLocalField + ".get()).booleanValue(); }"); } else if (e.isWriter()) { e.replace("{ " + threadLocalField + ".set(Boolean.valueOf($1)); }"); } } } }); } @Patch ( name = "public", emptyConstructor = false ) public void public_(Object o, Map<String, String> attributes) throws NotFoundException { String field = attributes.get("field"); if (field != null) { CtClass ctClass = (CtClass) o; CtField ctField = ctClass.getDeclaredField(field); ctField.setModifiers(Modifier.setPublic(ctField.getModifiers())); } else if (o instanceof CtClass) { CtClass ctClass = (CtClass) o; ctClass.setModifiers(Modifier.setPublic(ctClass.getModifiers())); List<Object> toPublic = new ArrayList<Object>(); if (attributes.containsKey("all")) { Collections.addAll(toPublic, ctClass.getDeclaredFields()); Collections.addAll(toPublic, ctClass.getDeclaredBehaviors()); } else { Collections.addAll(toPublic, ctClass.getDeclaredConstructors()); } for (Object o_ : toPublic) { public_(o_, Collections.<String, String>emptyMap()); } } else if (o instanceof CtField) { CtField ctField = (CtField) o; ctField.setModifiers(Modifier.setPublic(ctField.getModifiers())); } else { CtBehavior ctBehavior = (CtBehavior) o; ctBehavior.setModifiers(Modifier.setPublic(ctBehavior.getModifiers())); } } @Patch ( emptyConstructor = false ) public void noFinal(Object o, Map<String, String> attributes) throws NotFoundException { String field = attributes.get("field"); if (field != null) { CtClass ctClass = (CtClass) o; CtField ctField = ctClass.getDeclaredField(field); ctField.setModifiers(Modifier.clear(ctField.getModifiers(), Modifier.FINAL)); } else if (o instanceof CtClass) { CtClass ctClass = (CtClass) o; ctClass.setModifiers(Modifier.setPublic(ctClass.getModifiers())); for (CtConstructor ctConstructor : ctClass.getDeclaredConstructors()) { public_(ctConstructor, Collections.<String, String>emptyMap()); } } else { CtBehavior ctBehavior = (CtBehavior) o; ctBehavior.setModifiers(Modifier.clear(ctBehavior.getModifiers(), Modifier.FINAL)); } } @Patch ( requiredAttributes = "field" ) public void newInitializer(CtClass ctClass, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException { String field = attributes.get("field"); String clazz = attributes.get("class"); String initialise = attributes.get("code"); String arraySize = attributes.get("arraySize"); initialise = "{ " + field + " = " + (initialise == null ? ("new " + clazz + (arraySize == null ? "()" : '[' + arraySize + ']')) : initialise) + "; }"; if ((ctClass.getDeclaredField(field).getModifiers() & Modifier.STATIC) == Modifier.STATIC) { ctClass.makeClassInitializer().insertAfter(initialise); } else { CtMethod runConstructors; try { runConstructors = ctClass.getDeclaredMethod("runConstructors"); } catch (NotFoundException e) { runConstructors = CtNewMethod.make("public void runConstructors() { }", ctClass); ctClass.addMethod(runConstructors); ctClass.addField(new CtField(classRegistry.getClass("boolean"), "isConstructed", ctClass), CtField.Initializer.constant(false)); for (CtBehavior ctBehavior : ctClass.getDeclaredConstructors()) { ctBehavior.insertAfter("{ if(!this.isConstructed) { this.isConstructed = true; this.runConstructors(); } }"); } } runConstructors.insertAfter(initialise); } } @Patch ( requiredAttributes = "field" ) public void replaceField(CtClass ctClass, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException { String field = attributes.get("field"); String clazz = attributes.get("class"); String type = attributes.get("type"); if (type == null) { type = clazz; } String initialise = attributes.get("code"); String arraySize = attributes.get("arraySize"); initialise = "{ " + field + " = " + (initialise == null ? ("new " + clazz + (arraySize == null ? "()" : '[' + arraySize + ']')) : initialise) + "; }"; CtField oldField = ctClass.getDeclaredField(field); oldField.setName(oldField.getName() + "_rem"); CtField newField = new CtField(classRegistry.getClass(type), field, ctClass); newField.setModifiers(oldField.getModifiers()); ctClass.addField(newField); for (CtConstructor ctConstructor : ctClass.getConstructors()) { ctConstructor.insertAfter(initialise); } } @Patch ( requiredAttributes = "field,class" ) public void newField(CtClass ctClass, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException { String field = attributes.get("field"); String clazz = attributes.get("class"); String initialise = attributes.get("code"); if (initialise == null) { initialise = "new " + clazz + "();"; } try { CtField ctField = ctClass.getDeclaredField(field); Log.warning(field + " already exists as " + ctField); return; } catch (NotFoundException ignored) { } CtClass newType = classRegistry.getClass(clazz); CtField ctField = new CtField(newType, field, ctClass); if (attributes.get("static") != null) { ctField.setModifiers(ctField.getModifiers() | Modifier.STATIC); } ctField.setModifiers(Modifier.setPublic(ctField.getModifiers())); if ("none".equalsIgnoreCase(initialise)) { ctClass.addField(ctField); } else { CtField.Initializer initializer = CtField.Initializer.byExpr(initialise); ctClass.addField(ctField, initializer); } } @Patch ( requiredAttributes = "code" ) public void insertBefore(CtBehavior ctBehavior, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException { String field = attributes.get("field"); String code = attributes.get("code"); if (field != null) { code = code.replace("$field", field); } ctBehavior.insertBefore(code); } @Patch ( requiredAttributes = "code" ) public void insertAfter(CtBehavior ctBehavior, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException { String field = attributes.get("field"); String code = attributes.get("code"); if (field != null) { code = code.replace("$field", field); } ctBehavior.insertAfter(code, attributes.containsKey("finally")); } @Patch public void insertSuper(CtBehavior ctBehavior) throws CannotCompileException { ctBehavior.insertBefore("super." + ctBehavior.getName() + "($$);"); } @Patch ( requiredAttributes = "field" ) public void lock(CtMethod ctMethod, Map<String, String> attributes) throws NotFoundException, CannotCompileException, IOException { String field = attributes.get("field"); ctMethod.insertBefore("this." + field + ".lock();"); ctMethod.insertAfter("this." + field + ".unlock();", true); } @Patch ( requiredAttributes = "field" ) public void lockMethodCall(final CtBehavior ctBehavior, Map<String, String> attributes) throws CannotCompileException { String method_ = attributes.get("method"); if (method_ == null) { method_ = ""; } String className_ = null; int dotIndex = method_.indexOf('.'); if (dotIndex != -1) { className_ = method_.substring(0, dotIndex); method_ = method_.substring(dotIndex + 1); } String index_ = attributes.get("index"); if (index_ == null) { index_ = "-1"; } final String method = method_; final String className = className_; final String field = attributes.get("field"); final int index = Integer.valueOf(index_); ctBehavior.instrument(new ExprEditor() { private int currentIndex = 0; @Override public void edit(MethodCall methodCall) throws CannotCompileException { if ((className == null || methodCall.getClassName().equals(className)) && (method.isEmpty() || methodCall.getMethodName().equals(method)) && (index == -1 || currentIndex++ == index)) { Log.info("Replaced " + methodCall + " from " + ctBehavior); methodCall.replace("{ " + field + ".lock(); try { $_ = $proceed($$); } finally { " + field + ".unlock(); } }"); } } }); } @Patch ( requiredAttributes = "name,interface" ) public void renameInterfaceMethod(CtMethod ctMethod, Map<String, String> attributes) throws CannotCompileException, NotFoundException { CtClass currentClass = ctMethod.getDeclaringClass().getSuperclass(); final List<String> superClassNames = new ArrayList<String>(); boolean contains = false; do { if (!contains) { for (CtClass ctClass : currentClass.getInterfaces()) { if (ctClass.getName().equals(attributes.get("interface"))) { contains = true; } } } currentClass = currentClass.getSuperclass(); superClassNames.add(currentClass.getName()); } while (currentClass != classRegistry.getClass("java.lang.Object")); final String newName = attributes.get("name"); if (!contains) { ctMethod.setName(newName); return; } final String methodName = ctMethod.getName(); ctMethod.instrument(new ExprEditor() { @Override public void edit(MethodCall methodCall) throws CannotCompileException { if (methodName.equals(methodCall.getMethodName()) && superClassNames.contains(methodCall.getClassName())) { methodCall.replace("$_ = super." + newName + "($$);"); } } }); ctMethod.setName(newName); } @Patch ( requiredAttributes = "name" ) public void rename(CtMethod ctMethod, Map<String, String> attributes) { ctMethod.setName(attributes.get("name")); } @Patch ( requiredAttributes = "field" ) public void synchronizeMethodCall(final CtBehavior ctBehavior, Map<String, String> attributes) throws CannotCompileException { String method_ = attributes.get("method"); if (method_ == null) { method_ = ""; } String className_ = null; int dotIndex = method_.indexOf('.'); if (dotIndex != -1) { className_ = method_.substring(0, dotIndex); method_ = method_.substring(dotIndex + 1); } String index_ = attributes.get("index"); if (index_ == null) { index_ = "-1"; } final String method = method_; final String className = className_; final String field = attributes.get("field"); final int index = Integer.valueOf(index_); ctBehavior.instrument(new ExprEditor() { private int currentIndex = 0; @Override public void edit(MethodCall methodCall) throws CannotCompileException { if ((className == null || methodCall.getClassName().equals(className)) && (method.isEmpty() || methodCall.getMethodName().equals(method)) && (index == -1 || currentIndex++ == index)) { Log.info("Replaced " + methodCall + " from " + ctBehavior); methodCall.replace("synchronized(" + field + ") { $_ = $0.$proceed($$); }"); } } }); } @Patch public void unsynchronize(CtBehavior ctBehavior) { ctBehavior.setModifiers(ctBehavior.getModifiers() & ~Modifier.SYNCHRONIZED); } @Patch ( emptyConstructor = false ) public void synchronize(Object o, Map<String, String> attributes) throws CannotCompileException { //noinspection StatementWithEmptyBody if (o instanceof CtConstructor) { } else if (o instanceof CtMethod) { synchronize((CtMethod) o, attributes.get("field")); } else { int synchronized_ = 0; boolean static_ = attributes.containsKey("static"); for (CtMethod ctMethod : ((CtClass) o).getDeclaredMethods()) { boolean isStatic = (ctMethod.getModifiers() & Modifier.STATIC) == Modifier.STATIC; if (isStatic == static_) { synchronize(ctMethod, attributes.get("field")); synchronized_++; } } if (synchronized_ == 0) { Log.severe("Nothing synchronized - did you forget the 'static' attribute?"); } else { Log.info("Synchronized " + synchronized_ + " methods."); } } } private void synchronize(CtMethod ctMethod, String field) throws CannotCompileException { if (field == null) { int currentModifiers = ctMethod.getModifiers(); if (Modifier.isSynchronized(currentModifiers)) { Log.warning("Method: " + ctMethod.getLongName() + " is already synchronized"); } else { ctMethod.setModifiers(currentModifiers | Modifier.SYNCHRONIZED); } } else { CtClass ctClass = ctMethod.getDeclaringClass(); CtMethod replacement = CtNewMethod.copy(ctMethod, ctClass, null); int i = 0; try { //noinspection InfiniteLoopStatement for (; true; i++) { ctClass.getDeclaredMethod(ctMethod.getName() + "_sync" + i); } } catch (NotFoundException ignored) { } ctMethod.setName(ctMethod.getName() + "_sync" + i); List<AttributeInfo> attributes = ctMethod.getMethodInfo().getAttributes(); Iterator<AttributeInfo> attributeInfoIterator = attributes.iterator(); while (attributeInfoIterator.hasNext()) { AttributeInfo attributeInfo = attributeInfoIterator.next(); if (attributeInfo instanceof AnnotationsAttribute) { attributeInfoIterator.remove(); replacement.getMethodInfo().addAttribute(attributeInfo); } } replacement.setBody("synchronized(" + field + ") { return " + ctMethod.getName() + "($$); }"); replacement.setModifiers(replacement.getModifiers() & ~Modifier.SYNCHRONIZED); ctClass.addMethod(replacement); } } @Patch ( requiredAttributes = "field" ) public void synchronizeNotNull(CtMethod ctMethod, Map<String, String> attributes) throws CannotCompileException { String field = attributes.get("field"); CtClass ctClass = ctMethod.getDeclaringClass(); CtMethod replacement = CtNewMethod.copy(ctMethod, ctClass, null); int i = 0; try { //noinspection InfiniteLoopStatement for (; true; i++) { ctClass.getDeclaredMethod(ctMethod.getName() + "_sync" + i); } } catch (NotFoundException ignored) { } ctMethod.setName(ctMethod.getName() + "_sync" + i); List<AttributeInfo> annotations = ctMethod.getMethodInfo().getAttributes(); Iterator<AttributeInfo> attributeInfoIterator = annotations.iterator(); while (attributeInfoIterator.hasNext()) { AttributeInfo attributeInfo = attributeInfoIterator.next(); if (attributeInfo instanceof AnnotationsAttribute) { attributeInfoIterator.remove(); replacement.getMethodInfo().addAttribute(attributeInfo); } } replacement.setBody("Object sync = + " + field + "; if (sync == null) { return " + ctMethod.getName() + "($$); } else { synchronized(sync) { return " + ctMethod.getName() + "($$); }"); ctClass.addMethod(replacement); } @Patch public void ignoreExceptions(CtMethod ctMethod, Map<String, String> attributes) throws CannotCompileException, NotFoundException { String returnCode = attributes.get("code"); if (returnCode == null) { returnCode = "return;"; } String exceptionType = attributes.get("type"); if (exceptionType == null) { exceptionType = "java.lang.Throwable"; } Log.info("Ignoring " + exceptionType + " in " + ctMethod + ", returning with " + returnCode); ctMethod.addCatch("{ " + returnCode + '}', classRegistry.getClass(exceptionType)); } @Patch public void lockToSynchronized(CtBehavior ctBehavior, Map<String, String> attributes) throws BadBytecode { CtClass ctClass = ctBehavior.getDeclaringClass(); MethodInfo methodInfo = ctBehavior.getMethodInfo(); CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); CodeIterator iterator = codeAttribute.iterator(); ConstPool constPool = codeAttribute.getConstPool(); int done = 0; while (iterator.hasNext()) { int pos = iterator.next(); int op = iterator.byteAt(pos); if (op == Opcode.INVOKEINTERFACE) { int mref = iterator.u16bitAt(pos + 1); if (constPool.getInterfaceMethodrefClassName(mref).endsWith("Lock")) { String name = constPool.getInterfaceMethodrefName(mref); boolean remove = false; if ("lock".equals(name)) { remove = true; iterator.writeByte(Opcode.MONITORENTER, pos); } else if ("unlock".equals(name)) { remove = true; iterator.writeByte(Opcode.MONITOREXIT, pos); } if (remove) { done++; iterator.writeByte(Opcode.NOP, pos + 1); iterator.writeByte(Opcode.NOP, pos + 2); iterator.writeByte(Opcode.NOP, pos + 3); iterator.writeByte(Opcode.NOP, pos + 4); } } } else if (op == Opcode.INVOKEVIRTUAL) { int mref = iterator.u16bitAt(pos + 1); if (constPool.getMethodrefClassName(mref).endsWith("NativeMutex")) { String name = constPool.getMethodrefName(mref); boolean remove = false; if ("lock".equals(name)) { remove = true; iterator.writeByte(Opcode.MONITORENTER, pos); } else if ("unlock".equals(name)) { remove = true; iterator.writeByte(Opcode.MONITOREXIT, pos); } if (remove) { done++; iterator.writeByte(Opcode.NOP, pos + 1); iterator.writeByte(Opcode.NOP, pos + 2); } } } } methodInfo.rebuildStackMapIf6(ctClass.getClassPool(), ctClass.getClassFile2()); Log.fine("Replaced " + done + " lock/unlock calls."); } @Patch ( requiredAttributes = "field" ) public void removeField(CtClass ctClass, Map<String, String> attributes) throws NotFoundException { ctClass.removeField(ctClass.getDeclaredField(attributes.get("field"))); } @Patch ( requiredAttributes = "field" ) public void removeFieldAndInitializers(CtClass ctClass, Map<String, String> attributes) throws CannotCompileException, NotFoundException { CtField ctField; try { ctField = ctClass.getDeclaredField(attributes.get("field")); } catch (NotFoundException e) { if (!attributes.containsKey("silent")) { Log.severe("Couldn't find field " + attributes.get("field")); } return; } for (CtBehavior ctBehavior : ctClass.getDeclaredConstructors()) { removeInitializers(ctBehavior, ctField); } CtBehavior ctBehavior = ctClass.getClassInitializer(); if (ctBehavior != null) { removeInitializers(ctBehavior, ctField); } ctClass.removeField(ctField); } @Patch public void removeMethod(CtMethod ctMethod, Map<String, String> attributes) throws NotFoundException { ctMethod.getDeclaringClass().removeMethod(ctMethod); } private static String classSignatureToName(String signature) { //noinspection HardcodedFileSeparator return signature.substring(1, signature.length() - 1).replace("/", "."); } public static void findUnusedFields(CtClass ctClass) { final Set<String> readFields = new HashSet<String>(); final Set<String> writtenFields = new HashSet<String>(); try { ctClass.instrument(new ExprEditor() { @Override public void edit(FieldAccess fieldAccess) { if (fieldAccess.isReader()) { readFields.add(fieldAccess.getFieldName()); } else if (fieldAccess.isWriter()) { writtenFields.add(fieldAccess.getFieldName()); } } }); for (CtField ctField : ctClass.getDeclaredFields()) { String fieldName = ctField.getName(); if (fieldName.length() <= 2) { continue; } if (Modifier.isPrivate(ctField.getModifiers())) { boolean written = writtenFields.contains(fieldName); boolean read = readFields.contains(fieldName); if (read && written) { continue; } Log.fine("Field " + fieldName + " in " + MappingUtil.debobfuscate(ctClass.getName()) + " is read: " + read + ", written: " + written); if (!written && !read) { ctClass.removeField(ctField); } } } } catch (Throwable t) { throw UnsafeUtil.throwIgnoreChecked(t); } } }