repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
EliasFarhan/gsn
src/main/java/gsn/vsensor/GridRenderer.java
12336
/** * Global Sensor Networks (GSN) Source Code * Copyright (c) 2006-2014, Ecole Polytechnique Federale de Lausanne (EPFL) * * This file is part of GSN. * * GSN is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GSN is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GSN. If not, see <http://www.gnu.org/licenses/>. * * File: src/gsn/vsensor/GridRenderer.java * * @author Sofiane Sarni * @author Julien Eberle * */ package gsn.vsensor; import gsn.beans.DataTypes; import gsn.beans.StreamElement; import gsn.beans.VSensorConfig; import gsn.utils.geo.GridTools; import org.apache.log4j.Logger; import javax.imageio.ImageIO; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; import java.util.Hashtable; import java.util.TreeMap; public class GridRenderer extends AbstractVirtualSensor { private static final transient Logger logger = Logger.getLogger(GridRenderer.class); private static final String CELL_PIXELS = "cellpixels"; private static final String MAP_OVERLAY = "mapoverlay"; private static final String MAX_V = "max_value"; private static final String MIN_V = "min_value"; private int map[]; private double min_v; private double max_v; private double minvalue; private double maxvalue; private double cellsize; private double yllcorner; private double xllcorner; private int ncols; private int nrows; //to avoid querying all the time the same image from osm, we cache it. private Hashtable<Double,BufferedImage> cache = new Hashtable<Double,BufferedImage>(); int cell_pixels = 20; boolean map_overlay = false; @Override public boolean initialize() { VSensorConfig vsensor = getVirtualSensorConfiguration(); TreeMap<String, String> params = vsensor.getMainClassInitialParams(); // Approximative number of pixels for one cell of the array String cell_pixels_str = params.get(CELL_PIXELS); if (cell_pixels_str != null) { cell_pixels_str = cell_pixels_str.trim().toLowerCase(); try { cell_pixels = Integer.parseInt(cell_pixels_str.trim()); } catch (NumberFormatException e) { logger.warn("Parameter \"" + CELL_PIXELS + "\" has incorrect value in Virtual Sensor file. Assuming default value."); } } //value to be assigned to the min of the color scale String min_str = params.get(MIN_V); if (min_str != null) { min_str = min_str.trim().toLowerCase(); try { min_v = Double.parseDouble(min_str.trim()); } catch (NumberFormatException e) { logger.warn("Parameter \"" + MIN_V + "\" has incorrect value in Virtual Sensor file."); } } //value to be assigned to the max of the color scale String max_str = params.get(MAX_V); if (max_str != null) { max_str = max_str.trim().toLowerCase(); try { max_v = Double.parseDouble(max_str.trim()); } catch (NumberFormatException e) { logger.warn("Parameter \"" + MAX_V + "\" has incorrect value in Virtual Sensor file."); } } //using or not the osm overlay String map_overlay_str = params.get(MAP_OVERLAY); if (map_overlay_str != null) { map_overlay_str = map_overlay_str.trim().toLowerCase(); if(map_overlay_str.equals("no") || map_overlay_str.equals("false")){ map_overlay = false; }else if(map_overlay_str.equals("yes") || map_overlay_str.equals("true")){ map_overlay = true; } else { logger.warn("Parameter \"" + MAP_OVERLAY + "\" has incorrect value in Virtual Sensor file. Assuming default value."); } } initColorMap(); return true; } @Override public void dispose() { } @Override public void dataAvailable(String inputStreamName, StreamElement streamElement) { ncols = (Integer) streamElement.getData("ncols"); nrows = (Integer) streamElement.getData("nrows"); xllcorner = (Double) streamElement.getData("xllcorner"); yllcorner = (Double) streamElement.getData("yllcorner"); cellsize = (Double) streamElement.getData("cellsize"); // must be in meters long timestamp = streamElement.getTimeStamp(); Double values[][] = GridTools.deSerialize((byte[]) streamElement.getData("grid")); byte b[] = createImageFromArray(values); StreamElement se = new StreamElement(new String[]{"grid"}, new Byte[]{DataTypes.BINARY}, new Serializable[]{b}, timestamp); dataProduced(se); } /** * earth radius taken from * http://www.uwgb.edu/dutchs/UsefulData/UTMFormulas.htm * grayscale conversion from * http://en.wikipedia.org/wiki/Grayscale * openstreetmap zoom conversion taken from * http://wiki.openstreetmap.org/wiki/Zoom_levels * @param a * @return */ private byte[] createImageFromArray(Double[][] a) { BufferedImage back; // if the min and max values are not given, we search for them in the array of data if ((min_v == 0 && max_v == 0) || min_v >= max_v){ minvalue = a[0][0]; maxvalue = a[0][0]; for (int i = 0; i < a.length; i++) for (int j = 0; j < a[0].length; j++) { if (minvalue > a[i][j]) minvalue = a[i][j]; if (maxvalue < a[i][j]) maxvalue = a[i][j]; } }else{ minvalue = min_v; maxvalue = max_v; } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (map_overlay){ //openstreetmap needs the center of the tile (lat/lon) for querying the map... double centerY = yllcorner + (360/(6356752.0*2*Math.PI) * cellsize * nrows)/2; double centerX = xllcorner + (360/(6378137*2*Math.PI*Math.cos(Math.toRadians(centerY)))*cellsize * ncols)/2; //... and the zoom level int zoom = (int) Math.ceil(Math.log(cell_pixels*6378137*2*Math.PI*Math.cos(Math.toRadians(centerY))/cellsize)/Math.log(2)-8); //then we adjust the number of pixel per cell to match the zoom level's pixel/meter and compute the whole image size int width = (int) (cellsize * ncols / (6378137*2*Math.PI*Math.cos(Math.toRadians(centerY))/Math.pow(2, zoom+8))); int height = (int) (cellsize * nrows / (6378137*2*Math.PI*Math.cos(Math.toRadians(centerY))/Math.pow(2, zoom+8))); //the two images that will be blent later BufferedImage osmap = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); back = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //getting map from the cache or directly from osm staticmap try {//the key should guarantee some kind of uniqueness to the map tile if (cache.containsKey(centerX+centerY*180+zoom*180*360+width*180*360*20+height*180*360*20*1000)){ osmap = cache.get(centerX+centerY*180+zoom*180*360+width*180*360*20+height*180*360*20*1000); }else{ //You need to use a Tile Map Service for generating the map images. //you can get a list here: http://wiki.openstreetmap.org/wiki/TMS //Please read their policy and consider setting up you own service if you use it a lot //The grid renderer is caching the tiles and only makes a new request when one of the 5 parameters changes or the server restarts osmap = ImageIO.read(new URL("please insert the url here?center="+centerY+","+centerX+"&zoom="+zoom+"&size="+width+"x"+height)); cache.put(centerX+centerY*180+zoom*180*360+width*180*360*20+height*180*360*20*1000, osmap); } } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } //go through the picture pixel by pixel for (int x=0;x<width;x++) for (int y=0;y<height;y++){ //the indices in the grid corresponding to this pixel int i = (int) (x/(width * 1.0 / ncols)); int j = (int) (y/(height * 1.0 / ncols)); // convert map to black/white int val = osmap.getRGB(x, y); int r = (val & 0x00ff0000) >> 16; int g = (val & 0x0000ff00) >> 8; int b = (val & 0x000000ff); int bw = (int)(0.2126*r+0.7152*g+0.0722*b); //and blend it with the color from the grid of values int color = mapValue(a[j][i]); int r2 = (color & 0x00ff0000) >> 16; int g2 = (color & 0x0000ff00) >> 8; int b2 = (color & 0x000000ff); int rgb = (bw+r2)/2 * 256 * 256 + (bw+g2)/2 * 256 + (bw+b2)/2; back.setRGB(x, y, rgb); } } else { int Y = a.length; int X = a[0].length; back = new BufferedImage(X * cell_pixels, Y * cell_pixels, BufferedImage.TYPE_INT_RGB); int bigPixel[] = new int[cell_pixels * cell_pixels]; for (int i = 0; i < X; ++i) for (int j = 0; j < Y; ++j) { int color = mapValue(a[j][i]); for (int k = 0; k < cell_pixels * cell_pixels; k++) bigPixel[k] = color; back.setRGB(i * cell_pixels, j * cell_pixels, cell_pixels, cell_pixels, bigPixel, 0, cell_pixels); } } // draw the gradient of the scale int bigPixel[] = new int[15]; for (int x=0;x<back.getHeight();x++){ int color = map[255-(int)(x*255.0/back.getHeight())]; for (int k = 0; k < 15; k++) bigPixel[k] = color; back.setRGB(0, x, 15, 1, bigPixel, 0,15); } // draw the min and max of the scale Graphics2D gp = back.createGraphics(); gp.setColor(Color.black); gp.drawString(""+maxvalue, 3, 12); gp.drawString(""+minvalue, 3, back.getHeight()-3); try { ImageIO.write(back, "png", outputStream); } catch (IOException e) { logger.warn(e.getMessage(), e); } return outputStream.toByteArray(); } // green-yellow-red color map public void initColorMap() { map = new int[256]; int r, g, b; for (int i = 0; i <= 255; i++) { if (i < 128) r = 255; else r = 255 - i * 2; if (i < 128) g = i * 2;//i; else g = 255; b = 0;//255; map[255-i] = r * 256 * 256 + g * 256 + b; } } /** * Get the value of the color from the map and returns black if the value is greater than the max or white if the value is smaller than the min * @param value: rgb color * @return */ public int mapValue(double value) { if (value > maxvalue) return 0; //black if (value < minvalue) return 255 * 256 * 256 + 255 * 256 + 255; //white return map[(int) Math.round((value - minvalue) * 255 / (maxvalue - minvalue))]; } }
gpl-3.0
Antrax-Reloaded/Craftbuk
src/main/java/net/minecraft/server/BlockSoil.java
3865
package net.minecraft.server; import java.util.Random; // CraftBukkit start import org.bukkit.event.entity.EntityInteractEvent; import org.bukkit.craftbukkit.event.CraftEventFactory; // CraftBukkit end public class BlockSoil extends Block { protected BlockSoil(int i) { super(i, Material.EARTH); this.b(true); this.a(0.0F, 0.0F, 0.0F, 1.0F, 0.9375F, 1.0F); this.k(255); } public AxisAlignedBB b(World world, int i, int j, int k) { return AxisAlignedBB.a().a((double) (i + 0), (double) (j + 0), (double) (k + 0), (double) (i + 1), (double) (j + 1), (double) (k + 1)); } public boolean c() { return false; } public boolean b() { return false; } public void a(World world, int i, int j, int k, Random random) { if (!this.m(world, i, j, k) && !world.F(i, j + 1, k)) { int l = world.getData(i, j, k); if (l > 0) { world.setData(i, j, k, l - 1, 2); } else if (!this.k(world, i, j, k)) { // CraftBukkit start org.bukkit.block.Block block = world.getWorld().getBlockAt(i, j, k); if (CraftEventFactory.callBlockFadeEvent(block, Block.DIRT.id).isCancelled()) { return; } // CraftBukkit end world.setTypeIdUpdate(i, j, k, Block.DIRT.id); } } else { world.setData(i, j, k, 7, 2); } } public void a(World world, int i, int j, int k, Entity entity, float f) { if (!world.isStatic && world.random.nextFloat() < f - 0.5F) { if (!(entity instanceof EntityHuman) && !world.getGameRules().getBoolean("mobGriefing")) { return; } // CraftBukkit start - Interact soil org.bukkit.event.Cancellable cancellable; if (entity instanceof EntityHuman) { cancellable = CraftEventFactory.callPlayerInteractEvent((EntityHuman) entity, org.bukkit.event.block.Action.PHYSICAL, i, j, k, -1, null); } else { cancellable = new EntityInteractEvent(entity.getBukkitEntity(), world.getWorld().getBlockAt(i, j, k)); world.getServer().getPluginManager().callEvent((EntityInteractEvent) cancellable); } if (cancellable.isCancelled()) { return; } // CraftBukkit end world.setTypeIdUpdate(i, j, k, Block.DIRT.id); } } private boolean k(World world, int i, int j, int k) { byte b0 = 0; for (int l = i - b0; l <= i + b0; ++l) { for (int i1 = k - b0; i1 <= k + b0; ++i1) { int j1 = world.getTypeId(l, j + 1, i1); if (j1 == Block.CROPS.id || j1 == Block.MELON_STEM.id || j1 == Block.PUMPKIN_STEM.id || j1 == Block.POTATOES.id || j1 == Block.CARROTS.id) { return true; } } } return false; } private boolean m(World world, int i, int j, int k) { for (int l = i - 4; l <= i + 4; ++l) { for (int i1 = j; i1 <= j + 1; ++i1) { for (int j1 = k - 4; j1 <= k + 4; ++j1) { if (world.getMaterial(l, i1, j1) == Material.WATER) { return true; } } } } return false; } public void doPhysics(World world, int i, int j, int k, int l) { super.doPhysics(world, i, j, k, l); Material material = world.getMaterial(i, j + 1, k); if (material.isBuildable()) { world.setTypeIdUpdate(i, j, k, Block.DIRT.id); } } public int getDropType(int i, Random random, int j) { return Block.DIRT.getDropType(0, random, j); } }
gpl-3.0
aaorellana/Logisim-SeniorProject
src/main/java/com/cburch/logisim/gui/main/SimulationExplorer.java
3422
/* Copyright (c) 2011, Carl Burch. License information is located in the * com.cburch.logisim.Main source code and at www.cburch.com/logisim/. */ package com.cburch.logisim.gui.main; import java.awt.BorderLayout; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.tree.TreePath; import com.cburch.draw.toolbar.Toolbar; import com.cburch.logisim.circuit.CircuitState; import com.cburch.logisim.circuit.Simulator; import com.cburch.logisim.proj.Project; import com.cburch.logisim.proj.ProjectEvent; import com.cburch.logisim.proj.ProjectListener; @SuppressWarnings("serial") class SimulationExplorer extends JPanel implements ProjectListener, MouseListener { private Project project; private SimulationTreeModel model; private JTree tree; SimulationExplorer(Project proj, MenuListener menu) { super(new BorderLayout()); this.project = proj; SimulationToolbarModel toolbarModel = new SimulationToolbarModel(proj, menu); Toolbar toolbar = new Toolbar(toolbarModel); add(toolbar, BorderLayout.NORTH); model = new SimulationTreeModel(proj.getSimulator().getCircuitState()); model.setCurrentView(project.getCircuitState()); tree = new JTree(model); tree.setCellRenderer(new SimulationTreeRenderer()); tree.addMouseListener(this); tree.setToggleClickCount(3); add(new JScrollPane(tree), BorderLayout.CENTER); proj.addProjectListener(this); } // // ProjectListener methods // @Override public void projectChanged(ProjectEvent event) { int action = event.getAction(); if (action == ProjectEvent.ACTION_SET_STATE) { Simulator sim = project.getSimulator(); CircuitState root = sim.getCircuitState(); if (model.getRootState() != root) { model = new SimulationTreeModel(root); tree.setModel(model); } model.setCurrentView(project.getCircuitState()); TreePath path = model.mapToPath(project.getCircuitState()); if (path != null) { tree.scrollPathToVisible(path); } } } // // MouseListener methods // // // MouseListener methods // @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { requestFocus(); checkForPopup(e); } @Override public void mouseReleased(MouseEvent e) { checkForPopup(e); } private void checkForPopup(MouseEvent e) { if (e.isPopupTrigger()) { // do nothing ; } } @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { TreePath path = tree.getPathForLocation(e.getX(), e.getY()); if (path != null) { Object last = path.getLastPathComponent(); if (last instanceof SimulationTreeCircuitNode) { SimulationTreeCircuitNode node; node = (SimulationTreeCircuitNode) last; project.setCircuitState(node.getCircuitState()); } } } } }
gpl-3.0
BTCTaras/Essentials
Essentials/src/com/earth2me/essentials/commands/Commandworth.java
3492
package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.NumberUtil; import org.bukkit.Server; import org.bukkit.inventory.ItemStack; import java.math.BigDecimal; import java.util.List; import java.util.Locale; import static com.earth2me.essentials.I18n.tl; public class Commandworth extends EssentialsCommand { public Commandworth() { super("worth"); } @Override public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { BigDecimal totalWorth = BigDecimal.ZERO; String type = ""; List<ItemStack> is = ess.getItemDb().getMatching(user, args); int count = 0; boolean isBulk = is.size() > 1; for (ItemStack stack : is) { try { if (stack.getAmount() > 0) { totalWorth = totalWorth.add(itemWorth(user.getSource(), user, stack, args)); stack = stack.clone(); count++; for (ItemStack zeroStack : is) { if (zeroStack.isSimilar(stack)) { zeroStack.setAmount(0); } } } } catch (Exception e) { if (!isBulk) { throw e; } } } if (count > 1) { if (args.length > 0 && args[0].equalsIgnoreCase("blocks")) { user.sendMessage(tl("totalSellableBlocks", type, NumberUtil.displayCurrency(totalWorth, ess))); } else { user.sendMessage(tl("totalSellableAll", type, NumberUtil.displayCurrency(totalWorth, ess))); } } } @Override public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { if (args.length < 1) { throw new NotEnoughArgumentsException(); } ItemStack stack = ess.getItemDb().get(args[0]); itemWorth(sender, null, stack, args); } private BigDecimal itemWorth(CommandSource sender, User user, ItemStack is, String[] args) throws Exception { int amount = 1; if (user == null) { if (args.length > 1) { try { amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); } catch (NumberFormatException ex) { throw new NotEnoughArgumentsException(ex); } } } else { amount = ess.getWorth().getAmount(ess, user, is, args, true); } BigDecimal worth = ess.getWorth().getPrice(is); if (worth == null) { throw new Exception(tl("itemCannotBeSold")); } if (amount < 0) { amount = 0; } BigDecimal result = worth.multiply(BigDecimal.valueOf(amount)); sender.sendMessage(is.getDurability() != 0 ? tl("worthMeta", is.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), is.getDurability(), NumberUtil.displayCurrency(result, ess), amount, NumberUtil.displayCurrency(worth, ess)) : tl("worth", is.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), NumberUtil.displayCurrency(result, ess), amount, NumberUtil.displayCurrency(worth, ess))); return result; } }
gpl-3.0
AsherBond/MondocosmOS
wonderland/web/runner/src/java/org/jdesktop/wonderland/runner/resources/RunnerActionResource.java
5087
/** * Project Wonderland * * Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied * this code. */ package org.jdesktop.wonderland.runner.resources; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import org.jdesktop.wonderland.runner.StatusWaiter; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import org.jdesktop.wonderland.runner.RunManager; import org.jdesktop.wonderland.runner.Runner; import org.jdesktop.wonderland.runner.RunnerException; /** * The RunnerActionResource class is a Jersey RESTful service that allows * services to be started and stopped using a REST API. The get() * method handles the HTTP GET request. * * @author jkaplan */ @Path(value="/runner/{runner}/{action}") public class RunnerActionResource { private static final Logger logger = Logger.getLogger(RunnerActionResource.class.getName()); /** * Return a list of all runners currently running. * @return An XML encoding of the module's basic information */ @GET @Produces({"text/plain", "application/xml", "application/json"}) public Response get(@PathParam(value="runner") String runner, @PathParam(value="action") String action, @QueryParam(value="wait") String waitParam) { RunManager rm = RunManager.getInstance(); try { Runner r = rm.get(runner); if (r == null) { throw new RunnerException("Request for unknown runner: " + runner); } boolean wait = false; if (waitParam != null) { wait = Boolean.parseBoolean(waitParam); } StatusWaiter waiter = null; if (action.equalsIgnoreCase("start")) { waiter = rm.start(r, wait); } else if (action.equalsIgnoreCase("stop")) { waiter = rm.stop(r, wait); } else if (action.equalsIgnoreCase("restart")) { // stop the runner and wait for it to stop waiter = rm.stop(r, true); if (waiter != null) { waiter.waitFor(); } // wait for a bit so that everything gets cleaned up try { Thread.sleep(ActionResource.getRestartDelay() * 1000); } catch (InterruptedException ie) { // oh well } // restart the runner waiter = rm.start(r, wait); } else if (action.equalsIgnoreCase("log")) { // read the log file if (r.getLogFile() != null) { BufferedReader reader = new BufferedReader( new FileReader(r.getLogFile())); StringBuffer sb = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } ResponseBuilder rb = Response.ok(sb.toString()); return rb.build(); } } else { throw new RunnerException("Unkown action " + action); } // if necessary, wait for the runner if (waiter != null) { waiter.waitFor(); } ResponseBuilder rb = Response.ok(); return rb.build(); } catch (RunnerException re) { logger.log(Level.WARNING, re.getMessage(), re); ResponseBuilder rb = Response.status(Status.BAD_REQUEST); return rb.build(); } catch (InterruptedException ie) { logger.log(Level.WARNING, ie.getMessage(), ie); ResponseBuilder rb = Response.status(Status.INTERNAL_SERVER_ERROR); return rb.build(); } catch (IOException ioe) { logger.log(Level.WARNING, ioe.getMessage(), ioe); ResponseBuilder rb = Response.status(Status.INTERNAL_SERVER_ERROR); return rb.build(); } } }
agpl-3.0
iu-uits-es/kc
coeus-impl/src/main/java/org/kuali/kra/protocol/personnel/SaveProtocolPersonnelEventBase.java
1518
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2016 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kra.protocol.personnel; import org.kuali.coeus.sys.framework.rule.KcDocumentEventBaseExtension; import org.kuali.kra.protocol.ProtocolDocumentBase; /** * Represents the event to save a ProtocolPersonnel. */ public abstract class SaveProtocolPersonnelEventBase extends KcDocumentEventBaseExtension { /** * Constructs an SaveProtocolPersonnelEventBase. * @param errorPathPrefix The error path prefix * @param document The document to validate */ protected SaveProtocolPersonnelEventBase(String errorPathPrefix, ProtocolDocumentBase document) { super("Saving protocol personnel on document " + getDocumentId(document), errorPathPrefix, document); } }
agpl-3.0
sanjupolus/KC6.oLatest
coeus-impl/src/main/java/org/kuali/kra/subaward/service/impl/SubAwardRulesEngineExecutorImpl.java
2704
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2015 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kra.subaward.service.impl; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.kuali.coeus.sys.framework.service.KcServiceLocator; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.krms.KcKrmsConstants; import org.kuali.coeus.common.framework.krms.KcRulesEngineExecuter; import org.kuali.coeus.common.impl.krms.KcKrmsFactBuilderServiceHelper; import org.kuali.kra.subaward.bo.SubAward; import org.kuali.rice.kew.engine.RouteContext; import org.kuali.rice.krms.api.engine.Engine; import org.kuali.rice.krms.api.engine.EngineResults; import org.kuali.rice.krms.api.engine.Facts; import org.kuali.rice.krms.api.engine.SelectionCriteria; public class SubAwardRulesEngineExecutorImpl extends KcRulesEngineExecuter { public EngineResults performExecute(RouteContext routeContext, Engine engine) { Map<String, String> contextQualifiers = new HashMap<String, String>(); contextQualifiers.put("namespaceCode", Constants.MODULE_NAMESPACE_SUBAWARD); contextQualifiers.put("name", KcKrmsConstants.SubAward.SUBAWARD_CONTEXT); // extract facts from routeContext String docContent = routeContext.getDocument().getDocContent(); String unitNumber = getElementValue(docContent, "//document/subAwardList[1]/" + SubAward.class.getName() + "[1]/leadUnitNumber[1]"); SelectionCriteria selectionCriteria = SelectionCriteria.createCriteria(null, contextQualifiers, Collections.singletonMap("Unit Number", unitNumber)); KcKrmsFactBuilderServiceHelper fbService = KcServiceLocator.getService("subAwardFactBuilderService"); Facts.Builder factsBuilder = Facts.Builder.create(); fbService.addFacts(factsBuilder, docContent); EngineResults results = engine.execute(selectionCriteria, factsBuilder.build(), null); return results; } }
agpl-3.0
sanjupolus/KC6.oLatest
coeus-impl/src/main/java/org/kuali/coeus/common/budget/framework/personnel/AppointmentType.java
2284
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2015 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.coeus.common.budget.framework.personnel; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import org.kuali.coeus.common.budget.api.personnel.AppointmentTypeContract; import org.kuali.coeus.sys.framework.model.KcPersistableBusinessObjectBase; /** * Class representation of the Appointment Type Business Object * * AppointmentType.java */ @Entity @Table(name = "APPOINTMENT_TYPE") public class AppointmentType extends KcPersistableBusinessObjectBase implements AppointmentTypeContract { @Id @Column(name = "APPOINTMENT_TYPE_CODE") private String appointmentTypeCode; @Column(name = "DURATION") private Integer duration; @Column(name = "DESCRIPTION") private String description; @Override public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getAppointmentTypeCode() { return appointmentTypeCode; } public void setAppointmentTypeCode(String appointmentTypeCode) { this.appointmentTypeCode = appointmentTypeCode; } @Override public Integer getDuration() { return duration; } public void setDuration(Integer duration) { this.duration = duration; } @Override public String getCode() { return getAppointmentTypeCode(); } }
agpl-3.0
OvercastNetwork/ProjectAres
Util/core/src/main/java/tc/oc/commons/core/inject/AbstractBindingBuilder.java
2335
package tc.oc.commons.core.inject; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.Scope; import com.google.inject.TypeLiteral; import com.google.inject.binder.AnnotatedBindingBuilder; import com.google.inject.binder.LinkedBindingBuilder; import com.google.inject.binder.ScopedBindingBuilder; import com.google.inject.internal.Annotations; import com.google.inject.internal.Scoping; /** * Base implementation for the Guice DSL builder class. Possibly useful for custom binders. */ public abstract class AbstractBindingBuilder<T> implements AnnotatedBindingBuilder<T> { protected abstract void applyScoping(Scoping scoping); @Override public LinkedBindingBuilder<T> annotatedWith(Class<? extends Annotation> annotationType) { return annotatedWith(Annotations.generateAnnotation(annotationType)); } @Override public ScopedBindingBuilder to(Class<? extends T> implementation) { return to(Key.get(implementation)); } @Override public ScopedBindingBuilder to(TypeLiteral<? extends T> implementation) { return to(Key.get(implementation)); } @Override public ScopedBindingBuilder toProvider(Provider<? extends T> provider) { return toProvider((javax.inject.Provider<? extends T>) provider); } @Override public ScopedBindingBuilder toProvider(Class<? extends javax.inject.Provider<? extends T>> providerType) { return toProvider(Key.get(providerType)); } @Override public ScopedBindingBuilder toProvider(TypeLiteral<? extends javax.inject.Provider<? extends T>> providerType) { return toProvider(Key.get(providerType)); } @Override public <S extends T> ScopedBindingBuilder toConstructor(Constructor<S> constructor) { return toConstructor(constructor, TypeLiteral.get(constructor.getDeclaringClass())); } @Override public void in(Class<? extends Annotation> scopeAnnotation) { applyScoping(Scoping.forAnnotation(scopeAnnotation)); } @Override public void in(Scope scope) { applyScoping(Scoping.forInstance(scope)); } @Override public void asEagerSingleton() { applyScoping(Scoping.EAGER_SINGLETON); } }
agpl-3.0
bluenote10/TuxguitarParser
tuxguitar-src/TuxGuitar/src/org/herac/tuxguitar/app/action/impl/tools/TGSelectScaleAction.java
926
package org.herac.tuxguitar.app.action.impl.tools; import org.herac.tuxguitar.action.TGActionContext; import org.herac.tuxguitar.app.tools.scale.ScaleManager; import org.herac.tuxguitar.editor.action.TGActionBase; import org.herac.tuxguitar.util.TGContext; public class TGSelectScaleAction extends TGActionBase{ public static final String NAME = "action.tools.select-scale"; public static final String ATTRIBUTE_INDEX = "scaleIndex"; public static final String ATTRIBUTE_KEY = "scaleKey"; public TGSelectScaleAction(TGContext context) { super(context, NAME); } protected void processAction(TGActionContext context){ Integer index = context.getAttribute(ATTRIBUTE_INDEX); Integer key = context.getAttribute(ATTRIBUTE_KEY); ScaleManager scaleManager = ScaleManager.getInstance(getContext()); scaleManager.selectScale(index != null ? index : ScaleManager.NONE_SELECTION, key != null ? key : 0); } }
lgpl-2.1
JoeCarlson/intermine
intermine/objectstore/test/src/org/intermine/objectstore/query/QueryTestCaseTest.java
11191
package org.intermine.objectstore.query; /* * Copyright (C) 2002-2016 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import junit.framework.AssertionFailedError; import junit.framework.Test; import org.intermine.metadata.ConstraintOp; import org.intermine.model.testmodel.Company; import org.intermine.model.testmodel.Department; import org.intermine.model.testmodel.Manager; import org.intermine.testing.OneTimeTestCase; public class QueryTestCaseTest extends QueryTestCase { public QueryTestCaseTest(String arg1) { super(arg1); } public static Test suite() { return OneTimeTestCase.buildSuite(QueryTestCaseTest.class); } private boolean failed; public void testEmptyQueries() throws Exception { assertEquals(new Query(), new Query()); } public void testSimpleQueriesNoConstraints() throws Exception { Query q1 = new Query(); QueryClass qc1 = new QueryClass(Department.class); q1.addToSelect(qc1); q1.addFrom(qc1); Query q2 = new Query(); QueryClass qc2 = new QueryClass(Department.class); q2.addToSelect(qc2); q2.addFrom(qc2); assertEquals(q1, q2); QueryClass qc3 = new QueryClass(Department.class); q2.addFrom(qc3); failed = false; try { assertEquals(q1, q2); failed = true; } catch (AssertionFailedError e) { } finally { if (failed) { fail("q1 and q2 should not be equal"); } } } public void testQueriesSimpleConstraint() throws Exception { Query q1 = new Query(); QueryClass qc1 = new QueryClass(Department.class); q1.addToSelect(qc1); q1.addFrom(qc1); QueryField qf1 = new QueryField(qc1, "name"); Constraint c1 = new SimpleConstraint(qf1, ConstraintOp.EQUALS, new QueryValue("Department1")); q1.setConstraint(c1); Query q2 = new Query(); QueryClass qc2 = new QueryClass(Department.class); q2.addToSelect(qc2); q2.addFrom(qc2); QueryField qf2 = new QueryField(qc2, "name"); Constraint c2 = new SimpleConstraint(qf2, ConstraintOp.EQUALS, new QueryValue("Department1")); q2.setConstraint(c2); assertEquals(q1, q2); c2 = new SimpleConstraint(qf2, ConstraintOp.EQUALS, new QueryValue("Department2")); q2.setConstraint(c2); failed = false; try { assertEquals(q1, q2); failed = true; } catch (AssertionFailedError e) { } finally { if (failed) { fail("q1 and q2 should not be equal"); } } } public void testQueriesContainsConstraint() throws Exception { Query q1 = new Query(); QueryClass qc1 = new QueryClass(Department.class); q1.addToSelect(qc1); q1.addFrom(qc1); QueryReference qr1 = new QueryObjectReference(qc1, "company"); Constraint c1 = new ContainsConstraint(qr1, ConstraintOp.CONTAINS, new QueryClass(Company.class)); q1.setConstraint(c1); Query q2 = new Query(); QueryClass qc2 = new QueryClass(Department.class); q2.addToSelect(qc2); q2.addFrom(qc2); QueryReference qr2 = new QueryObjectReference(qc2, "company"); Constraint c2 = new ContainsConstraint(qr2, ConstraintOp.CONTAINS, new QueryClass(Company.class)); q2.setConstraint(c2); assertEquals(q1, q2); QueryReference qr3 = new QueryObjectReference(qc2, "manager"); c2 = new ContainsConstraint(qr3, ConstraintOp.CONTAINS, new QueryClass(Manager.class)); q2.setConstraint(c2); failed = false; try { assertEquals(q1, q2); failed = true; } catch (AssertionFailedError e) { } finally { if (failed) { fail("q1 and q2 should not be equal"); } } } public void testQueriesClassConstraint() throws Exception { Department dept = new Department(); dept.setId(new Integer(14)); Query q1 = new Query(); QueryClass qc1 = new QueryClass(Department.class); q1.addToSelect(qc1); q1.addFrom(qc1); Constraint c1 = new ClassConstraint(qc1, ConstraintOp.EQUALS, dept); q1.setConstraint(c1); Query q2 = new Query(); QueryClass qc2 = new QueryClass(Department.class); q2.addToSelect(qc2); q2.addFrom(qc2); Constraint c2 = new ClassConstraint(qc2, ConstraintOp.EQUALS, dept); q2.setConstraint(c2); assertEquals(q1, q2); Department d1 = new Department(); d1.setId(new Integer(25)); c2 = new ClassConstraint(qc2, ConstraintOp.EQUALS, d1); q2.setConstraint(c2); failed = false; try { assertEquals(q1, q2); failed = true; } catch (AssertionFailedError e) { } finally { if (failed) { fail("q1 and q2 should not be equal"); } } } public void testQueriesConstraintSet() throws Exception { Query q1 = new Query(); QueryClass qc1 = new QueryClass(Department.class); q1.addToSelect(qc1); q1.addFrom(qc1); ConstraintSet cs1 = new ConstraintSet(ConstraintOp.OR); QueryField qf1 = new QueryField(qc1, "name"); Constraint c1 = new SimpleConstraint(qf1, ConstraintOp.EQUALS, new QueryValue("Department1")); Constraint c2 = new SimpleConstraint(qf1, ConstraintOp.EQUALS, new QueryValue("Department2")); cs1.addConstraint(c1); cs1.addConstraint(c2); q1.setConstraint(cs1); Query q2 = new Query(); QueryClass qc2 = new QueryClass(Department.class); q2.addToSelect(qc2); q2.addFrom(qc2); ConstraintSet cs2 = new ConstraintSet(ConstraintOp.OR); QueryField qf2 = new QueryField(qc2, "name"); Constraint c3 = new SimpleConstraint(qf2, ConstraintOp.EQUALS, new QueryValue("Department1")); Constraint c4 = new SimpleConstraint(qf2, ConstraintOp.EQUALS, new QueryValue("Department2")); cs2.addConstraint(c3); cs2.addConstraint(c4); q2.setConstraint(cs2); assertEquals(q1, q2); Constraint c5 = new SimpleConstraint(qf2, ConstraintOp.EQUALS, new QueryValue("Department4")); cs2.addConstraint(c5); q2.setConstraint(cs2); failed = false; try { assertEquals(q1, q2); failed = true; } catch (AssertionFailedError e) { } finally { if (failed) { fail("q1 and q2 should not be equal"); } } } public void testQ1IsNull() throws Exception { failed = false; try { assertEquals(null, new Query()); failed = true; } catch (AssertionFailedError e) { } finally { if (failed) { fail("Failure should have happened"); } } } public void testQ2IsNull() throws Exception { failed = false; try { assertEquals(new Query(), null); failed = true; } catch (AssertionFailedError e) { } finally { if (failed) { fail("Failure should have happened"); } } } public void testBothNull() throws Exception { Query q1 = null; Query q2 = null; assertEquals(q1, q2); } public void testBothSubqueriesSame() throws Exception { Query q1 = new Query(); Query q2 = new Query(); Query q1Sub = new Query(); Query q2Sub = new Query(); q1.addFrom(q1Sub); q2.addFrom(q2Sub); assertEquals(q1, q2); } public void testBothSubqueriesDifferent() throws Exception { Query q1 = new Query(); Query q2 = new Query(); Query q1Sub = new Query(); Query q2Sub = new Query(); q2Sub.addFrom(new QueryClass(Department.class)); q1.addFrom(q1Sub); q2.addFrom(q2Sub); failed = false; try { assertEquals(q1, q2); failed = true; } catch (AssertionFailedError e) { } finally { if (failed) { fail("Failure should have happened"); } } } public void testOneSubquery() throws Exception { Query q1 = new Query(); Query q2 = new Query(); Query q1Sub = new Query(); q1.addFrom(q1Sub); q2.addFrom(new QueryClass(Department.class)); failed = false; try { assertEquals(q1, q2); failed = true; } catch (AssertionFailedError e) { } finally { if (failed) { fail("Failure should have happened"); } } } public void testDifferentSubquery() throws Exception { Query q1 = new Query(); Query q2 = new Query(); Query q1Sub1 = new Query(); Query q1Sub2 = new Query(); Query q2Sub1 = new Query(); Query q2Sub2 = new Query(); QueryClass c1 = new QueryClass(Department.class); QueryClass c2 = new QueryClass(Company.class); QueryClass c3 = new QueryClass(Department.class); QueryClass c4 = new QueryClass(Company.class); q1Sub1.addFrom(c1); q1Sub1.addToSelect(c1); q1Sub2.addFrom(c2); q1Sub2.addToSelect(c2); q2Sub1.addFrom(c3); q2Sub1.addToSelect(c3); q2Sub2.addFrom(c4); q2Sub2.addToSelect(c4); q1.addFrom(q1Sub1); q1.addFrom(q1Sub2); q2.addFrom(q2Sub1); q2.addFrom(q2Sub2); QueryField f1 = new QueryField(q1Sub1, c1, "name"); QueryField f2 = new QueryField(q2Sub2, c4, "name"); q1.addToSelect(f1); q2.addToSelect(f2); failed = false; try { assertEquals(q1, q2); failed = true; } catch (AssertionFailedError e) { try { assertEquals(e.getMessage(), "asserting equal: expected <" + q1.toString() + "> but was <" + q2.toString() + ">: SELECT lists are not equal: query nodes are not the same: field members of different subquery aliases expected:<...1...> but was:<...2...>", e.getMessage()); } catch (AssertionFailedError e2) { assertEquals(e.getMessage(), "asserting equal: expected <" + q1.toString() + "> but was <" + q2.toString() + ">: SELECT lists are not equal: query nodes are not the same: field members of different subquery aliases expected:<a[1]_> but was:<a[2]_>", e.getMessage()); } } finally { if (failed) { fail("Failure should have happened"); } } } }
lgpl-2.1
e-ucm/ead
editor/core/src/main/java/es/eucm/ead/editor/control/commands/SelectionCommand.java
4867
/** * eAdventure is a research project of the * e-UCM research group. * * Copyright 2005-2014 e-UCM research group. * * You can access a list of all the contributors to eAdventure at: * http://e-adventure.e-ucm.es/contributors * * e-UCM is a research group of the Department of Software Engineering * and Artificial Intelligence at the Complutense University of Madrid * (School of Computer Science). * * CL Profesor Jose Garcia Santesmases 9, * 28040 Madrid (Madrid), Spain. * * For more info please visit: <http://e-adventure.e-ucm.es> or * <http://www.e-ucm.es> * * **************************************************************************** * * This file is part of eAdventure * * eAdventure is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * eAdventure is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with eAdventure. If not, see <http://www.gnu.org/licenses/>. */ package es.eucm.ead.editor.control.commands; import com.badlogic.gdx.utils.Array; import es.eucm.ead.editor.control.Selection; import es.eucm.ead.editor.control.Selection.Context; import es.eucm.ead.editor.model.Model; import es.eucm.ead.editor.model.events.MultipleEvent; import es.eucm.ead.editor.model.events.SelectionEvent; import es.eucm.ead.editor.model.events.SelectionEvent.Type; /** * A command to change the selection in a model */ public class SelectionCommand extends Command { private Model model; private String parentContextId; private String contextId; private Object[] selection; private Array<Context> contextsRemoved; private Context oldContext; private boolean added; public SelectionCommand(Model model, String parentContextId, String contextId, Object... selection) { this.model = model; this.parentContextId = parentContextId; this.contextId = contextId; this.selection = selection; } @Override public MultipleEvent doCommand() { Selection selection = model.getSelection(); Context currentContext = selection.getCurrentContext(); if (currentContext != null) { oldContext = new Context(currentContext.getParentId(), currentContext.getId(), currentContext.getSelection()); } added = selection.getContext(contextId) == null; contextsRemoved = selection.set(parentContextId, contextId, this.selection); MultipleEvent multipleEvent = new MultipleEvent(); if (oldContext != null && oldContext.equals(selection.getCurrentContext())) { return multipleEvent; } for (Context context : contextsRemoved) { multipleEvent.addEvent(new SelectionEvent(model, Type.REMOVED, context.getParentId(), context.getId(), context .getSelection())); } if (added) { multipleEvent.addEvent(new SelectionEvent(model, Type.ADDED, parentContextId, contextId, this.selection)); } multipleEvent.addEvent(new SelectionEvent(model, Type.FOCUSED, parentContextId, contextId, this.selection)); return multipleEvent; } @Override public boolean canUndo() { return true; } @Override public MultipleEvent undoCommand() { Selection selection = model.getSelection(); MultipleEvent multipleEvent = new MultipleEvent(); if (added) { // Selection commands can be discontinuous, so it could happen the // context added is not present in the selection.E Context context = selection.remove(contextId); if (context != null) { multipleEvent.addEvent(new SelectionEvent(model, Type.REMOVED, parentContextId, contextId, this.selection)); } } for (Context context : contextsRemoved) { selection.set(context.getParentId(), context.getId(), context.getSelection()); multipleEvent.addEvent(new SelectionEvent(model, Type.ADDED, context.getParentId(), context.getId(), context .getSelection())); } if (oldContext != null) { selection.set(oldContext.getParentId(), oldContext.getId(), oldContext.getSelection()); multipleEvent.addEvent(new SelectionEvent(model, Type.FOCUSED, oldContext.getParentId(), oldContext.getId(), oldContext .getSelection())); } return multipleEvent; } @Override public boolean modifiesResource() { return false; } @Override public boolean combine(Command other) { return false; } @Override public boolean isTransparent() { return true; } }
lgpl-3.0
F1r3w477/CustomWorldGen
build/tmp/recompileMc/sources/net/minecraftforge/fml/common/LoaderState.java
4549
/* * Minecraft Forge * Copyright (c) 2016. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation version 2.1 * of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.minecraftforge.fml.common; import net.minecraftforge.fml.common.event.FMLConstructionEvent; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLLoadCompleteEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerAboutToStartEvent; import net.minecraftforge.fml.common.event.FMLServerStartedEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.event.FMLServerStoppedEvent; import net.minecraftforge.fml.common.event.FMLServerStoppingEvent; import net.minecraftforge.fml.common.event.FMLStateEvent; import com.google.common.base.Throwables; /** * The state enum used to help track state progression for the loader * @author cpw * */ public enum LoaderState { NOINIT("Uninitialized",null), LOADING("Loading",null), CONSTRUCTING("Constructing mods",FMLConstructionEvent.class), PREINITIALIZATION("Pre-initializing mods", FMLPreInitializationEvent.class), INITIALIZATION("Initializing mods", FMLInitializationEvent.class), POSTINITIALIZATION("Post-initializing mods", FMLPostInitializationEvent.class), AVAILABLE("Mod loading complete", FMLLoadCompleteEvent.class), SERVER_ABOUT_TO_START("Server about to start", FMLServerAboutToStartEvent.class), SERVER_STARTING("Server starting", FMLServerStartingEvent.class), SERVER_STARTED("Server started", FMLServerStartedEvent.class), SERVER_STOPPING("Server stopping", FMLServerStoppingEvent.class), SERVER_STOPPED("Server stopped", FMLServerStoppedEvent.class), ERRORED("Mod Loading errored",null); private Class<? extends FMLStateEvent> eventClass; private String name; private LoaderState(String name, Class<? extends FMLStateEvent> event) { this.name = name; this.eventClass = event; } public LoaderState transition(boolean errored) { if (errored) { return ERRORED; } // stopping -> available if (this == SERVER_STOPPED) { return AVAILABLE; } return values()[ordinal() < values().length ? ordinal()+1 : ordinal()]; } public boolean hasEvent() { return eventClass != null; } public FMLStateEvent getEvent(Object... eventData) { try { return eventClass.getConstructor(Object[].class).newInstance((Object)eventData); } catch (Exception e) { throw Throwables.propagate(e); } } public LoaderState requiredState() { if (this == NOINIT) return NOINIT; return LoaderState.values()[this.ordinal()-1]; } public String getPrettyName() { return name; } public enum ModState { UNLOADED ("Unloaded", "U"), LOADED ("Loaded", "L"), CONSTRUCTED ("Constructed", "C"), PREINITIALIZED ("Pre-initialized", "H"), INITIALIZED ("Initialized", "I"), POSTINITIALIZED("Post-initialized", "J"), AVAILABLE ("Available", "A"), DISABLED ("Disabled", "D"), ERRORED ("Errored", "E"); private String label; private String marker; private ModState(String label, String marker) { this.label = label; this.marker = marker; } @Override public String toString() { return this.label; } public String getMarker() { return this.marker; } } }
lgpl-3.0
e-ucm/ead
engine/core/src/main/java/es/eucm/ead/engine/components/ConditionedComponent.java
1902
/** * eAdventure is a research project of the * e-UCM research group. * * Copyright 2005-2014 e-UCM research group. * * You can access a list of all the contributors to eAdventure at: * http://e-adventure.e-ucm.es/contributors * * e-UCM is a research group of the Department of Software Engineering * and Artificial Intelligence at the Complutense University of Madrid * (School of Computer Science). * * CL Profesor Jose Garcia Santesmases 9, * 28040 Madrid (Madrid), Spain. * * For more info please visit: <http://e-adventure.e-ucm.es> or * <http://www.e-ucm.es> * * **************************************************************************** * * This file is part of eAdventure * * eAdventure is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * eAdventure is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with eAdventure. If not, see <http://www.gnu.org/licenses/>. */ package es.eucm.ead.engine.components; import com.badlogic.ashley.core.Component; /** * Basic engine container for a condition. * * Created by Javier Torrente on 17/04/14. */ public class ConditionedComponent extends Component { protected String condition; public String getCondition() { return condition; } public void setCondition(String condition) { this.condition = condition; } }
lgpl-3.0
barmstrong/bitcoin-android
src/com/google/bitcoin/bouncycastle/asn1/cms/ecc/MQVuserKeyingMaterial.java
3431
package com.google.bitcoin.bouncycastle.asn1.cms.ecc; import com.google.bitcoin.bouncycastle.asn1.ASN1Encodable; import com.google.bitcoin.bouncycastle.asn1.ASN1EncodableVector; import com.google.bitcoin.bouncycastle.asn1.ASN1OctetString; import com.google.bitcoin.bouncycastle.asn1.ASN1Sequence; import com.google.bitcoin.bouncycastle.asn1.ASN1TaggedObject; import com.google.bitcoin.bouncycastle.asn1.DERObject; import com.google.bitcoin.bouncycastle.asn1.DERSequence; import com.google.bitcoin.bouncycastle.asn1.DERTaggedObject; import com.google.bitcoin.bouncycastle.asn1.cms.OriginatorPublicKey; public class MQVuserKeyingMaterial extends ASN1Encodable { private OriginatorPublicKey ephemeralPublicKey; private ASN1OctetString addedukm; public MQVuserKeyingMaterial( OriginatorPublicKey ephemeralPublicKey, ASN1OctetString addedukm) { // TODO Check ephemeralPublicKey not null this.ephemeralPublicKey = ephemeralPublicKey; this.addedukm = addedukm; } private MQVuserKeyingMaterial( ASN1Sequence seq) { // TODO Check seq has either 1 or 2 elements this.ephemeralPublicKey = OriginatorPublicKey.getInstance( seq.getObjectAt(0)); if (seq.size() > 1) { this.addedukm = ASN1OctetString.getInstance( (ASN1TaggedObject)seq.getObjectAt(1), true); } } /** * return an MQVuserKeyingMaterial object from a tagged object. * * @param obj the tagged object holding the object we want. * @param explicit true if the object is meant to be explicitly * tagged false otherwise. * @throws IllegalArgumentException if the object held by the * tagged object cannot be converted. */ public static MQVuserKeyingMaterial getInstance( ASN1TaggedObject obj, boolean explicit) { return getInstance(ASN1Sequence.getInstance(obj, explicit)); } /** * return an MQVuserKeyingMaterial object from the given object. * * @param obj the object we want converted. * @throws IllegalArgumentException if the object cannot be converted. */ public static MQVuserKeyingMaterial getInstance( Object obj) { if (obj == null || obj instanceof MQVuserKeyingMaterial) { return (MQVuserKeyingMaterial)obj; } if (obj instanceof ASN1Sequence) { return new MQVuserKeyingMaterial((ASN1Sequence)obj); } throw new IllegalArgumentException("Invalid MQVuserKeyingMaterial: " + obj.getClass().getName()); } public OriginatorPublicKey getEphemeralPublicKey() { return ephemeralPublicKey; } public ASN1OctetString getAddedukm() { return addedukm; } /** * Produce an object suitable for an ASN1OutputStream. * <pre> * MQVuserKeyingMaterial ::= SEQUENCE { * ephemeralPublicKey OriginatorPublicKey, * addedukm [0] EXPLICIT UserKeyingMaterial OPTIONAL } * </pre> */ public DERObject toASN1Object() { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(ephemeralPublicKey); if (addedukm != null) { v.add(new DERTaggedObject(true, 0, addedukm)); } return new DERSequence(v); } }
apache-2.0
hasinitg/airavata
modules/workflow-model/workflow-model-core/src/main/java/org/apache/airavata/workflow/model/graph/ws/WSPort.java
4860
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.workflow.model.graph.ws; import com.google.gson.JsonObject; import org.apache.airavata.common.utils.WSConstants; import org.apache.airavata.model.application.io.DataType; import org.apache.airavata.workflow.model.component.ComponentPort; import org.apache.airavata.workflow.model.component.system.SystemComponentDataPort; import org.apache.airavata.workflow.model.component.ws.WSComponentPort; import org.apache.airavata.workflow.model.graph.DataPort; import org.apache.airavata.workflow.model.graph.GraphException; import org.apache.airavata.workflow.model.graph.GraphSchema; import org.apache.airavata.workflow.model.graph.impl.NodeImpl; import org.apache.airavata.workflow.model.graph.system.EndForEachNode; import org.apache.airavata.workflow.model.graph.system.ForEachNode; import org.xmlpull.infoset.XmlElement; public class WSPort extends DataPort { private WSComponentPort componentPort; /** * Constructs a WSPort. */ public WSPort() { super(); } /** * Constructs a WsPort. * * @param portElement */ public WSPort(XmlElement portElement) { super(portElement); } public WSPort(JsonObject portObject) { super(portObject); } /** * Returns the typeQName. * * @return The typeQName */ @Override public DataType getType() { return getComponentPort().getType(); } /** * @see org.apache.airavata.workflow.model.graph.DataPort#copyType(org.apache.airavata.workflow.model.graph.DataPort) */ @Override public void copyType(DataPort port) throws GraphException { DataType newType = port.getType(); DataType type = getType(); NodeImpl node = port.getNode(); if (node instanceof ForEachNode || node instanceof EndForEachNode) { // XXX ignore the check for foreach because we cannot parse arrays // from WSDL. return; } if (!(newType == null || newType.equals(WSConstants.XSD_ANY_TYPE) || type == null || type.equals(WSConstants.XSD_ANY_TYPE) || newType.equals(type))) { String message = "The type (" + newType + ") must be same as the type " + " (" + type + ") of " + getID() + "."; throw new GraphException(message); } } /** * @param componentPort */ @Override public void setComponentPort(ComponentPort componentPort) { super.setComponentPort(componentPort); this.componentPort = (WSComponentPort) componentPort; } /** * @see org.apache.airavata.workflow.model.graph.impl.PortImpl#getComponentPort() */ @Override public WSComponentPort getComponentPort() { if (this.componentPort == null) { ComponentPort port = super.getComponentPort(); if (port instanceof WSComponentPort) { this.componentPort = (WSComponentPort) port; } if (port instanceof SystemComponentDataPort) { // XXX to handle the xwf created by version 2.6.2_XX or earlier. SystemComponentDataPort systemPort = (SystemComponentDataPort) port; this.componentPort = new WSComponentPort(systemPort.getName(), systemPort.getType(), null); } } return this.componentPort; } /** * @see org.apache.airavata.workflow.model.graph.impl.PortImpl#toXML() */ @Override protected XmlElement toXML() { XmlElement portElement = super.toXML(); portElement.setAttributeValue(GraphSchema.NS, GraphSchema.PORT_TYPE_ATTRIBUTE, GraphSchema.PORT_TYPE_WS_DATA); return portElement; } protected JsonObject toJSON() { JsonObject portObject = super.toJSON(); portObject.addProperty(GraphSchema.PORT_TYPE_ATTRIBUTE, GraphSchema.PORT_TYPE_WS_DATA); portObject.addProperty(GraphSchema.PORT_DATA_TYPE_TAG, this.getType().toString()); return portObject; } }
apache-2.0
mycFelix/heron
storm-compatibility/src/java/backtype/storm/metric/api/MetricDelegate.java
1150
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package backtype.storm.metric.api; @SuppressWarnings("rawtypes") public class MetricDelegate implements org.apache.heron.api.metric.IMetric { private IMetric delegate; public MetricDelegate(IMetric delegate) { this.delegate = delegate; } @Override public Object getValueAndReset() { return delegate.getValueAndReset(); } }
apache-2.0
debian-pkg-android-tools/android-platform-tools-apksig
src/main/java/com/android/apksig/internal/apk/v2/ContentDigestAlgorithm.java
1714
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.apksig.internal.apk.v2; /** * APK Signature Scheme v2 content digest algorithm. */ public enum ContentDigestAlgorithm { /** SHA2-256 over 1 MB chunks. */ CHUNKED_SHA256("SHA-256", 256 / 8), /** SHA2-512 over 1 MB chunks. */ CHUNKED_SHA512("SHA-512", 512 / 8); private final String mJcaMessageDigestAlgorithm; private final int mChunkDigestOutputSizeBytes; private ContentDigestAlgorithm( String jcaMessageDigestAlgorithm, int chunkDigestOutputSizeBytes) { mJcaMessageDigestAlgorithm = jcaMessageDigestAlgorithm; mChunkDigestOutputSizeBytes = chunkDigestOutputSizeBytes; } /** * Returns the {@link java.security.MessageDigest} algorithm used for computing digests of * chunks by this content digest algorithm. */ String getJcaMessageDigestAlgorithm() { return mJcaMessageDigestAlgorithm; } /** * Returns the size (in bytes) of the digest of a chunk of content. */ int getChunkDigestOutputSizeBytes() { return mChunkDigestOutputSizeBytes; } }
apache-2.0
shs96c/buck
test/com/facebook/buck/features/rust/PrebuiltRustLibraryDescriptionTest.java
3094
/* * Copyright 2017-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.features.rust; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.targetgraph.TargetGraph; import com.facebook.buck.core.model.targetgraph.TargetGraphFactory; import com.facebook.buck.core.rules.ActionGraphBuilder; import com.facebook.buck.core.rules.resolver.impl.TestActionGraphBuilder; import com.facebook.buck.core.sourcepath.FakeSourcePath; import com.facebook.buck.rules.coercer.PatternMatchedCollection; import com.google.common.collect.ImmutableSortedSet; import java.util.regex.Pattern; import org.hamcrest.Matchers; import org.junit.Test; public class PrebuiltRustLibraryDescriptionTest { @Test public void platformDeps() { PrebuiltRustLibraryBuilder depABuilder = PrebuiltRustLibraryBuilder.from("//:depA").setRlib(FakeSourcePath.of("a.rlib")); PrebuiltRustLibraryBuilder depBBuilder = PrebuiltRustLibraryBuilder.from("//:depB").setRlib(FakeSourcePath.of("b.rlib")); PrebuiltRustLibraryBuilder ruleBuilder = PrebuiltRustLibraryBuilder.from("//:rule") .setRlib(FakeSourcePath.of("c.rlib")) .setPlatformDeps( PatternMatchedCollection.<ImmutableSortedSet<BuildTarget>>builder() .add( Pattern.compile( RustTestUtils.DEFAULT_PLATFORM.getFlavor().toString(), Pattern.LITERAL), ImmutableSortedSet.of(depABuilder.getTarget())) .add( Pattern.compile("matches nothing", Pattern.LITERAL), ImmutableSortedSet.of(depBBuilder.getTarget())) .build()); TargetGraph targetGraph = TargetGraphFactory.newInstance( depABuilder.build(), depBBuilder.build(), ruleBuilder.build()); ActionGraphBuilder graphBuilder = new TestActionGraphBuilder(targetGraph); PrebuiltRustLibrary depA = (PrebuiltRustLibrary) graphBuilder.requireRule(depABuilder.getTarget()); PrebuiltRustLibrary depB = (PrebuiltRustLibrary) graphBuilder.requireRule(depBBuilder.getTarget()); PrebuiltRustLibrary rule = (PrebuiltRustLibrary) graphBuilder.requireRule(ruleBuilder.getTarget()); assertThat( rule.getRustLinakbleDeps(RustTestUtils.DEFAULT_PLATFORM), Matchers.allOf(Matchers.hasItem(depA), not(Matchers.hasItem(depB)))); } }
apache-2.0
vineetgarg02/hive
standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/SQLForeignKey.java
60395
/** * Autogenerated by Thrift Compiler (0.9.3) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package org.apache.hadoop.hive.metastore.api; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import javax.annotation.Generated; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"}) @Generated(value = "Autogenerated by Thrift Compiler (0.9.3)") @org.apache.hadoop.classification.InterfaceAudience.Public @org.apache.hadoop.classification.InterfaceStability.Stable public class SQLForeignKey implements org.apache.thrift.TBase<SQLForeignKey, SQLForeignKey._Fields>, java.io.Serializable, Cloneable, Comparable<SQLForeignKey> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("SQLForeignKey"); private static final org.apache.thrift.protocol.TField PKTABLE_DB_FIELD_DESC = new org.apache.thrift.protocol.TField("pktable_db", org.apache.thrift.protocol.TType.STRING, (short)1); private static final org.apache.thrift.protocol.TField PKTABLE_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("pktable_name", org.apache.thrift.protocol.TType.STRING, (short)2); private static final org.apache.thrift.protocol.TField PKCOLUMN_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("pkcolumn_name", org.apache.thrift.protocol.TType.STRING, (short)3); private static final org.apache.thrift.protocol.TField FKTABLE_DB_FIELD_DESC = new org.apache.thrift.protocol.TField("fktable_db", org.apache.thrift.protocol.TType.STRING, (short)4); private static final org.apache.thrift.protocol.TField FKTABLE_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("fktable_name", org.apache.thrift.protocol.TType.STRING, (short)5); private static final org.apache.thrift.protocol.TField FKCOLUMN_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("fkcolumn_name", org.apache.thrift.protocol.TType.STRING, (short)6); private static final org.apache.thrift.protocol.TField KEY_SEQ_FIELD_DESC = new org.apache.thrift.protocol.TField("key_seq", org.apache.thrift.protocol.TType.I32, (short)7); private static final org.apache.thrift.protocol.TField UPDATE_RULE_FIELD_DESC = new org.apache.thrift.protocol.TField("update_rule", org.apache.thrift.protocol.TType.I32, (short)8); private static final org.apache.thrift.protocol.TField DELETE_RULE_FIELD_DESC = new org.apache.thrift.protocol.TField("delete_rule", org.apache.thrift.protocol.TType.I32, (short)9); private static final org.apache.thrift.protocol.TField FK_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("fk_name", org.apache.thrift.protocol.TType.STRING, (short)10); private static final org.apache.thrift.protocol.TField PK_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("pk_name", org.apache.thrift.protocol.TType.STRING, (short)11); private static final org.apache.thrift.protocol.TField ENABLE_CSTR_FIELD_DESC = new org.apache.thrift.protocol.TField("enable_cstr", org.apache.thrift.protocol.TType.BOOL, (short)12); private static final org.apache.thrift.protocol.TField VALIDATE_CSTR_FIELD_DESC = new org.apache.thrift.protocol.TField("validate_cstr", org.apache.thrift.protocol.TType.BOOL, (short)13); private static final org.apache.thrift.protocol.TField RELY_CSTR_FIELD_DESC = new org.apache.thrift.protocol.TField("rely_cstr", org.apache.thrift.protocol.TType.BOOL, (short)14); private static final org.apache.thrift.protocol.TField CAT_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("catName", org.apache.thrift.protocol.TType.STRING, (short)15); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new SQLForeignKeyStandardSchemeFactory()); schemes.put(TupleScheme.class, new SQLForeignKeyTupleSchemeFactory()); } private String pktable_db; // required private String pktable_name; // required private String pkcolumn_name; // required private String fktable_db; // required private String fktable_name; // required private String fkcolumn_name; // required private int key_seq; // required private int update_rule; // required private int delete_rule; // required private String fk_name; // required private String pk_name; // required private boolean enable_cstr; // required private boolean validate_cstr; // required private boolean rely_cstr; // required private String catName; // optional /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { PKTABLE_DB((short)1, "pktable_db"), PKTABLE_NAME((short)2, "pktable_name"), PKCOLUMN_NAME((short)3, "pkcolumn_name"), FKTABLE_DB((short)4, "fktable_db"), FKTABLE_NAME((short)5, "fktable_name"), FKCOLUMN_NAME((short)6, "fkcolumn_name"), KEY_SEQ((short)7, "key_seq"), UPDATE_RULE((short)8, "update_rule"), DELETE_RULE((short)9, "delete_rule"), FK_NAME((short)10, "fk_name"), PK_NAME((short)11, "pk_name"), ENABLE_CSTR((short)12, "enable_cstr"), VALIDATE_CSTR((short)13, "validate_cstr"), RELY_CSTR((short)14, "rely_cstr"), CAT_NAME((short)15, "catName"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // PKTABLE_DB return PKTABLE_DB; case 2: // PKTABLE_NAME return PKTABLE_NAME; case 3: // PKCOLUMN_NAME return PKCOLUMN_NAME; case 4: // FKTABLE_DB return FKTABLE_DB; case 5: // FKTABLE_NAME return FKTABLE_NAME; case 6: // FKCOLUMN_NAME return FKCOLUMN_NAME; case 7: // KEY_SEQ return KEY_SEQ; case 8: // UPDATE_RULE return UPDATE_RULE; case 9: // DELETE_RULE return DELETE_RULE; case 10: // FK_NAME return FK_NAME; case 11: // PK_NAME return PK_NAME; case 12: // ENABLE_CSTR return ENABLE_CSTR; case 13: // VALIDATE_CSTR return VALIDATE_CSTR; case 14: // RELY_CSTR return RELY_CSTR; case 15: // CAT_NAME return CAT_NAME; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private static final int __KEY_SEQ_ISSET_ID = 0; private static final int __UPDATE_RULE_ISSET_ID = 1; private static final int __DELETE_RULE_ISSET_ID = 2; private static final int __ENABLE_CSTR_ISSET_ID = 3; private static final int __VALIDATE_CSTR_ISSET_ID = 4; private static final int __RELY_CSTR_ISSET_ID = 5; private byte __isset_bitfield = 0; private static final _Fields optionals[] = {_Fields.CAT_NAME}; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.PKTABLE_DB, new org.apache.thrift.meta_data.FieldMetaData("pktable_db", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.PKTABLE_NAME, new org.apache.thrift.meta_data.FieldMetaData("pktable_name", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.PKCOLUMN_NAME, new org.apache.thrift.meta_data.FieldMetaData("pkcolumn_name", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.FKTABLE_DB, new org.apache.thrift.meta_data.FieldMetaData("fktable_db", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.FKTABLE_NAME, new org.apache.thrift.meta_data.FieldMetaData("fktable_name", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.FKCOLUMN_NAME, new org.apache.thrift.meta_data.FieldMetaData("fkcolumn_name", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.KEY_SEQ, new org.apache.thrift.meta_data.FieldMetaData("key_seq", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.UPDATE_RULE, new org.apache.thrift.meta_data.FieldMetaData("update_rule", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.DELETE_RULE, new org.apache.thrift.meta_data.FieldMetaData("delete_rule", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); tmpMap.put(_Fields.FK_NAME, new org.apache.thrift.meta_data.FieldMetaData("fk_name", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.PK_NAME, new org.apache.thrift.meta_data.FieldMetaData("pk_name", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); tmpMap.put(_Fields.ENABLE_CSTR, new org.apache.thrift.meta_data.FieldMetaData("enable_cstr", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.VALIDATE_CSTR, new org.apache.thrift.meta_data.FieldMetaData("validate_cstr", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.RELY_CSTR, new org.apache.thrift.meta_data.FieldMetaData("rely_cstr", org.apache.thrift.TFieldRequirementType.DEFAULT, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); tmpMap.put(_Fields.CAT_NAME, new org.apache.thrift.meta_data.FieldMetaData("catName", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(SQLForeignKey.class, metaDataMap); } public SQLForeignKey() { } public SQLForeignKey( String pktable_db, String pktable_name, String pkcolumn_name, String fktable_db, String fktable_name, String fkcolumn_name, int key_seq, int update_rule, int delete_rule, String fk_name, String pk_name, boolean enable_cstr, boolean validate_cstr, boolean rely_cstr) { this(); this.pktable_db = pktable_db; this.pktable_name = pktable_name; this.pkcolumn_name = pkcolumn_name; this.fktable_db = fktable_db; this.fktable_name = fktable_name; this.fkcolumn_name = fkcolumn_name; this.key_seq = key_seq; setKey_seqIsSet(true); this.update_rule = update_rule; setUpdate_ruleIsSet(true); this.delete_rule = delete_rule; setDelete_ruleIsSet(true); this.fk_name = fk_name; this.pk_name = pk_name; this.enable_cstr = enable_cstr; setEnable_cstrIsSet(true); this.validate_cstr = validate_cstr; setValidate_cstrIsSet(true); this.rely_cstr = rely_cstr; setRely_cstrIsSet(true); } /** * Performs a deep copy on <i>other</i>. */ public SQLForeignKey(SQLForeignKey other) { __isset_bitfield = other.__isset_bitfield; if (other.isSetPktable_db()) { this.pktable_db = other.pktable_db; } if (other.isSetPktable_name()) { this.pktable_name = other.pktable_name; } if (other.isSetPkcolumn_name()) { this.pkcolumn_name = other.pkcolumn_name; } if (other.isSetFktable_db()) { this.fktable_db = other.fktable_db; } if (other.isSetFktable_name()) { this.fktable_name = other.fktable_name; } if (other.isSetFkcolumn_name()) { this.fkcolumn_name = other.fkcolumn_name; } this.key_seq = other.key_seq; this.update_rule = other.update_rule; this.delete_rule = other.delete_rule; if (other.isSetFk_name()) { this.fk_name = other.fk_name; } if (other.isSetPk_name()) { this.pk_name = other.pk_name; } this.enable_cstr = other.enable_cstr; this.validate_cstr = other.validate_cstr; this.rely_cstr = other.rely_cstr; if (other.isSetCatName()) { this.catName = other.catName; } } public SQLForeignKey deepCopy() { return new SQLForeignKey(this); } @Override public void clear() { this.pktable_db = null; this.pktable_name = null; this.pkcolumn_name = null; this.fktable_db = null; this.fktable_name = null; this.fkcolumn_name = null; setKey_seqIsSet(false); this.key_seq = 0; setUpdate_ruleIsSet(false); this.update_rule = 0; setDelete_ruleIsSet(false); this.delete_rule = 0; this.fk_name = null; this.pk_name = null; setEnable_cstrIsSet(false); this.enable_cstr = false; setValidate_cstrIsSet(false); this.validate_cstr = false; setRely_cstrIsSet(false); this.rely_cstr = false; this.catName = null; } public String getPktable_db() { return this.pktable_db; } public void setPktable_db(String pktable_db) { this.pktable_db = pktable_db; } public void unsetPktable_db() { this.pktable_db = null; } /** Returns true if field pktable_db is set (has been assigned a value) and false otherwise */ public boolean isSetPktable_db() { return this.pktable_db != null; } public void setPktable_dbIsSet(boolean value) { if (!value) { this.pktable_db = null; } } public String getPktable_name() { return this.pktable_name; } public void setPktable_name(String pktable_name) { this.pktable_name = pktable_name; } public void unsetPktable_name() { this.pktable_name = null; } /** Returns true if field pktable_name is set (has been assigned a value) and false otherwise */ public boolean isSetPktable_name() { return this.pktable_name != null; } public void setPktable_nameIsSet(boolean value) { if (!value) { this.pktable_name = null; } } public String getPkcolumn_name() { return this.pkcolumn_name; } public void setPkcolumn_name(String pkcolumn_name) { this.pkcolumn_name = pkcolumn_name; } public void unsetPkcolumn_name() { this.pkcolumn_name = null; } /** Returns true if field pkcolumn_name is set (has been assigned a value) and false otherwise */ public boolean isSetPkcolumn_name() { return this.pkcolumn_name != null; } public void setPkcolumn_nameIsSet(boolean value) { if (!value) { this.pkcolumn_name = null; } } public String getFktable_db() { return this.fktable_db; } public void setFktable_db(String fktable_db) { this.fktable_db = fktable_db; } public void unsetFktable_db() { this.fktable_db = null; } /** Returns true if field fktable_db is set (has been assigned a value) and false otherwise */ public boolean isSetFktable_db() { return this.fktable_db != null; } public void setFktable_dbIsSet(boolean value) { if (!value) { this.fktable_db = null; } } public String getFktable_name() { return this.fktable_name; } public void setFktable_name(String fktable_name) { this.fktable_name = fktable_name; } public void unsetFktable_name() { this.fktable_name = null; } /** Returns true if field fktable_name is set (has been assigned a value) and false otherwise */ public boolean isSetFktable_name() { return this.fktable_name != null; } public void setFktable_nameIsSet(boolean value) { if (!value) { this.fktable_name = null; } } public String getFkcolumn_name() { return this.fkcolumn_name; } public void setFkcolumn_name(String fkcolumn_name) { this.fkcolumn_name = fkcolumn_name; } public void unsetFkcolumn_name() { this.fkcolumn_name = null; } /** Returns true if field fkcolumn_name is set (has been assigned a value) and false otherwise */ public boolean isSetFkcolumn_name() { return this.fkcolumn_name != null; } public void setFkcolumn_nameIsSet(boolean value) { if (!value) { this.fkcolumn_name = null; } } public int getKey_seq() { return this.key_seq; } public void setKey_seq(int key_seq) { this.key_seq = key_seq; setKey_seqIsSet(true); } public void unsetKey_seq() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __KEY_SEQ_ISSET_ID); } /** Returns true if field key_seq is set (has been assigned a value) and false otherwise */ public boolean isSetKey_seq() { return EncodingUtils.testBit(__isset_bitfield, __KEY_SEQ_ISSET_ID); } public void setKey_seqIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __KEY_SEQ_ISSET_ID, value); } public int getUpdate_rule() { return this.update_rule; } public void setUpdate_rule(int update_rule) { this.update_rule = update_rule; setUpdate_ruleIsSet(true); } public void unsetUpdate_rule() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __UPDATE_RULE_ISSET_ID); } /** Returns true if field update_rule is set (has been assigned a value) and false otherwise */ public boolean isSetUpdate_rule() { return EncodingUtils.testBit(__isset_bitfield, __UPDATE_RULE_ISSET_ID); } public void setUpdate_ruleIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __UPDATE_RULE_ISSET_ID, value); } public int getDelete_rule() { return this.delete_rule; } public void setDelete_rule(int delete_rule) { this.delete_rule = delete_rule; setDelete_ruleIsSet(true); } public void unsetDelete_rule() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __DELETE_RULE_ISSET_ID); } /** Returns true if field delete_rule is set (has been assigned a value) and false otherwise */ public boolean isSetDelete_rule() { return EncodingUtils.testBit(__isset_bitfield, __DELETE_RULE_ISSET_ID); } public void setDelete_ruleIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __DELETE_RULE_ISSET_ID, value); } public String getFk_name() { return this.fk_name; } public void setFk_name(String fk_name) { this.fk_name = fk_name; } public void unsetFk_name() { this.fk_name = null; } /** Returns true if field fk_name is set (has been assigned a value) and false otherwise */ public boolean isSetFk_name() { return this.fk_name != null; } public void setFk_nameIsSet(boolean value) { if (!value) { this.fk_name = null; } } public String getPk_name() { return this.pk_name; } public void setPk_name(String pk_name) { this.pk_name = pk_name; } public void unsetPk_name() { this.pk_name = null; } /** Returns true if field pk_name is set (has been assigned a value) and false otherwise */ public boolean isSetPk_name() { return this.pk_name != null; } public void setPk_nameIsSet(boolean value) { if (!value) { this.pk_name = null; } } public boolean isEnable_cstr() { return this.enable_cstr; } public void setEnable_cstr(boolean enable_cstr) { this.enable_cstr = enable_cstr; setEnable_cstrIsSet(true); } public void unsetEnable_cstr() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __ENABLE_CSTR_ISSET_ID); } /** Returns true if field enable_cstr is set (has been assigned a value) and false otherwise */ public boolean isSetEnable_cstr() { return EncodingUtils.testBit(__isset_bitfield, __ENABLE_CSTR_ISSET_ID); } public void setEnable_cstrIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __ENABLE_CSTR_ISSET_ID, value); } public boolean isValidate_cstr() { return this.validate_cstr; } public void setValidate_cstr(boolean validate_cstr) { this.validate_cstr = validate_cstr; setValidate_cstrIsSet(true); } public void unsetValidate_cstr() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __VALIDATE_CSTR_ISSET_ID); } /** Returns true if field validate_cstr is set (has been assigned a value) and false otherwise */ public boolean isSetValidate_cstr() { return EncodingUtils.testBit(__isset_bitfield, __VALIDATE_CSTR_ISSET_ID); } public void setValidate_cstrIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __VALIDATE_CSTR_ISSET_ID, value); } public boolean isRely_cstr() { return this.rely_cstr; } public void setRely_cstr(boolean rely_cstr) { this.rely_cstr = rely_cstr; setRely_cstrIsSet(true); } public void unsetRely_cstr() { __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __RELY_CSTR_ISSET_ID); } /** Returns true if field rely_cstr is set (has been assigned a value) and false otherwise */ public boolean isSetRely_cstr() { return EncodingUtils.testBit(__isset_bitfield, __RELY_CSTR_ISSET_ID); } public void setRely_cstrIsSet(boolean value) { __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __RELY_CSTR_ISSET_ID, value); } public String getCatName() { return this.catName; } public void setCatName(String catName) { this.catName = catName; } public void unsetCatName() { this.catName = null; } /** Returns true if field catName is set (has been assigned a value) and false otherwise */ public boolean isSetCatName() { return this.catName != null; } public void setCatNameIsSet(boolean value) { if (!value) { this.catName = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case PKTABLE_DB: if (value == null) { unsetPktable_db(); } else { setPktable_db((String)value); } break; case PKTABLE_NAME: if (value == null) { unsetPktable_name(); } else { setPktable_name((String)value); } break; case PKCOLUMN_NAME: if (value == null) { unsetPkcolumn_name(); } else { setPkcolumn_name((String)value); } break; case FKTABLE_DB: if (value == null) { unsetFktable_db(); } else { setFktable_db((String)value); } break; case FKTABLE_NAME: if (value == null) { unsetFktable_name(); } else { setFktable_name((String)value); } break; case FKCOLUMN_NAME: if (value == null) { unsetFkcolumn_name(); } else { setFkcolumn_name((String)value); } break; case KEY_SEQ: if (value == null) { unsetKey_seq(); } else { setKey_seq((Integer)value); } break; case UPDATE_RULE: if (value == null) { unsetUpdate_rule(); } else { setUpdate_rule((Integer)value); } break; case DELETE_RULE: if (value == null) { unsetDelete_rule(); } else { setDelete_rule((Integer)value); } break; case FK_NAME: if (value == null) { unsetFk_name(); } else { setFk_name((String)value); } break; case PK_NAME: if (value == null) { unsetPk_name(); } else { setPk_name((String)value); } break; case ENABLE_CSTR: if (value == null) { unsetEnable_cstr(); } else { setEnable_cstr((Boolean)value); } break; case VALIDATE_CSTR: if (value == null) { unsetValidate_cstr(); } else { setValidate_cstr((Boolean)value); } break; case RELY_CSTR: if (value == null) { unsetRely_cstr(); } else { setRely_cstr((Boolean)value); } break; case CAT_NAME: if (value == null) { unsetCatName(); } else { setCatName((String)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case PKTABLE_DB: return getPktable_db(); case PKTABLE_NAME: return getPktable_name(); case PKCOLUMN_NAME: return getPkcolumn_name(); case FKTABLE_DB: return getFktable_db(); case FKTABLE_NAME: return getFktable_name(); case FKCOLUMN_NAME: return getFkcolumn_name(); case KEY_SEQ: return getKey_seq(); case UPDATE_RULE: return getUpdate_rule(); case DELETE_RULE: return getDelete_rule(); case FK_NAME: return getFk_name(); case PK_NAME: return getPk_name(); case ENABLE_CSTR: return isEnable_cstr(); case VALIDATE_CSTR: return isValidate_cstr(); case RELY_CSTR: return isRely_cstr(); case CAT_NAME: return getCatName(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case PKTABLE_DB: return isSetPktable_db(); case PKTABLE_NAME: return isSetPktable_name(); case PKCOLUMN_NAME: return isSetPkcolumn_name(); case FKTABLE_DB: return isSetFktable_db(); case FKTABLE_NAME: return isSetFktable_name(); case FKCOLUMN_NAME: return isSetFkcolumn_name(); case KEY_SEQ: return isSetKey_seq(); case UPDATE_RULE: return isSetUpdate_rule(); case DELETE_RULE: return isSetDelete_rule(); case FK_NAME: return isSetFk_name(); case PK_NAME: return isSetPk_name(); case ENABLE_CSTR: return isSetEnable_cstr(); case VALIDATE_CSTR: return isSetValidate_cstr(); case RELY_CSTR: return isSetRely_cstr(); case CAT_NAME: return isSetCatName(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof SQLForeignKey) return this.equals((SQLForeignKey)that); return false; } public boolean equals(SQLForeignKey that) { if (that == null) return false; boolean this_present_pktable_db = true && this.isSetPktable_db(); boolean that_present_pktable_db = true && that.isSetPktable_db(); if (this_present_pktable_db || that_present_pktable_db) { if (!(this_present_pktable_db && that_present_pktable_db)) return false; if (!this.pktable_db.equals(that.pktable_db)) return false; } boolean this_present_pktable_name = true && this.isSetPktable_name(); boolean that_present_pktable_name = true && that.isSetPktable_name(); if (this_present_pktable_name || that_present_pktable_name) { if (!(this_present_pktable_name && that_present_pktable_name)) return false; if (!this.pktable_name.equals(that.pktable_name)) return false; } boolean this_present_pkcolumn_name = true && this.isSetPkcolumn_name(); boolean that_present_pkcolumn_name = true && that.isSetPkcolumn_name(); if (this_present_pkcolumn_name || that_present_pkcolumn_name) { if (!(this_present_pkcolumn_name && that_present_pkcolumn_name)) return false; if (!this.pkcolumn_name.equals(that.pkcolumn_name)) return false; } boolean this_present_fktable_db = true && this.isSetFktable_db(); boolean that_present_fktable_db = true && that.isSetFktable_db(); if (this_present_fktable_db || that_present_fktable_db) { if (!(this_present_fktable_db && that_present_fktable_db)) return false; if (!this.fktable_db.equals(that.fktable_db)) return false; } boolean this_present_fktable_name = true && this.isSetFktable_name(); boolean that_present_fktable_name = true && that.isSetFktable_name(); if (this_present_fktable_name || that_present_fktable_name) { if (!(this_present_fktable_name && that_present_fktable_name)) return false; if (!this.fktable_name.equals(that.fktable_name)) return false; } boolean this_present_fkcolumn_name = true && this.isSetFkcolumn_name(); boolean that_present_fkcolumn_name = true && that.isSetFkcolumn_name(); if (this_present_fkcolumn_name || that_present_fkcolumn_name) { if (!(this_present_fkcolumn_name && that_present_fkcolumn_name)) return false; if (!this.fkcolumn_name.equals(that.fkcolumn_name)) return false; } boolean this_present_key_seq = true; boolean that_present_key_seq = true; if (this_present_key_seq || that_present_key_seq) { if (!(this_present_key_seq && that_present_key_seq)) return false; if (this.key_seq != that.key_seq) return false; } boolean this_present_update_rule = true; boolean that_present_update_rule = true; if (this_present_update_rule || that_present_update_rule) { if (!(this_present_update_rule && that_present_update_rule)) return false; if (this.update_rule != that.update_rule) return false; } boolean this_present_delete_rule = true; boolean that_present_delete_rule = true; if (this_present_delete_rule || that_present_delete_rule) { if (!(this_present_delete_rule && that_present_delete_rule)) return false; if (this.delete_rule != that.delete_rule) return false; } boolean this_present_fk_name = true && this.isSetFk_name(); boolean that_present_fk_name = true && that.isSetFk_name(); if (this_present_fk_name || that_present_fk_name) { if (!(this_present_fk_name && that_present_fk_name)) return false; if (!this.fk_name.equals(that.fk_name)) return false; } boolean this_present_pk_name = true && this.isSetPk_name(); boolean that_present_pk_name = true && that.isSetPk_name(); if (this_present_pk_name || that_present_pk_name) { if (!(this_present_pk_name && that_present_pk_name)) return false; if (!this.pk_name.equals(that.pk_name)) return false; } boolean this_present_enable_cstr = true; boolean that_present_enable_cstr = true; if (this_present_enable_cstr || that_present_enable_cstr) { if (!(this_present_enable_cstr && that_present_enable_cstr)) return false; if (this.enable_cstr != that.enable_cstr) return false; } boolean this_present_validate_cstr = true; boolean that_present_validate_cstr = true; if (this_present_validate_cstr || that_present_validate_cstr) { if (!(this_present_validate_cstr && that_present_validate_cstr)) return false; if (this.validate_cstr != that.validate_cstr) return false; } boolean this_present_rely_cstr = true; boolean that_present_rely_cstr = true; if (this_present_rely_cstr || that_present_rely_cstr) { if (!(this_present_rely_cstr && that_present_rely_cstr)) return false; if (this.rely_cstr != that.rely_cstr) return false; } boolean this_present_catName = true && this.isSetCatName(); boolean that_present_catName = true && that.isSetCatName(); if (this_present_catName || that_present_catName) { if (!(this_present_catName && that_present_catName)) return false; if (!this.catName.equals(that.catName)) return false; } return true; } @Override public int hashCode() { List<Object> list = new ArrayList<Object>(); boolean present_pktable_db = true && (isSetPktable_db()); list.add(present_pktable_db); if (present_pktable_db) list.add(pktable_db); boolean present_pktable_name = true && (isSetPktable_name()); list.add(present_pktable_name); if (present_pktable_name) list.add(pktable_name); boolean present_pkcolumn_name = true && (isSetPkcolumn_name()); list.add(present_pkcolumn_name); if (present_pkcolumn_name) list.add(pkcolumn_name); boolean present_fktable_db = true && (isSetFktable_db()); list.add(present_fktable_db); if (present_fktable_db) list.add(fktable_db); boolean present_fktable_name = true && (isSetFktable_name()); list.add(present_fktable_name); if (present_fktable_name) list.add(fktable_name); boolean present_fkcolumn_name = true && (isSetFkcolumn_name()); list.add(present_fkcolumn_name); if (present_fkcolumn_name) list.add(fkcolumn_name); boolean present_key_seq = true; list.add(present_key_seq); if (present_key_seq) list.add(key_seq); boolean present_update_rule = true; list.add(present_update_rule); if (present_update_rule) list.add(update_rule); boolean present_delete_rule = true; list.add(present_delete_rule); if (present_delete_rule) list.add(delete_rule); boolean present_fk_name = true && (isSetFk_name()); list.add(present_fk_name); if (present_fk_name) list.add(fk_name); boolean present_pk_name = true && (isSetPk_name()); list.add(present_pk_name); if (present_pk_name) list.add(pk_name); boolean present_enable_cstr = true; list.add(present_enable_cstr); if (present_enable_cstr) list.add(enable_cstr); boolean present_validate_cstr = true; list.add(present_validate_cstr); if (present_validate_cstr) list.add(validate_cstr); boolean present_rely_cstr = true; list.add(present_rely_cstr); if (present_rely_cstr) list.add(rely_cstr); boolean present_catName = true && (isSetCatName()); list.add(present_catName); if (present_catName) list.add(catName); return list.hashCode(); } @Override public int compareTo(SQLForeignKey other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetPktable_db()).compareTo(other.isSetPktable_db()); if (lastComparison != 0) { return lastComparison; } if (isSetPktable_db()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.pktable_db, other.pktable_db); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPktable_name()).compareTo(other.isSetPktable_name()); if (lastComparison != 0) { return lastComparison; } if (isSetPktable_name()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.pktable_name, other.pktable_name); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPkcolumn_name()).compareTo(other.isSetPkcolumn_name()); if (lastComparison != 0) { return lastComparison; } if (isSetPkcolumn_name()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.pkcolumn_name, other.pkcolumn_name); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetFktable_db()).compareTo(other.isSetFktable_db()); if (lastComparison != 0) { return lastComparison; } if (isSetFktable_db()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.fktable_db, other.fktable_db); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetFktable_name()).compareTo(other.isSetFktable_name()); if (lastComparison != 0) { return lastComparison; } if (isSetFktable_name()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.fktable_name, other.fktable_name); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetFkcolumn_name()).compareTo(other.isSetFkcolumn_name()); if (lastComparison != 0) { return lastComparison; } if (isSetFkcolumn_name()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.fkcolumn_name, other.fkcolumn_name); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetKey_seq()).compareTo(other.isSetKey_seq()); if (lastComparison != 0) { return lastComparison; } if (isSetKey_seq()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.key_seq, other.key_seq); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetUpdate_rule()).compareTo(other.isSetUpdate_rule()); if (lastComparison != 0) { return lastComparison; } if (isSetUpdate_rule()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.update_rule, other.update_rule); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetDelete_rule()).compareTo(other.isSetDelete_rule()); if (lastComparison != 0) { return lastComparison; } if (isSetDelete_rule()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.delete_rule, other.delete_rule); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetFk_name()).compareTo(other.isSetFk_name()); if (lastComparison != 0) { return lastComparison; } if (isSetFk_name()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.fk_name, other.fk_name); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetPk_name()).compareTo(other.isSetPk_name()); if (lastComparison != 0) { return lastComparison; } if (isSetPk_name()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.pk_name, other.pk_name); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetEnable_cstr()).compareTo(other.isSetEnable_cstr()); if (lastComparison != 0) { return lastComparison; } if (isSetEnable_cstr()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.enable_cstr, other.enable_cstr); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetValidate_cstr()).compareTo(other.isSetValidate_cstr()); if (lastComparison != 0) { return lastComparison; } if (isSetValidate_cstr()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.validate_cstr, other.validate_cstr); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetRely_cstr()).compareTo(other.isSetRely_cstr()); if (lastComparison != 0) { return lastComparison; } if (isSetRely_cstr()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.rely_cstr, other.rely_cstr); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetCatName()).compareTo(other.isSetCatName()); if (lastComparison != 0) { return lastComparison; } if (isSetCatName()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.catName, other.catName); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("SQLForeignKey("); boolean first = true; sb.append("pktable_db:"); if (this.pktable_db == null) { sb.append("null"); } else { sb.append(this.pktable_db); } first = false; if (!first) sb.append(", "); sb.append("pktable_name:"); if (this.pktable_name == null) { sb.append("null"); } else { sb.append(this.pktable_name); } first = false; if (!first) sb.append(", "); sb.append("pkcolumn_name:"); if (this.pkcolumn_name == null) { sb.append("null"); } else { sb.append(this.pkcolumn_name); } first = false; if (!first) sb.append(", "); sb.append("fktable_db:"); if (this.fktable_db == null) { sb.append("null"); } else { sb.append(this.fktable_db); } first = false; if (!first) sb.append(", "); sb.append("fktable_name:"); if (this.fktable_name == null) { sb.append("null"); } else { sb.append(this.fktable_name); } first = false; if (!first) sb.append(", "); sb.append("fkcolumn_name:"); if (this.fkcolumn_name == null) { sb.append("null"); } else { sb.append(this.fkcolumn_name); } first = false; if (!first) sb.append(", "); sb.append("key_seq:"); sb.append(this.key_seq); first = false; if (!first) sb.append(", "); sb.append("update_rule:"); sb.append(this.update_rule); first = false; if (!first) sb.append(", "); sb.append("delete_rule:"); sb.append(this.delete_rule); first = false; if (!first) sb.append(", "); sb.append("fk_name:"); if (this.fk_name == null) { sb.append("null"); } else { sb.append(this.fk_name); } first = false; if (!first) sb.append(", "); sb.append("pk_name:"); if (this.pk_name == null) { sb.append("null"); } else { sb.append(this.pk_name); } first = false; if (!first) sb.append(", "); sb.append("enable_cstr:"); sb.append(this.enable_cstr); first = false; if (!first) sb.append(", "); sb.append("validate_cstr:"); sb.append(this.validate_cstr); first = false; if (!first) sb.append(", "); sb.append("rely_cstr:"); sb.append(this.rely_cstr); first = false; if (isSetCatName()) { if (!first) sb.append(", "); sb.append("catName:"); if (this.catName == null) { sb.append("null"); } else { sb.append(this.catName); } first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. __isset_bitfield = 0; read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class SQLForeignKeyStandardSchemeFactory implements SchemeFactory { public SQLForeignKeyStandardScheme getScheme() { return new SQLForeignKeyStandardScheme(); } } private static class SQLForeignKeyStandardScheme extends StandardScheme<SQLForeignKey> { public void read(org.apache.thrift.protocol.TProtocol iprot, SQLForeignKey struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // PKTABLE_DB if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.pktable_db = iprot.readString(); struct.setPktable_dbIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // PKTABLE_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.pktable_name = iprot.readString(); struct.setPktable_nameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 3: // PKCOLUMN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.pkcolumn_name = iprot.readString(); struct.setPkcolumn_nameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 4: // FKTABLE_DB if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.fktable_db = iprot.readString(); struct.setFktable_dbIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 5: // FKTABLE_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.fktable_name = iprot.readString(); struct.setFktable_nameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 6: // FKCOLUMN_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.fkcolumn_name = iprot.readString(); struct.setFkcolumn_nameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 7: // KEY_SEQ if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.key_seq = iprot.readI32(); struct.setKey_seqIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 8: // UPDATE_RULE if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.update_rule = iprot.readI32(); struct.setUpdate_ruleIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 9: // DELETE_RULE if (schemeField.type == org.apache.thrift.protocol.TType.I32) { struct.delete_rule = iprot.readI32(); struct.setDelete_ruleIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 10: // FK_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.fk_name = iprot.readString(); struct.setFk_nameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 11: // PK_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.pk_name = iprot.readString(); struct.setPk_nameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 12: // ENABLE_CSTR if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.enable_cstr = iprot.readBool(); struct.setEnable_cstrIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 13: // VALIDATE_CSTR if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.validate_cstr = iprot.readBool(); struct.setValidate_cstrIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 14: // RELY_CSTR if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { struct.rely_cstr = iprot.readBool(); struct.setRely_cstrIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 15: // CAT_NAME if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { struct.catName = iprot.readString(); struct.setCatNameIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, SQLForeignKey struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.pktable_db != null) { oprot.writeFieldBegin(PKTABLE_DB_FIELD_DESC); oprot.writeString(struct.pktable_db); oprot.writeFieldEnd(); } if (struct.pktable_name != null) { oprot.writeFieldBegin(PKTABLE_NAME_FIELD_DESC); oprot.writeString(struct.pktable_name); oprot.writeFieldEnd(); } if (struct.pkcolumn_name != null) { oprot.writeFieldBegin(PKCOLUMN_NAME_FIELD_DESC); oprot.writeString(struct.pkcolumn_name); oprot.writeFieldEnd(); } if (struct.fktable_db != null) { oprot.writeFieldBegin(FKTABLE_DB_FIELD_DESC); oprot.writeString(struct.fktable_db); oprot.writeFieldEnd(); } if (struct.fktable_name != null) { oprot.writeFieldBegin(FKTABLE_NAME_FIELD_DESC); oprot.writeString(struct.fktable_name); oprot.writeFieldEnd(); } if (struct.fkcolumn_name != null) { oprot.writeFieldBegin(FKCOLUMN_NAME_FIELD_DESC); oprot.writeString(struct.fkcolumn_name); oprot.writeFieldEnd(); } oprot.writeFieldBegin(KEY_SEQ_FIELD_DESC); oprot.writeI32(struct.key_seq); oprot.writeFieldEnd(); oprot.writeFieldBegin(UPDATE_RULE_FIELD_DESC); oprot.writeI32(struct.update_rule); oprot.writeFieldEnd(); oprot.writeFieldBegin(DELETE_RULE_FIELD_DESC); oprot.writeI32(struct.delete_rule); oprot.writeFieldEnd(); if (struct.fk_name != null) { oprot.writeFieldBegin(FK_NAME_FIELD_DESC); oprot.writeString(struct.fk_name); oprot.writeFieldEnd(); } if (struct.pk_name != null) { oprot.writeFieldBegin(PK_NAME_FIELD_DESC); oprot.writeString(struct.pk_name); oprot.writeFieldEnd(); } oprot.writeFieldBegin(ENABLE_CSTR_FIELD_DESC); oprot.writeBool(struct.enable_cstr); oprot.writeFieldEnd(); oprot.writeFieldBegin(VALIDATE_CSTR_FIELD_DESC); oprot.writeBool(struct.validate_cstr); oprot.writeFieldEnd(); oprot.writeFieldBegin(RELY_CSTR_FIELD_DESC); oprot.writeBool(struct.rely_cstr); oprot.writeFieldEnd(); if (struct.catName != null) { if (struct.isSetCatName()) { oprot.writeFieldBegin(CAT_NAME_FIELD_DESC); oprot.writeString(struct.catName); oprot.writeFieldEnd(); } } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class SQLForeignKeyTupleSchemeFactory implements SchemeFactory { public SQLForeignKeyTupleScheme getScheme() { return new SQLForeignKeyTupleScheme(); } } private static class SQLForeignKeyTupleScheme extends TupleScheme<SQLForeignKey> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, SQLForeignKey struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; BitSet optionals = new BitSet(); if (struct.isSetPktable_db()) { optionals.set(0); } if (struct.isSetPktable_name()) { optionals.set(1); } if (struct.isSetPkcolumn_name()) { optionals.set(2); } if (struct.isSetFktable_db()) { optionals.set(3); } if (struct.isSetFktable_name()) { optionals.set(4); } if (struct.isSetFkcolumn_name()) { optionals.set(5); } if (struct.isSetKey_seq()) { optionals.set(6); } if (struct.isSetUpdate_rule()) { optionals.set(7); } if (struct.isSetDelete_rule()) { optionals.set(8); } if (struct.isSetFk_name()) { optionals.set(9); } if (struct.isSetPk_name()) { optionals.set(10); } if (struct.isSetEnable_cstr()) { optionals.set(11); } if (struct.isSetValidate_cstr()) { optionals.set(12); } if (struct.isSetRely_cstr()) { optionals.set(13); } if (struct.isSetCatName()) { optionals.set(14); } oprot.writeBitSet(optionals, 15); if (struct.isSetPktable_db()) { oprot.writeString(struct.pktable_db); } if (struct.isSetPktable_name()) { oprot.writeString(struct.pktable_name); } if (struct.isSetPkcolumn_name()) { oprot.writeString(struct.pkcolumn_name); } if (struct.isSetFktable_db()) { oprot.writeString(struct.fktable_db); } if (struct.isSetFktable_name()) { oprot.writeString(struct.fktable_name); } if (struct.isSetFkcolumn_name()) { oprot.writeString(struct.fkcolumn_name); } if (struct.isSetKey_seq()) { oprot.writeI32(struct.key_seq); } if (struct.isSetUpdate_rule()) { oprot.writeI32(struct.update_rule); } if (struct.isSetDelete_rule()) { oprot.writeI32(struct.delete_rule); } if (struct.isSetFk_name()) { oprot.writeString(struct.fk_name); } if (struct.isSetPk_name()) { oprot.writeString(struct.pk_name); } if (struct.isSetEnable_cstr()) { oprot.writeBool(struct.enable_cstr); } if (struct.isSetValidate_cstr()) { oprot.writeBool(struct.validate_cstr); } if (struct.isSetRely_cstr()) { oprot.writeBool(struct.rely_cstr); } if (struct.isSetCatName()) { oprot.writeString(struct.catName); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, SQLForeignKey struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; BitSet incoming = iprot.readBitSet(15); if (incoming.get(0)) { struct.pktable_db = iprot.readString(); struct.setPktable_dbIsSet(true); } if (incoming.get(1)) { struct.pktable_name = iprot.readString(); struct.setPktable_nameIsSet(true); } if (incoming.get(2)) { struct.pkcolumn_name = iprot.readString(); struct.setPkcolumn_nameIsSet(true); } if (incoming.get(3)) { struct.fktable_db = iprot.readString(); struct.setFktable_dbIsSet(true); } if (incoming.get(4)) { struct.fktable_name = iprot.readString(); struct.setFktable_nameIsSet(true); } if (incoming.get(5)) { struct.fkcolumn_name = iprot.readString(); struct.setFkcolumn_nameIsSet(true); } if (incoming.get(6)) { struct.key_seq = iprot.readI32(); struct.setKey_seqIsSet(true); } if (incoming.get(7)) { struct.update_rule = iprot.readI32(); struct.setUpdate_ruleIsSet(true); } if (incoming.get(8)) { struct.delete_rule = iprot.readI32(); struct.setDelete_ruleIsSet(true); } if (incoming.get(9)) { struct.fk_name = iprot.readString(); struct.setFk_nameIsSet(true); } if (incoming.get(10)) { struct.pk_name = iprot.readString(); struct.setPk_nameIsSet(true); } if (incoming.get(11)) { struct.enable_cstr = iprot.readBool(); struct.setEnable_cstrIsSet(true); } if (incoming.get(12)) { struct.validate_cstr = iprot.readBool(); struct.setValidate_cstrIsSet(true); } if (incoming.get(13)) { struct.rely_cstr = iprot.readBool(); struct.setRely_cstrIsSet(true); } if (incoming.get(14)) { struct.catName = iprot.readString(); struct.setCatNameIsSet(true); } } } }
apache-2.0
apereo/cas
api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/model/support/saml/idp/SamlIdPDiscoveryProperties.java
1038
package org.apereo.cas.configuration.model.support.saml.idp; import org.apereo.cas.configuration.model.SpringResourceProperties; import org.apereo.cas.configuration.support.RequiresModule; import com.fasterxml.jackson.annotation.JsonFilter; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import org.springframework.boot.context.properties.NestedConfigurationProperty; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * This is {@link SamlIdPDiscoveryProperties}. * * @author Misagh Moayyed * @since 5.3.0 */ @RequiresModule(name = "cas-server-support-saml-idp-discovery") @Getter @Setter @Accessors(chain = true) @JsonFilter("SamlIdPDiscoveryProperties") public class SamlIdPDiscoveryProperties implements Serializable { private static final long serialVersionUID = 3547093517788229284L; /** * Locate discovery feed json file. */ @NestedConfigurationProperty private List<SpringResourceProperties> resource = new ArrayList<>(0); }
apache-2.0
stoksey69/googleads-java-lib
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201502/cm/ExperimentService.java
2829
package com.google.api.ads.adwords.jaxws.v201502.cm; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.WebEndpoint; import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceException; import javax.xml.ws.WebServiceFeature; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.1 * */ @WebServiceClient(name = "ExperimentService", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201502", wsdlLocation = "https://adwords.google.com/api/adwords/cm/v201502/ExperimentService?wsdl") public class ExperimentService extends Service { private final static URL EXPERIMENTSERVICE_WSDL_LOCATION; private final static WebServiceException EXPERIMENTSERVICE_EXCEPTION; private final static QName EXPERIMENTSERVICE_QNAME = new QName("https://adwords.google.com/api/adwords/cm/v201502", "ExperimentService"); static { URL url = null; WebServiceException e = null; try { url = new URL("https://adwords.google.com/api/adwords/cm/v201502/ExperimentService?wsdl"); } catch (MalformedURLException ex) { e = new WebServiceException(ex); } EXPERIMENTSERVICE_WSDL_LOCATION = url; EXPERIMENTSERVICE_EXCEPTION = e; } public ExperimentService() { super(__getWsdlLocation(), EXPERIMENTSERVICE_QNAME); } public ExperimentService(URL wsdlLocation, QName serviceName) { super(wsdlLocation, serviceName); } /** * * @return * returns ExperimentServiceInterface */ @WebEndpoint(name = "ExperimentServiceInterfacePort") public ExperimentServiceInterface getExperimentServiceInterfacePort() { return super.getPort(new QName("https://adwords.google.com/api/adwords/cm/v201502", "ExperimentServiceInterfacePort"), ExperimentServiceInterface.class); } /** * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. * @return * returns ExperimentServiceInterface */ @WebEndpoint(name = "ExperimentServiceInterfacePort") public ExperimentServiceInterface getExperimentServiceInterfacePort(WebServiceFeature... features) { return super.getPort(new QName("https://adwords.google.com/api/adwords/cm/v201502", "ExperimentServiceInterfacePort"), ExperimentServiceInterface.class, features); } private static URL __getWsdlLocation() { if (EXPERIMENTSERVICE_EXCEPTION!= null) { throw EXPERIMENTSERVICE_EXCEPTION; } return EXPERIMENTSERVICE_WSDL_LOCATION; } }
apache-2.0
medicayun/medicayundicom
dcm4jboss-all/tags/DCM4CHEE_2_14_2_TAGA/dcm4jboss-sar/src/java/org/dcm4chex/archive/xdsi/XDSIService.java
50876
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is part of dcm4che, an implementation of DICOM(TM) in * Java(TM), available at http://sourceforge.net/projects/dcm4che. * * The Initial Developer of the Original Code is * TIANI Medgraph AG. * Portions created by the Initial Developer are Copyright (C) 2003-2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gunter Zeilinger <gunter.zeilinger@tiani.com> * Franz Willer <franz.willer@gwi-ag.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package org.dcm4chex.archive.xdsi; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import javax.activation.DataHandler; import javax.management.MalformedObjectNameException; import javax.management.Notification; import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.RuntimeMBeanException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.AttachmentPart; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import org.apache.log4j.Logger; import org.dcm4che.data.Dataset; import org.dcm4che.data.DcmElement; import org.dcm4che.data.DcmObjectFactory; import org.dcm4che.dict.Tags; import org.dcm4che.dict.UIDs; import org.dcm4che.util.UIDGenerator; import org.dcm4che2.audit.message.AuditEvent; import org.dcm4che2.audit.message.AuditMessage; import org.dcm4che2.audit.message.DataExportMessage; import org.dcm4che2.audit.message.ParticipantObjectDescription; import org.dcm4che2.audit.util.InstanceSorter; import org.dcm4cheri.util.StringUtils; import org.dcm4chex.archive.dcm.ianscu.IANScuService; import org.dcm4chex.archive.ejb.interfaces.ContentManager; import org.dcm4chex.archive.ejb.interfaces.ContentManagerHome; import org.dcm4chex.archive.ejb.interfaces.FileDTO; import org.dcm4chex.archive.ejb.jdbc.QueryFilesCmd; import org.dcm4chex.archive.mbean.AuditLoggerDelegate; import org.dcm4chex.archive.mbean.HttpUserInfo; import org.dcm4chex.archive.util.EJBHomeFactory; import org.dcm4chex.archive.util.FileUtils; import org.jboss.system.ServiceMBeanSupport; import org.jboss.system.server.ServerConfigLocator; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; //import com.sun.xml.messaging.saaj.util.JAXMStreamSource; /** * @author franz.willer@gwi-ag.com * @version $Revision: 8715 $ $Date: 2008-12-12 21:29:49 +0800 (周五, 12 12月 2008) $ * @since Feb 15, 2006 */ public class XDSIService extends ServiceMBeanSupport { private static final String DEFAULT_XDSB_SOURCE_SERVICE = "dcm4chee.xds:service=XDSbSourceService"; public static final String DOCUMENT_ID = "doc_1"; public static final String PDF_DOCUMENT_ID = "pdf_doc_1"; public static final String AUTHOR_SPECIALITY = "authorSpeciality"; public static final String AUTHOR_PERSON = "authorPerson"; public static final String AUTHOR_ROLE = "authorRole"; public static final String AUTHOR_ROLE_DISPLAYNAME = "authorRoleDisplayName"; public static final String AUTHOR_INSTITUTION = "authorInstitution"; public static final String SOURCE_ID = "sourceId"; private static final String NONE = "NONE"; protected AuditLoggerDelegate auditLogger = new AuditLoggerDelegate(this); private ObjectName ianScuServiceName; private ObjectName keyObjectServiceName; private ObjectName xdsbSourceServiceName; private ObjectName xdsHttpCfgServiceName; private Boolean httpCfgServiceAvailable; protected String[] autoPublishAETs; private String autoPublishDocTitle; private static Logger log = Logger.getLogger(XDSIService.class.getName()); private Map usr2author = new TreeMap(); // http attributes to document repository actor (synchron) private String docRepositoryURI; private String docRepositoryAET; // Metadata attributes private File propertyFile; private File docTitleCodeListFile; private File classCodeListFile; private File contentTypeCodeListFile; private File eventCodeListFile; private File healthCareFacilityCodeListFile; private File autoPublishPropertyFile; private List authorRoles = new ArrayList(); private List confidentialityCodes; private Properties metadataProps = new Properties(); private Map mapCodeLists = new HashMap(); private ObjectName pixQueryServiceName; private String sourceID; private String localDomain; private String affinityDomain; private String ridURL; private boolean logSOAPMessage = true; private boolean indentSOAPLog = true; private boolean useXDSb = false; private final NotificationListener ianListener = new NotificationListener() { public void handleNotification(Notification notif, Object handback) { log.info("ianListener called!"); onIAN((Dataset) notif.getUserData()); } }; /** * @return Returns the property file path. */ public String getPropertyFile() { return propertyFile.getPath(); } public void setPropertyFile(String file) throws IOException { if ( file == null || file.trim().length() < 1) return; propertyFile = new File(file.replace('/', File.separatorChar)); try { readPropertyFile(); } catch ( Throwable ignore ) { log.warn("Property file "+file+" cant be read!"); } } public String getDocTitleCodeListFile() { return docTitleCodeListFile == null ? null : docTitleCodeListFile.getPath(); } public void setDocTitleCodeListFile(String file) throws IOException { if ( file == null || file.trim().length() < 1) { docTitleCodeListFile = null; } else { docTitleCodeListFile = new File(file.replace('/', File.separatorChar)); } } public String getClassCodeListFile() { return classCodeListFile == null ? null : classCodeListFile.getPath(); } public void setClassCodeListFile(String file) throws IOException { if ( file == null || file.trim().length() < 1) { classCodeListFile = null; } else { classCodeListFile = new File(file.replace('/', File.separatorChar)); } } public String getContentTypeCodeListFile() { return contentTypeCodeListFile == null ? null : contentTypeCodeListFile.getPath(); } public void setContentTypeCodeListFile(String file) throws IOException { if ( file == null || file.trim().length() < 1) { contentTypeCodeListFile = null; } else { contentTypeCodeListFile = new File(file.replace('/', File.separatorChar)); } } public String getHealthCareFacilityCodeListFile() { return healthCareFacilityCodeListFile == null ? null : healthCareFacilityCodeListFile.getPath(); } public void setHealthCareFacilityCodeListFile(String file) throws IOException { if ( file == null || file.trim().length() < 1) { healthCareFacilityCodeListFile = null; } else { healthCareFacilityCodeListFile = new File(file.replace('/', File.separatorChar)); } } public String getEventCodeListFile() { return eventCodeListFile == null ? null : eventCodeListFile.getPath(); } public void setEventCodeListFile(String file) throws IOException { if ( file == null || file.trim().length() < 1) { eventCodeListFile = null; } else { eventCodeListFile = new File(file.replace('/', File.separatorChar)); } } public String getConfidentialityCodes() { return getListString(confidentialityCodes); } public void setConfidentialityCodes(String codes) throws IOException { confidentialityCodes = setListString( codes );; } /** * @return Returns the authorPerson or a user to authorPerson mapping. */ public String getAuthorPersonMapping() { if ( usr2author.isEmpty() ) { return metadataProps.getProperty(AUTHOR_PERSON); } else { return this.getMappingString(usr2author); } } /** * Set either a fix authorPerson or a mapping user to authorPerson. * <p> * Mapping format: &lt;user&gt;=&lt;authorPerson&gt;<br> * Use either newline or semicolon to seperate mappings. * <p> * If '=' is ommited, a fixed autorPerson is set in <code>metadataProps</code> * * @param s The authorPerson(-mapping) to set. */ public void setAuthorPersonMapping(String s) { if ( s == null || s.trim().length() < 1) return; usr2author.clear(); if ( s.indexOf('=') == -1) { metadataProps.setProperty(AUTHOR_PERSON, s); //NO mapping user -> authorPerson; use fix authorPerson instead } else { this.addMappingString(s, usr2author); } } /** * get the authorPerson value for given user. * * @param user * @return */ public String getAuthorPerson( String user ) { String person = (String)usr2author.get(user); if ( person == null ) { person = metadataProps.getProperty(AUTHOR_PERSON); } return person; } public String getSourceID() { if ( sourceID == null ) sourceID = metadataProps.getProperty(SOURCE_ID); return sourceID; } public void setSourceID(String id) { sourceID = id; if ( sourceID != null ) metadataProps.setProperty(SOURCE_ID, sourceID); } /** * @return Returns a list of authorRoles (with displayName) as String. */ public String getAuthorRoles() { return getListString(authorRoles); } /** * Set authorRoles (with displayName). * <p> * Format: &lt;role&gt;^&lt;displayName&gt;<br> * Use either newline or semicolon to seperate roles. * <p> * @param s The roles to set. */ public void setAuthorRoles(String s) { if ( s == null || s.trim().length() < 1) return; authorRoles = setListString(s); } public Properties joinMetadataProperties(Properties props) { Properties p = new Properties();//we should not change metadataProps! p.putAll(metadataProps); if ( props == null ) p.putAll(props); return p; } // http /** * @return Returns the docRepositoryURI. */ public String getDocRepositoryURI() { return docRepositoryURI; } /** * @param docRepositoryURI The docRepositoryURI to set. */ public void setDocRepositoryURI(String docRepositoryURI) { this.docRepositoryURI = docRepositoryURI; } /** * @return Returns the docRepositoryAET. */ public String getDocRepositoryAET() { return docRepositoryAET == null ? "NONE" : docRepositoryAET; } /** * @param docRepositoryAET The docRepositoryAET to set. */ public void setDocRepositoryAET(String docRepositoryAET) { if ( "NONE".equals(docRepositoryAET)) this.docRepositoryAET = null; else this.docRepositoryAET = docRepositoryAET; } public final ObjectName getAuditLoggerName() { return auditLogger.getAuditLoggerName(); } public final void setAuditLoggerName(ObjectName auditLogName) { this.auditLogger.setAuditLoggerName(auditLogName); } public final ObjectName getPixQueryServiceName() { return pixQueryServiceName; } public final void setPixQueryServiceName(ObjectName name) { this.pixQueryServiceName = name; } public final ObjectName getIANScuServiceName() { return ianScuServiceName; } public final void setIANScuServiceName(ObjectName ianScuServiceName) { this.ianScuServiceName = ianScuServiceName; } public final ObjectName getKeyObjectServiceName() { return keyObjectServiceName; } public final void setKeyObjectServiceName(ObjectName keyObjectServiceName) { this.keyObjectServiceName = keyObjectServiceName; } public String getXdsbSourceServiceName() { return xdsbSourceServiceName == null ? NONE : xdsbSourceServiceName.toString(); } public void setXdsbSourceServiceName(String name) throws MalformedObjectNameException, NullPointerException { this.xdsbSourceServiceName = NONE.equals(name) ? null : ObjectName.getInstance(name); } public String getXdsHttpCfgServiceName() { return xdsHttpCfgServiceName == null ? NONE : xdsHttpCfgServiceName.toString(); } public void setXdsHttpCfgServiceName(String name) throws MalformedObjectNameException, NullPointerException { try { xdsHttpCfgServiceName = NONE.equals(name) ? null : ObjectName.getInstance(name); } finally { //Set available flag to false when ObjectName is not set or null ('unchecked') otherwise because we have //no dependency to the optional configuration service. httpCfgServiceAvailable = xdsHttpCfgServiceName == null ? Boolean.FALSE : null; } } public boolean isHttpCfgServiceAvailable() { if (httpCfgServiceAvailable==null) { if ( xdsHttpCfgServiceName != null ) { if ( server.isRegistered(xdsHttpCfgServiceName) ) { this.httpCfgServiceAvailable = Boolean.TRUE; } else { this.httpCfgServiceAvailable = Boolean.FALSE; } } else { return false; } } return httpCfgServiceAvailable.booleanValue(); } public boolean isUseXDSb() { return useXDSb; } public void setUseXDSb(boolean useXDSb) { if ( this.useXDSb != useXDSb ) { this.useXDSb = useXDSb; if ( useXDSb && xdsbSourceServiceName == null ) { try { setXdsbSourceServiceName(DEFAULT_XDSB_SOURCE_SERVICE); } catch (Exception x) { log.warn("Cant set default XDS.b Service ("+DEFAULT_XDSB_SOURCE_SERVICE+")!",x); } } } } public final String getAutoPublishAETs() { return autoPublishAETs.length > 0 ? StringUtils.toString(autoPublishAETs, '\\') : NONE; } public final void setAutoPublishAETs(String autoPublishAETs) { this.autoPublishAETs = NONE.equalsIgnoreCase(autoPublishAETs) ? new String[0] : StringUtils.split(autoPublishAETs, '\\'); } public final String getAutoPublishDocTitle() { return autoPublishDocTitle; } public final void setAutoPublishDocTitle(String autoPublishDocTitle ) { this.autoPublishDocTitle = autoPublishDocTitle; } public String getAutoPublishPropertyFile() { return autoPublishPropertyFile == null ? "NONE" : autoPublishPropertyFile.getPath(); } public void setAutoPublishPropertyFile(String file) throws IOException { if ( file == null || file.trim().length() < 1 || file.equalsIgnoreCase("NONE")) { autoPublishPropertyFile = null; } else { autoPublishPropertyFile = new File(file.replace('/', File.separatorChar)); } } public String getLocalDomain() { return localDomain == null ? "NONE" : localDomain; } public void setLocalDomain(String domain) { localDomain = ( domain==null || domain.trim().length()<1 || domain.equalsIgnoreCase("NONE") ) ? null : domain; } public String getAffinityDomain() { return affinityDomain; } public void setAffinityDomain(String domain) { affinityDomain = domain; } /** * Adds a 'mappingString' (format:&lt;key&gt;=&lt;value&gt;...) to a map. * * @param s */ private void addMappingString(String s, Map map) { StringTokenizer st = new StringTokenizer( s, ",;\n\r\t "); String t; int pos; while ( st.hasMoreTokens() ) { t = st.nextToken(); pos = t.indexOf('='); if ( pos == -1) { map.put(t,t); } else { map.put(t.substring(0,pos), t.substring(++pos)); } } } /** * Returns the String representation of a map * @return */ private String getMappingString(Map map) { if ( map == null || map.isEmpty() ) return null; StringBuffer sb = new StringBuffer(); String key; for ( Iterator iter = map.keySet().iterator() ; iter.hasNext() ; ) { key = iter.next().toString(); sb.append(key).append('=').append(map.get(key)).append( System.getProperty("line.separator", "\n")); } return sb.toString(); } private List setListString(String s) { List l = new ArrayList(); if ( NONE.equals(s) ) return l; StringTokenizer st = new StringTokenizer( s, ";\n\r"); while ( st.hasMoreTokens() ) { l.add(st.nextToken()); } return l; } private String getListString(List l) { if ( l == null || l.isEmpty() ) return NONE; StringBuffer sb = new StringBuffer(); for ( Iterator iter = l.iterator() ; iter.hasNext() ; ) { sb.append(iter.next()).append( System.getProperty("line.separator", "\n")); } return sb.toString(); } /** * @return Returns the ridURL. */ public String getRidURL() { return ridURL; } /** * @param ridURL The ridURL to set. */ public void setRidURL(String ridURL) { this.ridURL = ridURL; } /** * @return Returns the logSOAPMessage. */ public boolean isLogSOAPMessage() { return logSOAPMessage; } /** * @param logSOAPMessage The logSOAPMessage to set. */ public void setLogSOAPMessage(boolean logSOAPMessage) { this.logSOAPMessage = logSOAPMessage; } public boolean isIndentSOAPLog() { return indentSOAPLog; } public void setIndentSOAPLog(boolean indentSOAPLog) { this.indentSOAPLog = indentSOAPLog; } // Operations /** * @throws IOException */ public void readPropertyFile() throws IOException { File propFile = FileUtils.resolve(this.propertyFile); BufferedInputStream bis= new BufferedInputStream( new FileInputStream( propFile )); try { metadataProps.clear(); metadataProps.load(bis); if ( sourceID != null ) { metadataProps.setProperty(SOURCE_ID, sourceID); } } finally { bis.close(); } } public List listAuthorRoles() throws IOException { return this.authorRoles; } public List listDocTitleCodes() throws IOException { return readCodeFile(docTitleCodeListFile); } public List listEventCodes() throws IOException { return readCodeFile(eventCodeListFile); } public List listClassCodes() throws IOException { return readCodeFile(classCodeListFile); } public List listContentTypeCodes() throws IOException { return readCodeFile(contentTypeCodeListFile); } public List listHealthCareFacilityTypeCodes() throws IOException { return readCodeFile(healthCareFacilityCodeListFile); } public List listConfidentialityCodes() throws IOException { return confidentialityCodes; } /** * @throws IOException * */ public List readCodeFile(File codeFile) throws IOException { if ( codeFile == null ) return new ArrayList(); List l = (List) mapCodeLists.get(codeFile); if ( l == null ) { l = new ArrayList(); File file = FileUtils.resolve(codeFile); if ( file.exists() ) { BufferedReader r = new BufferedReader( new FileReader(file)); String line; while ( (line = r.readLine()) != null ) { if ( ! (line.charAt(0) == '#') ) { l.add( line ); } } log.debug("Codes read from code file "+codeFile); log.debug("Codes:"+l); mapCodeLists.put(codeFile,l); } else { log.warn("Code File "+file+" does not exist! return empty code list!"); } } return l; } public void clearCodeFileCache() { mapCodeLists.clear(); } public boolean sendSOAP( String metaDataFilename, String docNames, String url ) { File metaDataFile = new File( metaDataFilename); XDSIDocument[] docFiles = null; if ( docNames != null && docNames.trim().length() > 0) { StringTokenizer st = new StringTokenizer( docNames, "," ); docFiles = new XDSIDocument[ st.countTokens() ]; for ( int i=0; st.hasMoreTokens(); i++ ) { docFiles[i] = XDSIFileDocument.valueOf( st.nextToken() ); } } return sendSOAP( readXMLFile(metaDataFile), docFiles, url ); } public boolean sendSOAP( Document metaData, XDSIDocument[] docs, String url ) { if ( isUseXDSb() ) { if ( xdsbSourceServiceName != null ) { return exportXDSb(metaData, docs); } else { log.warn("UseXDSb is enabled but XdsbSourceServiceName is not configured! Use XDS.a instead!"); } } if ( url == null ) url = this.docRepositoryURI; log.info("Send 'Provide and Register Document Set' request to "+url); SOAPConnection conn = null; try { configTLS(url); MessageFactory messageFactory = MessageFactory.newInstance(); SOAPMessage message = messageFactory.createMessage(); SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); SOAPBody soapBody = envelope.getBody(); SOAPElement bodyElement = soapBody.addDocument(metaData); if ( docs != null ) { for (int i = 0; i < docs.length; i++) { DataHandler dhAttachment = docs[i].getDataHandler(); AttachmentPart part = message.createAttachmentPart(dhAttachment); part.setMimeHeader("Content-Type", docs[i].getMimeType()); String docId = docs[i].getDocumentID(); if ( docId.charAt(0) != '<' ) {//Wrap with < > docId = "<"+docId+">"; } part.setContentId(docId); if ( log.isDebugEnabled()){ log.debug("Add Attachment Part ("+(i+1)+"/"+docs.length+")! Document ID:"+part.getContentId()+" mime:"+docs[i].getMimeType()); } message.addAttachmentPart(part); } } SOAPConnectionFactory connFactory = SOAPConnectionFactory.newInstance(); conn = connFactory.createConnection(); log.info("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); log.info("send request to "+url); if ( logSOAPMessage ) log.info("-------------------------------- request ----------------------------------"); dumpSOAPMessage(message); SOAPMessage response = conn.call(message, url); if ( ! logSOAPMessage ) log.info("-------------------------------- response ----------------------------------"); dumpSOAPMessage(response); if ( logSOAPMessage ) log.info("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); return checkResponse( response ); } catch ( Throwable x ) { log.error("Cant send SOAP message! Reason:", x); return false; } finally { if ( conn != null ) try { conn.close(); } catch (SOAPException ignore) {} } } private void configTLS(String url) { if ( isHttpCfgServiceAvailable() ) { try { server.invoke(xdsHttpCfgServiceName, "configTLS", new Object[] { url }, new String[] { String.class.getName() } ); } catch ( Exception x ) { log.error( "Exception occured in configTLS: "+x.getMessage(), x ); } } } private boolean exportXDSb(Document metaData, XDSIDocument[] docs) { log.info("export Document(s) as XDS.b Document Source!"); Node rsp = null; try { Map mapDocs = new HashMap(); if ( docs != null) { for ( int i = 0 ; i < docs.length ; i++) { mapDocs.put(docs[i].getDocumentID(), docs[i].getDataHandler() ); } } log.info("call xds.b exportDocuments"); rsp = (Node) server.invoke(this.xdsbSourceServiceName, "exportDocuments", new Object[] { metaData, mapDocs }, new String[] { Node.class.getName(), Map.class.getName() }); log.info("response from xds.b exportDocuments:"+rsp); return checkResponse(rsp.getFirstChild()); } catch (Exception x) { log.error("Export Documents failed via XDS.b transaction",x); return false; } } public static String resolvePath(String fn) { File f = new File(fn); if (f.isAbsolute()) return f.getAbsolutePath(); File serverHomeDir = ServerConfigLocator.locate().getServerHomeDir(); return new File(serverHomeDir, f.getPath()).getAbsolutePath(); } public boolean sendSOAP(String kosIuid, Properties mdProps) throws SQLException { Dataset kos = queryInstance( kosIuid ); if ( kos == null ) return false; if ( mdProps == null ) mdProps = this.metadataProps; List files = new QueryFilesCmd(kosIuid).getFileDTOs(); if ( files == null || files.size() == 0 ) { return false; } FileDTO fileDTO = (FileDTO) files.iterator().next(); File file = FileUtils.toFile(fileDTO.getDirectoryPath(), fileDTO.getFilePath()); XDSIDocument[] docs = new XDSIFileDocument[] {new XDSIFileDocument(file,"application/dicom",DOCUMENT_ID,kosIuid)}; XDSMetadata md = new XDSMetadata(kos, mdProps, docs); Document metadata = md.getMetadata(); return sendSOAP(metadata, docs, null); } private Dataset queryInstance(String iuid) { try { return getContentManager().getInstanceInfo(iuid, true); } catch (Exception e) { log.error("Query for SOP Instance UID:" + iuid + " failed!", e); } return null; } public boolean sendSOAP(String kosIuid) throws SQLException { Dataset kos = queryInstance( kosIuid ); return sendSOAP(kos,null); } public boolean sendSOAP(Dataset kos, Properties mdProps) throws SQLException { if ( log.isDebugEnabled()) { log.debug("Key Selection Object:");log.debug(kos); } if ( kos == null ) return false; if ( mdProps == null ) mdProps = this.metadataProps; String user = mdProps.getProperty("user"); mdProps.setProperty("xadPatientID", getAffinityDomainPatientID(kos)); XDSIDocument[] docs; String pdfIUID = mdProps.getProperty("pdf_iuid"); if ( pdfIUID == null || !UIDs.isValid(pdfIUID) ) { docs = new XDSIDocument[]{ new XDSIDatasetDocument(kos,"application/dicom",DOCUMENT_ID)}; } else { String pdfUID = UIDGenerator.getInstance().createUID(); log.info("Add PDF document with IUID "+pdfIUID+" to this submission set!"); try { docs = new XDSIDocument[]{ new XDSIDatasetDocument(kos,"application/dicom",DOCUMENT_ID), new XDSIURLDocument(new URL(ridURL+pdfIUID),"application/pdf",PDF_DOCUMENT_ID,pdfUID)}; } catch (Exception x) { log.error("Cant attach PDF document! :"+x.getMessage(), x); return false; } } addAssociations(docs, mdProps); XDSMetadata md = new XDSMetadata(kos, mdProps, docs); Document metadata = md.getMetadata(); boolean b = sendSOAP(metadata, docs , null); logExport(kos, user, b); if ( b ) { logIHEYr4Export( kos.getString(Tags.PatientID), kos.getString(Tags.PatientName), this.getDocRepositoryURI(), docRepositoryAET, getSUIDs(kos)); } return b; } private void addAssociations(XDSIDocument[] docs, Properties mdProps) { if ( mdProps.getProperty("nrOfAssociations") == null) return; int len = Integer.parseInt(mdProps.getProperty("nrOfAssociations")); String assoc, uuid, type, status; StringTokenizer st; for ( int i=0; i < len ; i++ ) { assoc = mdProps.getProperty("association_"+i); st = new StringTokenizer(assoc,"|"); uuid = st.nextToken(); type = st.nextToken(); status = st.nextToken(); for ( int j = 0 ; j < docs.length ; j++) { docs[j].addAssociation(uuid, type, status); } } } public boolean exportPDF(String iuid) throws SQLException, MalformedURLException { return exportPDF(iuid,null); } public boolean exportPDF(String iuid, Properties mdProps) throws SQLException, MalformedURLException { log.debug("export PDF to XDS Instance UID:"+iuid); Dataset ds = queryInstance(iuid); if ( ds == null ) return false; String pdfUID = UIDGenerator.getInstance().createUID(); log.info("Document UID of exported PDF:"+pdfUID); ds.putUI(Tags.SOPInstanceUID,pdfUID); if ( mdProps == null ) mdProps = this.metadataProps; String user = mdProps.getProperty("user"); mdProps.setProperty("mimetype", "application/pdf"); mdProps.setProperty("xadPatientID", getAffinityDomainPatientID(ds)); XDSIDocument[] docs = new XDSIURLDocument[] {new XDSIURLDocument(new URL(ridURL+iuid),"application/pdf",PDF_DOCUMENT_ID,pdfUID)}; addAssociations(docs, mdProps); XDSMetadata md = new XDSMetadata(ds, mdProps, docs); Document metadata = md.getMetadata(); boolean b = sendSOAP(metadata,docs , null); logExport(ds, user, b); if ( b ) { logIHEYr4Export( ds.getString(Tags.PatientID), ds.getString(Tags.PatientName), this.getDocRepositoryURI(), docRepositoryAET, getSUIDs(ds)); } return b; } public boolean createFolder( Properties mdProps ) { String patDsIUID = mdProps.getProperty("folder.patDatasetIUID"); Dataset ds = queryInstance(patDsIUID); log.info("create XDS Folder for patient:"+ds.getString(Tags.PatientID)); mdProps.setProperty("xadPatientID", getAffinityDomainPatientID(ds)); log.info("XAD patient:"+mdProps.getProperty("xadPatientID")); XDSMetadata md = new XDSMetadata(null, mdProps, null); Document metadata = md.getMetadata(); boolean b = sendSOAP(metadata, null , null); return b; } /** * @param kos * @return */ private Set getSUIDs(Dataset kos) { Set suids = null; DcmElement sq = kos.get(Tags.CurrentRequestedProcedureEvidenceSeq); if ( sq != null ) { suids = new LinkedHashSet(); for ( int i = 0,len=sq.countItems() ; i < len ; i++ ) { suids.add(sq.getItem(i).getString(Tags.StudyInstanceUID)); } } return suids; } private void logIHEYr4Export(String patId, String patName, String node, String aet, Set suids) { if (!auditLogger.isAuditLogIHEYr4()) return; try { URL url = new URL(node); InetAddress inet = InetAddress.getByName(url.getHost()); server.invoke(auditLogger.getAuditLoggerName(), "logExport", new Object[] { patId, patName, "XDSI Export", suids, inet.getHostAddress(), inet.getHostName(), aet}, new String[] { String.class.getName(), String.class.getName(), String.class.getName(), Set.class.getName(), String.class.getName(), String.class.getName(), String.class.getName()}); /*_*/ } catch (Exception e) { log.warn("Audit Log failed:", e); } } private void logExport(Dataset dsKos, String user, boolean success) { String requestHost = null; HttpUserInfo userInfo = new HttpUserInfo(AuditMessage.isEnableDNSLookups()); user = userInfo.getUserId(); requestHost = userInfo.getHostName(); DataExportMessage msg = new DataExportMessage(); msg.setOutcomeIndicator(success ? AuditEvent.OutcomeIndicator.SUCCESS: AuditEvent.OutcomeIndicator.MINOR_FAILURE); msg.addExporterProcess(AuditMessage.getProcessID(), AuditMessage.getLocalAETitles(), AuditMessage.getProcessName(), user == null, AuditMessage.getLocalHostName()); if (user != null) { msg.addExporterPerson(user, null, null, true, requestHost); } String host = "unknown"; try { host = new URL(docRepositoryURI).getHost(); } catch (MalformedURLException ignore) { } msg.addDestinationMedia(docRepositoryURI, null, "XDS-I Export", false, host ); msg.addPatient(dsKos.getString(Tags.PatientID), dsKos.getString(Tags.PatientName)); InstanceSorter sorter = getInstanceSorter(dsKos); for (String suid : sorter.getSUIDs()) { ParticipantObjectDescription desc = new ParticipantObjectDescription(); for (String cuid : sorter.getCUIDs(suid)) { ParticipantObjectDescription.SOPClass sopClass = new ParticipantObjectDescription.SOPClass(cuid); sopClass.setNumberOfInstances( sorter.countInstances(suid, cuid)); desc.addSOPClass(sopClass); } msg.addStudy(suid, desc); } msg.validate(); Logger.getLogger("auditlog").info(msg); } private InstanceSorter getInstanceSorter(Dataset dsKos) { InstanceSorter sorter = new InstanceSorter(); DcmObjectFactory df = DcmObjectFactory.getInstance(); DcmElement sq = dsKos.get(Tags.CurrentRequestedProcedureEvidenceSeq); if ( sq != null ) { for (int i = 0, n = sq.countItems(); i < n; i++) { Dataset refStudyItem = sq.getItem(i); String suid = refStudyItem.getString(Tags.StudyInstanceUID); DcmElement refSerSeq = refStudyItem.get(Tags.RefSeriesSeq); for (int j = 0, m = refSerSeq.countItems(); j < m; j++) { Dataset refSer = refSerSeq.getItem(j); DcmElement srcRefSOPSeq = refSer.get(Tags.RefSOPSeq); for (int k = 0, l = srcRefSOPSeq.countItems(); k < l; k++) { Dataset srcRefSOP = srcRefSOPSeq.getItem(k); Dataset refSOP = df.newDataset(); String cuid = srcRefSOP.getString(Tags.RefSOPClassUID); refSOP.putUI(Tags.RefSOPClassUID, cuid); String iuid = srcRefSOP.getString(Tags.RefSOPInstanceUID); refSOP.putUI(Tags.RefSOPInstanceUID, iuid); sorter.addInstance(suid, cuid, iuid, null); } } } } else { //not a manifest! (PDF) sorter.addInstance(dsKos.getString(Tags.StudyInstanceUID), dsKos.getString(Tags.SOPClassUID), dsKos.getString(Tags.SOPInstanceUID), null); } return sorter; } /** * @param kos * @return */ public String getAffinityDomainPatientID(Dataset kos) { String patID = kos.getString(Tags.PatientID); String issuer = kos.getString(Tags.IssuerOfPatientID); if ( affinityDomain.charAt(0) == '=') { if ( affinityDomain.length() == 1 ) { patID+="^^^"; if ( issuer == null ) return patID; return patID+issuer; } else if (affinityDomain.charAt(1)=='?') { log.info("PIX Query disabled: replace issuer with affinity domain! "); log.debug("patID changed! ("+patID+"^^^"+issuer+" -> "+patID+"^^^"+affinityDomain.substring(2)+")"); return patID+"^^^"+affinityDomain.substring(2); } else { log.info("PIX Query disabled: replace configured patient ID! :"+affinityDomain.substring(1)); return affinityDomain.substring(1); } } if ( this.pixQueryServiceName == null ) { log.info("PIX Query disabled: use source patient ID!"); patID+="^^^"; if ( issuer == null ) return patID; return patID+issuer; } else { try { if ( localDomain != null ) { if ( localDomain.charAt(0) == '=') { String oldIssuer = issuer; issuer = localDomain.substring(1); log.info("PIX Query: Local affinity domain changed from "+oldIssuer+" to "+issuer); } else if ( issuer == null ) { log.info("PIX Query: Unknown local affinity domain changed to "+issuer); issuer = localDomain; } } else if ( issuer == null ) { issuer = ""; } List pids = (List) server.invoke(this.pixQueryServiceName, "queryCorrespondingPIDs", new Object[] { patID, issuer, new String[]{affinityDomain} }, new String[] { String.class.getName(), String.class.getName(), String[].class.getName() }); String pid, affPid; for ( Iterator iter = pids.iterator() ; iter.hasNext() ; ) { pid = toPIDString((String[]) iter.next()); log.debug("Check if from domain! PatientID:"+pid); if ( (affPid = isFromDomain(pid)) != null ) { log.debug("found domain patientID:"+affPid); return affPid; } } log.error("Patient ID is not known in Affinity domain:"+affinityDomain); return null; } catch (Exception e) { log.error("Failed to get patientID for Affinity Domain:", e); return null; } } } /** * @param pid * @return */ private String isFromDomain(String pid) { int pos = 0; for ( int i = 0 ; i < 3 ; i++) { pos = pid.indexOf('^', pos); if ( pos == -1 ) { log.warn("patient id does not contain domain (issuer)! :"+pid); return null; } pos++; } String s = pid.substring(pos); if ( !s.endsWith(this.affinityDomain) ) return null; if (s.length() == affinityDomain.length()) return pid; return pid.substring(0,pos)+affinityDomain; } private String toPIDString(String[] pid) { if (pid == null || pid.length < 1) return ""; StringBuffer sb = new StringBuffer(pid[0]); log.debug("pid[0]:"+pid[0]); if ( pid.length > 1 ) { sb.append("^^^").append(pid[1]); log.debug("pid[1]:"+pid[1]); } for (int i = 2 ; i < pid.length; i++) { sb.append('&').append(pid[i]); log.debug("pid["+i+"]:"+pid[i]); } return sb.toString(); } /** * @param response * @return * @throws SOAPException */ private boolean checkResponse(Node n) throws SOAPException { log.info("checkResponse node:"+n.getLocalName()+" in NS:"+n.getNamespaceURI()); String status = n.getAttributes().getNamedItem("status").getNodeValue(); log.info("XDSI: SOAP response status."+status); if ("Success".equals(status)) { return true; } else { StringBuffer sb = new StringBuffer(); try { NodeList errList = n.getChildNodes().item(0).getChildNodes(); Node errNode; for ( int j = 0, lenj = errList.getLength() ; j < lenj ; j++ ) { sb.setLength(0); sb.append("Error (").append(j).append("):"); if ( (errNode = errList.item(j)) != null && errNode.getFirstChild() != null ) { sb.append( errNode.getFirstChild().getNodeValue()); } log.info(sb.toString()); } } catch (Exception ignoreMissingErrorList){} return false; } } private boolean checkResponse(SOAPMessage response) throws SOAPException { log.info("checkResponse:"+response); try { SOAPBody body = response.getSOAPBody(); log.debug("SOAPBody:"+body ); NodeList nl = body.getChildNodes(); if ( nl.getLength() > 0 ) { for ( int i = 0, len = nl.getLength() ; i < len ; i++ ) { Node n = nl.item(i); if ( n.getNodeType() == Node.ELEMENT_NODE && "RegistryResponse".equals(n.getLocalName() ) ) { return checkResponse(n); } } } else { log.warn("XDSI: Empty SOAP response!"); } } catch ( Exception x ) { log.error("Cant check response!", x); } return false; } /** * @param message * @return * @throws IOException * @throws SOAPException * @throws SAXException * @throws ParserConfigurationException */ private void dumpSOAPMessage(SOAPMessage message) throws SOAPException, IOException, ParserConfigurationException, SAXException { if ( ! logSOAPMessage ) return; Source s = message.getSOAPPart().getContent(); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); out.write("SOAP message:".getBytes()); Transformer t = TransformerFactory.newInstance().newTransformer(); if (indentSOAPLog) t.setOutputProperty("indent", "yes"); t.transform(s, new StreamResult(out)); log.info(out.toString()); } catch (Exception e) { log.warn("Failed to log SOAP message", e); } } private Document readXMLFile(File xmlFile){ Document document = null; DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); try { dbFactory.setNamespaceAware(true); DocumentBuilder builder = dbFactory.newDocumentBuilder(); document = builder.parse(xmlFile); } catch (Exception x) { log.error("Cant read xml file:"+xmlFile, x); } return document; } protected void startService() throws Exception { server.addNotificationListener(ianScuServiceName, ianListener, IANScuService.NOTIF_FILTER, null); } protected void stopService() throws Exception { server.removeNotificationListener(ianScuServiceName, ianListener, IANScuService.NOTIF_FILTER, null); } private void onIAN(Dataset mpps) { log.debug("Received mpps");log.debug(mpps); if (Arrays.asList(autoPublishAETs).indexOf( mpps.getString(Tags.PerformedStationAET)) != -1) { List iuids = getIUIDS(mpps); log.debug("iuids:"+iuids); Dataset manifest = getKeyObject(iuids, getAutoPublishRootInfo(mpps), null); log.debug("Created manifest KOS:"); log.debug(manifest); try { sendSOAP(manifest, getAutoPublishMetadataProperties(mpps)); } catch (SQLException x) { log.error("XDS-I Autopublish failed! Reason:",x ); } return; } // TODO } private List getIUIDS(Dataset mpps) { List l = new ArrayList(); DcmElement refSerSQ = mpps.get(Tags.PerformedSeriesSeq); if ( refSerSQ != null ) { Dataset item; DcmElement refSopSQ; for ( int i = 0 ,len = refSerSQ.countItems() ; i < len ; i++){ refSopSQ = refSerSQ.getItem(i).get(Tags.RefImageSeq); for ( int j = 0 ,len1 = refSerSQ.countItems() ; j < len1 ; j++){ item = refSopSQ.getItem(j); l.add( item.getString(Tags.RefSOPInstanceUID)); } } } return l; } private Dataset getAutoPublishRootInfo(Dataset mpps) { Dataset rootInfo = DcmObjectFactory.getInstance().newDataset(); DcmElement sq = rootInfo.putSQ(Tags.ConceptNameCodeSeq); Dataset item = sq.addNewItem(); StringTokenizer st = new StringTokenizer(autoPublishDocTitle,"^"); item.putSH(Tags.CodeValue,st.hasMoreTokens() ? st.nextToken():"autoPublish"); item.putLO(Tags.CodeMeaning, st.hasMoreTokens() ? st.nextToken():"default doctitle for autopublish"); item.putSH(Tags.CodingSchemeDesignator,st.hasMoreTokens() ? st.nextToken():null); return rootInfo; } private Properties getAutoPublishMetadataProperties(Dataset mpps) { Properties props = new Properties(); BufferedInputStream bis = null; try { if (autoPublishPropertyFile == null ) return props; File propFile = FileUtils.resolve(this.autoPublishPropertyFile); bis= new BufferedInputStream( new FileInputStream( propFile )); props.load(bis); if ( sourceID != null ) { props.setProperty(SOURCE_ID, sourceID); } } catch (IOException x) { log.error("Cant read Metadata Properties for AutoPublish!",x); } finally { if (bis != null) { try { bis.close(); } catch (IOException ignore) {} } } return props; } private Dataset getKeyObject(Collection iuids, Dataset rootInfo, List contentItems) { Object o = null; try { o = server.invoke(keyObjectServiceName, "getKeyObject", new Object[] { iuids, rootInfo, contentItems }, new String[] { Collection.class.getName(), Dataset.class.getName(), Collection.class.getName() }); } catch (RuntimeMBeanException x) { log.warn("RuntimeException thrown in KeyObject Service:"+x.getCause()); throw new IllegalArgumentException(x.getCause().getMessage()); } catch (Exception e) { log.warn("Failed to create Key Object:", e); throw new IllegalArgumentException("Error: KeyObject Service cant create manifest Key Object! Reason:"+e.getClass().getName()); } return (Dataset) o; } private ContentManager getContentManager() throws Exception { ContentManagerHome home = (ContentManagerHome) EJBHomeFactory.getFactory() .lookup(ContentManagerHome.class, ContentManagerHome.JNDI_NAME); return home.create(); } }
apache-2.0
emre-aydin/hazelcast
hazelcast/src/main/java/com/hazelcast/client/impl/protocol/task/cache/CacheRemoveAllKeysMessageTask.java
3582
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.client.impl.protocol.task.cache; import com.hazelcast.cache.impl.CacheClearResponse; import com.hazelcast.cache.impl.CacheOperationProvider; import com.hazelcast.cache.impl.operation.CacheRemoveAllOperationFactory; import com.hazelcast.client.impl.protocol.ClientMessage; import com.hazelcast.client.impl.protocol.codec.CacheRemoveAllKeysCodec; import com.hazelcast.instance.impl.Node; import com.hazelcast.internal.nio.Connection; import com.hazelcast.internal.serialization.Data; import com.hazelcast.security.permission.ActionConstants; import com.hazelcast.security.permission.CachePermission; import com.hazelcast.spi.impl.operationservice.OperationFactory; import javax.cache.CacheException; import java.security.Permission; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * This client request specifically calls {@link CacheRemoveAllOperationFactory} on the server side. * * @see CacheRemoveAllOperationFactory */ public class CacheRemoveAllKeysMessageTask extends AbstractCacheAllPartitionsTask<CacheRemoveAllKeysCodec.RequestParameters> { public CacheRemoveAllKeysMessageTask(ClientMessage clientMessage, Node node, Connection connection) { super(clientMessage, node, connection); } @Override protected CacheRemoveAllKeysCodec.RequestParameters decodeClientMessage(ClientMessage clientMessage) { return CacheRemoveAllKeysCodec.decodeRequest(clientMessage); } @Override protected ClientMessage encodeResponse(Object response) { return CacheRemoveAllKeysCodec.encodeResponse(); } @Override protected OperationFactory createOperationFactory() { CacheOperationProvider operationProvider = getOperationProvider(parameters.name); Set<Data> keys = new HashSet<Data>(parameters.keys); return operationProvider.createRemoveAllOperationFactory(keys, parameters.completionId); } @Override protected ClientMessage reduce(Map<Integer, Object> map) { for (Map.Entry<Integer, Object> entry : map.entrySet()) { if (entry.getValue() == null) { continue; } final CacheClearResponse cacheClearResponse = (CacheClearResponse) nodeEngine.toObject(entry.getValue()); final Object response = cacheClearResponse.getResponse(); if (response instanceof CacheException) { throw (CacheException) response; } } return null; } @Override public Permission getRequiredPermission() { return new CachePermission(parameters.name, ActionConstants.ACTION_REMOVE); } @Override public String getDistributedObjectName() { return parameters.name; } @Override public Object[] getParameters() { return new Object[]{parameters.keys}; } @Override public String getMethodName() { return "removeAll"; } }
apache-2.0
ThiagoGarciaAlves/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/GithubApiUtil.java
26170
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.github.api; import com.google.gson.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.util.containers.ContainerUtil; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.message.BasicHeader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.io.mandatory.NullCheckingFactory; import org.jetbrains.plugins.github.api.GithubConnection.ArrayPagedRequest; import org.jetbrains.plugins.github.api.GithubConnection.PagedRequest; import org.jetbrains.plugins.github.api.data.*; import org.jetbrains.plugins.github.api.requests.*; import org.jetbrains.plugins.github.exceptions.GithubAuthenticationException; import org.jetbrains.plugins.github.exceptions.GithubConfusingException; import org.jetbrains.plugins.github.exceptions.GithubJsonException; import org.jetbrains.plugins.github.exceptions.GithubStatusCodeException; import org.jetbrains.plugins.github.util.GithubUtil; import java.io.IOException; import java.net.URLEncoder; import java.util.*; public class GithubApiUtil { private static final Logger LOG = GithubUtil.LOG; public static final String DEFAULT_GITHUB_HOST = "github.com"; private static final String PER_PAGE = "per_page=100"; private static final Header ACCEPT_V3_JSON_HTML_MARKUP = new BasicHeader("Accept", "application/vnd.github.v3.html+json"); private static final Header ACCEPT_V3_JSON = new BasicHeader("Accept", "application/vnd.github.v3+json"); @NotNull private static final Gson gson = initGson(); private static Gson initGson() { GsonBuilder builder = new GsonBuilder(); builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); builder.registerTypeAdapterFactory(NullCheckingFactory.INSTANCE); return builder.create(); } @NotNull public static <T> T fromJson(@Nullable JsonElement json, @NotNull Class<T> classT) throws IOException { if (json == null) { throw new GithubJsonException("Unexpected empty response"); } try { T res = gson.fromJson(json, classT); if (res == null) throw new GithubJsonException("Empty Json response"); return res; } catch (ClassCastException | JsonParseException e) { throw new GithubJsonException("Parse exception while converting JSON to object " + classT.toString(), e); } } @NotNull private static <T> List<T> loadAll(@NotNull GithubConnection connection, @NotNull String path, @NotNull Class<? extends T[]> type, @NotNull Header... headers) throws IOException { PagedRequest<T> request = new ArrayPagedRequest<>(path, type, headers); return request.getAll(connection); } @NotNull private static <T> T load(@NotNull GithubConnection connection, @NotNull String path, @NotNull Class<? extends T> type, @NotNull Header... headers) throws IOException { JsonElement result = connection.getRequest(path, headers); return fromJson(result, type); } @NotNull private static <T> T post(@NotNull GithubConnection connection, @NotNull String path, @NotNull Object request, @NotNull Class<? extends T> type, @NotNull Header... headers) throws IOException { JsonElement result = connection.postRequest(path, gson.toJson(request), headers); return fromJson(result, type); } /* * Operations */ public static void askForTwoFactorCodeSMS(@NotNull GithubConnection connection) { try { connection.postRequest("/authorizations", null, ACCEPT_V3_JSON); } catch (IOException e) { LOG.info(e); } } @NotNull public static Collection<String> getTokenScopes(@NotNull GithubConnection connection) throws IOException { Header[] headers = connection.headRequest("/user", ACCEPT_V3_JSON); Header scopesHeader = null; for (Header header : headers) { if (header.getName().equals("X-OAuth-Scopes")) { scopesHeader = header; break; } } if (scopesHeader == null) { throw new GithubConfusingException("No scopes header"); } Collection<String> scopes = new ArrayList<>(); for (HeaderElement elem : scopesHeader.getElements()) { scopes.add(elem.getName()); } return scopes; } @NotNull public static String getScopedToken(@NotNull GithubConnection connection, @NotNull Collection<String> scopes, @NotNull String note) throws IOException { try { return getNewScopedToken(connection, scopes, note).getToken(); } catch (GithubStatusCodeException e) { if (e.getError() != null && e.getError().containsErrorCode("already_exists")) { // with new API we can't reuse old token, so let's just create new one // we need to change note as well, because it should be unique List<GithubAuthorization> tokens = getAllTokens(connection); for (int i = 1; i < 100; i++) { final String newNote = note + "_" + i; if (!ContainerUtil.exists(tokens, authorization -> newNote.equals(authorization.getNote()))) { return getNewScopedToken(connection, scopes, newNote).getToken(); } } } throw e; } } @NotNull private static GithubAuthorization updateTokenScopes(@NotNull GithubConnection connection, @NotNull GithubAuthorization token, @NotNull Collection<String> scopes) throws IOException { try { String path = "/authorizations/" + token.getId(); GithubAuthorizationUpdateRequest request = new GithubAuthorizationUpdateRequest(new ArrayList<>(scopes)); return fromJson(connection.patchRequest(path, gson.toJson(request), ACCEPT_V3_JSON), GithubAuthorization.class); } catch (GithubConfusingException e) { e.setDetails("Can't update token: scopes - " + scopes); throw e; } } @NotNull private static GithubAuthorization getNewScopedToken(@NotNull GithubConnection connection, @NotNull Collection<String> scopes, @NotNull String note) throws IOException { try { String path = "/authorizations"; GithubAuthorizationCreateRequest request = new GithubAuthorizationCreateRequest(new ArrayList<>(scopes), note, null); return post(connection, path, request, GithubAuthorization.class, ACCEPT_V3_JSON); } catch (GithubConfusingException e) { e.setDetails("Can't create token: scopes - " + scopes + " - note " + note); throw e; } } @NotNull private static List<GithubAuthorization> getAllTokens(@NotNull GithubConnection connection) throws IOException { try { String path = "/authorizations"; return loadAll(connection, path, GithubAuthorization[].class, ACCEPT_V3_JSON); } catch (GithubConfusingException e) { e.setDetails("Can't get available tokens"); throw e; } } @NotNull public static String getMasterToken(@NotNull GithubConnection connection, @NotNull String note) throws IOException { // "repo" - read/write access to public/private repositories // "gist" - create/delete gists List<String> scopes = Arrays.asList("repo", "gist"); return getScopedToken(connection, scopes, note); } @NotNull public static String getTasksToken(@NotNull GithubConnection connection, @NotNull String user, @NotNull String repo, @NotNull String note) throws IOException { GithubRepo repository = getDetailedRepoInfo(connection, user, repo); List<String> scopes = repository.isPrivate() ? Collections.singletonList("repo") : Collections.singletonList("public_repo"); return getScopedToken(connection, scopes, note); } @NotNull public static GithubUserDetailed getCurrentUser(@NotNull GithubConnection connection) throws IOException { try { return load(connection, "/user", GithubUserDetailed.class, ACCEPT_V3_JSON); } catch (GithubConfusingException e) { e.setDetails("Can't get user info"); throw e; } } @NotNull public static List<GithubRepo> getUserRepos(@NotNull GithubConnection connection) throws IOException { return getUserRepos(connection, false); } @NotNull public static List<GithubRepo> getUserRepos(@NotNull GithubConnection connection, boolean allAssociated) throws IOException { try { String type = allAssociated ? "" : "type=owner&"; String path = "/user/repos?" + type + PER_PAGE; return loadAll(connection, path, GithubRepo[].class, ACCEPT_V3_JSON); } catch (GithubConfusingException e) { e.setDetails("Can't get user repositories"); throw e; } } @NotNull public static List<GithubRepo> getUserRepos(@NotNull GithubConnection connection, @NotNull String user) throws IOException { try { String path = "/users/" + user + "/repos?type=owner&" + PER_PAGE; return loadAll(connection, path, GithubRepo[].class, ACCEPT_V3_JSON); } catch (GithubConfusingException e) { e.setDetails("Can't get user repositories: " + user); throw e; } } @NotNull public static List<GithubRepo> getAvailableRepos(@NotNull GithubConnection connection) throws IOException { try { List<GithubRepo> repos = new ArrayList<>(getUserRepos(connection, true)); // We already can return something useful from getUserRepos, so let's ignore errors. // One of this may not exist in GitHub enterprise try { repos.addAll(getWatchedRepos(connection)); } catch (GithubAuthenticationException | GithubStatusCodeException ignore) { } return repos; } catch (GithubConfusingException e) { e.setDetails("Can't get available repositories"); throw e; } } @NotNull private static List<GithubRepo> getWatchedRepos(@NotNull GithubConnection connection) throws IOException { String pathWatched = "/user/subscriptions?" + PER_PAGE; return loadAll(connection, pathWatched, GithubRepo[].class, ACCEPT_V3_JSON); } @NotNull public static GithubRepoDetailed getDetailedRepoInfo(@NotNull GithubConnection connection, @NotNull String owner, @NotNull String name) throws IOException { try { final String request = "/repos/" + owner + "/" + name; return load(connection, request, GithubRepoDetailed.class, ACCEPT_V3_JSON); } catch (GithubConfusingException e) { e.setDetails("Can't get repository info: " + owner + "/" + name); throw e; } } public static void deleteGithubRepository(@NotNull GithubConnection connection, @NotNull String username, @NotNull String repo) throws IOException { try { String path = "/repos/" + username + "/" + repo; connection.deleteRequest(path); } catch (GithubConfusingException e) { e.setDetails("Can't delete repository: " + username + "/" + repo); throw e; } } public static void deleteGist(@NotNull GithubConnection connection, @NotNull String id) throws IOException { try { String path = "/gists/" + id; connection.deleteRequest(path); } catch (GithubConfusingException e) { e.setDetails("Can't delete gist: id - " + id); throw e; } } @NotNull public static GithubGist getGist(@NotNull GithubConnection connection, @NotNull String id) throws IOException { try { String path = "/gists/" + id; return load(connection, path, GithubGist.class, ACCEPT_V3_JSON); } catch (GithubConfusingException e) { e.setDetails("Can't get gist info: id " + id); throw e; } } @NotNull public static GithubGist createGist(@NotNull GithubConnection connection, @NotNull List<GithubGistRequest.FileContent> contents, @NotNull String description, boolean isPublic) throws IOException { try { GithubGistRequest request = new GithubGistRequest(contents, description, isPublic); return post(connection, "/gists", request, GithubGist.class, ACCEPT_V3_JSON); } catch (GithubConfusingException e) { e.setDetails("Can't create gist"); throw e; } } @NotNull public static List<GithubRepo> getForks(@NotNull GithubConnection connection, @NotNull String owner, @NotNull String name) throws IOException { String path = "/repos/" + owner + "/" + name + "/forks?" + PER_PAGE; return loadAll(connection, path, GithubRepo[].class, ACCEPT_V3_JSON); } @NotNull public static GithubPullRequest createPullRequest(@NotNull GithubConnection connection, @NotNull String user, @NotNull String repo, @NotNull String title, @NotNull String description, @NotNull String head, @NotNull String base) throws IOException { try { String path = "/repos/" + user + "/" + repo + "/pulls"; GithubPullRequestRequest request = new GithubPullRequestRequest(title, description, head, base); return post(connection, path, request, GithubPullRequest.class, ACCEPT_V3_JSON); } catch (GithubConfusingException e) { e.setDetails("Can't create pull request"); throw e; } } @NotNull public static GithubRepo createRepo(@NotNull GithubConnection connection, @NotNull String name, @NotNull String description, boolean isPrivate) throws IOException { try { String path = "/user/repos"; GithubRepoRequest request = new GithubRepoRequest(name, description, isPrivate); return post(connection, path, request, GithubRepo.class, ACCEPT_V3_JSON); } catch (GithubConfusingException e) { e.setDetails("Can't create repository: " + name); throw e; } } /* * Open issues only */ @NotNull public static List<GithubIssue> getIssuesAssigned(@NotNull GithubConnection connection, @NotNull String user, @NotNull String repo, @Nullable String assigned, int max, boolean withClosed) throws IOException { try { String state = "state=" + (withClosed ? "all" : "open"); String path; if (StringUtil.isEmptyOrSpaces(assigned)) { path = "/repos/" + user + "/" + repo + "/issues?" + PER_PAGE + "&" + state; } else { path = "/repos/" + user + "/" + repo + "/issues?assignee=" + assigned + "&" + PER_PAGE + "&" + state; } PagedRequest<GithubIssue> request = new ArrayPagedRequest<>(path, GithubIssue[].class, ACCEPT_V3_JSON); List<GithubIssue> result = new ArrayList<>(); while (request.hasNext() && max > result.size()) { result.addAll(request.next(connection)); } return result; } catch (GithubConfusingException e) { e.setDetails("Can't get assigned issues: " + user + "/" + repo + " - " + assigned); throw e; } } @NotNull public static List<GithubIssue> getIssuesQueried(@NotNull GithubConnection connection, @NotNull String user, @NotNull String repo, @Nullable String assignedUser, @Nullable String query, boolean withClosed) throws IOException { try { String state = withClosed ? "" : " state:open"; String assignee = StringUtil.isEmptyOrSpaces(assignedUser) ? "" : " assignee:" + assignedUser; query = URLEncoder.encode("repo:" + user + "/" + repo + state + assignee + " " + query, CharsetToolkit.UTF8); String path = "/search/issues?q=" + query; //TODO: Use bodyHtml for issues - GitHub does not support this feature for SearchApi yet return load(connection, path, GithubIssuesSearchResult.class, ACCEPT_V3_JSON).getIssues(); } catch (GithubConfusingException e) { e.setDetails("Can't get queried issues: " + user + "/" + repo + " - " + query); throw e; } } @NotNull public static GithubIssue getIssue(@NotNull GithubConnection connection, @NotNull String user, @NotNull String repo, @NotNull String id) throws IOException { try { String path = "/repos/" + user + "/" + repo + "/issues/" + id; return load(connection, path, GithubIssue.class, ACCEPT_V3_JSON); } catch (GithubConfusingException e) { e.setDetails("Can't get issue info: " + user + "/" + repo + " - " + id); throw e; } } @NotNull public static List<GithubIssueComment> getIssueComments(@NotNull GithubConnection connection, @NotNull String user, @NotNull String repo, long id) throws IOException { try { String path = "/repos/" + user + "/" + repo + "/issues/" + id + "/comments?" + PER_PAGE; return loadAll(connection, path, GithubIssueComment[].class, ACCEPT_V3_JSON_HTML_MARKUP); } catch (GithubConfusingException e) { e.setDetails("Can't get issue comments: " + user + "/" + repo + " - " + id); throw e; } } public static void setIssueState(@NotNull GithubConnection connection, @NotNull String user, @NotNull String repo, @NotNull String id, boolean open) throws IOException { try { String path = "/repos/" + user + "/" + repo + "/issues/" + id; GithubChangeIssueStateRequest request = new GithubChangeIssueStateRequest(open ? "open" : "closed"); JsonElement result = connection.patchRequest(path, gson.toJson(request), ACCEPT_V3_JSON); fromJson(result, GithubIssue.class); } catch (GithubConfusingException e) { e.setDetails("Can't set issue state: " + user + "/" + repo + " - " + id + "@" + (open ? "open" : "closed")); throw e; } } @NotNull public static GithubCommitDetailed getCommit(@NotNull GithubConnection connection, @NotNull String user, @NotNull String repo, @NotNull String sha) throws IOException { try { String path = "/repos/" + user + "/" + repo + "/commits/" + sha; return load(connection, path, GithubCommitDetailed.class, ACCEPT_V3_JSON); } catch (GithubConfusingException e) { e.setDetails("Can't get commit info: " + user + "/" + repo + " - " + sha); throw e; } } @NotNull public static List<GithubCommitComment> getCommitComments(@NotNull GithubConnection connection, @NotNull String user, @NotNull String repo, @NotNull String sha) throws IOException { try { String path = "/repos/" + user + "/" + repo + "/commits/" + sha + "/comments"; return loadAll(connection, path, GithubCommitComment[].class, ACCEPT_V3_JSON_HTML_MARKUP); } catch (GithubConfusingException e) { e.setDetails("Can't get commit comments: " + user + "/" + repo + " - " + sha); throw e; } } @NotNull public static List<GithubCommitComment> getPullRequestComments(@NotNull GithubConnection connection, @NotNull String user, @NotNull String repo, long id) throws IOException { try { String path = "/repos/" + user + "/" + repo + "/pulls/" + id + "/comments"; return loadAll(connection, path, GithubCommitComment[].class, ACCEPT_V3_JSON_HTML_MARKUP); } catch (GithubConfusingException e) { e.setDetails("Can't get pull request comments: " + user + "/" + repo + " - " + id); throw e; } } @NotNull public static GithubPullRequest getPullRequest(@NotNull GithubConnection connection, @NotNull String user, @NotNull String repo, int id) throws IOException { try { String path = "/repos/" + user + "/" + repo + "/pulls/" + id; return load(connection, path, GithubPullRequest.class, ACCEPT_V3_JSON_HTML_MARKUP); } catch (GithubConfusingException e) { e.setDetails("Can't get pull request info: " + user + "/" + repo + " - " + id); throw e; } } @NotNull public static List<GithubPullRequest> getPullRequests(@NotNull GithubConnection connection, @NotNull String user, @NotNull String repo) throws IOException { try { String path = "/repos/" + user + "/" + repo + "/pulls?" + PER_PAGE; return loadAll(connection, path, GithubPullRequest[].class, ACCEPT_V3_JSON_HTML_MARKUP); } catch (GithubConfusingException e) { e.setDetails("Can't get pull requests" + user + "/" + repo); throw e; } } @NotNull public static PagedRequest<GithubPullRequest> getPullRequests(@NotNull String user, @NotNull String repo) { String path = "/repos/" + user + "/" + repo + "/pulls?state=all&" + PER_PAGE; return new ArrayPagedRequest<>(path, GithubPullRequest[].class, ACCEPT_V3_JSON_HTML_MARKUP); } @NotNull public static List<GithubCommit> getPullRequestCommits(@NotNull GithubConnection connection, @NotNull String user, @NotNull String repo, long id) throws IOException { try { String path = "/repos/" + user + "/" + repo + "/pulls/" + id + "/commits?" + PER_PAGE; return loadAll(connection, path, GithubCommit[].class, ACCEPT_V3_JSON); } catch (GithubConfusingException e) { e.setDetails("Can't get pull request commits: " + user + "/" + repo + " - " + id); throw e; } } @NotNull public static List<GithubFile> getPullRequestFiles(@NotNull GithubConnection connection, @NotNull String user, @NotNull String repo, long id) throws IOException { try { String path = "/repos/" + user + "/" + repo + "/pulls/" + id + "/files?" + PER_PAGE; return loadAll(connection, path, GithubFile[].class, ACCEPT_V3_JSON); } catch (GithubConfusingException e) { e.setDetails("Can't get pull request files: " + user + "/" + repo + " - " + id); throw e; } } @NotNull public static List<GithubBranch> getRepoBranches(@NotNull GithubConnection connection, @NotNull String user, @NotNull String repo) throws IOException { try { String path = "/repos/" + user + "/" + repo + "/branches?" + PER_PAGE; return loadAll(connection, path, GithubBranch[].class, ACCEPT_V3_JSON); } catch (GithubConfusingException e) { e.setDetails("Can't get repository branches: " + user + "/" + repo); throw e; } } @Nullable public static GithubRepo findForkByUser(@NotNull GithubConnection connection, @NotNull String user, @NotNull String repo, @NotNull String forkUser) throws IOException { try { String path = "/repos/" + user + "/" + repo + "/forks?" + PER_PAGE; PagedRequest<GithubRepo> request = new ArrayPagedRequest<>(path, GithubRepo[].class, ACCEPT_V3_JSON); while (request.hasNext()) { for (GithubRepo fork : request.next(connection)) { if (StringUtil.equalsIgnoreCase(fork.getUserName(), forkUser)) { return fork; } } } return null; } catch (GithubConfusingException e) { e.setDetails("Can't find fork by user: " + user + "/" + repo + " - " + forkUser); throw e; } } }
apache-2.0
jwren/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/update/ShowUpdatedDiffActionProvider.java
8195
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.vcs.update; import com.intellij.diff.DiffContentFactoryEx; import com.intellij.diff.DiffDialogHints; import com.intellij.diff.DiffManager; import com.intellij.diff.DiffRequestFactoryImpl; import com.intellij.diff.chains.DiffRequestChain; import com.intellij.diff.chains.DiffRequestProducer; import com.intellij.diff.chains.DiffRequestProducerException; import com.intellij.diff.contents.DiffContent; import com.intellij.diff.requests.DiffRequest; import com.intellij.diff.requests.SimpleDiffRequest; import com.intellij.history.ByteContent; import com.intellij.history.Label; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.UserDataHolder; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.VcsBundle; import com.intellij.openapi.vcs.changes.ui.ChangeDiffRequestChain; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class ShowUpdatedDiffActionProvider implements AnActionExtensionProvider { @Override public boolean isActive(@NotNull AnActionEvent e) { return isVisible(e.getDataContext()); } @Override public void update(@NotNull AnActionEvent e) { final DataContext dc = e.getDataContext(); final Presentation presentation = e.getPresentation(); presentation.setDescription(VcsBundle.messagePointer("action.presentation.ShowUpdatedDiffActionProvider.description")); //presentation.setVisible(isVisible(dc)); presentation.setEnabled(isVisible(dc) && isEnabled(dc)); } private boolean isVisible(final DataContext dc) { final Project project = CommonDataKeys.PROJECT.getData(dc); return (project != null) && (UpdateInfoTree.LABEL_BEFORE.getData(dc) != null) && (UpdateInfoTree.LABEL_AFTER.getData(dc) != null); } private boolean isEnabled(final DataContext dc) { final Iterable<Pair<FilePath, FileStatus>> iterable = UpdateInfoTree.UPDATE_VIEW_FILES_ITERABLE.getData(dc); return iterable != null; } @Override public void actionPerformed(@NotNull AnActionEvent e) { final DataContext dc = e.getDataContext(); if ((!isVisible(dc)) || (!isEnabled(dc))) return; final Project project = CommonDataKeys.PROJECT.getData(dc); final Iterable<Pair<FilePath, FileStatus>> iterable = e.getRequiredData(UpdateInfoTree.UPDATE_VIEW_FILES_ITERABLE); final Label before = e.getRequiredData(UpdateInfoTree.LABEL_BEFORE); final Label after = e.getRequiredData(UpdateInfoTree.LABEL_AFTER); final FilePath selectedUrl = UpdateInfoTree.UPDATE_VIEW_SELECTED_PATH.getData(dc); DiffRequestChain requestChain = createDiffRequestChain(project, before, after, iterable, selectedUrl); DiffManager.getInstance().showDiff(project, requestChain, DiffDialogHints.FRAME); } public static ChangeDiffRequestChain createDiffRequestChain(@Nullable Project project, @NotNull Label before, @NotNull Label after, @NotNull Iterable<? extends Pair<FilePath, FileStatus>> iterable, @Nullable FilePath selectedPath) { List<MyDiffRequestProducer> requests = new ArrayList<>(); int selected = -1; for (Pair<FilePath, FileStatus> pair : iterable) { if (selected == -1 && pair.first.equals(selectedPath)) selected = requests.size(); requests.add(new MyDiffRequestProducer(project, before, after, pair.first, pair.second)); } if (selected == -1) selected = 0; return new ChangeDiffRequestChain(requests, selected); } private static class MyDiffRequestProducer implements DiffRequestProducer, ChangeDiffRequestChain.Producer { @Nullable private final Project myProject; @NotNull private final Label myBefore; @NotNull private final Label myAfter; @NotNull private final FileStatus myFileStatus; @NotNull private final FilePath myFilePath; MyDiffRequestProducer(@Nullable Project project, @NotNull Label before, @NotNull Label after, @NotNull FilePath filePath, @NotNull FileStatus fileStatus) { myProject = project; myBefore = before; myAfter = after; myFileStatus = fileStatus; myFilePath = filePath; } @NotNull @Override public String getName() { return myFilePath.getPresentableUrl(); } @NotNull @Override public FilePath getFilePath() { return myFilePath; } @NotNull @Override public FileStatus getFileStatus() { return myFileStatus; } @NotNull @Override public DiffRequest process(@NotNull UserDataHolder context, @NotNull ProgressIndicator indicator) throws DiffRequestProducerException, ProcessCanceledException { try { DiffContent content1; DiffContent content2; DiffContentFactoryEx contentFactory = DiffContentFactoryEx.getInstanceEx(); if (FileStatus.ADDED.equals(myFileStatus)) { content1 = contentFactory.createEmpty(); } else { byte[] bytes1 = loadContent(myFilePath, myBefore); content1 = contentFactory.createFromBytes(myProject, bytes1, myFilePath); } if (FileStatus.DELETED.equals(myFileStatus)) { content2 = contentFactory.createEmpty(); } else { byte[] bytes2 = loadContent(myFilePath, myAfter); content2 = contentFactory.createFromBytes(myProject, bytes2, myFilePath); } String title = DiffRequestFactoryImpl.getContentTitle(myFilePath); return new SimpleDiffRequest(title, content1, content2, VcsBundle.message("update.label.before.update"), VcsBundle.message("update.label.after.update")); } catch (IOException e) { throw new DiffRequestProducerException(VcsBundle.message("update.can.t.load.content"), e); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MyDiffRequestProducer producer = (MyDiffRequestProducer)o; return myBefore.equals(producer.myBefore) && myAfter.equals(producer.myAfter) && myFileStatus.equals(producer.myFileStatus) && myFilePath.equals(producer.myFilePath); } @Override public int hashCode() { return Objects.hash(myBefore, myAfter, myFileStatus, myFilePath); } } private static byte @NotNull [] loadContent(@NotNull FilePath path, @NotNull Label label) throws DiffRequestProducerException { ByteContent byteContent = label.getByteContent(path.getPath()); if (byteContent == null || byteContent.isDirectory() || byteContent.getBytes() == null) { throw new DiffRequestProducerException(VcsBundle.message("update.can.t.load.content")); } return byteContent.getBytes(); } }
apache-2.0
jhouserizer/ehcache3
ehcache-api/src/test/java/org/ehcache/config/units/MemoryUnitTest.java
12836
/* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ehcache.config.units; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThan; import org.junit.Test; /** * * @author cdennis */ public class MemoryUnitTest { @Test public void testBasicPositiveConversions() { assertThat(MemoryUnit.B.toBytes(1L), is(1L)); assertThat(MemoryUnit.KB.toBytes(1L), is(1024L)); assertThat(MemoryUnit.MB.toBytes(1L), is(1024L * 1024L)); assertThat(MemoryUnit.GB.toBytes(1L), is(1024L * 1024L * 1024L)); assertThat(MemoryUnit.TB.toBytes(1L), is(1024L * 1024L * 1024L * 1024L)); assertThat(MemoryUnit.PB.toBytes(1L), is(1024L * 1024L * 1024L * 1024L * 1024L)); assertThat(MemoryUnit.B.convert(1L, MemoryUnit.B), is(1L)); assertThat(MemoryUnit.KB.convert(1L, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.MB.convert(1L, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.GB.convert(1L, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.TB.convert(1L, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.PB.convert(1L, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.B.convert(1L, MemoryUnit.KB), is(1024L)); assertThat(MemoryUnit.KB.convert(1L, MemoryUnit.KB), is(1L)); assertThat(MemoryUnit.MB.convert(1L, MemoryUnit.KB), is(0L)); assertThat(MemoryUnit.GB.convert(1L, MemoryUnit.KB), is(0L)); assertThat(MemoryUnit.TB.convert(1L, MemoryUnit.KB), is(0L)); assertThat(MemoryUnit.PB.convert(1L, MemoryUnit.KB), is(0L)); assertThat(MemoryUnit.B.convert(1L, MemoryUnit.MB), is(1024L * 1024L)); assertThat(MemoryUnit.KB.convert(1L, MemoryUnit.MB), is(1024L)); assertThat(MemoryUnit.MB.convert(1L, MemoryUnit.MB), is(1L)); assertThat(MemoryUnit.GB.convert(1L, MemoryUnit.MB), is(0L)); assertThat(MemoryUnit.TB.convert(1L, MemoryUnit.MB), is(0L)); assertThat(MemoryUnit.PB.convert(1L, MemoryUnit.MB), is(0L)); assertThat(MemoryUnit.B.convert(1L, MemoryUnit.GB), is(1024L * 1024L * 1024L)); assertThat(MemoryUnit.KB.convert(1L, MemoryUnit.GB), is(1024L * 1024L)); assertThat(MemoryUnit.MB.convert(1L, MemoryUnit.GB), is(1024L)); assertThat(MemoryUnit.GB.convert(1L, MemoryUnit.GB), is(1L)); assertThat(MemoryUnit.TB.convert(1L, MemoryUnit.GB), is(0L)); assertThat(MemoryUnit.PB.convert(1L, MemoryUnit.GB), is(0L)); assertThat(MemoryUnit.B.convert(1L, MemoryUnit.TB), is(1024L * 1024L * 1024L * 1024L)); assertThat(MemoryUnit.KB.convert(1L, MemoryUnit.TB), is(1024L * 1024L * 1024L)); assertThat(MemoryUnit.MB.convert(1L, MemoryUnit.TB), is(1024L * 1024L)); assertThat(MemoryUnit.GB.convert(1L, MemoryUnit.TB), is(1024L)); assertThat(MemoryUnit.TB.convert(1L, MemoryUnit.TB), is(1L)); assertThat(MemoryUnit.PB.convert(1L, MemoryUnit.TB), is(0L)); assertThat(MemoryUnit.B.convert(1L, MemoryUnit.PB), is(1024L * 1024L * 1024L * 1024L * 1024L)); assertThat(MemoryUnit.KB.convert(1L, MemoryUnit.PB), is(1024L * 1024L * 1024L * 1024L)); assertThat(MemoryUnit.MB.convert(1L, MemoryUnit.PB), is(1024L * 1024L * 1024L)); assertThat(MemoryUnit.GB.convert(1L, MemoryUnit.PB), is(1024L * 1024L)); assertThat(MemoryUnit.TB.convert(1L, MemoryUnit.PB), is(1024L)); assertThat(MemoryUnit.PB.convert(1L, MemoryUnit.PB), is(1L)); } @Test public void testBasicNegativeConversions() { assertThat(MemoryUnit.B.toBytes(-1L), is(-1L)); assertThat(MemoryUnit.KB.toBytes(-1L), is(-1024L)); assertThat(MemoryUnit.MB.toBytes(-1L), is(-1024L * 1024L)); assertThat(MemoryUnit.GB.toBytes(-1L), is(-1024L * 1024L * 1024L)); assertThat(MemoryUnit.TB.toBytes(-1L), is(-1024L * 1024L * 1024L * 1024L)); assertThat(MemoryUnit.PB.toBytes(-1L), is(-1024L * 1024L * 1024L * 1024L * 1024L)); assertThat(MemoryUnit.B.convert(-1L, MemoryUnit.B), is(-1L)); assertThat(MemoryUnit.KB.convert(-1L, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.MB.convert(-1L, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.GB.convert(-1L, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.TB.convert(-1L, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.PB.convert(-1L, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.B.convert(-1L, MemoryUnit.KB), is(-1024L)); assertThat(MemoryUnit.KB.convert(-1L, MemoryUnit.KB), is(-1L)); assertThat(MemoryUnit.MB.convert(-1L, MemoryUnit.KB), is(0L)); assertThat(MemoryUnit.GB.convert(-1L, MemoryUnit.KB), is(0L)); assertThat(MemoryUnit.TB.convert(-1L, MemoryUnit.KB), is(0L)); assertThat(MemoryUnit.PB.convert(-1L, MemoryUnit.KB), is(0L)); assertThat(MemoryUnit.B.convert(-1L, MemoryUnit.MB), is(-1024L * 1024L)); assertThat(MemoryUnit.KB.convert(-1L, MemoryUnit.MB), is(-1024L)); assertThat(MemoryUnit.MB.convert(-1L, MemoryUnit.MB), is(-1L)); assertThat(MemoryUnit.GB.convert(-1L, MemoryUnit.MB), is(0L)); assertThat(MemoryUnit.TB.convert(-1L, MemoryUnit.MB), is(0L)); assertThat(MemoryUnit.PB.convert(-1L, MemoryUnit.MB), is(0L)); assertThat(MemoryUnit.B.convert(-1L, MemoryUnit.GB), is(-1024L * 1024L * 1024L)); assertThat(MemoryUnit.KB.convert(-1L, MemoryUnit.GB), is(-1024L * 1024L)); assertThat(MemoryUnit.MB.convert(-1L, MemoryUnit.GB), is(-1024L)); assertThat(MemoryUnit.GB.convert(-1L, MemoryUnit.GB), is(-1L)); assertThat(MemoryUnit.TB.convert(-1L, MemoryUnit.GB), is(0L)); assertThat(MemoryUnit.PB.convert(-1L, MemoryUnit.GB), is(0L)); assertThat(MemoryUnit.B.convert(-1L, MemoryUnit.TB), is(-1024L * 1024L * 1024L * 1024L)); assertThat(MemoryUnit.KB.convert(-1L, MemoryUnit.TB), is(-1024L * 1024L * 1024L)); assertThat(MemoryUnit.MB.convert(-1L, MemoryUnit.TB), is(-1024L * 1024L)); assertThat(MemoryUnit.GB.convert(-1L, MemoryUnit.TB), is(-1024L)); assertThat(MemoryUnit.TB.convert(-1L, MemoryUnit.TB), is(-1L)); assertThat(MemoryUnit.PB.convert(-1L, MemoryUnit.TB), is(0L)); assertThat(MemoryUnit.B.convert(-1L, MemoryUnit.PB), is(-1024L * 1024L * 1024L * 1024L * 1024L)); assertThat(MemoryUnit.KB.convert(-1L, MemoryUnit.PB), is(-1024L * 1024L * 1024L * 1024L)); assertThat(MemoryUnit.MB.convert(-1L, MemoryUnit.PB), is(-1024L * 1024L * 1024L)); assertThat(MemoryUnit.GB.convert(-1L, MemoryUnit.PB), is(-1024L * 1024L)); assertThat(MemoryUnit.TB.convert(-1L, MemoryUnit.PB), is(-1024L)); assertThat(MemoryUnit.PB.convert(-1L, MemoryUnit.PB), is(-1L)); } @Test public void testPositiveThresholdConditions() { assertThat(MemoryUnit.KB.convert(1024L - 1, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.KB.convert(1024L + 1, MemoryUnit.B), is(1L)); assertThat(MemoryUnit.MB.convert((1024L * 1024L) - 1, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.MB.convert((1024L * 1024L) + 1, MemoryUnit.B), is(1L)); assertThat(MemoryUnit.GB.convert((1024L * 1024L * 1024L) - 1, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.GB.convert((1024L * 1024L * 1024L) + 1, MemoryUnit.B), is(1L)); assertThat(MemoryUnit.TB.convert((1024L * 1024L * 1024L * 1024L) - 1, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.TB.convert((1024L * 1024L * 1024L * 1024L) + 1, MemoryUnit.B), is(1L)); assertThat(MemoryUnit.PB.convert((1024L * 1024L * 1024L * 1024L * 1024L) - 1, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.PB.convert((1024L * 1024L * 1024L * 1024L * 1024L) + 1, MemoryUnit.B), is(1L)); assertThat(MemoryUnit.MB.convert(1024L - 1, MemoryUnit.KB), is(0L)); assertThat(MemoryUnit.MB.convert(1024L + 1, MemoryUnit.KB), is(1L)); assertThat(MemoryUnit.GB.convert((1024L * 1024L) - 1, MemoryUnit.KB), is(0L)); assertThat(MemoryUnit.GB.convert((1024L * 1024L) + 1, MemoryUnit.KB), is(1L)); assertThat(MemoryUnit.TB.convert((1024L * 1024L * 1024L) - 1, MemoryUnit.KB), is(0L)); assertThat(MemoryUnit.TB.convert((1024L * 1024L * 1024L) + 1, MemoryUnit.KB), is(1L)); assertThat(MemoryUnit.PB.convert((1024L * 1024L * 1024L * 1024L) - 1, MemoryUnit.KB), is(0L)); assertThat(MemoryUnit.PB.convert((1024L * 1024L * 1024L * 1024L) + 1, MemoryUnit.KB), is(1L)); assertThat(MemoryUnit.GB.convert(1024L - 1, MemoryUnit.MB), is(0L)); assertThat(MemoryUnit.GB.convert(1024L + 1, MemoryUnit.MB), is(1L)); assertThat(MemoryUnit.TB.convert((1024L * 1024L) - 1, MemoryUnit.MB), is(0L)); assertThat(MemoryUnit.TB.convert((1024L * 1024L) + 1, MemoryUnit.MB), is(1L)); assertThat(MemoryUnit.PB.convert((1024L * 1024L * 1024L) - 1, MemoryUnit.MB), is(0L)); assertThat(MemoryUnit.PB.convert((1024L * 1024L * 1024L) + 1, MemoryUnit.MB), is(1L)); assertThat(MemoryUnit.TB.convert(1024L - 1, MemoryUnit.GB), is(0L)); assertThat(MemoryUnit.TB.convert(1024L + 1, MemoryUnit.GB), is(1L)); assertThat(MemoryUnit.PB.convert((1024L * 1024L) - 1, MemoryUnit.GB), is(0L)); assertThat(MemoryUnit.PB.convert((1024L * 1024L) + 1, MemoryUnit.GB), is(1L)); assertThat(MemoryUnit.PB.convert(1024L - 1, MemoryUnit.TB), is(0L)); assertThat(MemoryUnit.PB.convert(1024L + 1, MemoryUnit.TB), is(1L)); } @Test public void testNegativeThresholdConditions() { assertThat(MemoryUnit.KB.convert(-1024L + 1, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.KB.convert(-1024L - 1, MemoryUnit.B), is(-1L)); assertThat(MemoryUnit.MB.convert(-(1024L * 1024L) + 1, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.MB.convert(-(1024L * 1024L) - 1, MemoryUnit.B), is(-1L)); assertThat(MemoryUnit.GB.convert(-(1024L * 1024L * 1024L) + 1, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.GB.convert(-(1024L * 1024L * 1024L) - 1, MemoryUnit.B), is(-1L)); assertThat(MemoryUnit.TB.convert(-(1024L * 1024L * 1024L * 1024L) + 1, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.TB.convert(-(1024L * 1024L * 1024L * 1024L) - 1, MemoryUnit.B), is(-1L)); assertThat(MemoryUnit.PB.convert(-(1024L * 1024L * 1024L * 1024L * 1024L) + 1, MemoryUnit.B), is(0L)); assertThat(MemoryUnit.PB.convert(-(1024L * 1024L * 1024L * 1024L * 1024L) - 1, MemoryUnit.B), is(-1L)); assertThat(MemoryUnit.MB.convert(-1024L + 1, MemoryUnit.KB), is(0L)); assertThat(MemoryUnit.MB.convert(-1024L - 1, MemoryUnit.KB), is(-1L)); assertThat(MemoryUnit.GB.convert(-(1024L * 1024L) + 1, MemoryUnit.KB), is(0L)); assertThat(MemoryUnit.GB.convert(-(1024L * 1024L) - 1, MemoryUnit.KB), is(-1L)); assertThat(MemoryUnit.TB.convert(-(1024L * 1024L * 1024L) + 1, MemoryUnit.KB), is(0L)); assertThat(MemoryUnit.TB.convert(-(1024L * 1024L * 1024L) - 1, MemoryUnit.KB), is(-1L)); assertThat(MemoryUnit.PB.convert(-(1024L * 1024L * 1024L * 1024L) + 1, MemoryUnit.KB), is(0L)); assertThat(MemoryUnit.PB.convert(-(1024L * 1024L * 1024L * 1024L) - 1, MemoryUnit.KB), is(-1L)); assertThat(MemoryUnit.GB.convert(-1024L + 1, MemoryUnit.MB), is(0L)); assertThat(MemoryUnit.GB.convert(-1024L - 1, MemoryUnit.MB), is(-1L)); assertThat(MemoryUnit.TB.convert(-(1024L * 1024L) + 1, MemoryUnit.MB), is(0L)); assertThat(MemoryUnit.TB.convert(-(1024L * 1024L) - 1, MemoryUnit.MB), is(-1L)); assertThat(MemoryUnit.PB.convert(-(1024L * 1024L * 1024L) + 1, MemoryUnit.MB), is(0L)); assertThat(MemoryUnit.PB.convert(-(1024L * 1024L * 1024L) - 1, MemoryUnit.MB), is(-1L)); assertThat(MemoryUnit.TB.convert(-1024L + 1, MemoryUnit.GB), is(0L)); assertThat(MemoryUnit.TB.convert(-1024L - 1, MemoryUnit.GB), is(-1L)); assertThat(MemoryUnit.PB.convert(-(1024L * 1024L) + 1, MemoryUnit.GB), is(0L)); assertThat(MemoryUnit.PB.convert(-(1024L * 1024L) - 1, MemoryUnit.GB), is(-1L)); assertThat(MemoryUnit.PB.convert(-1024L + 1, MemoryUnit.TB), is(0L)); assertThat(MemoryUnit.PB.convert(-1024L - 1, MemoryUnit.TB), is(-1L)); } @Test public void testThresholdComparisons() { assertThat(MemoryUnit.KB.compareTo(1, 1024L - 1, MemoryUnit.B), greaterThan(0)); assertThat(MemoryUnit.KB.compareTo(1, 1024L, MemoryUnit.B), is(0)); assertThat(MemoryUnit.KB.compareTo(1, 1024L + 1, MemoryUnit.B), lessThan(0)); assertThat(MemoryUnit.KB.compareTo(2, 2048L - 1, MemoryUnit.B), greaterThan(0)); assertThat(MemoryUnit.KB.compareTo(2, 2048L, MemoryUnit.B), is(0)); assertThat(MemoryUnit.KB.compareTo(2, 2048L + 1, MemoryUnit.B), lessThan(0)); } }
apache-2.0
mrchristine/spark-examples-dbc
src/main/java/org/apache/spark/examples/ml/JavaNormalizerExample.java
1864
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.examples.ml; import org.apache.spark.sql.SparkSession; // $example on$ import org.apache.spark.ml.feature.Normalizer; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; // $example off$ public class JavaNormalizerExample { public static void main(String[] args) { SparkSession spark = SparkSession .builder() .appName("JavaNormalizerExample") .getOrCreate(); // $example on$ Dataset<Row> dataFrame = spark.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt"); // Normalize each Vector using $L^1$ norm. Normalizer normalizer = new Normalizer() .setInputCol("features") .setOutputCol("normFeatures") .setP(1.0); Dataset<Row> l1NormData = normalizer.transform(dataFrame); l1NormData.show(); // Normalize each Vector using $L^\infty$ norm. Dataset<Row> lInfNormData = normalizer.transform(dataFrame, normalizer.p().w(Double.POSITIVE_INFINITY)); lInfNormData.show(); // $example off$ spark.stop(); } }
apache-2.0
pivotal-amurmann/geode
geode-core/src/test/java/org/apache/geode/internal/cache/CacheServerLauncherJUnitTest.java
1761
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.cache; import static org.apache.geode.internal.Assert.assertTrue; import static org.junit.Assert.assertFalse; import org.junit.Test; import org.junit.Before; import org.junit.After; import org.junit.experimental.categories.Category; import org.apache.geode.test.junit.categories.UnitTest; /** * CacheServerLauncher Tester. */ @Category(UnitTest.class) public class CacheServerLauncherJUnitTest { @Test public void testSafeEquals() { String string1 = "string1"; String string2 = string1; @SuppressWarnings("RedundantStringConstructorCall") String string3 = new String(string1); assertTrue(CacheServerLauncher.safeEquals(string1, string2)); assertTrue(CacheServerLauncher.safeEquals(string1, string3)); assertTrue(CacheServerLauncher.safeEquals(null, null)); assertFalse(CacheServerLauncher.safeEquals(null, string3)); assertFalse(CacheServerLauncher.safeEquals(string1, null)); } }
apache-2.0
paulk-asert/groovy
src/main/java/org/codehaus/groovy/vmplugin/v8/CacheableCallSite.java
3138
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.codehaus.groovy.vmplugin.v8; import org.apache.groovy.util.SystemUtil; import org.codehaus.groovy.runtime.memoize.LRUCache; import org.codehaus.groovy.runtime.memoize.MemoizeCache; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodType; import java.lang.invoke.MutableCallSite; import java.util.concurrent.atomic.AtomicLong; /** * Represents a cacheable call site, which can reduce the cost of resolving methods * * @since 3.0.0 */ public class CacheableCallSite extends MutableCallSite { private static final int CACHE_SIZE = SystemUtil.getIntegerSafe("groovy.indy.callsite.cache.size", 16); private final MemoizeCache<String, MethodHandleWrapper> cache = new LRUCache<>(CACHE_SIZE); private volatile MethodHandleWrapper latestHitMethodHandleWrapper = null; private final AtomicLong fallbackCount = new AtomicLong(0); private MethodHandle defaultTarget; private MethodHandle fallbackTarget; public CacheableCallSite(MethodType type) { super(type); } public MethodHandleWrapper getAndPut(String className, MemoizeCache.ValueProvider<? super String, ? extends MethodHandleWrapper> valueProvider) { final MethodHandleWrapper result = cache.getAndPut(className, valueProvider); final MethodHandleWrapper lhmh = latestHitMethodHandleWrapper; if (lhmh == result) { result.incrementLatestHitCount(); } else { result.resetLatestHitCount(); if (null != lhmh) lhmh.resetLatestHitCount(); latestHitMethodHandleWrapper = result; } return result; } public MethodHandleWrapper put(String name, MethodHandleWrapper mhw) { return cache.put(name, mhw); } public long incrementFallbackCount() { return fallbackCount.incrementAndGet(); } public void resetFallbackCount() { fallbackCount.set(0); } public MethodHandle getDefaultTarget() { return defaultTarget; } public void setDefaultTarget(MethodHandle defaultTarget) { this.defaultTarget = defaultTarget; } public MethodHandle getFallbackTarget() { return fallbackTarget; } public void setFallbackTarget(MethodHandle fallbackTarget) { this.fallbackTarget = fallbackTarget; } }
apache-2.0
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/ide/util/MemberChooser.java
31519
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.util; import com.intellij.codeInsight.generation.*; import com.intellij.icons.AllIcons; import com.intellij.ide.IdeBundle; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.PlatformEditorBundle; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.VerticalFlowLayout; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.NlsActions; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiCompiledElement; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.ui.*; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.PlatformIcons; import com.intellij.util.containers.FactoryMap; import com.intellij.util.ui.JBInsets; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.*; import java.awt.*; import java.awt.event.*; import java.util.List; import java.util.*; import java.util.function.Supplier; import static com.intellij.openapi.keymap.KeymapUtil.getActiveKeymapShortcuts; import static com.intellij.ui.tree.TreePathUtil.toTreePathArray; import static java.util.Comparator.comparing; import static java.util.Comparator.nullsLast; public class MemberChooser<T extends ClassMember> extends DialogWrapper implements DataProvider { protected Tree myTree; private DefaultTreeModel myTreeModel; protected JComponent[] myOptionControls; private JCheckBox myCopyJavadocCheckbox; private JCheckBox myInsertOverrideAnnotationCheckbox; private final ArrayList<MemberNode> mySelectedNodes = new ArrayList<>(); private final SortEmAction mySortAction; private boolean myAlphabeticallySorted = false; private boolean myShowClasses = true; protected boolean myAllowEmptySelection; private final boolean myAllowMultiSelection; private final boolean myIsInsertOverrideVisible; private final JComponent myHeaderPanel; protected T[] myElements; protected Comparator<? super ElementNode> myComparator = new OrderComparator(); protected final HashMap<MemberNode,ParentNode> myNodeToParentMap = new HashMap<>(); protected final HashMap<ClassMember, MemberNode> myElementToNodeMap = new HashMap<>(); protected final ArrayList<ContainerNode> myContainerNodes = new ArrayList<>(); protected LinkedHashSet<T> mySelectedElements; @NonNls private static final String PROP_SORTED = "MemberChooser.sorted"; @NonNls private static final String PROP_SHOWCLASSES = "MemberChooser.showClasses"; @NonNls private static final String PROP_COPYJAVADOC = "MemberChooser.copyJavadoc"; public MemberChooser(T[] elements, boolean allowEmptySelection, boolean allowMultiSelection, @NotNull Project project, @Nullable JComponent headerPanel, JComponent[] optionControls) { this(allowEmptySelection, allowMultiSelection, project, false, headerPanel, optionControls); resetElements(elements); init(); } public MemberChooser(T[] elements, boolean allowEmptySelection, boolean allowMultiSelection, @NotNull Project project) { this(elements, allowEmptySelection, allowMultiSelection, project, false); } public MemberChooser(T[] elements, boolean allowEmptySelection, boolean allowMultiSelection, @NotNull Project project, boolean isInsertOverrideVisible) { this(elements, allowEmptySelection, allowMultiSelection, project, isInsertOverrideVisible, null); } public MemberChooser(T[] elements, boolean allowEmptySelection, boolean allowMultiSelection, @NotNull Project project, boolean isInsertOverrideVisible, @Nullable JComponent headerPanel ) { this(allowEmptySelection, allowMultiSelection, project, isInsertOverrideVisible, headerPanel, null); resetElements(elements); init(); } protected MemberChooser(boolean allowEmptySelection, boolean allowMultiSelection, @NotNull Project project, boolean isInsertOverrideVisible, @Nullable JComponent headerPanel, JComponent @Nullable [] optionControls) { super(project, true); myAllowEmptySelection = allowEmptySelection; myAllowMultiSelection = allowMultiSelection; myIsInsertOverrideVisible = isInsertOverrideVisible; myHeaderPanel = headerPanel; myTree = createTree(); myOptionControls = optionControls; mySortAction = new SortEmAction(); mySortAction.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.ALT_MASK)), myTree); } protected void resetElementsWithDefaultComparator(T[] elements) { myComparator = myAlphabeticallySorted ? new AlphaComparator() : new OrderComparator(); resetElements(elements, null, true); } public void resetElements(T[] elements) { resetElements(elements, null, false); } public void resetElements(T[] elements, final @Nullable Comparator<? super T> sortComparator, final boolean restoreSelectedElements) { final List<T> selectedElements = restoreSelectedElements && mySelectedElements != null ? new ArrayList<>(mySelectedElements) : null; myElements = elements; if (sortComparator != null) { myComparator = new ElementNodeComparatorWrapper<>(sortComparator); } mySelectedNodes.clear(); myNodeToParentMap.clear(); myElementToNodeMap.clear(); myContainerNodes.clear(); ApplicationManager.getApplication().runReadAction(() -> { myTreeModel = buildModel(); }); myTree.setModel(myTreeModel); myTree.setRootVisible(false); doSort(); defaultExpandTree(); //TODO: dmitry batkovich: appcode tests fail //restoreTree(); if (myOptionControls == null) { myCopyJavadocCheckbox = new NonFocusableCheckBox(IdeBundle.message("checkbox.copy.javadoc")); if (myIsInsertOverrideVisible) { myInsertOverrideAnnotationCheckbox = new NonFocusableCheckBox(IdeBundle.message("checkbox.insert.at.override")); myOptionControls = new JCheckBox[] {myCopyJavadocCheckbox, myInsertOverrideAnnotationCheckbox}; } else { myOptionControls = new JCheckBox[] {myCopyJavadocCheckbox}; } } myTree.doLayout(); setOKActionEnabled(myAllowEmptySelection || myElements != null && myElements.length > 0); if (selectedElements != null) { selectElements(selectedElements.toArray(ClassMember.EMPTY_ARRAY)); } if (mySelectedElements == null || mySelectedElements.isEmpty()) { expandFirst(); } } /** * should be invoked in read action */ private DefaultTreeModel buildModel() { final DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(); final Ref<Integer> count = new Ref<>(0); Ref<Map<MemberChooserObject, ParentNode>> mapRef = new Ref<>(); mapRef.set(FactoryMap.create(key -> { ParentNode node = null; DefaultMutableTreeNode parentNode1 = rootNode; if (supportsNestedContainers() && key instanceof ClassMember) { MemberChooserObject parentNodeDelegate = ((ClassMember)key).getParentNodeDelegate(); if (parentNodeDelegate != null) { parentNode1 = mapRef.get().get(parentNodeDelegate); } } if (isContainerNode(key)) { final ContainerNode containerNode = new ContainerNode(parentNode1, key, count); node = containerNode; myContainerNodes.add(containerNode); } if (node == null) { node = new ParentNode(parentNode1, key, count); } return node; })); final Map<MemberChooserObject, ParentNode> map = mapRef.get(); for (T object : myElements) { final ParentNode parentNode = map.get(object.getParentNodeDelegate()); final MemberNode elementNode = createMemberNode(count, object, parentNode); myNodeToParentMap.put(elementNode, parentNode); myElementToNodeMap.put(object, elementNode); } return new DefaultTreeModel(rootNode); } protected MemberNode createMemberNode(Ref<Integer> count, @NotNull T object, ParentNode parentNode) { return new MemberNodeImpl(parentNode, object, count); } protected boolean supportsNestedContainers() { return false; } protected void defaultExpandTree() { TreeUtil.expandAll(myTree); } protected boolean isContainerNode(MemberChooserObject key) { return key instanceof PsiElementMemberChooserObject; } public void selectElements(ClassMember[] elements) { ArrayList<TreePath> selectionPaths = new ArrayList<>(); for (ClassMember element : elements) { MemberNode treeNode = myElementToNodeMap.get(element); if (treeNode != null) { selectionPaths.add(new TreePath(((DefaultMutableTreeNode)treeNode).getPath())); } } final TreePath[] paths = toTreePathArray(selectionPaths); myTree.setSelectionPaths(paths); if (paths.length > 0) { TreeUtil.showRowCentered(myTree, myTree.getRowForPath(paths[0]), true, true); } } @Override protected Action @NotNull [] createActions() { final List<Action> actions = new ArrayList<>(); actions.add(getOKAction()); if (myAllowEmptySelection) { actions.add(new SelectNoneAction()); } actions.add(getCancelAction()); if (getHelpId() != null) { actions.add(getHelpAction()); } return actions.toArray(new Action[0]); } protected void customizeOptionsPanel() { if (myInsertOverrideAnnotationCheckbox != null && myIsInsertOverrideVisible) { myInsertOverrideAnnotationCheckbox.setSelected(isInsertOverrideAnnotationSelected()); } if (myCopyJavadocCheckbox != null) { myCopyJavadocCheckbox.setSelected(PropertiesComponent.getInstance().isTrueValue(PROP_COPYJAVADOC)); } } protected boolean isInsertOverrideAnnotationSelected() { return false; } @Override protected JComponent createSouthPanel() { JPanel panel = new JPanel(new GridBagLayout()); customizeOptionsPanel(); JPanel optionsPanel = new JPanel(new VerticalFlowLayout()); for (final JComponent component : myOptionControls) { optionsPanel.add(component); } panel.add( optionsPanel, new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, JBUI.insetsRight(5), 0, 0) ); if (!myAllowEmptySelection && (myElements == null || myElements.length == 0)) { setOKActionEnabled(false); } panel.add( super.createSouthPanel(), new GridBagConstraints(1, 0, 1, 1, 0, 0, GridBagConstraints.SOUTH, GridBagConstraints.NONE, JBInsets.emptyInsets(), 0, 0) ); return panel; } @Override protected JComponent createNorthPanel() { return myHeaderPanel; } @Override protected JComponent createCenterPanel() { JPanel panel = new JPanel(new BorderLayout()); // Toolbar DefaultActionGroup group = new DefaultActionGroup(); fillToolbarActions(group); group.addSeparator(); ExpandAllAction expandAllAction = new ExpandAllAction(); expandAllAction.registerCustomShortcutSet(getActiveKeymapShortcuts(IdeActions.ACTION_EXPAND_ALL), myTree); group.add(expandAllAction); CollapseAllAction collapseAllAction = new CollapseAllAction(); collapseAllAction.registerCustomShortcutSet(getActiveKeymapShortcuts(IdeActions.ACTION_COLLAPSE_ALL), myTree); group.add(collapseAllAction); ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar("MemberChooser", group, true); toolbar.setTargetComponent(myTree); panel.add(toolbar.getComponent(), BorderLayout.NORTH); // Tree expandFirst(); defaultExpandTree(); installSpeedSearch(); JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTree); scrollPane.setPreferredSize(JBUI.size(350, 450)); panel.add(scrollPane, BorderLayout.CENTER); return panel; } private void expandFirst() { if (getRootNode().getChildCount() > 0) { myTree.expandRow(0); myTree.setSelectionRow(1); } } protected Tree createTree() { final Tree tree = new Tree(new DefaultTreeModel(new DefaultMutableTreeNode())); tree.setCellRenderer(getTreeCellRenderer()); tree.setRootVisible(false); tree.setShowsRootHandles(true); tree.addKeyListener(new TreeKeyListener()); tree.addTreeSelectionListener(new MyTreeSelectionListener()); if (!myAllowMultiSelection) { tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); } new DoubleClickListener() { @Override protected boolean onDoubleClick(@NotNull MouseEvent e) { if (tree.getPathForLocation(e.getX(), e.getY()) != null) { doOKAction(); return true; } return false; } }.installOn(tree); TreeUtil.installActions(tree); return tree; } protected TreeCellRenderer getTreeCellRenderer() { return new ColoredTreeCellRenderer() { @Override public void customizeCellRenderer(@NotNull JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { if (value instanceof ElementNode) { ((ElementNode) value).getDelegate().renderTreeNode(this, tree); } } }; } @NotNull protected String convertElementText(@NotNull String originalElementText) { return originalElementText; } protected void installSpeedSearch() { final TreeSpeedSearch treeSpeedSearch = new TreeSpeedSearch(myTree, path -> { final ElementNode lastPathComponent = (ElementNode)path.getLastPathComponent(); if (lastPathComponent == null) return null; String text = lastPathComponent.getDelegate().getText(); text = convertElementText(text); return text; }); treeSpeedSearch.setComparator(getSpeedSearchComparator()); } protected SpeedSearchComparator getSpeedSearchComparator() { return new SpeedSearchComparator(false); } protected void disableAlphabeticalSorting(@NotNull AnActionEvent event) { mySortAction.setSelected(event, false); } protected void onAlphabeticalSortingEnabled(final AnActionEvent event) { //do nothing by default } protected void fillToolbarActions(DefaultActionGroup group) { final boolean alphabeticallySorted = PropertiesComponent.getInstance().isTrueValue(PROP_SORTED); if (alphabeticallySorted) { setSortComparator(new AlphaComparator()); } myAlphabeticallySorted = alphabeticallySorted; group.add(mySortAction); if (!supportsNestedContainers()) { ShowContainersAction showContainersAction = getShowContainersAction(); showContainersAction.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.ALT_MASK)), myTree); setShowClasses(PropertiesComponent.getInstance().getBoolean(PROP_SHOWCLASSES, true)); group.add(showContainersAction); } } @Override protected String getDimensionServiceKey() { return "#com.intellij.ide.util.MemberChooser"; } @Override public JComponent getPreferredFocusedComponent() { return myTree; } public JComponent[] getOptionControls() { return myOptionControls; } @Nullable private LinkedHashSet<T> getSelectedElementsList() { return getExitCode() == OK_EXIT_CODE ? mySelectedElements : null; } @Nullable public List<T> getSelectedElements() { final LinkedHashSet<T> list = getSelectedElementsList(); return list == null ? null : new ArrayList<>(list); } public T @Nullable [] getSelectedElements(T[] a) { LinkedHashSet<T> list = getSelectedElementsList(); if (list == null) return null; return list.toArray(a); } protected final boolean areElementsSelected() { return mySelectedElements != null && !mySelectedElements.isEmpty(); } public void setCopyJavadocVisible(boolean state) { if (myCopyJavadocCheckbox != null) { myCopyJavadocCheckbox.setVisible(state); } } public boolean isCopyJavadoc() { return myCopyJavadocCheckbox != null && myCopyJavadocCheckbox.isSelected(); } public boolean isInsertOverrideAnnotation() { return myIsInsertOverrideVisible && myInsertOverrideAnnotationCheckbox.isSelected(); } private boolean isAlphabeticallySorted() { return myAlphabeticallySorted; } protected void changeSortComparator(final Comparator<? super T> comparator) { setSortComparator(new ElementNodeComparatorWrapper<>(comparator)); } private void setSortComparator(Comparator<? super ElementNode> sortComparator) { if (myComparator.equals(sortComparator)) return; myComparator = sortComparator; doSort(); } protected void doSort() { Pair<ElementNode, List<ElementNode>> pair = storeSelection(); Enumeration<TreeNode> children = getRootNodeChildren(); while (children.hasMoreElements()) { ParentNode classNode = (ParentNode)children.nextElement(); sortNode(classNode, myComparator); myTreeModel.nodeStructureChanged(classNode); } restoreSelection(pair); } private static void sortNode(ParentNode node, final Comparator<? super ElementNode> sortComparator) { ArrayList<ElementNode> arrayList = new ArrayList<>(); Enumeration<TreeNode> children = node.children(); while (children.hasMoreElements()) { arrayList.add((ElementNode)children.nextElement()); } arrayList.sort(sortComparator); replaceChildren(node, arrayList); } private static void replaceChildren(final DefaultMutableTreeNode node, final Collection<? extends ElementNode> arrayList) { node.removeAllChildren(); for (ElementNode child : arrayList) { node.add(child); } } protected void restoreTree() { Pair<ElementNode, List<ElementNode>> selection = storeSelection(); DefaultMutableTreeNode root = getRootNode(); if (!myShowClasses || myContainerNodes.isEmpty()) { List<ParentNode> otherObjects = new ArrayList<>(); Enumeration<TreeNode> children = getRootNodeChildren(); ParentNode newRoot = new ParentNode(null, new MemberChooserObjectBase(getAllContainersNodeName()), new Ref<>(0)); while (children.hasMoreElements()) { final ParentNode nextElement = (ParentNode)children.nextElement(); if (nextElement instanceof ContainerNode) { final ContainerNode containerNode = (ContainerNode)nextElement; Enumeration<TreeNode> memberNodes = containerNode.children(); List<MemberNode> memberNodesList = new ArrayList<>(); while (memberNodes.hasMoreElements()) { memberNodesList.add((MemberNode)memberNodes.nextElement()); } for (MemberNode memberNode : memberNodesList) { newRoot.add(memberNode); } } else { otherObjects.add(nextElement); } } replaceChildren(root, otherObjects); sortNode(newRoot, myComparator); if (newRoot.children().hasMoreElements()) root.add(newRoot); } else { Enumeration<TreeNode> children = getRootNodeChildren(); while (children.hasMoreElements()) { ParentNode allClassesNode = (ParentNode)children.nextElement(); Enumeration<TreeNode> memberNodes = allClassesNode.children(); ArrayList<MemberNode> arrayList = new ArrayList<>(); while (memberNodes.hasMoreElements()) { arrayList.add((MemberNode)memberNodes.nextElement()); } arrayList.sort(myComparator); for (MemberNode memberNode : arrayList) { myNodeToParentMap.get(memberNode).add(memberNode); } } replaceChildren(root, myContainerNodes); } myTreeModel.nodeStructureChanged(root); defaultExpandTree(); restoreSelection(selection); } protected void setShowClasses(boolean showClasses) { myShowClasses = showClasses; restoreTree(); } protected @Nls(capitalization = Nls.Capitalization.Sentence) String getAllContainersNodeName() { return IdeBundle.message("node.memberchooser.all.classes"); } private Enumeration<TreeNode> getRootNodeChildren() { return getRootNode().children(); } protected DefaultMutableTreeNode getRootNode() { return (DefaultMutableTreeNode)myTreeModel.getRoot(); } private Pair<ElementNode,List<ElementNode>> storeSelection() { List<ElementNode> selectedNodes = new ArrayList<>(); TreePath[] paths = myTree.getSelectionPaths(); if (paths != null) { for (TreePath path : paths) { selectedNodes.add((ElementNode)path.getLastPathComponent()); } } TreePath leadSelectionPath = myTree.getLeadSelectionPath(); return Pair.create(leadSelectionPath != null ? (ElementNode)leadSelectionPath.getLastPathComponent() : null, selectedNodes); } private void restoreSelection(Pair<? extends ElementNode, ? extends List<ElementNode>> pair) { List<ElementNode> selectedNodes = pair.second; DefaultMutableTreeNode root = getRootNode(); ArrayList<TreePath> toSelect = new ArrayList<>(); for (ElementNode node : selectedNodes) { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)node; if (root.isNodeDescendant(treeNode)) { toSelect.add(new TreePath(treeNode.getPath())); } } if (!toSelect.isEmpty()) { myTree.setSelectionPaths(toTreePathArray(toSelect)); } ElementNode leadNode = pair.first; if (leadNode != null) { myTree.setLeadSelectionPath(new TreePath(((DefaultMutableTreeNode)leadNode).getPath())); } } @Override public void dispose() { PropertiesComponent instance = PropertiesComponent.getInstance(); instance.setValue(PROP_SORTED, isAlphabeticallySorted()); instance.setValue(PROP_SHOWCLASSES, myShowClasses); if (myCopyJavadocCheckbox != null) { instance.setValue(PROP_COPYJAVADOC, Boolean.toString(myCopyJavadocCheckbox.isSelected())); } final Container contentPane = getContentPane(); if (contentPane != null) { contentPane.removeAll(); } mySelectedNodes.clear(); myElements = null; super.dispose(); } @Nullable @Override public Object getData(@NotNull String dataId) { if (CommonDataKeys.PSI_ELEMENT.is(dataId)) { if (mySelectedElements != null && !mySelectedElements.isEmpty()) { T selectedElement = mySelectedElements.iterator().next(); return selectedElement instanceof ClassMemberWithElement ? ((ClassMemberWithElement)selectedElement).getElement() : null; } } return null; } private class MyTreeSelectionListener implements TreeSelectionListener { @Override public void valueChanged(TreeSelectionEvent e) { TreePath[] paths = e.getPaths(); if (paths == null) return; for (int i = 0; i < paths.length; i++) { Object node = paths[i].getLastPathComponent(); if (node instanceof MemberNode) { final MemberNode memberNode = (MemberNode)node; if (e.isAddedPath(i)) { if (!mySelectedNodes.contains(memberNode)) { mySelectedNodes.add(memberNode); } } else { mySelectedNodes.remove(memberNode); } } } mySelectedNodes.sort(new OrderComparator()); mySelectedElements = new LinkedHashSet<>(); for (MemberNode selectedNode : mySelectedNodes) { mySelectedElements.add((T)selectedNode.getDelegate()); } if (!myAllowEmptySelection) { setOKActionEnabled(!mySelectedElements.isEmpty()); } } } protected interface ElementNode extends MutableTreeNode { @NotNull MemberChooserObject getDelegate(); int getOrder(); } protected interface MemberNode extends ElementNode {} protected abstract static class ElementNodeImpl extends DefaultMutableTreeNode implements ElementNode { private final int myOrder; @NotNull private final MemberChooserObject myDelegate; public ElementNodeImpl(@Nullable DefaultMutableTreeNode parent, @NotNull MemberChooserObject delegate, Ref<Integer> order) { myOrder = order.get(); order.set(myOrder + 1); myDelegate = delegate; if (parent != null) { parent.add(this); } } @NotNull @Override public MemberChooserObject getDelegate() { return myDelegate; } @Override public int getOrder() { return myOrder; } } protected static class MemberNodeImpl extends ElementNodeImpl implements MemberNode { public MemberNodeImpl(ParentNode parent, @NotNull ClassMember delegate, Ref<Integer> order) { super(parent, delegate, order); } } protected static class ParentNode extends ElementNodeImpl { public ParentNode(@Nullable DefaultMutableTreeNode parent, MemberChooserObject delegate, Ref<Integer> order) { super(parent, delegate, order); } } protected static class ContainerNode extends ParentNode { public ContainerNode(DefaultMutableTreeNode parent, MemberChooserObject delegate, Ref<Integer> order) { super(parent, delegate, order); } } private class SelectNoneAction extends AbstractAction { SelectNoneAction() { super(IdeBundle.message("action.select.none")); } @Override public void actionPerformed(ActionEvent e) { myTree.clearSelection(); doOKAction(); } } private class TreeKeyListener extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { TreePath path = myTree.getLeadSelectionPath(); if (path == null) return; final Object lastComponent = path.getLastPathComponent(); if (e.getKeyCode() == KeyEvent.VK_ENTER) { if (lastComponent instanceof ParentNode) return; doOKAction(); e.consume(); } else if (e.getKeyCode() == KeyEvent.VK_INSERT) { if (lastComponent instanceof ElementNode) { final DefaultMutableTreeNode node = (DefaultMutableTreeNode)lastComponent; if (!mySelectedNodes.contains(node)) { if (node.getNextNode() != null) { myTree.setSelectionPath(new TreePath(node.getNextNode().getPath())); } } else { if (node.getNextNode() != null) { myTree.removeSelectionPath(new TreePath(node.getPath())); myTree.setSelectionPath(new TreePath(node.getNextNode().getPath())); myTree.repaint(); } } e.consume(); } } } } private class SortEmAction extends ToggleAction { SortEmAction() { super(PlatformEditorBundle.messagePointer("action.sort.alphabetically"), AllIcons.ObjectBrowser.Sorted); } @Override public boolean isSelected(@NotNull AnActionEvent event) { return isAlphabeticallySorted(); } @Override public void setSelected(@NotNull AnActionEvent event, boolean flag) { myAlphabeticallySorted = flag; setSortComparator(flag ? new AlphaComparator() : new OrderComparator()); if (flag) { MemberChooser.this.onAlphabeticalSortingEnabled(event); } } } protected ShowContainersAction getShowContainersAction() { return new ShowContainersAction(IdeBundle.messagePointer("action.show.classes"), PlatformIcons.CLASS_ICON); } protected class ShowContainersAction extends ToggleAction { public ShowContainersAction(@NotNull Supplier<@NlsActions.ActionText String> text, final Icon icon) { super(text, icon); } @Override public boolean isSelected(@NotNull AnActionEvent event) { return myShowClasses; } @Override public void setSelected(@NotNull AnActionEvent event, boolean flag) { setShowClasses(flag); } @Override public void update(@NotNull AnActionEvent e) { super.update(e); Presentation presentation = e.getPresentation(); presentation.setEnabled(myContainerNodes.size() > 1); } } private class ExpandAllAction extends AnAction { ExpandAllAction() { super(IdeBundle.messagePointer("action.expand.all"), AllIcons.Actions.Expandall); } @Override public void actionPerformed(@NotNull AnActionEvent e) { TreeUtil.expandAll(myTree); } } private class CollapseAllAction extends AnAction { CollapseAllAction() { super(IdeBundle.messagePointer("action.collapse.all"), AllIcons.Actions.Collapseall); } @Override public void actionPerformed(@NotNull AnActionEvent e) { TreeUtil.collapseAll(myTree, 1); } } private static class AlphaComparator implements Comparator<ElementNode> { @Override public int compare(ElementNode n1, ElementNode n2) { return n1.getDelegate().getText().compareToIgnoreCase(n2.getDelegate().getText()); } } protected static class OrderComparator implements Comparator<ElementNode> { public OrderComparator() { } // To make this class instantiable from the subclasses @Override public int compare(ElementNode n1, ElementNode n2) { if (n1.getDelegate() instanceof ClassMemberWithElement && n2.getDelegate() instanceof ClassMemberWithElement) { PsiElement element1 = ((ClassMemberWithElement)n1.getDelegate()).getElement(); PsiElement element2 = ((ClassMemberWithElement)n2.getDelegate()).getElement(); if (!(element1 instanceof PsiCompiledElement) && !(element2 instanceof PsiCompiledElement)) { final PsiFile file1 = element1.getContainingFile(); final PsiFile file2 = element2.getContainingFile(); if (Comparing.equal(file1, file2)) { return element1.getTextOffset() - element2.getTextOffset(); } else { if (file2 == null) return -1; if (file1 == null) return 1; return comparing(PsiFile::getVirtualFile, nullsLast(comparing(VirtualFile::getPath))).compare(file1, file2); } } } return n1.getOrder() - n2.getOrder(); } } private static class ElementNodeComparatorWrapper<T> implements Comparator<ElementNode> { private final Comparator<? super T> myDelegate; ElementNodeComparatorWrapper(final Comparator<? super T> delegate) { myDelegate = delegate; } @SuppressWarnings("unchecked") @Override public int compare(final ElementNode o1, final ElementNode o2) { return myDelegate.compare((T) o1.getDelegate(), (T) o2.getDelegate()); } } }
apache-2.0
madhav123/gkmaster
questionnaire/src/test/java/org/mifos/platform/questionnaire/ui/controller/SectionDetailFormTest.java
3065
/* * Copyright (c) 2005-2011 Grameen Foundation USA * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.platform.questionnaire.ui.controller; import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; import org.mifos.platform.questionnaire.service.SectionDetail; import org.mifos.platform.questionnaire.service.SectionQuestionDetail; import org.mifos.platform.questionnaire.service.QuestionDetail; import org.mifos.platform.questionnaire.service.QuestionType; import org.mifos.platform.questionnaire.ui.model.SectionDetailForm; import org.mifos.platform.questionnaire.ui.model.SectionQuestionDetailForm; import org.mockito.runners.MockitoJUnitRunner; import java.util.List; import static org.junit.Assert.assertThat; @RunWith(MockitoJUnitRunner.class) public class SectionDetailFormTest { @Test public void shouldGetQuestions() { SectionDetailForm sectionDetailForm = new SectionDetailForm(getSectionDefinition()); List<SectionQuestionDetailForm> sectionQuestions = sectionDetailForm.getSectionQuestions(); assertThat(sectionQuestions, Matchers.notNullValue()); assertThat(sectionQuestions.size(), Matchers.is(3)); assertQuestionDetailForm(sectionQuestions.get(0), 121, "Question1", true); assertQuestionDetailForm(sectionQuestions.get(1), 122, "Question2", false); assertQuestionDetailForm(sectionQuestions.get(2), 123, "Question3", true); } private void assertQuestionDetailForm(SectionQuestionDetailForm questionDetailForm, int id, String title, boolean mandatory) { assertThat(questionDetailForm.getQuestionId(), Matchers.is(id)); assertThat(questionDetailForm.getText(), Matchers.is(title)); assertThat(questionDetailForm.isMandatory(), Matchers.is(mandatory)); } private SectionDetail getSectionDefinition() { SectionDetail sectionDetail = new SectionDetail(); sectionDetail.addQuestion(new SectionQuestionDetail(new QuestionDetail(121, "Question1", QuestionType.FREETEXT, true, true), true)); sectionDetail.addQuestion(new SectionQuestionDetail(new QuestionDetail(122, "Question2", QuestionType.FREETEXT, true, true), false)); sectionDetail.addQuestion(new SectionQuestionDetail(new QuestionDetail(123, "Question3", QuestionType.FREETEXT, true, true), true)); return sectionDetail; } }
apache-2.0
hasinitg/airavata
modules/workflow-model/workflow-engine/src/main/java/org/apache/airavata/workflow/engine/WorkflowEngineImpl.java
4497
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.workflow.engine; import org.apache.airavata.registry.cpi.WorkflowCatalog; import org.apache.airavata.common.exception.AiravataException; import org.apache.airavata.common.utils.ServerSettings; import org.apache.airavata.messaging.core.Publisher; import org.apache.airavata.messaging.core.impl.RabbitMQStatusPublisher; import org.apache.airavata.model.error.AiravataClientConnectException; import org.apache.airavata.model.experiment.ExperimentModel; import org.apache.airavata.orchestrator.client.OrchestratorClientFactory; import org.apache.airavata.orchestrator.cpi.OrchestratorService; import org.apache.airavata.registry.core.experiment.catalog.impl.RegistryFactory; import org.apache.airavata.registry.cpi.ExperimentCatalog; import org.apache.airavata.registry.cpi.ExperimentCatalogModelType; import org.apache.airavata.registry.cpi.RegistryException; import org.apache.airavata.workflow.catalog.WorkflowCatalogFactory; import org.apache.airavata.workflow.engine.interpretor.WorkflowInterpreter; import org.apache.airavata.workflow.engine.interpretor.WorkflowInterpreterConfiguration; import org.apache.airavata.workflow.model.exceptions.WorkflowException; import org.apache.airavata.workflow.model.wf.Workflow; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WorkflowEngineImpl implements WorkflowEngine { private static final Logger logger = LoggerFactory.getLogger(WorkflowEngineImpl.class); private Publisher rabbitMQPublisher; WorkflowEngineImpl() { try { rabbitMQPublisher = new RabbitMQStatusPublisher(); } catch (Exception e) { logger.error("Failed to instantiate RabbitMQPublisher", e); } } @Override public void launchExperiment(String experimentId, String token) throws WorkflowEngineException { try { ExperimentCatalog experimentCatalog = RegistryFactory.getDefaultExpCatalog(); Experiment experiment = (Experiment) experimentCatalog.get(ExperimentCatalogModelType.EXPERIMENT, experimentId); WorkflowCatalog workflowCatalog = WorkflowCatalogFactory.getWorkflowCatalog(); WorkflowInterpreterConfiguration config = new WorkflowInterpreterConfiguration(new Workflow(workflowCatalog.getWorkflow(experiment.getApplicationId()).getGraph())); final WorkflowInterpreter workflowInterpreter = new WorkflowInterpreter(experiment, token, config , getOrchestratorClient(), rabbitMQPublisher); new Thread(){ public void run() { try { workflowInterpreter.scheduleDynamically(); } catch (WorkflowException e) { logger.error(e.getMessage(), e); } catch (RegistryException e) { logger.error(e.getMessage(), e); } catch (AiravataException e) { logger.error(e.getMessage(), e); } }; }.start(); } catch (Exception e) { logger.error("Error while retrieving the experiment", e); WorkflowEngineException exception = new WorkflowEngineException("Error while launching the workflow experiment. More info : " + e.getMessage()); throw exception; } } private OrchestratorService.Client getOrchestratorClient() throws AiravataClientConnectException{ final int serverPort = Integer.parseInt(ServerSettings.getSetting(org.apache.airavata.common.utils.Constants.ORCHESTRATOR_SERVER_PORT,"8940")); final String serverHost = ServerSettings.getSetting(org.apache.airavata.common.utils.Constants.ORCHESTRATOR_SERVER_HOST, null); return OrchestratorClientFactory.createOrchestratorClient(serverHost, serverPort); } }
apache-2.0
liveqmock/platform-tools-idea
plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/conversions/IndexedExpressionConversionPredicate.java
2533
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.intentions.conversions; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import org.jetbrains.plugins.groovy.intentions.base.ErrorUtil; import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate; import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty; class IndexedExpressionConversionPredicate implements PsiElementPredicate { public boolean satisfiedBy(PsiElement element) { if (!(element instanceof GrIndexProperty)) return false; if (ErrorUtil.containsError(element)) return false; final GrIndexProperty arrayIndexExpression = (GrIndexProperty) element; final PsiElement lastChild = arrayIndexExpression.getLastChild(); if (!(lastChild instanceof GrArgumentList)) return false; final GrArgumentList argList = (GrArgumentList) lastChild; final GrExpression[] arguments = argList.getExpressionArguments(); if (arguments.length != 1) return false; final PsiElement parent = element.getParent(); if (!(parent instanceof GrAssignmentExpression)) { return true; } final GrAssignmentExpression assignmentExpression = (GrAssignmentExpression) parent; final GrExpression rvalue = assignmentExpression.getRValue(); if (rvalue == null) return false; if (rvalue.equals(element)) return true; final IElementType operator = assignmentExpression.getOperationTokenType(); return GroovyTokenTypes.mASSIGN.equals(operator); } }
apache-2.0
objectiser/camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/tx/JmsToJmsTransactedTest.java
4933
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.jms.tx; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.spring.CamelSpringTestSupport; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; public class JmsToJmsTransactedTest extends CamelSpringTestSupport { @Override protected ClassPathXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("/org/apache/camel/component/jms/tx/JmsToJmsTransactedTest.xml"); } @Test public void testJmsToJmsTestOK() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("activemq:queue:foo") .transacted() .to("activemq:queue:bar"); } }); context.start(); template.sendBody("activemq:queue:foo", "Hello World"); String reply = consumer.receiveBody("activemq:queue:bar", 5000, String.class); assertEquals("Hello World", reply); } @Test public void testJmsToJmsTestRollbackDueToException() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("activemq:queue:foo") .transacted() .to("mock:start") .to("activemq:queue:bar") .throwException(new IllegalArgumentException("Damn")); from("activemq:queue:bar").to("log:bar").to("mock:bar"); } }); context.start(); MockEndpoint bar = getMockEndpoint("mock:bar"); bar.expectedMessageCount(0); MockEndpoint start = getMockEndpoint("mock:start"); start.expectedMessageCount(7); // default number of redeliveries by AMQ is 6 so we get 6+1 template.sendBody("activemq:queue:foo", "Hello World"); assertMockEndpointsSatisfied(); } @Test public void testJmsToJmsTestRollbackDueToRollback() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("activemq:queue:foo") .transacted() .to("mock:start") .to("activemq:queue:bar") .rollback(); from("activemq:queue:bar").to("log:bar").to("mock:bar"); } }); context.start(); MockEndpoint bar = getMockEndpoint("mock:bar"); bar.expectedMessageCount(0); MockEndpoint start = getMockEndpoint("mock:start"); start.expectedMessageCount(7); // default number of redeliveries by AMQ is 6 so we get 6+1 template.sendBody("activemq:queue:foo", "Hello World"); assertMockEndpointsSatisfied(); // it should be moved to DLQ in JMS broker Object body = consumer.receiveBody("activemq:queue:ActiveMQ.DLQ", 2000); assertEquals("Hello World", body); } @Test public void testJmsToJmsTestRollbackDueToMarkRollbackOnly() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("activemq:queue:foo") .transacted() .to("mock:start") .to("activemq:queue:bar") .markRollbackOnly(); from("activemq:queue:bar").to("log:bar").to("mock:bar"); } }); context.start(); MockEndpoint bar = getMockEndpoint("mock:bar"); bar.expectedMessageCount(0); MockEndpoint start = getMockEndpoint("mock:start"); start.expectedMessageCount(7); // default number of redeliveries by AMQ is 6 so we get 6+1 template.sendBody("activemq:queue:foo", "Hello World"); assertMockEndpointsSatisfied(); } }
apache-2.0
WillJiang/WillJiang
src/plugins/osgi/src/main/java/org/apache/struts2/osgi/DefaultBundleAccessor.java
7481
/* * $Id$ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.struts2.osgi; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.ActionProxy; import com.opensymphony.xwork2.config.entities.ActionConfig; import com.opensymphony.xwork2.util.logging.Logger; import com.opensymphony.xwork2.util.logging.LoggerFactory; import org.apache.struts2.osgi.host.OsgiHost; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Helper class that find resources and loads classes from the list of bundles */ public class DefaultBundleAccessor implements BundleAccessor { private static DefaultBundleAccessor self; private static final Logger LOG = LoggerFactory.getLogger(DefaultBundleAccessor.class); private BundleContext bundleContext; private Map<String, String> packageToBundle = new HashMap<String, String>(); private Map<Bundle, Set<String>> packagesByBundle = new HashMap<Bundle, Set<String>>(); private OsgiHost osgiHost; public DefaultBundleAccessor() { self = this; } public static DefaultBundleAccessor getInstance() { return self; } public Object getService(ServiceReference ref) { return bundleContext != null ? bundleContext.getService(ref) : null; } public ServiceReference getServiceReference(String className) { return bundleContext != null ? bundleContext.getServiceReference(className) : null; } public ServiceReference[] getAllServiceReferences(String className) { if (bundleContext != null) { try { return bundleContext.getServiceReferences(className, null); } catch (InvalidSyntaxException e) { //cannot happen we are passing null as the param if (LOG.isErrorEnabled()) LOG.error("Invalid syntax for service lookup", e); } } return null; } public ServiceReference[] getServiceReferences(String className, String params) throws InvalidSyntaxException { return bundleContext != null ? bundleContext.getServiceReferences(className, params) : null; } /** * Add as Bundle -> Package mapping * @param bundle the bundle where the package was loaded from * @param packageName the anme of the loaded package */ public void addPackageFromBundle(Bundle bundle, String packageName) { this.packageToBundle.put(packageName, bundle.getSymbolicName()); Set<String> pkgs = packagesByBundle.get(bundle); if (pkgs == null) { pkgs = new HashSet<String>(); packagesByBundle.put(bundle, pkgs); } pkgs.add(packageName); } public Class<?> loadClass(String className) throws ClassNotFoundException { Bundle bundle = getCurrentBundle(); if (bundle != null) { Class cls = bundle.loadClass(className); if (LOG.isTraceEnabled()) LOG.trace("Located class [#0] in bundle [#1]", className, bundle.getSymbolicName()); return cls; } throw new ClassNotFoundException("Unable to find class " + className); } private Bundle getCurrentBundle() { ActionContext ctx = ActionContext.getContext(); String bundleName = (String) ctx.get(CURRENT_BUNDLE_NAME); if (bundleName == null) { ActionInvocation inv = ctx.getActionInvocation(); ActionProxy proxy = inv.getProxy(); ActionConfig actionConfig = proxy.getConfig(); bundleName = packageToBundle.get(actionConfig.getPackageName()); } if (bundleName != null) { return osgiHost.getActiveBundles().get(bundleName); } return null; } public List<URL> loadResources(String name) throws IOException { return loadResources(name, false); } public List<URL> loadResources(String name, boolean translate) throws IOException { Bundle bundle = getCurrentBundle(); if (bundle != null) { List<URL> resources = new ArrayList<URL>(); Enumeration e = bundle.getResources(name); if (e != null) { while (e.hasMoreElements()) { resources.add(translate ? OsgiUtil.translateBundleURLToJarURL((URL) e.nextElement(), getCurrentBundle()) : (URL) e.nextElement()); } } return resources; } return null; } public URL loadResourceFromAllBundles(String name) throws IOException { for (Map.Entry<String, Bundle> entry : osgiHost.getActiveBundles().entrySet()) { Enumeration e = entry.getValue().getResources(name); if (e != null && e.hasMoreElements()) { return (URL) e.nextElement(); } } return null; } public InputStream loadResourceFromAllBundlesAsStream(String name) throws IOException { URL url = loadResourceFromAllBundles(name); if (url != null) { return url.openStream(); } return null; } public URL loadResource(String name) { return loadResource(name, false); } public URL loadResource(String name, boolean translate) { Bundle bundle = getCurrentBundle(); if (bundle != null) { URL url = bundle.getResource(name); try { return translate ? OsgiUtil.translateBundleURLToJarURL(url, getCurrentBundle()) : url; } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unable to translate bundle URL to jar URL", e); } return null; } } return null; } public Set<String> getPackagesByBundle(Bundle bundle) { return packagesByBundle.get(bundle); } public InputStream loadResourceAsStream(String name) throws IOException { URL url = loadResource(name); if (url != null) { return url.openStream(); } return null; } public void setBundleContext(BundleContext bundleContext) { this.bundleContext = bundleContext; } public void setOsgiHost(OsgiHost osgiHost) { this.osgiHost = osgiHost; } }
apache-2.0
jjeb/kettle-trunk
ui/src/org/pentaho/di/ui/trans/steps/creditcardvalidator/CreditCardValidatorDialog.java
13899
/******************************************************************************* * * Pentaho Data Integration * * Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.ui.trans.steps.creditcardvalidator; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDialogInterface; import org.pentaho.di.trans.steps.creditcardvalidator.CreditCardValidatorMeta; import org.pentaho.di.ui.core.dialog.ErrorDialog; import org.pentaho.di.ui.core.widget.TextVar; import org.pentaho.di.ui.trans.step.BaseStepDialog; public class CreditCardValidatorDialog extends BaseStepDialog implements StepDialogInterface { private static Class<?> PKG = CreditCardValidatorMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private boolean gotPreviousFields=false; private Label wlFieldName; private CCombo wFieldName; private FormData fdlFieldName, fdFieldName; private Label wlResult,wlCardType; private TextVar wResult,wFileType; private FormData fdlResult, fdResult,fdAdditionalFields,fdlCardType,fdCardType; private Label wlNotValidMsg; private TextVar wNotValidMsg; private FormData fdlNotValidMsg,fdNotValidMsg; private Label wlgetOnlyDigits; private Button wgetOnlyDigits; private FormData fdlgetOnlyDigits, fdgetOnlyDigits; private Group wOutputFields; private CreditCardValidatorMeta input; public CreditCardValidatorDialog(Shell parent, Object in, TransMeta transMeta, String sname) { super(parent, (BaseStepMeta)in, transMeta, sname); input=(CreditCardValidatorMeta)in; } public String open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN); props.setLook(shell); setShellImage(shell, input); ModifyListener lsMod = new ModifyListener() { public void modifyText(ModifyEvent e) { input.setChanged(); } }; changed = input.hasChanged(); FormLayout formLayout = new FormLayout (); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); shell.setText(BaseMessages.getString(PKG, "CreditCardValidatorDialog.Shell.Title")); //$NON-NLS-1$ int middle = props.getMiddlePct(); int margin=Const.MARGIN; // Stepname line wlStepname=new Label(shell, SWT.RIGHT); wlStepname.setText(BaseMessages.getString(PKG, "CreditCardValidatorDialog.Stepname.Label")); //$NON-NLS-1$ props.setLook(wlStepname); fdlStepname=new FormData(); fdlStepname.left = new FormAttachment(0, 0); fdlStepname.right= new FormAttachment(middle, -margin); fdlStepname.top = new FormAttachment(0, margin); wlStepname.setLayoutData(fdlStepname); wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wStepname.setText(stepname); props.setLook(wStepname); wStepname.addModifyListener(lsMod); fdStepname=new FormData(); fdStepname.left = new FormAttachment(middle, 0); fdStepname.top = new FormAttachment(0, margin); fdStepname.right= new FormAttachment(100, 0); wStepname.setLayoutData(fdStepname); // filename field wlFieldName=new Label(shell, SWT.RIGHT); wlFieldName.setText(BaseMessages.getString(PKG, "CreditCardValidatorDialog.FieldName.Label")); //$NON-NLS-1$ props.setLook(wlFieldName); fdlFieldName=new FormData(); fdlFieldName.left = new FormAttachment(0, 0); fdlFieldName.right= new FormAttachment(middle, -margin); fdlFieldName.top = new FormAttachment(wStepname, margin); wlFieldName.setLayoutData(fdlFieldName); wFieldName=new CCombo(shell, SWT.BORDER | SWT.READ_ONLY); props.setLook(wFieldName); wFieldName.addModifyListener(lsMod); fdFieldName=new FormData(); fdFieldName.left = new FormAttachment(middle, 0); fdFieldName.top = new FormAttachment(wStepname, margin); fdFieldName.right= new FormAttachment(100, -margin); wFieldName.setLayoutData(fdFieldName); wFieldName.addFocusListener(new FocusListener() { public void focusLost(org.eclipse.swt.events.FocusEvent e) { } public void focusGained(org.eclipse.swt.events.FocusEvent e) { Cursor busy = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT); shell.setCursor(busy); get(); shell.setCursor(null); busy.dispose(); } } ); // get only digits? wlgetOnlyDigits=new Label(shell, SWT.RIGHT); wlgetOnlyDigits.setText(BaseMessages.getString(PKG, "CreditCardValidator.getOnlyDigits.Label")); props.setLook(wlgetOnlyDigits); fdlgetOnlyDigits=new FormData(); fdlgetOnlyDigits.left = new FormAttachment(0, 0); fdlgetOnlyDigits.top = new FormAttachment(wFieldName, margin); fdlgetOnlyDigits.right= new FormAttachment(middle, -margin); wlgetOnlyDigits.setLayoutData(fdlgetOnlyDigits); wgetOnlyDigits=new Button(shell, SWT.CHECK ); props.setLook(wgetOnlyDigits); wgetOnlyDigits.setToolTipText(BaseMessages.getString(PKG, "CreditCardValidator.getOnlyDigits.Tooltip")); fdgetOnlyDigits=new FormData(); fdgetOnlyDigits.left = new FormAttachment(middle, 0); fdgetOnlyDigits.top = new FormAttachment(wFieldName, margin); wgetOnlyDigits.setLayoutData(fdgetOnlyDigits); ///////////////////////////////// // START OF Output Fields GROUP // ///////////////////////////////// wOutputFields = new Group(shell, SWT.SHADOW_NONE); props.setLook(wOutputFields); wOutputFields.setText(BaseMessages.getString(PKG, "CreditCardValidatorDialog.OutputFields.Label")); FormLayout OutputFieldsgroupLayout = new FormLayout(); OutputFieldsgroupLayout.marginWidth = 10; OutputFieldsgroupLayout.marginHeight = 10; wOutputFields.setLayout(OutputFieldsgroupLayout); // Result fieldname ... wlResult=new Label(wOutputFields, SWT.RIGHT); wlResult.setText(BaseMessages.getString(PKG, "CreditCardValidatorDialog.ResultField.Label")); //$NON-NLS-1$ props.setLook(wlResult); fdlResult=new FormData(); fdlResult.left = new FormAttachment(0, -margin); fdlResult.right= new FormAttachment(middle, -2*margin); fdlResult.top = new FormAttachment(wgetOnlyDigits, 2*margin); wlResult.setLayoutData(fdlResult); wResult=new TextVar(transMeta,wOutputFields, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wResult.setToolTipText(BaseMessages.getString(PKG, "CreditCardValidatorDialog.ResultField.Tooltip")); props.setLook(wResult); wResult.addModifyListener(lsMod); fdResult=new FormData(); fdResult.left = new FormAttachment(middle, -margin); fdResult.top = new FormAttachment(wgetOnlyDigits, 2*margin); fdResult.right= new FormAttachment(100, 0); wResult.setLayoutData(fdResult); // FileType fieldname ... wlCardType=new Label(wOutputFields, SWT.RIGHT); wlCardType.setText(BaseMessages.getString(PKG, "CreditCardValidatorDialog.CardType.Label")); //$NON-NLS-1$ props.setLook(wlCardType); fdlCardType=new FormData(); fdlCardType.left = new FormAttachment(0, -margin); fdlCardType.right= new FormAttachment(middle, -2*margin); fdlCardType.top = new FormAttachment(wResult, margin); wlCardType.setLayoutData(fdlCardType); wFileType=new TextVar(transMeta,wOutputFields, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wFileType.setToolTipText(BaseMessages.getString(PKG, "CreditCardValidatorDialog.CardType.Tooltip")); props.setLook(wFileType); wFileType.addModifyListener(lsMod); fdCardType=new FormData(); fdCardType.left = new FormAttachment(middle, -margin); fdCardType.top = new FormAttachment(wResult, margin); fdCardType.right= new FormAttachment(100, 0); wFileType.setLayoutData(fdCardType); // UnvalidMsg fieldname ... wlNotValidMsg=new Label(wOutputFields, SWT.RIGHT); wlNotValidMsg.setText(BaseMessages.getString(PKG, "CreditCardValidatorDialog.NotValidMsg.Label")); //$NON-NLS-1$ props.setLook(wlNotValidMsg); fdlNotValidMsg=new FormData(); fdlNotValidMsg.left = new FormAttachment(0, -margin); fdlNotValidMsg.right= new FormAttachment(middle, -2*margin); fdlNotValidMsg.top = new FormAttachment(wFileType, margin); wlNotValidMsg.setLayoutData(fdlNotValidMsg); wNotValidMsg=new TextVar(transMeta,wOutputFields, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wNotValidMsg.setToolTipText(BaseMessages.getString(PKG, "CreditCardValidatorDialog.NotValidMsg.Tooltip")); props.setLook(wNotValidMsg); wNotValidMsg.addModifyListener(lsMod); fdNotValidMsg=new FormData(); fdNotValidMsg.left = new FormAttachment(middle, -margin); fdNotValidMsg.top = new FormAttachment(wFileType, margin); fdNotValidMsg.right= new FormAttachment(100, 0); wNotValidMsg.setLayoutData(fdNotValidMsg); fdAdditionalFields = new FormData(); fdAdditionalFields.left = new FormAttachment(0, margin); fdAdditionalFields.top = new FormAttachment(wgetOnlyDigits, 2*margin); fdAdditionalFields.right = new FormAttachment(100, -margin); wOutputFields.setLayoutData(fdAdditionalFields); ///////////////////////////////// // END OF Additional Fields GROUP // ///////////////////////////////// // THE BUTTONS wOK=new Button(shell, SWT.PUSH); wOK.setText(BaseMessages.getString(PKG, "System.Button.OK")); //$NON-NLS-1$ wCancel=new Button(shell, SWT.PUSH); wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); //$NON-NLS-1$ setButtonPositions(new Button[] { wOK, wCancel }, margin, wOutputFields); // Add listeners lsOK = new Listener() { public void handleEvent(Event e) { ok(); } }; lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } }; wOK.addListener (SWT.Selection, lsOK ); wCancel.addListener(SWT.Selection, lsCancel); lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } }; wStepname.addSelectionListener( lsDef ); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } ); // Set the shell size, based upon previous time... setSize(); getData(); input.setChanged(changed); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return stepname; } /** * Copy information from the meta-data input to the dialog fields. */ public void getData() { if (input.getDynamicField() !=null) wFieldName.setText(input.getDynamicField()); wgetOnlyDigits.setSelection(input.isOnlyDigits()); if (input.getResultFieldName()!=null) wResult.setText(input.getResultFieldName()); if (input.getCardType()!=null) wFileType.setText(input.getCardType()); if (input.getNotValidMsg()!=null) wNotValidMsg.setText(input.getNotValidMsg()); wStepname.selectAll(); } private void cancel() { stepname=null; input.setChanged(changed); dispose(); } private void ok() { if (Const.isEmpty(wStepname.getText())) return; input.setDynamicField(wFieldName.getText() ); input.setOnlyDigits(wgetOnlyDigits.getSelection()); input.setResultFieldName(wResult.getText() ); input.setCardType(wFileType.getText() ); input.setNotValidMsg(wNotValidMsg.getText() ); stepname = wStepname.getText(); // return value dispose(); } private void get() { if(!gotPreviousFields) { try { String columnName = wFieldName.getText(); wFieldName.removeAll(); RowMetaInterface r = transMeta.getPrevStepFields(stepname); if (r != null) { r.getFieldNames(); for (int i = 0; i < r.getFieldNames().length; i++) { wFieldName.add(r.getFieldNames()[i]); } } wFieldName.setText(columnName); gotPreviousFields=true; } catch (KettleException ke) { new ErrorDialog(shell, BaseMessages.getString(PKG, "CreditCardValidatorDialog.FailedToGetFields.DialogTitle"), BaseMessages.getString(PKG, "CreditCardValidatorDialog.FailedToGetFields.DialogMessage"), ke); //$NON-NLS-1$ //$NON-NLS-2$ } } } }
apache-2.0
javazhangtao/nifty
nifty-core/src/main/java/com/facebook/nifty/codec/ThriftFrameCodecFactory.java
876
/* * Copyright (C) 2012-2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.nifty.codec; import org.apache.thrift.protocol.TProtocolFactory; import org.jboss.netty.channel.ChannelHandler; public interface ThriftFrameCodecFactory { public ChannelHandler create(int maxFrameSize, TProtocolFactory defaultProtocolFactory); }
apache-2.0
camunda/camunda-engine-dmn
feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelSyntaxException.java
1653
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.dmn.feel.impl.juel; import org.camunda.bpm.dmn.feel.impl.FeelException; /** * Exception thrown if the syntax of a FEEL expression is invalid. */ public class FeelSyntaxException extends FeelException { protected String feelExpression; protected String description; public FeelSyntaxException(String message, String feelExpression, String description) { super(message); this.feelExpression = feelExpression; this.description = description; } public FeelSyntaxException(String message, String feelExpression, String description, Throwable cause) { super(message, cause); this.feelExpression = feelExpression; this.description = description; } public String getFeelExpression() { return feelExpression; } public String getDescription() { return description; } }
apache-2.0
nishantmonu51/hive
common/src/java/org/apache/hadoop/hive/conf/LoopingByteArrayInputStream.java
3631
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.conf; import org.apache.hive.common.util.SuppressFBWarnings; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; /** * LoopingByteArrayInputStream. * * This was designed specifically to handle the problem in Hadoop's Configuration object that it * tries to read the entire contents of the same InputStream repeatedly without resetting it. * * The Configuration object does attempt to close the InputStream though, so, since close does * nothing for the ByteArrayInputStream object, override it to reset it. * * It also uses a thread local ByteArrayInputStream for method calls. This is because * Configuration's copy constructor does a shallow copy of the resources, meaning that when the * copy constructor is used to generate HiveConfs in different threads, they all share the same * LoopingByteArrayInputStream. ByteArrayInputStreams are not thread safe in such situations. */ public class LoopingByteArrayInputStream extends InputStream { private final byte[] buf; @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Intended") public LoopingByteArrayInputStream(byte[] buf) { this.buf = buf; } private final ThreadLocal<ByteArrayInputStream> threadLocalByteArrayInputStream = new ThreadLocal<ByteArrayInputStream>() { @Override protected ByteArrayInputStream initialValue() { return null; } }; private ByteArrayInputStream getByteArrayInputStream() { ByteArrayInputStream bais = threadLocalByteArrayInputStream.get(); if (bais == null) { bais = new ByteArrayInputStream(buf); threadLocalByteArrayInputStream.set(bais); } return bais; } @Override public synchronized int available() { return getByteArrayInputStream().available(); } @Override public void mark(int arg0) { getByteArrayInputStream().mark(arg0); } @Override public boolean markSupported() { return getByteArrayInputStream().markSupported(); } @Override public synchronized int read() { return getByteArrayInputStream().read(); } @Override public synchronized int read(byte[] arg0, int arg1, int arg2) { return getByteArrayInputStream().read(arg0, arg1, arg2); } @Override public synchronized void reset() { getByteArrayInputStream().reset(); } @Override public synchronized long skip(long arg0) { return getByteArrayInputStream().skip(arg0); } @Override public int read(byte[] arg0) throws IOException { return getByteArrayInputStream().read(arg0); } @Override public void close() throws IOException { getByteArrayInputStream().reset(); // According to the Java documentation this does nothing, but just in case getByteArrayInputStream().close(); } }
apache-2.0
jwren/intellij-community
plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/fromObject/fromCompanion/staticLateinit/Read.java
106
public class Read { public static void main(String[] args) { Main.getStaticLateinit(); } }
apache-2.0
winningsix/hive
spark-client/src/main/java/org/apache/hive/spark/client/JobContextImpl.java
2285
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hive.spark.client; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.hive.spark.counter.SparkCounters; import org.apache.spark.api.java.JavaFutureAction; import org.apache.spark.api.java.JavaSparkContext; class JobContextImpl implements JobContext { private final JavaSparkContext sc; private final ThreadLocal<MonitorCallback> monitorCb; private final Map<String, List<JavaFutureAction<?>>> monitoredJobs; private final List<String> addedJars; public JobContextImpl(JavaSparkContext sc) { this.sc = sc; this.monitorCb = new ThreadLocal<MonitorCallback>(); monitoredJobs = new ConcurrentHashMap<String, List<JavaFutureAction<?>>>(); addedJars = new CopyOnWriteArrayList<String>(); } @Override public JavaSparkContext sc() { return sc; } @Override public <T> JavaFutureAction<T> monitor(JavaFutureAction<T> job, SparkCounters sparkCounters, Set<Integer> cachedRDDIds) { monitorCb.get().call(job, sparkCounters, cachedRDDIds); return job; } @Override public Map<String, List<JavaFutureAction<?>>> getMonitoredJobs() { return monitoredJobs; } @Override public List<String> getAddedJars() { return addedJars; } void setMonitorCb(MonitorCallback cb) { monitorCb.set(cb); } void stop() { monitoredJobs.clear(); sc.stop(); } }
apache-2.0
lankavitharana/siddhi
modules/siddhi-core/src/main/java/org/wso2/siddhi/core/query/selector/attribute/processor/AggregationAttributeProcessor.java
2255
/* * Copyright (c) 2005-2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.siddhi.core.query.selector.attribute.processor; import org.wso2.siddhi.core.config.SiddhiContext; import org.wso2.siddhi.core.event.AtomicEvent; import org.wso2.siddhi.core.query.selector.attribute.factory.OutputAttributeAggregatorFactory; import org.wso2.siddhi.core.query.selector.attribute.handler.OutputAttributeAggregator; import org.wso2.siddhi.query.api.expression.Expression; import org.wso2.siddhi.query.api.query.QueryEventSource; import java.util.List; public class AggregationAttributeProcessor extends AbstractAggregationAttributeProcessor implements NonGroupingAttributeProcessor { private OutputAttributeAggregator outputAttributeAggregator; public AggregationAttributeProcessor(Expression[] expressions, List<QueryEventSource> queryEventSourceList, OutputAttributeAggregatorFactory outputAttributeAggregatorFactory, String elementId, SiddhiContext siddhiContext) { super(expressions, queryEventSourceList, outputAttributeAggregatorFactory, elementId, siddhiContext); this.outputAttributeAggregator = sampleOutputAttributeAggregator; } public synchronized Object process(AtomicEvent event) { return process(event, outputAttributeAggregator); } @Override public void lock() { } @Override public void unlock() { } @Override protected Object[] currentState() { return new Object[]{outputAttributeAggregator}; } @Override protected void restoreState(Object[] data) { outputAttributeAggregator = (OutputAttributeAggregator) data[0]; } }
apache-2.0
sunchao/presto
presto-base-jdbc/src/test/java/com/facebook/presto/plugin/jdbc/TestJdbcMetadata.java
8508
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.plugin.jdbc; import com.facebook.presto.spi.ColumnMetadata; import com.facebook.presto.spi.ConnectorTableMetadata; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.SchemaTableName; import com.facebook.presto.spi.TableNotFoundException; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static com.facebook.presto.plugin.jdbc.TestingDatabase.CONNECTOR_ID; import static com.facebook.presto.spi.StandardErrorCode.NOT_FOUND; import static com.facebook.presto.spi.StandardErrorCode.PERMISSION_DENIED; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static com.facebook.presto.testing.TestingConnectorSession.SESSION; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; @Test(singleThreaded = true) public class TestJdbcMetadata { private TestingDatabase database; private JdbcMetadata metadata; private JdbcTableHandle tableHandle; @BeforeMethod public void setUp() throws Exception { database = new TestingDatabase(); metadata = new JdbcMetadata(new JdbcConnectorId(CONNECTOR_ID), database.getJdbcClient(), new JdbcMetadataConfig()); tableHandle = metadata.getTableHandle(SESSION, new SchemaTableName("example", "numbers")); } @AfterMethod(alwaysRun = true) public void tearDown() throws Exception { database.close(); } @Test public void testListSchemaNames() { assertTrue(metadata.listSchemaNames(SESSION).containsAll(ImmutableSet.of("example", "tpch"))); } @Test public void testGetTableHandle() { JdbcTableHandle tableHandle = metadata.getTableHandle(SESSION, new SchemaTableName("example", "numbers")); assertEquals(metadata.getTableHandle(SESSION, new SchemaTableName("example", "numbers")), tableHandle); assertNull(metadata.getTableHandle(SESSION, new SchemaTableName("example", "unknown"))); assertNull(metadata.getTableHandle(SESSION, new SchemaTableName("unknown", "numbers"))); assertNull(metadata.getTableHandle(SESSION, new SchemaTableName("unknown", "unknown"))); } @Test public void testGetColumnHandles() { // known table assertEquals(metadata.getColumnHandles(SESSION, tableHandle), ImmutableMap.of( "text", new JdbcColumnHandle(CONNECTOR_ID, "TEXT", VARCHAR), "value", new JdbcColumnHandle(CONNECTOR_ID, "VALUE", BIGINT))); // unknown table unknownTableColumnHandle(new JdbcTableHandle(CONNECTOR_ID, new SchemaTableName("unknown", "unknown"), "unknown", "unknown", "unknown")); unknownTableColumnHandle(new JdbcTableHandle(CONNECTOR_ID, new SchemaTableName("example", "numbers"), null, "example", "unknown")); } private void unknownTableColumnHandle(JdbcTableHandle tableHandle) { try { metadata.getColumnHandles(SESSION, tableHandle); fail("Expected getColumnHandle of unknown table to throw a TableNotFoundException"); } catch (TableNotFoundException ignored) { } } @Test public void getTableMetadata() { // known table ConnectorTableMetadata tableMetadata = metadata.getTableMetadata(SESSION, tableHandle); assertEquals(tableMetadata.getTable(), new SchemaTableName("example", "numbers")); assertEquals(tableMetadata.getColumns(), ImmutableList.of( new ColumnMetadata("text", VARCHAR), new ColumnMetadata("value", BIGINT))); // escaping name patterns JdbcTableHandle specialTableHandle = metadata.getTableHandle(SESSION, new SchemaTableName("exa_ple", "num_ers")); ConnectorTableMetadata specialTableMetadata = metadata.getTableMetadata(SESSION, specialTableHandle); assertEquals(specialTableMetadata.getTable(), new SchemaTableName("exa_ple", "num_ers")); assertEquals(specialTableMetadata.getColumns(), ImmutableList.of( new ColumnMetadata("te_t", VARCHAR), new ColumnMetadata("va%ue", BIGINT))); // unknown tables should produce null unknownTableMetadata(new JdbcTableHandle(CONNECTOR_ID, new SchemaTableName("u", "numbers"), null, "unknown", "unknown")); unknownTableMetadata(new JdbcTableHandle(CONNECTOR_ID, new SchemaTableName("example", "numbers"), null, "example", "unknown")); unknownTableMetadata(new JdbcTableHandle(CONNECTOR_ID, new SchemaTableName("example", "numbers"), null, "unknown", "numbers")); } private void unknownTableMetadata(JdbcTableHandle tableHandle) { try { metadata.getTableMetadata(SESSION, tableHandle); fail("Expected getTableMetadata of unknown table to throw a TableNotFoundException"); } catch (TableNotFoundException ignored) { } } @Test public void testListTables() { // all schemas assertEquals(ImmutableSet.copyOf(metadata.listTables(SESSION, null)), ImmutableSet.of( new SchemaTableName("example", "numbers"), new SchemaTableName("example", "view_source"), new SchemaTableName("example", "view"), new SchemaTableName("tpch", "orders"), new SchemaTableName("tpch", "lineitem"), new SchemaTableName("exa_ple", "num_ers"))); // specific schema assertEquals(ImmutableSet.copyOf(metadata.listTables(SESSION, "example")), ImmutableSet.of( new SchemaTableName("example", "numbers"), new SchemaTableName("example", "view_source"), new SchemaTableName("example", "view"))); assertEquals(ImmutableSet.copyOf(metadata.listTables(SESSION, "tpch")), ImmutableSet.of( new SchemaTableName("tpch", "orders"), new SchemaTableName("tpch", "lineitem"))); assertEquals(ImmutableSet.copyOf(metadata.listTables(SESSION, "exa_ple")), ImmutableSet.of( new SchemaTableName("exa_ple", "num_ers"))); // unknown schema assertEquals(ImmutableSet.copyOf(metadata.listTables(SESSION, "unknown")), ImmutableSet.of()); } @Test public void getColumnMetadata() { assertEquals( metadata.getColumnMetadata(SESSION, tableHandle, new JdbcColumnHandle(CONNECTOR_ID, "text", VARCHAR)), new ColumnMetadata("text", VARCHAR)); } @Test(expectedExceptions = PrestoException.class) public void testCreateTable() { metadata.createTable(SESSION, new ConnectorTableMetadata( new SchemaTableName("example", "foo"), ImmutableList.of(new ColumnMetadata("text", VARCHAR)))); } @Test public void testDropTableTable() { try { metadata.dropTable(SESSION, tableHandle); fail("expected exception"); } catch (PrestoException e) { assertEquals(e.getErrorCode(), PERMISSION_DENIED.toErrorCode()); } JdbcMetadataConfig config = new JdbcMetadataConfig().setAllowDropTable(true); metadata = new JdbcMetadata(new JdbcConnectorId(CONNECTOR_ID), database.getJdbcClient(), config); metadata.dropTable(SESSION, tableHandle); try { metadata.getTableMetadata(SESSION, tableHandle); fail("expected exception"); } catch (PrestoException e) { assertEquals(e.getErrorCode(), NOT_FOUND.toErrorCode()); } } }
apache-2.0
oalles/camel
components/camel-spark-rest/src/main/java/org/apache/camel/component/sparkrest/springboot/SparkComponentConfiguration.java
4777
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.sparkrest.springboot; import org.apache.camel.component.sparkrest.SparkBinding; import org.apache.camel.component.sparkrest.SparkConfiguration; import org.springframework.boot.context.properties.ConfigurationProperties; /** * The spark-rest component is used for hosting REST services which has been * defined using Camel rest-dsl. * * Generated by camel-package-maven-plugin - do not edit this file! */ @ConfigurationProperties(prefix = "camel.component.spark-rest") public class SparkComponentConfiguration { /** * Port number. Will by default use 4567 */ private Integer port; /** * Set the IP address that Spark should listen on. If not called the default * address is '0.0.0.0'. */ private String ipAddress; /** * Minimum number of threads in Spark thread-pool (shared globally) */ private Integer minThreads; /** * Maximum number of threads in Spark thread-pool (shared globally) */ private Integer maxThreads; /** * Thread idle timeout in millis where threads that has been idle for a * longer period will be terminated from the thread pool */ private Integer timeOutMillis; /** * Configures connection to be secure to use the keystore file */ private String keystoreFile; /** * Configures connection to be secure to use the keystore password */ private String keystorePassword; /** * Configures connection to be secure to use the truststore file */ private String truststoreFile; /** * Configures connection to be secure to use the truststore password */ private String truststorePassword; /** * To use the shared SparkConfiguration */ private SparkConfiguration sparkConfiguration; /** * To use a custom SparkBinding to map to/from Camel message. */ private SparkBinding sparkBinding; public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public Integer getMinThreads() { return minThreads; } public void setMinThreads(Integer minThreads) { this.minThreads = minThreads; } public Integer getMaxThreads() { return maxThreads; } public void setMaxThreads(Integer maxThreads) { this.maxThreads = maxThreads; } public Integer getTimeOutMillis() { return timeOutMillis; } public void setTimeOutMillis(Integer timeOutMillis) { this.timeOutMillis = timeOutMillis; } public String getKeystoreFile() { return keystoreFile; } public void setKeystoreFile(String keystoreFile) { this.keystoreFile = keystoreFile; } public String getKeystorePassword() { return keystorePassword; } public void setKeystorePassword(String keystorePassword) { this.keystorePassword = keystorePassword; } public String getTruststoreFile() { return truststoreFile; } public void setTruststoreFile(String truststoreFile) { this.truststoreFile = truststoreFile; } public String getTruststorePassword() { return truststorePassword; } public void setTruststorePassword(String truststorePassword) { this.truststorePassword = truststorePassword; } public SparkConfiguration getSparkConfiguration() { return sparkConfiguration; } public void setSparkConfiguration(SparkConfiguration sparkConfiguration) { this.sparkConfiguration = sparkConfiguration; } public SparkBinding getSparkBinding() { return sparkBinding; } public void setSparkBinding(SparkBinding sparkBinding) { this.sparkBinding = sparkBinding; } }
apache-2.0
stoksey69/googleads-java-lib
modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201502/cm/InternalApiError.java
4511
/** * InternalApiError.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.adwords.axis.v201502.cm; /** * Indicates that a server-side error has occured. {@code InternalApiError}s * are generally not the result of an invalid request or message sent * by the * client. */ public class InternalApiError extends com.google.api.ads.adwords.axis.v201502.cm.ApiError implements java.io.Serializable { /* The error reason represented by an enum. */ private com.google.api.ads.adwords.axis.v201502.cm.InternalApiErrorReason reason; public InternalApiError() { } public InternalApiError( java.lang.String fieldPath, java.lang.String trigger, java.lang.String errorString, java.lang.String apiErrorType, com.google.api.ads.adwords.axis.v201502.cm.InternalApiErrorReason reason) { super( fieldPath, trigger, errorString, apiErrorType); this.reason = reason; } /** * Gets the reason value for this InternalApiError. * * @return reason * The error reason represented by an enum. */ public com.google.api.ads.adwords.axis.v201502.cm.InternalApiErrorReason getReason() { return reason; } /** * Sets the reason value for this InternalApiError. * * @param reason * The error reason represented by an enum. */ public void setReason(com.google.api.ads.adwords.axis.v201502.cm.InternalApiErrorReason reason) { this.reason = reason; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof InternalApiError)) return false; InternalApiError other = (InternalApiError) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.reason==null && other.getReason()==null) || (this.reason!=null && this.reason.equals(other.getReason()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); if (getReason() != null) { _hashCode += getReason().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(InternalApiError.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201502", "InternalApiError")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("reason"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201502", "reason")); elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201502", "InternalApiError.Reason")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
apache-2.0
greese/dasein-cloud-azure
src/main/java/org/dasein/cloud/azure/platform/model/CreateDatabaseRestoreModel.java
3194
/** * Copyright (C) 2013-2015 Dell, Inc * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.dasein.cloud.azure.platform.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * Created by vmunthiu on 1/14/2015. */ /* <ServiceResource xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <SourceDatabaseName>sourceDb</SourceDatabaseName> <SourceDatabaseDeletionDate>2013-08-29T21:38:54.5330000Z</SourceDatabaseDeletionDate> <!-- Optional, only applies when restoring a dropped database. --> <TargetDatabaseName>targetDb</TargetDatabaseName> <TargetUtcPointInTime>2013-09-03T00:00:00.0000000Z</TargetUtcPointInTime> <!-- Optional --> </ServiceResource> */ @XmlRootElement(name="ServiceResource", namespace ="http://schemas.microsoft.com/windowsazure") @XmlAccessorType(XmlAccessType.FIELD) public class CreateDatabaseRestoreModel { @XmlElement(name="SourceDatabaseName", namespace ="http://schemas.microsoft.com/windowsazure") private String sourceDatabaseName; @XmlElement(name="SourceDatabaseDeletionDate", namespace ="http://schemas.microsoft.com/windowsazure") private String sourceDatabaseDeletionDate; @XmlElement(name="TargetDatabaseName", namespace ="http://schemas.microsoft.com/windowsazure") private String targetDatabaseName; @XmlElement(name="TargetUtcPointInTime", namespace ="http://schemas.microsoft.com/windowsazure") private String targetUtcPointInTime; public String getSourceDatabaseName() { return sourceDatabaseName; } public void setSourceDatabaseName(String sourceDatabaseName) { this.sourceDatabaseName = sourceDatabaseName; } public String getSourceDatabaseDeletionDate() { return sourceDatabaseDeletionDate; } public void setSourceDatabaseDeletionDate(String sourceDatabaseDeletionDate) { this.sourceDatabaseDeletionDate = sourceDatabaseDeletionDate; } public String getTargetDatabaseName() { return targetDatabaseName; } public void setTargetDatabaseName(String targetDatabaseName) { this.targetDatabaseName = targetDatabaseName; } public String getTargetUtcPointInTime() { return targetUtcPointInTime; } public void setTargetUtcPointInTime(String targetUtcPointInTime) { this.targetUtcPointInTime = targetUtcPointInTime; } }
apache-2.0
yrcourage/netty
transport-udt/src/main/java/io/netty/channel/udt/nio/NioUdtByteConnectorChannel.java
6314
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.channel.udt.nio; import com.barchart.udt.TypeUDT; import com.barchart.udt.nio.SocketChannelUDT; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelException; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelMetadata; import io.netty.channel.FileRegion; import io.netty.channel.RecvByteBufAllocator; import io.netty.channel.nio.AbstractNioByteChannel; import io.netty.channel.udt.DefaultUdtChannelConfig; import io.netty.channel.udt.UdtChannel; import io.netty.channel.udt.UdtChannelConfig; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.net.InetSocketAddress; import java.net.SocketAddress; import static java.nio.channels.SelectionKey.OP_CONNECT; /** * Byte Channel Connector for UDT Streams. */ public class NioUdtByteConnectorChannel extends AbstractNioByteChannel implements UdtChannel { private static final InternalLogger logger = InternalLoggerFactory.getInstance(NioUdtByteConnectorChannel.class); private static final ChannelMetadata METADATA = new ChannelMetadata(false, 16); private final UdtChannelConfig config; public NioUdtByteConnectorChannel() { this(TypeUDT.STREAM); } public NioUdtByteConnectorChannel(final Channel parent, final SocketChannelUDT channelUDT) { super(parent, channelUDT); try { channelUDT.configureBlocking(false); switch (channelUDT.socketUDT().status()) { case INIT: case OPENED: config = new DefaultUdtChannelConfig(this, channelUDT, true); break; default: config = new DefaultUdtChannelConfig(this, channelUDT, false); break; } } catch (final Exception e) { try { channelUDT.close(); } catch (final Exception e2) { if (logger.isWarnEnabled()) { logger.warn("Failed to close channel.", e2); } } throw new ChannelException("Failed to configure channel.", e); } } public NioUdtByteConnectorChannel(final SocketChannelUDT channelUDT) { this(null, channelUDT); } public NioUdtByteConnectorChannel(final TypeUDT type) { this(NioUdtProvider.newConnectorChannelUDT(type)); } @Override public UdtChannelConfig config() { return config; } @Override protected void doBind(final SocketAddress localAddress) throws Exception { javaChannel().bind(localAddress); } @Override protected void doClose() throws Exception { javaChannel().close(); } @Override protected boolean doConnect(final SocketAddress remoteAddress, final SocketAddress localAddress) throws Exception { doBind(localAddress != null? localAddress : new InetSocketAddress(0)); boolean success = false; try { final boolean connected = javaChannel().connect(remoteAddress); if (!connected) { selectionKey().interestOps( selectionKey().interestOps() | OP_CONNECT); } success = true; return connected; } finally { if (!success) { doClose(); } } } @Override protected void doDisconnect() throws Exception { doClose(); } @Override protected void doFinishConnect() throws Exception { if (javaChannel().finishConnect()) { selectionKey().interestOps( selectionKey().interestOps() & ~OP_CONNECT); } else { throw new Error( "Provider error: failed to finish connect. Provider library should be upgraded."); } } @Override protected int doReadBytes(final ByteBuf byteBuf) throws Exception { final RecvByteBufAllocator.Handle allocHandle = unsafe().recvBufAllocHandle(); allocHandle.attemptedBytesRead(byteBuf.writableBytes()); return byteBuf.writeBytes(javaChannel(), allocHandle.attemptedBytesRead()); } @Override protected int doWriteBytes(final ByteBuf byteBuf) throws Exception { final int expectedWrittenBytes = byteBuf.readableBytes(); return byteBuf.readBytes(javaChannel(), expectedWrittenBytes); } @Override protected ChannelFuture shutdownInput() { return newFailedFuture(new UnsupportedOperationException("shutdownInput")); } @Override protected long doWriteFileRegion(FileRegion region) throws Exception { throw new UnsupportedOperationException(); } @Override public boolean isActive() { final SocketChannelUDT channelUDT = javaChannel(); return channelUDT.isOpen() && channelUDT.isConnectFinished(); } @Override protected SocketChannelUDT javaChannel() { return (SocketChannelUDT) super.javaChannel(); } @Override protected SocketAddress localAddress0() { return javaChannel().socket().getLocalSocketAddress(); } @Override public ChannelMetadata metadata() { return METADATA; } @Override protected SocketAddress remoteAddress0() { return javaChannel().socket().getRemoteSocketAddress(); } @Override public InetSocketAddress localAddress() { return (InetSocketAddress) super.localAddress(); } @Override public InetSocketAddress remoteAddress() { return (InetSocketAddress) super.remoteAddress(); } }
apache-2.0
tabish121/activemq-artemis
artemis-server/src/main/java/org/apache/activemq/artemis/core/server/mirror/MirrorController.java
1934
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.core.server.mirror; import java.util.List; import org.apache.activemq.artemis.api.core.Message; import org.apache.activemq.artemis.api.core.QueueConfiguration; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.core.server.MessageReference; import org.apache.activemq.artemis.core.server.RoutingContext; import org.apache.activemq.artemis.core.server.impl.AckReason; import org.apache.activemq.artemis.core.server.impl.AddressInfo; /** * This represents the contract we will use to send messages to replicas. * */ public interface MirrorController { void addAddress(AddressInfo addressInfo) throws Exception; void deleteAddress(AddressInfo addressInfo) throws Exception; void createQueue(QueueConfiguration queueConfiguration) throws Exception; void deleteQueue(SimpleString addressName, SimpleString queueName) throws Exception; void sendMessage(Message message, RoutingContext context, List<MessageReference> refs); void postAcknowledge(MessageReference ref, AckReason reason) throws Exception; String getRemoteMirrorId(); }
apache-2.0
nicolaferraro/camel
components/camel-dropbox/src/test/java/org/apache/camel/component/dropbox/integration/DropboxTestSupport.java
3844
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.dropbox.integration; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import com.dropbox.core.DbxDownloader; import com.dropbox.core.DbxException; import com.dropbox.core.DbxRequestConfig; import com.dropbox.core.v2.DbxClientV2; import com.dropbox.core.v2.files.FileMetadata; import org.apache.camel.test.junit5.CamelTestSupport; import org.junit.jupiter.api.BeforeEach; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DropboxTestSupport extends CamelTestSupport { private static final Logger LOG = LoggerFactory.getLogger(DropboxTestSupport.class); protected final Properties properties; protected String workdir; protected String token; private DbxClientV2 client; protected DropboxTestSupport() { properties = new Properties(); try (InputStream inStream = getClass().getResourceAsStream("/test-options.properties")) { properties.load(inStream); } catch (IOException e) { LOG.error("I/O error: reading test-options.properties: {}", e.getMessage(), e); throw new IllegalAccessError("test-options.properties could not be found"); } workdir = properties.getProperty("workDir"); token = properties.getProperty("accessToken"); DbxRequestConfig config = DbxRequestConfig.newBuilder(properties.getProperty("clientIdentifier")).build(); client = new DbxClientV2(config, token); } @BeforeEach public void setUpWorkingFolder() throws DbxException { createDir(workdir); } protected void createDir(String name) throws DbxException { try { removeDir(name); } finally { client.files().createFolder(name); } } protected void removeDir(String name) throws DbxException { client.files().delete(name); } protected void createFile(String fileName, String content) throws IOException { try { client.files().uploadBuilder(workdir + "/" + fileName) .uploadAndFinish(new ByteArrayInputStream(content.getBytes())); //wait some time for synchronization Thread.sleep(1000); } catch (DbxException e) { LOG.info("folder is already created"); } catch (InterruptedException e) { LOG.debug("Waiting for synchronization interrupted."); } } protected String getFileContent(String path) throws DbxException, IOException { ByteArrayOutputStream target = new ByteArrayOutputStream(); DbxDownloader<FileMetadata> downloadedFile = client.files().download(path); if (downloadedFile != null) { downloadedFile.download(target); } return new String(target.toByteArray()); } @Override protected Properties useOverridePropertiesWithPropertiesComponent() { return properties; } }
apache-2.0
emeroad/pinpoint
commons-server/src/main/java/com/navercorp/pinpoint/common/server/bo/serializer/trace/v2/SpanEncodingContext.java
596
package com.navercorp.pinpoint.common.server.bo.serializer.trace.v2; /** * @author Woonduk Kang(emeroad) */ public class SpanEncodingContext<T> { private final T value; // private AnnotationBo prevAnnotationBo; public SpanEncodingContext(T value) { this.value = value; } public T getValue() { return value; } // public AnnotationBo getPrevFirstAnnotationBo() { // return prevAnnotationBo; // } // // public void setPrevFirstAnnotationBo(AnnotationBo prevAnnotationBo) { // this.prevAnnotationBo = prevAnnotationBo; // } }
apache-2.0
qobel/esoguproject
spring-framework/spring-context/src/main/java/org/springframework/context/weaving/package-info.java
220
/** * Load-time weaving support for a Spring application context, building on Spring's * {@link org.springframework.instrument.classloading.LoadTimeWeaver} abstraction. */ package org.springframework.context.weaving;
apache-2.0
bboyfeiyu/ExoPlayer
demo/src/main/java/com/google/android/exoplayer/demo/simple/SimplePlayerActivity.java
8386
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer.demo.simple; import com.google.android.exoplayer.ExoPlaybackException; import com.google.android.exoplayer.ExoPlayer; import com.google.android.exoplayer.MediaCodecAudioTrackRenderer; import com.google.android.exoplayer.MediaCodecTrackRenderer.DecoderInitializationException; import com.google.android.exoplayer.MediaCodecVideoTrackRenderer; import com.google.android.exoplayer.VideoSurfaceView; import com.google.android.exoplayer.demo.DemoUtil; import com.google.android.exoplayer.demo.R; import com.google.android.exoplayer.util.PlayerControl; import android.app.Activity; import android.content.Intent; import android.media.MediaCodec.CryptoException; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.MotionEvent; import android.view.Surface; import android.view.SurfaceHolder; import android.view.View; import android.view.View.OnTouchListener; import android.widget.MediaController; import android.widget.Toast; /** * An activity that plays media using {@link ExoPlayer}. */ public class SimplePlayerActivity extends Activity implements SurfaceHolder.Callback, ExoPlayer.Listener, MediaCodecVideoTrackRenderer.EventListener { /** * Builds renderers for the player. */ public interface RendererBuilder { void buildRenderers(RendererBuilderCallback callback); } public static final int RENDERER_COUNT = 2; public static final int TYPE_VIDEO = 0; public static final int TYPE_AUDIO = 1; private static final String TAG = "PlayerActivity"; private MediaController mediaController; private Handler mainHandler; private View shutterView; private VideoSurfaceView surfaceView; private ExoPlayer player; private RendererBuilder builder; private RendererBuilderCallback callback; private MediaCodecVideoTrackRenderer videoRenderer; private boolean autoPlay = true; private long playerPosition; private Uri contentUri; private int contentType; private String contentId; // Activity lifecycle @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); contentUri = intent.getData(); contentType = intent.getIntExtra(DemoUtil.CONTENT_TYPE_EXTRA, DemoUtil.TYPE_OTHER); contentId = intent.getStringExtra(DemoUtil.CONTENT_ID_EXTRA); mainHandler = new Handler(getMainLooper()); builder = getRendererBuilder(); setContentView(R.layout.player_activity_simple); View root = findViewById(R.id.root); root.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent arg1) { if (arg1.getAction() == MotionEvent.ACTION_DOWN) { toggleControlsVisibility(); } return true; } }); mediaController = new MediaController(this); mediaController.setAnchorView(root); shutterView = findViewById(R.id.shutter); surfaceView = (VideoSurfaceView) findViewById(R.id.surface_view); surfaceView.getHolder().addCallback(this); DemoUtil.setDefaultCookieManager(); } @Override public void onResume() { super.onResume(); // Setup the player player = ExoPlayer.Factory.newInstance(RENDERER_COUNT, 1000, 5000); player.addListener(this); player.seekTo(playerPosition); // Build the player controls mediaController.setMediaPlayer(new PlayerControl(player)); mediaController.setEnabled(true); // Request the renderers callback = new RendererBuilderCallback(); builder.buildRenderers(callback); } @Override public void onPause() { super.onPause(); // Release the player if (player != null) { playerPosition = player.getCurrentPosition(); player.release(); player = null; } callback = null; videoRenderer = null; shutterView.setVisibility(View.VISIBLE); } // Public methods public Handler getMainHandler() { return mainHandler; } // Internal methods private void toggleControlsVisibility() { if (mediaController.isShowing()) { mediaController.hide(); } else { mediaController.show(0); } } private RendererBuilder getRendererBuilder() { String userAgent = DemoUtil.getUserAgent(this); switch (contentType) { case DemoUtil.TYPE_SS: return new SmoothStreamingRendererBuilder(this, userAgent, contentUri.toString(), contentId); case DemoUtil.TYPE_DASH: return new DashRendererBuilder(this, userAgent, contentUri.toString(), contentId); default: return new DefaultRendererBuilder(this, contentUri); } } private void onRenderers(RendererBuilderCallback callback, MediaCodecVideoTrackRenderer videoRenderer, MediaCodecAudioTrackRenderer audioRenderer) { if (this.callback != callback) { return; } this.callback = null; this.videoRenderer = videoRenderer; player.prepare(videoRenderer, audioRenderer); maybeStartPlayback(); } private void maybeStartPlayback() { Surface surface = surfaceView.getHolder().getSurface(); if (videoRenderer == null || surface == null || !surface.isValid()) { // We're not ready yet. return; } player.sendMessage(videoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, surface); if (autoPlay) { player.setPlayWhenReady(true); autoPlay = false; } } private void onRenderersError(RendererBuilderCallback callback, Exception e) { if (this.callback != callback) { return; } this.callback = null; onError(e); } private void onError(Exception e) { Log.e(TAG, "Playback failed", e); Toast.makeText(this, R.string.failed, Toast.LENGTH_SHORT).show(); finish(); } // ExoPlayer.Listener implementation @Override public void onPlayerStateChanged(boolean playWhenReady, int playbackState) { // Do nothing. } @Override public void onPlayWhenReadyCommitted() { // Do nothing. } @Override public void onPlayerError(ExoPlaybackException e) { onError(e); } // MediaCodecVideoTrackRenderer.Listener @Override public void onVideoSizeChanged(int width, int height, float pixelWidthHeightRatio) { surfaceView.setVideoWidthHeightRatio( height == 0 ? 1 : (pixelWidthHeightRatio * width) / height); } @Override public void onDrawnToSurface(Surface surface) { shutterView.setVisibility(View.GONE); } @Override public void onDroppedFrames(int count, long elapsed) { Log.d(TAG, "Dropped frames: " + count); } @Override public void onDecoderInitializationError(DecoderInitializationException e) { // This is for informational purposes only. Do nothing. } @Override public void onCryptoError(CryptoException e) { // This is for informational purposes only. Do nothing. } // SurfaceHolder.Callback implementation @Override public void surfaceCreated(SurfaceHolder holder) { maybeStartPlayback(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // Do nothing. } @Override public void surfaceDestroyed(SurfaceHolder holder) { if (videoRenderer != null) { player.blockingSendMessage(videoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, null); } } /* package */ final class RendererBuilderCallback { public void onRenderers(MediaCodecVideoTrackRenderer videoRenderer, MediaCodecAudioTrackRenderer audioRenderer) { SimplePlayerActivity.this.onRenderers(this, videoRenderer, audioRenderer); } public void onRenderersError(Exception e) { SimplePlayerActivity.this.onRenderersError(this, e); } } }
apache-2.0
quyixia/springside4
modules/utils/src/main/java/org/springside/modules/utils/Digests.java
7162
/******************************************************************************* * Copyright (c) 2005, 2014 springside.github.io * * Licensed under the Apache License, Version 2.0 (the "License"); *******************************************************************************/ package org.springside.modules.utils; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.SecureRandom; import java.util.zip.CRC32; import org.apache.commons.lang3.Validate; import org.springside.modules.constants.Charsets; import com.google.common.hash.Hashing; /** * 消息摘要的工具类. * * 支持SHA-1/MD5这些安全性较高,返回byte[]的(可用Encodes进一步被编码为Hex, Base64或UrlSafeBase64),支持带salt达到更高的安全性. * * 也支持crc32,murmur32这些不追求安全性,性能较高,返回int的. * * @author calvin */ public class Digests { private static final String SHA1 = "SHA-1"; private static final String MD5 = "MD5"; private static SecureRandom random = new SecureRandom(); /** * 对输入字符串进行sha1散列. */ public static byte[] sha1(byte[] input) { return digest(input, SHA1, null, 1); } /** * 对输入字符串进行sha1散列. */ public static byte[] sha1(String input) { return digest(input.getBytes(Charsets.UTF8), SHA1, null, 1); } /** * 对输入字符串进行sha1散列. */ public static byte[] sha1(String input, Charset charset) { return digest(input.getBytes(charset), SHA1, null, 1); } /** * 对输入字符串进行sha1散列,带salt达到更高的安全性. */ public static byte[] sha1(byte[] input, byte[] salt) { return digest(input, SHA1, salt, 1); } /** * 对输入字符串进行sha1散列,带salt达到更高的安全性. */ public static byte[] sha1(String input, byte[] salt) { return digest(input.getBytes(Charsets.UTF8), SHA1, salt, 1); } /** * 对输入字符串进行sha1散列,带salt达到更高的安全性. */ public static byte[] sha1(String input, Charset charset, byte[] salt) { return digest(input.getBytes(charset), SHA1, salt, 1); } /** * 对输入字符串进行sha1散列,带salt而且迭代达到更高更高的安全性. */ public static byte[] sha1(byte[] input, byte[] salt, int iterations) { return digest(input, SHA1, salt, iterations); } /** * 对输入字符串进行sha1散列,带salt而且迭代达到更高更高的安全性. */ public static byte[] sha1(String input, byte[] salt, int iterations) { return digest(input.getBytes(Charsets.UTF8), SHA1, salt, iterations); } /** * 对输入字符串进行sha1散列,带salt而且迭代达到更高更高的安全性. */ public static byte[] sha1(String input, Charset charset, byte[] salt, int iterations) { return digest(input.getBytes(charset), SHA1, salt, iterations); } /** * 对字符串进行散列, 支持md5与sha1算法. */ private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) { try { MessageDigest digest = MessageDigest.getInstance(algorithm); if (salt != null) { digest.update(salt); } byte[] result = digest.digest(input); for (int i = 1; i < iterations; i++) { digest.reset(); result = digest.digest(result); } return result; } catch (GeneralSecurityException e) { throw Exceptions.unchecked(e); } } /** * 生成随机的Byte[]作为salt. * * @param numBytes salt数组的大小 */ public static byte[] generateSalt(int numBytes) { Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes); byte[] bytes = new byte[numBytes]; random.nextBytes(bytes); return bytes; } /** * 对文件进行md5散列. */ public static byte[] md5(InputStream input) throws IOException { return digest(input, MD5); } /** * 对文件进行sha1散列. */ public static byte[] sha1(InputStream input) throws IOException { return digest(input, SHA1); } private static byte[] digest(InputStream input, String algorithm) throws IOException { try { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); int bufferLength = 8 * 1024; byte[] buffer = new byte[bufferLength]; int read = input.read(buffer, 0, bufferLength); while (read > -1) { messageDigest.update(buffer, 0, read); read = input.read(buffer, 0, bufferLength); } return messageDigest.digest(); } catch (GeneralSecurityException e) { throw Exceptions.unchecked(e); } } /** * 对输入字符串进行crc32散列. */ public static int crc32(byte[] input) { CRC32 crc32 = new CRC32(); crc32.update(input); return (int) crc32.getValue(); } /** * 对输入字符串进行crc32散列. */ public static int crc32(String input) { CRC32 crc32 = new CRC32(); crc32.update(input.getBytes(Charsets.UTF8)); return (int) crc32.getValue(); } /** * 对输入字符串进行crc32散列. */ public static int crc32(String input, Charset charset) { CRC32 crc32 = new CRC32(); crc32.update(input.getBytes(charset)); return (int) crc32.getValue(); } /** * 对输入字符串进行crc32散列,与php兼容,在64bit系统下返回永远是正数的long */ public static long crc32AsLong(byte[] input) { CRC32 crc32 = new CRC32(); crc32.update(input); return crc32.getValue(); } /** * 对输入字符串进行crc32散列,与php兼容,在64bit系统下返回永远是正数的long */ public static long crc32AsLong(String input) { CRC32 crc32 = new CRC32(); crc32.update(input.getBytes(Charsets.UTF8)); return crc32.getValue(); } /** * 对输入字符串进行crc32散列,与php兼容,在64bit系统下返回永远是正数的long */ public static long crc32AsLong(String input, Charset charset) { CRC32 crc32 = new CRC32(); crc32.update(input.getBytes(charset)); return crc32.getValue(); } /** * 对输入字符串进行murmur32散列 */ public static int murmur32(byte[] input) { return Hashing.murmur3_32().hashBytes(input).asInt(); } /** * 对输入字符串进行murmur32散列 */ public static int murmur32(String input) { return Hashing.murmur3_32().hashString(input, Charsets.UTF8).asInt(); } /** * 对输入字符串进行murmur32散列 */ public static int murmur32(String input, Charset charset) { return Hashing.murmur3_32().hashString(input, charset).asInt(); } /** * 对输入字符串进行murmur32散列,带有seed */ public static int murmur32(byte[] input, int seed) { return Hashing.murmur3_32(seed).hashBytes(input).asInt(); } /** * 对输入字符串进行murmur32散列,带有seed */ public static int murmur32(String input, int seed) { return Hashing.murmur3_32(seed).hashString(input, Charsets.UTF8).asInt(); } /** * 对输入字符串进行murmur32散列,带有seed */ public static int murmur32(String input, Charset charset, int seed) { return Hashing.murmur3_32(seed).hashString(input, charset).asInt(); } }
apache-2.0
DariusX/camel
core/camel-core/src/test/java/org/apache/camel/processor/DeadLetterChannelUnmarshalSetHeaderTest.java
2790
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.processor; import java.io.InputStream; import java.io.OutputStream; import org.apache.camel.ContextTestSupport; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.spi.DataFormat; import org.apache.camel.support.service.ServiceSupport; import org.junit.Test; /** * */ public class DeadLetterChannelUnmarshalSetHeaderTest extends ContextTestSupport { @Test public void testDLCSetHeader() throws Exception { MockEndpoint mock = getMockEndpoint("mock:error"); mock.expectedBodiesReceived("Hello World"); mock.expectedHeaderReceived("foo", "123"); mock.expectedHeaderReceived("bar", "456"); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { MyDataFormat df = new MyDataFormat(); from("direct:start").errorHandler(deadLetterChannel("direct:error")).unmarshal(df); from("direct:error").setHeader("foo", constant("123")).setHeader("bar", constant("456")).to("mock:error"); } }; } private class MyDataFormat extends ServiceSupport implements DataFormat { @Override public void marshal(Exchange exchange, Object graph, OutputStream stream) throws Exception { // noop } @Override public Object unmarshal(Exchange exchange, InputStream stream) throws Exception { throw new IllegalArgumentException("Damn"); } @Override protected void doStart() throws Exception { // noop } @Override protected void doStop() throws Exception { // noop } } }
apache-2.0
sflyphotobooks/crp-batik
sources/org/apache/batik/ext/awt/image/codec/util/ImageDecodeParam.java
1265
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.batik.ext.awt.image.codec.util; import java.io.Serializable; /** * An empty (marker) interface to be implemented by all image decoder * parameter classes. * * <p><b> This interface is not a committed part of the JAI API. It may * be removed or changed in future releases of JAI.</b> * * @version $Id: ImageDecodeParam.java 498740 2007-01-22 18:35:57Z dvholten $ */ public interface ImageDecodeParam extends Cloneable, Serializable { }
apache-2.0
semonte/intellij-community
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/XDebugSessionTab.java
17128
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.xdebugger.impl.ui; import com.intellij.debugger.ui.DebuggerContentInfo; import com.intellij.execution.ExecutionManager; import com.intellij.execution.Executor; import com.intellij.execution.executors.DefaultDebugExecutor; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.RunContentBuilder; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.execution.ui.RunContentManager; import com.intellij.execution.ui.RunnerLayoutUi; import com.intellij.execution.ui.actions.CloseAction; import com.intellij.execution.ui.layout.PlaceInGrid; import com.intellij.execution.ui.layout.impl.RunnerContentUi; import com.intellij.execution.ui.layout.impl.ViewImpl; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.ide.actions.ContextHelpAction; import com.intellij.ide.impl.ProjectUtil; import com.intellij.idea.ActionsBundle; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.ToolWindow; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.ui.AppIcon; import com.intellij.ui.AppUIUtil; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentManagerAdapter; import com.intellij.ui.content.ContentManagerEvent; import com.intellij.ui.content.tabs.PinToolwindowTabAction; import com.intellij.util.SystemProperties; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.hash.LinkedHashMap; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XDebuggerBundle; import com.intellij.xdebugger.impl.XDebugSessionImpl; import com.intellij.xdebugger.impl.actions.XDebuggerActions; import com.intellij.xdebugger.impl.frame.*; import com.intellij.xdebugger.ui.XDebugTabLayouter; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.List; public class XDebugSessionTab extends DebuggerSessionTabBase { public static final DataKey<XDebugSessionTab> TAB_KEY = DataKey.create("XDebugSessionTab"); private XWatchesViewImpl myWatchesView; private boolean myWatchesInVariables = Registry.is("debugger.watches.in.variables"); private final LinkedHashMap<String, XDebugView> myViews = new LinkedHashMap<>(); @Nullable private XDebugSessionImpl mySession; private XDebugSessionData mySessionData; private final Runnable myRebuildWatchesRunnable = new Runnable() { @Override public void run() { if (myWatchesView != null) { myWatchesView.computeWatches(); } } }; @NotNull public static XDebugSessionTab create(@NotNull XDebugSessionImpl session, @Nullable Icon icon, @Nullable ExecutionEnvironment environment, @Nullable RunContentDescriptor contentToReuse) { if (contentToReuse != null && SystemProperties.getBooleanProperty("xdebugger.reuse.session.tab", false)) { JComponent component = contentToReuse.getComponent(); if (component != null) { XDebugSessionTab oldTab = TAB_KEY.getData(DataManager.getInstance().getDataContext(component)); if (oldTab != null) { oldTab.setSession(session, environment, icon); oldTab.attachToSession(session); return oldTab; } } } XDebugSessionTab tab = new XDebugSessionTab(session, icon, environment); tab.myRunContentDescriptor.setActivateToolWindowWhenAdded(contentToReuse == null || contentToReuse.isActivateToolWindowWhenAdded()); return tab; } @NotNull public RunnerLayoutUi getUi() { return myUi; } private XDebugSessionTab(@NotNull XDebugSessionImpl session, @Nullable Icon icon, @Nullable ExecutionEnvironment environment) { super(session.getProject(), "Debug", session.getSessionName(), GlobalSearchScope.allScope(session.getProject())); setSession(session, environment, icon); myUi.addContent(createFramesContent(), 0, PlaceInGrid.left, false); addVariablesAndWatches(session); attachToSession(session); DefaultActionGroup focus = new DefaultActionGroup(); focus.add(ActionManager.getInstance().getAction(XDebuggerActions.FOCUS_ON_BREAKPOINT)); myUi.getOptions().setAdditionalFocusActions(focus); myUi.addListener(new ContentManagerAdapter() { @Override public void selectionChanged(ContentManagerEvent event) { Content content = event.getContent(); if (mySession != null && content.isSelected() && getWatchesContentId().equals(ViewImpl.ID.get(content))) { myRebuildWatchesRunnable.run(); } } }, myRunContentDescriptor); rebuildViews(); } private void addVariablesAndWatches(@NotNull XDebugSessionImpl session) { myUi.addContent(createVariablesContent(session), 0, PlaceInGrid.center, false); if (!myWatchesInVariables) { myUi.addContent(createWatchesContent(session), 0, PlaceInGrid.right, false); } } private void setSession(@NotNull XDebugSessionImpl session, @Nullable ExecutionEnvironment environment, @Nullable Icon icon) { myEnvironment = environment; mySession = session; mySessionData = session.getSessionData(); myConsole = session.getConsoleView(); AnAction[] restartActions; List<AnAction> restartActionsList = session.getRestartActions(); if (ContainerUtil.isEmpty(restartActionsList)) { restartActions = AnAction.EMPTY_ARRAY; } else { restartActions = restartActionsList.toArray(new AnAction[restartActionsList.size()]); } myRunContentDescriptor = new RunContentDescriptor(myConsole, session.getDebugProcess().getProcessHandler(), myUi.getComponent(), session.getSessionName(), icon, myRebuildWatchesRunnable, restartActions); myRunContentDescriptor.setRunnerLayoutUi(myUi); Disposer.register(myRunContentDescriptor, this); Disposer.register(myProject, myRunContentDescriptor); } @Nullable @Override public Object getData(@NonNls String dataId) { if (XWatchesView.DATA_KEY.is(dataId)) { return myWatchesView; } else if (TAB_KEY.is(dataId)) { return this; } else if (XDebugSessionData.DATA_KEY.is(dataId)) { return mySessionData; } if (mySession != null) { if (XDebugSession.DATA_KEY.is(dataId)) { return mySession; } else if (LangDataKeys.CONSOLE_VIEW.is(dataId)) { return mySession.getConsoleView(); } } return super.getData(dataId); } private Content createVariablesContent(@NotNull XDebugSessionImpl session) { XVariablesView variablesView; if (myWatchesInVariables) { variablesView = myWatchesView = new XWatchesViewImpl(session, myWatchesInVariables); } else { variablesView = new XVariablesView(session); } registerView(DebuggerContentInfo.VARIABLES_CONTENT, variablesView); Content result = myUi.createContent(DebuggerContentInfo.VARIABLES_CONTENT, variablesView.getPanel(), XDebuggerBundle.message("debugger.session.tab.variables.title"), AllIcons.Debugger.Value, null); result.setCloseable(false); ActionGroup group = getCustomizedActionGroup(XDebuggerActions.VARIABLES_TREE_TOOLBAR_GROUP); result.setActions(group, ActionPlaces.DEBUGGER_TOOLBAR, variablesView.getTree()); return result; } private Content createWatchesContent(@NotNull XDebugSessionImpl session) { myWatchesView = new XWatchesViewImpl(session, myWatchesInVariables); registerView(DebuggerContentInfo.WATCHES_CONTENT, myWatchesView); Content watchesContent = myUi.createContent(DebuggerContentInfo.WATCHES_CONTENT, myWatchesView.getPanel(), XDebuggerBundle.message("debugger.session.tab.watches.title"), AllIcons.Debugger.Watches, null); watchesContent.setCloseable(false); return watchesContent; } @NotNull private Content createFramesContent() { XFramesView framesView = new XFramesView(myProject); registerView(DebuggerContentInfo.FRAME_CONTENT, framesView); Content framesContent = myUi.createContent(DebuggerContentInfo.FRAME_CONTENT, framesView.getMainPanel(), XDebuggerBundle.message("debugger.session.tab.frames.title"), AllIcons.Debugger.Frame, null); framesContent.setCloseable(false); return framesContent; } public void rebuildViews() { AppUIUtil.invokeLaterIfProjectAlive(myProject, () -> { if (mySession != null) { for (XDebugView view : myViews.values()) { view.processSessionEvent(XDebugView.SessionEvent.SETTINGS_CHANGED, mySession); } } }); } public XWatchesView getWatchesView() { return myWatchesView; } private void attachToSession(@NotNull XDebugSessionImpl session) { for (XDebugView view : myViews.values()) { attachViewToSession(session, view); } XDebugTabLayouter layouter = session.getDebugProcess().createTabLayouter(); Content consoleContent = layouter.registerConsoleContent(myUi, myConsole); attachNotificationTo(consoleContent); layouter.registerAdditionalContent(myUi); RunContentBuilder.addAdditionalConsoleEditorActions(myConsole, consoleContent); if (ApplicationManager.getApplication().isUnitTestMode()) { return; } DefaultActionGroup leftToolbar = new DefaultActionGroup(); final Executor debugExecutor = DefaultDebugExecutor.getDebugExecutorInstance(); if (myEnvironment != null) { leftToolbar.add(ActionManager.getInstance().getAction(IdeActions.ACTION_RERUN)); List<AnAction> additionalRestartActions = session.getRestartActions(); if (!additionalRestartActions.isEmpty()) { leftToolbar.addAll(additionalRestartActions); leftToolbar.addSeparator(); } leftToolbar.addAll(session.getExtraActions()); } leftToolbar.addAll(getCustomizedActionGroup(XDebuggerActions.TOOL_WINDOW_LEFT_TOOLBAR_GROUP)); for (AnAction action : session.getExtraStopActions()) { leftToolbar.add(action, new Constraints(Anchor.AFTER, IdeActions.ACTION_STOP_PROGRAM)); } //group.addSeparator(); //addAction(group, DebuggerActions.EXPORT_THREADS); leftToolbar.addSeparator(); leftToolbar.add(myUi.getOptions().getLayoutActions()); final AnAction[] commonSettings = myUi.getOptions().getSettingsActionsList(); DefaultActionGroup settings = new DefaultActionGroup(ActionsBundle.message("group.XDebugger.settings.text"), true); settings.getTemplatePresentation().setIcon(myUi.getOptions().getSettingsActions().getTemplatePresentation().getIcon()); settings.addAll(commonSettings); leftToolbar.add(settings); leftToolbar.addSeparator(); leftToolbar.add(PinToolwindowTabAction.getPinAction()); leftToolbar.add(new CloseAction(myEnvironment != null ? myEnvironment.getExecutor() : debugExecutor, myRunContentDescriptor, myProject)); leftToolbar.add(new ContextHelpAction(debugExecutor.getHelpId())); DefaultActionGroup topToolbar = new DefaultActionGroup(); topToolbar.addAll(getCustomizedActionGroup(XDebuggerActions.TOOL_WINDOW_TOP_TOOLBAR_GROUP)); session.getDebugProcess().registerAdditionalActions(leftToolbar, topToolbar, settings); myUi.getOptions().setLeftToolbar(leftToolbar, ActionPlaces.DEBUGGER_TOOLBAR); myUi.getOptions().setTopToolbar(topToolbar, ActionPlaces.DEBUGGER_TOOLBAR); if (myEnvironment != null) { initLogConsoles(myEnvironment.getRunProfile(), myRunContentDescriptor, myConsole); } } private static void attachViewToSession(@NotNull XDebugSessionImpl session, @Nullable XDebugView view) { if (view != null) { XDebugViewSessionListener.attach(view, session); } } public void detachFromSession() { assert mySession != null; mySession = null; } @Nullable public RunContentDescriptor getRunContentDescriptor() { return myRunContentDescriptor; } public boolean isWatchesInVariables() { return myWatchesInVariables; } public void setWatchesInVariables(boolean watchesInVariables) { if (myWatchesInVariables != watchesInVariables) { myWatchesInVariables = watchesInVariables; Registry.get("debugger.watches.in.variables").setValue(watchesInVariables); if (mySession != null) { removeContent(DebuggerContentInfo.VARIABLES_CONTENT); removeContent(DebuggerContentInfo.WATCHES_CONTENT); addVariablesAndWatches(mySession); attachViewToSession(mySession, myViews.get(DebuggerContentInfo.VARIABLES_CONTENT)); attachViewToSession(mySession, myViews.get(DebuggerContentInfo.WATCHES_CONTENT)); myUi.selectAndFocus(myUi.findContent(DebuggerContentInfo.VARIABLES_CONTENT), true, false); rebuildViews(); } } } public static void showWatchesView(@NotNull XDebugSessionImpl session) { XDebugSessionTab tab = session.getSessionTab(); if (tab != null) { showView(session, tab.getWatchesContentId()); } } public static void showFramesView(@NotNull XDebugSessionImpl session) { showView(session, DebuggerContentInfo.FRAME_CONTENT); } private static void showView(@NotNull XDebugSessionImpl session, String viewId) { XDebugSessionTab tab = session.getSessionTab(); if (tab != null) { tab.toFront(false, null); // restore watches tab if minimized tab.restoreContent(viewId); JComponent component = tab.getUi().getComponent(); if (component instanceof DataProvider) { RunnerContentUi ui = RunnerContentUi.KEY.getData(((DataProvider)component)); if (ui != null) { Content content = ui.findContent(viewId); // if the view is not visible (e.g. Console tab is selected, while Debugger tab is not) // make sure we make it visible to the user if (content != null) { ui.select(content, false); } } } } } public void toFront(boolean focus, @Nullable final Runnable onShowCallback) { if (ApplicationManager.getApplication().isUnitTestMode()) return; ApplicationManager.getApplication().invokeLater(() -> { if (myRunContentDescriptor != null) { RunContentManager manager = ExecutionManager.getInstance(myProject).getContentManager(); ToolWindow toolWindow = manager.getToolWindowByDescriptor(myRunContentDescriptor); if (toolWindow != null) { if (!toolWindow.isVisible()) { toolWindow.show(() -> { if (onShowCallback != null) { onShowCallback.run(); } myRebuildWatchesRunnable.run(); }); } manager.selectRunContent(myRunContentDescriptor); } } }); if (focus) { ApplicationManager.getApplication().invokeLater(() -> { boolean focusWnd = Registry.is("debugger.mayBringFrameToFrontOnBreakpoint"); ProjectUtil.focusProjectWindow(myProject, focusWnd); if (!focusWnd) { AppIcon.getInstance().requestAttention(myProject, true); } }); } } @NotNull private String getWatchesContentId() { return myWatchesInVariables ? DebuggerContentInfo.VARIABLES_CONTENT : DebuggerContentInfo.WATCHES_CONTENT; } private void registerView(String contentId, @NotNull XDebugView view) { myViews.put(contentId, view); Disposer.register(myRunContentDescriptor, view); } private void removeContent(String contentId) { restoreContent(contentId); //findContent returns null if content is minimized myUi.removeContent(myUi.findContent(contentId), true); XDebugView view = myViews.remove(contentId); if (view != null) { Disposer.dispose(view); } } private void restoreContent(String contentId) { JComponent component = myUi.getComponent(); if (component instanceof DataProvider) { RunnerContentUi ui = RunnerContentUi.KEY.getData(((DataProvider)component)); if (ui != null) { ui.restoreContent(contentId); } } } }
apache-2.0
walteryang47/ovirt-engine
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/storage/AddNFSStorageDomainCommand.java
785
package org.ovirt.engine.core.bll.storage; import org.ovirt.engine.core.bll.context.CommandContext; import org.ovirt.engine.core.common.action.StorageDomainManagementParameter; import org.ovirt.engine.core.compat.Guid; public class AddNFSStorageDomainCommand<T extends StorageDomainManagementParameter> extends AddStorageDomainCommon<T> { /** * Constructor for command creation when compensation is applied on startup * * @param commandId */ protected AddNFSStorageDomainCommand(Guid commandId) { super(commandId); } public AddNFSStorageDomainCommand(T parameters) { super(parameters); } public AddNFSStorageDomainCommand(T parameters, CommandContext commandContext) { super(parameters, commandContext); } }
apache-2.0
chrismattmann/grobid
grobid-core/src/main/java/org/grobid/core/main/batch/GrobidMainArgs.java
2331
package org.grobid.core.main.batch; /** * Class containing args of the batch {@link GrobidMain}. * * @author Damien * */ public class GrobidMainArgs { private String path2grobidHome; private String path2grobidProperty; private String path2Input; private String path2Output; private String processMethodName; private String input; private boolean isPdf; /** * @return the path2grobidHome */ public final String getPath2grobidHome() { return path2grobidHome; } /** * @param pPath2grobidHome * the path2grobidHome to set */ public final void setPath2grobidHome(final String pPath2grobidHome) { path2grobidHome = pPath2grobidHome; } /** * @return the path2grobidProperty */ public final String getPath2grobidProperty() { return path2grobidProperty; } /** * @param pPath2grobidProperty * the path2grobidProperty to set */ public final void setPath2grobidProperty(final String pPath2grobidProperty) { path2grobidProperty = pPath2grobidProperty; } /** * @return the path2input */ public final String getPath2Input() { return path2Input; } /** * @param pPath2input * the path2input to set */ public final void setPath2Input(final String pPath2input) { path2Input = pPath2input; } /** * @return the path2Output */ public final String getPath2Output() { return path2Output; } /** * @param pPath2Output * the path2Output to set */ public final void setPath2Output(final String pPath2Output) { path2Output = pPath2Output; } /** * @return the processMethodName */ public final String getProcessMethodName() { return processMethodName; } /** * @param pProcessMethodName * the processMethodName to set */ public final void setProcessMethodName(final String pProcessMethodName) { processMethodName = pProcessMethodName; } /** * @return the input */ public final String getInput() { return input; } /** * @param pInput * the input to set */ public final void setInput(final String pInput) { input = pInput; } /** * @return the isPdf */ public final boolean isPdf() { return isPdf; } /** * @param pIsPdf * the isPdf to set */ public final void setPdf(final boolean pIsPdf) { isPdf = pIsPdf; } }
apache-2.0
emre-aydin/hazelcast
hazelcast/src/test/java/com/hazelcast/client/flakeidgen/impl/FlakeIdGenerator_ClientBackpressureTest.java
1765
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.client.flakeidgen.impl; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.client.config.ClientFlakeIdGeneratorConfig; import com.hazelcast.client.test.TestHazelcastFactory; import com.hazelcast.flakeidgen.impl.FlakeIdGenerator_AbstractBackpressureTest; import com.hazelcast.test.HazelcastSerialClassRunner; import com.hazelcast.test.annotation.SlowTest; import org.junit.After; import org.junit.Before; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; @RunWith(HazelcastSerialClassRunner.class) @Category(SlowTest.class) public class FlakeIdGenerator_ClientBackpressureTest extends FlakeIdGenerator_AbstractBackpressureTest { private TestHazelcastFactory factory; @Before public void before() { factory = new TestHazelcastFactory(1); factory.newHazelcastInstance(); instance = factory.newHazelcastClient(new ClientConfig().addFlakeIdGeneratorConfig(new ClientFlakeIdGeneratorConfig("gen") .setPrefetchCount(BATCH_SIZE))); } @After public void after() { factory.shutdownAll(); } }
apache-2.0
yapengsong/ovirt-engine
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/storage/StorageHelperBase.java
11151
package org.ovirt.engine.core.bll.storage; import java.util.Collections; import java.util.EnumMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Predicate; import org.ovirt.engine.core.bll.Backend; import org.ovirt.engine.core.bll.context.CommandContext; import org.ovirt.engine.core.bll.job.ExecutionHandler; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.action.ConnectHostToStoragePoolServersParameters; import org.ovirt.engine.core.common.action.HostStoragePoolParametersBase; import org.ovirt.engine.core.common.action.SetNonOperationalVdsParameters; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.businessentities.NonOperationalReason; import org.ovirt.engine.core.common.businessentities.StorageDomain; import org.ovirt.engine.core.common.businessentities.StorageDomainStatic; import org.ovirt.engine.core.common.businessentities.StorageDomainStatus; import org.ovirt.engine.core.common.businessentities.StorageServerConnections; import org.ovirt.engine.core.common.businessentities.storage.LUNs; import org.ovirt.engine.core.common.businessentities.storage.StorageType; import org.ovirt.engine.core.common.errors.EngineError; import org.ovirt.engine.core.common.errors.EngineFault; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dal.dbbroker.DbFacade; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase; import org.ovirt.engine.core.dao.LunDao; import org.ovirt.engine.core.utils.collections.MultiValueMapUtils; import org.slf4j.Logger; public abstract class StorageHelperBase implements IStorageHelper { protected abstract Pair<Boolean, EngineFault> runConnectionStorageToDomain(StorageDomain storageDomain, Guid vdsId, int type); protected Pair<Boolean, EngineFault> runConnectionStorageToDomain(StorageDomain storageDomain, Guid vdsId, int type, LUNs lun, Guid storagePoolId) { return new Pair<>(true, null); } @Override public boolean connectStorageToDomainByVdsId(StorageDomain storageDomain, Guid vdsId) { return connectStorageToDomainByVdsIdDetails(storageDomain, vdsId).getFirst(); } @Override public Pair<Boolean, EngineFault> connectStorageToDomainByVdsIdDetails(StorageDomain storageDomain, Guid vdsId) { return runConnectionStorageToDomain(storageDomain, vdsId, VdcActionType.ConnectStorageToVds.getValue()); } @Override public boolean disconnectStorageFromDomainByVdsId(StorageDomain storageDomain, Guid vdsId) { return runConnectionStorageToDomain(storageDomain, vdsId, VdcActionType.DisconnectStorageServerConnection.getValue()).getFirst(); } @Override public boolean connectStorageToLunByVdsId(StorageDomain storageDomain, Guid vdsId, LUNs lun, Guid storagePoolId) { return runConnectionStorageToDomain(storageDomain, vdsId, VdcActionType.ConnectStorageToVds.getValue(), lun, storagePoolId).getFirst(); } @Override public boolean disconnectStorageFromLunByVdsId(StorageDomain storageDomain, Guid vdsId, LUNs lun) { return runConnectionStorageToDomain(storageDomain, vdsId, VdcActionType.DisconnectStorageServerConnection.getValue(), lun, Guid.Empty).getFirst(); } @Override public boolean storageDomainRemoved(StorageDomainStatic storageDomain) { return true; } @Override public void removeLun(LUNs lun) { if (lun.getvolume_group_id().isEmpty()) { DbFacade.getInstance().getLunDao().remove(lun.getLUN_id()); for (StorageServerConnections connection : filterConnectionsUsedByOthers(lun.getLunConnections(), "", lun.getLUN_id())) { DbFacade.getInstance().getStorageServerConnectionDao().remove(connection.getId()); } } } protected List<StorageServerConnections> filterConnectionsUsedByOthers( List<StorageServerConnections> connections, String vgId, final String lunId) { return Collections.emptyList(); } @Override public boolean isConnectSucceeded(Map<String, String> returnValue, List<StorageServerConnections> connections) { return true; } @Override public boolean prepareConnectHostToStoragePoolServers(CommandContext cmdContext, ConnectHostToStoragePoolServersParameters parameters, List<StorageServerConnections> connections) { return true; } @Override public void prepareDisconnectHostFromStoragePoolServers(HostStoragePoolParametersBase parameters, List<StorageServerConnections> connections) { // default implementation } @Override public Pair<Boolean, AuditLogType> disconnectHostFromStoragePoolServersCommandCompleted(HostStoragePoolParametersBase parameters) { return new Pair<Boolean, AuditLogType>(true, null); } public static Map<StorageType, List<StorageServerConnections>> filterConnectionsByStorageType(LUNs lun) { Map<StorageType, List<StorageServerConnections>> storageConnectionsForStorageTypeMap = new EnumMap<>(StorageType.class); for (StorageServerConnections lunConnections : lun.getLunConnections()) { MultiValueMapUtils.addToMap(lunConnections.getstorage_type(), lunConnections, storageConnectionsForStorageTypeMap); } return storageConnectionsForStorageTypeMap; } protected boolean isActiveStorageDomainAvailable(final StorageType storageType, Guid poolId) { List<StorageDomain> storageDomains = DbFacade.getInstance().getStorageDomainDao().getAllForStoragePool(poolId); return CollectionUtils.exists(storageDomains, new Predicate() { @Override public boolean evaluate(Object o) { StorageDomain storageDomain = (StorageDomain) o; return storageDomain.getStorageType() == storageType && storageDomain.getStatus() == StorageDomainStatus.Active; } }); } protected void setNonOperational(CommandContext cmdContext, Guid vdsId, NonOperationalReason reason) { Backend.getInstance().runInternalAction(VdcActionType.SetNonOperationalVds, new SetNonOperationalVdsParameters(vdsId, reason), ExecutionHandler.createInternalJobContext(cmdContext)); } protected static LunDao getLunDao() { return DbFacade.getInstance().getLunDao(); } protected int removeStorageDomainLuns(StorageDomainStatic storageDomain) { final List<LUNs> lunsList = getLunDao().getAllForVolumeGroup(storageDomain.getStorage()); int numOfRemovedLuns = 0; for (LUNs lun : lunsList) { if (DbFacade.getInstance().getDiskLunMapDao().getDiskIdByLunId(lun.getLUN_id()) == null) { getLunDao().remove(lun.getLUN_id()); numOfRemovedLuns++; } else { lun.setvolume_group_id(""); getLunDao().update(lun); } } return numOfRemovedLuns; } protected String addToAuditLogErrorMessage(String connection, String errorCode, List<StorageServerConnections> connections) { return addToAuditLogErrorMessage(connection, errorCode, connections, null); } protected String addToAuditLogErrorMessage(String connection, String errorCode, List<StorageServerConnections> connections, LUNs lun) { AuditLogableBase logable = new AuditLogableBase(); String connectionField = getConnectionDescription(connections, connection) + (lun == null ? "" : " (LUN " + lun.getLUN_id() + ")"); logable.addCustomValue("Connection", connectionField); // Get translated error by error code ,if no translation found (should not happened) , // will set the error code instead. String translatedError = getTranslatedStorageError(errorCode); logable.addCustomValue("ErrorMessage", translatedError); new AuditLogDirector().log(logable, AuditLogType.STORAGE_DOMAIN_ERROR); return connectionField; } protected void printLog(Logger logger, String connectionField, String errorCode) { String translatedError = getTranslatedStorageError(errorCode); logger.error( "The connection with details '{}' failed because of error code '{}' and error message is: {}", connectionField, errorCode, Backend.getInstance().getVdsErrorsTranslator() .TranslateErrorTextSingle(translatedError)); } /** * Get translated error by error code ,if no enum for the error code (should not happened) , will set the error code * instead. <BR/> * When no enum found for the error code, we should check it with the vdsm team. * * @param errorCode * - The error code we want to translate. * @return - Translated error if found or error code. */ private String getTranslatedStorageError(String errorCode) { String translatedError = errorCode; EngineError error = EngineError.forValue(Integer.parseInt(errorCode)); if (error != null) { translatedError = Backend.getInstance() .getVdsErrorsTranslator() .TranslateErrorTextSingle(error.toString()); } return translatedError; } private String getConnectionDescription(List<StorageServerConnections> connections, String connectionId) { // Using Guid in order to handle nulls. This can happened when we trying // to import an existing domain Guid connectionIdGuid = Guid.createGuidFromStringDefaultEmpty(connectionId); for (StorageServerConnections connection : connections) { Guid connectionGuid = Guid.createGuidFromStringDefaultEmpty(connection.getId()); if (connectionGuid.equals(connectionIdGuid)) { String desc = connection.getconnection(); if (connection.getiqn() != null) { desc += " " + connection.getiqn(); } return desc; } } return ""; } @Override public boolean syncDomainInfo(StorageDomain storageDomain, Guid vdsId) { return true; } public static void addMessageToAuditLog(AuditLogType auditLogType, String storageDomainName, String vdsName){ AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("StorageDomainName", storageDomainName); logable.addCustomValue("VdsName", vdsName); new AuditLogDirector().log(logable, auditLogType); } }
apache-2.0
mv2a/yajsw
src/yajsw/src/main/java/org/rzo/yajsw/timer/Timer.java
203
package org.rzo.yajsw.timer; public interface Timer { void init(); boolean isHasTrigger(); boolean isTriggered(); boolean isStartImmediate(); void start(); void stop(); }
apache-2.0
zstackorg/zstack
sdk/src/main/java/org/zstack/sdk/KVMIsoTO.java
559
package org.zstack.sdk; public class KVMIsoTO extends org.zstack.sdk.ImageInventory { public java.lang.String pathInCache; public void setPathInCache(java.lang.String pathInCache) { this.pathInCache = pathInCache; } public java.lang.String getPathInCache() { return this.pathInCache; } public java.lang.String installUrl; public void setInstallUrl(java.lang.String installUrl) { this.installUrl = installUrl; } public java.lang.String getInstallUrl() { return this.installUrl; } }
apache-2.0
mdecourci/assertj-core
src/main/java/org/assertj/core/api/AbstractInputStreamAssert.java
3130
/** * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright 2012-2015 the original author or authors. */ package org.assertj.core.api; import java.io.InputStream; import org.assertj.core.internal.InputStreams; import org.assertj.core.internal.InputStreamsException; import org.assertj.core.util.VisibleForTesting; /** * Base class for all implementations of assertions for {@link InputStream}s. * @param <S> the "self" type of this assertion class. Please read &quot;<a href="http://bit.ly/1IZIRcY" * target="_blank">Emulating 'self types' using Java Generics to simplify fluent API implementation</a>&quot; * for more details. * @param <A> the type of the "actual" value. * * @author Matthieu Baechler * @author Mikhail Mazursky */ public abstract class AbstractInputStreamAssert<S extends AbstractInputStreamAssert<S, A>, A extends InputStream> extends AbstractAssert<S, A> { @VisibleForTesting InputStreams inputStreams = InputStreams.instance(); protected AbstractInputStreamAssert(A actual, Class<?> selfType) { super(actual, selfType); } /** * Verifies that the content of the actual {@code InputStream} is equal to the content of the given one. * * @param expected the given {@code InputStream} to compare the actual {@code InputStream} to. * @return {@code this} assertion object. * @throws NullPointerException if the given {@code InputStream} is {@code null}. * @throws AssertionError if the actual {@code InputStream} is {@code null}. * @throws AssertionError if the content of the actual {@code InputStream} is not equal to the content of the given one. * @throws InputStreamsException if an I/O error occurs. * * @deprecated use hasSameContentAs */ @Deprecated public S hasContentEqualTo(InputStream expected) { inputStreams.assertSameContentAs(info, actual, expected); return myself; } /** * Verifies that the content of the actual {@code InputStream} is equal to the content of the given one. * * @param expected the given {@code InputStream} to compare the actual {@code InputStream} to. * @return {@code this} assertion object. * @throws NullPointerException if the given {@code InputStream} is {@code null}. * @throws AssertionError if the actual {@code InputStream} is {@code null}. * @throws AssertionError if the content of the actual {@code InputStream} is not equal to the content of the given one. * @throws InputStreamsException if an I/O error occurs. */ public S hasSameContentAs(InputStream expected) { inputStreams.assertSameContentAs(info, actual, expected); return myself; } }
apache-2.0
nathancomstock/closure-templates
java/src/com/google/template/soy/incrementaldomsrc/IncrementalDomOutputOptimizers.java
4771
/* * Copyright 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.incrementaldomsrc; import com.google.template.soy.html.HtmlAttributeNode; import com.google.template.soy.html.HtmlCloseTagNode; import com.google.template.soy.html.HtmlOpenTagEndNode; import com.google.template.soy.html.HtmlOpenTagNode; import com.google.template.soy.html.HtmlOpenTagStartNode; import com.google.template.soy.html.HtmlVoidTagNode; import com.google.template.soy.soytree.SoyNode; import com.google.template.soy.soytree.SoyNode.BlockNode; import com.google.template.soy.soytree.SoyNode.StandaloneNode; import com.google.template.soy.soytree.SoytreeUtils; import java.util.List; final class IncrementalDomOutputOptimizers { private IncrementalDomOutputOptimizers() {} /** * Finds nodes in the tree where an {@link HtmlOpenTagNode} is followed by a {@link * HtmlCloseTagNode} and collapses them into a {@link HtmlVoidTagNode}. * @param node The root node in which to collapse nodes. */ static void collapseElements(SoyNode node) { Iterable<HtmlOpenTagNode> openTagNodes = SoytreeUtils.getAllNodesOfType( node, HtmlOpenTagNode.class); for (HtmlOpenTagNode openTagNode : openTagNodes) { BlockNode parent = openTagNode.getParent(); int nextIndex = parent.getChildIndex(openTagNode) + 1; if (nextIndex >= parent.getChildren().size()) { continue; } StandaloneNode nextNode = parent.getChild(nextIndex); if (nextNode instanceof HtmlCloseTagNode) { HtmlVoidTagNode htmlVoidTagNode = new HtmlVoidTagNode( openTagNode.getId(), openTagNode.getTagName(), openTagNode.getSourceLocation()); htmlVoidTagNode.addChildren(openTagNode.getChildren()); parent.replaceChild(openTagNode, htmlVoidTagNode); parent.removeChild(nextNode); } } } /** * Finds nodes in the tree where an {@link HtmlOpenTagStartNode} is followed by zero or more * {@link HtmlAttributeNode}s and finally an {@link HtmlOpenTagEndNode} and collapses them into a * {@link HtmlOpenTagNode}. This allows the code generation to output efficient way of specifying * attributes. * @param node The root node in which to collapse nodes. */ static void collapseOpenTags(SoyNode node) { Iterable<HtmlOpenTagStartNode> openTagStartNodes = SoytreeUtils.getAllNodesOfType( node, HtmlOpenTagStartNode.class); for (HtmlOpenTagStartNode openTagStartNode : openTagStartNodes) { BlockNode parent = openTagStartNode.getParent(); List<StandaloneNode> children = parent.getChildren(); final int startIndex = children.indexOf(openTagStartNode); int currentIndex = startIndex + 1; StandaloneNode currentNode = null; // Keep going while HtmlAttributeNodes are encountered for (; currentIndex < children.size(); currentIndex++) { currentNode = children.get(currentIndex); if (!(currentNode instanceof HtmlAttributeNode)) { break; } } // If the currentNode is an HtmlOpenTagEndNode, then we encountered a start, zero or more // attributes, followed by an end. if (currentNode instanceof HtmlOpenTagEndNode) { // At this point, startIndex points to the HtmlOpenTagStartNode and currentIndex points to // the HtmlOpenTagEndNode, with everything in between being an HtmlAttributeNode. List<StandaloneNode> tagNodesRange = children.subList(startIndex, currentIndex + 1); HtmlOpenTagNode openTagNode = new HtmlOpenTagNode( openTagStartNode.getId(), openTagStartNode.getTagName(), openTagStartNode.getSourceLocation().extend(currentNode.getSourceLocation())); // Get all the attribute nodes (all of the nodes in the range, except the first and last) for (StandaloneNode standaloneNode : tagNodesRange.subList(1, tagNodesRange.size() - 1)) { openTagNode.addChild((HtmlAttributeNode) standaloneNode); } // Replace the range of nodes with the newly created HtmlOpenTagNode. tagNodesRange.clear(); parent.addChild(startIndex, openTagNode); } } } }
apache-2.0
lshain-android-source/external-mockwebserver
src/main/java/com/google/mockwebserver/RecordedRequest.java
4786
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mockwebserver; import java.io.UnsupportedEncodingException; import java.net.Socket; import java.util.ArrayList; import java.util.List; import javax.net.ssl.SSLSocket; /** * An HTTP request that came into the mock web server. */ public final class RecordedRequest { private final String requestLine; private final String method; private final String path; private final List<String> headers; private final List<Integer> chunkSizes; private final int bodySize; private final byte[] body; private final int sequenceNumber; private final String sslProtocol; public RecordedRequest(String requestLine, List<String> headers, List<Integer> chunkSizes, int bodySize, byte[] body, int sequenceNumber, Socket socket) { this.requestLine = requestLine; this.headers = headers; this.chunkSizes = chunkSizes; this.bodySize = bodySize; this.body = body; this.sequenceNumber = sequenceNumber; if (socket instanceof SSLSocket) { SSLSocket sslSocket = (SSLSocket) socket; sslProtocol = sslSocket.getSession().getProtocol(); } else { sslProtocol = null; } if (requestLine != null) { int methodEnd = requestLine.indexOf(' '); int pathEnd = requestLine.indexOf(' ', methodEnd + 1); this.method = requestLine.substring(0, methodEnd); this.path = requestLine.substring(methodEnd + 1, pathEnd); } else { this.method = null; this.path = null; } } public String getRequestLine() { return requestLine; } public String getMethod() { return method; } public String getPath() { return path; } /** * Returns all headers. */ public List<String> getHeaders() { return headers; } /** * Returns the first header named {@code name}, or null if no such header * exists. */ public String getHeader(String name) { name += ":"; for (String header : headers) { if (name.regionMatches(true, 0, header, 0, name.length())) { return header.substring(name.length()).trim(); } } return null; } /** * Returns the headers named {@code name}. */ public List<String> getHeaders(String name) { List<String> result = new ArrayList<String>(); name += ":"; for (String header : headers) { if (name.regionMatches(true, 0, header, 0, name.length())) { result.add(header.substring(name.length()).trim()); } } return result; } /** * Returns the sizes of the chunks of this request's body, or an empty list * if the request's body was empty or unchunked. */ public List<Integer> getChunkSizes() { return chunkSizes; } /** * Returns the total size of the body of this POST request (before * truncation). */ public int getBodySize() { return bodySize; } /** * Returns the body of this POST request. This may be truncated. */ public byte[] getBody() { return body; } /** * Returns the body of this POST request decoded as a UTF-8 string. */ public String getUtf8Body() { try { return new String(body, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new AssertionError(); } } /** * Returns the index of this request on its HTTP connection. Since a single * HTTP connection may serve multiple requests, each request is assigned its * own sequence number. */ public int getSequenceNumber() { return sequenceNumber; } /** * Returns the connection's SSL protocol like {@code TLSv1}, {@code SSLv3}, * {@code NONE} or null if the connection doesn't use SSL. */ public String getSslProtocol() { return sslProtocol; } @Override public String toString() { return "RecordedRequest {" + requestLine + "}"; } }
apache-2.0
hurricup/intellij-community
RegExpSupport/src/org/intellij/lang/regexp/psi/impl/RegExpOptionsImpl.java
1782
/* * Copyright 2006 Sascha Weinreuter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.lang.regexp.psi.impl; import com.intellij.lang.ASTNode; import org.intellij.lang.regexp.RegExpTT; import org.intellij.lang.regexp.psi.RegExpElementVisitor; import org.intellij.lang.regexp.psi.RegExpOptions; import org.jetbrains.annotations.Nullable; public class RegExpOptionsImpl extends RegExpElementImpl implements RegExpOptions { public RegExpOptionsImpl(ASTNode astNode) { super(astNode); } @Override public void accept(RegExpElementVisitor visitor) { visitor.visitRegExpOptions(this); } @Override public boolean isSwitchedOn(char flag) { final ASTNode node = getOptionsOn(); return node != null && node.getText().indexOf(flag) >= 0; } @Override public boolean isSwitchedOff(char flag) { final ASTNode node = getOptionsOff(); return node != null && node.getText().indexOf(flag) > 0; } @Override @Nullable public ASTNode getOptionsOn() { return getNode().findChildByType(RegExpTT.OPTIONS_ON); } @Override @Nullable public ASTNode getOptionsOff() { return getNode().findChildByType(RegExpTT.OPTIONS_OFF); } }
apache-2.0
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/packageDependencies/actions/AnalyzeDependenciesAction.java
1486
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.packageDependencies.actions; import com.intellij.analysis.AnalysisScope; import com.intellij.analysis.BaseAnalysisAction; import com.intellij.analysis.BaseAnalysisActionDialog; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class AnalyzeDependenciesAction extends BaseAnalysisAction { private AnalyzeDependenciesAdditionalUi myPanel; public AnalyzeDependenciesAction() { super(CodeInsightBundle.messagePointer("action.forward.dependency.analysis"), CodeInsightBundle.messagePointer("action.analysis.noun")); } @Override protected void analyze(@NotNull final Project project, @NotNull AnalysisScope scope) { new AnalyzeDependenciesHandler(project, scope, myPanel.getTransitiveCB().isSelected() ? ((SpinnerNumberModel)myPanel.getBorderChooser().getModel()).getNumber().intValue() : 0).analyze(); myPanel = null; } @Override @Nullable protected JComponent getAdditionalActionSettings(final Project project, final BaseAnalysisActionDialog dialog) { myPanel = new AnalyzeDependenciesAdditionalUi(); return myPanel.getPanel(); } @Override protected void canceled() { super.canceled(); myPanel = null; } }
apache-2.0
christophd/camel
components/camel-cxf/src/main/java/org/apache/camel/component/cxf/jaxrs/SimpleCxfRsBinding.java
17096
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.cxf.jaxrs; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.ws.rs.CookieParam; import javax.ws.rs.FormParam; import javax.ws.rs.HeaderParam; import javax.ws.rs.MatrixParam; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import org.apache.camel.Message; import org.apache.camel.attachment.AttachmentMessage; import org.apache.camel.attachment.DefaultAttachment; import org.apache.camel.spi.HeaderFilterStrategy; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.InputStreamDataSource; import org.apache.cxf.jaxrs.ext.multipart.Multipart; import org.apache.cxf.jaxrs.model.URITemplate; import org.apache.cxf.jaxrs.utils.AnnotationUtils; import org.apache.cxf.message.Exchange; import org.apache.cxf.message.MessageContentsList; /** * A CXF RS Binding which maps method parameters as Camel IN headers and the payload as the IN message body. It replaces * the default behaviour of creating a MessageContentsList, which requires the route to process the contents low-level. * * <p /> * * The mapping from CXF to Camel is performed as follows: * * <ul> * <li>JAX-RS Parameter types (@QueryParam, @HeaderParam, @CookieParam, @FormParam, @PathParam, @MatrixParam) are all * transferred as IN message headers.</li> * <li>If a request entity is clearly identified (for example, because it's the only parameter without an annotation), * it's set as the IN message body. Otherwise, the original {@link MessageContentsList} is preserved as the message * body.</li> * <li>If Multipart is in use, binary parts are mapped as Camel IN message attachments, while any others are mapped as * IN message headers for convenience. These classes are considered binary: Attachment, DataHandler, DataSource, * InputStream. Additionally, the original {@link MessageContentsList} is preserved as the message body.</li> * </ul> * * For example, the following JAX-RS method signatures are supported, with the specified outcomes: * <p /> * * <b><tt>public Response doAction(BusinessObject request);</tt></b><br /> * Request payload is placed in IN message body, replacing the original {@link MessageContentsList}. * <p /> * * <b><tt>public Response doAction(BusinessObject request, @HeaderParam("abcd") String abcd, @QueryParam("defg") String defg);</tt></b><br/> * Request payload placed in IN message body, replacing the original {@link MessageContentsList}. Both request params * mapped as IN message headers with names <tt>abcd</tt> and <tt>defg</tt>. * <p /> * * <b><tt>public Response doAction(@HeaderParam("abcd") String abcd, @QueryParam("defg") String defg);</tt></b><br/> * Both request params mapped as IN message headers with names <tt>abcd</tt> and <tt>defg</tt>. The original * {@link MessageContentsList} is preserved, even though it only contains the 2 parameters. * <p /> * * <b><tt>public Response doAction(@Multipart(value="body1", type="application/json") BusinessObject request, @Multipart(value="image", * type="image/jpeg") DataHandler image);</tt></b><br/> * The first parameter is transferred as a POJO in a header named <tt>body1</tt>, while the second parameter gets * injected as an attachment with name <tt>image</tt>. The MIME type is observed by the CXF stack. The IN message body * is the original {@link MessageContentsList} handed over from CXF. * <p /> * * <b><tt>public Response doAction(InputStream abcd);</tt></b><br/> * The InputStream is unwrapped from the {@link MessageContentsList} and preserved as the IN message body. * <p /> * * <b><tt>public Response doAction(DataHandler abcd);</tt></b><br/> * The DataHandler is unwrapped from the {@link MessageContentsList} and preserved as the IN message body. */ public class SimpleCxfRsBinding extends DefaultCxfRsBinding { /** The JAX-RS annotations to be injected as headers in the IN message */ private static final Set<Class<?>> HEADER_ANNOTATIONS = Collections.unmodifiableSet( new HashSet<>( Arrays.asList( CookieParam.class, FormParam.class, PathParam.class, HeaderParam.class, MatrixParam.class, QueryParam.class))); private static final Set<Class<?>> BINARY_ATTACHMENT_TYPES = Collections.unmodifiableSet( new HashSet<>( Arrays.asList( Attachment.class, DataHandler.class, DataSource.class, InputStream.class))); private static final Class<?>[] NO_PARAMETER_TYPES = null; private static final Object[] NO_PARAMETERS = null; /** Caches the Method to Parameters associations to avoid reflection with every request */ private Map<Method, MethodSpec> methodSpecCache = new ConcurrentHashMap<>(); @Override public void populateExchangeFromCxfRsRequest( Exchange cxfExchange, org.apache.camel.Exchange camelExchange, Method method, Object[] paramArray) { super.populateExchangeFromCxfRsRequest(cxfExchange, camelExchange, method, paramArray); Message in = camelExchange.getIn(); bindHeadersFromSubresourceLocators(cxfExchange, camelExchange); MethodSpec spec = methodSpecCache.get(method); if (spec == null) { spec = MethodSpec.fromMethod(method); methodSpecCache.put(method, spec); } bindParameters(in, paramArray, spec.paramNames, spec.numberParameters); bindBody(in, paramArray, spec.entityIndex); if (spec.multipart) { transferMultipartParameters(paramArray, spec.multipartNames, spec.multipartTypes, in); } } @Override public Object populateCxfRsResponseFromExchange(org.apache.camel.Exchange camelExchange, Exchange cxfExchange) throws Exception { Object base = super.populateCxfRsResponseFromExchange(camelExchange, cxfExchange); return buildResponse(camelExchange, base); } /** * Builds the response for the client. * <p /> * Always returns a JAX-RS {@link Response} object, which gives the user a better control on the response behaviour. * If the message body is already an instance of {@link Response}, we reuse it and just inject the relevant HTTP * headers. * * @param camelExchange * @param base * @return */ protected Object buildResponse(org.apache.camel.Exchange camelExchange, Object base) { Message m = camelExchange.getMessage(); ResponseBuilder response; // if the body is different to Response, it's an entity; therefore, check if (base instanceof Response) { response = Response.fromResponse((Response) base); } else { int status = m.getHeader(org.apache.camel.Exchange.HTTP_RESPONSE_CODE, Status.OK.getStatusCode(), Integer.class); response = Response.status(status); // avoid using the request MessageContentsList as the entity; it simply doesn't make sense if (base != null && !(base instanceof MessageContentsList)) { response.entity(base); } } // Compute which headers to transfer by applying the HeaderFilterStrategy, and transfer them to the JAX-RS Response Map<String, String> headersToPropagate = filterCamelHeadersForResponseHeaders(m.getHeaders(), camelExchange); for (Entry<String, String> entry : headersToPropagate.entrySet()) { response.header(entry.getKey(), entry.getValue()); } return response.build(); } /** * Filters the response headers that will be sent back to the client. * <p /> * The {@link DefaultCxfRsBinding} doesn't filter the response headers according to the * {@link HeaderFilterStrategy}, so we handle this task in this binding. */ protected Map<String, String> filterCamelHeadersForResponseHeaders( Map<String, Object> headers, org.apache.camel.Exchange camelExchange) { Map<String, String> answer = new HashMap<>(); for (Map.Entry<String, Object> entry : headers.entrySet()) { if (getHeaderFilterStrategy().applyFilterToCamelHeaders(entry.getKey(), entry.getValue(), camelExchange)) { continue; } // skip content-length as the simple binding with Response will set correct content-length based // on the entity set as the Response if ("content-length".equalsIgnoreCase(entry.getKey())) { continue; } answer.put(entry.getKey(), entry.getValue().toString()); } return answer; } /** * Transfers path parameters from the full path (including ancestor subresource locators) into Camel IN Message * Headers. */ @SuppressWarnings("unchecked") protected void bindHeadersFromSubresourceLocators(Exchange cxfExchange, org.apache.camel.Exchange camelExchange) { MultivaluedMap<String, String> pathParams = (MultivaluedMap<String, String>) cxfExchange.getInMessage().get(URITemplate.TEMPLATE_PARAMETERS); // return immediately if we have no path parameters if (pathParams == null || pathParams.size() == 1 && pathParams.containsKey(URITemplate.FINAL_MATCH_GROUP)) { return; } Message m = camelExchange.getIn(); for (Entry<String, List<String>> entry : pathParams.entrySet()) { // skip over the FINAL_MATCH_GROUP which stores the entire path if (URITemplate.FINAL_MATCH_GROUP.equals(entry.getKey())) { continue; } m.setHeader(entry.getKey(), entry.getValue().get(0)); } } /** * Binds JAX-RS parameter types (@HeaderParam, @QueryParam, @MatrixParam, etc.) to the exchange. * * @param in * @param paramArray * @param paramNames * @param numberParameters */ protected void bindParameters(Message in, Object[] paramArray, String[] paramNames, int numberParameters) { if (numberParameters == 0) { return; } for (int i = 0; i < paramNames.length; i++) { if (paramNames[i] != null) { in.setHeader(paramNames[i], paramArray[i]); } } } /** * Binds the message body. * * @param in * @param paramArray * @param singleBodyIndex */ protected void bindBody(Message in, Object[] paramArray, int singleBodyIndex) { if (singleBodyIndex == -1) { return; } in.setBody(paramArray[singleBodyIndex]); } private void transferMultipartParameters( Object[] paramArray, String[] multipartNames, String[] multipartTypes, Message in) { for (int i = 0; i < multipartNames.length; i++) { if (multipartNames[i] == null || paramArray[i] == null) { continue; } if (BINARY_ATTACHMENT_TYPES.contains(paramArray[i].getClass())) { transferBinaryMultipartParameter(paramArray[i], multipartNames[i], multipartTypes[i], in); } else { in.setHeader(multipartNames[i], paramArray[i]); } } } private void transferBinaryMultipartParameter(Object toMap, String parameterName, String multipartType, Message in) { org.apache.camel.attachment.Attachment dh = null; if (toMap instanceof Attachment) { dh = createCamelAttachment((Attachment) toMap); } else if (toMap instanceof DataSource) { dh = new DefaultAttachment((DataSource) toMap); } else if (toMap instanceof DataHandler) { dh = new DefaultAttachment((DataHandler) toMap); } else if (toMap instanceof InputStream) { dh = new DefaultAttachment( new InputStreamDataSource( (InputStream) toMap, multipartType == null ? "application/octet-stream" : multipartType)); } if (dh != null) { in.getExchange().getMessage(AttachmentMessage.class).addAttachmentObject(parameterName, dh); } } private DefaultAttachment createCamelAttachment(Attachment attachment) { DefaultAttachment camelAttachment = new DefaultAttachment(attachment.getDataHandler()); for (String name : attachment.getHeaders().keySet()) { for (String value : attachment.getHeaderAsList(name)) { camelAttachment.addHeader(name, value); } } return camelAttachment; } protected static class MethodSpec { private boolean multipart; private int numberParameters; private int entityIndex = -1; private String[] paramNames; private String[] multipartNames; private String[] multipartTypes; /** * Processes this method definition and extracts metadata relevant for the binding process. * * @param method The Method to process. * @return A MethodSpec instance representing the method metadata relevant to the Camel binding process. */ public static MethodSpec fromMethod(Method method) { method = AnnotationUtils.getAnnotatedMethod(method.getDeclaringClass(), method); MethodSpec answer = new MethodSpec(); Annotation[][] annotations = method.getParameterAnnotations(); int paramCount = method.getParameterTypes().length; answer.paramNames = new String[paramCount]; answer.multipartNames = new String[paramCount]; answer.multipartTypes = new String[paramCount]; // remember the names of parameters to be bound to headers and/or attachments for (int i = 0; i < paramCount; i++) { // if the parameter has no annotations, let its array element remain = null for (Annotation a : annotations[i]) { // am I a header? if (HEADER_ANNOTATIONS.contains(a.annotationType())) { try { answer.paramNames[i] = (String) a.annotationType().getMethod("value", NO_PARAMETER_TYPES).invoke(a, NO_PARAMETERS); answer.numberParameters++; } catch (Exception e) { } } // am I multipart? if (Multipart.class.equals(a.annotationType())) { Multipart multipart = (Multipart) a; answer.multipart = true; answer.multipartNames[i] = multipart.value(); answer.multipartTypes[i] = multipart.type(); } } } // if we are not multipart and the number of detected JAX-RS parameters (query, headers, etc.) is less than the number of method parameters // there's one parameter that will serve as message body if (!answer.multipart && answer.numberParameters < method.getParameterTypes().length) { for (int i = 0; i < answer.paramNames.length; i++) { if (answer.paramNames[i] == null) { answer.entityIndex = i; break; } } } return answer; } } }
apache-2.0
felipewmartins/aesh
src/main/java/org/jboss/aesh/edit/KeyOperation.java
2637
/* * JBoss, Home of Professional Open Source * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.aesh.edit; import org.jboss.aesh.edit.actions.Action; import org.jboss.aesh.edit.actions.Operation; import org.jboss.aesh.terminal.Key; /** * @author Ståle W. Pedersen <stale.pedersen@jboss.org> */ public class KeyOperation { private final Key key; private final Operation operation; private Action workingMode = Action.NO_ACTION; public KeyOperation(Key key, Operation operation) { this.key = key; this.operation = operation; } public KeyOperation(Key key, Operation operation, Action workingMode) { this.key = key; this.operation = operation; this.workingMode = workingMode; } public Key getKey() { return key; } public int[] getKeyValues() { return key.getKeyValues(); } public int getFirstValue() { return key.getFirstValue(); } public Operation getOperation() { return operation; } public Action getWorkingMode() { return workingMode; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof KeyOperation)) return false; KeyOperation that = (KeyOperation) o; return key == that.key && operation == that.operation && workingMode == that.workingMode; } @Override public int hashCode() { int result = key.hashCode(); result = 31 * result + operation.hashCode(); result = 31 * result + workingMode.hashCode(); return result; } @Override public String toString() { return "KeyOperation{" + "key=" + key + ", operation=" + operation + ", workingMode=" + workingMode + '}'; } }
apache-2.0
srvaroa/RxJava
rxjava-core/src/test/java/rx/ObservableDoOnTest.java
2430
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.junit.Test; import rx.functions.Action0; import rx.functions.Action1; public class ObservableDoOnTest { @Test public void testDoOnEach() { final AtomicReference<String> r = new AtomicReference<String>(); String output = Observable.from("one").doOnNext(new Action1<String>() { @Override public void call(String v) { r.set(v); } }).toBlocking().single(); assertEquals("one", output); assertEquals("one", r.get()); } @Test public void testDoOnError() { final AtomicReference<Throwable> r = new AtomicReference<Throwable>(); Throwable t = null; try { Observable.<String> error(new RuntimeException("an error")).doOnError(new Action1<Throwable>() { @Override public void call(Throwable v) { r.set(v); } }).toBlocking().single(); fail("expected exception, not a return value"); } catch (Throwable e) { t = e; } assertNotNull(t); assertEquals(t, r.get()); } @Test public void testDoOnCompleted() { final AtomicBoolean r = new AtomicBoolean(); String output = Observable.from("one").doOnCompleted(new Action0() { @Override public void call() { r.set(true); } }).toBlocking().single(); assertEquals("one", output); assertTrue(r.get()); } }
apache-2.0
suraj-raturi/pinpoint
plugins/openwhisk/src/main/java/com/navercorp/pinpoint/plugin/openwhisk/descriptor/LogMarkerMethodDescriptor.java
2295
/* * Copyright 2018 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.plugin.openwhisk.descriptor; import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor; import com.navercorp.pinpoint.common.trace.MethodType; import org.apache.openwhisk.common.LogMarkerToken; public class LogMarkerMethodDescriptor implements MethodDescriptor { private int apiId = 0; private int type = MethodType.INVOCATION; private String fullName; private String className; private String methodName; private String apiDescriptor; public LogMarkerMethodDescriptor(LogMarkerToken logMarkerToken) { this.className = logMarkerToken.component(); this.methodName = logMarkerToken.action(); this.fullName = className + "_" + methodName; } @Override public String getMethodName() { return methodName; } @Override public String getClassName() { return className; } @Override public String[] getParameterTypes() { return null; } @Override public String[] getParameterVariableName() { return null; } @Override public String getParameterDescriptor() { return "()"; } @Override public int getLineNumber() { return -1; } @Override public String getFullName() { return this.fullName; } @Override public void setApiId(int apiId) { this.apiId = apiId; } @Override public int getApiId() { return apiId; } @Override public String getApiDescriptor() { return apiDescriptor; } public int getType() { return type; } public void setType(int type) { this.type = type; } }
apache-2.0
rmetzger/flink
flink-formats/flink-avro/src/main/java/org/apache/flink/formats/avro/AvroFileSystemFormatFactory.java
7445
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.formats.avro; import org.apache.flink.api.common.io.InputFormat; import org.apache.flink.configuration.ConfigOption; import org.apache.flink.core.fs.FileInputSplit; import org.apache.flink.core.fs.Path; import org.apache.flink.formats.avro.typeutils.AvroSchemaConverter; import org.apache.flink.table.data.GenericRowData; import org.apache.flink.table.data.RowData; import org.apache.flink.table.factories.FileSystemFormatFactory; import org.apache.flink.table.types.DataType; import org.apache.flink.table.types.logical.RowType; import org.apache.flink.table.utils.PartitionPathUtils; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.IndexedRecord; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import static org.apache.flink.formats.avro.AvroFileFormatFactory.AVRO_OUTPUT_CODEC; /** Avro format factory for file system. */ public class AvroFileSystemFormatFactory implements FileSystemFormatFactory { public static final String IDENTIFIER = "avro"; @Override public String factoryIdentifier() { return IDENTIFIER; } @Override public Set<ConfigOption<?>> requiredOptions() { return new HashSet<>(); } @Override public Set<ConfigOption<?>> optionalOptions() { Set<ConfigOption<?>> options = new HashSet<>(); options.add(AVRO_OUTPUT_CODEC); return options; } @Override public InputFormat<RowData, ?> createReader(ReaderContext context) { String[] fieldNames = context.getSchema().getFieldNames(); List<String> projectFields = Arrays.stream(context.getProjectFields()) .mapToObj(idx -> fieldNames[idx]) .collect(Collectors.toList()); List<String> csvFields = Arrays.stream(fieldNames) .filter(field -> !context.getPartitionKeys().contains(field)) .collect(Collectors.toList()); int[] selectFieldToProjectField = context.getFormatProjectFields().stream() .mapToInt(projectFields::indexOf) .toArray(); int[] selectFieldToFormatField = context.getFormatProjectFields().stream().mapToInt(csvFields::indexOf).toArray(); //noinspection unchecked return new RowDataAvroInputFormat( context.getPaths(), context.getFormatRowType(), context.getSchema().getFieldDataTypes(), context.getSchema().getFieldNames(), context.getProjectFields(), context.getPartitionKeys(), context.getDefaultPartName(), context.getPushedDownLimit(), selectFieldToProjectField, selectFieldToFormatField); } /** * InputFormat that reads avro record into {@link RowData}. * * <p>This extends {@link AvroInputFormat}, but {@link RowData} is not a avro record, so now we * remove generic information. TODO {@link AvroInputFormat} support type conversion. */ private static class RowDataAvroInputFormat extends AvroInputFormat { private static final long serialVersionUID = 1L; private final DataType[] fieldTypes; private final String[] fieldNames; private final int[] selectFields; private final List<String> partitionKeys; private final String defaultPartValue; private final long limit; private final int[] selectFieldToProjectField; private final int[] selectFieldToFormatField; private final RowType formatRowType; private transient long emitted; // reuse object for per record private transient GenericRowData rowData; private transient IndexedRecord record; private transient AvroToRowDataConverters.AvroToRowDataConverter converter; public RowDataAvroInputFormat( Path[] filePaths, RowType formatRowType, DataType[] fieldTypes, String[] fieldNames, int[] selectFields, List<String> partitionKeys, String defaultPartValue, long limit, int[] selectFieldToProjectField, int[] selectFieldToFormatField) { super(filePaths[0], GenericRecord.class); super.setFilePaths(filePaths); this.formatRowType = formatRowType; this.fieldTypes = fieldTypes; this.fieldNames = fieldNames; this.partitionKeys = partitionKeys; this.defaultPartValue = defaultPartValue; this.selectFields = selectFields; this.limit = limit; this.emitted = 0; this.selectFieldToProjectField = selectFieldToProjectField; this.selectFieldToFormatField = selectFieldToFormatField; } @Override public void open(FileInputSplit split) throws IOException { super.open(split); Schema schema = AvroSchemaConverter.convertToSchema(formatRowType); record = new GenericData.Record(schema); rowData = PartitionPathUtils.fillPartitionValueForRecord( fieldNames, fieldTypes, selectFields, partitionKeys, currentSplit.getPath(), defaultPartValue); this.converter = AvroToRowDataConverters.createRowConverter(formatRowType); } @Override public boolean reachedEnd() throws IOException { return emitted >= limit || super.reachedEnd(); } @Override public Object nextRecord(Object reuse) throws IOException { @SuppressWarnings("unchecked") IndexedRecord r = (IndexedRecord) super.nextRecord(record); if (r == null) { return null; } GenericRowData row = (GenericRowData) converter.convert(r); for (int i = 0; i < selectFieldToFormatField.length; i++) { rowData.setField( selectFieldToProjectField[i], row.getField(selectFieldToFormatField[i])); } emitted++; return rowData; } } }
apache-2.0
baboune/compass
src/main/src/org/compass/core/lucene/engine/transaction/support/PrepareCommitCallable.java
1608
/* * Copyright 2004-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.compass.core.lucene.engine.transaction.support; import java.util.concurrent.Callable; import org.apache.lucene.index.IndexWriter; import org.compass.core.engine.SearchEngineException; /** * A simple callable that calls {@link org.apache.lucene.index.IndexWriter#prepareCommit()}. Nothing * is done in case of an exception, it is propagated outside of the callable. * * @author kimchy */ public class PrepareCommitCallable implements Callable { private final String subIndex; private final IndexWriter indexWriter; public PrepareCommitCallable(String subIndex, IndexWriter indexWriter) { this.subIndex = subIndex; this.indexWriter = indexWriter; } public Object call() throws Exception { try { indexWriter.prepareCommit(); } catch (Exception e) { throw new SearchEngineException("Failed to call prepare commit on sub index [" + subIndex + "]", e); } return null; } }
apache-2.0
leafclick/intellij-community
platform/platform-impl/src/com/intellij/ui/tabs/layout/tableLayout/TablePassInfo.java
1905
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.tabs.layout.tableLayout; import com.intellij.ui.tabs.TabInfo; import com.intellij.ui.tabs.impl.tabsLayout.TabsLayout; import com.intellij.ui.tabs.impl.tabsLayout.TabsLayoutCallback; import com.intellij.ui.tabs.layout.LayoutPassInfoBase; import java.awt.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TablePassInfo extends LayoutPassInfoBase { final List<TableRow> table = new ArrayList<>(); public Rectangle toFitRec; final Map<TabInfo, TableRow> myInfo2Row = new HashMap<>(); int requiredWidth; int requiredRows; int rowToFitMaxX; final TabsLayoutCallback myCallback; List<LineCoordinates> myExtraBorderLines = new ArrayList<>(); public TablePassInfo(List<TabInfo> visibleInfos, TabsLayout tabsLayout, TabsLayoutCallback tabsLayoutCallback) { super(visibleInfos, tabsLayout, tabsLayoutCallback); myCallback = tabsLayoutCallback; } public boolean isInSelectionRow(final TabInfo tabInfo) { final TableRow row = myInfo2Row.get(tabInfo); final int index = table.indexOf(row); return index != -1 && index == table.size() - 1; } @Deprecated @Override public int getRowCount() { return table.size(); } @Deprecated @Override public int getColumnCount(final int row) { return table.get(row).myColumns.size(); } @Deprecated @Override public TabInfo getTabAt(final int row, final int column) { return table.get(row).myColumns.get(column); } @Override public Rectangle getHeaderRectangle() { return (Rectangle)toFitRec.clone(); } @Override public List<LineCoordinates> getExtraBorderLines() { return myExtraBorderLines; } }
apache-2.0
guozhangwang/kafka
streams/src/main/java/org/apache/kafka/streams/KeyQueryMetadata.java
4472
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.streams; import org.apache.kafka.streams.state.HostInfo; import java.util.Collections; import java.util.Objects; import java.util.Set; /** * Represents all the metadata related to a key, where a particular key resides in a {@link KafkaStreams} application. * It contains the active {@link HostInfo} and a set of standby {@link HostInfo}s, denoting the instances where the key resides. * It also contains the partition number where the key belongs, which could be useful when used in conjunction with other APIs. * e.g: Relating with lags for that store partition. * NOTE: This is a point in time view. It may change as rebalances happen. */ public class KeyQueryMetadata { /** * Sentinel to indicate that the KeyQueryMetadata is currently unavailable. This can occur during rebalance * operations. */ public static final KeyQueryMetadata NOT_AVAILABLE = new KeyQueryMetadata(HostInfo.unavailable(), Collections.emptySet(), -1); private final HostInfo activeHost; private final Set<HostInfo> standbyHosts; private final int partition; public KeyQueryMetadata(final HostInfo activeHost, final Set<HostInfo> standbyHosts, final int partition) { this.activeHost = activeHost; this.standbyHosts = standbyHosts; this.partition = partition; } /** * Get the active Kafka Streams instance for given key. * * @return active instance's {@link HostInfo} * @deprecated Use {@link #activeHost()} instead. */ @Deprecated public HostInfo getActiveHost() { return activeHost; } /** * Get the Kafka Streams instances that host the key as standbys. * * @return set of standby {@link HostInfo} or a empty set, if no standbys are configured * @deprecated Use {@link #standbyHosts()} instead. */ @Deprecated public Set<HostInfo> getStandbyHosts() { return standbyHosts; } /** * Get the store partition corresponding to the key. * * @return store partition number * @deprecated Use {@link #partition()} instead. */ @Deprecated public int getPartition() { return partition; } /** * Get the active Kafka Streams instance for given key. * * @return active instance's {@link HostInfo} */ public HostInfo activeHost() { return activeHost; } /** * Get the Kafka Streams instances that host the key as standbys. * * @return set of standby {@link HostInfo} or a empty set, if no standbys are configured */ public Set<HostInfo> standbyHosts() { return standbyHosts; } /** * Get the store partition corresponding to the key. * * @return store partition number */ public int partition() { return partition; } @Override public boolean equals(final Object obj) { if (!(obj instanceof KeyQueryMetadata)) { return false; } final KeyQueryMetadata keyQueryMetadata = (KeyQueryMetadata) obj; return Objects.equals(keyQueryMetadata.activeHost, activeHost) && Objects.equals(keyQueryMetadata.standbyHosts, standbyHosts) && Objects.equals(keyQueryMetadata.partition, partition); } @Override public String toString() { return "KeyQueryMetadata {" + "activeHost=" + activeHost + ", standbyHosts=" + standbyHosts + ", partition=" + partition + '}'; } @Override public int hashCode() { return Objects.hash(activeHost, standbyHosts, partition); } }
apache-2.0
troyel/dhis2-core
dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/validation/DefaultValidationCriteriaService.java
3639
package org.hisp.dhis.validation; /* * Copyright (c) 2004-2017, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import org.hisp.dhis.common.GenericNameableObjectStore; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @author Chau Thu Tran * @version $Id$ */ @Transactional public class DefaultValidationCriteriaService implements ValidationCriteriaService { // ------------------------------------------------------------------------- // Dependency // ------------------------------------------------------------------------- private GenericNameableObjectStore<ValidationCriteria> validationCriteriaStore; public void setValidationCriteriaStore( GenericNameableObjectStore<ValidationCriteria> validationCriteriaStore ) { this.validationCriteriaStore = validationCriteriaStore; } // ------------------------------------------------------------------------- // ValidationCriteria implementation // ------------------------------------------------------------------------- @Override public int saveValidationCriteria( ValidationCriteria validationCriteria ) { validationCriteriaStore.save( validationCriteria ); return validationCriteria.getId(); } @Override public void updateValidationCriteria( ValidationCriteria validationCriteria ) { validationCriteriaStore.update( validationCriteria ); } @Override public void deleteValidationCriteria( ValidationCriteria validationCriteria ) { validationCriteriaStore.delete( validationCriteria ); } @Override public ValidationCriteria getValidationCriteria( int id ) { return validationCriteriaStore.get( id ); } @Override public List<ValidationCriteria> getAllValidationCriterias() { return validationCriteriaStore.getAll(); } @Override public ValidationCriteria getValidationCriteria( String name ) { return validationCriteriaStore.getByName( name ); } }
bsd-3-clause
jamesr/flutter_engine
shell/platform/android/test/io/flutter/FlutterTestSuite.java
4483
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter; import io.flutter.embedding.android.FlutterActivityAndFragmentDelegateTest; import io.flutter.embedding.android.FlutterActivityTest; import io.flutter.embedding.android.FlutterAndroidComponentTest; import io.flutter.embedding.android.FlutterFragmentActivityTest; import io.flutter.embedding.android.FlutterFragmentTest; import io.flutter.embedding.android.FlutterViewTest; import io.flutter.embedding.android.KeyChannelResponderTest; import io.flutter.embedding.android.KeyboardManagerTest; import io.flutter.embedding.engine.FlutterEngineCacheTest; import io.flutter.embedding.engine.FlutterEngineConnectionRegistryTest; import io.flutter.embedding.engine.FlutterEngineGroupComponentTest; import io.flutter.embedding.engine.FlutterJNITest; import io.flutter.embedding.engine.LocalizationPluginTest; import io.flutter.embedding.engine.RenderingComponentTest; import io.flutter.embedding.engine.dart.DartExecutorTest; import io.flutter.embedding.engine.dart.DartMessengerTest; import io.flutter.embedding.engine.deferredcomponents.PlayStoreDeferredComponentManagerTest; import io.flutter.embedding.engine.loader.ApplicationInfoLoaderTest; import io.flutter.embedding.engine.loader.FlutterLoaderTest; import io.flutter.embedding.engine.mutatorsstack.FlutterMutatorViewTest; import io.flutter.embedding.engine.plugins.shim.ShimPluginRegistryTest; import io.flutter.embedding.engine.renderer.FlutterRendererTest; import io.flutter.embedding.engine.systemchannels.DeferredComponentChannelTest; import io.flutter.embedding.engine.systemchannels.KeyEventChannelTest; import io.flutter.embedding.engine.systemchannels.PlatformChannelTest; import io.flutter.embedding.engine.systemchannels.RestorationChannelTest; import io.flutter.external.FlutterLaunchTests; import io.flutter.plugin.common.BinaryCodecTest; import io.flutter.plugin.common.StandardMessageCodecTest; import io.flutter.plugin.common.StandardMethodCodecTest; import io.flutter.plugin.editing.InputConnectionAdaptorTest; import io.flutter.plugin.editing.ListenableEditingStateTest; import io.flutter.plugin.editing.TextInputPluginTest; import io.flutter.plugin.mouse.MouseCursorPluginTest; import io.flutter.plugin.platform.PlatformPluginTest; import io.flutter.plugin.platform.PlatformViewsControllerTest; import io.flutter.plugin.platform.SingleViewPresentationTest; import io.flutter.util.PreconditionsTest; import io.flutter.view.AccessibilityBridgeTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import test.io.flutter.embedding.engine.FlutterEngineTest; import test.io.flutter.embedding.engine.FlutterShellArgsTest; import test.io.flutter.embedding.engine.PluginComponentTest; @RunWith(Suite.class) @SuiteClasses({ AccessibilityBridgeTest.class, ApplicationInfoLoaderTest.class, BinaryCodecTest.class, DartExecutorTest.class, DartMessengerTest.class, FlutterActivityAndFragmentDelegateTest.class, FlutterActivityTest.class, FlutterAndroidComponentTest.class, FlutterEngineCacheTest.class, FlutterEngineConnectionRegistryTest.class, FlutterEngineGroupComponentTest.class, FlutterEngineTest.class, FlutterFragmentActivityTest.class, FlutterFragmentTest.class, FlutterInjectorTest.class, FlutterJNITest.class, FlutterLaunchTests.class, FlutterLoaderTest.class, FlutterMutatorViewTest.class, FlutterShellArgsTest.class, FlutterRendererTest.class, FlutterShellArgsTest.class, FlutterViewTest.class, InputConnectionAdaptorTest.class, DeferredComponentChannelTest.class, KeyboardManagerTest.class, KeyChannelResponderTest.class, KeyEventChannelTest.class, ListenableEditingStateTest.class, LocalizationPluginTest.class, MouseCursorPluginTest.class, PlatformChannelTest.class, PlatformPluginTest.class, PlatformViewsControllerTest.class, PlayStoreDeferredComponentManagerTest.class, PluginComponentTest.class, PreconditionsTest.class, RenderingComponentTest.class, RestorationChannelTest.class, ShimPluginRegistryTest.class, SingleViewPresentationTest.class, SmokeTest.class, StandardMessageCodecTest.class, StandardMethodCodecTest.class, TextInputPluginTest.class, }) /** Runs all of the unit tests listed in the {@code @SuiteClasses} annotation. */ public class FlutterTestSuite {}
bsd-3-clause
AdamStelmaszczyk/stripe-java
src/main/java/com/stripe/model/ApplicationFeeCollection.java
111
package com.stripe.model; public class ApplicationFeeCollection extends StripeCollection<ApplicationFee> { }
mit
BD-ITAC/BD-ITAC
mobile/Alertas/MPChartLib/src/main/java/com/github/mikephil/charting/data/realm/implementation/RealmRadarData.java
633
package com.github.mikephil.charting.data.realm.implementation; import com.github.mikephil.charting.data.RadarData; import com.github.mikephil.charting.data.realm.base.RealmUtils; import com.github.mikephil.charting.interfaces.datasets.IRadarDataSet; import java.util.List; import io.realm.RealmObject; import io.realm.RealmResults; /** * Created by Philipp Jahoda on 19/12/15. */ public class RealmRadarData extends RadarData{ public RealmRadarData(RealmResults<? extends RealmObject> result, String xValuesField, List<IRadarDataSet> dataSets) { super(RealmUtils.toXVals(result, xValuesField), dataSets); } }
mit
anwfr/XChange
xchange-itbit/src/main/java/org/knowm/xchange/itbit/v1/service/ItBitMarketDataService.java
1800
package org.knowm.xchange.itbit.v1.service; import java.io.IOException; import java.util.List; import org.knowm.xchange.Exchange; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order.OrderType; import org.knowm.xchange.dto.marketdata.OrderBook; import org.knowm.xchange.dto.marketdata.Ticker; import org.knowm.xchange.dto.marketdata.Trades; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.itbit.v1.ItBitAdapters; import org.knowm.xchange.itbit.v1.dto.marketdata.ItBitDepth; import org.knowm.xchange.itbit.v1.dto.marketdata.ItBitTicker; import org.knowm.xchange.service.marketdata.MarketDataService; public class ItBitMarketDataService extends ItBitMarketDataServiceRaw implements MarketDataService { /** * Constructor * * @param exchange */ public ItBitMarketDataService(Exchange exchange) { super(exchange); } @Override public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException { ItBitTicker itBitTicker = getItBitTicker(currencyPair); return ItBitAdapters.adaptTicker(currencyPair, itBitTicker); } @Override public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException { ItBitDepth depth = getItBitDepth(currencyPair, args); List<LimitOrder> asks = ItBitAdapters.adaptOrders(depth.getAsks(), currencyPair, OrderType.ASK); List<LimitOrder> bids = ItBitAdapters.adaptOrders(depth.getBids(), currencyPair, OrderType.BID); return new OrderBook(null, asks, bids); } @Override public Trades getTrades(CurrencyPair currencyPair, Object... args) throws IOException { return ItBitAdapters.adaptTrades(getItBitTrades(currencyPair, args), currencyPair); } }
mit
joshgarde/SpongeAPI
src/main/java/org/spongepowered/api/event/state/ServerStoppingEvent.java
1462
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.event.state; import org.spongepowered.api.GameState; /** * Represents a {@link GameState#SERVER_STOPPING} event. */ public interface ServerStoppingEvent extends StateEvent { }
mit
sannies/args4j
args4j-tools/test/org/kohsuke/args4j/apt/AnnotationVisitorReordererTest.java
1688
package org.kohsuke.args4j.apt; import junit.framework.TestCase; import org.kohsuke.args4j.Option; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class AnnotationVisitorReordererTest extends TestCase { private AnnotationVisitor target; private AnnotationVisitorReorderer reorderer; final OptionWithUsage optionb = new OptionWithUsage(mockOption("-b"), "optionb"); final OptionWithUsage optiona = new OptionWithUsage(mockOption("-a"), "optiona"); protected void setUp() throws Exception { super.setUp(); target = mock(AnnotationVisitor.class); reorderer = new AnnotationVisitorReorderer(target); } public void testReorderWithUnorderedAnnotations() throws Exception { simulateOnOptionsThenDone(optionb, optiona); verifyOptionsThenDone(optiona, optionb); } public void testReorderWithAlreadyOrderedAnnotations() throws Exception { simulateOnOptionsThenDone(optiona, optionb); verifyOptionsThenDone(optiona, optionb); } private void simulateOnOptionsThenDone(OptionWithUsage... options) { for (OptionWithUsage option : options) { reorderer.onOption(option); } reorderer.done(); } private void verifyOptionsThenDone(OptionWithUsage... options) { for (OptionWithUsage option : options) { verify(target).onOption(option); } verify(target).done(); } private Option mockOption(String name) { Option option1 = mock(Option.class); when(option1.name()).thenReturn(name); return option1; } }
mit
sbrannen/junit-lambda
junit-platform-console/src/main/java/org/junit/platform/console/tasks/package-info.java
109
/** * Internal execution tasks for JUnit's console launcher. */ package org.junit.platform.console.tasks;
epl-1.0
RallySoftware/eclipselink.runtime
foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/models/generic/ClassI17.java
812
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.models.generic; public interface ClassI17 { }
epl-1.0
RallySoftware/eclipselink.runtime
jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/models/jpa/xml/relationships/Order.java
2640
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.models.jpa.xml.relationships; public class Order implements java.io.Serializable { private Integer orderId; private int version; private Item item; private int quantity; private String shippingAddress; private Customer customer; private Auditor auditor; private OrderLabel orderLabel; private OrderCard orderCard; public Order() {} public Auditor getAuditor() { return auditor; } public void setAuditor(Auditor auditor) { this.auditor = auditor; } public OrderLabel getOrderLabel() { return orderLabel; } public void setOrderLabel(OrderLabel orderLabel) { this.orderLabel = orderLabel; } public OrderCard getOrderCard() { return orderCard; } public void setOrderCard(OrderCard orderCard) { this.orderCard = orderCard; if (this.orderCard != null) { this.orderCard.setOrder(this); } } public Integer getOrderId() { return orderId; } public void setOrderId(Integer id) { this.orderId = id; } protected int getVersion() { return version; } protected void setVersion(int version) { this.version = version; } public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public String getShippingAddress() { return shippingAddress; } public void setShippingAddress(String shippingAddress) { this.shippingAddress = shippingAddress; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } }
epl-1.0
RallySoftware/eclipselink.runtime
jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/models/jpa/inheritance/RockTireInfo.java
1249
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.models.jpa.inheritance; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name="CMP3_ROCK_TIRE") @DiscriminatorValue("Rock") public class RockTireInfo extends OffRoadTireInfo { public enum Grip { REGULAR, SUPER, MEGA } protected Grip grip; public RockTireInfo() {} public Grip getGrip() { return grip; } public void setGrip(Grip grip) { this.grip = grip; } }
epl-1.0
RallySoftware/eclipselink.runtime
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/mappings/xmlfragmentcollection/XMLFragmentCollectionElementDiffPrefixTestCases.java
2582
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.oxm.mappings.xmlfragmentcollection; import java.io.InputStream; import java.util.ArrayList; import org.eclipse.persistence.oxm.NamespaceResolver; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class XMLFragmentCollectionElementDiffPrefixTestCases extends XMLFragmentCollectionNSTestCases { private final static String XML_RESOURCE_DIFF_PFX = "org/eclipse/persistence/testing/oxm/mappings/xmlfragmentcollection/employee_element_ns_different_prefix.xml"; private final static String XML_SUB_ELEMENT_DIFF_PFX = "org/eclipse/persistence/testing/oxm/mappings/xmlfragmentcollection/sub_element_ns_different_prefix.xml"; public XMLFragmentCollectionElementDiffPrefixTestCases(String name) throws Exception { super(name); NamespaceResolver nsresolver = new NamespaceResolver(); nsresolver.put("ns1", "http://www.example.com/test-uri"); setProject(new XMLFragmentCollectionElementProject(nsresolver)); setControlDocument(XML_RESOURCE_DIFF_PFX); } protected Object getControlObject() { Employee employee = new Employee(); employee.firstName = "Jane"; employee.lastName = "Doe"; try { InputStream inputStream = ClassLoader.getSystemResourceAsStream(XML_SUB_ELEMENT_DIFF_PFX); Document xdoc = parser.parse(inputStream); removeEmptyTextNodes(xdoc); inputStream.close(); employee.xmlnodes = new ArrayList<Node>(); NodeList xmlnodes = xdoc.getElementsByTagName("xml-node"); for (int i = 0; i < xmlnodes.getLength(); i++) { employee.xmlnodes.add(xmlnodes.item(i)); } } catch (Exception ex) { ex.printStackTrace(); } return employee; } }
epl-1.0
lucasicf/metricgenerator-jdk-compiler
test/tools/javac/missingSuperRecovery/MissingSuperRecovery.java
624
/* * @test /nodynamiccopyright/ * @bug 4332631 4785453 * @summary Check for proper error recovery when superclass of extended * class is no longer available during a subsequent compilation. * @author maddox * * @compile/fail/ref=MissingSuperRecovery.out -XDstdout -XDdiags=%b:%l:%_%m MissingSuperRecovery.java */ // Requires "golden" class file 'impl.class', which contains // a reference to a superclass at a location no longer on the classpath. // Note that this test should elicit an error, but should not cause a compiler crash. public class MissingSuperRecovery extends impl { private String workdir=""; }
gpl-2.0
isaacl/openjdk-jdk
src/share/classes/javax/swing/text/NavigationFilter.java
6110
/* * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.text; import java.awt.Shape; /** * <code>NavigationFilter</code> can be used to restrict where the cursor can * be positioned. When the default cursor positioning actions attempt to * reposition the cursor they will call into the * <code>NavigationFilter</code>, assuming * the <code>JTextComponent</code> has a non-null * <code>NavigationFilter</code> set. In this manner * the <code>NavigationFilter</code> can effectively restrict where the * cursor can be positioned. Similarly <code>DefaultCaret</code> will call * into the <code>NavigationFilter</code> when the user is changing the * selection to further restrict where the cursor can be positioned. * <p> * Subclasses can conditionally call into supers implementation to restrict * where the cursor can be placed, or call directly into the * <code>FilterBypass</code>. * * @see javax.swing.text.Caret * @see javax.swing.text.DefaultCaret * @see javax.swing.text.View * * @since 1.4 */ public class NavigationFilter { /** * Invoked prior to the Caret setting the dot. The default implementation * calls directly into the <code>FilterBypass</code> with the passed * in arguments. Subclasses may wish to conditionally * call super with a different location, or invoke the necessary method * on the <code>FilterBypass</code> * * @param fb FilterBypass that can be used to mutate caret position * @param dot the position &gt;= 0 * @param bias Bias to place the dot at */ public void setDot(FilterBypass fb, int dot, Position.Bias bias) { fb.setDot(dot, bias); } /** * Invoked prior to the Caret moving the dot. The default implementation * calls directly into the <code>FilterBypass</code> with the passed * in arguments. Subclasses may wish to conditionally * call super with a different location, or invoke the necessary * methods on the <code>FilterBypass</code>. * * @param fb FilterBypass that can be used to mutate caret position * @param dot the position &gt;= 0 * @param bias Bias for new location */ public void moveDot(FilterBypass fb, int dot, Position.Bias bias) { fb.moveDot(dot, bias); } /** * Returns the next visual position to place the caret at from an * existing position. The default implementation simply forwards the * method to the root View. Subclasses may wish to further restrict the * location based on additional criteria. * * @param text JTextComponent containing text * @param pos Position used in determining next position * @param bias Bias used in determining next position * @param direction the direction from the current position that can * be thought of as the arrow keys typically found on a keyboard. * This will be one of the following values: * <ul> * <li>SwingConstants.WEST * <li>SwingConstants.EAST * <li>SwingConstants.NORTH * <li>SwingConstants.SOUTH * </ul> * @param biasRet Used to return resulting Bias of next position * @return the location within the model that best represents the next * location visual position * @exception BadLocationException for a bad location within a document model * @exception IllegalArgumentException if <code>direction</code> * doesn't have one of the legal values above */ public int getNextVisualPositionFrom(JTextComponent text, int pos, Position.Bias bias, int direction, Position.Bias[] biasRet) throws BadLocationException { return text.getUI().getNextVisualPositionFrom(text, pos, bias, direction, biasRet); } /** * Used as a way to circumvent calling back into the caret to * position the cursor. Caret implementations that wish to support * a NavigationFilter must provide an implementation that will * not callback into the NavigationFilter. * @since 1.4 */ public static abstract class FilterBypass { /** * Returns the Caret that is changing. * * @return Caret that is changing */ public abstract Caret getCaret(); /** * Sets the caret location, bypassing the NavigationFilter. * * @param dot the position &gt;= 0 * @param bias Bias to place the dot at */ public abstract void setDot(int dot, Position.Bias bias); /** * Moves the caret location, bypassing the NavigationFilter. * * @param dot the position &gt;= 0 * @param bias Bias for new location */ public abstract void moveDot(int dot, Position.Bias bias); } }
gpl-2.0
danielyc/test-1.9.4
build/tmp/recompileMc/sources/net/minecraftforge/items/CapabilityItemHandler.java
2707
package net.minecraftforge.items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.capabilities.CapabilityManager; import java.util.concurrent.Callable; public class CapabilityItemHandler { @CapabilityInject(IItemHandler.class) public static Capability<IItemHandler> ITEM_HANDLER_CAPABILITY = null; public static void register() { CapabilityManager.INSTANCE.register(IItemHandler.class, new Capability.IStorage<IItemHandler>() { @Override public NBTBase writeNBT(Capability<IItemHandler> capability, IItemHandler instance, EnumFacing side) { NBTTagList nbtTagList = new NBTTagList(); int size = instance.getSlots(); for (int i = 0; i < size; i++) { ItemStack stack = instance.getStackInSlot(i); if (stack != null) { NBTTagCompound itemTag = new NBTTagCompound(); itemTag.setInteger("Slot", i); stack.writeToNBT(itemTag); nbtTagList.appendTag(itemTag); } } return nbtTagList; } @Override public void readNBT(Capability<IItemHandler> capability, IItemHandler instance, EnumFacing side, NBTBase base) { if (!(instance instanceof IItemHandlerModifiable)) throw new RuntimeException("IItemHandler instance does not implement IItemHandlerModifiable"); IItemHandlerModifiable itemHandlerModifiable = (IItemHandlerModifiable) instance; NBTTagList tagList = (NBTTagList) base; for (int i = 0; i < tagList.tagCount(); i++) { NBTTagCompound itemTags = tagList.getCompoundTagAt(i); int j = itemTags.getInteger("Slot"); if (j >= 0 && j < instance.getSlots()) { itemHandlerModifiable.setStackInSlot(j, ItemStack.loadItemStackFromNBT(itemTags)); } } } }, new Callable<ItemStackHandler>() { @Override public ItemStackHandler call() throws Exception { return new ItemStackHandler(); } }); } }
gpl-3.0
Zerrens/InterstellarOres
src/main/java/appeng/api/networking/IGridMultiblock.java
716
package appeng.api.networking; import java.util.Iterator; /** * An extension of IGridBlock, only means something when your getFlags() contains REQUIRE_CHANNEL, when done properly it * will call the method to get a list of all related nodes and give each of them a channel simultaneously for the entire * set. This means your entire Multiblock can work with a single channel, instead of one channel per block. */ public interface IGridMultiblock extends IGridBlock { /** * Used to acquire a list of all nodes that are part of the multiblock. * * @return an iterator that will iterate all the nodes for the multiblock. ( read-only iterator expected. ) */ Iterator<IGridNode> getMultiblockNodes(); }
gpl-3.0
Jenyay/tasks
src/main/java/org/tasks/scheduling/BackupIntentService.java
2846
package org.tasks.scheduling; import android.content.Context; import com.todoroo.astrid.backup.TasksXmlExporter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tasks.preferences.Preferences; import java.io.File; import java.io.FileFilter; import java.util.Arrays; import java.util.Comparator; import javax.inject.Inject; public class BackupIntentService extends MidnightIntentService { private static final Logger log = LoggerFactory.getLogger(BackupIntentService.class); public static final String BACKUP_FILE_NAME_REGEX = "auto\\.[-\\d]+\\.xml"; //$NON-NLS-1$ private static final int DAYS_TO_KEEP_BACKUP = 7; @Inject TasksXmlExporter xmlExporter; @Inject Preferences preferences; public BackupIntentService() { super(BackupIntentService.class.getSimpleName()); } @Override void run() { startBackup(this); } @Override String getLastRunPreference() { return TasksXmlExporter.PREF_BACKUP_LAST_DATE; } /** * Test hook for backup */ void testBackup(TasksXmlExporter xmlExporter, Preferences preferences, Context context) { this.xmlExporter = xmlExporter; this.preferences = preferences; startBackup(context); } private void startBackup(Context context) { if (context == null || context.getResources() == null) { return; } try { deleteOldBackups(); } catch (Exception e) { log.error(e.getMessage(), e); } try { xmlExporter.exportTasks(context, TasksXmlExporter.ExportType.EXPORT_TYPE_SERVICE, null); } catch (Exception e) { log.error(e.getMessage(), e); } } private void deleteOldBackups() { FileFilter backupFileFilter = new FileFilter() { @Override public boolean accept(File file) { if (file.getName().matches(BACKUP_FILE_NAME_REGEX)) { return true; } return false; } }; File astridDir = preferences.getBackupDirectory(); if(astridDir == null) { return; } // grab all backup files, sort by modified date, delete old ones File[] files = astridDir.listFiles(backupFileFilter); if(files == null) { return; } Arrays.sort(files, new Comparator<File>() { @Override public int compare(File file1, File file2) { return -Long.valueOf(file1.lastModified()).compareTo(file2.lastModified()); } }); for(int i = DAYS_TO_KEEP_BACKUP; i < files.length; i++) { if(!files[i].delete()) { log.info("Unable to delete: {}", files[i]); } } } }
gpl-3.0
Zerrens/InterstellarOres
src/main/java/appeng/api/networking/crafting/ICraftingWatcherHost.java
664
package appeng.api.networking.crafting; import appeng.api.storage.data.IAEItemStack; public interface ICraftingWatcherHost { /** * provides the ICraftingWatcher for this host, for the current network, is called when the hot changes networks. * You do not need to clear your old watcher, its already been removed by the time this gets called. * * @param newWatcher crafting watcher for this host */ void updateWatcher(ICraftingWatcher newWatcher); /** * Called when a crafting status changes. * * @param craftingGrid current crafting grid * @param what change */ void onRequestChange(ICraftingGrid craftingGrid, IAEItemStack what); }
gpl-3.0
open-health-hub/openMAXIMS
openmaxims_workspace/Therapies/src/ims/therapies/domain/WheelchairReferral.java
2457
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.therapies.domain; // Generated from form domain impl public interface WheelchairReferral extends ims.domain.DomainInterface { // Generated from form domain interface definition /** * save WheelchairReferral */ public void save(ims.therapies.vo.WheelchairReferralVo voWheelchairReferral) throws ims.domain.exceptions.StaleObjectException, ims.domain.exceptions.UniqueKeyViolationException; // Generated from form domain interface definition /** * get */ public ims.therapies.vo.WheelchairReferralVoCollection getWheelchairReferralVoByCareContext(ims.core.vo.CareContextShortVo voCareContext); // Generated from form domain interface definition /** * returns a list of hcps */ public ims.core.vo.HcpCollection listHCPs(ims.core.vo.HcpFilter voHcpFilter); }
agpl-3.0
open-health-hub/openMAXIMS
openmaxims_workspace/SpinalInjuries/src/ims/spinalinjuries/forms/neurologicalexaminationmotor/BaseLogic.java
2718
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.spinalinjuries.forms.neurologicalexaminationmotor; public abstract class BaseLogic extends Handlers { public final Class getDomainInterface() throws ClassNotFoundException { return ims.spinalinjuries.domain.NeurologicalExaminationMotor.class; } public final void setContext(ims.framework.UIEngine engine, GenForm form, ims.spinalinjuries.domain.NeurologicalExaminationMotor domain) { setContext(engine, form); this.domain = domain; } public void initialize() throws ims.framework.exceptions.FormOpenException { } public boolean allowNew() { return form.getMode() == ims.framework.enumerations.FormMode.VIEW && !form.isReadOnly(); } public boolean allowUpdate() { return form.getMode() == ims.framework.enumerations.FormMode.VIEW && !form.isReadOnly(); } public String[] validateUIRules() { return null; } public void clear() { } public void search() { } public final void free() { super.free(); domain = null; } protected ims.spinalinjuries.domain.NeurologicalExaminationMotor domain; }
agpl-3.0
open-health-hub/openMAXIMS
openmaxims_workspace/ValueObjects/src/ims/coe/vo/MnaEnhancedVo.java
9903
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.coe.vo; public class MnaEnhancedVo extends ims.vo.ValueObject implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public MnaEnhancedVo() { } public MnaEnhancedVo(ims.coe.vo.beans.MnaEnhancedVoBean bean) { this.mnarecord = bean.getMnaRecord() == null ? null : bean.getMnaRecord().buildVo(); this.aedrecord = bean.getAedRecord() == null ? null : bean.getAedRecord().buildVo(); this.vsrecord = bean.getVsRecord() == null ? null : bean.getVsRecord().buildVo(); this.ashrecord = bean.getAshRecord() == null ? null : bean.getAshRecord().buildVo(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.coe.vo.beans.MnaEnhancedVoBean bean) { this.mnarecord = bean.getMnaRecord() == null ? null : bean.getMnaRecord().buildVo(map); this.aedrecord = bean.getAedRecord() == null ? null : bean.getAedRecord().buildVo(map); this.vsrecord = bean.getVsRecord() == null ? null : bean.getVsRecord().buildVo(map); this.ashrecord = bean.getAshRecord() == null ? null : bean.getAshRecord().buildVo(map); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.coe.vo.beans.MnaEnhancedVoBean bean = null; if(map != null) bean = (ims.coe.vo.beans.MnaEnhancedVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.coe.vo.beans.MnaEnhancedVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public boolean getMnaRecordIsNotNull() { return this.mnarecord != null; } public ims.nursing.vo.MiniNutritionalAssessment getMnaRecord() { return this.mnarecord; } public void setMnaRecord(ims.nursing.vo.MiniNutritionalAssessment value) { this.isValidated = false; this.mnarecord = value; } public boolean getAedRecordIsNotNull() { return this.aedrecord != null; } public ims.coe.vo.AssessmentEatingAndDrinking getAedRecord() { return this.aedrecord; } public void setAedRecord(ims.coe.vo.AssessmentEatingAndDrinking value) { this.isValidated = false; this.aedrecord = value; } public boolean getVsRecordIsNotNull() { return this.vsrecord != null; } public ims.core.vo.VitalSignsVo getVsRecord() { return this.vsrecord; } public void setVsRecord(ims.core.vo.VitalSignsVo value) { this.isValidated = false; this.vsrecord = value; } public boolean getAshRecordIsNotNull() { return this.ashrecord != null; } public ims.nursing.vo.AssessmentHeaderInfo getAshRecord() { return this.ashrecord; } public void setAshRecord(ims.nursing.vo.AssessmentHeaderInfo value) { this.isValidated = false; this.ashrecord = value; } public final String getIItemText() { return toString(); } public final Integer getBoId() { return null; } public final String getBoClassName() { return null; } public boolean equals(Object obj) { if(obj == null) return false; if(!(obj instanceof MnaEnhancedVo)) return false; MnaEnhancedVo compareObj = (MnaEnhancedVo)obj; if(this.getMnaRecord() == null && compareObj.getMnaRecord() != null) return false; if(this.getMnaRecord() != null && compareObj.getMnaRecord() == null) return false; if(this.getMnaRecord() != null && compareObj.getMnaRecord() != null) return this.getMnaRecord().equals(compareObj.getMnaRecord()); return super.equals(obj); } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } if(this.mnarecord != null) { if(!this.mnarecord.isValidated()) { this.isBusy = false; return false; } } if(this.aedrecord != null) { if(!this.aedrecord.isValidated()) { this.isBusy = false; return false; } } if(this.vsrecord != null) { if(!this.vsrecord.isValidated()) { this.isBusy = false; return false; } } if(this.ashrecord != null) { if(!this.ashrecord.isValidated()) { this.isBusy = false; return false; } } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } if(this.mnarecord != null) { String[] listOfOtherErrors = this.mnarecord.validate(); if(listOfOtherErrors != null) { for(int x = 0; x < listOfOtherErrors.length; x++) { listOfErrors.add(listOfOtherErrors[x]); } } } if(this.aedrecord != null) { String[] listOfOtherErrors = this.aedrecord.validate(); if(listOfOtherErrors != null) { for(int x = 0; x < listOfOtherErrors.length; x++) { listOfErrors.add(listOfOtherErrors[x]); } } } if(this.vsrecord != null) { String[] listOfOtherErrors = this.vsrecord.validate(); if(listOfOtherErrors != null) { for(int x = 0; x < listOfOtherErrors.length; x++) { listOfErrors.add(listOfOtherErrors[x]); } } } if(this.ashrecord != null) { String[] listOfOtherErrors = this.ashrecord.validate(); if(listOfOtherErrors != null) { for(int x = 0; x < listOfOtherErrors.length; x++) { listOfErrors.add(listOfOtherErrors[x]); } } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; MnaEnhancedVo clone = new MnaEnhancedVo(); if(this.mnarecord == null) clone.mnarecord = null; else clone.mnarecord = (ims.nursing.vo.MiniNutritionalAssessment)this.mnarecord.clone(); if(this.aedrecord == null) clone.aedrecord = null; else clone.aedrecord = (ims.coe.vo.AssessmentEatingAndDrinking)this.aedrecord.clone(); if(this.vsrecord == null) clone.vsrecord = null; else clone.vsrecord = (ims.core.vo.VitalSignsVo)this.vsrecord.clone(); if(this.ashrecord == null) clone.ashrecord = null; else clone.ashrecord = (ims.nursing.vo.AssessmentHeaderInfo)this.ashrecord.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(MnaEnhancedVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A MnaEnhancedVo object cannot be compared an Object of type " + obj.getClass().getName()); } MnaEnhancedVo compareObj = (MnaEnhancedVo)obj; int retVal = 0; if (retVal == 0) { if(this.getMnaRecord() == null && compareObj.getMnaRecord() != null) return -1; if(this.getMnaRecord() != null && compareObj.getMnaRecord() == null) return 1; if(this.getMnaRecord() != null && compareObj.getMnaRecord() != null) retVal = this.getMnaRecord().compareTo(compareObj.getMnaRecord()); } return retVal; } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.mnarecord != null) count++; if(this.aedrecord != null) count++; if(this.vsrecord != null) count++; if(this.ashrecord != null) count++; return count; } public int countValueObjectFields() { return 4; } protected ims.nursing.vo.MiniNutritionalAssessment mnarecord; protected ims.coe.vo.AssessmentEatingAndDrinking aedrecord; protected ims.core.vo.VitalSignsVo vsrecord; protected ims.nursing.vo.AssessmentHeaderInfo ashrecord; private boolean isValidated = false; private boolean isBusy = false; }
agpl-3.0
open-health-hub/openMAXIMS
openmaxims_workspace/RefMan/src/ims/RefMan/forms/removefromelectivelist/IFormUILogicCode.java
333
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.RefMan.forms.removefromelectivelist; public interface IFormUILogicCode { // No methods yet. }
agpl-3.0
open-health-hub/openMAXIMS
openmaxims_workspace/Assessment/src/ims/assessment/forms/userassessmentpreview/GlobalContext.java
2928
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.assessment.forms.userassessmentpreview; import java.io.Serializable; public final class GlobalContext extends ims.framework.FormContext implements Serializable { private static final long serialVersionUID = 1L; public GlobalContext(ims.framework.Context context) { super(context); Core = new CoreContext(context); } public final class CoreContext implements Serializable { private static final long serialVersionUID = 1L; private CoreContext(ims.framework.Context context) { this.context = context; } public boolean getSelectedUserAssessmentIsNotNull() { return !cx_CoreSelectedUserAssessment.getValueIsNull(context); } public ims.assessment.vo.UserAssessmentShortVo getSelectedUserAssessment() { return (ims.assessment.vo.UserAssessmentShortVo)cx_CoreSelectedUserAssessment.getValue(context); } public void setSelectedUserAssessment(ims.assessment.vo.UserAssessmentShortVo value) { cx_CoreSelectedUserAssessment.setValue(context, value); } private ims.framework.ContextVariable cx_CoreSelectedUserAssessment = new ims.framework.ContextVariable("Core.SelectedUserAssessment", "_cv_Core.SelectedUserAssessment"); private ims.framework.Context context; } public CoreContext Core; }
agpl-3.0
open-health-hub/openMAXIMS
openmaxims_workspace/Clinical/src/ims/clinical/forms/pastmedicalhistory/AccessLogic.java
1936
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Neil McAnaspie using IMS Development Environment (version 1.51 build 2480.15886) // Copyright (C) 1995-2006 IMS MAXIMS plc. All rights reserved. package ims.clinical.forms.pastmedicalhistory; import java.io.Serializable; public final class AccessLogic extends BaseAccessLogic implements Serializable { private static final long serialVersionUID = 1L; public boolean isAccessible() { if(!super.isAccessible()) return false; return true; } }
agpl-3.0