answer
stringlengths 17
10.2M
|
|---|
package io.nub.core.file.text;
import java.util.Iterator;
import io.nub.core.Nub;
import io.nub.core.file.File2;
import io.nub.core.i.ITable;
import io.nub.core.util.arrays.ArrayString;
/**
* @author Nektro
*/
public class CsvFile extends TextFile implements ITable, Iterable<String>
{
private static final long serialVersionUID = 1067439784131596081L;
private final String[][] value;
public CsvFile(String path) {
super("");
if (!this.extension.equals("csv")) {
// throw exception
}
this.value = new ArrayString(Nub.getLineContent(new File2(path).getInputStream()).toArray()).split(",");
}
@Override
public String getValue(int x, int y) {
return value[y][x];
}
@Override
public Iterator<String> iterator() {
return new Iterator<String>() {
private int x=0,y=0;
@Override
public boolean hasNext() {
return y != value.length && x != value[y].length;
}
@Override
public String next() {
String r = value[y][x];
x += 1;
if (x == value[y].length - 1) {
y += 1;
x = 0;
}
return r;
}
};
}
}
|
package de.sb.messenger.rest;
import static de.sb.messenger.persistence.Person.Group.ADMIN;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static javax.ws.rs.core.MediaType.APPLICATION_XML;
import static javax.ws.rs.core.Response.Status.CONFLICT;
import static javax.ws.rs.core.Response.Status.FORBIDDEN;
import static javax.ws.rs.core.Response.Status.NOT_FOUND;
import java.util.Arrays;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import javax.persistence.RollbackException;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import de.sb.messenger.persistence.BaseEntity;
import de.sb.messenger.persistence.Message;
import de.sb.messenger.persistence.Person;
import de.sb.toolbox.Copyright;
import de.sb.toolbox.net.RestCredentials;
import de.sb.toolbox.net.RestJpaLifecycleProvider;
/**
* JAX-RS based REST service implementation for polymorphic entity resources. The following path and
* method combinations are supported:
* <ul>
* <li>GET entities/{identity}: Returns the entity matching the given identity.</li>
* <li>DELETE entities/{identity}: Deletes the entity matching the given identity.</li>
* <li>GET entities/{identity}/messagesCaused: Returns the messages caused by the entity matching
* the given identity.</li>
* </ul>
*/
@Path("entities")
@Copyright(year=2013, holders="Sascha Baumeister")
public class EntityService {
static EntityManagerFactory messengerManagerFactory = null;
static private EntityManagerFactory getEntityManagerFactory() {
if(messengerManagerFactory==null) {
final EntityManager em = getEntityManager();
messengerManagerFactory=em.getEntityManagerFactory();
}
return messengerManagerFactory;
}
static public EntityManager getEntityManager(){
return RestJpaLifecycleProvider.entityManager("messenger");
}
@GET
@Path("{identity}")
@Produces({ APPLICATION_JSON, APPLICATION_XML })
public BaseEntity queryIdentity (@HeaderParam("Authorization") final String authentication, @PathParam("identity") final long identity) {
Authenticator.authenticate(RestCredentials.newBasicInstance(authentication));
final BaseEntity entity = getEntityManager().find(BaseEntity.class, identity);
if (entity == null) throw new NotFoundException();
return entity;
}
@DELETE
@Path("{identity}")
public void deleteEntity (@HeaderParam("Authorization") final String authentication, @PathParam("identity") final long identity) {
final Person requester = Authenticator.authenticate(RestCredentials.newBasicInstance(authentication));
final EntityManager em = getEntityManager();
if (requester.getGroup() != ADMIN) throw new ClientErrorException(FORBIDDEN);
getEntityManagerFactory().getCache().evict(BaseEntity.class, identity);
final BaseEntity entity = em.find(BaseEntity.class, identity);
if (entity == null) throw new ClientErrorException(NOT_FOUND);
em.remove(entity);
try {
em.getTransaction().commit();
} catch (final RollbackException exception) {
throw new ClientErrorException(CONFLICT);
} finally {
em.getTransaction().begin();
}
}
@GET
@Path("{identity}/messagesCaused")
@Produces({ APPLICATION_JSON, APPLICATION_XML })
public Message[] queryMessagesCaused (@HeaderParam("Authorization") final String authentication, @PathParam("identity") final long identity) {
Authenticator.authenticate(RestCredentials.newBasicInstance(authentication));
final BaseEntity entity = getEntityManager().find(BaseEntity.class, identity);
if (entity == null) throw new ClientErrorException(NOT_FOUND);
final Message[] messages = entity.getMessagesCaused().toArray(new Message[0]);
Arrays.sort(messages);
return messages;
}
}
|
package com.atlassian.webdriver.component.menu;
import com.atlassian.webdriver.AtlassianWebDriver;
import com.atlassian.webdriver.Link;
import com.atlassian.webdriver.PageObject;
import com.atlassian.webdriver.component.AbstractComponent;
import com.atlassian.webdriver.product.TestedProduct;
import com.atlassian.webdriver.utils.Check;
import com.atlassian.webdriver.utils.element.ElementLocated;
import com.atlassian.webdriver.utils.element.ElementNotLocated;
import org.apache.commons.lang.Validate;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
/**
* TODO: Document this class / interface here
*
* @since v4.2
*/
public class AuiDropdownMenu<T extends TestedProduct> extends AbstractComponent<T, AuiDropdownMenu<T>> implements DropdownMenu
{
protected WebElement menuItem;
public AuiDropdownMenu(T testedProduct)
{
super(testedProduct);
}
@Override
public void initialise(final By componentLocator)
{
super.initialise(componentLocator);
this.menuItem = getDriver().findElement(componentLocator);
}
public boolean isOpen()
{
return Check.hasClass("active", menuItem);
}
public void open()
{
if (!isOpen())
{
menuItem.findElement(By.cssSelector("a.drop")).click();
}
// Wait until the menu has finished loading items
getTestedProduct().getDriver().waitUntilElementIsNotLocatedAt(By.className("loading"), menuItem);
// Wait until the menu item has been injected after it's loaded.
getTestedProduct().getDriver().waitUntilElementIsLocatedAt(By.tagName("li"), menuItem);
}
public <T extends PageObject> T activate(Link<T> link)
{
open();
return link.activate(menuItem, getTestedProduct());
}
public void close()
{
if (isOpen())
{
menuItem.findElement(By.cssSelector("a.drop")).click();
}
}
}
|
package gov.nih.nci.cagrid.cadsr.portal.discovery;
import gov.nih.nci.cadsr.domain.ValueDomain;
import gov.nih.nci.cadsr.umlproject.domain.Project;
import gov.nih.nci.cadsr.umlproject.domain.UMLAttributeMetadata;
import gov.nih.nci.cadsr.umlproject.domain.UMLClassMetadata;
import gov.nih.nci.cadsr.umlproject.domain.UMLPackageMetadata;
import gov.nih.nci.cagrid.cadsr.client.CaDSRServiceClient;
import gov.nih.nci.cagrid.cadsr.common.CaDSRServiceI;
import gov.nih.nci.cagrid.cadsr.domain.UMLAssociation;
import gov.nih.nci.cagrid.cadsr.portal.CaDSRBrowserPanel;
import gov.nih.nci.cagrid.cadsr.portal.PackageSelectedListener;
import gov.nih.nci.cagrid.cadsr.portal.ProjectSelectedListener;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.graph.uml.UMLClass;
import gov.nih.nci.cagrid.graph.uml.UMLDiagram;
import gov.nih.nci.cagrid.introduce.ResourceManager;
import gov.nih.nci.cagrid.introduce.beans.extension.DiscoveryExtensionDescriptionType;
import gov.nih.nci.cagrid.introduce.beans.extension.ExtensionDescription;
import gov.nih.nci.cagrid.introduce.portal.discoverytools.NamespaceTypeToolsComponent;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;
/**
* @author oster
*
*/
public class CaDSRTypeDiscoveryComponent extends NamespaceTypeToolsComponent
implements
PackageSelectedListener,
ProjectSelectedListener {
private CaDSRBrowserPanel caDSRPanel = null;
private JPanel graphPanel = null;
private UMLDiagram umlDiagram;
private JPanel refreshPanel = null;
private JButton refreshButton = null;
/**
*
* @param desc
*/
public CaDSRTypeDiscoveryComponent(DiscoveryExtensionDescriptionType desc) {
super(desc);
initialize();
this.getCaDSRPanel().setDefaultCaDSRURL(getCaDSRURL());
this.getCaDSRPanel().discoverFromCaDSR();
}
private String getCaDSRURL() {
return ResourceManager.getServiceURLProperty(CaDSRDiscoveryConstants.CADSR_URL_PROPERTY);
}
private void initialize() {
GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
gridBagConstraints11.gridy = 1;
gridBagConstraints11.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints11.gridx = 0;
GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
gridBagConstraints1.gridx = 0;
gridBagConstraints1.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints1.weightx = 1.0D;
gridBagConstraints1.weighty = 1.0D;
gridBagConstraints1.gridy = 2;
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.gridy = 0;
gridBagConstraints.weightx = 0.0D;
gridBagConstraints.weighty = 0.0D;
this.setLayout(new GridBagLayout());
this.add(getCaDSRPanel(), gridBagConstraints);
this.add(getRefreshPanel(), gridBagConstraints11);
this.add(getGraphPanel(), gridBagConstraints1);
}
/**
* This method initializes cadsrPanel
*
* @return javax.swing.JPanel
*/
private CaDSRBrowserPanel getCaDSRPanel() {
if (caDSRPanel == null) {
caDSRPanel = new CaDSRBrowserPanel(false, false);
caDSRPanel.addPackageSelectionListener(this);
caDSRPanel.addProjectSelectionListener(this);
}
return caDSRPanel;
}
public void handleProjectSelection(Project project) {
this.getCaDSRPanel().getCadsr().setText(getCaDSRURL());
}
public void handlePackageSelection(final UMLPackageMetadata pkg) {
this.getCaDSRPanel().getCadsr().setText(getCaDSRURL());
// update the graph for the given package
Thread t = new Thread() {
public void run() {
try {
final int progressEventID = getCaDSRPanel().getMultiEventProgressBar().startEvent(
"Processing Package " + pkg.getName());
CaDSRServiceI cadsrService = new CaDSRServiceClient(getCaDSRPanel().getCadsr().getText());
getUMLDiagram().clear();
UMLClassMetadata[] classes = cadsrService.findClassesInPackage(
getCaDSRPanel().getSelectedProject(), pkg.getName());
Map classMap = new HashMap();
if (classes != null) {
for (int i = 0; i < classes.length; i++) {
UMLClassMetadata clazz = classes[i];
UMLClass c = new UMLClass(clazz.getName());
getCaDSRPanel().getMultiEventProgressBar().updateProgress(
"Processing Class " + clazz.getName() + " ( " + i + " of " + classes.length + ")", 0,
classes.length, i);
UMLAttributeMetadata[] atts = cadsrService.findAttributesInClass(getCaDSRPanel()
.getSelectedProject(), clazz);
if (atts != null) {
for (int j = 0; j < atts.length; j++) {
UMLAttributeMetadata att = atts[j];
ValueDomain domain = cadsrService.findValueDomainForAttribute(getCaDSRPanel()
.getSelectedProject(), att);
c.addAttribute(domain.getDatatypeName(), att.getName());
}
}
classMap.put(clazz.getId(), c);
getUMLDiagram().addClass(c);
}
}
final int assocProgressEventID = getCaDSRPanel().getMultiEventProgressBar().startEvent(
"Processing Associations...");
UMLAssociation[] assocs = cadsrService.findAssociationsInPackage(getCaDSRPanel()
.getSelectedProject(), pkg.getName());
if (assocs != null) {
for (int i = 0; i < assocs.length; i++) {
UMLAssociation assoc = assocs[i];
getCaDSRPanel().getMultiEventProgressBar().updateProgress(
"Processing Association " + " ( " + i + " of " + assocs.length + ")", 0, assocs.length,
i);
UMLClassMetadata source = assoc.getSourceUMLClassMetadata().getUMLClassMetadata();
UMLClassMetadata target = assoc.getTargetUMLClassMetadata().getUMLClassMetadata();
UMLClass sourceGraph = (UMLClass) classMap.get(source.getId());
UMLClass targetGraph = (UMLClass) classMap.get(target.getId());
if (sourceGraph == null || targetGraph == null) {
System.out
.println("Skipping association, as both source and target are not in this package.");
System.out.println("Source:" + source.getFullyQualifiedName());
System.out.println("Target:" + target.getFullyQualifiedName());
} else {
getUMLDiagram().addAssociation(
sourceGraph,
targetGraph,
assoc.getSourceRoleName(),
assoc.getSourceMinCardinality()
+ ".."
+ (assoc.getSourceMaxCardinality() == -1 ? "*" : String.valueOf(assoc
.getSourceMaxCardinality())),
assoc.getTargetRoleName(),
assoc.getTargetMinCardinality()
+ ".."
+ (assoc.getTargetMaxCardinality() == -1 ? "*" : String.valueOf(assoc
.getTargetMaxCardinality())));
}
}
}
getCaDSRPanel().getMultiEventProgressBar().stopEvent(assocProgressEventID,
"Done with Associations.");
final int renderProgressEventID = getCaDSRPanel().getMultiEventProgressBar().startEvent(
"Rendering...");
getUMLDiagram().refresh();
getCaDSRPanel().getMultiEventProgressBar().stopEvent(renderProgressEventID, "Done with Rendering.");
getCaDSRPanel().getMultiEventProgressBar().stopEvent(progressEventID, "Done with Package.");
} catch (RemoteException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(CaDSRTypeDiscoveryComponent.this,
"Error communicating with caDSR; please check the caDSR URL!");
getCaDSRPanel().getMultiEventProgressBar().stopAll(
"Error communicating with caDSR; please check the caDSR URL!");
getUMLDiagram().clear();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(CaDSRTypeDiscoveryComponent.this, "Error processing model!");
getCaDSRPanel().getMultiEventProgressBar().stopAll("Error processing model!");
getUMLDiagram().clear();
}
}
};
t.start();
}
/**
* This method initializes graphPanel
*
* @return javax.swing.JPanel
*/
private JPanel getGraphPanel() {
if (graphPanel == null) {
graphPanel = new JPanel();
graphPanel.setLayout(new GridBagLayout());
GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
gridBagConstraints1.gridx = 0;
gridBagConstraints1.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints1.weightx = 1.0D;
gridBagConstraints1.weighty = 1.0D;
gridBagConstraints1.gridy = 1;
graphPanel.add(getUMLDiagram(), gridBagConstraints1);
}
return graphPanel;
}
private UMLDiagram getUMLDiagram() {
if (umlDiagram == null) {
umlDiagram = new UMLDiagram();
}
return umlDiagram;
}
/**
* This method initializes refreshPanel
*
* @return javax.swing.JPanel
*/
private JPanel getRefreshPanel() {
if (refreshPanel == null) {
refreshPanel = new JPanel();
refreshPanel.add(getRefreshButton(), null);
}
return refreshPanel;
}
/**
* This method initializes refreshButton
*
* @return javax.swing.JButton
*/
private JButton getRefreshButton() {
if (refreshButton == null) {
refreshButton = new JButton();
refreshButton.setText("Refresh");
refreshButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
getCaDSRPanel().getCadsr().setText(getCaDSRURL());
getCaDSRPanel().discoverFromCaDSR();
}
});
}
return refreshButton;
}
public static void main(String[] args) {
try {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ExtensionDescription ext = (ExtensionDescription) Utils.deserializeDocument("extension.xml",
ExtensionDescription.class);
final CaDSRTypeDiscoveryComponent panel = new CaDSRTypeDiscoveryComponent(ext
.getDiscoveryExtensionDescription());
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
import java.util.*;
public class RepairDroid
{
public static final String INITIAL_INPUT = Integer.toString(DroidMovement.NORTH);
private static final int EXPLORE_UNTIL_OXYGEN = 1;
private static final int EXPLORE_ENTIRE_MAZE = 2;
public RepairDroid (Vector<String> instructions, boolean debug)
{
_debug = debug;
_theComputer = new Intcode(instructions, INITIAL_INPUT, _debug);
_currentLocation = new Coordinate(0, 0); // starting location
_startingPoint = _currentLocation;
_theMap = new Maze();
_trackTaken = new Stack<Integer>();
_foundOxygenStation = false;
_exploreOption = EXPLORE_UNTIL_OXYGEN;
_theMap.updateTile(_currentLocation, TileId.STARTING_POINT);
}
public final int moveToOxygenStation ()
{
_exploreOption = EXPLORE_UNTIL_OXYGEN;
explore();
return _trackTaken.size();
}
public final void mapEntireMaze ()
{
_exploreOption = EXPLORE_ENTIRE_MAZE;
explore();
}
public void printGrid ()
{
System.out.println(_theMap);
}
/*
* If we run into a wall then try a different direction.
* If we can't move other than backwards then do that.
* Don't move into areas we've already been.
*/
private int explore ()
{
int response = DroidStatus.ERROR;
while (!_theComputer.hasHalted() && !stopSearch())
{
boolean needToBackup = false;
//if (_debug)
System.out.println("\n"+_theMap);
/*
* We search N, E, S and then W.
*/
response = tryToMove(String.valueOf(DroidMovement.NORTH), DroidMovement.getNextPosition(_currentLocation, DroidMovement.NORTH));
if (tryNextLocation(response))
{
//if (_debug)
System.out.println("\n"+_theMap);
response = tryToMove(String.valueOf(DroidMovement.EAST), DroidMovement.getNextPosition(_currentLocation, DroidMovement.EAST));
if (tryNextLocation(response))
{
//if (_debug)
System.out.println("\n"+_theMap);
response = tryToMove(String.valueOf(DroidMovement.SOUTH), DroidMovement.getNextPosition(_currentLocation, DroidMovement.SOUTH));
if (tryNextLocation(response))
{
//if (_debug)
System.out.println("\n"+_theMap);
response = tryToMove(String.valueOf(DroidMovement.WEST), DroidMovement.getNextPosition(_currentLocation, DroidMovement.WEST));
if (tryNextLocation(response))
{
//if (_debug)
System.out.println("\n"+_theMap);
/*
* At this point we've exhausted all of the options for moving from
* the current location. Therefore, we need to backtrack.
*/
needToBackup = true;
}
}
}
}
if (_theComputer.status() == Status.HALTED)
response = DroidStatus.HALTED;
System.out.println("**DroidStatus "+DroidStatus.toString(response));
System.out.println("**search status "+stopSearch());
System.out.println("**and "+needToBackup);
System.out.println("**and "+Status.toString(_theComputer.status()));
System.out.println("**location "+_currentLocation);
if (needToBackup)
return backtrack();
}
if (_theComputer.status() == Status.HALTED)
response = DroidStatus.HALTED;
System.out.println("**DroidStatus "+DroidStatus.toString(response));
return response;
}
private int tryToMove (String direction, Coordinate to)
{
if (_debug)
System.out.println("Trying to move from: "+_currentLocation+" to "+to+" with direction "+DroidMovement.toString(direction));
// if we've already been there then don't move!
if (_theMap.isExplored(to))
return DroidStatus.VISITED;
_theComputer.setInput(direction);
_theComputer.executeUntilInput();
if (_theComputer.hasOutput())
{
int response = Integer.parseInt(_theComputer.getOutput());
if (_debug)
System.out.println("Response is "+DroidStatus.toString(response));
switch (response)
{
case DroidStatus.ARRIVED: // arrived at the station!!
{
_theMap.updateTile(_currentLocation, TileId.TRAVERSE);
_theMap.updateTile(to, TileId.OXYGEN_STATION);
_currentLocation = to;
recordJourney(Integer.parseInt(direction));
_foundOxygenStation = true;
if (_debug)
{
System.out.println("FOUND OXYGEN!");
System.out.println("\n"+_theMap);
}
return response;
}
case DroidStatus.COLLISION:
{
_theMap.updateTile(to, TileId.WALL); // didn't move as we hit a wall
return response;
}
case DroidStatus.MOVED:
{
/*
* Droid moved so let's try to move again.
*/
if (!_currentLocation.equals(_startingPoint))
_theMap.updateTile(_currentLocation, TileId.TRAVERSE);
_theMap.updateTile(to, TileId.DROID);
_currentLocation = to;
recordJourney(Integer.parseInt(direction));
return explore();
}
default:
System.out.println("Unknown response: "+response);
}
}
else
System.out.println("Error - no output after move instruction!");
return DroidStatus.ERROR; // error!!
}
private int backtrack ()
{
int status = DroidStatus.ERROR;
if (_trackTaken.size() > 0)
{
int backupDirection = DroidMovement.backupDirection(_trackTaken.pop());
if (_debug)
System.out.println("Trying to backup from: "+_currentLocation+" with direction "+DroidMovement.toString(backupDirection));
_theComputer.setInput(String.valueOf(backupDirection));
_theComputer.executeUntilInput();
if (_theComputer.hasOutput())
{
int response = Integer.parseInt(_theComputer.getOutput());
if (response == DroidStatus.MOVED)
{
_theMap.updateTile(_currentLocation, TileId.TRAVERSE);
_currentLocation = DroidMovement.getNextPosition(_currentLocation, backupDirection);
_theMap.updateTile(_currentLocation, TileId.DROID);
status = DroidStatus.BACKTRACKED; // different from normal move response
}
else
System.out.println("Unexpected backup response: "+response);
}
else
System.out.println("Error - no output after move instruction!");
}
else
System.out.println("Cannot backtrack!");
return status;
}
private void recordJourney (int direction)
{
if (!stopSearch())
_trackTaken.push(direction);
}
private final void printTrack ()
{
Enumeration<Integer> iter = _trackTaken.elements();
System.out.println("Path taken so far ...");
while (iter.hasMoreElements())
System.out.println("Moved "+DroidMovement.toString(iter.nextElement()));
}
private final boolean stopSearch ()
{
if ((_exploreOption == EXPLORE_UNTIL_OXYGEN) && (_foundOxygenStation))
return true;
else
return false;
}
private final boolean tryNextLocation (int response)
{
boolean result = false;
if (_exploreOption == EXPLORE_UNTIL_OXYGEN)
{
if ((response != DroidStatus.ARRIVED) && (response != DroidStatus.MOVED))
result = true;
}
else
{
if (response != DroidStatus.MOVED)
result = true;
}
return result;
}
private boolean _debug;
private Intcode _theComputer;
private Coordinate _currentLocation;
private Coordinate _startingPoint;
private Maze _theMap;
private Stack<Integer> _trackTaken;
private boolean _foundOxygenStation;
private int _exploreOption;
}
|
package goryachev.fx;
import javafx.scene.control.Menu;
import javafx.scene.control.SeparatorMenuItem;
/**
* CMenu.
*/
public class CMenu
extends Menu
{
public CMenu(String text)
{
super(text);
}
public SeparatorMenuItem addSeparator()
{
SeparatorMenuItem m = new SeparatorMenuItem();
getItems().add(m);
return m;
}
public CMenuItem add(String text, CAction a)
{
CMenuItem m = new CMenuItem(text, a);
getItems().add(m);
return m;
}
}
|
package gui.graphical;
// Graphical Libraries (AWT)
import java.awt.Polygon;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Graphics2D;
import java.awt.TexturePaint;
import java.awt.image.BufferedImage;
// Libraries
import arena.Terrain;
/**
* <b>Graphical Element - Cell</b><br>
* Encapsulates the creation of the hexagonal
* terrains of the map.
* @see Panel
*
* @author Karina Suemi
* @author Renato Cordeiro Ferreira
* @author Vinicius Silva
*/
class Cell
{
final private Polygon hex = new Polygon();
/* final private Graphics2D GImg; */
private Terrain terrain; private int x, y;
private BufferedImage appearence;
/**
* Default constructor.<br>
* @param x Horizontal position where the cell
* center will be set
* @param y Vertical position whee the cell
* center will be set
* @param img Texture for the cell
*/
Cell(int x, int y, int r, Terrain terrain)
{
this.x = x; this.y = y;
this.terrain = terrain;
this.appearence = Cell.appearence(terrain);
for(int i = 0; i < 6; i++)
hex.addPoint(
x + (int) (r * Math.sin(i * Math.PI/3)),
y + (int) (r * Math.cos(i * Math.PI/3))
);
/* GImg = img.createGraphics(); */
}
/**
* Add the texture to the cell, using an image
* inside a rectangle with dimensions 32x32.
* @param g Graphic object with all context
* needed to render the image
*/
void draw(Graphics g)
{
/* TODO: Take out hardcoded numbers */
Graphics2D g2d = (Graphics2D) g;
Rectangle rec = new Rectangle(0,0,32,32);
g2d.setPaint (new TexturePaint(appearence, rec));
g2d.fill (hex);
if(terrain.getItem() != null)
{
Images test = Images.valueOf(terrain.getItem().name());
g2d.drawImage(test.img(), x-11, y-13, null);
}
}
/**
* Translates the cell among the X and Y axis.
* @param dx Variation in the X axis
* @param dy Variation in the Y axis
*/
void trans(int dx, int dy)
{
hex.translate(dx, dy);
}
private static BufferedImage appearence(Terrain t)
{
String app = t.getAppearence().name();
return Images.valueOf(app).img();
}
}
|
package org.zstack.kvm;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestClientException;
import org.springframework.web.util.UriComponentsBuilder;
import org.zstack.compute.host.HostBase;
import org.zstack.compute.host.HostGlobalConfig;
import org.zstack.compute.host.HostSystemTags;
import org.zstack.compute.host.MigrateNetworkExtensionPoint;
import org.zstack.compute.vm.*;
import org.zstack.core.CoreGlobalProperty;
import org.zstack.core.MessageCommandRecorder;
import org.zstack.core.Platform;
import org.zstack.core.agent.AgentConstant;
import org.zstack.core.ansible.*;
import org.zstack.core.cloudbus.CloudBusCallBack;
import org.zstack.core.cloudbus.CloudBusGlobalProperty;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.db.Q;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.core.errorcode.ErrorFacade;
import org.zstack.core.thread.*;
import org.zstack.core.timeout.ApiTimeoutManager;
import org.zstack.core.workflow.FlowChainBuilder;
import org.zstack.core.workflow.ShareFlow;
import org.zstack.header.Constants;
import org.zstack.header.core.*;
import org.zstack.header.core.progress.TaskProgressRange;
import org.zstack.header.core.workflow.*;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.header.errorcode.SysErrors;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.host.*;
import org.zstack.header.host.MigrateVmOnHypervisorMsg.StorageMigrationPolicy;
import org.zstack.header.image.ImageBootMode;
import org.zstack.header.image.ImagePlatform;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.header.message.MessageReply;
import org.zstack.header.message.NeedReplyMessage;
import org.zstack.header.network.l2.*;
import org.zstack.header.network.l3.L3NetworkInventory;
import org.zstack.header.network.l3.L3NetworkVO;
import org.zstack.header.rest.JsonAsyncRESTCallback;
import org.zstack.header.rest.RESTFacade;
import org.zstack.header.storage.primary.*;
import org.zstack.header.storage.snapshot.VolumeSnapshotInventory;
import org.zstack.header.tag.SystemTagInventory;
import org.zstack.header.vm.*;
import org.zstack.header.volume.VolumeInventory;
import org.zstack.header.volume.VolumeType;
import org.zstack.header.volume.VolumeVO;
import org.zstack.kvm.KVMAgentCommands.*;
import org.zstack.kvm.KVMConstant.KvmVmState;
import org.zstack.network.l3.NetworkGlobalProperty;
import org.zstack.resourceconfig.ResourceConfigFacade;
import org.zstack.tag.SystemTag;
import org.zstack.tag.SystemTagCreator;
import org.zstack.tag.TagManager;
import org.zstack.utils.*;
import org.zstack.utils.gson.JSONObjectUtil;
import org.zstack.utils.logging.CLogger;
import org.zstack.utils.network.NetworkUtils;
import org.zstack.utils.path.PathUtil;
import org.zstack.utils.ssh.Ssh;
import org.zstack.utils.ssh.SshResult;
import org.zstack.utils.ssh.SshShell;
import org.zstack.utils.tester.ZTester;
import javax.persistence.TypedQuery;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.zstack.core.Platform.*;
import static org.zstack.core.progress.ProgressReportService.*;
import static org.zstack.utils.CollectionDSL.e;
import static org.zstack.utils.CollectionDSL.map;
public class KVMHost extends HostBase implements Host {
private static final CLogger logger = Utils.getLogger(KVMHost.class);
private static final ZTester tester = Utils.getTester();
@Autowired
@Qualifier("KVMHostFactory")
private KVMHostFactory factory;
@Autowired
private RESTFacade restf;
@Autowired
private KVMExtensionEmitter extEmitter;
@Autowired
private ErrorFacade errf;
@Autowired
private TagManager tagmgr;
@Autowired
private ApiTimeoutManager timeoutManager;
@Autowired
private PluginRegistry pluginRegistry;
@Autowired
private ThreadFacade thdf;
@Autowired
private AnsibleFacade asf;
@Autowired
private ResourceConfigFacade rcf;
@Autowired
private DeviceBootOrderOperator deviceBootOrderOperator;
@Autowired
private VmNicManager nicManager;
private KVMHostContext context;
// ///////////////////// REST URL //////////////////////////
private String baseUrl;
private String connectPath;
private String pingPath;
private String checkPhysicalNetworkInterfacePath;
private String startVmPath;
private String stopVmPath;
private String pauseVmPath;
private String resumeVmPath;
private String rebootVmPath;
private String destroyVmPath;
private String attachDataVolumePath;
private String detachDataVolumePath;
private String echoPath;
private String attachNicPath;
private String detachNicPath;
private String migrateVmPath;
private String snapshotPath;
private String mergeSnapshotPath;
private String hostFactPath;
private String attachIsoPath;
private String detachIsoPath;
private String updateNicPath;
private String checkVmStatePath;
private String getConsolePortPath;
private String onlineIncreaseCpuPath;
private String onlineIncreaseMemPath;
private String deleteConsoleFirewall;
private String updateHostOSPath;
private String updateDependencyPath;
private String shutdownHost;
private String updateVmPriorityPath;
private String updateSpiceChannelConfigPath;
private String cancelJob;
private String getVmFirstBootDevicePath;
private String scanVmPortPath;
private String getDevCapacityPath;
private String agentPackageName = KVMGlobalProperty.AGENT_PACKAGE_NAME;
public KVMHost(KVMHostVO self, KVMHostContext context) {
super(self);
this.context = context;
baseUrl = context.getBaseUrl();
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_CONNECT_PATH);
connectPath = ub.build().toUriString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_PING_PATH);
pingPath = ub.build().toUriString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_CHECK_PHYSICAL_NETWORK_INTERFACE_PATH);
checkPhysicalNetworkInterfacePath = ub.build().toUriString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_START_VM_PATH);
startVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_STOP_VM_PATH);
stopVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_PAUSE_VM_PATH);
pauseVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_RESUME_VM_PATH);
resumeVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_REBOOT_VM_PATH);
rebootVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DESTROY_VM_PATH);
destroyVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ATTACH_VOLUME);
attachDataVolumePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DETACH_VOLUME);
detachDataVolumePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ECHO_PATH);
echoPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ATTACH_NIC_PATH);
attachNicPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DETACH_NIC_PATH);
detachNicPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_MIGRATE_VM_PATH);
migrateVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_TAKE_VOLUME_SNAPSHOT_PATH);
snapshotPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_MERGE_SNAPSHOT_PATH);
mergeSnapshotPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_HOST_FACT_PATH);
hostFactPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ATTACH_ISO_PATH);
attachIsoPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DETACH_ISO_PATH);
detachIsoPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_UPDATE_NIC_PATH);
updateNicPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_CHECK_STATE);
checkVmStatePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_GET_VNC_PORT_PATH);
getConsolePortPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_ONLINE_INCREASE_CPU);
onlineIncreaseCpuPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_ONLINE_INCREASE_MEMORY);
onlineIncreaseMemPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DELETE_CONSOLE_FIREWALL_PATH);
deleteConsoleFirewall = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_UPDATE_HOST_OS_PATH);
updateHostOSPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_HOST_UPDATE_DEPENDENCY_PATH);
updateDependencyPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.HOST_SHUTDOWN);
shutdownHost = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_UPDATE_PRIORITY_PATH);
updateVmPriorityPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.HOST_UPDATE_SPICE_CHANNEL_CONFIG_PATH);
updateSpiceChannelConfigPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(AgentConstant.CANCEL_JOB);
cancelJob = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_GET_VM_FIRST_BOOT_DEVICE_PATH);
getVmFirstBootDevicePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_SCAN_VM_PORT_STATUS);
scanVmPortPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.GET_DEV_CAPACITY);
getDevCapacityPath = ub.build().toString();
}
class Http<T> {
String path;
AgentCommand cmd;
Class<T> responseClass;
String commandStr;
public Http(String path, String cmd, Class<T> rspClz) {
this.path = path;
this.commandStr = cmd;
this.responseClass = rspClz;
}
public Http(String path, AgentCommand cmd, Class<T> rspClz) {
this.path = path;
this.cmd = cmd;
this.responseClass = rspClz;
}
void call(ReturnValueCompletion<T> completion) {
call(null, completion);
}
void call(String resourceUuid, ReturnValueCompletion<T> completion) {
Map<String, String> header = new HashMap<>();
header.put(Constants.AGENT_HTTP_HEADER_RESOURCE_UUID, resourceUuid == null ? self.getUuid() : resourceUuid);
runBeforeAsyncJsonPostExts(header);
if (commandStr != null) {
restf.asyncJsonPost(path, commandStr, header, new JsonAsyncRESTCallback<T>(completion) {
@Override
public void fail(ErrorCode err) {
completion.fail(err);
}
@Override
public void success(T ret) {
if (dbf.isExist(self.getUuid(), HostVO.class)) {
completion.success(ret);
} else {
completion.fail(operr("host[uuid:%s] has been deleted", self.getUuid()));
}
}
@Override
public Class<T> getReturnClass() {
return responseClass;
}
}, TimeUnit.MILLISECONDS, timeoutManager.getTimeout());
} else {
restf.asyncJsonPost(path, cmd, header, new JsonAsyncRESTCallback<T>(completion) {
@Override
public void fail(ErrorCode err) {
completion.fail(err);
}
@Override
public void success(T ret) {
if (dbf.isExist(self.getUuid(), HostVO.class)) {
completion.success(ret);
} else {
completion.fail(operr("host[uuid:%s] has been deleted", self.getUuid()));
}
}
@Override
public Class<T> getReturnClass() {
return responseClass;
}
}); // DO NOT pass unit, timeout here, they are null
}
}
void runBeforeAsyncJsonPostExts(Map<String, String> header) {
if (commandStr == null) {
commandStr = JSONObjectUtil.toJsonString(cmd);
}
if (commandStr == null || commandStr.isEmpty()) {
logger.warn(String.format("commandStr is empty, path: %s, header: %s", path, header));
return;
}
LinkedHashMap commandMap = JSONObjectUtil.toObject(commandStr, LinkedHashMap.class);
LinkedHashMap kvmHostAddon = new LinkedHashMap();
for (KVMBeforeAsyncJsonPostExtensionPoint extp : pluginRegistry.getExtensionList(KVMBeforeAsyncJsonPostExtensionPoint.class)) {
LinkedHashMap tmpHashMap = extp.kvmBeforeAsyncJsonPostExtensionPoint(path, commandMap, header);
if (tmpHashMap != null && !tmpHashMap.isEmpty()) {
tmpHashMap.keySet().stream().forEachOrdered((key -> {
kvmHostAddon.put(key, tmpHashMap.get(key));
}));
}
}
if (commandStr.equals("{}")) {
commandStr = commandStr.replaceAll("\\}$",
String.format("\"%s\":%s}", KVMConstant.KVM_HOST_ADDONS, JSONObjectUtil.toJsonString(kvmHostAddon)));
} else {
commandStr = commandStr.replaceAll("\\}$",
String.format(",\"%s\":%s}", KVMConstant.KVM_HOST_ADDONS, JSONObjectUtil.toJsonString(kvmHostAddon)));
}
}
}
@Override
protected void handleApiMessage(APIMessage msg) {
super.handleApiMessage(msg);
}
@Override
protected void handleLocalMessage(Message msg) {
if (msg instanceof CheckNetworkPhysicalInterfaceMsg) {
handle((CheckNetworkPhysicalInterfaceMsg) msg);
} else if (msg instanceof StartVmOnHypervisorMsg) {
handle((StartVmOnHypervisorMsg) msg);
} else if (msg instanceof CreateVmOnHypervisorMsg) {
handle((CreateVmOnHypervisorMsg) msg);
} else if (msg instanceof UpdateSpiceChannelConfigMsg) {
handle((UpdateSpiceChannelConfigMsg) msg);
} else if (msg instanceof StopVmOnHypervisorMsg) {
handle((StopVmOnHypervisorMsg) msg);
} else if (msg instanceof RebootVmOnHypervisorMsg) {
handle((RebootVmOnHypervisorMsg) msg);
} else if (msg instanceof DestroyVmOnHypervisorMsg) {
handle((DestroyVmOnHypervisorMsg) msg);
} else if (msg instanceof AttachVolumeToVmOnHypervisorMsg) {
handle((AttachVolumeToVmOnHypervisorMsg) msg);
} else if (msg instanceof DetachVolumeFromVmOnHypervisorMsg) {
handle((DetachVolumeFromVmOnHypervisorMsg) msg);
} else if (msg instanceof VmAttachNicOnHypervisorMsg) {
handle((VmAttachNicOnHypervisorMsg) msg);
} else if (msg instanceof VmUpdateNicOnHypervisorMsg) {
handle((VmUpdateNicOnHypervisorMsg) msg);
} else if (msg instanceof MigrateVmOnHypervisorMsg) {
handle((MigrateVmOnHypervisorMsg) msg);
} else if (msg instanceof TakeSnapshotOnHypervisorMsg) {
handle((TakeSnapshotOnHypervisorMsg) msg);
} else if (msg instanceof MergeVolumeSnapshotOnKvmMsg) {
handle((MergeVolumeSnapshotOnKvmMsg) msg);
} else if (msg instanceof KVMHostAsyncHttpCallMsg) {
handle((KVMHostAsyncHttpCallMsg) msg);
} else if (msg instanceof KVMHostSyncHttpCallMsg) {
handle((KVMHostSyncHttpCallMsg) msg);
} else if (msg instanceof DetachNicFromVmOnHypervisorMsg) {
handle((DetachNicFromVmOnHypervisorMsg) msg);
} else if (msg instanceof AttachIsoOnHypervisorMsg) {
handle((AttachIsoOnHypervisorMsg) msg);
} else if (msg instanceof DetachIsoOnHypervisorMsg) {
handle((DetachIsoOnHypervisorMsg) msg);
} else if (msg instanceof CheckVmStateOnHypervisorMsg) {
handle((CheckVmStateOnHypervisorMsg) msg);
} else if (msg instanceof UpdateVmPriorityMsg) {
handle((UpdateVmPriorityMsg) msg);
} else if (msg instanceof GetVmConsoleAddressFromHostMsg) {
handle((GetVmConsoleAddressFromHostMsg) msg);
} else if (msg instanceof KvmRunShellMsg) {
handle((KvmRunShellMsg) msg);
} else if (msg instanceof VmDirectlyDestroyOnHypervisorMsg) {
handle((VmDirectlyDestroyOnHypervisorMsg) msg);
} else if (msg instanceof IncreaseVmCpuMsg) {
handle((IncreaseVmCpuMsg) msg);
} else if (msg instanceof IncreaseVmMemoryMsg) {
handle((IncreaseVmMemoryMsg) msg);
} else if (msg instanceof PauseVmOnHypervisorMsg) {
handle((PauseVmOnHypervisorMsg) msg);
} else if (msg instanceof ResumeVmOnHypervisorMsg) {
handle((ResumeVmOnHypervisorMsg) msg);
} else if (msg instanceof GetKVMHostDownloadCredentialMsg) {
handle((GetKVMHostDownloadCredentialMsg) msg);
} else if (msg instanceof ShutdownHostMsg) {
handle((ShutdownHostMsg) msg);
} else if (msg instanceof CancelHostTaskMsg) {
handle((CancelHostTaskMsg) msg);
} else if (msg instanceof GetVmFirstBootDeviceOnHypervisorMsg) {
handle((GetVmFirstBootDeviceOnHypervisorMsg) msg);
} else {
super.handleLocalMessage(msg);
}
}
private void handle(GetVmFirstBootDeviceOnHypervisorMsg msg) {
inQueue().name(String.format("get-first-boot-device-of-vm-%s-on-kvm-%s", msg.getVmInstanceUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> getVmFirstBootDevice(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void getVmFirstBootDevice(final GetVmFirstBootDeviceOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
GetVmFirstBootDeviceCmd cmd = new GetVmFirstBootDeviceCmd();
cmd.setUuid(msg.getVmInstanceUuid());
new Http<>(getVmFirstBootDevicePath, cmd, GetVmFirstBootDeviceResponse.class).call(new ReturnValueCompletion<GetVmFirstBootDeviceResponse>(msg, completion) {
@Override
public void success(GetVmFirstBootDeviceResponse ret) {
final GetVmFirstBootDeviceOnHypervisorReply reply = new GetVmFirstBootDeviceOnHypervisorReply();
if (!ret.isSuccess()) {
reply.setError(operr("unable to get first boot dev of vm[uuid:%s] on kvm host [uuid:%s, ip:%s], because %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
} else {
reply.setFirstBootDevice(ret.getFirstBootDevice());
logger.debug(String.format("first boot dev of vm[uuid:%s] on kvm host[uuid:%s] is %s",
msg.getVmInstanceUuid(), self.getUuid(), ret.getFirstBootDevice()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
final GetVmFirstBootDeviceOnHypervisorReply reply = new GetVmFirstBootDeviceOnHypervisorReply();
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(GetKVMHostDownloadCredentialMsg msg) {
final GetKVMHostDownloadCredentialReply reply = new GetKVMHostDownloadCredentialReply();
String key = asf.getPrivateKey();
String hostname = null;
if (Strings.isNotEmpty(msg.getDataNetworkCidr())) {
String dataNetworkAddress = getDataNetworkAddress(self.getUuid(), msg.getDataNetworkCidr());
if (dataNetworkAddress != null) {
hostname = dataNetworkAddress;
}
}
reply.setHostname(hostname == null ? getSelf().getManagementIp() : hostname);
reply.setUsername(getSelf().getUsername());
reply.setSshPort(getSelf().getPort());
reply.setSshKey(key);
bus.reply(msg, reply);
}
protected static String getDataNetworkAddress(String hostUuid, String cidr) {
final String extraIps = HostSystemTags.EXTRA_IPS.getTokenByResourceUuid(
hostUuid, HostSystemTags.EXTRA_IPS_TOKEN);
if (extraIps == null) {
logger.debug(String.format("Host [uuid:%s] has no IPs in data network", hostUuid));
return null;
}
final String[] ips = extraIps.split(",");
for (String ip: ips) {
if (NetworkUtils.isIpv4InCidr(ip, cidr)) {
return ip;
}
}
return null;
}
private void handle(final IncreaseVmCpuMsg msg) {
IncreaseVmCpuReply reply = new IncreaseVmCpuReply();
IncreaseCpuCmd cmd = new IncreaseCpuCmd();
cmd.setVmUuid(msg.getVmInstanceUuid());
cmd.setCpuNum(msg.getCpuNum());
new Http<>(onlineIncreaseCpuPath, cmd, IncreaseCpuResponse.class).call(new ReturnValueCompletion<IncreaseCpuResponse>(msg) {
@Override
public void success(IncreaseCpuResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
reply.setCpuNum(ret.getCpuNum());
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final IncreaseVmMemoryMsg msg) {
IncreaseVmMemoryReply reply = new IncreaseVmMemoryReply();
IncreaseMemoryCmd cmd = new IncreaseMemoryCmd();
cmd.setVmUuid(msg.getVmInstanceUuid());
cmd.setMemorySize(msg.getMemorySize());
new Http<>(onlineIncreaseMemPath, cmd, IncreaseMemoryResponse.class).call(new ReturnValueCompletion<IncreaseMemoryResponse>(msg) {
@Override
public void success(IncreaseMemoryResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
reply.setMemorySize(ret.getMemorySize());
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void directlyDestroy(final VmDirectlyDestroyOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmDirectlyDestroyOnHypervisorReply reply = new VmDirectlyDestroyOnHypervisorReply();
DestroyVmCmd cmd = new DestroyVmCmd();
cmd.setUuid(msg.getVmUuid());
new Http<>(destroyVmPath, cmd, DestroyVmResponse.class).call(new ReturnValueCompletion<DestroyVmResponse>(completion) {
@Override
public void success(DestroyVmResponse ret) {
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_DESTROY_VM_ON_HYPERVISOR, ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
protected class RunInKVMHostQueue {
private String name;
private List<AsyncBackup> asyncBackups = new ArrayList<>();
public RunInKVMHostQueue name(String v) {
name = v;
return this;
}
public RunInKVMHostQueue asyncBackup(AsyncBackup v) {
asyncBackups.add(v);
return this;
}
public void run(Consumer<SyncTaskChain> consumer) {
DebugUtils.Assert(name != null, "name() must be called");
DebugUtils.Assert(!asyncBackups.isEmpty(), "asyncBackup must be called");
AsyncBackup one = asyncBackups.get(0);
AsyncBackup[] rest = asyncBackups.size() > 1 ?
asyncBackups.subList(1, asyncBackups.size()).toArray(new AsyncBackup[asyncBackups.size()-1]) :
new AsyncBackup[0];
thdf.chainSubmit(new ChainTask(one, rest) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(SyncTaskChain chain) {
consumer.accept(chain);
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
@Override
public String getName() {
return name;
}
});
}
}
protected RunInKVMHostQueue inQueue() {
return new RunInKVMHostQueue();
}
private void handle(final VmDirectlyDestroyOnHypervisorMsg msg) {
inQueue().name(String.format("directly-delete-vm-%s-msg-on-kvm-%s", msg.getVmUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> directlyDestroy(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private SshResult runShell(String script) {
Ssh ssh = new Ssh();
ssh.setHostname(self.getManagementIp());
ssh.setPort(getSelf().getPort());
ssh.setUsername(getSelf().getUsername());
ssh.setPassword(getSelf().getPassword());
ssh.shell(script);
return ssh.runAndClose();
}
private void handle(KvmRunShellMsg msg) {
SshResult result = runShell(msg.getScript());
KvmRunShellReply reply = new KvmRunShellReply();
if (result.isSshFailure()) {
reply.setError(operr("unable to connect to KVM[ip:%s, username:%s, sshPort:%d ] to do DNS check," +
" please check if username/password is wrong; %s",
self.getManagementIp(), getSelf().getUsername(),
getSelf().getPort(), result.getExitErrorMessage()));
} else {
reply.setStdout(result.getStdout());
reply.setStderr(result.getStderr());
reply.setReturnCode(result.getReturnCode());
}
bus.reply(msg, reply);
}
private void handle(final GetVmConsoleAddressFromHostMsg msg) {
final GetVmConsoleAddressFromHostReply reply = new GetVmConsoleAddressFromHostReply();
GetVncPortCmd cmd = new GetVncPortCmd();
cmd.setVmUuid(msg.getVmInstanceUuid());
new Http<>(getConsolePortPath, cmd, GetVncPortResponse.class).call(new ReturnValueCompletion<GetVncPortResponse>(msg) {
@Override
public void success(GetVncPortResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
reply.setHostIp(self.getManagementIp());
reply.setProtocol(ret.getProtocol());
reply.setPort(ret.getPort());
VdiPortInfo vdiPortInfo = new VdiPortInfo();
if (ret.getVncPort() != null) {
vdiPortInfo.setVncPort(ret.getVncPort());
}
if (ret.getSpicePort() != null) {
vdiPortInfo.setSpicePort(ret.getSpicePort());
}
if (ret.getSpiceTlsPort() != null) {
vdiPortInfo.setSpiceTlsPort(ret.getSpiceTlsPort());
}
reply.setVdiPortInfo(vdiPortInfo);
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final UpdateVmPriorityMsg msg) {
final UpdateVmPriorityReply reply = new UpdateVmPriorityReply();
if (self.getStatus() != HostStatus.Connected) {
reply.setError(operr("the host[uuid:%s, status:%s] is not Connected", self.getUuid(), self.getStatus()));
bus.reply(msg, reply);
return;
}
UpdateVmPriorityCmd cmd = new UpdateVmPriorityCmd();
cmd.priorityConfigStructs = msg.getPriorityConfigStructs();
new Http<>(updateVmPriorityPath, cmd, UpdateVmPriorityRsp.class).call(new ReturnValueCompletion<UpdateVmPriorityRsp>(msg) {
@Override
public void success(UpdateVmPriorityRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final CheckVmStateOnHypervisorMsg msg) {
final CheckVmStateOnHypervisorReply reply = new CheckVmStateOnHypervisorReply();
if (self.getStatus() != HostStatus.Connected) {
reply.setError(operr("the host[uuid:%s, status:%s] is not Connected", self.getUuid(), self.getStatus()));
bus.reply(msg, reply);
return;
}
// NOTE: don't run this message in the sync task
// there can be many such kind of messages
// running in the sync task may cause other tasks starved
CheckVmStateCmd cmd = new CheckVmStateCmd();
cmd.vmUuids = msg.getVmInstanceUuids();
cmd.hostUuid = self.getUuid();
new Http<>(checkVmStatePath, cmd, CheckVmStateRsp.class).call(new ReturnValueCompletion<CheckVmStateRsp>(msg) {
@Override
public void success(CheckVmStateRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
Map<String, String> m = new HashMap<>();
for (Map.Entry<String, String> e : ret.states.entrySet()) {
m.put(e.getKey(), KvmVmState.valueOf(e.getValue()).toVmInstanceState().toString());
}
reply.setStates(m);
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final DetachIsoOnHypervisorMsg msg) {
inQueue().asyncBackup(msg)
.name(String.format("detach-iso-%s-on-host-%s", msg.getIsoUuid(), self.getUuid()))
.run(chain -> detachIso(msg, new NoErrorCompletion(msg, chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void detachIso(final DetachIsoOnHypervisorMsg msg, final NoErrorCompletion completion) {
final DetachIsoOnHypervisorReply reply = new DetachIsoOnHypervisorReply();
DetachIsoCmd cmd = new DetachIsoCmd();
cmd.isoUuid = msg.getIsoUuid();
cmd.vmUuid = msg.getVmInstanceUuid();
Integer deviceId = IsoOperator.getIsoDeviceId(msg.getVmInstanceUuid(), msg.getIsoUuid());
assert deviceId != null;
cmd.deviceId = deviceId;
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPreDetachIsoExtensionPoint ext : pluginRgty.getExtensionList(KVMPreDetachIsoExtensionPoint.class)) {
ext.preDetachIsoExtensionPoint(inv, cmd);
}
new Http<>(detachIsoPath, cmd, DetachIsoRsp.class).call(new ReturnValueCompletion<DetachIsoRsp>(msg, completion) {
@Override
public void success(DetachIsoRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final AttachIsoOnHypervisorMsg msg) {
inQueue().asyncBackup(msg)
.name(String.format("attach-iso-%s-on-host-%s", msg.getIsoSpec().getImageUuid(), self.getUuid()))
.run(chain -> attachIso(msg, new NoErrorCompletion(msg, chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void attachIso(final AttachIsoOnHypervisorMsg msg, final NoErrorCompletion completion) {
final AttachIsoOnHypervisorReply reply = new AttachIsoOnHypervisorReply();
IsoTO iso = new IsoTO();
iso.setImageUuid(msg.getIsoSpec().getImageUuid());
iso.setPath(msg.getIsoSpec().getInstallPath());
iso.setDeviceId(msg.getIsoSpec().getDeviceId());
AttachIsoCmd cmd = new AttachIsoCmd();
cmd.vmUuid = msg.getVmInstanceUuid();
cmd.iso = iso;
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPreAttachIsoExtensionPoint ext : pluginRgty.getExtensionList(KVMPreAttachIsoExtensionPoint.class)) {
ext.preAttachIsoExtensionPoint(inv, cmd);
}
new Http<>(attachIsoPath, cmd, AttachIsoRsp.class).call(new ReturnValueCompletion<AttachIsoRsp>(msg, completion) {
@Override
public void success(AttachIsoRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final DetachNicFromVmOnHypervisorMsg msg) {
inQueue().name("detach-nic-on-kvm-host-" + self.getUuid())
.asyncBackup(msg)
.run(chain -> detachNic(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void detachNic(final DetachNicFromVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
final DetachNicFromVmOnHypervisorReply reply = new DetachNicFromVmOnHypervisorReply();
NicTO to = completeNicInfo(msg.getNic());
DetachNicCommand cmd = new DetachNicCommand();
cmd.setVmUuid(msg.getVmInstanceUuid());
cmd.setNic(to);
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KvmPreDetachNicExtensionPoint ext : pluginRgty.getExtensionList(KvmPreDetachNicExtensionPoint.class)) {
ext.preDetachNicExtensionPoint(inv, cmd);
}
new Http<>(detachNicPath, cmd, DetachNicRsp.class).call(new ReturnValueCompletion<DetachNicRsp>(msg, completion) {
@Override
public void success(DetachNicRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void doHandleKvmSyncMsg(final KVMHostSyncHttpCallMsg msg, SyncTaskChain outter) {
inQueue().name(String.format("execute-sync-http-call-on-kvm-host-%s", self.getUuid()))
.asyncBackup(msg)
.asyncBackup(outter)
.run(chain -> executeSyncHttpCall(msg, new NoErrorCompletion(chain, outter) {
@Override
public void done() {
chain.next();
outter.next();
}
}));
}
private static int getHostMaxThreadsNum() {
int n = (int)(KVMGlobalProperty.KVM_HOST_MAX_THREDS_RATIO * ThreadGlobalProperty.MAX_THREAD_NUM);
int m = ThreadGlobalProperty.MAX_THREAD_NUM / 5;
return Math.max(n, m);
}
private void handle(final KVMHostSyncHttpCallMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return "host-sync-control";
}
@Override
public void run(SyncTaskChain chain) {
doHandleKvmSyncMsg(msg, chain);
}
@Override
protected int getSyncLevel() {
return getHostMaxThreadsNum();
}
@Override
public String getName() {
return String.format("sync-call-on-kvm-%s", self.getUuid());
}
});
}
private void executeSyncHttpCall(KVMHostSyncHttpCallMsg msg, NoErrorCompletion completion) {
if (!msg.isNoStatusCheck()) {
checkStatus();
}
String url = buildUrl(msg.getPath());
MessageCommandRecorder.record(msg.getCommandClassName());
Map<String, String> headers = new HashMap<>();
headers.put(Constants.AGENT_HTTP_HEADER_RESOURCE_UUID, self.getUuid());
LinkedHashMap rsp = restf.syncJsonPost(url, msg.getCommand(), headers, LinkedHashMap.class);
KVMHostSyncHttpCallReply reply = new KVMHostSyncHttpCallReply();
reply.setResponse(rsp);
bus.reply(msg, reply);
completion.done();
}
private void doHandleKvmAsyncMsg(final KVMHostAsyncHttpCallMsg msg, SyncTaskChain outter) {
inQueue().name(String.format("execute-async-http-call-on-kvm-host-%s", self.getUuid()))
.asyncBackup(msg)
.asyncBackup(outter)
.run(chain -> executeAsyncHttpCall(msg, new NoErrorCompletion(chain, outter) {
@Override
public void done() {
chain.next();
outter.next();
}
}));
}
private void handle(final KVMHostAsyncHttpCallMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return "host-sync-control";
}
@Override
public void run(SyncTaskChain chain) {
doHandleKvmAsyncMsg(msg, chain);
}
@Override
protected int getSyncLevel() {
return getHostMaxThreadsNum();
}
@Override
public String getName() {
return String.format("async-call-on-kvm-%s", self.getUuid());
}
});
}
private String buildUrl(String path) {
UriComponentsBuilder ub = UriComponentsBuilder.newInstance();
ub.scheme(KVMGlobalProperty.AGENT_URL_SCHEME);
ub.host(self.getManagementIp());
ub.port(KVMGlobalProperty.AGENT_PORT);
if (!"".equals(KVMGlobalProperty.AGENT_URL_ROOT_PATH)) {
ub.path(KVMGlobalProperty.AGENT_URL_ROOT_PATH);
}
ub.path(path);
return ub.build().toUriString();
}
private void executeAsyncHttpCall(final KVMHostAsyncHttpCallMsg msg, final NoErrorCompletion completion) {
if (!msg.isNoStatusCheck()) {
checkStatus();
}
String url = buildUrl(msg.getPath());
MessageCommandRecorder.record(msg.getCommandClassName());
new Http<>(url, msg.getCommand(), LinkedHashMap.class)
.call(new ReturnValueCompletion<LinkedHashMap>(msg, completion) {
@Override
public void success(LinkedHashMap ret) {
KVMHostAsyncHttpCallReply reply = new KVMHostAsyncHttpCallReply();
reply.setResponse(ret);
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
KVMHostAsyncHttpCallReply reply = new KVMHostAsyncHttpCallReply();
if (err.isError(SysErrors.HTTP_ERROR, SysErrors.IO_ERROR)) {
reply.setError(err(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, err, "cannot do the operation on the KVM host"));
} else {
reply.setError(err);
}
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final MergeVolumeSnapshotOnKvmMsg msg) {
inQueue().name(String.format("merge-volume-snapshot-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> mergeVolumeSnapshot(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void mergeVolumeSnapshot(final MergeVolumeSnapshotOnKvmMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final MergeVolumeSnapshotOnKvmReply reply = new MergeVolumeSnapshotOnKvmReply();
VolumeInventory volume = msg.getTo();
if (volume.getVmInstanceUuid() != null) {
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.state);
q.add(VmInstanceVO_.uuid, Op.EQ, volume.getVmInstanceUuid());
VmInstanceState state = q.findValue();
if (state != VmInstanceState.Stopped && state != VmInstanceState.Running && state != VmInstanceState.Paused && state != VmInstanceState.Destroyed) {
throw new OperationFailureException(operr("cannot do volume snapshot merge when vm[uuid:%s] is in state of %s." +
" The operation is only allowed when vm is Running or Stopped", volume.getUuid(), state));
}
if (state == VmInstanceState.Running) {
String libvirtVersion = KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN);
if (new VersionComparator(KVMConstant.MIN_LIBVIRT_LIVE_BLOCK_COMMIT_VERSION).compare(libvirtVersion) > 0) {
throw new OperationFailureException(operr("live volume snapshot merge needs libvirt version greater than %s," +
" current libvirt version is %s. Please stop vm and redo the operation or detach the volume if it's data volume",
KVMConstant.MIN_LIBVIRT_LIVE_BLOCK_COMMIT_VERSION, libvirtVersion));
}
}
}
VolumeSnapshotInventory snapshot = msg.getFrom();
MergeSnapshotCmd cmd = new MergeSnapshotCmd();
cmd.setFullRebase(msg.isFullRebase());
cmd.setDestPath(volume.getInstallPath());
cmd.setSrcPath(snapshot.getPrimaryStorageInstallPath());
cmd.setVmUuid(volume.getVmInstanceUuid());
cmd.setVolume(VolumeTO.valueOf(volume, (KVMHostInventory) getSelfInventory()));
extEmitter.beforeMergeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd);
new Http<>(mergeSnapshotPath, cmd, MergeSnapshotRsp.class)
.call(new ReturnValueCompletion<MergeSnapshotRsp>(msg, completion) {
@Override
public void success(MergeSnapshotRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
extEmitter.afterMergeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, reply.getError());
}
extEmitter.afterMergeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd);
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
extEmitter.afterMergeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, reply.getError());
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final TakeSnapshotOnHypervisorMsg msg) {
inQueue().name(String.format("take-snapshot-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> {
takeSnapshot(msg);
chain.next();
});
}
private void takeSnapshot(final TakeSnapshotOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return getName();
}
@Override
public void run(SyncTaskChain chain) {
doTakeSnapshot(msg, new NoErrorCompletion() {
@Override
public void done() {
chain.next();
}
});
}
@Override
protected int getSyncLevel() {
return KVMGlobalConfig.HOST_SNAPSHOT_SYNC_LEVEL.value(Integer.class);
}
@Override
public String getName() {
return String.format("take-snapshot-on-kvm-%s", self.getUuid());
}
});
}
private void doTakeSnapshot(final TakeSnapshotOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final TakeSnapshotOnHypervisorReply reply = new TakeSnapshotOnHypervisorReply();
TakeSnapshotCmd cmd = new TakeSnapshotCmd();
if (msg.getVmUuid() != null) {
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.state);
q.add(VmInstanceVO_.uuid, SimpleQuery.Op.EQ, msg.getVmUuid());
VmInstanceState vmState = q.findValue();
if (vmState != VmInstanceState.Running && vmState != VmInstanceState.Stopped && vmState != VmInstanceState.Paused) {
throw new OperationFailureException(operr("vm[uuid:%s] is not Running or Stopped, current state[%s]", msg.getVmUuid(), vmState));
}
if (!HostSystemTags.LIVE_SNAPSHOT.hasTag(self.getUuid())) {
if (vmState != VmInstanceState.Stopped) {
throw new OperationFailureException(err(SysErrors.NO_CAPABILITY_ERROR,
"kvm host[uuid:%s, name:%s, ip:%s] doesn't not support live snapshot. please stop vm[uuid:%s] and try again",
self.getUuid(), self.getName(), self.getManagementIp(), msg.getVmUuid()
));
}
}
cmd.setVolumeUuid(msg.getVolume().getUuid());
cmd.setVmUuid(msg.getVmUuid());
cmd.setVolume(VolumeTO.valueOf(msg.getVolume(), (KVMHostInventory) getSelfInventory()));
}
cmd.setVolumeInstallPath(msg.getVolume().getInstallPath());
cmd.setInstallPath(msg.getInstallPath());
cmd.setFullSnapshot(msg.isFullSnapshot());
cmd.setVolumeUuid(msg.getVolume().getUuid());
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("before-take-snapshot-%s-for-volume-%s", msg.getSnapshotName(), msg.getVolume().getUuid()));
chain.then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
extEmitter.beforeTakeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
}).then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
new Http<>(snapshotPath, cmd, TakeSnapshotResponse.class).call(new ReturnValueCompletion<TakeSnapshotResponse>(msg, trigger) {
@Override
public void success(TakeSnapshotResponse ret) {
if (ret.isSuccess()) {
extEmitter.afterTakeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd, ret);
reply.setNewVolumeInstallPath(ret.getNewVolumeInstallPath());
reply.setSnapshotInstallPath(ret.getSnapshotInstallPath());
reply.setSize(ret.getSize());
} else {
ErrorCode err = operr("operation error, because:%s", ret.getError());
extEmitter.afterTakeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, ret, err);
reply.setError(err);
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
extEmitter.afterTakeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, null, errorCode);
reply.setError(errorCode);
trigger.fail(errorCode);
}
});
}
}).done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
bus.reply(msg, reply);
completion.done();
}
}).error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
reply.setError(errCode);
bus.reply(msg, reply);
completion.done();
}
}).start();
}
private void migrateVm(final MigrateStruct s, final Completion completion) {
final TaskProgressRange parentStage = getTaskStage();
final TaskProgressRange MIGRATE_VM_STAGE = new TaskProgressRange(0, 90);
final String dstHostMigrateIp, dstHostMnIp, dstHostUuid;
final String vmUuid;
final StorageMigrationPolicy storageMigrationPolicy;
final boolean migrateFromDestination;
final String srcHostMigrateIp, srcHostMnIp, srcHostUuid;
vmUuid = s.vmUuid;
dstHostMigrateIp = s.dstHostMigrateIp;
dstHostMnIp = s.dstHostMnIp;
dstHostUuid = s.dstHostUuid;
storageMigrationPolicy = s.storageMigrationPolicy;
migrateFromDestination = s.migrateFromDestition;
srcHostMigrateIp = s.srcHostMigrateIp;
srcHostMnIp = s.srcHostMnIp;
srcHostUuid = s.srcHostUuid;
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.internalId);
q.add(VmInstanceVO_.uuid, Op.EQ, vmUuid);
final Long vmInternalId = q.findValue();
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("migrate-vm-%s-on-kvm-host-%s", vmUuid, self.getUuid()));
chain.then(new ShareFlow() {
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "migrate-vm";
@Override
public void run(final FlowTrigger trigger, Map data) {
TaskProgressRange stage = markTaskStage(parentStage, MIGRATE_VM_STAGE);
boolean autoConverage = KVMGlobalConfig.MIGRATE_AUTO_CONVERGE.value(Boolean.class);
if (!autoConverage) {
autoConverage = s.strategy != null && s.strategy.equals("auto-converge");
}
MigrateVmCmd cmd = new MigrateVmCmd();
cmd.setDestHostIp(dstHostMigrateIp);
cmd.setSrcHostIp(srcHostMigrateIp);
cmd.setMigrateFromDestination(migrateFromDestination);
cmd.setStorageMigrationPolicy(storageMigrationPolicy == null ? null : storageMigrationPolicy.toString());
cmd.setVmUuid(vmUuid);
cmd.setAutoConverge(autoConverage);
cmd.setUseNuma(rcf.getResourceConfigValue(VmGlobalConfig.NUMA, vmUuid, Boolean.class));
cmd.setTimeout(timeoutManager.getTimeout());
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(migrateVmPath);
ub.host(migrateFromDestination ? dstHostMnIp : srcHostMnIp);
String migrateUrl = ub.build().toString();
new Http<>(migrateUrl, cmd, MigrateVmResponse.class).call(migrateFromDestination ? dstHostUuid : srcHostUuid, new ReturnValueCompletion<MigrateVmResponse>(trigger) {
@Override
public void success(MigrateVmResponse ret) {
if (!ret.isSuccess()) {
ErrorCode err = err(HostErrors.FAILED_TO_MIGRATE_VM_ON_HYPERVISOR,
"failed to migrate vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s], %s",
vmUuid, srcHostUuid, srcHostMigrateIp, dstHostMigrateIp, ret.getError()
);
trigger.fail(err);
} else {
String info = String.format("successfully migrated vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s]",
vmUuid, srcHostUuid, srcHostMigrateIp, dstHostMigrateIp);
logger.debug(info);
reportProgress(stage.getEnd().toString());
trigger.next();
}
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "harden-vm-console-on-dst-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
HardenVmConsoleCmd cmd = new HardenVmConsoleCmd();
cmd.vmInternalId = vmInternalId;
cmd.vmUuid = vmUuid;
cmd.hostManagementIp = dstHostMnIp;
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.host(dstHostMnIp);
ub.path(KVMConstant.KVM_HARDEN_CONSOLE_PATH);
String url = ub.build().toString();
new Http<>(url, cmd, AgentResponse.class).call(dstHostUuid, new ReturnValueCompletion<AgentResponse>(trigger) {
@Override
public void success(AgentResponse ret) {
if (!ret.isSuccess()) {
//TODO: add GC
logger.warn(String.format("failed to harden VM[uuid:%s]'s console, %s", vmUuid, ret.getError()));
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
//TODO add GC
logger.warn(String.format("failed to harden VM[uuid:%s]'s console, %s", vmUuid, errorCode));
// continue
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "delete-vm-console-firewall-on-source-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
DeleteVmConsoleFirewallCmd cmd = new DeleteVmConsoleFirewallCmd();
cmd.vmInternalId = vmInternalId;
cmd.vmUuid = vmUuid;
cmd.hostManagementIp = srcHostMnIp;
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.host(srcHostMnIp);
ub.path(KVMConstant.KVM_DELETE_CONSOLE_FIREWALL_PATH);
String url = ub.build().toString();
new Http<>(url, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(trigger) {
@Override
public void success(AgentResponse ret) {
if (!ret.isSuccess()) {
logger.warn(String.format("failed to delete console firewall rule for the vm[uuid:%s] on" +
" the source host[uuid:%s, ip:%s], %s", vmUuid, srcHostUuid, srcHostMigrateIp, ret.getError()));
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
//TODO
logger.warn(String.format("failed to delete console firewall rule for the vm[uuid:%s] on" +
" the source host[uuid:%s, ip:%s], %s", vmUuid, srcHostUuid, srcHostMigrateIp, errorCode));
trigger.next();
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
String info = String.format("successfully migrated vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s]",
vmUuid, srcHostUuid, srcHostMigrateIp, dstHostMigrateIp);
logger.debug(info);
reportProgress(parentStage.getEnd().toString());
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
private void handle(final MigrateVmOnHypervisorMsg msg) {
inQueue().name(String.format("migrate-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> migrateVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
class MigrateStruct {
String vmUuid;
String dstHostMigrateIp;
String strategy;
String dstHostMnIp;
String dstHostUuid;
StorageMigrationPolicy storageMigrationPolicy;
boolean migrateFromDestition;
String srcHostMigrateIp;
String srcHostMnIp;
String srcHostUuid;
}
private MigrateStruct buildMigrateStuct(final MigrateVmOnHypervisorMsg msg){
MigrateStruct s = new MigrateStruct();
s.vmUuid = msg.getVmInventory().getUuid();
s.srcHostUuid = msg.getSrcHostUuid();
s.dstHostUuid = msg.getDestHostInventory().getUuid();
s.storageMigrationPolicy = msg.getStorageMigrationPolicy();
s.migrateFromDestition = msg.isMigrateFromDestination();
s.strategy = msg.getStrategy();
MigrateNetworkExtensionPoint.MigrateInfo migrateIpInfo = null;
for (MigrateNetworkExtensionPoint ext: pluginRgty.getExtensionList(MigrateNetworkExtensionPoint.class)) {
MigrateNetworkExtensionPoint.MigrateInfo r = ext.getMigrationAddressForVM(s.srcHostUuid, s.dstHostUuid);
if (r == null) {
continue;
}
migrateIpInfo = r;
}
s.dstHostMnIp = msg.getDestHostInventory().getManagementIp();
s.dstHostMigrateIp = migrateIpInfo == null ? s.dstHostMnIp : migrateIpInfo.dstMigrationAddress;
s.srcHostMnIp = Q.New(HostVO.class).eq(HostVO_.uuid, msg.getSrcHostUuid()).select(HostVO_.managementIp).findValue();
s.srcHostMigrateIp = migrateIpInfo == null ? s.srcHostMnIp : migrateIpInfo.srcMigrationAddress;
return s;
}
private void migrateVm(final MigrateVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
MigrateStruct s = buildMigrateStuct(msg);
final MigrateVmOnHypervisorReply reply = new MigrateVmOnHypervisorReply();
migrateVm(s, new Completion(msg, completion) {
@Override
public void success() {
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final VmUpdateNicOnHypervisorMsg msg) {
inQueue().name(String.format("update-nic-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> updateNic(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void updateNic(VmUpdateNicOnHypervisorMsg msg, NoErrorCompletion completion) {
checkStateAndStatus();
final VmUpdateNicOnHypervisorReply reply = new VmUpdateNicOnHypervisorReply();
List<VmNicVO> nics = Q.New(VmNicVO.class).eq(VmNicVO_.vmInstanceUuid, msg.getVmInstanceUuid()).list();
UpdateNicCmd cmd = new UpdateNicCmd();
cmd.setVmInstanceUuid(msg.getVmInstanceUuid());
cmd.setNics(VmNicInventory.valueOf(nics).stream().map(this::completeNicInfo).collect(Collectors.toList()));
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPreUpdateNicExtensionPoint ext : pluginRgty.getExtensionList(KVMPreUpdateNicExtensionPoint.class)) {
ext.preUpdateNic(inv, cmd);
}
new Http<>(updateNicPath, cmd, AttachNicResponse.class).call(new ReturnValueCompletion<AttachNicResponse>(msg, completion) {
@Override
public void success(AttachNicResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("failed to update nic[vm:%s] on kvm host[uuid:%s, ip:%s]," +
"because %s", msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final VmAttachNicOnHypervisorMsg msg) {
inQueue().name(String.format("attach-nic-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> attachNic(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void attachNic(final VmAttachNicOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
NicTO to = completeNicInfo(msg.getNicInventory());
final VmAttachNicOnHypervisorReply reply = new VmAttachNicOnHypervisorReply();
AttachNicCommand cmd = new AttachNicCommand();
cmd.setVmUuid(msg.getNicInventory().getVmInstanceUuid());
cmd.setNic(to);
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KvmPreAttachNicExtensionPoint ext : pluginRgty.getExtensionList(KvmPreAttachNicExtensionPoint.class)) {
ext.preAttachNicExtensionPoint(inv, cmd);
}
new Http<>(attachNicPath, cmd, AttachNicResponse.class).call(new ReturnValueCompletion<AttachNicResponse>(msg, completion) {
@Override
public void success(AttachNicResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("failed to attach nic[uuid:%s, vm:%s] on kvm host[uuid:%s, ip:%s]," +
"because %s", msg.getNicInventory().getUuid(), msg.getNicInventory().getVmInstanceUuid(),
self.getUuid(), self.getManagementIp(), ret.getError()));
}
bus.reply(msg, reply);
if (ret.getPciAddress() != null) {
SystemTagCreator creator = KVMSystemTags.VMNIC_PCI_ADDRESS.newSystemTagCreator(msg.getNicInventory().getUuid());
creator.inherent = true;
creator.recreate = true;
creator.setTagByTokens(map(e(KVMSystemTags.VMNIC_PCI_ADDRESS_TOKEN, ret.getPciAddress().toString())));
creator.create();
}
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final DetachVolumeFromVmOnHypervisorMsg msg) {
inQueue().name(String.format("detach-volume-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> detachVolume(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void detachVolume(final DetachVolumeFromVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final VolumeInventory vol = msg.getInventory();
final VmInstanceInventory vm = msg.getVmInventory();
VolumeTO to = VolumeTO.valueOfWithOutExtension(vol, (KVMHostInventory) getSelfInventory(), vm.getPlatform());
final DetachVolumeFromVmOnHypervisorReply reply = new DetachVolumeFromVmOnHypervisorReply();
final DetachDataVolumeCmd cmd = new DetachDataVolumeCmd();
cmd.setVolume(to);
cmd.setVmUuid(vm.getUuid());
extEmitter.beforeDetachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd);
new Http<>(detachDataVolumePath, cmd, DetachDataVolumeResponse.class).call(new ReturnValueCompletion<DetachDataVolumeResponse>(msg, completion) {
@Override
public void success(DetachDataVolumeResponse ret) {
if (!ret.isSuccess()) {
ErrorCode err = operr("failed to detach data volume[uuid:%s, installPath:%s] from vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s",
vol.getUuid(), vol.getInstallPath(), vm.getUuid(), vm.getName(), getSelf().getUuid(), getSelf().getManagementIp(), ret.getError());
reply.setError(err);
extEmitter.detachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError());
bus.reply(msg, reply);
completion.done();
} else {
extEmitter.afterDetachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd);
bus.reply(msg, reply);
completion.done();
}
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
extEmitter.detachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError());
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final AttachVolumeToVmOnHypervisorMsg msg) {
inQueue().name(String.format("attach-volume-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> attachVolume(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
static String computeWwnIfAbsent(String volumeUUid) {
String wwn;
String tag = KVMSystemTags.VOLUME_WWN.getTag(volumeUUid);
if (tag != null) {
wwn = KVMSystemTags.VOLUME_WWN.getTokenByTag(tag, KVMSystemTags.VOLUME_WWN_TOKEN);
} else {
wwn = new WwnUtils().getRandomWwn();
SystemTagCreator creator = KVMSystemTags.VOLUME_WWN.newSystemTagCreator(volumeUUid);
creator.inherent = true;
creator.setTagByTokens(Collections.singletonMap(KVMSystemTags.VOLUME_WWN_TOKEN, wwn));
creator.create();
}
DebugUtils.Assert(new WwnUtils().isValidWwn(wwn), String.format("Not a valid wwn[%s] for volume[uuid:%s]", wwn, volumeUUid));
return wwn;
}
private String makeAndSaveVmSystemSerialNumber(String vmUuid) {
String serialNumber;
String tag = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.getTag(vmUuid);
if (tag != null) {
serialNumber = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.getTokenByTag(tag, VmSystemTags.VM_SYSTEM_SERIAL_NUMBER_TOKEN);
} else {
SystemTagCreator creator = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.newSystemTagCreator(vmUuid);
creator.ignoreIfExisting = true;
creator.inherent = true;
creator.setTagByTokens(map(e(VmSystemTags.VM_SYSTEM_SERIAL_NUMBER_TOKEN, UUID.randomUUID().toString())));
SystemTagInventory inv = creator.create();
serialNumber = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.getTokenByTag(inv.getTag(), VmSystemTags.VM_SYSTEM_SERIAL_NUMBER_TOKEN);
}
return serialNumber;
}
private void attachVolume(final AttachVolumeToVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
KVMHostInventory host = (KVMHostInventory) getSelfInventory();
final VolumeInventory vol = msg.getInventory();
final VmInstanceInventory vm = msg.getVmInventory();
VolumeTO to = VolumeTO.valueOfWithOutExtension(vol, host, vm.getPlatform());
final AttachVolumeToVmOnHypervisorReply reply = new AttachVolumeToVmOnHypervisorReply();
final AttachDataVolumeCmd cmd = new AttachDataVolumeCmd();
cmd.setVolume(to);
cmd.setVmUuid(msg.getVmInventory().getUuid());
cmd.getAddons().put("attachedDataVolumes", VolumeTO.valueOf(msg.getAttachedDataVolumes(), host));
Map data = new HashMap();
extEmitter.beforeAttachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd, data);
new Http<>(attachDataVolumePath, cmd, AttachDataVolumeResponse.class).call(new ReturnValueCompletion<AttachDataVolumeResponse>(msg, completion) {
@Override
public void success(AttachDataVolumeResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("failed to attach data volume[uuid:%s, installPath:%s] to vm[uuid:%s, name:%s]" +
" on kvm host[uuid:%s, ip:%s], because %s", vol.getUuid(), vol.getInstallPath(), vm.getUuid(), vm.getName(),
getSelf().getUuid(), getSelf().getManagementIp(), ret.getError()));
extEmitter.attachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError(), data);
} else {
extEmitter.afterAttachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
extEmitter.attachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, err, data);
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final DestroyVmOnHypervisorMsg msg) {
inQueue().name(String.format("destroy-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> destroyVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void destroyVm(final DestroyVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
try {
extEmitter.beforeDestroyVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv);
} catch (KVMException e) {
ErrorCode err = operr("failed to destroy vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(),
self.getUuid(), self.getManagementIp(), e.getMessage());
throw new OperationFailureException(err);
}
DestroyVmCmd cmd = new DestroyVmCmd();
cmd.setUuid(vminv.getUuid());
new Http<>(destroyVmPath, cmd, DestroyVmResponse.class).call(new ReturnValueCompletion<DestroyVmResponse>(msg, completion) {
@Override
public void success(DestroyVmResponse ret) {
DestroyVmOnHypervisorReply reply = new DestroyVmOnHypervisorReply();
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_DESTROY_VM_ON_HYPERVISOR, "unable to destroy vm[uuid:%s, name:%s] on kvm host [uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
extEmitter.destroyVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
} else {
logger.debug(String.format("successfully destroyed vm[uuid:%s] on kvm host[uuid:%s]", vminv.getUuid(), self.getUuid()));
extEmitter.destroyVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
DestroyVmOnHypervisorReply reply = new DestroyVmOnHypervisorReply();
if (err.isError(SysErrors.HTTP_ERROR, SysErrors.IO_ERROR, SysErrors.TIMEOUT)) {
err = err(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, err, "unable to destroy a vm");
}
reply.setError(err);
extEmitter.destroyVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final RebootVmOnHypervisorMsg msg) {
inQueue().name(String.format("reboot-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> rebootVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private List<String> toKvmBootDev(List<String> order) {
List<String> ret = new ArrayList<String>();
for (String o : order) {
if (VmBootDevice.HardDisk.toString().equals(o)) {
ret.add(BootDev.hd.toString());
} else if (VmBootDevice.CdRom.toString().equals(o)) {
ret.add(BootDev.cdrom.toString());
} else if (VmBootDevice.Network.toString().equals(o)) {
ret.add(BootDev.network.toString());
} else {
throw new CloudRuntimeException(String.format("unknown boot device[%s]", o));
}
}
return ret;
}
private void rebootVm(final RebootVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
try {
extEmitter.beforeRebootVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv);
} catch (KVMException e) {
String err = String.format("failed to reboot vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(),
self.getUuid(), self.getManagementIp(), e.getMessage());
logger.warn(err, e);
throw new OperationFailureException(operr(err));
}
RebootVmCmd cmd = new RebootVmCmd();
long timeout = TimeUnit.MILLISECONDS.toSeconds(msg.getTimeout());
cmd.setUuid(vminv.getUuid());
cmd.setTimeout(timeout);
cmd.setBootDev(toKvmBootDev(msg.getBootOrders()));
new Http<>(rebootVmPath, cmd, RebootVmResponse.class).call(new ReturnValueCompletion<RebootVmResponse>(msg, completion) {
@Override
public void success(RebootVmResponse ret) {
RebootVmOnHypervisorReply reply = new RebootVmOnHypervisorReply();
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_REBOOT_VM_ON_HYPERVISOR, "unable to reboot vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
extEmitter.rebootVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
} else {
extEmitter.rebootVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
RebootVmOnHypervisorReply reply = new RebootVmOnHypervisorReply();
reply.setError(err);
extEmitter.rebootVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final StopVmOnHypervisorMsg msg) {
inQueue().name(String.format("stop-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> stopVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void stopVm(final StopVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
try {
extEmitter.beforeStopVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv);
} catch (KVMException e) {
ErrorCode err = operr("failed to stop vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(),
self.getUuid(), self.getManagementIp(), e.getMessage());
throw new OperationFailureException(err);
}
StopVmCmd cmd = new StopVmCmd();
cmd.setUuid(vminv.getUuid());
cmd.setType(msg.getType());
cmd.setTimeout(120);
new Http<>(stopVmPath, cmd, StopVmResponse.class).call(new ReturnValueCompletion<StopVmResponse>(msg, completion) {
@Override
public void success(StopVmResponse ret) {
StopVmOnHypervisorReply reply = new StopVmOnHypervisorReply();
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, "unable to stop vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
logger.warn(reply.getError().getDetails());
extEmitter.stopVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
} else {
extEmitter.stopVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
StopVmOnHypervisorReply reply = new StopVmOnHypervisorReply();
if (err.isError(SysErrors.IO_ERROR, SysErrors.HTTP_ERROR)) {
err = err(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, err, "unable to stop a vm");
}
reply.setError(err);
extEmitter.stopVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, err);
bus.reply(msg, reply);
completion.done();
}
});
}
@Transactional
private void setDataVolumeUseVirtIOSCSI(final VmInstanceSpec spec) {
String vmUuid = spec.getVmInventory().getUuid();
Map<String, Integer> diskOfferingUuid_Num = new HashMap<>();
List<Map<String, String>> tokenList = KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI.getTokensOfTagsByResourceUuid(vmUuid);
for (Map<String, String> tokens : tokenList) {
String diskOfferingUuid = tokens.get(KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI_TOKEN);
Integer num = Integer.parseInt(tokens.get(KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI_NUM_TOKEN));
diskOfferingUuid_Num.put(diskOfferingUuid, num);
}
for (VolumeInventory volumeInv : spec.getDestDataVolumes()) {
if (volumeInv.getType().equals(VolumeType.Root.toString())) {
continue;
}
if (diskOfferingUuid_Num.containsKey(volumeInv.getDiskOfferingUuid())
&& diskOfferingUuid_Num.get(volumeInv.getDiskOfferingUuid()) > 0) {
tagmgr.createNonInherentSystemTag(volumeInv.getUuid(),
KVMSystemTags.VOLUME_VIRTIO_SCSI.getTagFormat(),
VolumeVO.class.getSimpleName());
diskOfferingUuid_Num.put(volumeInv.getDiskOfferingUuid(),
diskOfferingUuid_Num.get(volumeInv.getDiskOfferingUuid()) - 1);
}
}
}
private void handle(final CreateVmOnHypervisorMsg msg) {
inQueue().name(String.format("start-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> {
setDataVolumeUseVirtIOSCSI(msg.getVmSpec());
startVm(msg.getVmSpec(), msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
});
}
private void handle(final UpdateSpiceChannelConfigMsg msg) {
UpdateSpiceChannelConfigReply reply = new UpdateSpiceChannelConfigReply();
UpdateSpiceChannelConfigCmd cmd = new UpdateSpiceChannelConfigCmd();
new Http<>(updateSpiceChannelConfigPath, cmd, UpdateSpiceChannelConfigResponse.class).call(new ReturnValueCompletion<UpdateSpiceChannelConfigResponse>(msg) {
@Override
public void success(UpdateSpiceChannelConfigResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("Host[%s] update spice channel config faild, because %s", msg.getHostUuid(), ret.getError()));
logger.warn(reply.getError().getDetails());
}
reply.setRestartLibvirt(ret.restartLibvirt);
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
}
});
}
private L2NetworkInventory getL2NetworkTypeFromL3NetworkUuid(String l3NetworkUuid) {
String sql = "select l2 from L2NetworkVO l2 where l2.uuid = (select l3.l2NetworkUuid from L3NetworkVO l3 where l3.uuid = :l3NetworkUuid)";
TypedQuery<L2NetworkVO> query = dbf.getEntityManager().createQuery(sql, L2NetworkVO.class);
query.setParameter("l3NetworkUuid", l3NetworkUuid);
L2NetworkVO l2vo = query.getSingleResult();
return L2NetworkInventory.valueOf(l2vo);
}
@Transactional(readOnly = true)
private NicTO completeNicInfo(VmNicInventory nic) {
/* all l3 networks of the nic has same l2 network */
L3NetworkInventory l3Inv = L3NetworkInventory.valueOf(dbf.findByUuid(nic.getL3NetworkUuid(), L3NetworkVO.class));
L2NetworkInventory l2inv = getL2NetworkTypeFromL3NetworkUuid(nic.getL3NetworkUuid());
KVMCompleteNicInformationExtensionPoint extp = factory.getCompleteNicInfoExtension(L2NetworkType.valueOf(l2inv.getType()));
NicTO to = extp.completeNicInformation(l2inv, l3Inv, nic);
if (to.getUseVirtio() == null) {
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.platform);
q.add(VmInstanceVO_.uuid, Op.EQ, nic.getVmInstanceUuid());
String platform = q.findValue();
to.setUseVirtio(ImagePlatform.valueOf(platform).isParaVirtualization());
to.setIps(getCleanTrafficIp(nic));
}
if (!nic.getType().equals(VmInstanceConstant.VIRTUAL_NIC_TYPE)) {
return to;
}
// build vhost addon
if (to.getDriverType() == null) {
if (nic.getDriverType() != null) {
to.setDriverType(nic.getDriverType());
} else {
to.setDriverType(to.getUseVirtio() ? nicManager.getDefaultPVNicDriver() : nicManager.getDefaultNicDriver());
}
}
VHostAddOn vHostAddOn = new VHostAddOn();
if (to.getDriverType().equals(nicManager.getDefaultPVNicDriver())) {
vHostAddOn.setQueueNum(rcf.getResourceConfigValue(VmGlobalConfig.VM_NIC_MULTIQUEUE_NUM, nic.getVmInstanceUuid(), Integer.class));
} else {
vHostAddOn.setQueueNum(VmGlobalConfig.VM_NIC_MULTIQUEUE_NUM.defaultValue(Integer.class));
}
if (VmSystemTags.VM_VRING_BUFFER_SIZE.hasTag(nic.getVmInstanceUuid())) {
Map<String, String> tokens = VmSystemTags.VM_VRING_BUFFER_SIZE.getTokensByResourceUuid(nic.getVmInstanceUuid());
if (tokens.get(VmSystemTags.RX_SIZE_TOKEN) != null) {
vHostAddOn.setRxBufferSize(tokens.get(VmSystemTags.RX_SIZE_TOKEN));
}
if (tokens.get(VmSystemTags.TX_SIZE_TOKEN) != null) {
vHostAddOn.setTxBufferSize(tokens.get(VmSystemTags.TX_SIZE_TOKEN));
}
}
to.setvHostAddOn(vHostAddOn);
String pci = KVMSystemTags.VMNIC_PCI_ADDRESS.getTokenByResourceUuid(nic.getUuid(), KVMSystemTags.VMNIC_PCI_ADDRESS_TOKEN);
if (pci != null) {
to.setPci(PciAddressConfig.fromString(pci));
}
return to;
}
private List<String> getCleanTrafficIp(VmNicInventory nic) {
boolean isUserVm = Q.New(VmInstanceVO.class)
.eq(VmInstanceVO_.uuid, nic.getVmInstanceUuid()).select(VmInstanceVO_.type)
.findValue().equals(VmInstanceConstant.USER_VM_TYPE);
if (!isUserVm) {
return null;
}
String tagValue = VmSystemTags.CLEAN_TRAFFIC.getTokenByResourceUuid(nic.getVmInstanceUuid(), VmSystemTags.CLEAN_TRAFFIC_TOKEN);
if (Boolean.valueOf(tagValue) || (tagValue == null && VmGlobalConfig.VM_CLEAN_TRAFFIC.value(Boolean.class))) {
return VmNicHelper.getIpAddresses(nic);
}
return null;
}
static String getVolumeTOType(VolumeInventory vol) {
DebugUtils.Assert(vol.getInstallPath() != null, String.format("volume [%s] installPath is null, it has not been initialized", vol.getUuid()));
return vol.getInstallPath().startsWith("iscsi") ? VolumeTO.ISCSI : VolumeTO.FILE;
}
private void startVm(final VmInstanceSpec spec, final NeedReplyMessage msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final StartVmCmd cmd = new StartVmCmd();
boolean virtio;
String nestedVirtualization;
String platform = spec.getVmInventory().getPlatform() == null ? spec.getImageSpec().getInventory().getPlatform() :
spec.getVmInventory().getPlatform();
if (ImagePlatform.Windows.toString().equals(platform)) {
virtio = VmSystemTags.WINDOWS_VOLUME_ON_VIRTIO.hasTag(spec.getVmInventory().getUuid());
} else {
virtio = ImagePlatform.valueOf(platform).isParaVirtualization();
}
int cpuNum = spec.getVmInventory().getCpuNum();
cmd.setCpuNum(cpuNum);
int socket;
int cpuOnSocket;
//TODO: this is a HACK!!!
if (ImagePlatform.Windows.toString().equals(platform) || ImagePlatform.WindowsVirtio.toString().equals(platform)) {
if (cpuNum == 1) {
socket = 1;
cpuOnSocket = 1;
} else if (cpuNum % 2 == 0) {
socket = 2;
cpuOnSocket = cpuNum / 2;
} else {
socket = cpuNum;
cpuOnSocket = 1;
}
} else {
socket = 1;
cpuOnSocket = cpuNum;
}
cmd.setImagePlatform(platform);
cmd.setSocketNum(socket);
cmd.setCpuOnSocket(cpuOnSocket);
cmd.setVmName(spec.getVmInventory().getName());
cmd.setVmInstanceUuid(spec.getVmInventory().getUuid());
cmd.setCpuSpeed(spec.getVmInventory().getCpuSpeed());
cmd.setMemory(spec.getVmInventory().getMemorySize());
cmd.setMaxMemory(self.getCapacity().getTotalPhysicalMemory());
cmd.setClock(ImagePlatform.isType(platform, ImagePlatform.Windows, ImagePlatform.WindowsVirtio) ? "localtime" : "utc");
cmd.setVideoType(VmGlobalConfig.VM_VIDEO_TYPE.value(String.class));
if (VmSystemTags.QXL_MEMORY.hasTag(spec.getVmInventory().getUuid())) {
Map<String,String> qxlMemory = VmSystemTags.QXL_MEMORY.getTokensByResourceUuid(spec.getVmInventory().getUuid());
cmd.setQxlMemory(qxlMemory);
}
if (VmSystemTags.SOUND_TYPE.hasTag(spec.getVmInventory().getUuid())) {
cmd.setSoundType(VmSystemTags.SOUND_TYPE.getTokenByResourceUuid(spec.getVmInventory().getUuid(), VmInstanceVO.class, VmSystemTags.SOUND_TYPE_TOKEN));
}
cmd.setInstanceOfferingOnlineChange(VmSystemTags.INSTANCEOFFERING_ONLIECHANGE.getTokenByResourceUuid(spec.getVmInventory().getUuid(), VmSystemTags.INSTANCEOFFERING_ONLINECHANGE_TOKEN) != null);
cmd.setKvmHiddenState(rcf.getResourceConfigValue(VmGlobalConfig.KVM_HIDDEN_STATE, spec.getDestHost().getClusterUuid(), Boolean.class));
cmd.setSpiceStreamingMode(VmGlobalConfig.VM_SPICE_STREAMING_MODE.value(String.class));
cmd.setEmulateHyperV(rcf.getResourceConfigValue(VmGlobalConfig.EMULATE_HYPERV, spec.getVmInventory().getUuid(), Boolean.class));
cmd.setAdditionalQmp(VmGlobalConfig.ADDITIONAL_QMP.value(Boolean.class));
cmd.setApplianceVm(spec.getVmInventory().getType().equals("ApplianceVm"));
cmd.setSystemSerialNumber(makeAndSaveVmSystemSerialNumber(spec.getVmInventory().getUuid()));
if (!NetworkGlobalProperty.CHASSIS_ASSET_TAG.isEmpty()) {
cmd.setChassisAssetTag(NetworkGlobalProperty.CHASSIS_ASSET_TAG);
}
String machineType = VmSystemTags.MACHINE_TYPE.getTokenByResourceUuid(cmd.getVmInstanceUuid(),
VmInstanceVO.class, VmSystemTags.MACHINE_TYPE_TOKEN);
cmd.setMachineType(StringUtils.isNotEmpty(machineType) ? machineType : "pc");
if (KVMSystemTags.VM_PREDEFINED_PCI_BRIDGE_NUM.hasTag(spec.getVmInventory().getUuid())) {
cmd.setPredefinedPciBridgeNum(Integer.valueOf(KVMSystemTags.VM_PREDEFINED_PCI_BRIDGE_NUM.getTokenByResourceUuid(spec.getVmInventory().getUuid(), KVMSystemTags.VM_PREDEFINED_PCI_BRIDGE_NUM_TOKEN)));
}
if (VmMachineType.q35.toString().equals(machineType)) {
cmd.setPciePortNums(VmGlobalConfig.PCIE_PORT_NUMS.value(Integer.class));
if (cmd.getPredefinedPciBridgeNum() == null) {
cmd.setPredefinedPciBridgeNum(1);
}
}
VmPriorityLevel level = new VmPriorityOperator().getVmPriority(spec.getVmInventory().getUuid());
VmPriorityConfigVO priorityVO = Q.New(VmPriorityConfigVO.class).eq(VmPriorityConfigVO_.level, level).find();
cmd.setPriorityConfigStruct(new PriorityConfigStruct(priorityVO, spec.getVmInventory().getUuid()));
VolumeTO rootVolume = new VolumeTO();
rootVolume.setInstallPath(spec.getDestRootVolume().getInstallPath());
rootVolume.setDeviceId(spec.getDestRootVolume().getDeviceId());
rootVolume.setDeviceType(getVolumeTOType(spec.getDestRootVolume()));
rootVolume.setVolumeUuid(spec.getDestRootVolume().getUuid());
rootVolume.setUseVirtio(virtio);
rootVolume.setUseVirtioSCSI(KVMSystemTags.VOLUME_VIRTIO_SCSI.hasTag(spec.getDestRootVolume().getUuid()));
rootVolume.setWwn(computeWwnIfAbsent(spec.getDestRootVolume().getUuid()));
rootVolume.setCacheMode(KVMGlobalConfig.LIBVIRT_CACHE_MODE.value());
nestedVirtualization = KVMGlobalConfig.NESTED_VIRTUALIZATION.value(String.class);
cmd.setNestedVirtualization(nestedVirtualization);
cmd.setRootVolume(rootVolume);
cmd.setUseBootMenu(VmGlobalConfig.VM_BOOT_MENU.value(Boolean.class));
List<VolumeTO> dataVolumes = new ArrayList<>(spec.getDestDataVolumes().size());
for (VolumeInventory data : spec.getDestDataVolumes()) {
VolumeTO v = VolumeTO.valueOfWithOutExtension(data, (KVMHostInventory) getSelfInventory(), spec.getVmInventory().getPlatform());
// always use virtio driver for data volume
v.setUseVirtio(true);
dataVolumes.add(v);
}
dataVolumes.sort(Comparator.comparing(VolumeTO::getDeviceId));
cmd.setDataVolumes(dataVolumes);
cmd.setVmInternalId(spec.getVmInventory().getInternalId());
List<NicTO> nics = new ArrayList<>(spec.getDestNics().size());
for (VmNicInventory nic : spec.getDestNics()) {
NicTO to = completeNicInfo(nic);
nics.add(to);
}
nics = nics.stream().sorted(Comparator.comparing(NicTO::getDeviceId)).collect(Collectors.toList());
cmd.setNics(nics);
for (VmInstanceSpec.CdRomSpec cdRomSpec : spec.getCdRomSpecs()) {
CdRomTO cdRomTO = new CdRomTO();
cdRomTO.setPath(cdRomSpec.getInstallPath());
cdRomTO.setImageUuid(cdRomSpec.getImageUuid());
cdRomTO.setDeviceId(cdRomSpec.getDeviceId());
cdRomTO.setEmpty(cdRomSpec.getImageUuid() == null);
cmd.getCdRoms().add(cdRomTO);
}
String bootMode = VmSystemTags.BOOT_MODE.getTokenByResourceUuid(spec.getVmInventory().getUuid(), VmSystemTags.BOOT_MODE_TOKEN);
cmd.setBootMode(bootMode == null ? ImageBootMode.Legacy.toString() : bootMode);
deviceBootOrderOperator.updateVmDeviceBootOrder(cmd, spec);
cmd.setBootDev(toKvmBootDev(spec.getBootOrders()));
cmd.setHostManagementIp(self.getManagementIp());
cmd.setConsolePassword(spec.getConsolePassword());
cmd.setUsbRedirect(spec.getUsbRedirect());
cmd.setVDIMonitorNumber(Integer.valueOf(spec.getVDIMonitorNumber()));
cmd.setUseNuma(rcf.getResourceConfigValue(VmGlobalConfig.NUMA, spec.getVmInventory().getUuid(), Boolean.class));
cmd.setVmPortOff(VmGlobalConfig.VM_PORT_OFF.value(Boolean.class));
cmd.setConsoleMode("vnc");
cmd.setTimeout(TimeUnit.MINUTES.toSeconds(5));
if (spec.isCreatePaused()) {
cmd.setCreatePaused(true);
}
addons(spec, cmd);
KVMHostInventory khinv = KVMHostInventory.valueOf(getSelf());
extEmitter.beforeStartVmOnKvm(khinv, spec, cmd);
extEmitter.addOn(khinv, spec, cmd);
new Http<>(startVmPath, cmd, StartVmResponse.class).call(new ReturnValueCompletion<StartVmResponse>(msg, completion) {
@Override
public void success(StartVmResponse ret) {
StartVmOnHypervisorReply reply = new StartVmOnHypervisorReply();
if (ret.isSuccess()) {
String info = String.format("successfully start vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s]",
spec.getVmInventory().getUuid(), spec.getVmInventory().getName(),
self.getUuid(), self.getManagementIp());
logger.debug(info);
extEmitter.startVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), spec);
} else {
reply.setError(err(HostErrors.FAILED_TO_START_VM_ON_HYPERVISOR, "failed to start vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s",
spec.getVmInventory().getUuid(), spec.getVmInventory().getName(),
self.getUuid(), self.getManagementIp(), ret.getError()));
logger.warn(reply.getError().getDetails());
extEmitter.startVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), spec, reply.getError());
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
StartVmOnHypervisorReply reply = new StartVmOnHypervisorReply();
reply.setError(err);
reply.setSuccess(false);
extEmitter.startVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), spec, err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void addons(final VmInstanceSpec spec, StartVmCmd cmd) {
KVMAddons.Channel chan = new KVMAddons.Channel();
chan.setSocketPath(makeChannelSocketPath(spec.getVmInventory().getUuid()));
chan.setTargetName("org.qemu.guest_agent.0");
cmd.getAddons().put(KVMAddons.Channel.NAME, chan);
logger.debug(String.format("make kvm channel device[path:%s, target:%s]", chan.getSocketPath(), chan.getTargetName()));
}
private String makeChannelSocketPath(String apvmuuid) {
return PathUtil.join(String.format("/var/lib/libvirt/qemu/%s", apvmuuid));
}
private void handle(final StartVmOnHypervisorMsg msg) {
inQueue().name(String.format("start-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> startVmInQueue(msg, chain));
}
private void startVmInQueue(StartVmOnHypervisorMsg msg, SyncTaskChain outterChain) {
thdf.chainSubmit(new ChainTask(msg, outterChain) {
@Override
public String getSyncSignature() {
return getName();
}
@Override
public void run(final SyncTaskChain chain) {
startVm(msg.getVmSpec(), msg, new NoErrorCompletion(chain, outterChain) {
@Override
public void done() {
chain.next();
outterChain.next();
}
});
}
@Override
public String getName() {
return String.format("start-vm-on-kvm-%s-inner-queue", self.getUuid());
}
@Override
protected int getSyncLevel() {
return KVMGlobalConfig.VM_CREATE_CONCURRENCY.value(Integer.class);
}
});
}
private void handle(final CheckNetworkPhysicalInterfaceMsg msg) {
inQueue().name(String.format("check-network-physical-interface-on-host-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> checkPhysicalInterface(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void pauseVm(final PauseVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
PauseVmOnHypervisorReply reply = new PauseVmOnHypervisorReply();
PauseVmCmd cmd = new PauseVmCmd();
cmd.setUuid(vminv.getUuid());
cmd.setTimeout(120);
new Http<>(pauseVmPath, cmd, PauseVmResponse.class).call(new ReturnValueCompletion<PauseVmResponse>(msg, completion) {
@Override
public void success(PauseVmResponse ret) {
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, "unable to pause vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
logger.warn(reply.getError().getDetails());
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final PauseVmOnHypervisorMsg msg) {
inQueue().name(String.format("pause-vm-%s-on-host-%s", msg.getVmInventory().getUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> pauseVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void handle(final ResumeVmOnHypervisorMsg msg) {
inQueue().name(String.format("resume-vm-%s-on-host-%s", msg.getVmInventory().getUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> resumeVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void resumeVm(final ResumeVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
ResumeVmOnHypervisorReply reply = new ResumeVmOnHypervisorReply();
ResumeVmCmd cmd = new ResumeVmCmd();
cmd.setUuid(vminv.getUuid());
cmd.setTimeout(120);
new Http<>(resumeVmPath, cmd, ResumeVmResponse.class).call(new ReturnValueCompletion<ResumeVmResponse>(msg, completion) {
@Override
public void success(ResumeVmResponse ret) {
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, "unable to resume vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
logger.warn(reply.getError().getDetails());
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void checkPhysicalInterface(CheckNetworkPhysicalInterfaceMsg msg, NoErrorCompletion completion) {
checkState();
CheckPhysicalNetworkInterfaceCmd cmd = new CheckPhysicalNetworkInterfaceCmd();
cmd.addInterfaceName(msg.getPhysicalInterface());
CheckNetworkPhysicalInterfaceReply reply = new CheckNetworkPhysicalInterfaceReply();
CheckPhysicalNetworkInterfaceResponse rsp = restf.syncJsonPost(checkPhysicalNetworkInterfacePath, cmd, CheckPhysicalNetworkInterfaceResponse.class);
if (!rsp.isSuccess()) {
if (rsp.getFailedInterfaceNames().isEmpty()) {
reply.setError(operr("operation error, because:%s", rsp.getError()));
} else {
reply.setError(operr("failed to check physical network interfaces[names : %s] on kvm host[uuid:%s, ip:%s]",
msg.getPhysicalInterface(), context.getInventory().getUuid(), context.getInventory().getManagementIp()));
}
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void handleMessage(Message msg) {
try {
if (msg instanceof APIMessage) {
handleApiMessage((APIMessage) msg);
} else {
handleLocalMessage(msg);
}
} catch (Exception e) {
bus.logExceptionWithMessageDump(msg, e);
bus.replyErrorByMessageType(msg, e);
}
}
@Override
public void changeStateHook(HostState current, HostStateEvent stateEvent, HostState next) {
}
@Override
public void deleteHook() {
}
@Override
protected HostInventory getSelfInventory() {
return KVMHostInventory.valueOf(getSelf());
}
@Override
protected void pingHook(final Completion completion) {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("ping-kvm-host-%s", self.getUuid()));
chain.then(new ShareFlow() {
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "ping-host";
@AfterDone
List<Runnable> afterDone = new ArrayList<>();
@Override
public void run(FlowTrigger trigger, Map data) {
PingCmd cmd = new PingCmd();
cmd.hostUuid = self.getUuid();
restf.asyncJsonPost(pingPath, cmd, new JsonAsyncRESTCallback<PingResponse>(trigger) {
@Override
public void fail(ErrorCode err) {
trigger.fail(err);
}
@Override
public void success(PingResponse ret) {
if (ret.isSuccess()) {
if (!self.getUuid().equals(ret.getHostUuid())) {
afterDone.add(() -> {
String info = i18n("detected abnormal status[host uuid change, expected: %s but: %s] of kvmagent," +
"it's mainly caused by kvmagent restarts behind zstack management server. Report this to ping task, it will issue a reconnect soon", self.getUuid(), ret.getHostUuid());
logger.warn(info);
changeConnectionState(HostStatusEvent.disconnected);
new HostDisconnectedCanonicalEvent(self.getUuid(), argerr(info)).fire();
ReconnectHostMsg rmsg = new ReconnectHostMsg();
rmsg.setHostUuid(self.getUuid());
bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(rmsg);
});
}
trigger.next();
} else {
trigger.fail(operr("%s", ret.getError()));
}
}
@Override
public Class<PingResponse> getReturnClass() {
return PingResponse.class;
}
},TimeUnit.SECONDS, HostGlobalConfig.PING_HOST_TIMEOUT.value(Long.class));
}
});
flow(new NoRollbackFlow() {
String __name__ = "call-ping-no-failure-plugins";
@Override
public void run(FlowTrigger trigger, Map data) {
List<KVMPingAgentNoFailureExtensionPoint> exts = pluginRgty.getExtensionList(KVMPingAgentNoFailureExtensionPoint.class);
if (exts.isEmpty()) {
trigger.next();
return;
}
AsyncLatch latch = new AsyncLatch(exts.size(), new NoErrorCompletion(trigger) {
@Override
public void done() {
trigger.next();
}
});
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPingAgentNoFailureExtensionPoint ext : exts) {
ext.kvmPingAgentNoFailure(inv, new NoErrorCompletion(latch) {
@Override
public void done() {
latch.ack();
}
});
}
}
});
flow(new NoRollbackFlow() {
String __name__ = "call-ping-plugins";
@Override
public void run(FlowTrigger trigger, Map data) {
List<KVMPingAgentExtensionPoint> exts = pluginRgty.getExtensionList(KVMPingAgentExtensionPoint.class);
Iterator<KVMPingAgentExtensionPoint> it = exts.iterator();
callPlugin(it, trigger);
}
private void callPlugin(Iterator<KVMPingAgentExtensionPoint> it, FlowTrigger trigger) {
if (!it.hasNext()) {
trigger.next();
return;
}
KVMPingAgentExtensionPoint ext = it.next();
logger.debug(String.format("calling KVMPingAgentExtensionPoint[%s]", ext.getClass()));
ext.kvmPingAgent((KVMHostInventory) getSelfInventory(), new Completion(trigger) {
@Override
public void success() {
callPlugin(it, trigger);
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
@Override
protected int getVmMigrateQuantity() {
return KVMGlobalConfig.VM_MIGRATION_QUANTITY.value(Integer.class);
}
private ErrorCode connectToAgent() {
ErrorCode errCode = null;
try {
ConnectCmd cmd = new ConnectCmd();
cmd.setHostUuid(self.getUuid());
cmd.setSendCommandUrl(restf.getSendCommandUrl());
cmd.setIptablesRules(KVMGlobalProperty.IPTABLES_RULES);
cmd.setIgnoreMsrs(KVMGlobalConfig.KVM_IGNORE_MSRS.value(Boolean.class));
if (HostSystemTags.PAGE_TABLE_EXTENSION_DISABLED.hasTag(self.getUuid(), HostVO.class) || !KVMSystemTags.EPT_CPU_FLAG.hasTag(self.getUuid())) {
cmd.setPageTableExtensionDisabled(true);
}
ConnectResponse rsp = restf.syncJsonPost(connectPath, cmd, ConnectResponse.class);
if (!rsp.isSuccess() || !rsp.isIptablesSucc()) {
errCode = operr("unable to connect to kvm host[uuid:%s, ip:%s, url:%s], because %s",
self.getUuid(), self.getManagementIp(), connectPath, rsp.getError());
} else {
VersionComparator libvirtVersion = new VersionComparator(rsp.getLibvirtVersion());
VersionComparator qemuVersion = new VersionComparator(rsp.getQemuVersion());
boolean liveSnapshot = libvirtVersion.compare(KVMConstant.MIN_LIBVIRT_LIVESNAPSHOT_VERSION) >= 0
&& qemuVersion.compare(KVMConstant.MIN_QEMU_LIVESNAPSHOT_VERSION) >= 0;
String hostOS = HostSystemTags.OS_DISTRIBUTION.getTokenByResourceUuid(self.getUuid(), HostSystemTags.OS_DISTRIBUTION_TOKEN);
//liveSnapshot = liveSnapshot && (!"CentOS".equals(hostOS) || KVMGlobalConfig.ALLOW_LIVE_SNAPSHOT_ON_REDHAT.value(Boolean.class));
if (liveSnapshot) {
logger.debug(String.format("kvm host[OS:%s, uuid:%s, name:%s, ip:%s] supports live snapshot with libvirt[version:%s], qemu[version:%s]",
hostOS, self.getUuid(), self.getName(), self.getManagementIp(), rsp.getLibvirtVersion(), rsp.getQemuVersion()));
recreateNonInherentTag(HostSystemTags.LIVE_SNAPSHOT);
} else {
HostSystemTags.LIVE_SNAPSHOT.deleteInherentTag(self.getUuid());
}
}
} catch (RestClientException e) {
errCode = operr("unable to connect to kvm host[uuid:%s, ip:%s, url:%s], because %s", self.getUuid(), self.getManagementIp(),
connectPath, e.getMessage());
} catch (Throwable t) {
logger.warn(t.getMessage(), t);
errCode = inerr(t.getMessage());
}
return errCode;
}
private KVMHostVO getSelf() {
return (KVMHostVO) self;
}
private void continueConnect(final ConnectHostInfo info, final Completion completion) {
ErrorCode errCode = connectToAgent();
if (errCode != null) {
throw new OperationFailureException(errCode);
}
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("continue-connecting-kvm-host-%s-%s", self.getManagementIp(), self.getUuid()));
chain.allowWatch();
for (KVMHostConnectExtensionPoint extp : factory.getConnectExtensions()) {
KVMHostConnectedContext ctx = new KVMHostConnectedContext();
ctx.setInventory((KVMHostInventory) getSelfInventory());
ctx.setNewAddedHost(info.isNewAdded());
ctx.setBaseUrl(baseUrl);
ctx.setSkipPackages(info.getSkipPackages());
chain.then(extp.createKvmHostConnectingFlow(ctx));
}
chain.done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
if (noStorageAccessible()){
completion.fail(operr("host can not access any primary storage, please check network"));
} else {
completion.success();
}
}
}).error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(err(HostErrors.CONNECTION_ERROR, errCode, "connection error for KVM host[uuid:%s, ip:%s]", self.getUuid(),
self.getManagementIp()));
}
}).start();
}
@Transactional(readOnly = true)
private boolean noStorageAccessible(){
// detach ps will delete PrimaryStorageClusterRefVO first.
List<String> attachedPsUuids = Q.New(PrimaryStorageClusterRefVO.class)
.select(PrimaryStorageClusterRefVO_.primaryStorageUuid)
.eq(PrimaryStorageClusterRefVO_.clusterUuid, self.getClusterUuid())
.listValues();
long attachedPsCount = attachedPsUuids.size();
long inaccessiblePsCount = attachedPsCount == 0 ? 0 : Q.New(PrimaryStorageHostRefVO.class)
.eq(PrimaryStorageHostRefVO_.hostUuid, self.getUuid())
.eq(PrimaryStorageHostRefVO_.status, PrimaryStorageHostStatus.Disconnected)
.in(PrimaryStorageHostRefVO_.primaryStorageUuid, attachedPsUuids)
.count();
return inaccessiblePsCount == attachedPsCount && attachedPsCount > 0;
}
private void createHostVersionSystemTags(String distro, String release, String version) {
createTagWithoutNonValue(HostSystemTags.OS_DISTRIBUTION, HostSystemTags.OS_DISTRIBUTION_TOKEN, distro, true);
createTagWithoutNonValue(HostSystemTags.OS_RELEASE, HostSystemTags.OS_RELEASE_TOKEN, release, true);
createTagWithoutNonValue(HostSystemTags.OS_VERSION, HostSystemTags.OS_VERSION_TOKEN, version, true);
}
private void createTagWithoutNonValue(SystemTag tag, String token, String value, boolean inherent) {
if (value == null) {
return;
}
recreateTag(tag, token, value, inherent);
}
private void recreateNonInherentTag(SystemTag tag, String token, String value) {
recreateTag(tag, token, value, false);
}
private void recreateNonInherentTag(SystemTag tag) {
recreateTag(tag, null, null, false);
}
private void recreateInherentTag(SystemTag tag, String token, String value) {
recreateTag(tag, token, value, true);
}
private void recreateTag(SystemTag tag, String token, String value, boolean inherent) {
SystemTagCreator creator = tag.newSystemTagCreator(self.getUuid());
Optional.ofNullable(token).ifPresent(it -> creator.setTagByTokens(Collections.singletonMap(token, value)));
creator.inherent = inherent;
creator.recreate = true;
creator.create();
}
@Override
public void connectHook(final ConnectHostInfo info, final Completion complete) {
if (CoreGlobalProperty.UNIT_TEST_ON) {
if (info.isNewAdded()) {
createHostVersionSystemTags("zstack", "kvmSimulator", tester.get(ZTester.KVM_HostVersion, "0.1", String.class));
if (null == KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN)) {
createTagWithoutNonValue(KVMSystemTags.LIBVIRT_VERSION, KVMSystemTags.LIBVIRT_VERSION_TOKEN, tester.get(ZTester.KVM_LibvirtVersion, "1.2.9", String.class), true);
}
if (null == KVMSystemTags.QEMU_IMG_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.QEMU_IMG_VERSION_TOKEN)) {
createTagWithoutNonValue(KVMSystemTags.QEMU_IMG_VERSION, KVMSystemTags.QEMU_IMG_VERSION_TOKEN, tester.get(ZTester.KVM_QemuImageVersion, "2.0.0", String.class), true);
}
if (null == KVMSystemTags.CPU_MODEL_NAME.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.CPU_MODEL_NAME_TOKEN)) {
createTagWithoutNonValue(KVMSystemTags.CPU_MODEL_NAME, KVMSystemTags.CPU_MODEL_NAME_TOKEN, tester.get(ZTester.KVM_CpuModelName, "Broadwell", String.class), true);
}
if (null == KVMSystemTags.EPT_CPU_FLAG.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.EPT_CPU_FLAG_TOKEN)) {
createTagWithoutNonValue(KVMSystemTags.EPT_CPU_FLAG, KVMSystemTags.EPT_CPU_FLAG_TOKEN, "ept", false);
}
if (null == HostSystemTags.CPU_ARCHITECTURE.getTokenByResourceUuid(self.getUuid(), HostSystemTags.CPU_ARCHITECTURE_TOKEN)) {
createTagWithoutNonValue(HostSystemTags.CPU_ARCHITECTURE, HostSystemTags.CPU_ARCHITECTURE_TOKEN, "x86_64", false);
}
if (!checkQemuLibvirtVersionOfHost()) {
complete.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because qemu/libvirt version does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
if (KVMSystemTags.CHECK_CLUSTER_CPU_MODEL.hasTag(self.getClusterUuid())) {
if (KVMSystemTags.CHECK_CLUSTER_CPU_MODEL
.getTokenByResourceUuid(self.getClusterUuid(), KVMSystemTags.CHECK_CLUSTER_CPU_MODEL_TOKEN)
.equals("true")
&& !checkCpuModelOfHost()) {
complete.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
complete.success();
return;
}
if (KVMGlobalConfig.CHECK_HOST_CPU_MODEL_NAME.value(Boolean.class) && !checkCpuModelOfHost()) {
complete.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
}
continueConnect(info, complete);
} else {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("run-ansible-for-kvm-%s", self.getUuid()));
chain.allowWatch();
chain.then(new ShareFlow() {
boolean deployed = false;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "test-if-ssh-port-open";
@Override
public void run(FlowTrigger trigger, Map data) {
long sshTimeout = TimeUnit.SECONDS.toMillis(KVMGlobalConfig.TEST_SSH_PORT_ON_OPEN_TIMEOUT.value(Long.class));
long timeout = System.currentTimeMillis() + sshTimeout;
long ctimeout = TimeUnit.SECONDS.toMillis(KVMGlobalConfig.TEST_SSH_PORT_ON_CONNECT_TIMEOUT.value(Integer.class).longValue());
thdf.submitCancelablePeriodicTask(new CancelablePeriodicTask(trigger) {
@Override
public boolean run() {
if (testPort()) {
trigger.next();
return true;
}
return ifTimeout();
}
private boolean testPort() {
if (!NetworkUtils.isRemotePortOpen(getSelf().getManagementIp(), getSelf().getPort(), (int) ctimeout)) {
logger.debug(String.format("host[uuid:%s, name:%s, ip:%s]'s ssh port[%s] is not ready yet", getSelf().getUuid(), getSelf().getName(), getSelf().getManagementIp(), getSelf().getPort()));
return false;
} else {
return true;
}
}
private boolean ifTimeout() {
if (System.currentTimeMillis() > timeout) {
trigger.fail(operr("the host[%s] ssh port[%s] not open after %s seconds, connect timeout", getSelf().getManagementIp(), getSelf().getPort(), sshTimeout));
return true;
} else {
return false;
}
}
@Override
public TimeUnit getTimeUnit() {
return TimeUnit.SECONDS;
}
@Override
public long getInterval() {
return 2;
}
@Override
public String getName() {
return "test-ssh-port-open-for-kvm-host";
}
});
}
});
if (info.isNewAdded()) {
if ((!AnsibleGlobalProperty.ZSTACK_REPO.contains("zstack-mn")) && (!AnsibleGlobalProperty.ZSTACK_REPO.equals("false"))) {
flow(new NoRollbackFlow() {
String __name__ = "ping-DNS-check-list";
@Override
public void run(FlowTrigger trigger, Map data) {
String checkList;
if (AnsibleGlobalProperty.ZSTACK_REPO.contains(KVMConstant.ALI_REPO)) {
checkList = KVMGlobalConfig.HOST_DNS_CHECK_ALIYUN.value();
} else if (AnsibleGlobalProperty.ZSTACK_REPO.contains(KVMConstant.NETEASE_REPO)) {
checkList = KVMGlobalConfig.HOST_DNS_CHECK_163.value();
} else {
checkList = KVMGlobalConfig.HOST_DNS_CHECK_LIST.value();
}
checkList = checkList.replaceAll(",", " ");
SshShell sshShell = new SshShell();
sshShell.setHostname(getSelf().getManagementIp());
sshShell.setUsername(getSelf().getUsername());
sshShell.setPassword(getSelf().getPassword());
sshShell.setPort(getSelf().getPort());
SshResult ret = sshShell.runScriptWithToken("scripts/check-public-dns-name.sh",
map(e("dnsCheckList", checkList)));
if (ret.isSshFailure()) {
trigger.fail(operr("unable to connect to KVM[ip:%s, username:%s, sshPort: %d, ] to do DNS check, please check if username/password is wrong; %s", self.getManagementIp(), getSelf().getUsername(), getSelf().getPort(), ret.getExitErrorMessage()));
} else if (ret.getReturnCode() != 0) {
trigger.fail(operr("failed to ping all DNS/IP in %s; please check /etc/resolv.conf to make sure your host is able to reach public internet", checkList));
} else {
trigger.next();
}
}
});
}
}
flow(new NoRollbackFlow() {
String __name__ = "check-if-host-can-reach-management-node";
@Override
public void run(FlowTrigger trigger, Map data) {
SshShell sshShell = new SshShell();
sshShell.setHostname(getSelf().getManagementIp());
sshShell.setUsername(getSelf().getUsername());
sshShell.setPassword(getSelf().getPassword());
sshShell.setPort(getSelf().getPort());
ShellUtils.run(String.format("arp -d %s || true", getSelf().getManagementIp()));
SshResult ret = sshShell.runCommand(String.format("curl --connect-timeout 10 %s|| wget --spider -q --connect-timeout=10 %s|| test $? -eq 8", restf.getCallbackUrl(), restf.getCallbackUrl()));
if (ret.isSshFailure()) {
throw new OperationFailureException(operr("unable to connect to KVM[ip:%s, username:%s, sshPort:%d] to check the management node connectivity," +
"please check if username/password is wrong; %s", self.getManagementIp(), getSelf().getUsername(), getSelf().getPort(), ret.getExitErrorMessage()));
} else if (ret.getReturnCode() != 0) {
throw new OperationFailureException(operr("the KVM host[ip:%s] cannot access the management node's callback url. It seems" +
" that the KVM host cannot reach the management IP[%s]. %s %s", self.getManagementIp(), restf.getHostName(),
ret.getStderr(), ret.getExitErrorMessage()));
}
trigger.next();
}
});
flow(new NoRollbackFlow() {
String __name__ = "apply-ansible-playbook";
@Override
public void run(final FlowTrigger trigger, Map data) {
String srcPath = PathUtil.findFileOnClassPath(String.format("ansible/kvm/%s", agentPackageName), true).getAbsolutePath();
String destPath = String.format("/var/lib/zstack/kvm/package/%s", agentPackageName);
SshFileMd5Checker checker = new SshFileMd5Checker();
checker.setUsername(getSelf().getUsername());
checker.setPassword(getSelf().getPassword());
checker.setSshPort(getSelf().getPort());
checker.setTargetIp(getSelf().getManagementIp());
checker.addSrcDestPair(SshFileMd5Checker.ZSTACKLIB_SRC_PATH, String.format("/var/lib/zstack/kvm/package/%s", AnsibleGlobalProperty.ZSTACKLIB_PACKAGE_NAME));
checker.addSrcDestPair(srcPath, destPath);
SshChronyConfigChecker chronyChecker = new SshChronyConfigChecker();
chronyChecker.setTargetIp(getSelf().getManagementIp());
chronyChecker.setUsername(getSelf().getUsername());
chronyChecker.setPassword(getSelf().getPassword());
chronyChecker.setSshPort(getSelf().getPort());
SshYumRepoChecker repoChecker = new SshYumRepoChecker();
repoChecker.setTargetIp(getSelf().getManagementIp());
repoChecker.setUsername(getSelf().getUsername());
repoChecker.setPassword(getSelf().getPassword());
repoChecker.setSshPort(getSelf().getPort());
CallBackNetworkChecker callbackChecker = new CallBackNetworkChecker();
callbackChecker.setTargetIp(getSelf().getManagementIp());
callbackChecker.setUsername(getSelf().getUsername());
callbackChecker.setPassword(getSelf().getPassword());
callbackChecker.setPort(getSelf().getPort());
callbackChecker.setCallbackIp(Platform.getManagementServerIp());
callbackChecker.setCallBackPort(CloudBusGlobalProperty.HTTP_PORT);
AnsibleRunner runner = new AnsibleRunner();
runner.installChecker(checker);
runner.installChecker(chronyChecker);
runner.installChecker(repoChecker);
runner.installChecker(callbackChecker);
for (KVMHostAddSshFileMd5CheckerExtensionPoint exp : pluginRgty.getExtensionList(KVMHostAddSshFileMd5CheckerExtensionPoint.class)) {
SshFileMd5Checker sshFileMd5Checker = exp.getSshFileMd5Checker(getSelf());
if (sshFileMd5Checker != null) {
runner.installChecker(sshFileMd5Checker);
}
}
runner.setAgentPort(KVMGlobalProperty.AGENT_PORT);
runner.setTargetIp(getSelf().getManagementIp());
runner.setTargetUuid(getSelf().getUuid());
runner.setPlayBookName(KVMConstant.ANSIBLE_PLAYBOOK_NAME);
runner.setUsername(getSelf().getUsername());
runner.setPassword(getSelf().getPassword());
runner.setSshPort(getSelf().getPort());
if (info.isNewAdded()) {
runner.putArgument("init", "true");
runner.setFullDeploy(true);
}
if (NetworkGlobalProperty.SKIP_IPV6) {
runner.putArgument("skipIpv6", "true");
}
if (NetworkGlobalProperty.BRIDGE_DISABLE_IPTABLES) {
runner.putArgument("bridgeDisableIptables", "true");
}
runner.putArgument("pkg_kvmagent", agentPackageName);
runner.putArgument("hostname", String.format("%s.zstack.org", self.getManagementIp().replaceAll("\\.", "-")));
if (CoreGlobalProperty.SYNC_NODE_TIME) {
if (CoreGlobalProperty.CHRONY_SERVERS == null || CoreGlobalProperty.CHRONY_SERVERS.isEmpty()) {
trigger.fail(operr("chrony server not configured!"));
return;
}
runner.putArgument("chrony_servers", String.join(",", CoreGlobalProperty.CHRONY_SERVERS));
}
runner.putArgument("skip_packages", info.getSkipPackages());
runner.putArgument("update_packages", String.valueOf(CoreGlobalProperty.UPDATE_PKG_WHEN_CONNECT));
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(restf.getBaseUrl());
ub.path(new StringBind(KVMConstant.KVM_ANSIBLE_LOG_PATH_FROMAT).bind("uuid", self.getUuid()).toString());
String postUrl = ub.build().toString();
runner.putArgument("post_url", postUrl);
runner.run(new ReturnValueCompletion<Boolean>(trigger) {
@Override
public void success(Boolean run) {
if (run != null) {
deployed = run;
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "configure-iptables";
@Override
public void run(FlowTrigger trigger, Map data) {
StringBuilder builder = new StringBuilder();
if (!KVMGlobalProperty.MN_NETWORKS.isEmpty()) {
builder.append(String.format("sudo bash %s -m %s -p %s -c %s",
"/var/lib/zstack/kvm/kvmagent-iptables",
KVMConstant.IPTABLES_COMMENTS,
KVMGlobalConfig.KVMAGENT_ALLOW_PORTS_LIST.value(String.class),
String.join(",", KVMGlobalProperty.MN_NETWORKS)));
} else {
builder.append(String.format("sudo bash %s -m %s -p %s",
"/var/lib/zstack/kvm/kvmagent-iptables",
KVMConstant.IPTABLES_COMMENTS,
KVMGlobalConfig.KVMAGENT_ALLOW_PORTS_LIST.value(String.class)));
}
new Ssh().shell(builder.toString())
.setUsername(getSelf().getUsername())
.setPassword(getSelf().getPassword())
.setHostname(getSelf().getManagementIp())
.setPort(getSelf().getPort()).runErrorByExceptionAndClose();
trigger.next();
}
});
flow(new NoRollbackFlow() {
String __name__ = "echo-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
restf.echo(echoPath, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
boolean needRestart = KVMGlobalConfig.RESTART_AGENT_IF_FAKE_DEAD.value(Boolean.class);
if (!deployed && needRestart) {
// if not deployed and echo failed, we thought it is fake dead, see: ZSTACK-18628
AnsibleRunner runner = new AnsibleRunner();
runner.setAgentPort(KVMGlobalProperty.AGENT_PORT);
runner.setTargetIp(getSelf().getManagementIp());
runner.setTargetUuid(getSelf().getUuid());
runner.setUsername(getSelf().getUsername());
runner.setPassword(getSelf().getPassword());
runner.setSshPort(getSelf().getPort());
runner.restartAgent(AnsibleConstant.KVM_AGENT_NAME, new Completion(trigger) {
@Override
public void success() {
restf.echo(echoPath, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
} else {
trigger.fail(errorCode);
}
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "update-kvmagent-dependencies";
@Override
public void run(FlowTrigger trigger, Map data) {
if (!CoreGlobalProperty.UPDATE_PKG_WHEN_CONNECT) {
trigger.next();
return;
}
UpdateDependencyCmd cmd = new UpdateDependencyCmd();
cmd.hostUuid = self.getUuid();
new Http<>(updateDependencyPath, cmd, UpdateDependencyRsp.class)
.call(new ReturnValueCompletion<UpdateDependencyRsp>(trigger) {
@Override
public void success(UpdateDependencyRsp ret) {
if (ret.isSuccess()) {
trigger.next();
} else {
trigger.fail(Platform.operr("%s", ret.getError()));
}
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "collect-kvm-host-facts";
@Override
public void run(final FlowTrigger trigger, Map data) {
HostFactCmd cmd = new HostFactCmd();
new Http<>(hostFactPath, cmd, HostFactResponse.class)
.call(new ReturnValueCompletion<HostFactResponse>(trigger) {
@Override
public void success(HostFactResponse ret) {
if (!ret.isSuccess()) {
trigger.fail(operr("operation error, because:%s", ret.getError()));
return;
}
if (ret.getHvmCpuFlag() == null) {
trigger.fail(operr("cannot find either 'vmx' or 'svm' in /proc/cpuinfo, please make sure you have enabled virtualization in your BIOS setting"));
return;
}
// create system tags of os::version etc
createHostVersionSystemTags(ret.getOsDistribution(), ret.getOsRelease(), ret.getOsVersion());
createTagWithoutNonValue(KVMSystemTags.QEMU_IMG_VERSION, KVMSystemTags.QEMU_IMG_VERSION_TOKEN, ret.getQemuImgVersion(), false);
createTagWithoutNonValue(KVMSystemTags.LIBVIRT_VERSION, KVMSystemTags.LIBVIRT_VERSION_TOKEN, ret.getLibvirtVersion(), false);
createTagWithoutNonValue(KVMSystemTags.HVM_CPU_FLAG, KVMSystemTags.HVM_CPU_FLAG_TOKEN, ret.getHvmCpuFlag(), false);
createTagWithoutNonValue(KVMSystemTags.EPT_CPU_FLAG, KVMSystemTags.EPT_CPU_FLAG_TOKEN, ret.getEptFlag(), false);
createTagWithoutNonValue(KVMSystemTags.CPU_MODEL_NAME, KVMSystemTags.CPU_MODEL_NAME_TOKEN, ret.getCpuModelName(), false);
createTagWithoutNonValue(HostSystemTags.CPU_ARCHITECTURE, HostSystemTags.CPU_ARCHITECTURE_TOKEN, ret.getCpuArchitecture(), true);
createTagWithoutNonValue(HostSystemTags.HOST_CPU_MODEL_NAME, HostSystemTags.HOST_CPU_MODEL_NAME_TOKEN, ret.getHostCpuModelName(), true);
createTagWithoutNonValue(HostSystemTags.CPU_GHZ, HostSystemTags.CPU_GHZ_TOKEN, ret.getCpuGHz(), true);
createTagWithoutNonValue(HostSystemTags.SYSTEM_PRODUCT_NAME, HostSystemTags.SYSTEM_PRODUCT_NAME_TOKEN, ret.getSystemProductName(), true);
createTagWithoutNonValue(HostSystemTags.SYSTEM_SERIAL_NUMBER, HostSystemTags.SYSTEM_SERIAL_NUMBER_TOKEN, ret.getSystemSerialNumber(), true);
if (ret.getLibvirtVersion().compareTo(KVMConstant.MIN_LIBVIRT_VIRTIO_SCSI_VERSION) >= 0) {
recreateNonInherentTag(KVMSystemTags.VIRTIO_SCSI);
}
List<String> ips = ret.getIpAddresses();
if (ips != null) {
ips.remove(self.getManagementIp());
if (CoreGlobalProperty.MN_VIP != null) {
ips.remove(CoreGlobalProperty.MN_VIP);
}
if (!ips.isEmpty()) {
recreateNonInherentTag(HostSystemTags.EXTRA_IPS, HostSystemTags.EXTRA_IPS_TOKEN, StringUtils.join(ips, ","));
} else {
HostSystemTags.EXTRA_IPS.delete(self.getUuid());
}
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
if (info.isNewAdded()) {
flow(new NoRollbackFlow() {
String __name__ = "check-qemu-libvirt-version";
@Override
public void run(FlowTrigger trigger, Map data) {
if (!checkQemuLibvirtVersionOfHost()) {
trigger.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because qemu/libvirt version does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
if (KVMSystemTags.CHECK_CLUSTER_CPU_MODEL.hasTag(self.getClusterUuid())) {
if (KVMSystemTags.CHECK_CLUSTER_CPU_MODEL
.getTokenByResourceUuid(self.getClusterUuid(), KVMSystemTags.CHECK_CLUSTER_CPU_MODEL_TOKEN)
.equals("true")
&& !checkCpuModelOfHost()) {
trigger.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
trigger.next();
return;
}
if (KVMGlobalConfig.CHECK_HOST_CPU_MODEL_NAME.value(Boolean.class) && !checkCpuModelOfHost()) {
trigger.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
trigger.next();
}
});
}
flow(new NoRollbackFlow() {
String __name__ = "prepare-host-env";
@Override
public void run(FlowTrigger trigger, Map data) {
String script = "which iptables > /dev/null && iptables -C FORWARD -j REJECT --reject-with icmp-host-prohibited > /dev/null 2>&1 && iptables -D FORWARD -j REJECT --reject-with icmp-host-prohibited > /dev/null 2>&1 || true";
runShell(script);
trigger.next();
}
});
error(new FlowErrorHandler(complete) {
@Override
public void handle(ErrorCode errCode, Map data) {
complete.fail(errCode);
}
});
done(new FlowDoneHandler(complete) {
@Override
public void handle(Map data) {
continueConnect(info, complete);
}
});
}
}).start();
}
}
private void handle(final ShutdownHostMsg msg) {
inQueue().name(String.format("shut-down-kvm-host-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> handleShutdownHost(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void handleShutdownHost(final ShutdownHostMsg msg, final NoErrorCompletion completion) {
ShutdownHostReply reply = new ShutdownHostReply();
KVMAgentCommands.ShutdownHostCmd cmd = new KVMAgentCommands.ShutdownHostCmd();
new Http<>(shutdownHost, cmd, ShutdownHostResponse.class).call(new ReturnValueCompletion<ShutdownHostResponse>(msg, completion) {
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
@Override
public void success(KVMAgentCommands.ShutdownHostResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
bus.reply(msg, reply);
completion.done();
} else {
changeConnectionState(HostStatusEvent.disconnected);
waitForHostShutdown(reply, completion);
}
}
private boolean testPort() {
if (CoreGlobalProperty.UNIT_TEST_ON) {
return false;
}
long ctimeout = TimeUnit.SECONDS.toMillis(KVMGlobalConfig.TEST_SSH_PORT_ON_CONNECT_TIMEOUT.value(Integer.class).longValue());
if (!NetworkUtils.isRemotePortOpen(getSelf().getManagementIp(), getSelf().getPort(), (int) ctimeout)) {
logger.debug(String.format("host[uuid:%s, name:%s, ip:%s]'s ssh port[%s] is no longer open, " +
"seem to be shutdowned", getSelf().getUuid(), getSelf().getName(), getSelf().getManagementIp(), getSelf().getPort()));
return false;
} else {
return true;
}
}
private void waitForHostShutdown(ShutdownHostReply reply, NoErrorCompletion noErrorCompletion) {
thdf.submitCancelablePeriodicTask(new CancelablePeriodicTask(msg, noErrorCompletion) {
@Override
public boolean run() {
if (testPort()) {
return false;
}
bus.reply(msg, reply);
noErrorCompletion.done();
return true;
}
@Override
public TimeUnit getTimeUnit() {
return TimeUnit.SECONDS;
}
@Override
public long getInterval() {
return 2;
}
@Override
public String getName() {
return "test-ssh-port-open-for-kvm-host";
}
});
}
});
}
private void handle(final CancelHostTaskMsg msg) {
CancelHostTaskReply reply = new CancelHostTaskReply();
cancelJob(msg.getCancellationApiId(), new Completion(msg) {
@Override
public void success() {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void cancelJob(String apiId, Completion completion) {
CancelCmd cmd = new CancelCmd();
cmd.setCancellationApiId(apiId);
new Http<>(cancelJob, cmd, CancelRsp.class).call(new ReturnValueCompletion<CancelRsp>(completion) {
@Override
public void success(CancelRsp ret) {
if (ret.isSuccess()) {
completion.success();
} else {
completion.fail(Platform.operr("%s", ret.getError()));
}
}
@Override
public void fail(ErrorCode errorCode) {
completion.fail(errorCode);
}
});
}
private boolean checkCpuModelOfHost() {
List<String> hostUuidsInCluster = Q.New(HostVO.class)
.select(HostVO_.uuid)
.eq(HostVO_.clusterUuid, self.getClusterUuid())
.notEq(HostVO_.uuid, self.getUuid())
.listValues();
if (hostUuidsInCluster.isEmpty()) {
return true;
}
Map<String, List<String>> cpuModelNames = KVMSystemTags.CPU_MODEL_NAME.getTags(hostUuidsInCluster);
if (cpuModelNames != null && cpuModelNames.size() != 0) {
String clusterCpuModelName = KVMSystemTags.CPU_MODEL_NAME.getTokenByTag(
cpuModelNames.values().iterator().next().get(0),
KVMSystemTags.CPU_MODEL_NAME_TOKEN
);
String hostCpuModelName = KVMSystemTags.CPU_MODEL_NAME.getTokenByResourceUuid(
self.getUuid(), KVMSystemTags.CPU_MODEL_NAME_TOKEN
);
if (clusterCpuModelName != null && !clusterCpuModelName.equals(hostCpuModelName)) {
return false;
}
}
return true;
}
@Override
protected void updateOsHook(UpdateHostOSMsg msg, Completion completion) {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("update-operating-system-for-host-%s", self.getUuid()));
chain.then(new ShareFlow() {
// is the host in maintenance already?
HostState oldState = self.getState();
boolean maintenance = oldState == HostState.Maintenance;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "double-check-host-state-status";
@Override
public void run(FlowTrigger trigger, Map data) {
if (self.getState() == HostState.PreMaintenance) {
trigger.fail(Platform.operr("host is in the premaintenance state, cannot update os"));
} else if (self.getStatus() != HostStatus.Connected) {
trigger.fail(Platform.operr("host is not in the connected status, cannot update os"));
} else {
trigger.next();
}
}
});
flow(new Flow() {
String __name__ = "make-host-in-maintenance";
@Override
public void run(FlowTrigger trigger, Map data) {
if (maintenance) {
trigger.next();
return;
}
// enter maintenance, but donot stop/migrate vm on the host
ChangeHostStateMsg cmsg = new ChangeHostStateMsg();
cmsg.setUuid(self.getUuid());
cmsg.setStateEvent(HostStateEvent.preMaintain.toString());
bus.makeTargetServiceIdByResourceUuid(cmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(cmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
trigger.next();
} else {
trigger.fail(reply.getError());
}
}
});
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (maintenance) {
trigger.rollback();
return;
}
// back to old host state
if (oldState == HostState.Disabled) {
changeState(HostStateEvent.disable);
} else {
changeState(HostStateEvent.enable);
}
trigger.rollback();
}
});
flow(new NoRollbackFlow() {
String __name__ = "update-host-os";
@Override
public void run(FlowTrigger trigger, Map data) {
UpdateHostOSCmd cmd = new UpdateHostOSCmd();
cmd.hostUuid = self.getUuid();
cmd.excludePackages = msg.getExcludePackages();
cmd.updatePackages = msg.getUpdatePackages();
cmd.releaseVersion = msg.getReleaseVersion();
cmd.enableExpRepo = msg.isEnableExperimentalRepo();
new Http<>(updateHostOSPath, cmd, UpdateHostOSRsp.class)
.call(new ReturnValueCompletion<UpdateHostOSRsp>(trigger) {
@Override
public void success(UpdateHostOSRsp ret) {
if (ret.isSuccess()) {
trigger.next();
} else {
trigger.fail(Platform.operr("%s", ret.getError()));
}
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "recover-host-state";
@Override
public void run(FlowTrigger trigger, Map data) {
if (maintenance) {
trigger.next();
return;
}
// back to old host state
if (oldState == HostState.Disabled) {
changeState(HostStateEvent.disable);
} else {
changeState(HostStateEvent.enable);
}
trigger.next();
}
});
flow(new NoRollbackFlow() {
String __name__ = "auto-reconnect-host";
@Override
public void run(FlowTrigger trigger, Map data) {
ReconnectHostMsg rmsg = new ReconnectHostMsg();
rmsg.setHostUuid(self.getUuid());
bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(rmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
logger.info("successfully reconnected host " + self.getUuid());
} else {
logger.error("failed to reconnect host " + self.getUuid());
}
trigger.next();
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
logger.debug(String.format("successfully updated operating system for host[uuid:%s]", self.getUuid()));
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
logger.warn(String.format("failed to updated operating system for host[uuid:%s] because %s",
self.getUuid(), errCode.getDetails()));
completion.fail(errCode);
}
});
}
}).start();
}
private boolean checkMigrateNetworkCidrOfHost(String cidr) {
if (NetworkUtils.isIpv4InCidr(self.getManagementIp(), cidr)) {
return true;
}
final String extraIps = HostSystemTags.EXTRA_IPS.getTokenByResourceUuid(
self.getUuid(), HostSystemTags.EXTRA_IPS_TOKEN);
if (extraIps == null) {
logger.error(String.format("Host[uuid:%s] has no IPs in migrate network", self.getUuid()));
return false;
}
final String[] ips = extraIps.split(",");
for (String ip: ips) {
if (NetworkUtils.isIpv4InCidr(ip, cidr)) {
return true;
}
}
return false;
}
private boolean checkQemuLibvirtVersionOfHost() {
List<String> hostUuidsInCluster = Q.New(HostVO.class)
.select(HostVO_.uuid)
.eq(HostVO_.clusterUuid, self.getClusterUuid())
.notEq(HostVO_.uuid, self.getUuid())
.listValues();
if (hostUuidsInCluster.isEmpty()) {
return true;
}
Map<String, List<String>> qemuVersions = KVMSystemTags.QEMU_IMG_VERSION.getTags(hostUuidsInCluster);
if (qemuVersions != null && qemuVersions.size() != 0) {
String clusterQemuVer = KVMSystemTags.QEMU_IMG_VERSION.getTokenByTag(
qemuVersions.values().iterator().next().get(0),
KVMSystemTags.QEMU_IMG_VERSION_TOKEN
);
String hostQemuVer = KVMSystemTags.QEMU_IMG_VERSION.getTokenByResourceUuid(
self.getUuid(), KVMSystemTags.QEMU_IMG_VERSION_TOKEN
);
if (clusterQemuVer != null && !clusterQemuVer.equals(hostQemuVer)) {
return false;
}
}
Map<String, List<String>> libvirtVersions = KVMSystemTags.LIBVIRT_VERSION.getTags(hostUuidsInCluster);
if (libvirtVersions != null && libvirtVersions.size() != 0) {
String clusterLibvirtVer = KVMSystemTags.LIBVIRT_VERSION.getTokenByTag(
libvirtVersions.values().iterator().next().get(0),
KVMSystemTags.LIBVIRT_VERSION_TOKEN
);
String hostLibvirtVer = KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(
self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN
);
if (clusterLibvirtVer != null && !clusterLibvirtVer.equals(hostLibvirtVer)) {
return false;
}
}
return true;
}
@Override
protected int getHostSyncLevel() {
return KVMGlobalConfig.HOST_SYNC_LEVEL.value(Integer.class);
}
@Override
protected HostVO updateHost(APIUpdateHostMsg msg) {
if (!(msg instanceof APIUpdateKVMHostMsg)) {
return super.updateHost(msg);
}
KVMHostVO vo = (KVMHostVO) super.updateHost(msg);
vo = vo == null ? getSelf() : vo;
APIUpdateKVMHostMsg umsg = (APIUpdateKVMHostMsg) msg;
if (umsg.getUsername() != null) {
vo.setUsername(umsg.getUsername());
}
if (umsg.getPassword() != null) {
vo.setPassword(umsg.getPassword());
}
if (umsg.getSshPort() != null && umsg.getSshPort() > 0 && umsg.getSshPort() <= 65535) {
vo.setPort(umsg.getSshPort());
}
return vo;
}
@Override
protected void scanVmPorts(ScanVmPortMsg msg) {
ScanVmPortReply reply = new ScanVmPortReply();
reply.setSupportScan(true);
checkStatus();
ScanVmPortCmd cmd = new ScanVmPortCmd();
cmd.setIp(msg.getIp());
cmd.setBrname(msg.getBrName());
cmd.setPort(msg.getPort());
new Http<>(scanVmPortPath, cmd, ScanVmPortResponse.class).call(new ReturnValueCompletion<ScanVmPortResponse>(msg) {
@Override
public void success(ScanVmPortResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
reply.setStatus(ret.getPortStatus());
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
}
|
package io.reporters;
import core.Path;
import core.Protocol;
import core.topology.ConnectedNode;
import core.topology.Link;
import core.topology.Network;
import core.topology.Topology;
import main.ExecutionStateTracker;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import simulators.Detection;
import simulators.Simulator;
import simulators.basic.BasicDataset;
import simulators.gradualdeployment.GradualDeploymentDataset;
import simulators.timeddeployment.TimedDeploymentDataset;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
/**
* Generates reports in CSV format.
*/
public class CSVReporter implements Reporter {
private static final char DELIMITER = ';';
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Set of headers
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
private static final String[] BASIC_COUNTS_HEADERS = {
"Seed", "Time", "Total Message Count", "Detecting Nodes Count",
"Cut-Off Links Count", "False Positive Count"
};
private static final String[] TIMED_DEPLOYMENT_COUNTS_HEADERS = { "Messages After Deployment Count" };
private static final String[] GRADUAL_DEPLOYMENT_COUNTS_HEADERS = { "Deployed Nodes Count" };
private static final String[] DETECTIONS_HEADERS = { "Simulation", "Detections", "Detecting Nodes",
"Cut-Off Links", "Cycles", "Initial Attribute", "False Positive" };
private static final String[] DEPLOYMENTS_HEADERS = { "Simulation", "Deployed Nodes" };
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Private fields
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
private final File baseOutputFile; // path with the base file name for the output
private final ExecutionStateTracker stateTracker;
private boolean countsHeadersWereAlreadyPrinted = false;
private boolean detectionsHeadersWereAlreadyPrinted = false;
private boolean deploymentsHeadersWereAlreadyPrinted = false;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Constructors
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Constructs a reporter associating the output file. Takes a simulation tracker used by the reporter when
* reporting information relative to some simulation instance.
*
* @param baseOutputFile file to output report to.
*/
public CSVReporter(File baseOutputFile, ExecutionStateTracker stateTracker) throws IOException {
this.baseOutputFile = baseOutputFile;
this.stateTracker = stateTracker;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Public interface - Write methods from the Reporter Interface
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Writes the simulation time, total message count, number of detection nodes, and number of cut-off links to
* the counts csv file and fills the detections file with the detections relative to this simulation.
*
* @param dataSet basic data set containing the data to write in the report.
* @throws IOException if it fails to write to the report resource.
*/
@Override
public void writeData(BasicDataset dataSet) throws IOException {
try (CSVPrinter printer = getCountsFilePrinter()) {
if (!countsHeadersWereAlreadyPrinted) {
printer.printRecord((Object[]) BASIC_COUNTS_HEADERS);
countsHeadersWereAlreadyPrinted = true;
}
printCounts(printer, dataSet);
printer.println();
}
writeDetections(dataSet);
}
/**
* The difference from the version with a basic data is set is that: Adds the number of messages after
* deployment to the counts file.
*
* @param basicDataset basic data set containing the data to write in the report.
* @param timedDeploymentDataset timed deployment data set containing the data to write in the report.
* @throws IOException if it fails to write to the report resource.
*/
@Override
public void writeData(BasicDataset basicDataset, TimedDeploymentDataset timedDeploymentDataset)
throws IOException {
try (CSVPrinter printer = getCountsFilePrinter()) {
if (!countsHeadersWereAlreadyPrinted) {
printHeaders(printer, BASIC_COUNTS_HEADERS, TIMED_DEPLOYMENT_COUNTS_HEADERS);
countsHeadersWereAlreadyPrinted = true;
}
printCounts(printer, basicDataset);
printer.print(timedDeploymentDataset.getMessageCountAfterDeployment());
printer.println();
}
writeDetections(basicDataset);
}
/**
* Writes the data in a gradual deployment dataset to the report. Called by the gradual deployment
* dataset report method.
*
* @param basicDataset basic data set containing the data to write in the report.
* @param gradualDeploymentDataset gradual deployment data set containing the data to write in the report.
* @throws IOException if it fails to write to the report resource.
*/
@Override
public void writeData(BasicDataset basicDataset, GradualDeploymentDataset gradualDeploymentDataset)
throws IOException {
try (CSVPrinter printer = getCountsFilePrinter()) {
if (!countsHeadersWereAlreadyPrinted) {
printHeaders(printer, BASIC_COUNTS_HEADERS, GRADUAL_DEPLOYMENT_COUNTS_HEADERS);
countsHeadersWereAlreadyPrinted = true;
}
printCounts(printer, basicDataset);
printer.print(gradualDeploymentDataset.getDeployingNodesCount());
printer.println();
}
writeDetections(basicDataset);
// write the deploying nodes
try (CSVPrinter printer = getDeploymentsFilePrinter()) {
if (!deploymentsHeadersWereAlreadyPrinted) {
printHeaders(printer, DEPLOYMENTS_HEADERS);
deploymentsHeadersWereAlreadyPrinted = true;
}
printer.print(currentSimulationNumber());
for (ConnectedNode node : gradualDeploymentDataset.getDeployingNodes()) {
printer.print(node);
}
printer.println();
}
}
/**
* Writes a summary of the simulation before it starts. Writes basic information about the topology and the
* simulation parameters.
*
* @param topology original topology.
* @param destinationId ID of the destination.
* @param minDelay minimum delay for an exported message.
* @param maxDelay maximum delay for an exported message.
* @param protocol protocol being analysed.
* @param simulator simulator used for the simulation.
*/
@Override
public void writeBeforeSummary(Topology topology, int destinationId, int minDelay, int maxDelay, Protocol protocol,
Simulator simulator) throws IOException {
Network network = topology.getNetwork();
try (CSVPrinter csvPrinter = getBeforeSummaryFilePrinter()) {
csvPrinter.printRecord("Policy", topology.getPolicy());
csvPrinter.printRecord("ConnectedNode Count", network.getNodeCount());
csvPrinter.printRecord("Link Count", network.getLinkCount());
csvPrinter.printRecord("Destination", destinationId);
csvPrinter.printRecord("Message Delay", minDelay, maxDelay);
csvPrinter.printRecord("Protocol", protocol);
csvPrinter.printRecord("Simulation Type", simulator);
}
}
/**
* Writes a summary of the simulation after it finishes. Writes basic information abouts the total results of
* the simulation.
*/
@Override
public void writeAfterSummary() throws IOException {
// be careful to avoid division by zero
float detectionAvg = stateTracker.getDetectionCount() != 0 ?
(float) stateTracker.getDetectionCount() / (float) stateTracker.getSimulationCount() : 0;
try (CSVPrinter csvPrinter = getAfterSummaryFilePrinter()) {
csvPrinter.printRecord("Simulation Count", stateTracker.getSimulationCount());
csvPrinter.printRecord("Avg. Detection Count", String.format("%.2f", detectionAvg));
}
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Private Print methods that can be concatenated. This is true because they do not print a
* new line after printing a new column of data.
*
* There is also write methods in the cases where concatenation is not necessary. Write
* methods print a new line after each record.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
private void printCounts(CSVPrinter printer, BasicDataset dataSet) throws IOException {
printer.print(dataSet.getSimulationSeed());
printer.print(dataSet.getSimulationTime());
printer.print(dataSet.getTotalMessageCount());
printer.print(dataSet.getDetectingNodesCount());
printer.print(dataSet.getCutOffLinksCount());
printer.print(dataSet.getFalsePositiveCount());
}
private void writeDetections(BasicDataset dataSet) throws IOException {
try (CSVPrinter printer = getDetectionsFilePrinter()) {
if (!detectionsHeadersWereAlreadyPrinted) {
printHeaders(printer, DETECTIONS_HEADERS);
detectionsHeadersWereAlreadyPrinted = true;
}
int detectionNumber = 1;
for (Detection detection : dataSet.getDetections()) {
printer.printRecord(
currentSimulationNumber(),
detectionNumber++,
pretty(detection.getDetectingNode()),
pretty(detection.getCutOffLink()),
pretty(detection.getCycle()),
detection.getInitialAttribute(),
detection.isFalsePositive() ? "Yes" : "No"
);
}
}
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Private Helper Methods to get a CSV printer for each type of output file
*
* They all return a file printer for the respective file type
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
private CSVPrinter getBeforeSummaryFilePrinter() throws IOException {
return getFilePrinter(getFile("beforesummary"), false);
}
private CSVPrinter getAfterSummaryFilePrinter() throws IOException {
return getFilePrinter(getFile("aftersummary"), false);
}
private CSVPrinter getCountsFilePrinter() throws IOException {
return getFilePrinter(getFile("counts"), true);
}
private CSVPrinter getDetectionsFilePrinter() throws IOException {
return getFilePrinter(getFile("detections"), true);
}
private CSVPrinter getDeploymentsFilePrinter() throws IOException {
return getFilePrinter(getFile("deployments"), true);
}
/**
* Base method to get a CSV printer for any file. All other "get printer" methods call this base method.
*
* @param file file to associate with the printer.
* @param append true to open the file in append mode and false to truncate the file.
* @return a new instance of a CSV printer associated with the given file.
* @throws IOException if fails to open the file.
*/
private static CSVPrinter getFilePrinter(File file, boolean append) throws IOException {
return new CSVPrinter(new FileWriter(file, append), CSVFormat.EXCEL.withDelimiter(DELIMITER));
}
/**
* Appends the given tag to the end of the base output filename and returns the result file. Keeps original file
* extension.
*
* @param tag tag to add to the base output file.
* @return file with the class name associated to its name.
*/
private File getFile(String tag) {
String extension = FilenameUtils.getExtension(baseOutputFile.getName());
// append the tag to the original file name (keep the extension)
String filename = FilenameUtils.getBaseName(baseOutputFile.getName()) + String.format("-%s.%s", tag, extension);
return new File(baseOutputFile.getParent(), filename);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Set of helper methods to display any element like Nodes, Links, Paths, etc in a prettier
* format then its standard toString() result.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
private static String pretty(ConnectedNode node) {
return String.valueOf(node.getId());
}
private static String pretty(Link link) {
return link.getSource().getId() + " → " + link.getDestination().getId();
}
private static String pretty(Path path) {
List<Integer> pathNodesIds = path.stream()
.map(ConnectedNode::getId)
.collect(Collectors.toList());
return StringUtils.join(pathNodesIds.iterator(), " → ");
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Private Helper Methods
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Returns the current simulation number based on the current simulation stateTracker.
*
* @return the current simulation number.
*/
private int currentSimulationNumber() {
return stateTracker.getSimulationCount();
}
/**
* Prints multiple groups of headers.
*
* @param printer printer used to print.
* @param headerGroups groups of headers to print.
* @throws IOException
*/
private void printHeaders(CSVPrinter printer, String[]... headerGroups) throws IOException {
for (String[] headers : headerGroups) {
for (String header : headers) {
printer.print(header);
}
}
printer.println();
}
}
|
// This file is distributed in the hope that it will be useful,
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
package propsandcovariants;
import acq.AcquisitionEvent;
import coordinates.AffineUtils;
import coordinates.XYStagePosition;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.util.Arrays;
import java.util.List;
import misc.Log;
import surfacesandregions.SingleResolutionInterpolation;
import surfacesandregions.SurfaceInterpolator;
/**
* Category about interpolated surface (e.g. distance below surface) to be used in
* covaried settings
*/
public class SurfaceData implements Covariant {
//all data must start with this prefix so they can be reconstructed when read from a text file on disk
public static String PREFIX = "Surface data: ";
//number of test points per dimension for finding minimum distance to surface
private static final int NUM_XY_TEST_POINTS = 9;
//number of test points per dimension for finding minimum distance to surface within angle
// private static final int NUM_XY_TEST_POINTS_ANGLE = 5;
public static String SPACER = "
public static String DISTANCE_BELOW_SURFACE_CENTER = "Vertical distance below at XY position center";
public static String DISTANCE_BELOW_SURFACE_MINIMUM = "Minimum vertical distance below at XY position";
public static String DISTANCE_BELOW_SURFACE_MAXIMUM = "Maximum vertical distance below at XY position";
public static String LN_OPTIMAL_DISTANCE_MT = "Lymph Node optimal distance Maitai";
public static String LN_OPTIMAL_DISTANCE_CHAM = "Lymph Node optimal distance Chameleon";
private String category_;
private SurfaceInterpolator surface_;
public SurfaceData(SurfaceInterpolator surface, String type) throws Exception {
category_ = type;
surface_ = surface;
if (!Arrays.asList(enumerateDataTypes()).contains(type)) {
//not a recognized type
throw new Exception();
}
}
public SurfaceInterpolator getSurface() {
return surface_;
}
public static String[] enumerateDataTypes() {
return new String[] {DISTANCE_BELOW_SURFACE_CENTER, DISTANCE_BELOW_SURFACE_MINIMUM,
DISTANCE_BELOW_SURFACE_MAXIMUM, LN_OPTIMAL_DISTANCE_MT, LN_OPTIMAL_DISTANCE_CHAM};
}
@Override
public String toString() {
return getName();
}
@Override
public String getAbbreviatedName() {
if (category_.equals(DISTANCE_BELOW_SURFACE_CENTER)) {
return "Vertical distance to " + surface_.getName();
} else if (category_.equals(DISTANCE_BELOW_SURFACE_MINIMUM)) {
return "Min vertical distance to " + surface_.getName();
} else if (category_.equals(DISTANCE_BELOW_SURFACE_MAXIMUM)) {
return "Min distance to " + surface_.getName();
} else if (category_.equals(LN_OPTIMAL_DISTANCE_MT)) {
return "Maitai Lymph node optimal distance for " + surface_.getName();
} else if (category_.equals(LN_OPTIMAL_DISTANCE_CHAM)) {
return "Chameleon Lymph node optimal distance for " + surface_.getName();
} else {
Log.log("Unknown Surface data type");
throw new RuntimeException();
}
}
@Override
public String getName() {
return PREFIX + surface_.getName() + SPACER + category_;
}
@Override
public boolean isValid(CovariantValue potentialValue) {
return potentialValue.getType() == CovariantType.DOUBLE;
}
@Override
public CovariantValue[] getAllowedValues() {
//not applicable because all numerical for now
return null;
}
@Override
public boolean isDiscrete() {
return false;
}
@Override
public boolean hasLimits() {
return false;
}
@Override
public CovariantValue getLowerLimit() {
return null;
}
@Override
public CovariantValue getUpperLimit() {
return null;
}
@Override
public CovariantType getType() {
return CovariantType.DOUBLE;
}
@Override
public CovariantValue getValidValue(List<CovariantValue> vals) {
double d = 0;
while (true) {
if (!vals.contains(new CovariantValue(d))) {
return new CovariantValue(d);
}
d++;
}
}
// private double lnOptimalDistanceOld(XYStagePosition xyPos, double zPosition) throws InterruptedException {
// // a special measure for curved surfaces, which gives:
// //-min distance at surface on flatter parts of curved surface (ie top)
// //-increased distance up to max distance as you go deeper
// //-higher distance at surface on side to account for curved surface blocking out some of exciation light
// //{minDistance,maxDistance, minNormalAngle, maxNormalAngle)
// double[] vals = distanceAndNormalCalc(xyPos.getFullTileCorners(), zPosition);
// double extraDistance = 0; //pretend actually deeper in LN than we are to account for blockage by curved surface
// double angleCutoff = 64; //angle cutoff is maximum nalge colletred by 1.2 NA objective
// double doublingDistance = 50;
// double angleCutoffPercent = 0;
// //twice as much power if angle goes to 0
// //doubling distance ~40-70 um when b = 0.01-0.018 i exponent
// //add extra distance to account for blockage by LN surface
// //never want to make extra distance higher than the double distance,
// //so extra power is capped at 2x
// angleCutoffPercent = Math.min(angleCutoff, vals[3]) / angleCutoff;
// extraDistance = angleCutoffPercent * doublingDistance;
// double curvatureCorrectedMin = vals[0] + extraDistance;
// double ret = Math.min(vals[1], Math.max(curvatureCorrectedMin, Math.pow(vals[0], 1.2)));
// return ret;
private double lnOptimalDistance(XYStagePosition xyPos, double zPosition, boolean maitai) throws InterruptedException {
double[] vals = distanceAndNormalCalc(xyPos.getFullTileCorners(), zPosition);
//use mindistance and max normal so as to not explode LN
double minDist = vals[0];
double maxNormal = vals[3];
//look up
int minDistIndex = (int) Math.max(0, Math.min(33, minDist / 9));
int normalIndex = (int) Math.max(0, Math.min(15, maxNormal / 5));
return maitai ? LN_DISTANCES_MT[normalIndex][minDistIndex] : LN_DISTANCES_CHAM[normalIndex][minDistIndex];
}
/**
*
* @param corners
* @param min true to get min, false to get max
* @return {minDistance,maxDistance, minNormalAngle, maxNormalAngle)
*/
private double[] distanceAndNormalCalc(Point2D.Double[] corners, double zVal) throws InterruptedException {
//check a grid of points spanning entire position
//square is aligned with axes in pixel space, so convert to pixel space to generate test points
double xSpan = corners[2].getX() - corners[0].getX();
double ySpan = corners[2].getY() - corners[0].getY();
Point2D.Double pixelSpan = new Point2D.Double();
AffineTransform transform = AffineUtils.getAffineTransform(surface_.getCurrentPixelSizeConfig(),0, 0);
try {
transform.inverseTransform(new Point2D.Double(xSpan, ySpan), pixelSpan);
} catch (NoninvertibleTransformException ex) {
Log.log("Problem inverting affine transform");
}
double minDistance = Integer.MAX_VALUE;
double maxDistance = 0;
double minNormalAngle = 90;
double maxNormalAngle = 0;
for (double x = 0; x <= pixelSpan.x; x += pixelSpan.x / (double) NUM_XY_TEST_POINTS) {
for (double y = 0; y <= pixelSpan.y; y += pixelSpan.y / (double) NUM_XY_TEST_POINTS) {
//convert these abritray pixel coordinates back to stage coordinates
double[] transformMaxtrix = new double[6];
transform.getMatrix(transformMaxtrix);
transformMaxtrix[4] = corners[0].getX();
transformMaxtrix[5] = corners[0].getY();
//create new transform with translation applied
transform = new AffineTransform(transformMaxtrix);
Point2D.Double stageCoords = new Point2D.Double();
transform.transform(new Point2D.Double(x, y), stageCoords);
//test point for inclusion of position
if (!surface_.waitForCurentInterpolation().isInterpDefined(stageCoords.x, stageCoords.y)) {
//if position is outside of convex hull, assume min distance is 0
minDistance = 0;
//get extrapolated value for max distance
float interpVal = surface_.waitForCurentInterpolation().getExtrapolatedValue(stageCoords.x, stageCoords.y);
maxDistance = Math.max(zVal - interpVal, maxDistance);
//only take actual values for normals
} else {
float interpVal = surface_.waitForCurentInterpolation().getInterpolatedValue(stageCoords.x, stageCoords.y);
float normalAngle = surface_.waitForCurentInterpolation().getNormalAngleToVertical(stageCoords.x, stageCoords.y);
minDistance = Math.min(Math.max(0,zVal - interpVal), minDistance);
maxDistance = Math.max(zVal - interpVal, maxDistance);
minNormalAngle = Math.min(minNormalAngle, normalAngle);
maxNormalAngle = Math.max(maxNormalAngle, normalAngle);
}
}
}
return new double[]{minDistance, maxDistance, minNormalAngle, maxNormalAngle};
}
@Override
public CovariantValue getCurrentValue(AcquisitionEvent event) throws Exception {
XYStagePosition xyPos = event.xyPosition_;
if (category_.equals(DISTANCE_BELOW_SURFACE_CENTER)) {
//if interpolation is undefined at position center, assume distance below is 0
Point2D.Double center = xyPos.getCenter();
SingleResolutionInterpolation interp = surface_.waitForCurentInterpolation();
if (interp.isInterpDefined(center.x, center.y)) {
return new CovariantValue( event.zPosition_ - interp.getInterpolatedValue(center.x, center.y));
}
return new CovariantValue(0.0);
} else if (category_.equals(DISTANCE_BELOW_SURFACE_MINIMUM)) {
return new CovariantValue(distanceAndNormalCalc(xyPos.getFullTileCorners(), event.zPosition_)[0]);
} else if (category_.equals(DISTANCE_BELOW_SURFACE_MAXIMUM)) {
return new CovariantValue(distanceAndNormalCalc(xyPos.getFullTileCorners(), event.zPosition_)[1]);
} else if (category_.equals(LN_OPTIMAL_DISTANCE_MT)) {
return new CovariantValue(lnOptimalDistance(xyPos, event.zPosition_, true));
} else if (category_.equals(LN_OPTIMAL_DISTANCE_CHAM)) {
return new CovariantValue(lnOptimalDistance(xyPos, event.zPosition_, false));
} else {
Log.log("Unknown Surface data type",true);
throw new RuntimeException();
}
}
@Override
public void updateHardwareToValue(CovariantValue dVal) {
Log.log("No hardware associated with Surface data",true);
throw new RuntimeException();
}
public static void main (String[] args) {
System.out.println();
}
private static final double[][] LN_DISTANCES_CHAM = new double[][]
{{-0.000000,9.146382,18.234974,27.266530,36.241822,45.161643,54.026803,62.838128,71.596457,80.302642,88.957547,97.562041,106.117005,114.623321,123.081877,131.493564,139.859272,148.179891,156.456312,164.689418,172.880093,181.029210,189.137641,197.206247,205.235882,213.227391,221.181608,229.099357,236.981452,244.828692,252.641867,260.421753,268.169112,275.884693},
{-0.000000,9.207467,18.345123,27.414656,36.417732,45.355985,54.231023,63.044424,71.797734,80.492472,89.130121,97.712136,106.239938,114.714918,123.138433,131.511808,139.836339,148.113288,156.343885,164.529331,172.670797,180.769420,188.826311,196.842550,204.819188,212.757250,220.657730,228.521597,236.349792,244.143232,251.902806,259.629380,267.323796,274.986870},
{-0.000000,9.404749,18.697773,27.884768,36.971114,45.961890,54.861878,63.675580,72.407225,81.060787,89.639993,98.148342,106.589117,114.965395,123.280061,131.535825,139.735228,147.880654,155.974344,164.018404,172.014814,179.965436,187.872025,195.736234,203.559625,211.343670,219.089761,226.799214,234.473277,242.113132,249.719899,257.294643,264.838376,272.352061},
{-0.000000,9.790376,19.372345,28.764980,37.985429,47.049067,55.969646,64.759452,73.429452,81.989434,90.448132,98.813350,107.092063,115.290516,123.414306,131.468463,139.457512,147.385532,155.256211,163.072891,170.838604,178.556110,186.227929,193.856365,201.443529,208.991363,216.501656,223.976059,231.416102,238.823202,246.198678,253.543758,260.859590,268.147246},
{-0.000000,10.503015,20.558682,30.241821,39.612650,48.719599,57.601695,66.290509,74.811717,83.186329,91.431665,99.562106,107.589684,115.524548,123.375321,131.149387,138.853111,146.492019,154.070944,161.594130,169.065334,176.487896,183.864799,191.198724,198.492087,205.747076,212.965681,220.149717,227.300848,234.420598,241.510374,248.571475,255.605104,262.612378},
{-0.000000,11.984941,22.690768,32.601064,41.972711,50.953196,59.633933,68.075522,76.320435,84.399784,92.337186,100.151080,107.856197,115.464528,122.985995,130.428928,137.800379,145.106403,152.352235,159.542440,166.681024,173.771531,180.817108,187.820571,194.784446,201.711014,208.602338,215.460298,222.286607,229.082832,235.850414,242.590681,249.304857,255.994076},
{1.294231,16.288229,27.001753,36.651080,45.691522,54.313270,62.621654,70.683381,78.544162,86.237027,93.786831,101.212836,108.530337,115.751726,122.887204,129.945299,136.933220,143.857122,150.722316,157.533419,164.294474,171.009048,177.680301,184.311054,190.903833,197.460914,203.984353,210.476015,216.937602,223.370665,229.776630,236.156803,242.512391,248.844490},
{5.012817,21.692950,32.820143,42.418489,51.202039,59.468169,67.371629,75.003599,82.422502,89.668292,96.769459,103.747362,110.618426,117.395618,124.089442,130.708555,137.260194,143.750494,150.184715,156.567405,162.902534,169.193591,175.443663,181.655497,187.831550,193.974029,200.084928,206.166052,212.219046,218.245407,224.246509,230.223612,236.177876,242.110371},
{9.157103,26.104313,37.458632,47.144951,55.894159,64.028282,71.724340,79.091655,86.202846,93.108671,99.845988,106.442368,112.918944,119.292262,125.575493,131.779285,137.912395,143.982083,149.994474,155.954716,161.867555,167.735986,173.564187,179.354811,185.110454,190.833415,196.525758,202.189320,207.825787,213.436656,219.023309,224.587002,230.128887,235.650024},
{13.510033,29.910306,41.100297,50.679720,59.323709,67.334129,74.880367,82.069623,88.974957,95.648967,102.130694,108.450203,114.631060,120.692103,126.648622,132.513183,138.296233,144.006543,149.651542,155.237568,160.770067,166.253752,171.692723,177.090570,182.450446,187.775141,193.067132,198.328626,203.561601,208.767833,213.948925,219.106329,224.241361,229.355225},
{17.956378,33.312456,44.001962,53.225301,61.582666,69.342758,76.657019,83.621813,90.303545,96.750424,102.998863,109.077211,115.008050,120.809706,126.497323,132.083543,137.579054,142.992955,148.333095,153.606264,158.818362,163.974588,169.079522,174.137201,179.151243,184.124842,189.060894,193.961984,198.830448,203.668385,208.477718,213.260184,218.017372,222.750731},
{22.445367,36.454511,46.386762,55.027609,62.900258,70.238595,77.174247,83.791019,90.078298,96.282991,102.231979,108.018404,113.662160,119.179505,124.584093,129.886810,135.097855,140.225332,145.276543,150.257767,155.174617,160.032027,164.834399,169.585668,174.289376,178.948711,183.566575,188.145594,192.688162,197.196470,201.672522,206.118159,210.535074,214.924830},
{26.964997,39.440850,48.427195,56.301506,63.512406,70.260494,76.658522,82.778176,88.668743,94.366008,99.897061,105.283018,110.540815,115.684242,120.724793,125.672143,130.534514,135.319069,140.032007,144.678626,149.263826,153.791889,158.266626,162.691455,167.069474,171.403498,175.696085,179.949573,184.166110,188.347664,192.496055,196.612966,200.699954,204.758462},
{31.526919,42.345342,50.245140,57.207783,63.610228,69.621362,75.336208,80.815169,86.099763,91.220115,96.198980,101.054094,105.799641,110.447179,115.006295,119.485059,123.890341,128.228052,132.503388,136.720796,140.884276,144.997365,149.063225,153.084695,157.064341,161.004491,164.907265,168.774604,172.608281,176.409929,180.181071,183.923094,187.637302,191.324912},
{36.158279,45.219329,51.918043,57.849844,63.321680,68.471592,73.377494,78.089000,82.640253,87.056054,91.355151,95.552127,99.658661,103.684271,107.636863,111.523074,115.348572,119.118119,122.836025,126.505953,130.131182,133.714608,137.258674,140.765845,144.238151,147.677547,151.085636,154.464090,157.814314,161.137640,164.435273,167.708348,170.957906,174.184878},
{40.897855,48.095654,53.482716,58.272749,62.702423,66.878934,70.863017,74.693513,78.397195,81.993603,85.497472,88.920350,92.271479,95.558382,98.787347,101.963537,105.091537,108.175171,111.217792,114.222274,117.191374,120.127223,123.031926,125.907324,128.755076,131.576685,134.373231,137.146822,139.897740,142.627322,145.336550,148.026284,150.697362,153.350573}};
private static final double[][] LN_DISTANCES_MT = new double[][]
{{-0.000000,9.124383,18.148035,27.073360,35.902862,44.639129,53.284815,61.842622,70.315290,78.705573,87.016233,95.250020,103.409667,111.497873,119.517297,127.470547,135.360178,143.188678,150.958470,158.671906,166.331262,173.938737,181.496454,189.006456,196.470706,203.891090,211.269417,218.607418,225.906750,233.168997,240.395672,247.588220,254.748020,261.876386},
{-0.000000,9.180868,18.241086,27.185799,36.019997,44.748506,53.375988,61.906929,70.345643,78.696269,86.962773,95.148950,103.258426,111.294664,119.260969,127.160489,134.996224,142.771030,150.487624,158.148590,165.756386,173.313349,180.821698,188.283542,195.700884,203.075629,210.409585,217.704468,224.961910,232.183461,239.370593,246.524704,253.647124,260.739115},
{-0.000000,9.362086,18.535053,27.535455,36.378216,45.076736,53.643016,62.087784,70.420625,78.650102,86.783872,94.828790,102.791006,110.676047,118.488894,126.234050,133.915594,141.537234,149.102351,156.614034,164.075120,171.488214,178.855723,186.179868,193.462713,200.706173,207.912033,215.081959,222.217510,229.320147,236.391242,243.432083,250.443886,257.427797},
{-0.000000,9.710525,19.079390,28.159067,36.992784,45.615983,54.057675,62.341638,70.487418,78.511155,86.426260,94.243944,101.973649,109.623388,117.200010,124.709414,132.156720,139.546403,146.882400,154.168197,161.406904,168.601305,175.753909,182.866990,189.942613,196.982645,203.988888,210.962865,217.906074,224.819877,231.705542,238.564251,245.397106,252.205138},
{-0.000000,10.330476,19.971375,29.105943,37.859353,46.317975,54.542488,62.576469,70.451969,78.193123,85.818525,93.342798,100.777664,108.132680,115.415754,122.633520,129.791606,136.894843,143.947410,150.952958,157.914700,164.835481,171.717839,178.564047,185.376155,192.155993,198.905328,205.625621,212.318311,218.984698,225.625978,232.243261,238.837574,245.409875},
{-0.000000,11.480989,21.323301,30.345825,38.866892,47.040947,54.956019,62.667979,70.214971,77.624441,84.916913,92.108222,99.210889,106.235012,113.188883,120.079407,126.912407,133.692848,140.425009,147.112603,153.758882,160.366685,166.938641,173.476933,179.983625,186.460552,192.909374,199.331600,205.728608,212.101658,218.451908,224.780425,231.088194,237.376128},
{0.735123,13.951579,23.528456,32.195357,40.338976,48.127854,55.655290,62.979645,70.140359,77.165594,84.076279,90.888468,97.614796,104.265414,110.848620,117.371302,123.839247,130.257375,136.629901,142.960507,149.252360,155.508274,161.730728,167.921931,174.083857,180.218280,186.326802,192.410874,198.471818,204.510839,210.529043,216.527445,222.506981,228.468516},
{2.847280,17.232953,26.737938,35.060609,42.782359,50.127008,57.205946,64.083795,70.802100,77.389608,83.867283,90.251021,96.553219,102.783806,108.950854,115.061048,121.119989,127.132428,133.102433,139.033520,144.928750,150.790808,156.622065,162.424622,168.200357,173.950954,179.677929,185.382652,191.066368,196.730213,202.375223,208.002347,213.612461,219.206370},
{5.201234,19.844046,29.420186,37.621411,45.097435,52.120422,58.832370,65.316678,71.626337,77.796989,83.853783,89.815113,95.694907,101.503952,107.250829,112.942497,118.584689,124.182208,129.739123,135.258922,140.744622,146.198857,151.623940,157.021922,162.394624,167.743679,173.070556,178.376574,183.662937,188.930739,194.180976,199.414563,204.632338,209.835074},
{7.673699,21.929842,31.397626,39.476758,46.784228,53.590388,60.042881,66.232682,72.219846,78.046172,83.741784,89.329077,94.825097,100.243091,105.593529,110.884824,116.123828,121.316195,126.466644,131.579154,136.657115,141.703440,146.720659,151.710962,156.676302,161.618387,166.538746,171.438745,176.319613,181.182459,186.028293,190.858030,195.672513,200.472508},
{10.199223,23.635981,32.755220,40.579795,47.660583,54.241690,60.459424,66.399663,72.120754,77.664452,83.061752,88.336336,93.506683,98.587514,103.590703,108.525961,113.401323,118.223481,122.998088,127.729934,132.423121,137.081177,141.707157,146.303722,150.873202,155.417652,159.938883,164.438510,168.917972,173.378555,177.821426,182.247628,186.658115,191.053744},
{12.748968,25.081836,33.630073,41.025947,47.748652,54.010393,59.929998,65.582763,71.020361,76.280218,81.390541,86.373205,91.245648,96.021964,100.713768,105.330665,109.881008,114.371527,118.808234,123.196259,127.540061,131.843540,136.110105,140.342789,144.544263,148.716905,152.862839,156.983967,161.082002,165.158486,169.214807,173.252229,177.271900,181.274870},
{15.316118,26.357575,34.151814,40.949689,47.161846,52.969703,58.474510,63.740347,68.811143,73.718705,78.487120,83.135095,87.677608,92.126918,96.493139,100.784797,105.009146,109.172419,113.280030,117.336703,121.346598,125.313392,129.240360,133.130429,136.986224,140.810114,144.604236,148.370534,152.110769,155.826566,159.519382,163.190574,166.841381,170.472949},
{17.907290,27.526392,34.421369,40.474591,46.031948,51.246267,56.202749,60.955157,65.540263,69.984641,74.308298,78.526859,82.652695,86.695946,90.665002,94.566923,98.407713,102.192553,105.925838,109.611805,113.253633,116.854518,120.417211,123.944207,127.437747,130.899845,134.332326,137.736997,141.115282,144.468662,147.798405,151.105747,154.391821,157.657660},
{20.537903,28.628679,34.504870,39.689398,44.465510,48.958813,53.239426,57.351636,61.325692,65.183478,68.941422,72.612307,76.206277,79.731555,83.195028,86.602430,89.958614,93.267794,96.533562,99.759084,102.947217,106.100381,109.220802,112.310473,115.371183,118.404555,121.412058,124.395051,127.354758,130.292280,133.208764,136.105091,138.982184,141.840879},
{23.229982,29.684556,34.430686,38.634626,42.516172,46.173967,49.663180,53.018800,56.264782,59.418430,62.492829,65.498080,68.442358,71.332136,74.172844,76.969011,79.724792,82.443161,85.127095,87.779137,90.401487,92.996104,95.564732,98.108937,100.630145,103.129560,105.608408,108.067034,110.508463,112.931517,115.337700,117.727757,120.102387,122.462244}};
}
|
package it.uniroma3.model;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.*;
@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Orders {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
//@Temporal(TemporalType.DATE)
//private Date creationTime;
//@Temporal(TemporalType.DATE)
//private Date evasionTime;
@ManyToOne
private Customer customer;
@OneToMany(cascade={CascadeType.PERSIST, CascadeType.REMOVE}, fetch=FetchType.EAGER)
@JoinColumn(name="orders_id")
private List<OrderLine> orderLines;
public Orders() {
this.orderLines = new LinkedList<OrderLine>();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getCreationTime() {
return creationTime;
}
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public List<OrderLine> getOrderLines() {
return orderLines;
}
public void setOrderLines(List<OrderLine> orderLines) {
this.orderLines = orderLines;
}
@Override
public String toString() {
return "Orders [id=" + id + ", creationTime=" + creationTime + ", customer=" + customer + "]";
}
public Date getEvasionTime() {
return evasionTime;
}
public void setEvasionTime(Date evasionTime) {
this.evasionTime = evasionTime;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((creationTime == null) ? 0 : creationTime.hashCode());
result = prime * result
+ ((customer == null) ? 0 : customer.hashCode());
result = prime * result
+ ((evasionTime == null) ? 0 : evasionTime.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result
+ ((orderLines == null) ? 0 : orderLines.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Orders other = (Orders) obj;
if (creationTime == null) {
if (other.creationTime != null)
return false;
} else if (!creationTime.equals(other.creationTime))
return false;
if (customer == null) {
if (other.customer != null)
return false;
} else if (!customer.equals(other.customer))
return false;
if (evasionTime == null) {
if (other.evasionTime != null)
return false;
} else if (!evasionTime.equals(other.evasionTime))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (orderLines == null) {
if (other.orderLines != null)
return false;
} else if (!orderLines.equals(other.orderLines))
return false;
return true;
}
}
|
package jade.core;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.List;
import jade.lang.acl.ACLMessage;
/**
@author Giovanni Rimassa - Universita` di Parma
@version $Date$ $Revision$
*/
interface AgentContainer extends Remote {
static final boolean NOSTART = false;
static final boolean START = true;
static final boolean TRANSFER_ABORT = false;
static final boolean TRANSFER_COMMIT = true;
static final int ADD_RT = 1;
static final int DEL_RT = 2;
void createAgent(AID agentID, String className,String arguments[], boolean startIt) throws RemoteException;
void createAgent(AID agentID, byte[] serializedInstance, AgentContainer classSite, boolean startIt) throws RemoteException;
byte[] fetchClassFile(String name) throws RemoteException, ClassNotFoundException;
void suspendAgent(AID agentID) throws RemoteException, NotFoundException;
void resumeAgent(AID agentID) throws RemoteException, NotFoundException;
void waitAgent(AID agentID) throws RemoteException, NotFoundException;
void wakeAgent(AID agentID) throws RemoteException, NotFoundException;
void moveAgent(AID agentID, Location where) throws RemoteException, NotFoundException;
void copyAgent(AID agentID, Location where, String newName) throws RemoteException, NotFoundException;
void killAgent(AID agentID) throws RemoteException, NotFoundException;
void exit() throws RemoteException;
void postTransferResult(AID agentID, boolean result, List messages) throws RemoteException, NotFoundException;
void dispatch(ACLMessage msg, AID receiverID) throws RemoteException, NotFoundException;
void ping(boolean hang) throws RemoteException;
String installMTP(String address, String className) throws RemoteException;
void uninstallMTP(String address) throws RemoteException, NotFoundException;
void updateRoutingTable(int op, String address, AgentContainer ac) throws RemoteException;
void route(Object env, byte[] payload, String address) throws RemoteException, NotFoundException;
void enableSniffer(AID snifferName , List toBeSniffed) throws RemoteException;
void disableSniffer(AID snifferName, List notToBeSniffed) throws RemoteException;
}
|
package dr.app.tools;
import dr.util.Version;
import dr.app.beast.BeastVersion;
import dr.app.util.Arguments;
import dr.app.util.Utils;
import dr.inference.trace.TraceException;
import dr.inference.model.Parameter;
import dr.evolution.io.TreeImporter;
import dr.evolution.io.NexusImporter;
import dr.evolution.io.Importer;
import dr.evolution.tree.Tree;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.FlexibleTree;
import dr.evomodel.tree.TreeModel;
import dr.evomodel.tree.NodeTraitLogger;
import java.io.*;
import java.util.*;
public class NormaliseMeanTreeRate {
private final static Version version = new BeastVersion();
public NormaliseMeanTreeRate(String inputFileName, String outputFileName, double normaliseMeanRateTo) throws java.io.IOException {
File parentFile = new File(inputFileName);
if (parentFile.isFile()) {
System.out.println("Analysing tree file: " + inputFileName);
} else {
System.err.println("File " + inputFileName + " does not exist!");
System.exit(0);
}
File outFile = new File(outputFileName);
if (outputFileName != null) {
FileOutputStream outputStream = new FileOutputStream(outFile);
System.setOut(new PrintStream(outputStream));
}
if(!outFile.canWrite()) {
System.err.println("Cannot write to file" + outFile.getAbsolutePath());
System.exit(0);
}
FileReader fileReader = new FileReader(parentFile);
TreeImporter importer = new NexusImporter(fileReader);
ArrayList<Tree> treeList = new ArrayList<Tree>();
ArrayList<String> treeNames = new ArrayList<String>();
try {
while (importer.hasTree()) {
Tree tree = importer.importNextTree();
analyze(tree, normaliseMeanRateTo);
treeList.add(tree);
treeNames.add(tree.getId());
}
NexusExporter exporter = new NexusExporter(System.out);
exporter.setSortedTranslationTable(true);
exporter.exportTrees(treeList.toArray(new Tree[treeList.size()]),
true, treeNames.toArray(new String[treeNames.size()]));
} catch (Importer.ImportException e) {
System.err.println("Error Parsing Input Tree: " + e.getMessage());
return;
}
}
/**
* Normalises individual trees to the mean rate
*
* @param tree tree to normalise
* @param normaliseMeanRateTo rate to normalise to
* if the trace file is in the wrong format or corrupted
*/
public static void analyze(Tree tree, double normaliseMeanRateTo) {
double treeRate = 0;
double treeTime = 0;
for (int i = 0; i < tree.getNodeCount(); i++) {
NodeRef node = tree.getNode(i);
if(tree.getClass().getName().equals("dr.evomodel.tree.TreeModel")) {
throw new RuntimeException("Does not currently handle TreeModel");
}
if(!tree.isRoot(node)) {
if(tree.getNodeAttribute(node, "rate") == null) {
System.out.println("Tree file does not contain rate information. ");
System.setOut(System.out);
System.err.println("Tree file does not contain rate information. Program terminated");
System.exit(0);
}
treeRate += tree.getNodeRate(node) * tree.getBranchLength(node);
treeTime += tree.getBranchLength(node);
}
}
treeRate /= treeTime;
/* Normalise the rates here */
FlexibleTree modifiedTree = (FlexibleTree) tree;
for (int i = 0; i < modifiedTree.getNodeCount(); i++) {
NodeRef node = modifiedTree.getNode(i);
if(!modifiedTree.isRoot(node)) {
double nodeRate = normaliseMeanRateTo * modifiedTree.getNodeRate(node) / treeRate;
modifiedTree.setNodeAttribute(node, "rate", Double.valueOf(nodeRate));
double nodeTime = modifiedTree.getBranchLength(node);
nodeTime = nodeTime * treeRate / normaliseMeanRateTo;
modifiedTree.setBranchLength(node, nodeTime);
}
}
}
public static void printTitle() {
System.out.println();
centreLine("NormaliseMeanTreeRate " + version.getVersionString() + ", " + version.getDateString(), 60);
centreLine("MCMC Output analysis", 60);
centreLine("by", 60);
centreLine("Andrew Rambaut and Alexei J. Drummond", 60);
System.out.println();
centreLine("Institute of Evolutionary Biology", 60);
centreLine("University of Edinburgh", 60);
centreLine("a.rambaut@ed.ac.uk", 60);
System.out.println();
centreLine("Department of Computer Science", 60);
centreLine("University of Auckland", 60);
centreLine("alexei@cs.auckland.ac.nz", 60);
System.out.println();
System.out.println();
}
public static void centreLine(String line, int pageWidth) {
int n = pageWidth - line.length();
int n1 = n / 2;
for (int i = 0; i < n1; i++) {
System.out.print(" ");
}
System.out.println(line);
}
public static void printUsage(Arguments arguments) {
arguments.printUsage("normaliseMeanTreeRate", "[-input-file-name <input-file-name>] [-output-file-name <output-file-name>] [-normaliseMeanRateTo <normaliseMeanRateTo>]");
System.out.println();
System.out.println(" Example: normaliseMeanTreeRate test.trees out.trees 1.0");
System.out.println();
}
//Main method
public static void main(String[] args) throws java.io.IOException, TraceException {
printTitle();
Arguments arguments = new Arguments(
new Arguments.Option[]{
new Arguments.StringOption("input-file-name", "infile", "Input file name"),
new Arguments.StringOption("output-file-name", "outfile", "Output file name"),
new Arguments.RealOption("normaliseMeanRateTo", "Mean rate we should normalise to"),
new Arguments.Option("help", "option to print this message")
});
try {
arguments.parseArguments(args);
} catch (Arguments.ArgumentException ae) {
System.out.println(ae);
printUsage(arguments);
System.exit(1);
}
if (arguments.hasOption("help")) {
printUsage(arguments);
System.exit(0);
}
String inputFileName = null;
if(arguments.hasOption("input-file-name")) {
inputFileName = arguments.getStringOption("input-file-name");
}
String outputFileName = null;
if(arguments.hasOption("output-file-name")) {
outputFileName = arguments.getStringOption("output-file-name");
}
double normaliseMeanRateTo = Double.NaN;
if(arguments.hasOption("normaliseMeanRateTo")) {
normaliseMeanRateTo = arguments.getRealOption("normaliseMeanRateTo");
}
if (inputFileName == null) {
// No input file name was given so throw up a dialog box...
inputFileName = Utils.getLoadFileName("NormaliseMeanTreeRate " + version.getVersionString() + " - Select log file to analyse");
}
if (outputFileName == null) {
// No input file name was given so throw up a dialog box...
outputFileName = Utils.getSaveFileName("NormaliseMeanTreeRate " + version.getVersionString() + " - Select file to save to");
}
if(Double.isNaN(normaliseMeanRateTo)) {
System.out.println("Enter rate value to normalise to: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
normaliseMeanRateTo = Double.parseDouble(br.readLine());
}
new NormaliseMeanTreeRate(inputFileName, outputFileName, normaliseMeanRateTo);
System.out.println("Please bear in mind that the trees files are unchanged and results may vary slightly from if you ran them internally");
System.exit(0);
}
}
|
package effectivejava.chapter5;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EmptyStackException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Test;
public class SetUtilTest {
@Test
public void testUnionSimple() {
Set<Integer> si1 = new HashSet<>();
si1.add(1);
si1.add(2);
si1.add(3);
si1.add(4);
Set<Integer> si2 = new HashSet<>();
si2.add(1);
si2.add(21);
si2.add(31);
Set<Integer> sfinal = SetUtil.union(si1, si2);
assertEquals(si1.size() + si2.size() - 1, sfinal.size());
}
@Test
public void testUnionSubclass() {
Set<Integer> si1 = new HashSet<>();
si1.add(1);
si1.add(2);
si1.add(3);
si1.add(4);
Set<Double> si2 = new HashSet<>();
si2.add(1.1);
si2.add(2.1);
si2.add(3.1);
si2.add(4.1);
Set<Number> sfinal = SetUtil.union(si1, si2);
// this is how to explicitly call the Number version if the compiler can't figure it out
// Set<Number> sfinal = SetUtil.<Number>union(si1, si2);
// System.out.println(sfinal);
assertEquals(si1.size() + si2.size(), sfinal.size());
}
}
|
package fr.jayasoft.ivy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.swing.event.EventListenerList;
import org.xml.sax.SAXException;
import fr.jayasoft.ivy.IvyNode.EvictionData;
import fr.jayasoft.ivy.conflict.LatestConflictManager;
import fr.jayasoft.ivy.conflict.NoConflictManager;
import fr.jayasoft.ivy.conflict.StrictConflictManager;
import fr.jayasoft.ivy.event.IvyEvent;
import fr.jayasoft.ivy.event.IvyListener;
import fr.jayasoft.ivy.event.PrepareDownloadEvent;
import fr.jayasoft.ivy.filter.Filter;
import fr.jayasoft.ivy.filter.FilterHelper;
import fr.jayasoft.ivy.latest.LatestLexicographicStrategy;
import fr.jayasoft.ivy.latest.LatestRevisionStrategy;
import fr.jayasoft.ivy.latest.LatestTimeStrategy;
import fr.jayasoft.ivy.matcher.ExactOrRegexpPatternMatcher;
import fr.jayasoft.ivy.matcher.ExactPatternMatcher;
import fr.jayasoft.ivy.matcher.GlobPatternMatcher;
import fr.jayasoft.ivy.matcher.Matcher;
import fr.jayasoft.ivy.matcher.MatcherHelper;
import fr.jayasoft.ivy.matcher.ModuleIdMatcher;
import fr.jayasoft.ivy.matcher.PatternMatcher;
import fr.jayasoft.ivy.matcher.RegexpPatternMatcher;
import fr.jayasoft.ivy.namespace.NameSpaceHelper;
import fr.jayasoft.ivy.namespace.Namespace;
import fr.jayasoft.ivy.parser.ModuleDescriptorParser;
import fr.jayasoft.ivy.parser.ModuleDescriptorParserRegistry;
import fr.jayasoft.ivy.report.ArtifactDownloadReport;
import fr.jayasoft.ivy.report.ConfigurationResolveReport;
import fr.jayasoft.ivy.report.DownloadReport;
import fr.jayasoft.ivy.report.DownloadStatus;
import fr.jayasoft.ivy.report.LogReportOutputter;
import fr.jayasoft.ivy.report.ReportOutputter;
import fr.jayasoft.ivy.report.ResolveReport;
import fr.jayasoft.ivy.report.XmlReportOutputter;
import fr.jayasoft.ivy.repository.TransferEvent;
import fr.jayasoft.ivy.repository.TransferListener;
import fr.jayasoft.ivy.repository.url.URLResource;
import fr.jayasoft.ivy.resolver.AbstractResolver;
import fr.jayasoft.ivy.resolver.CacheResolver;
import fr.jayasoft.ivy.resolver.ChainResolver;
import fr.jayasoft.ivy.resolver.DualResolver;
import fr.jayasoft.ivy.resolver.ModuleEntry;
import fr.jayasoft.ivy.resolver.OrganisationEntry;
import fr.jayasoft.ivy.resolver.RevisionEntry;
import fr.jayasoft.ivy.url.URLHandlerRegistry;
import fr.jayasoft.ivy.util.FileUtil;
import fr.jayasoft.ivy.util.IvyPatternHelper;
import fr.jayasoft.ivy.util.Message;
import fr.jayasoft.ivy.util.PropertiesFile;
import fr.jayasoft.ivy.xml.XmlIvyConfigurationParser;
import fr.jayasoft.ivy.xml.XmlModuleDescriptorParser;
import fr.jayasoft.ivy.xml.XmlModuleDescriptorUpdater;
import fr.jayasoft.ivy.xml.XmlReportParser;
/**
* Ivy is a free java based dependency manager.
*
* This class is the main class of Ivy, which offers mainly dependency resolution.
*
* Here is one typical usage:
* Ivy ivy = new Ivy();
* ivy.configure(new URL("ivyconf.xml"));
* ivy.resolve(new URL("ivy.xml"), null, new String[] {"*"}, null, null, true);
*
* @author x.hanin
*
*/
public class Ivy implements TransferListener {
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
private static final String DEFAULT_CACHE_ARTIFACT_PATTERN = "[organisation]/[module]/[type]s/[artifact]-[revision].[ext]";
private static final String DEFAULT_CACHE_DATA_FILE_PATTERN = "[organisation]/[module]/ivydata-[revision].properties";
private static final String DEFAULT_CACHE_IVY_PATTERN = "[organisation]/[module]/ivy-[revision].xml";
private static final String DEFAULT_CACHE_RESOLVED_IVY_PATTERN = "resolved-[organisation]-[module]-[revision].xml";
private static final String DEFAULT_CACHE_RESOLVED_IVY_PROPERTIES_PATTERN = "resolved-[organisation]-[module]-[revision].properties";
private Map _typeDefs = new HashMap();
private Map _resolversMap = new HashMap();
private DependencyResolver _defaultResolver;
private DependencyResolver _dictatorResolver = null;
private String _defaultResolverName;
private File _defaultCache;
private boolean _checkUpToDate = true;
private Map _moduleConfigurations = new LinkedHashMap(); // Map (ModuleIdMatcher -> String resolverName)
private Map _conflictsManager = new HashMap(); // Map (String conflictManagerName -> ConflictManager)
private Map _latestStrategies = new HashMap(); // Map (String latestStrategyName -> LatestStrategy)
private Map _namespaces = new HashMap(); // Map (String namespaceName -> Namespace)
private Map _matchers = new HashMap(); // Map (String matcherName -> Matcher)
private Map _variables = new HashMap();
private ReportOutputter[] _reportOutputters = new ReportOutputter[] {new LogReportOutputter(), new XmlReportOutputter()};
private String _cacheIvyPattern = DEFAULT_CACHE_IVY_PATTERN;
private String _cacheResolvedIvyPattern = DEFAULT_CACHE_RESOLVED_IVY_PATTERN;
private String _cacheResolvedIvyPropertiesPattern = DEFAULT_CACHE_RESOLVED_IVY_PROPERTIES_PATTERN;
private String _cacheArtifactPattern = DEFAULT_CACHE_ARTIFACT_PATTERN;
private String _cacheDataFilePattern = DEFAULT_CACHE_DATA_FILE_PATTERN;
private boolean _validate = true;
private LatestStrategy _defaultLatestStrategy = null;
private ConflictManager _defaultConflictManager = null;
private List _listingIgnore = new ArrayList();
private boolean _repositoriesConfigured;
private boolean _useRemoteConfig = false;
private File _defaultUserDir;
public Ivy() {
setVariable("ivy.default.conf.dir", Ivy.class.getResource("conf").toExternalForm(), true);
String ivyTypeDefs = System.getProperty("ivy.typedef.files");
if (ivyTypeDefs != null) {
String[] files = ivyTypeDefs.split("\\,");
for (int i = 0; i < files.length; i++) {
try {
typeDefs(new FileInputStream(new File(files[i].trim())));
} catch (FileNotFoundException e) {
Message.warn("typedefs file not found: "+files[i].trim());
} catch (IOException e) {
Message.warn("problem with typedef file: "+files[i].trim()+": "+e.getMessage());
}
}
} else {
try {
typeDefs(Ivy.class.getResourceAsStream("typedef.properties"));
} catch (IOException e) {
Message.warn("impossible to load default type defs");
}
}
LatestLexicographicStrategy latestLexicographicStrategy = new LatestLexicographicStrategy();
LatestRevisionStrategy latestRevisionStrategy = new LatestRevisionStrategy();
LatestTimeStrategy latestTimeStrategy = new LatestTimeStrategy();
addLatestStrategy("latest-revision", latestRevisionStrategy);
addLatestStrategy("latest-lexico", latestLexicographicStrategy);
addLatestStrategy("latest-time", latestTimeStrategy);
addConflictManager("latest-revision", new LatestConflictManager("latest-revision", latestRevisionStrategy));
addConflictManager("latest-time", new LatestConflictManager("latest-time", latestTimeStrategy));
addConflictManager("all", new NoConflictManager());
addConflictManager("strict", new StrictConflictManager());
addMatcher(ExactPatternMatcher.getInstance());
addMatcher(RegexpPatternMatcher.getInstance());
addMatcher(ExactOrRegexpPatternMatcher.getInstance());
addMatcher(GlobPatternMatcher.getInstance());
_listingIgnore.add(".cvsignore");
_listingIgnore.add("CVS");
_listingIgnore.add(".svn");
addTransferListener(new TransferListener() {
public void transferProgress(TransferEvent evt) {
switch (evt.getEventType()) {
case TransferEvent.TRANSFER_PROGRESS:
Message.progress();
break;
case TransferEvent.TRANSFER_COMPLETED:
Message.endProgress(" ("+(evt.getTotalLength() / 1024)+"kB)");
break;
default:
break;
}
}
});
}
/**
* Call this method to ask ivy to configure some variables using either a remote or a local properties file
*/
public void configureRepositories(boolean remote) {
if (!_repositoriesConfigured) {
Properties props = new Properties();
boolean configured = false;
if (_useRemoteConfig && remote) {
try {
URL url = new URL("http:
Message.verbose("configuring repositories with "+url);
props.load(URLHandlerRegistry.getDefault().openStream(url));
configured = true;
} catch (Exception ex) {
Message.verbose("unable to use remote repository configuration: "+ex.getMessage());
props = new Properties();
}
}
if (!configured) {
try {
props.load(Ivy.class.getResourceAsStream("repository.properties"));
} catch (IOException e) {
Message.error("unable to use internal repository configuration: "+e.getMessage());
}
}
addAllVariables(props, false);
_repositoriesConfigured = true;
}
}
public void typeDefs(InputStream stream) throws IOException {
try {
Properties p = new Properties();
p.load(stream);
typeDefs(p);
} finally {
stream.close();
}
}
public void typeDefs(Properties p) {
for (Iterator iter = p.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
try {
typeDef(name, Class.forName(p.getProperty(name)));
} catch (ClassNotFoundException e) {
Message.warn("impossible to define resolver "+name+": class not found: "+p.getProperty(name));
}
}
}
// CONFIGURATION
public void configure(File configurationFile) throws ParseException, IOException {
Message.info(":: configuring :: file = "+configurationFile);
long start = System.currentTimeMillis();
setConfigurationVariables(configurationFile);
if (getVariable("ivy.default.ivy.user.dir") != null) {
setDefaultIvyUserDir(new File(getVariable("ivy.default.ivy.user.dir")));
} else {
getDefaultIvyUserDir();
}
getDefaultCache();
try {
new XmlIvyConfigurationParser(this).parse(configurationFile.toURL());
} catch (MalformedURLException e) {
IllegalArgumentException iae = new IllegalArgumentException("given file cannot be transformed to url: "+configurationFile);
iae.initCause(e);
throw iae;
}
setVariable("ivy.default.ivy.user.dir", getDefaultIvyUserDir().getAbsolutePath(), false);
Message.verbose("configuration done ("+(System.currentTimeMillis()-start)+"ms)");
dumpConfig();
}
public void configure(URL configurationURL) throws ParseException, IOException {
Message.info(":: configuring :: url = "+configurationURL);
long start = System.currentTimeMillis();
setConfigurationVariables(configurationURL);
if (getVariable("ivy.default.ivy.user.dir") != null) {
setDefaultIvyUserDir(new File(getVariable("ivy.default.ivy.user.dir")));
} else {
getDefaultIvyUserDir();
}
getDefaultCache();
new XmlIvyConfigurationParser(this).parse(configurationURL);
setVariable("ivy.default.ivy.user.dir", getDefaultIvyUserDir().getAbsolutePath(), false);
Message.verbose("configuration done ("+(System.currentTimeMillis()-start)+"ms)");
dumpConfig();
}
public void configureDefault() throws ParseException, IOException {
configure(getDefaultConfigurationURL());
}
public void setConfigurationVariables(File configurationFile) {
try {
setVariable("ivy.conf.dir", new File(configurationFile.getAbsolutePath()).getParent());
setVariable("ivy.conf.file", configurationFile.getAbsolutePath());
setVariable("ivy.conf.url", configurationFile.toURL().toExternalForm());
} catch (MalformedURLException e) {
IllegalArgumentException iae = new IllegalArgumentException("given file cannot be transformed to url: "+configurationFile);
iae.initCause(e);
throw iae;
}
}
public void setConfigurationVariables(URL configurationURL) {
String confURL = configurationURL.toExternalForm();
setVariable("ivy.conf.url", confURL);
int slashIndex = confURL.lastIndexOf('/');
if (slashIndex != -1) {
setVariable("ivy.conf.dir", confURL.substring(0, slashIndex));
} else {
Message.warn("configuration url does not contain any slash (/): ivy.conf.dir variable not set");
}
}
private void dumpConfig() {
Message.verbose("\tdefault cache: "+getDefaultCache());
Message.verbose("\tdefault resolver: "+getDefaultResolver());
Message.debug("\tdefault latest strategy: "+getDefaultLatestStrategy());
Message.debug("\tdefault conflict manager: "+getDefaultConflictManager());
Message.debug("\tvalidate: "+doValidate());
Message.debug("\tcheck up2date: "+isCheckUpToDate());
Message.debug("\tcache ivy pattern: "+getCacheIvyPattern());
Message.debug("\tcache artifact pattern: "+getCacheArtifactPattern());
Message.verbose("\t-- "+_resolversMap.size()+" resolvers:");
for (Iterator iter = _resolversMap.values().iterator(); iter.hasNext();) {
DependencyResolver resolver = (DependencyResolver)iter.next();
resolver.dumpConfig();
}
if (!_moduleConfigurations.isEmpty()) {
Message.debug("\tmodule configurations:");
for (Iterator iter = _moduleConfigurations.keySet().iterator(); iter.hasNext();) {
ModuleIdMatcher midm = (ModuleIdMatcher)iter.next();
String res = (String)_moduleConfigurations.get(midm);
Message.debug("\t\t"+midm+" -> "+res);
}
}
}
public void loadProperties(URL url) throws IOException {
loadProperties(url, true);
}
public void loadProperties(URL url, boolean overwrite) throws IOException {
Properties properties = new Properties();
properties.load(url.openStream());
addAllVariables(properties, overwrite);
}
public void loadProperties(File file) throws IOException {
loadProperties(file, true);
}
public void loadProperties(File file, boolean overwrite) throws IOException {
Properties properties = new Properties();
properties.load(new FileInputStream(file));
addAllVariables(properties, overwrite);
}
public void setVariable(String varName, String value) {
setVariable(varName, value, true);
}
public void setVariable(String varName, String value, boolean overwrite) {
if (overwrite || !_variables.containsKey(varName)) {
Message.debug("setting '"+varName+"' to '"+value+"'");
_variables.put(varName, substitute(value));
} else {
Message.debug("'"+varName+"' already set: discarding '"+value+"'");
}
}
public void addAllVariables(Map variables) {
addAllVariables(variables, true);
}
public void addAllVariables(Map variables, boolean overwrite) {
for (Iterator iter = variables.keySet().iterator(); iter.hasNext();) {
String key = (String)iter.next();
String val = (String)variables.get(key);
setVariable(key, val, overwrite);
}
}
/**
* Substitute variables in the given string by their value found in the current
* set of variables
*
* @param str the string in which substitution should be made
* @return the string where all current ivy variables have been substituted by their value
*/
public String substitute(String str) {
return IvyPatternHelper.substituteVariables(str, getVariables());
}
/**
* Returns the variables loaded in configuration file. Those variables
* may better be seen as ant properties
*
* @return
*/
public Map getVariables() {
return _variables;
}
public void typeDef(String name, Class clazz) {
_typeDefs.put(name, clazz);
}
public Map getTypeDefs() {
return _typeDefs;
}
public Class getTypeDef(String name) {
return (Class)_typeDefs.get(name);
}
// methods which match ivy conf method signature specs
public void addConfigured(DependencyResolver resolver) {
addResolver(resolver);
}
public void addConfigured(ModuleDescriptorParser parser) {
ModuleDescriptorParserRegistry.getInstance().addParser(parser);
}
public void addResolver(DependencyResolver resolver) {
if (resolver == null) {
throw new NullPointerException("null resolver");
}
if (resolver instanceof IvyAware) {
((IvyAware)resolver).setIvy(this);
}
_resolversMap.put(resolver.getName(), resolver);
if (resolver instanceof ChainResolver) {
List subresolvers = ((ChainResolver)resolver).getResolvers();
for (Iterator iter = subresolvers.iterator(); iter.hasNext();) {
DependencyResolver dr = (DependencyResolver)iter.next();
addResolver(dr);
}
} else if (resolver instanceof DualResolver) {
DependencyResolver ivyResolver = ((DualResolver)resolver).getIvyResolver();
if (ivyResolver != null) {
addResolver(ivyResolver);
}
DependencyResolver artifactResolver = ((DualResolver)resolver).getArtifactResolver();
if (artifactResolver != null) {
addResolver(artifactResolver);
}
}
}
public void setDefaultCache(File cacheDirectory) {
_defaultCache = cacheDirectory;
}
public void setDefaultResolver(String resolverName) {
checkResolverName(resolverName);
_defaultResolverName = resolverName;
}
private void checkResolverName(String resolverName) {
if (!_resolversMap.containsKey(resolverName)) {
throw new IllegalArgumentException("no resolver found called "+resolverName+": check your configuration");
}
}
/**
* regular expressions as explained in Pattern class may be used in ModuleId
* organisation and name
*
* @param moduleId
* @param resolverName
*/
public void addModuleConfiguration(ModuleId mid, PatternMatcher matcher, String resolverName) {
checkResolverName(resolverName);
_moduleConfigurations.put(new ModuleIdMatcher(mid, matcher), resolverName);
}
public File getDefaultIvyUserDir() {
if (_defaultUserDir==null) {
setDefaultIvyUserDir(new File(System.getProperty("user.home"), ".ivy"));
Message.verbose("no default ivy user dir defined: set to "+_defaultUserDir);
}
return _defaultUserDir;
}
public void setDefaultIvyUserDir(File defaultUserDir) {
_defaultUserDir = defaultUserDir;
setVariable("ivy.default.ivy.user.dir", _defaultUserDir.getAbsolutePath());
}
public File getDefaultCache() {
if (_defaultCache==null) {
_defaultCache = new File(getDefaultIvyUserDir(), "cache");
Message.verbose("no default cache defined: set to "+_defaultCache);
}
return _defaultCache;
}
public DependencyResolver getResolver(ModuleId moduleId) {
if (_dictatorResolver != null) {
return _dictatorResolver;
}
String resolverName = getResolverName(moduleId);
return getResolver(resolverName);
}
public DependencyResolver getResolver(String resolverName) {
if (_dictatorResolver != null) {
return _dictatorResolver;
}
DependencyResolver resolver = (DependencyResolver)_resolversMap.get(resolverName);
if (resolver == null) {
Message.error("unknown resolver "+resolverName);
}
return resolver;
}
public DependencyResolver getDefaultResolver() {
if (_dictatorResolver != null) {
return _dictatorResolver;
}
if (_defaultResolver == null) {
_defaultResolver = (DependencyResolver)_resolversMap.get(_defaultResolverName);
}
return _defaultResolver;
}
public String getResolverName(ModuleId moduleId) {
for (Iterator iter = _moduleConfigurations.keySet().iterator(); iter.hasNext();) {
ModuleIdMatcher midm = (ModuleIdMatcher)iter.next();
if (midm.matches(moduleId)) {
return (String)_moduleConfigurations.get(midm);
}
}
return _defaultResolverName;
}
public void addConfigured(ConflictManager cm) {
addConflictManager(cm.getName(), cm);
}
public ConflictManager getConflictManager(String name) {
if ("default".equals(name)) {
return getDefaultConflictManager();
}
return (ConflictManager)_conflictsManager.get(name);
}
public void addConflictManager(String name, ConflictManager cm) {
if (cm instanceof IvyAware) {
((IvyAware)cm).setIvy(this);
}
_conflictsManager.put(name, cm);
}
public void addConfigured(LatestStrategy latest) {
addLatestStrategy(latest.getName(), latest);
}
public LatestStrategy getLatestStrategy(String name) {
if ("default".equals(name)) {
return getDefaultLatestStrategy();
}
return (LatestStrategy)_latestStrategies.get(name);
}
public void addLatestStrategy(String name, LatestStrategy latest) {
if (latest instanceof IvyAware) {
((IvyAware)latest).setIvy(this);
}
_latestStrategies.put(name, latest);
}
public void addConfigured(Namespace ns) {
addNamespace(ns);
}
public Namespace getNamespace(String name) {
if ("system".equals(name)) {
return getSystemNamespace();
}
return (Namespace)_namespaces.get(name);
}
public Namespace getSystemNamespace() {
return Namespace.SYSTEM_NAMESPACE;
}
public void addNamespace(Namespace ns) {
if (ns instanceof IvyAware) {
((IvyAware)ns).setIvy(this);
}
_namespaces.put(ns.getName(), ns);
}
public void addConfigured(PatternMatcher m) {
addMatcher(m);
}
public PatternMatcher getMatcher(String name) {
return (PatternMatcher)_matchers.get(name);
}
public void addMatcher(PatternMatcher m) {
if (m instanceof IvyAware) {
((IvyAware)m).setIvy(this);
}
_matchers.put(m.getName(), m);
}
// CHECK
/**
* Checks the given ivy file using current configuration to see if all dependencies
* are available, with good confs. If a resolver name is given, it also checks that the declared
* publications are available in the corresponding resolver.
* Note that the check is not performed recursively, i.e. if a dependency has itself dependencies
* badly described or not available, this check will not discover it.
*/
public boolean check(URL ivyFile, String resolvername) {
try {
boolean result = true;
// parse ivy file
ModuleDescriptor md = ModuleDescriptorParserRegistry.getInstance().parseDescriptor(this, ivyFile, doValidate());
// check publications if possible
if (resolvername != null) {
DependencyResolver resolver = getResolver(resolvername);
String[] confs = md.getConfigurationsNames();
Set artifacts = new HashSet();
for (int i = 0; i < confs.length; i++) {
artifacts.addAll(Arrays.asList(md.getArtifacts(confs[i])));
}
for (Iterator iter = artifacts.iterator(); iter.hasNext();) {
Artifact art = (Artifact)iter.next();
if (!resolver.exists(art)) {
Message.info("declared publication not found: "+art);
result = false;
}
}
}
// check dependencies
DependencyDescriptor[] dds = md.getDependencies();
ResolveData data = new ResolveData(this, getDefaultCache(), new Date(), null, true);
for (int i = 0; i < dds.length; i++) {
// check master confs
String[] masterConfs = dds[i].getModuleConfigurations();
for (int j = 0; j < masterConfs.length; j++) {
if (!"*".equals(masterConfs[j].trim()) && md.getConfiguration(masterConfs[j]) == null) {
Message.info("dependency required in non existing conf for "+ivyFile+" \n\tin "+dds[i].getDependencyRevisionId()+": "+masterConfs[j]);
result = false;
}
}
// resolve
DependencyResolver resolver = getResolver(dds[i].getDependencyId());
ResolvedModuleRevision rmr = resolver.getDependency(dds[i], data);
if (rmr == null) {
Message.info("dependency not found in "+ivyFile+":\n\t"+dds[i]);
result = false;
} else {
String[] depConfs = dds[i].getDependencyConfigurations(md.getConfigurationsNames());
for (int j = 0; j < depConfs.length; j++) {
if (!Arrays.asList(rmr.getDescriptor().getConfigurationsNames()).contains(depConfs[j])) {
Message.info("dependency configuration is missing for "+ivyFile+"\n\tin "+dds[i].getDependencyRevisionId()+": "+depConfs[j]);
result = false;
}
Artifact[] arts = rmr.getDescriptor().getArtifacts(depConfs[j]);
for (int k = 0; k < arts.length; k++) {
if (!resolver.exists(arts[k])) {
Message.info("dependency artifact is missing for "+ivyFile+"\n\t in "+dds[i].getDependencyRevisionId()+": "+arts[k]);
result = false;
}
}
}
}
}
return result;
} catch (ParseException e) {
Message.info("parse problem on "+ivyFile+": "+e.getMessage());
return false;
} catch (IOException e) {
Message.info("io problem on "+ivyFile+": "+e.getMessage());
return false;
} catch (Exception e) {
Message.info("problem on "+ivyFile+": "+e.getMessage());
return false;
}
}
// RESOLVE
/**
*
* @param ivySource the url to the descriptor of the module for which dependencies should be resolved
* @param revision the revision of the module for which dependencies should be resolved.
* This revision is considered as the resolved revision of the module, unless it is null.
* If it is null, then a default revision is given if necessary (no revision found in ivy file)
* @param confs the configurations for which dependencies should be resolved
* @param cache the directory where to place resolved dependencies
* @param date the date for which the dependencies should be resolved. All obtained artifacts
* should have a publication date which is before or equal to the given date
* @throws ParseException
* @throws IOException
* @throws NullPointerException if any parameter is null except cache or date
*/
public ResolveReport resolve(URL ivySource, String revision, String[] confs, File cache, Date date, boolean validate) throws ParseException, IOException {
return resolve(ivySource, revision, confs, cache, date, validate, false);
}
public ResolveReport resolve(URL ivySource, String revision, String[] confs, File cache, Date date, boolean validate, boolean useCacheOnly) throws ParseException, IOException {
return resolve(ivySource, revision, confs, cache, date, validate, useCacheOnly, FilterHelper.NO_FILTER);
}
public ResolveReport resolve(URL ivySource, String revision, String[] confs, File cache, Date date, boolean validate, boolean useCacheOnly, Filter artifactFilter) throws ParseException, IOException {
DependencyResolver oldDictator = getDictatorResolver();
if (useCacheOnly) {
setDictatorResolver(new CacheResolver(this));
}
URLResource res = new URLResource(ivySource);
ModuleDescriptorParser parser = ModuleDescriptorParserRegistry.getInstance().getParser(res);
Message.verbose("using "+parser+" to parse "+ivySource);
try {
ModuleDescriptor md = parser.parseDescriptor(this, ivySource, validate);
if (cache==null) { // ensure that a cache exists
cache = getDefaultCache();
}
if (revision == null && md.getResolvedModuleRevisionId().getRevision() == null) {
revision = "working@"+getLocalHostName();
}
if (revision != null) {
md.setResolvedModuleRevisionId(new ModuleRevisionId(md.getModuleRevisionId().getModuleId(), revision));
}
if (confs.length == 1 && confs[0].equals("*")) {
confs = md.getConfigurationsNames();
}
long start = System.currentTimeMillis();
Message.info(":: resolving dependencies :: "+md.getResolvedModuleRevisionId());
Message.info("\tconfs: "+Arrays.asList(confs));
Message.verbose("\tvalidate = "+validate);
ResolveReport report = new ResolveReport(md);
// resolve dependencies
IvyNode[] dependencies = getDependencies(md, confs, cache, date, report, validate);
Message.verbose(":: downloading artifacts ::");
Map resolvedRevisions = new HashMap(); // Map (ModuleId dependency -> String revision)
Map dependenciesStatus = new HashMap(); // Map (ModuleId dependency -> String status)
downloadArtifacts(dependencies, artifactFilter, report, resolvedRevisions, dependenciesStatus, cache);
// produce resolved ivy file and ivy properties in cache
File ivyFileInCache = getResolvedIvyFileInCache(cache, md.getResolvedModuleRevisionId());
parser.toIvyFile(ivySource, res, ivyFileInCache, md);
File ivyPropertiesInCache = getResolvedIvyPropertiesInCache(cache, md.getResolvedModuleRevisionId());
Properties props = new Properties();
for (Iterator iter = resolvedRevisions.keySet().iterator(); iter.hasNext();) {
ModuleId mid = (ModuleId)iter.next();
String rev = (String)resolvedRevisions.get(mid);
String status = (String)dependenciesStatus.get(mid);
props.put(mid.encodeToString(), rev+" "+status);
}
props.store(new FileOutputStream(ivyPropertiesInCache), md.getResolvedModuleRevisionId()+ " resolved revisions");
Message.verbose("\tresolved ivy file produced in "+ivyFileInCache);
Message.info(":: resolution report ::");
// output report
report.output(getReportOutputters(), cache);
Message.verbose("\tresolve done ("+(System.currentTimeMillis()-start)+"ms)");
Message.sumupProblems();
return report;
} finally {
setDictatorResolver(oldDictator);
}
}
private void downloadArtifacts(IvyNode[] dependencies, Filter artifactFilter, ResolveReport report, File cache) {
downloadArtifacts(dependencies, artifactFilter, report, new HashMap(), new HashMap(), cache);
}
private void downloadArtifacts(IvyNode[] dependencies, Filter artifactFilter, ResolveReport report, Map resolvedRevisions, Map dependenciesStatus, File cache) {
// collect list of artifacts
Collection artifacts = new ArrayList();
for (int i = 0; i < dependencies.length; i++) {
//download artifacts required in all asked configurations
if (!dependencies[i].isCompletelyEvicted() && !dependencies[i].hasProblem()) {
artifacts.addAll(Arrays.asList(dependencies[i].getSelectedArtifacts(artifactFilter)));
}
}
fireIvyEvent(new PrepareDownloadEvent((Artifact[])artifacts.toArray(new Artifact[artifacts.size()])));
for (int i = 0; i < dependencies.length; i++) {
//download artifacts required in all asked configurations
if (!dependencies[i].isCompletelyEvicted() && !dependencies[i].hasProblem()) {
DependencyResolver resolver = dependencies[i].getModuleRevision().getResolver();
Artifact[] selectedArtifacts = dependencies[i].getSelectedArtifacts(artifactFilter);
DownloadReport dReport = resolver.download(selectedArtifacts, this, cache);
ArtifactDownloadReport[] adrs = dReport.getArtifactsReports();
for (int j = 0; j < adrs.length; j++) {
if (adrs[j].getDownloadStatus() == DownloadStatus.FAILED) {
Message.warn("\t[NOT FOUND ] "+adrs[j].getArtifact());
resolver.reportFailure(adrs[j].getArtifact());
}
}
// update concerned reports
String[] dconfs = dependencies[i].getRootModuleConfigurations();
for (int j = 0; j < dconfs.length; j++) {
// the report itself is responsible to take into account only
// artifacts required in its corresponding configuration
// (as described by the Dependency object)
if (dependencies[i].isEvicted(dconfs[j])) {
report.getConfigurationReport(dconfs[j]).addDependency(dependencies[i]);
} else {
report.getConfigurationReport(dconfs[j]).addDependency(dependencies[i], dReport);
}
}
// update resolved dependencies map for resolved ivy file producing
resolvedRevisions.put(dependencies[i].getModuleId(), dependencies[i].getResolvedId().getRevision());
dependenciesStatus.put(dependencies[i].getModuleId(), dependencies[i].getDescriptor().getStatus());
} else if (dependencies[i].isCompletelyEvicted()) {
// dependencies has been evicted: it has not been added to the report yet
String[] dconfs = dependencies[i].getRootModuleConfigurations();
for (int j = 0; j < dconfs.length; j++) {
report.getConfigurationReport(dconfs[j]).addDependency(dependencies[i]);
}
}
}
}
/**
* Download an artifact to the cache.
* Not used internally, useful especially for IDE plugins
* needing to download artifact one by one (for source or javadoc artifact,
* for instance).
*
* Downloaded artifact file can be accessed using getArchiveFileInCache method.
*
* It is possible to track the progression of the download using classical ivy
* progress monitoring feature (see addTransferListener).
*
* @param artifact the artifact to download
* @param cache the cache to use. If null, will use default cache
* @return a report concerning the download
*/
public ArtifactDownloadReport download(Artifact artifact, File cache) {
if (cache == null) {
cache = getDefaultCache();
}
DependencyResolver resolver = getResolver(artifact.getModuleRevisionId().getModuleId());
DownloadReport r = resolver.download(new Artifact[] {artifact}, this, cache);
return r.getArtifactReport(artifact);
}
public ReportOutputter[] getReportOutputters() {
return _reportOutputters;
}
/**
* Resolve the dependencies of a module without downloading corresponding artifacts.
* The module to resolve is given by its ivy file URL. This method requires
* appropriate configuration of the ivy instance, especially resolvers.
*
* @param ivySource url of the ivy file to use for dependency resolving
* @param confs an array of configuration names to resolve - must not be null nor empty
* @param cache the cache to use - default cache is used if null
* @param date the date to which resolution must be done - may be null
* @return an array of the resolved dependencies
* @throws ParseException if a parsing problem occured in the ivy file
* @throws IOException if an IO problem was raised during ivy file parsing
*/
public IvyNode[] getDependencies(URL ivySource, String[] confs, File cache, Date date, boolean validate) throws ParseException, IOException {
return getDependencies(ModuleDescriptorParserRegistry.getInstance().parseDescriptor(this, ivySource, validate), confs, cache, date, null, validate);
}
/**
* Resolve the dependencies of a module without downloading corresponding artifacts.
* The module to resolve is given by its module descriptor.This method requires
* appropriate configuration of the ivy instance, especially resolvers.
*
* @param md the descriptor of the module for which we want to get dependencies - must not be null
* @param confs an array of configuration names to resolve - must not be null nor empty
* @param cache the cache to use - default cache is used if null
* @param date the date to which resolution must be done - may be null
* @param report a resolve report to fill during resolution - may be null
* @return an array of the resolved Dependencies
*/
public IvyNode[] getDependencies(ModuleDescriptor md, String[] confs, File cache, Date date, ResolveReport report, boolean validate) {
if (md == null) {
throw new NullPointerException("module descriptor must not be null");
}
if (cache==null) { // ensure that a cache exists
cache = getDefaultCache();
}
if (confs.length == 1 && confs[0].equals("*")) {
confs = md.getConfigurationsNames();
}
Map dependenciesMap = new HashMap();
Date reportDate = new Date();
for (int i = 0; i < confs.length; i++) {
Configuration configuration = md.getConfiguration(confs[i]);
if (configuration == null) {
Message.error("asked configuration not found in "+md.getModuleRevisionId()+": "+confs[i]);
} else {
ConfigurationResolveReport confReport = null;
if (report != null) {
confReport = report.getConfigurationReport(confs[i]);
if (confReport == null) {
confReport = new ConfigurationResolveReport(this, md, confs[i], reportDate, cache);
report.addReport(confs[i], confReport);
}
}
ResolveData data = new ResolveData(this, cache, date, confReport, validate, dependenciesMap);
IvyNode node = new IvyNode(data, md, confs[i], true);
node.setRootModuleConf(confs[i]);
fetchDependencies(node, confs[i], false);
}
}
// prune and reverse sort fectched dependencies
Collection dependencies = new HashSet(dependenciesMap.size()); // use a Set to avoids duplicates
for (Iterator iter = dependenciesMap.values().iterator(); iter.hasNext();) {
IvyNode dep = (IvyNode) iter.next();
if (dep != null) {
dependencies.add(dep);
}
}
List sortedDependencies = sortNodes(dependencies);
Collections.reverse(sortedDependencies);
// handle transitive eviction now:
// if a module has been evicted then all its dependencies required
// only by it should be evicted too. Since nodes are now sorted from the more dependent to
// the less one, we can traverse the list and check only the direct parent and not all
// the ancestors
for (ListIterator iter = sortedDependencies.listIterator(); iter.hasNext();) {
IvyNode node = (IvyNode)iter.next();
if (!node.isCompletelyEvicted()) {
for (int i = 0; i < confs.length; i++) {
IvyNode.Caller[] callers = node.getCallers(confs[i]);
Message.debug("checking if "+node.getId()+" is transitively evicted in "+confs[i]);
boolean allEvicted = callers.length > 0;
for (int j = 0; j < callers.length; j++) {
if (callers[j].getModuleRevisionId().equals(md.getModuleRevisionId())) {
// the caller is the root module itself, it can't be evicted
allEvicted = false;
break;
} else {
IvyNode callerNode = (IvyNode)dependenciesMap.get(callers[j].getModuleRevisionId());
if (callerNode == null) {
Message.warn("ivy internal error: no node found for "+callers[j].getModuleRevisionId()+": looked in "+dependenciesMap.keySet()+" and root module id was "+md.getModuleRevisionId());
} else if (!callerNode.isEvicted(confs[i])) {
allEvicted = false;
break;
} else {
Message.debug("caller "+callerNode.getId()+" of "+node.getId()+" is evicted");
}
}
}
if (allEvicted) {
Message.verbose("all callers are evicted for "+node+": evicting too");
node.markEvicted(confs[i], null, null, null);
} else {
Message.debug(node.getId()+" isn't transitively evicted, at least one caller was not evicted");
}
}
}
}
return (IvyNode[])sortedDependencies.toArray(new IvyNode[sortedDependencies.size()]);
}
private void fetchDependencies(IvyNode node, String conf, boolean shouldBePublic) {
long start = System.currentTimeMillis();
Message.debug(node.getId()+" => resolving dependencies in "+conf);
resolveConflict(node, node.getParent());
if (node.loadData(conf, shouldBePublic)) {
node = node.getRealNode(); // if data loading discarded the node, get the real one
resolveConflict(node, node.getParent());
if (!node.isEvicted(node.getRootModuleConf())) {
String[] confs = node.getRealConfs(conf);
for (int i = 0; i < confs.length; i++) {
doFetchDependencies(node, confs[i]);
}
}
} else if (!node.hasProblem()) {
// the node has not been loaded but hasn't problem: it was already loaded
// => we just have to update its dependencies data
if (!node.isEvicted(node.getRootModuleConf())) {
String[] confs = node.getRealConfs(conf);
for (int i = 0; i < confs.length; i++) {
doFetchDependencies(node, confs[i]);
}
}
}
if (node.isEvicted(node.getRootModuleConf())) {
// update selected nodes with confs asked in evicted one
IvyNode.EvictionData ed = node.getEvictedData(node.getRootModuleConf());
for (Iterator iter = ed.getSelected().iterator(); iter.hasNext();) {
IvyNode selected = (IvyNode)iter.next();
fetchDependencies(selected, conf, true);
}
}
Message.debug(node.getId()+" => dependencies resolved in "+conf+" ("+(System.currentTimeMillis()-start)+"ms)");
}
private void doFetchDependencies(IvyNode node, String conf) {
Configuration c = node.getConfiguration(conf);
if (c == null) {
Message.warn("configuration not found '"+conf+"' in "+node.getResolvedId()+": ignoring");
if (node.getParent() != null) {
Message.warn("it was required from "+node.getParent().getResolvedId());
}
return;
}
// we handle the case where the asked configuration extends others:
// we have to first fetch the extended configurations
String[] extendedConfs = c.getExtends();
if (extendedConfs.length > 0) {
node.updateConfsToFetch(Arrays.asList(extendedConfs));
}
for (int i = 0; i < extendedConfs.length; i++) {
fetchDependencies(node, extendedConfs[i], false);
}
if (node.getDependencyDescriptor() == null || node.getDependencyDescriptor().isTransitive()) {
Collection dependencies = node.getDependencies(conf, true);
for (Iterator iter = dependencies.iterator(); iter.hasNext();) {
IvyNode dep = (IvyNode)iter.next();
if (dep.isCircular()) {
Message.warn("circular dependency found ! "+node.getId()+" depends on "+dep.getId()+" which is already on the same branch of dependency");
continue;
}
String[] confs = dep.getRequiredConfigurations(node, conf);
for (int i = 0; i < confs.length; i++) {
fetchDependencies(dep, confs[i], true);
}
// if there are still confs to fetch (usually because they have
// been updated when evicting another module), we fetch them now
confs = dep.getConfsToFetch();
for (int i = 0; i < confs.length; i++) {
fetchDependencies(dep, confs[i], true);
}
}
}
}
private void resolveConflict(IvyNode node, IvyNode parent) {
resolveConflict(node, parent, Collections.EMPTY_SET);
}
private void resolveConflict(IvyNode node, IvyNode parent, Collection toevict) {
if (parent == null || node == parent) {
return;
}
// check if job is not already done
if (checkConflictSolved(node, parent)) {
return;
}
// compute conflicts
Collection resolvedNodes = new HashSet(parent.getResolvedNodes(node.getModuleId(), node.getRootModuleConf()));
Collection conflicts = computeConflicts(node, parent, toevict, resolvedNodes);
Message.debug("found conflicting revisions for "+node+" in "+parent+": "+conflicts);
Collection resolved = parent.getConflictManager(node.getModuleId()).resolveConflicts(parent, conflicts);
Message.debug("selected revisions for "+node+" in "+parent+": "+resolved);
if (resolved.contains(node)) {
// node has been selected for the current parent
// we update its eviction... but it can still be evicted by parent !
node.markSelected(node.getRootModuleConf());
Message.debug("selecting "+node+" in "+parent);
// handle previously selected nodes that are now evicted by this new node
toevict = resolvedNodes;
toevict.removeAll(resolved);
for (Iterator iter = toevict.iterator(); iter.hasNext();) {
IvyNode te = (IvyNode)iter.next();
te.markEvicted(node.getRootModuleConf(), parent, parent.getConflictManager(node.getModuleId()), resolved);
Message.debug("evicting "+te+" by "+te.getEvictedData(node.getRootModuleConf()));
}
// it's very important to update resolved and evicted nodes BEFORE recompute parent call
// to allow it to recompute its resolved collection with correct data
// if necessary
parent.setResolvedNodes(node.getModuleId(), node.getRootModuleConf(), resolved);
Collection evicted = new HashSet(parent.getEvictedNodes(node.getModuleId(), node.getRootModuleConf()));
evicted.removeAll(resolved);
evicted.addAll(toevict);
parent.setEvictedNodes(node.getModuleId(), node.getRootModuleConf(), evicted);
resolveConflict(node, parent.getParent(), toevict);
} else {
// node has been evicted for the current parent
if (resolved.isEmpty()) {
Message.verbose("conflict manager '"+parent.getConflictManager(node.getModuleId())+"' evicted all revisions among "+conflicts);
}
// first we mark the selected nodes as selected if it isn't already the case
for (Iterator iter = resolved.iterator(); iter.hasNext();) {
IvyNode selected = (IvyNode)iter.next();
if (selected.isEvicted(node.getRootModuleConf())) {
selected.markSelected(node.getRootModuleConf());
Message.debug("selecting "+selected+" in "+parent);
}
}
// it's time to update parent resolved and evicted with what was found...
// if they have not been recomputed, it does not change anything
parent.setResolvedNodes(node.getModuleId(), node.getRootModuleConf(), resolved);
Collection evicted = new HashSet(parent.getEvictedNodes(node.getModuleId(), node.getRootModuleConf()));
evicted.removeAll(resolved);
evicted.addAll(toevict);
evicted.add(node);
parent.setEvictedNodes(node.getModuleId(), node.getRootModuleConf(), evicted);
node.markEvicted(node.getRootModuleConf(), parent, parent.getConflictManager(node.getModuleId()), resolved);
Message.debug("evicting "+node+" by "+node.getEvictedData(node.getRootModuleConf()));
}
}
private Collection computeConflicts(IvyNode node, IvyNode parent, Collection toevict, Collection resolvedNodes) {
Collection conflicts = new HashSet();
if (resolvedNodes.removeAll(toevict)) {
// recompute resolved from all sub nodes
conflicts.add(node);
Collection deps = parent.getDependencies(parent.getRequiredConfigurations());
for (Iterator iter = deps.iterator(); iter.hasNext();) {
IvyNode dep = (IvyNode)iter.next();
conflicts.addAll(dep.getResolvedNodes(node.getModuleId(), node.getRootModuleConf()));
}
} else if (resolvedNodes.isEmpty() && node.getParent() != parent) {
conflicts.add(node);
DependencyDescriptor[] dds = parent.getDescriptor().getDependencies();
for (int i = 0; i < dds.length; i++) {
if (dds[i].getDependencyId().equals(node.getModuleId())) {
IvyNode n = node.findNode(dds[i].getDependencyRevisionId());
if (n != null) {
conflicts.add(n);
break;
}
}
}
} else {
conflicts.add(node);
conflicts.addAll(resolvedNodes);
}
return conflicts;
}
private boolean checkConflictSolved(IvyNode node, IvyNode parent) {
if (parent.getResolvedRevisions(node.getModuleId(), node.getRootModuleConf()).contains(node.getResolvedId())) {
// resolve conflict has already be done with node with the same id
// => job already done, we just have to check if the node wasn't previously evicted in root ancestor
Message.debug("conflict resolution already done for "+node+" in "+parent);
EvictionData evictionData = node.getEvictionDataInRoot(node.getRootModuleConf(), parent);
if (evictionData != null) {
// node has been previously evicted in an ancestor: we mark it as evicted and ensure selected are selected
Message.debug(node+" was previously evicted in root module conf "+node.getRootModuleConf());
if (evictionData.getSelected() != null) {
for (Iterator iter = evictionData.getSelected().iterator(); iter.hasNext();) {
IvyNode selected = (IvyNode)iter.next();
if (selected.isEvicted(node.getRootModuleConf())) {
selected.markSelected(node.getRootModuleConf());
Message.debug("selecting "+selected+" in "+parent+" due to eviction of "+node);
}
}
}
node.markEvicted(evictionData);
Message.debug("evicting "+node+" by "+evictionData);
}
return true;
} else if (parent.getEvictedRevisions(node.getModuleId(), node.getRootModuleConf()).contains(node.getResolvedId())) {
// resolve conflict has already be done with node with the same id
// => job already done, we just have to check if the node wasn't previously selected in root ancestor
Message.debug("conflict resolution already done for "+node+" in "+parent);
EvictionData evictionData = node.getEvictionDataInRoot(node.getRootModuleConf(), parent);
if (evictionData == null) {
// node was selected in the root, we have to select it
Message.debug(node+" was previously selected in root module conf "+node.getRootModuleConf());
node.markSelected(node.getRootModuleConf());
Message.debug("selecting "+node+" in "+parent);
}
return true;
}
return false;
}
public ResolvedModuleRevision findModuleInCache(ModuleRevisionId mrid, File cache, boolean validate) {
// first, check if it is in cache
if (mrid.isExactRevision()) {
File ivyFile = getIvyFileInCache(cache, mrid);
if (ivyFile.exists()) {
// found in cache !
try {
ModuleDescriptor depMD = XmlModuleDescriptorParser.getInstance().parseDescriptor(this, ivyFile.toURL(), validate);
String resolverName = getSavedResolverName(cache, depMD);
DependencyResolver resolver = (DependencyResolver)_resolversMap.get(resolverName);
if (resolver == null) {
Message.debug("\tresolver not found: "+resolverName+" => trying to use the one configured for "+mrid);
resolver = getResolver(depMD.getResolvedModuleRevisionId().getModuleId());
if (resolver != null) {
Message.debug("\tconfigured resolver found for "+depMD.getResolvedModuleRevisionId()+": "+resolver.getName()+": saving this data");
saveResolver(cache, depMD, resolver.getName());
}
}
if (resolver != null) {
Message.debug("\tfound ivy file in cache for "+mrid+" (resolved by "+resolver.getName()+"): "+ivyFile);
return new DefaultModuleRevision(resolver, depMD, false, false);
} else {
Message.debug("\tresolver not found: "+resolverName+" => cannot use cached ivy file for "+mrid);
}
} catch (Exception e) {
// will try with resolver
Message.debug("\tproblem while parsing cached ivy file for: "+mrid+": "+e.getMessage());
}
} else {
Message.debug("\tno ivy file in cache for "+mrid+": tried "+ivyFile);
}
}
return null;
}
// INSTALL
public ResolveReport install(ModuleRevisionId mrid, String from, String to, boolean transitive, boolean validate, boolean overwrite, Filter artifactFilter, File cache, String matcherName) throws IOException {
if (cache == null) {
cache = getDefaultCache();
}
if (artifactFilter == null) {
artifactFilter = FilterHelper.NO_FILTER;
}
DependencyResolver fromResolver = getResolver(from);
DependencyResolver toResolver = getResolver(to);
if (fromResolver == null) {
throw new IllegalArgumentException("unknown resolver "+from+". Available resolvers are: "+_resolversMap.keySet());
}
if (toResolver == null) {
throw new IllegalArgumentException("unknown resolver "+to+". Available resolvers are: "+_resolversMap.keySet());
}
PatternMatcher matcher = getMatcher(matcherName);
if (matcher == null) {
throw new IllegalArgumentException("unknown matcher "+matcherName+". Available matchers are: "+_matchers.keySet());
}
// build module file declaring the dependency
Message.info(":: installing "+mrid+" ::");
DependencyResolver oldDicator = getDictatorResolver();
boolean log = logNotConvertedExclusionRule();
try {
setLogNotConvertedExclusionRule(true);
setDictatorResolver(fromResolver);
DefaultModuleDescriptor md = new DefaultModuleDescriptor(ModuleRevisionId.newInstance("jayasoft", "ivy-install", "1.0"), Status.DEFAULT_STATUS, new Date());
md.addConfiguration(new Configuration("default"));
md.addConflictManager(new ModuleId(ExactPatternMatcher.ANY_EXPRESSION, ExactPatternMatcher.ANY_EXPRESSION), ExactPatternMatcher.getInstance(), new NoConflictManager());
if (MatcherHelper.isExact(matcher, mrid)) {
DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(md, mrid, false, false, transitive);
dd.addDependencyConfiguration("default", "*");
md.addDependency(dd);
} else {
Collection mrids = findModuleRevisionIds(fromResolver, mrid, matcher);
for (Iterator iter = mrids.iterator(); iter.hasNext();) {
ModuleRevisionId foundMrid = (ModuleRevisionId)iter.next();
Message.info("\tfound "+foundMrid+" to install: adding to the list");
DefaultDependencyDescriptor dd = new DefaultDependencyDescriptor(md, foundMrid, false, false, transitive);
dd.addDependencyConfiguration("default", "*");
md.addDependency(dd);
}
}
// resolve using appropriate resolver
ResolveReport report = new ResolveReport(md);
Message.info(":: resolving dependencies ::");
IvyNode[] dependencies = getDependencies(md, new String[] {"default"}, cache, null, report, validate);
Message.info(":: downloading artifacts to cache ::");
downloadArtifacts(dependencies, artifactFilter, report, cache);
// now that everything is in cache, we can publish all these modules
Message.info(":: installing in "+to+" ::");
for (int i = 0; i < dependencies.length; i++) {
ModuleDescriptor depmd = dependencies[i].getDescriptor();
if (depmd != null) {
Message.verbose("installing "+depmd.getModuleRevisionId());
publish(depmd,
toResolver,
cache.getAbsolutePath()+"/"+getCacheArtifactPattern(),
cache.getAbsolutePath()+"/"+getCacheIvyPattern(),
overwrite);
}
}
Message.info(":: install resolution report ::");
// output report
report.output(getReportOutputters(), cache);
return report;
} finally {
setDictatorResolver(oldDicator);
setLogNotConvertedExclusionRule(log);
}
}
public Collection findModuleRevisionIds(DependencyResolver resolver, ModuleRevisionId pattern, PatternMatcher matcher) {
Collection mrids = new ArrayList();
String resolverName = resolver.getName();
Message.verbose("looking for modules matching "+pattern+" using "+matcher.getName());
Namespace fromNamespace = resolver instanceof AbstractResolver ? ((AbstractResolver)resolver).getNamespace() : null;
Collection modules = new ArrayList();
OrganisationEntry[] orgs = resolver.listOrganisations();
if (orgs == null || orgs.length == 0) {
// hack for resolvers which are not able to list organisation, we try to see if the asked organisation is not an exact one:
String org = pattern.getOrganisation();
if (fromNamespace != null) {
org = NameSpaceHelper.transform(pattern.getModuleId(), fromNamespace.getFromSystemTransformer()).getOrganisation();
}
modules.addAll(Arrays.asList(resolver.listModules(new OrganisationEntry(resolver, org))));
} else {
Matcher orgMatcher = matcher.getMatcher(pattern.getOrganisation());
for (int i = 0; i < orgs.length; i++) {
String org = orgs[i].getOrganisation();
String systemOrg = org;;
if (fromNamespace != null) {
systemOrg = NameSpaceHelper.transformOrganisation(org, fromNamespace.getToSystemTransformer());
}
if (orgMatcher.matches(systemOrg)) {
modules.addAll(Arrays.asList(resolver.listModules(new OrganisationEntry(resolver, org))));
}
}
}
Message.debug("found " + modules.size() + " modules for "+pattern.getOrganisation()+" on " + resolverName);
boolean foundModule = false;
for (Iterator iter = modules.iterator(); iter.hasNext();) {
ModuleEntry mEntry = (ModuleEntry)iter.next();
ModuleId foundMid = new ModuleId(mEntry.getOrganisation(), mEntry.getModule());
ModuleId systemMid = foundMid;
if (fromNamespace != null) {
systemMid = NameSpaceHelper.transform(foundMid, fromNamespace.getToSystemTransformer());
}
if (MatcherHelper.matches(matcher, pattern.getModuleId(), systemMid)) {
// The module corresponds to the searched module pattern
foundModule = true;
RevisionEntry[] rEntries = resolver.listRevisions(mEntry);
Message.debug("found " + rEntries.length + " revisions for [" + mEntry.getOrganisation() + ", "+ mEntry.getModule() + "] on " + resolverName);
boolean foundRevision = false;
for (int j = 0; j < rEntries.length; j++) {
RevisionEntry rEntry = rEntries[j];
ModuleRevisionId foundMrid = ModuleRevisionId.newInstance(mEntry.getOrganisation(), mEntry.getModule(), rEntry.getRevision());
ModuleRevisionId systemMrid = foundMrid;
if (fromNamespace != null) {
systemMrid = fromNamespace.getToSystemTransformer().transform(foundMrid);
}
if (MatcherHelper.matches(matcher, pattern, systemMrid)) {
// We have a matching module revision
foundRevision = true;
mrids.add(systemMrid);
}
}
if (!foundRevision) {
Message.debug("no revision found matching "+pattern+" in [" + mEntry.getOrganisation() + "," + mEntry.getModule()+ "] using " + resolverName);
}
}
}
if (!foundModule) {
Message.debug("no module found matching "+pattern+" using " + resolverName);
}
return mrids;
}
// RETRIEVE
public void retrieve(ModuleId moduleId, String[] confs, final File cache, String destFilePattern) {
retrieve(moduleId, confs, cache, destFilePattern, null);
}
/**
* If destIvyPattern is null no ivy files will be copied.
*/
public void retrieve(ModuleId moduleId, String[] confs, final File cache, String destFilePattern, String destIvyPattern) {
Message.info(":: retrieving :: "+moduleId);
Message.info("\tconfs: "+Arrays.asList(confs));
long start = System.currentTimeMillis();
destFilePattern = IvyPatternHelper.substituteVariables(destFilePattern, getVariables());
destIvyPattern = IvyPatternHelper.substituteVariables(destIvyPattern, getVariables());
try {
// find what we must retrieve where
final Map artifactsToCopy = new HashMap(); // Artifact source -> Set (String copyDestAbsolutePath)
final Map conflictsMap = new HashMap(); // String copyDestAbsolutePath -> Set (Artifact source)
final Map conflictsConfMap = new HashMap(); // String copyDestAbsolutePath -> Set (String conf)
XmlReportParser parser = new XmlReportParser();
for (int i = 0; i < confs.length; i++) {
final String conf = confs[i];
Collection artifacts = new ArrayList(Arrays.asList(parser.getArtifacts(moduleId, conf, cache)));
if (destIvyPattern != null) {
ModuleRevisionId[] mrids = parser.getRealDependencyRevisionIds(moduleId, conf, cache);
for (int j = 0; j < mrids.length; j++) {
ModuleRevisionId mrid = mrids[i];
artifacts.add(new DefaultArtifact(mrid, new Date(), "ivy", "ivy", "xml"));
}
}
for (Iterator iter = artifacts.iterator(); iter.hasNext();) {
Artifact artifact = (Artifact)iter.next();
String destPattern = "ivy".equals(artifact.getType()) ? destIvyPattern: destFilePattern;
String destFileName = IvyPatternHelper.substitute(destPattern, artifact.getModuleRevisionId().getOrganisation(), artifact.getModuleRevisionId().getName(), artifact.getModuleRevisionId().getRevision(), artifact.getName(), artifact.getType(), artifact.getExt(), conf);
Set dest = (Set)artifactsToCopy.get(artifact);
if (dest == null) {
dest = new HashSet();
artifactsToCopy.put(artifact, dest);
}
String copyDest = new File(destFileName).getAbsolutePath();
dest.add(copyDest);
Set conflicts = (Set)conflictsMap.get(copyDest);
Set conflictsConf = (Set)conflictsConfMap.get(copyDest);
if (conflicts == null) {
conflicts = new HashSet();
conflictsMap.put(copyDest, conflicts);
}
if (conflictsConf == null) {
conflictsConf = new HashSet();
conflictsConfMap.put(copyDest, conflictsConf);
}
conflicts.add(artifact);
conflictsConf.add(conf);
}
}
// resolve conflicts if any
for (Iterator iter = conflictsMap.keySet().iterator(); iter.hasNext();) {
String copyDest = (String)iter.next();
Set artifacts = (Set)conflictsMap.get(copyDest);
Set conflictsConfs = (Set)conflictsConfMap.get(copyDest);
if (artifacts.size() > 1) {
List artifactsList = new ArrayList(artifacts);
// conflicts battle is resolved by a sort using a conflict resolving policy comparator
// which consider as greater a winning artifact
Collections.sort(artifactsList, getConflictResolvingPolicy());
// after the sort, the winning artifact is the greatest one, i.e. the last one
Message.info("\tconflict on "+copyDest+" in "+conflictsConfs+": "+((Artifact)artifactsList.get(artifactsList.size() -1)).getModuleRevisionId().getRevision()+" won");
// we now iterate over the list beginning with the artifact preceding the winner,
// and going backward to the least artifact
for (int i=artifactsList.size() - 2; i >=0; i
Artifact looser = (Artifact)artifactsList.get(i);
Message.verbose("\t\tremoving conflict looser artifact: "+looser);
// for each loser, we remove the pair (loser - copyDest) in the artifactsToCopy map
Set dest = (Set)artifactsToCopy.get(looser);
dest.remove(copyDest);
if (dest.isEmpty()) {
artifactsToCopy.remove(looser);
}
}
}
}
// do retrieve
int targetsCopied = 0;
int targetsUpToDate = 0;
for (Iterator iter = artifactsToCopy.keySet().iterator(); iter.hasNext();) {
Artifact artifact = (Artifact)iter.next();
File archive = "ivy".equals(artifact.getType())? getIvyFileInCache(cache, artifact.getModuleRevisionId()):getArchiveFileInCache(cache, artifact);
Set dest = (Set)artifactsToCopy.get(artifact);
Message.verbose("\tretrieving "+archive);
for (Iterator it2 = dest.iterator(); it2.hasNext();) {
File destFile = new File((String)it2.next());
if (!_checkUpToDate || !upToDate(archive, destFile)) {
Message.verbose("\t\tto "+destFile);
FileUtil.copy(archive, destFile, null);
targetsCopied++;
} else {
Message.verbose("\t\tto "+destFile+" [NOT REQUIRED]");
targetsUpToDate++;
}
}
}
Message.info("\t"+targetsCopied+" artifacts copied, "+targetsUpToDate+" already retrieved");
Message.verbose("\tretrieve done ("+(System.currentTimeMillis()-start)+"ms)");
} catch (Exception ex) {
IllegalStateException ise = new IllegalStateException("problem during retrieve of "+moduleId);
ise.initCause(ex);
throw ise;
}
}
private boolean upToDate(File source, File target) {
if (!target.exists()) {
return false;
}
return source.lastModified() == target.lastModified();
}
/**
* The returned comparator should consider greater the artifact which
* gains the conflict battle.
* This is used only during retrieve... prefer resolve conflict manager
* to resolve conflicts.
* @return
*/
private Comparator getConflictResolvingPolicy() {
return new Comparator() {
// younger conflict resolving policy
public int compare(Object o1, Object o2) {
Artifact a1 = (Artifact)o1;
Artifact a2 = (Artifact)o2;
if (a1.getPublicationDate().after(a2.getPublicationDate())) {
// a1 is after a2 <=> a1 is younger than a2 <=> a1 wins the conflict battle
return +1;
} else if (a1.getPublicationDate().before(a2.getPublicationDate())) {
// a1 is before a2 <=> a2 is younger than a1 <=> a2 wins the conflict battle
return -1;
} else {
return 0;
}
}
};
}
// PUBLISH
public void deliver(ModuleRevisionId mrid,
String revision,
File cache,
String destIvyPattern,
String status,
Date pubdate,
PublishingDependencyRevisionResolver pdrResolver,
boolean validate
) throws IOException, ParseException {
deliver(mrid, revision, cache, destIvyPattern, status, pubdate, pdrResolver, validate, true);
}
public void deliver(ModuleRevisionId mrid,
String revision,
File cache,
String destIvyPattern,
String status,
Date pubdate,
PublishingDependencyRevisionResolver pdrResolver,
boolean validate,
boolean resolveDynamicRevisions) throws IOException, ParseException {
Message.info(":: delivering :: "+mrid+" :: "+revision+" :: "+status+" :: "+pubdate);
Message.verbose("\tvalidate = "+validate);
long start = System.currentTimeMillis();
destIvyPattern = substitute(destIvyPattern);
// 1) find the resolved module descriptor in cache
File ivyFile = getResolvedIvyFileInCache(cache, mrid);
if (!ivyFile.exists()) {
throw new IllegalStateException("ivy file not found in cache for "+mrid+": please resolve dependencies before publishing ("+ivyFile+")");
}
ModuleDescriptor md = null;
URL ivyFileURL = null;
try {
ivyFileURL = ivyFile.toURL();
md = XmlModuleDescriptorParser.getInstance().parseDescriptor(this, ivyFileURL, validate);
md.setResolvedModuleRevisionId(new ModuleRevisionId(mrid.getModuleId(), revision));
md.setResolvedPublicationDate(pubdate);
} catch (MalformedURLException e) {
throw new RuntimeException("malformed url obtained for file "+ivyFile);
} catch (ParseException e) {
throw new IllegalStateException("bad ivy file in cache for "+mrid+": please clean and resolve again");
}
// 2) parse resolvedRevisions From properties file
Map resolvedRevisions = new HashMap(); // Map (ModuleId -> String revision)
Map dependenciesStatus = new HashMap(); // Map (ModuleId -> String status)
File ivyProperties = getResolvedIvyPropertiesInCache(cache, mrid);
if (!ivyProperties.exists()) {
throw new IllegalStateException("ivy properties not found in cache for "+mrid+": please resolve dependencies before publishing ("+ivyFile+")");
}
Properties props = new Properties();
props.load(new FileInputStream(ivyProperties));
for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
String mid = (String)iter.next();
String[] parts = props.getProperty(mid).split(" ");
if (resolveDynamicRevisions) {
resolvedRevisions.put(ModuleId.decode(mid), parts[0]);
}
String depStatus = props.getProperty(mid);
dependenciesStatus.put(ModuleId.decode(mid), parts[1]);
}
// 3) use pdrResolver to resolve dependencies info
Map resolvedDependencies = new HashMap(); // Map (ModuleId -> String revision)
DependencyDescriptor[] dependencies = md.getDependencies();
for (int i = 0; i < dependencies.length; i++) {
String rev = (String)resolvedRevisions.get(dependencies[i].getDependencyId());
if (rev == null) {
rev = dependencies[i].getDependencyRevisionId().getRevision();
}
String depStatus = (String)dependenciesStatus.get(dependencies[i].getDependencyId());
resolvedDependencies.put(dependencies[i].getDependencyId(),
pdrResolver.resolve(md, status,
new ModuleRevisionId(dependencies[i].getDependencyId(), rev),
depStatus));
}
// 4) copy the source resolved ivy to the destination specified,
// updating status, revision and dependency revisions obtained by
// PublishingDependencyRevisionResolver
String publishedIvy = IvyPatternHelper.substitute(destIvyPattern, md.getResolvedModuleRevisionId());
Message.info("\tdelivering ivy file to "+publishedIvy);
try {
XmlModuleDescriptorUpdater.update(this, ivyFileURL,
new File(publishedIvy),
resolvedDependencies, status, revision, pubdate, null, true);
} catch (SAXException ex) {
throw new IllegalStateException("bad ivy file in cache for "+mrid+": please clean and resolve again");
}
Message.verbose("\tdeliver done ("+(System.currentTimeMillis()-start)+"ms)");
}
/**
*
* @param pubrevision
* @param resolverName the name of a resolver to use for publication
* @param srcArtifactPattern a pattern to find artifacts to publish with the given resolver
* @param srcIvyPattern a pattern to find ivy file to publish, null if ivy file should not be published
* @return a collection of missing artifacts (those that are not published)
* @throws ParseException
*/
public Collection publish(ModuleRevisionId mrid, String pubrevision, File cache, String srcArtifactPattern, String resolverName, String srcIvyPattern, boolean validate) throws IOException {
return publish(mrid, pubrevision, cache, srcArtifactPattern, resolverName, srcIvyPattern, validate, false);
}
/**
*
* @param pubrevision
* @param resolverName the name of a resolver to use for publication
* @param srcArtifactPattern a pattern to find artifacts to publish with the given resolver
* @param srcIvyPattern a pattern to find ivy file to publish, null if ivy file should not be published
* @return a collection of missing artifacts (those that are not published)
* @throws ParseException
*/
public Collection publish(ModuleRevisionId mrid, String pubrevision, File cache, String srcArtifactPattern, String resolverName, String srcIvyPattern, boolean validate, boolean overwrite) throws IOException {
Message.info(":: publishing :: "+mrid);
Message.verbose("\tvalidate = "+validate);
long start = System.currentTimeMillis();
srcArtifactPattern = substitute(srcArtifactPattern);
srcIvyPattern = substitute(srcIvyPattern);
// 1) find the resolved module descriptor in cache
File ivyFile = getResolvedIvyFileInCache(cache, mrid);
if (!ivyFile.exists()) {
throw new IllegalStateException("ivy file not found in cache for "+mrid+": please resolve dependencies before publishing ("+ivyFile+")");
}
DependencyResolver resolver = getResolver(resolverName);
if (resolver == null) {
throw new IllegalArgumentException("unknown resolver "+resolverName);
}
ModuleDescriptor md = null;
URL ivyFileURL = null;
try {
ivyFileURL = ivyFile.toURL();
md = XmlModuleDescriptorParser.getInstance().parseDescriptor(this, ivyFileURL, false);
md.setResolvedModuleRevisionId(new ModuleRevisionId(mrid.getModuleId(), pubrevision));
} catch (MalformedURLException e) {
throw new RuntimeException("malformed url obtained for file "+ivyFile);
} catch (ParseException e) {
throw new IllegalStateException("bad ivy file in cache for "+mrid+": please clean cache and resolve again");
}
// collect all declared artifacts of this module
Collection missing = publish(md, resolver, srcArtifactPattern, srcIvyPattern, overwrite);
Message.verbose("\tpublish done ("+(System.currentTimeMillis()-start)+"ms)");
return missing;
}
private Collection publish(ModuleDescriptor md, DependencyResolver resolver, String srcArtifactPattern, String srcIvyPattern, boolean overwrite) throws IOException {
Collection missing = new ArrayList();
Set artifactsSet = new HashSet();
String[] confs = md.getConfigurationsNames();
for (int i = 0; i < confs.length; i++) {
Artifact[] artifacts = md.getArtifacts(confs[i]);
for (int j = 0; j < artifacts.length; j++) {
artifactsSet.add(artifacts[j]);
}
}
// for each declared published artifact in this descriptor, do:
for (Iterator iter = artifactsSet.iterator(); iter.hasNext();) {
Artifact artifact = (Artifact) iter.next();
// 1) copy the artifact using src pattern and resolver
if (!publish(artifact, srcArtifactPattern, resolver, overwrite)) {
missing.add(artifact);
}
}
if (srcIvyPattern != null) {
Artifact artifact = new MDArtifact(md, "ivy", "ivy", "xml");
if (!publish(artifact, srcIvyPattern, resolver, overwrite)) {
missing.add(artifact);
}
}
return missing;
}
private boolean publish(Artifact artifact, String srcArtifactPattern, DependencyResolver resolver, boolean overwrite) throws IOException {
File src = new File(IvyPatternHelper.substitute(srcArtifactPattern, artifact));
if (src.exists()) {
resolver.publish(artifact, src, overwrite);
return true;
} else {
Message.info("missing artifact "+artifact+": "+src+" file does not exist");
return false;
}
}
// SORT
public static List sortNodes(Collection nodes) {
return ModuleDescriptorSorter.sortNodes(nodes);
}
/**
* Sorts the given ModuleDescriptors from the less dependent to the more dependent.
* This sort ensures that a ModuleDescriptor is always found in the list before all
* ModuleDescriptors depending directly on it.
* @param moduleDescriptors a Collection of ModuleDescriptor to sort
* @return a List of sorted ModuleDescriptors
*/
public static List sortModuleDescriptors(Collection moduleDescriptors) {
return ModuleDescriptorSorter.sortModuleDescriptors(moduleDescriptors);
}
// CACHE
public File getResolvedIvyFileInCache(File cache, ModuleRevisionId mrid) {
return new File(cache, IvyPatternHelper.substitute(_cacheResolvedIvyPattern, mrid.getOrganisation(), mrid.getName(), mrid.getRevision(), "ivy", "ivy", "xml"));
}
public File getResolvedIvyPropertiesInCache(File cache, ModuleRevisionId mrid) {
return new File(cache, IvyPatternHelper.substitute(_cacheResolvedIvyPropertiesPattern, mrid.getOrganisation(), mrid.getName(), mrid.getRevision(), "ivy", "ivy", "xml"));
}
public File getIvyFileInCache(File cache, ModuleRevisionId mrid) {
return new File(cache, IvyPatternHelper.substitute(_cacheIvyPattern, mrid.getOrganisation(), mrid.getName(), mrid.getRevision(), "ivy", "ivy", "xml"));
}
public File getArchiveFileInCache(File cache, Artifact artifact) {
return new File(cache, getArchivePathInCache(artifact));
}
public File getArchiveFileInCache(File cache, String organisation, String module, String revision, String artifact, String type, String ext) {
return new File(cache, getArchivePathInCache(organisation, module, revision, artifact, type, ext));
}
public String getArchivePathInCache(Artifact artifact) {
return getArchivePathInCache(
artifact.getModuleRevisionId().getOrganisation(),
artifact.getModuleRevisionId().getName(),
artifact.getModuleRevisionId().getRevision(),
artifact.getName(),
artifact.getType(),
artifact.getExt());
}
public String getArchivePathInCache(String organisation, String module, String revision, String artifact, String type, String ext) {
return IvyPatternHelper.substitute(_cacheArtifactPattern, organisation, module, revision, artifact, type, ext);
}
public static String getLocalHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "localhost";
}
}
public OrganisationEntry[] listOrganisationEntries() {
List entries = new ArrayList();
for (Iterator iter = _resolversMap.values().iterator(); iter.hasNext();) {
DependencyResolver resolver = (DependencyResolver)iter.next();
entries.addAll(Arrays.asList(resolver.listOrganisations()));
}
return (OrganisationEntry[])entries.toArray(new OrganisationEntry[entries.size()]);
}
public String[] listOrganisations() {
Collection orgs = new HashSet();
for (Iterator iter = _resolversMap.values().iterator(); iter.hasNext();) {
DependencyResolver resolver = (DependencyResolver)iter.next();
OrganisationEntry[] entries = resolver.listOrganisations();
if (entries != null) {
for (int i = 0; i < entries.length; i++) {
if (entries[i] != null) {
orgs.add(entries[i].getOrganisation());
}
}
}
}
return (String[])orgs.toArray(new String[orgs.size()]);
}
public ModuleEntry[] listModuleEntries(OrganisationEntry org) {
List entries = new ArrayList();
for (Iterator iter = _resolversMap.values().iterator(); iter.hasNext();) {
DependencyResolver resolver = (DependencyResolver)iter.next();
entries.addAll(Arrays.asList(resolver.listModules(org)));
}
return (ModuleEntry[])entries.toArray(new ModuleEntry[entries.size()]);
}
public String[] listModules(String org) {
List mods = new ArrayList();
for (Iterator iter = _resolversMap.values().iterator(); iter.hasNext();) {
DependencyResolver resolver = (DependencyResolver)iter.next();
ModuleEntry[] entries = resolver.listModules(new OrganisationEntry(resolver, org));
if (entries != null) {
for (int i = 0; i < entries.length; i++) {
if (entries[i] != null) {
mods.add(entries[i].getModule());
}
}
}
}
return (String[])mods.toArray(new String[mods.size()]);
}
public RevisionEntry[] listRevisionEntries(ModuleEntry module) {
List entries = new ArrayList();
for (Iterator iter = _resolversMap.values().iterator(); iter.hasNext();) {
DependencyResolver resolver = (DependencyResolver)iter.next();
entries.addAll(Arrays.asList(resolver.listRevisions(module)));
}
return (RevisionEntry[])entries.toArray(new RevisionEntry[entries.size()]);
}
public String[] listRevisions(String org, String module) {
List revs = new ArrayList();
for (Iterator iter = _resolversMap.values().iterator(); iter.hasNext();) {
DependencyResolver resolver = (DependencyResolver)iter.next();
RevisionEntry[] entries = resolver.listRevisions(new ModuleEntry(new OrganisationEntry(resolver, org), module));
if (entries != null) {
for (int i = 0; i < entries.length; i++) {
if (entries[i] != null) {
revs.add(entries[i].getRevision());
}
}
}
}
return (String[])revs.toArray(new String[revs.size()]);
}
/**
* Returns true if the name should be ignored in listing
* @param name
* @return
*/
public boolean listingIgnore(String name) {
return _listingIgnore.contains(name);
}
/**
* Filters the names list by removing all names that should be ignored
* as defined by the listing ignore list
* @param names
*/
public void filterIgnore(Collection names) {
names.removeAll(_listingIgnore);
}
public boolean isCheckUpToDate() {
return _checkUpToDate;
}
public void setCheckUpToDate(boolean checkUpToDate) {
_checkUpToDate = checkUpToDate;
}
public String getCacheArtifactPattern() {
return _cacheArtifactPattern;
}
public void setCacheArtifactPattern(String cacheArtifactPattern) {
_cacheArtifactPattern = cacheArtifactPattern;
}
public String getCacheIvyPattern() {
return _cacheIvyPattern;
}
public void setCacheIvyPattern(String cacheIvyPattern) {
_cacheIvyPattern = cacheIvyPattern;
}
public boolean doValidate() {
return _validate;
}
public void setValidate(boolean validate) {
_validate = validate;
}
public String getVariable(String name) {
String val = (String)_variables.get(name);
return val==null?val:substitute(val);
}
public ConflictManager getDefaultConflictManager() {
if (_defaultConflictManager == null) {
_defaultConflictManager = new LatestConflictManager(getDefaultLatestStrategy());
}
return _defaultConflictManager;
}
public void setDefaultConflictManager(ConflictManager defaultConflictManager) {
_defaultConflictManager = defaultConflictManager;
}
public LatestStrategy getDefaultLatestStrategy() {
if (_defaultLatestStrategy == null) {
_defaultLatestStrategy = new LatestRevisionStrategy();
}
return _defaultLatestStrategy;
}
public void setDefaultLatestStrategy(LatestStrategy defaultLatestStrategy) {
_defaultLatestStrategy = defaultLatestStrategy;
}
private EventListenerList _listeners = new EventListenerList();
private boolean _logNotConvertedExclusionRule;
public void addTransferListener(TransferListener listener) {
_listeners.add(TransferListener.class, listener);
}
public void removeTransferListener(TransferListener listener) {
_listeners.remove(TransferListener.class, listener);
}
public boolean hasTransferListener(TransferListener listener) {
return Arrays.asList(_listeners.getListeners(TransferListener.class)).contains(listener);
}
protected void fireTransferEvent(TransferEvent evt) {
Object[] listeners = _listeners.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TransferListener.class) {
((TransferListener)listeners[i+1]).transferProgress(evt);
}
}
}
public void addIvyListener(IvyListener listener) {
_listeners.add(IvyListener.class, listener);
}
public void removeIvyListener(IvyListener listener) {
_listeners.remove(IvyListener.class, listener);
}
public boolean hasIvyListener(IvyListener listener) {
return Arrays.asList(_listeners.getListeners(IvyListener.class)).contains(listener);
}
public void fireIvyEvent(IvyEvent evt) {
Object[] listeners = _listeners.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==IvyListener.class) {
((IvyListener)listeners[i+1]).progress(evt);
}
}
}
public void transferProgress(TransferEvent evt) {
fireTransferEvent(evt);
fireIvyEvent(evt);
}
public boolean isUseRemoteConfig() {
return _useRemoteConfig;
}
public void setUseRemoteConfig(boolean useRemoteConfig) {
_useRemoteConfig = useRemoteConfig;
}
public DependencyResolver getDictatorResolver() {
return _dictatorResolver;
}
public void setDictatorResolver(DependencyResolver dictatorResolver) {
_dictatorResolver = dictatorResolver;
}
/**
* WARNING: Replace all current ivy variables by the given Map.
* Should be used only when restoring variables.
*
* Thr given Map is not copied, but stored by reference.
* @param variables
*/
public void setVariables(Map variables) {
if (variables == null) {
throw new NullPointerException("variables shouldn't be null");
}
_variables = variables;
}
public static URL getDefaultConfigurationURL() {
return Ivy.class.getResource("conf/ivyconf.xml");
}
/**
* Saves the information of which resolver was used to resolve a md,
* so that this info can be retrieve later (even after a jvm restart)
* by getSavedResolverName(ModuleDescriptor md)
* @param md the module descriptor resolved
* @param name resolver name
*/
public void saveResolver(File cache, ModuleDescriptor md, String name) {
PropertiesFile cdf = getCachedDataFile(cache, md);
cdf.setProperty("resolver", name);
cdf.save();
}
private String getSavedResolverName(File cache, ModuleDescriptor md) {
PropertiesFile cdf = getCachedDataFile(cache, md);
return cdf.getProperty("resolver");
}
private PropertiesFile getCachedDataFile(File cache, ModuleDescriptor md) {
return new PropertiesFile(new File(cache, IvyPatternHelper.substitute(getCacheDataFilePattern(), md.getResolvedModuleRevisionId())), "ivy cached data file for "+md.getResolvedModuleRevisionId());
}
public String getCacheDataFilePattern() {
return _cacheDataFilePattern;
}
public boolean logModuleWhenFound() {
String var = getVariable("ivy.log.module.when.found");
return var == null || Boolean.valueOf(var).booleanValue();
}
public boolean logResolvedRevision() {
String var = getVariable("ivy.log.resolved.revision");
return var == null || Boolean.valueOf(var).booleanValue();
}
public boolean logNotConvertedExclusionRule() {
return _logNotConvertedExclusionRule;
}
public void setLogNotConvertedExclusionRule(boolean logNotConvertedExclusionRule) {
_logNotConvertedExclusionRule = logNotConvertedExclusionRule;
}
}
|
package net.runelite.client.plugins.lowmemory;
import javax.inject.Inject;
import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.events.GameStateChanged;
import net.runelite.client.callback.ClientThread;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
@PluginDescriptor(
name = "Low Detail",
description = "Turn off ground decorations and certain textures, reducing memory usage",
tags = {"memory", "usage", "ground", "decorations"},
enabledByDefault = false
)
public class LowMemoryPlugin extends Plugin
{
@Inject
private Client client;
@Inject
private ClientThread clientThread;
@Override
protected void startUp()
{
if (client.getGameState() == GameState.LOGGED_IN)
{
clientThread.invoke(() -> client.changeMemoryMode(true));
}
}
@Override
protected void shutDown()
{
clientThread.invoke(() -> client.changeMemoryMode(false));
}
@Subscribe
public void onGameStateChanged(GameStateChanged event)
{
// When the client starts it initializes the texture size based on the memory mode setting.
// Don't set low memory before the login screen is ready to prevent loading the low detail textures,
// which breaks the gpu plugin due to it requiring the 128x128px textures
if (event.getGameState() == GameState.LOGIN_SCREEN)
{
client.changeMemoryMode(true);
}
}
}
|
package org.hisp.dhis.system.database;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.commons.util.SystemUtils;
import org.hisp.dhis.external.conf.ConfigurationKey;
import org.hisp.dhis.external.conf.DhisConfigurationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Lars Helge Overland
*/
public class HibernateDatabaseInfoProvider
implements DatabaseInfoProvider
{
private static final String POSTGIS_MISSING_ERROR = "Postgis extension is not installed. Execute \"CREATE EXTENSION postgis;\" as a superuser and start the application again.";
private static final Log log = LogFactory.getLog( HibernateDatabaseInfoProvider.class );
private static final String DEL_A = "/";
private static final String DEL_B = ":";
private static final String DEL_C = "?";
private static final String POSTGRES_REGEX = "^([a-zA-Z_-]+ \\d+\\.+\\d+)? .*$";
private static final Pattern PATTERN = Pattern.compile( POSTGRES_REGEX );
private DatabaseInfo info;
// Dependencies
@Autowired
private DhisConfigurationProvider config;
@Autowired
private JdbcTemplate jdbcTemplate;
public void init()
{
checkDatabaseConnectivity();
boolean spatialSupport = isSpatialSupport();
// Check if postgis is installed. If not, fail startup.
if ( !spatialSupport && !SystemUtils.isTestRun() )
{
log.error( POSTGIS_MISSING_ERROR );
throw new IllegalStateException( POSTGIS_MISSING_ERROR );
}
String url = config.getProperty( ConfigurationKey.CONNECTION_URL );
String user = config.getProperty( ConfigurationKey.CONNECTION_USERNAME );
String password = config.getProperty( ConfigurationKey.CONNECTION_PASSWORD );
info = new DatabaseInfo();
info.setName( getNameFromConnectionUrl( url ) );
info.setUser( user );
info.setPassword( password );
info.setUrl( url );
info.setSpatialSupport( spatialSupport );
info.setDatabaseVersion( getDatabaseVersion() );
}
// DatabaseInfoProvider implementation
@Override
public DatabaseInfo getDatabaseInfo()
{
return info;
}
@Override
public boolean isInMemory()
{
return info.getUrl() != null && info.getUrl().contains( ":mem:" );
}
@Override
public String getNameFromConnectionUrl( String url )
{
String name = null;
if ( url != null && url.lastIndexOf( DEL_B ) != -1 )
{
int startPos = url.lastIndexOf( DEL_A ) != -1 ? url.lastIndexOf( DEL_A ) : url.lastIndexOf( DEL_B );
int endPos = url.lastIndexOf( DEL_C ) != -1 ? url.lastIndexOf( DEL_C ) : url.length();
name = url.substring( startPos + 1, endPos );
}
return name;
}
// Supportive methods
/**
* Attempts to create a spatial database extension. Checks if spatial operations
* are supported.
*/
private String getDatabaseVersion()
{
try
{
String version = jdbcTemplate.queryForObject( "select version();", String.class );
Matcher matcher = PATTERN.matcher( version );
if( matcher.find() )
{
version = matcher.group( 1 );
}
return version;
}
catch ( Exception ex )
{
return "";
}
}
private void checkDatabaseConnectivity()
{
jdbcTemplate.queryForObject( "select 'checking db connection';", String.class );
}
private boolean isSpatialSupport()
{
try
{
jdbcTemplate.execute( "create extension postgis;" );
}
catch ( Exception ex )
{
}
try
{
String version = jdbcTemplate.queryForObject( "select postgis_full_version();", String.class );
return version != null;
}
catch ( Exception ex )
{
log.error( "Exception when checking postgis version:", ex );
return false;
}
}
}
|
package org.dominokit.domino.apt.client.processors.handlers;
import com.squareup.javapoet.*;
import org.dominokit.domino.api.client.annotations.Path;
import org.dominokit.domino.api.client.annotations.RequestSender;
import org.dominokit.domino.api.client.request.AbstractArrayResponseRequestSender;
import org.dominokit.domino.api.client.request.AbstractSingleResponseRequestSender;
import org.dominokit.domino.api.shared.history.HistoryToken;
import org.dominokit.domino.api.shared.history.StateHistoryToken;
import org.dominokit.domino.api.shared.request.ArrayResponse;
import org.dominokit.domino.api.shared.request.VoidRequest;
import org.dominokit.domino.api.shared.request.VoidResponse;
import org.dominokit.domino.apt.commons.DominoTypeBuilder;
import org.dominokit.domino.apt.commons.FullClassName;
import org.dominokit.domino.apt.commons.JavaSourceWriter;
import org.dominokit.domino.apt.commons.ProcessorElement;
import org.dominokit.jacksonapt.AbstractObjectMapper;
import javax.lang.model.element.Modifier;
import javax.tools.Diagnostic;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class RequestSenderSourceWriter extends JavaSourceWriter {
private final String serviceRoot;
private final String method;
private final String path;
private final ClassName requestType;
private final ClassName responseType;
private final int[] successCodes;
private final boolean arrayResponse;
public RequestSenderSourceWriter(ProcessorElement processorElement, FullClassName request, FullClassName response, FullClassName fullSuperClassName) {
super(processorElement);
this.path = processorElement.getAnnotation(Path.class).value();
this.serviceRoot = processorElement.getAnnotation(Path.class).serviceRoot();
this.method = processorElement.getAnnotation(Path.class).method();
this.successCodes = processorElement.getAnnotation(Path.class).successCodes();
requestType = ClassName.get(request.asPackage(), request.asSimpleName());
if (response.asImport().equals(new FullClassName(ArrayResponse.class.getCanonicalName()).asImport())) {
FullClassName actualResponse = new FullClassName(fullSuperClassName.allImports().get(3));
responseType = ClassName.get(actualResponse.asPackage(), actualResponse.asSimpleName());
this.arrayResponse = true;
} else {
responseType = ClassName.get(response.asPackage(), response.asSimpleName());
this.arrayResponse = false;
}
}
@Override
public String write() throws IOException {
TypeSpec.Builder senderBuilder = makeSenderBuilder();
if (hasServiceRoot()) {
senderBuilder.addField(addServiceRoot());
}
senderBuilder
.addField(addPathField())
.addField(addSuccessCodesField());
senderBuilder.addMethod(MethodSpec.methodBuilder("getPath")
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.returns(String.class)
.addStatement("return PATH")
.build());
senderBuilder.addMethod(MethodSpec.methodBuilder("getSuccessCodes")
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.returns(Integer[].class)
.addStatement("return SUCCESS_CODES")
.build());
senderBuilder.addMethod(MethodSpec.methodBuilder("getRequestMapper")
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.returns(ParameterizedTypeName.get(ClassName.get(AbstractObjectMapper.class), requestType))
.addCode(getRequestMapper().build())
.build());
senderBuilder.addMethod(MethodSpec.methodBuilder("getResponseMapper")
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.returns(ParameterizedTypeName.get(ClassName.get(AbstractObjectMapper.class), responseType))
.addCode(getResponseMapper().build())
.build());
senderBuilder.addMethod(MethodSpec.methodBuilder("getMethod")
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.returns(String.class)
.addStatement("return \""+method+"\"")
.build());
senderBuilder.addMethod(MethodSpec.methodBuilder("getCustomRoot")
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.returns(String.class)
.addStatement(hasServiceRoot()?"return SERVICE_ROOT":"return null")
.build());
senderBuilder.addMethod(MethodSpec.methodBuilder("isVoidResponse")
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.returns(boolean.class)
.addStatement(isVoidResponse()?"return true":"return false")
.build());
senderBuilder.addMethod(MethodSpec.methodBuilder("isVoidRequest")
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.returns(boolean.class)
.addStatement(isVoidRequest()?"return true":"return false")
.build());
senderBuilder.addMethod(new ReplaceParametersMethodBuilder().build());
if(arrayResponse){
senderBuilder.addMethod(MethodSpec.methodBuilder("initArray")
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.returns(ArrayTypeName.of(responseType))
.addParameter(int.class, "length")
.addStatement("return new $T[length]", responseType)
.build());
}
StringBuilder asString = new StringBuilder();
JavaFile.builder(processorElement.elementPackage(), senderBuilder.build()).skipJavaLangImports(true).build().writeTo(asString);
return asString.toString();
}
private CodeBlock.Builder getRequestMapper() {
CodeBlock.Builder builder = CodeBlock.builder();
if (isVoidRequest()) {
builder.addStatement("return null");
}else{
builder.addStatement("return $T.INSTANCE", ClassName.get(requestType.packageName(), requestType.simpleName() + "_MapperImpl"));
}
return builder;
}
private CodeBlock.Builder getResponseMapper() {
CodeBlock.Builder builder = CodeBlock.builder();
if (isVoidResponse()) {
builder.addStatement("return null");
}else{
builder.addStatement("return $T.INSTANCE", ClassName.get(responseType.packageName(), responseType.simpleName() + "_MapperImpl"));
}
return builder;
}
private boolean isVoidRequest() {
return requestType.compareTo(ClassName.get(VoidRequest.class)) == 0;
}
private boolean isVoidResponse() {
return responseType.compareTo(ClassName.get(VoidResponse.class)) == 0;
}
private TypeSpec.Builder makeSenderBuilder() {
AnnotationSpec.Builder requestSenderAnnotationBuilder = AnnotationSpec.builder(RequestSender.class)
.addMember("value", CodeBlock.builder().add("$T.class", TypeName.get(processorElement.getElement().asType())).build());
if (hasServiceRoot()) {
requestSenderAnnotationBuilder.addMember("customServiceRoot", "true");
}
return DominoTypeBuilder.build(processorElement.simpleName() + "Sender", RequestPathProcessor.class)
.addAnnotation(requestSenderAnnotationBuilder.build())
.superclass(ParameterizedTypeName.get(ClassName.get(arrayResponse ? AbstractArrayResponseRequestSender.class : AbstractSingleResponseRequestSender.class), requestType, responseType));
}
private FieldSpec addServiceRoot() {
return FieldSpec.builder(String.class, "SERVICE_ROOT")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.initializer("\"" + serviceRoot + "\"").build();
}
private FieldSpec addPathField() {
return FieldSpec.builder(String.class, "PATH")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.initializer("\"" + path + "\"").build();
}
private FieldSpec addSuccessCodesField() {
return FieldSpec.builder(Integer[].class, "SUCCESS_CODES")
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
.initializer("new Integer[]{" + getSuccessCodesString() + "}").build();
}
private String getSuccessCodesString() {
return IntStream.of(successCodes)
.mapToObj(operand -> operand + "")
.collect(Collectors.joining(","));
}
private boolean hasServiceRoot() {
return !serviceRoot.trim().isEmpty();
}
private class ReplaceParametersMethodBuilder {
private MethodSpec build() {
MethodSpec.Builder replaceParametersBuilder = MethodSpec.methodBuilder("replaceRequestParameters")
.addAnnotation(Override.class)
.addModifiers(Modifier.PROTECTED)
.returns(String.class)
.addParameter(HistoryToken.class, "token")
.addParameter(requestType, "request");
try {
CodeBlock.Builder replaceBuilder = CodeBlock.builder()
.beginControlFlow("if (path.contains(\":\"))")
.addStatement("$T processedPath = path", String.class);
StateHistoryToken token = new StateHistoryToken(path);
token.paths()
.stream()
.filter(tokenPath -> tokenPath.startsWith(":"))
.forEach(tokenPath -> replaceBuilder.addStatement("token.replacePath(\"" + tokenPath + "\", " + convertParameterToGetter(tokenPath.replace(":","")) + "+\"\")", Objects.class));
token.queryParameters()
.entrySet()
.stream()
.filter(entry -> entry.getValue().startsWith(":"))
.forEach(entry -> {
replaceBuilder.addStatement("token.replaceParameter(\"" + entry.getKey() + "\", \"" + entry.getKey() + "\", " + convertParameterToGetter(entry.getValue().replace(":","")) + "+\"\")", Objects.class);
});
token.fragments()
.stream()
.filter(fragment -> fragment.startsWith(":"))
.forEach(fragment -> replaceBuilder.addStatement("token.replaceFragment(\"" + fragment + "\", " + convertParameterToGetter(fragment.replace(":","")) + "+\"\")", Objects.class));
replaceBuilder.addStatement("return token.value()");
replaceBuilder.endControlFlow();
replaceParametersBuilder
.addCode(CodeBlock.builder()
.add(replaceBuilder.build())
.addStatement("return token.value()")
.build());
return replaceParametersBuilder.build();
} catch (Exception ex) {
handleError(ex);
}
return replaceParametersBuilder.build();
}
private String convertParameterToGetter(String parameter) {
String names = parameter
.replace("{", "")
.replace("}", "");
String[] fieldsNames = names.contains(".") ? names.split("\\.") : new String[]{names};
List<String> gettersString = Arrays.asList(fieldsNames)
.stream()
.map(s -> "get" + s.replaceFirst(s.charAt(0) + "", (s.charAt(0) + "").toUpperCase()) + "()")
.collect(Collectors.toList());
String result = getterWithNullCheck(gettersString, 1);
return result;
}
private String getterWithNullCheck(List<String> getters, int upTo) {
if (upTo <= getters.size()) {
return "$1T.isNull(request." + getters.subList(0, upTo).stream().collect(Collectors.joining(".")) + ")?null:(" + getterWithNullCheck(getters, ++upTo) + ")";
} else {
return "request." + getters.subList(0, upTo - 1).stream().collect(Collectors.joining("."));
}
}
}
protected void handleError(Exception e) {
StringWriter out = new StringWriter();
e.printStackTrace(new PrintWriter(out));
processorElement.getMessager().printMessage(Diagnostic.Kind.ERROR, "error while creating source file " + out.getBuffer().toString());
}
}
|
package org.springframework.samples.petclinic.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContextException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.object.MappingSqlQuery;
import org.springframework.jdbc.object.SqlUpdate;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.samples.petclinic.Clinic;
import org.springframework.samples.petclinic.Entity;
import org.springframework.samples.petclinic.Owner;
import org.springframework.samples.petclinic.Pet;
import org.springframework.samples.petclinic.PetType;
import org.springframework.samples.petclinic.Specialty;
import org.springframework.samples.petclinic.Vet;
import org.springframework.samples.petclinic.Visit;
import org.springframework.samples.petclinic.util.EntityUtils;
/**
* Base class for JDBC implementations of the Clinic interface.
*
* @author Ken Krebs
* @author Juergen Hoeller
*/
abstract public class AbstractJdbcClinic extends JdbcDaoSupport implements Clinic {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
/** Holds all vets Query Object. */
private VetsQuery vetsQuery;
/** Holds specialties Query Object. */
private SpecialtiesQuery specialtiesQuery;
/** Holds vet specialties Query Object. */
private VetSpecialtiesQuery vetSpecialtiesQuery;
/** Holds owners by name Query Object. */
private OwnersByNameQuery ownersByNameQuery;
/** Holds owner by id Query Object. */
private OwnerQuery ownerQuery;
/** Holds owner Insert Object. */
private OwnerInsert ownerInsert;
/** Holds owner Update Object. */
private OwnerUpdate ownerUpdate;
/** Holds pets by owner Query Object. */
private PetsByOwnerQuery petsByOwnerQuery;
/** Holds pets by owner Query Object. */
private PetQuery petQuery;
/** Holds pet Insert Object. */
private PetInsert petInsert;
/** Holds pet Update Object. */
private PetUpdate petUpdate;
/** Holds pet types Query Object. */
private PetTypesQuery petTypesQuery;
/** Holds visits Query Object. */
private VisitsQuery visitsQuery;
/** Holds Visit Insert Object. */
private VisitInsert visitInsert;
protected void setVetsQuery(VetsQuery vetsQuery) {
this.vetsQuery = vetsQuery;
}
protected void setSpecialtiesQuery(SpecialtiesQuery specialtiesQuery) {
this.specialtiesQuery = specialtiesQuery;
}
protected void setVetSpecialtiesQuery(VetSpecialtiesQuery vetSpecialtiesQuery) {
this.vetSpecialtiesQuery = vetSpecialtiesQuery;
}
protected void setOwnersByNameQuery(OwnersByNameQuery ownersByNameQuery) {
this.ownersByNameQuery = ownersByNameQuery;
}
protected void setOwnerQuery(OwnerQuery ownerQuery) {
this.ownerQuery = ownerQuery;
}
protected void setOwnerInsert(OwnerInsert ownerInsert) {
this.ownerInsert = ownerInsert;
}
protected void setOwnerUpdate(OwnerUpdate ownerUpdate) {
this.ownerUpdate = ownerUpdate;
}
protected void setPetsByOwnerQuery(PetsByOwnerQuery petsByOwnerQuery) {
this.petsByOwnerQuery = petsByOwnerQuery;
}
protected void setPetQuery(PetQuery petQuery) {
this.petQuery = petQuery;
}
protected void setPetInsert(PetInsert petInsert) {
this.petInsert = petInsert;
}
protected void setPetUpdate(PetUpdate petUpdate) {
this.petUpdate = petUpdate;
}
protected void setPetTypesQuery(PetTypesQuery petTypesQuery) {
this.petTypesQuery = petTypesQuery;
}
protected void setVisitsQuery(VisitsQuery visitsQuery) {
this.visitsQuery = visitsQuery;
}
protected void setVisitInsert(VisitInsert visitInsert) {
this.visitInsert = visitInsert;
}
protected void initDao() throws ApplicationContextException {
if (vetsQuery == null)
vetsQuery = new VetsQuery(getDataSource());
if (specialtiesQuery == null)
specialtiesQuery = new SpecialtiesQuery(getDataSource());
if (vetSpecialtiesQuery == null)
vetSpecialtiesQuery = new VetSpecialtiesQuery(getDataSource());
if (petTypesQuery == null)
petTypesQuery = new PetTypesQuery(getDataSource());
if (ownersByNameQuery == null)
ownersByNameQuery = new OwnersByNameQuery(getDataSource());
if (ownerQuery == null)
ownerQuery = new OwnerQuery(getDataSource());
if (ownerInsert == null)
ownerInsert = new OwnerInsert(getDataSource());
if (ownerUpdate == null)
ownerUpdate = new OwnerUpdate(getDataSource());
if (petsByOwnerQuery == null)
petsByOwnerQuery = new PetsByOwnerQuery(getDataSource());
if (petQuery == null)
petQuery = new PetQuery(getDataSource());
if (petInsert == null)
petInsert = new PetInsert(getDataSource());
if (petUpdate == null)
petUpdate = new PetUpdate(getDataSource());
if (visitsQuery == null)
visitsQuery = new VisitsQuery(getDataSource());
if (visitInsert == null)
visitInsert = new VisitInsert(getDataSource());
}
public List getVets() throws DataAccessException {
// establish the Map of all vets
List vets = vetsQuery.execute();
// establish the map of all the possible specialties
List specialties = specialtiesQuery.execute();
// establish each vet's List of specialties
Iterator vi = vets.iterator();
while (vi.hasNext()) {
Vet vet = (Vet) vi.next();
List vetSpecialtiesIds = vetSpecialtiesQuery.execute(vet.getId());
Iterator vsi = vetSpecialtiesIds.iterator();
while (vsi.hasNext()) {
long specialtyId = ((Long) vsi.next()).longValue();
Specialty specialty = (Specialty) EntityUtils.getById(specialties, Specialty.class, specialtyId);
vet.addSpecialty(specialty);
}
}
return vets;
}
public List getPetTypes() throws DataAccessException {
return petTypesQuery.execute();
}
/** Method loads owners plus pets and visits if not already loaded */
public List findOwners(String lastName) throws DataAccessException {
List owners = ownersByNameQuery.execute(lastName + "%");
loadOwnersPetsAndVisits(owners);
return owners;
}
/** Method loads an owner plus pets and visits if not already loaded */
public Owner loadOwner(long id) throws DataAccessException {
Owner owner = (Owner) ownerQuery.findObject(id);
if (owner == null) {
throw new ObjectRetrievalFailureException(Owner.class, new Long(id));
}
loadPetsAndVisits(owner);
return owner;
}
public Pet loadPet(long id) throws DataAccessException {
JdbcPet pet = (JdbcPet) petQuery.findObject(id);
if (pet == null) {
throw new ObjectRetrievalFailureException(Pet.class, new Long(id));
}
Owner owner = loadOwner(pet.getOwnerId());
owner.addPet(pet);
loadVisits(pet);
return pet;
}
public void storeOwner(Owner owner) throws DataAccessException {
if (owner.isNew()) {
ownerInsert.insert(owner);
}
else {
ownerUpdate.update(owner);
}
}
public void storePet(Pet pet) throws DataAccessException {
if (pet.isNew()) {
petInsert.insert(pet);
}
else {
petUpdate.update(pet);
}
}
public void storeVisit(Visit visit) throws DataAccessException {
if (visit.isNew()) {
visitInsert.insert(visit);
}
else {
throw new UnsupportedOperationException("Visit update not supported");
}
}
/**
* Method maps a List of Entitys keyed to their ids
* @param list containing Entitys
* @return Map containing Entitys
*/
protected final Map mapEntityList(List list) {
Map map = new HashMap();
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
Entity entity = (Entity) iterator.next();
map.put(new Long(entity.getId()), entity);
}
return map;
}
/**
* Method to retrieve the <code>Visit</code> data for a <code>Pet</code>.
* @param pet
*/
protected void loadVisits(JdbcPet pet) {
pet.setType((PetType) EntityUtils.getById(getPetTypes(), PetType.class, pet.getTypeId()));
List visits = visitsQuery.execute(pet.getId());
Iterator vi = visits.iterator();
while (vi.hasNext()) {
Visit visit = (Visit) vi.next();
pet.addVisit(visit);
}
}
/**
* Method to retrieve the <code>Pet</code> and <code>Visit</code>
* data for an <code>Owner</code>.
* @param owner
*/
protected void loadPetsAndVisits(Owner owner) {
List pets = petsByOwnerQuery.execute(owner.getId());
Iterator pi = pets.iterator();
while (pi.hasNext()) {
JdbcPet pet = (JdbcPet) pi.next();
owner.addPet(pet);
loadVisits(pet);
}
}
/**
* Method to retrieve a <code>List</code> of <code>Owner</code>s
* and their <code>Pet</code> and <code>Visit</code> data.
* @param owners <code>List</code>.
* @see #loadPetsAndVisits(Owner)
*/
protected void loadOwnersPetsAndVisits(List owners) {
Iterator oi = owners.iterator();
while (oi.hasNext()) {
Owner owner = (Owner) oi.next();
loadPetsAndVisits(owner);
}
}
protected void retrieveIdentity(final Entity entity) {
entity.setId(getJdbcTemplate().queryForLong(getIdentityQuery()));
}
/**
* Return the identity query for the particular database:
* a query that can be used to retrieve the id of a row
* that has just been inserted.
* @return the identity query
*/
protected abstract String getIdentityQuery();
/**
* Base class for all <code>Vet</code> Query Objects.
*/
protected static class VetsQuery extends MappingSqlQuery {
/**
* Creates a new instance of VetsQuery
* @param ds the DataSource to use for the query.
* @param sql Value of the SQL to use for the query.
*/
protected VetsQuery(DataSource ds, String sql) {
super(ds, sql);
}
/**
* Creates a new instance of VetsQuery that returns all vets
* @param ds the DataSource to use for the query.
*/
protected VetsQuery(DataSource ds) {
super(ds, "SELECT id,first_name,last_name FROM vets ORDER BY last_name,first_name");
compile();
}
protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
Vet vet = new Vet();
vet.setId(rs.getLong("id"));
vet.setFirstName(rs.getString("first_name"));
vet.setLastName(rs.getString("last_name"));
return vet;
}
}
/**
* All <code>Vet</code>s specialties Query Object.
*/
protected static class SpecialtiesQuery extends MappingSqlQuery {
/**
* Creates a new instance of SpecialtiesQuery
* @param ds the DataSource to use for the query.
*/
protected SpecialtiesQuery(DataSource ds) {
super(ds, "SELECT id,name FROM specialties");
compile();
}
protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
Specialty specialty = new Specialty();
specialty.setId(rs.getLong("id"));
specialty.setName(rs.getString("name"));
return specialty;
}
}
/**
* A particular <code>Vet</code>'s specialties Query Object.
*/
protected static class VetSpecialtiesQuery extends MappingSqlQuery {
/**
* Creates a new instance of VetSpecialtiesQuery
* @param ds the DataSource to use for the query.
*/
protected VetSpecialtiesQuery(DataSource ds) {
super(ds, "SELECT specialty_id FROM vet_specialties WHERE vet_id=?");
declareParameter(new SqlParameter(Types.INTEGER));
compile();
}
protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
return new Long(rs.getLong("specialty_id"));
}
}
/**
* Abstract base class for all <code>Owner</code> Query Objects.
*/
protected static abstract class OwnersQuery extends MappingSqlQuery {
/**
* Creates a new instance of OwnersQuery
* @param ds the DataSource to use for the query.
* @param sql Value of the SQL to use for the query.
*/
protected OwnersQuery(DataSource ds, String sql) {
super(ds, sql);
}
protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
Owner owner = new Owner();
owner.setId(rs.getLong("id"));
owner.setFirstName(rs.getString("first_name"));
owner.setLastName(rs.getString("last_name"));
owner.setAddress(rs.getString("address"));
owner.setCity(rs.getString("city"));
owner.setTelephone(rs.getString("telephone"));
return owner;
}
}
/**
* <code>Owner</code>s by last name Query Object.
*/
protected static class OwnersByNameQuery extends OwnersQuery {
/**
* Creates a new instance of OwnersByNameQuery
* @param ds the DataSource to use for the query.
*/
protected OwnersByNameQuery(DataSource ds) {
super(ds, "SELECT id,first_name,last_name,address,city,telephone FROM owners WHERE last_name like ?");
declareParameter(new SqlParameter(Types.VARCHAR));
compile();
}
}
/**
* <code>Owner</code> by id Query Object.
*/
protected static class OwnerQuery extends OwnersQuery {
/**
* Creates a new instance of OwnerQuery
* @param ds the DataSource to use for the query.
*/
protected OwnerQuery(DataSource ds) {
super(ds, "SELECT id,first_name,last_name,address,city,telephone FROM owners WHERE id=?");
declareParameter(new SqlParameter(Types.INTEGER));
compile();
}
}
/**
* <code>Owner</code> Insert Object.
*/
protected class OwnerInsert extends SqlUpdate {
protected OwnerInsert(DataSource ds) {
super(ds, "INSERT INTO owners VALUES(?,?,?,?,?,?)");
declareParameter(new SqlParameter(Types.INTEGER));
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.VARCHAR));
compile();
}
protected void insert(Owner owner) {
Object[] objs =
new Object[]{
null,
owner.getFirstName(),
owner.getLastName(),
owner.getAddress(),
owner.getCity(),
owner.getTelephone()};
super.update(objs);
retrieveIdentity(owner);
}
}
/**
* <code>Owner</code> Update Object.
*/
protected static class OwnerUpdate extends SqlUpdate {
/**
* Creates a new instance of OwnerUpdate
* @param ds the DataSource to use for the update.
*/
protected OwnerUpdate(DataSource ds) {
super(ds, "UPDATE owners SET first_name=?,last_name=?,address=?,city=?,telephone=? WHERE id=?");
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.INTEGER));
compile();
}
/**
* Method to update an <code>Owner</code>'s data.
* @param owner to update.
* @return the number of rows affected by the update
*/
protected int update(Owner owner) {
return this.update(
new Object[]{
owner.getFirstName(),
owner.getLastName(),
owner.getAddress(),
owner.getCity(),
owner.getTelephone(),
new Long(owner.getId())});
}
}
/**
* Abstract base class for all <code>Pet</code> Query Objects.
*/
protected static abstract class PetsQuery extends MappingSqlQuery {
/**
* Creates a new instance of PetsQuery
* @param ds the DataSource to use for the query.
* @param sql Value of the SQL to use for the query.
*/
protected PetsQuery(DataSource ds, String sql) {
super(ds, sql);
}
protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
JdbcPet pet = new JdbcPet();
pet.setId(rs.getLong("id"));
pet.setName(rs.getString("name"));
pet.setBirthDate(rs.getDate("birth_date"));
pet.setTypeId(rs.getLong("type_id"));
pet.setOwnerId(rs.getLong("owner_id"));
return pet;
}
}
/**
* <code>Pet</code>s by <code>Owner</code> Query Object.
*/
protected static class PetsByOwnerQuery extends PetsQuery {
/**
* Creates a new instance of PetsByOwnerQuery
* @param ds the DataSource to use for the query.
*/
protected PetsByOwnerQuery(DataSource ds) {
super(ds, "SELECT id,name,birth_date,type_id,owner_id FROM pets WHERE owner_id=?");
declareParameter(new SqlParameter(Types.INTEGER));
compile();
}
}
/**
* <code>Pet</code> by id Query Object.
*/
static class PetQuery extends PetsQuery {
/**
* Creates a new instance of PetQuery
* @param ds the DataSource to use for the query.
*/
protected PetQuery(DataSource ds) {
super(ds, "SELECT id,name,birth_date,type_id,owner_id FROM pets WHERE id=?");
declareParameter(new SqlParameter(Types.INTEGER));
compile();
}
}
/**
* <code>Pet</code> Insert Object.
*/
protected class PetInsert extends SqlUpdate {
/**
* Creates a new instance of PetInsert
*/
protected PetInsert(DataSource ds) {
super(ds, "INSERT INTO pets VALUES(?,?,?,?,?)");
declareParameter(new SqlParameter(Types.INTEGER));
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.DATE));
declareParameter(new SqlParameter(Types.INTEGER));
declareParameter(new SqlParameter(Types.INTEGER));
compile();
}
/**
* Method to insert a new <code>Pet</code>.
* @param pet to insert.
*/
protected void insert(Pet pet) {
Object[] objs =
new Object[]{
null,
pet.getName(),
new java.sql.Date(pet.getBirthDate().getTime()),
new Long(pet.getType().getId()),
new Long(pet.getOwner().getId()),
};
super.update(objs);
retrieveIdentity(pet);
}
}
/**
* <code>Pet</code> Update Object.
*/
protected static class PetUpdate extends SqlUpdate {
/**
* Creates a new instance of PetUpdate
* @param ds the DataSource to use for the update.
*/
protected PetUpdate(DataSource ds) {
super(ds, "UPDATE pets SET name=?,birth_date=?,type_id=?,owner_id=? WHERE id=?");
declareParameter(new SqlParameter(Types.VARCHAR));
declareParameter(new SqlParameter(Types.DATE));
declareParameter(new SqlParameter(Types.INTEGER));
declareParameter(new SqlParameter(Types.INTEGER));
declareParameter(new SqlParameter(Types.INTEGER));
compile();
}
/**
* Method to update an <code>Pet</code>'s data.
* @param pet to update.
* @return the number of rows affected by the update
*/
protected int update(Pet pet) {
return this.update(
new Object[]{
pet.getName(),
new java.sql.Date(pet.getBirthDate().getTime()),
new Long(pet.getType().getId()),
new Long(pet.getOwner().getId()),
new Long(pet.getId())
});
}
}
/**
* All <code>Pet</code> types Query Object.
*/
protected static class PetTypesQuery extends MappingSqlQuery {
/**
* Creates a new instance of PetTypesQuery
* @param ds the DataSource to use for the query.
*/
protected PetTypesQuery(DataSource ds) {
super(ds, "SELECT id,name FROM types ORDER BY name");
compile();
}
protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
PetType type = new PetType();
type.setId(rs.getLong("id"));
type.setName(rs.getString("name"));
return type;
}
}
/**
* <code>Visit</code>s by <code>Pet</code> Query Object.
*/
protected static class VisitsQuery extends MappingSqlQuery {
/**
* Creates a new instance of VisitsQuery
* @param ds the DataSource to use for the update.
*/
protected VisitsQuery(DataSource ds) {
super(ds, "SELECT id,visit_date,description FROM visits WHERE pet_id=?");
declareParameter(new SqlParameter(Types.INTEGER));
compile();
}
protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
Visit visit = new Visit();
visit.setId(rs.getLong("id"));
visit.setDate(rs.getDate("visit_date"));
visit.setDescription(rs.getString("description"));
return visit;
}
}
/**
* <code>Visit</code> Insert Object.
*/
protected class VisitInsert extends SqlUpdate {
/**
* Creates a new instance of VisitInsert
*/
protected VisitInsert(DataSource ds) {
super(ds, "INSERT INTO visits VALUES(?,?,?,?)");
declareParameter(new SqlParameter(Types.INTEGER));
declareParameter(new SqlParameter(Types.INTEGER));
declareParameter(new SqlParameter(Types.DATE));
declareParameter(new SqlParameter(Types.VARCHAR));
compile();
}
/**
* Method to insert a new <code>Visit</code>.
* @param visit to insert.
*/
protected void insert(Visit visit) {
Object[] objs =
new Object[]{
null,
new Long(visit.getPet().getId()),
new java.sql.Date(visit.getDate().getTime()),
visit.getDescription()
};
super.update(objs);
retrieveIdentity(visit);
}
}
}
|
package org.ovirt.engine.ui.frontend.server.gwt;
import java.util.ArrayList;
import java.util.Random;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.ovirt.engine.core.common.action.LoginUserParameters;
import org.ovirt.engine.core.common.action.LogoutUserParameters;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.interfaces.BackendLocal;
import org.ovirt.engine.core.common.queries.VdcQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.common.users.VdcUser;
import org.ovirt.engine.ui.frontend.gwtservices.GenericApiGWTService;
import com.google.gwt.rpc.server.RpcServlet;
import com.google.gwt.user.client.rpc.SerializationException;
public class GenericApiGWTServiceImpl extends RpcServlet implements GenericApiGWTService {
private static final long serialVersionUID = 7395780289048030855L;
static Random r = new Random();
boolean noBackend = false;
private static final Logger log = Logger.getLogger(GenericApiGWTServiceImpl.class);
private BackendLocal backend;
@EJB(beanInterface = BackendLocal.class,
mappedName = "java:global/engine/bll/Backend!org.ovirt.engine.core.common.interfaces.BackendLocal")
public void setBackend(BackendLocal backend) {
this.backend = backend;
}
public BackendLocal getBackend() {
return backend;
}
@Override
public void init() throws ServletException {
log.debug("Initializing servlet!"); //$NON-NLS-1$
}
@Override
public VdcQueryReturnValue RunQuery(VdcQueryType search,
VdcQueryParametersBase searchParameters) {
log.debug("Server: RunQuery invoked!"); //$NON-NLS-1$
searchParameters.setSessionId(getSessionId());
return getBackend().RunQuery(search, searchParameters);
}
@Override
public VdcQueryReturnValue RunPublicQuery(VdcQueryType queryType,
VdcQueryParametersBase params) {
log.debug("Server: RunPublicQuery invoked!"); //$NON-NLS-1$
return getBackend().RunPublicQuery(queryType, params);
}
@Override
public ArrayList<VdcQueryReturnValue> RunMultipleQueries(
ArrayList<VdcQueryType> queryTypeList,
ArrayList<VdcQueryParametersBase> queryParamsList) {
log.debug("Server: RunMultipleQuery invoked! [amount of queries: " + queryTypeList.size() + "]"); //$NON-NLS-1$ //$NON-NLS-2$
ArrayList<VdcQueryReturnValue> ret = new ArrayList<VdcQueryReturnValue>();
if (queryTypeList == null || queryParamsList == null) {
// TODO: LOG: "queryTypeList and/or queryParamsList is null."
}
else if (queryTypeList.size() != queryParamsList.size()) {
// TODO: LOG:
// "queryTypeList and queryParamsList don't have the same amount of items."
}
else {
for (int i = 0; i < queryTypeList.size(); i++) {
ret.add(RunQuery(queryTypeList.get(i), queryParamsList.get(i)));
}
}
for (VdcQueryReturnValue vqrv : ret) {
log.debug("VdcQueryReturnValue: " + vqrv); //$NON-NLS-1$
}
log.debug("Server: RunMultipleQuery result [amount of queries: " + ret.size() + "]"); //$NON-NLS-1$ //$NON-NLS-2$
return ret;
}
@Override
public ArrayList<VdcReturnValueBase> RunMultipleActions(VdcActionType actionType,
ArrayList<VdcActionParametersBase> multipleParams, boolean isRunOnlyIfAllCanDoPass) {
log.debug("Server: RunMultipleAction invoked! [amount of actions: " + multipleParams.size() + "]"); //$NON-NLS-1$ //$NON-NLS-2$
for (VdcActionParametersBase params : multipleParams) {
params.setSessionId(getSessionId());
}
ArrayList<VdcReturnValueBase> returnValues =
getBackend().RunMultipleActions(actionType, multipleParams, isRunOnlyIfAllCanDoPass);
return returnValues;
}
@Override
public VdcReturnValueBase RunAction(VdcActionType actionType,
VdcActionParametersBase params) {
log.debug("Server: RunAction invoked!"); //$NON-NLS-1$
params.setSessionId(getSessionId());
if (noBackend) {
VdcReturnValueBase rValue = new VdcReturnValueBase();
rValue.setSucceeded(true);
return rValue;
}
return getBackend().RunAction(actionType, params);
}
@Override
public VdcUser getLoggedInUser() {
VdcQueryParametersBase queryParams = new VdcQueryParametersBase();
queryParams.setSessionId(getSessionId());
queryParams.setHttpSessionId(getSessionId());
VdcQueryReturnValue vqrv = RunQuery(VdcQueryType.GetUserBySessionId,
queryParams);
if (!vqrv.getSucceeded()) {
return null;
} else if (vqrv.getSucceeded()) {
if (vqrv.getReturnValue() == null)
return null;
return (VdcUser) vqrv.getReturnValue();
} else {
// For unknown reason the result was failed be returned.
return null;
}
}
@Override
public VdcReturnValueBase logOff(VdcUser userToLogoff) {
LogoutUserParameters params = new LogoutUserParameters(userToLogoff.getUserId());
params.setSessionId(getSessionId());
VdcReturnValueBase returnValue = getBackend().Logoff(params);
return returnValue;
}
@Override
public VdcReturnValueBase Login(String userName, String password, String domain) {
LoginUserParameters params = new LoginUserParameters(userName, password, domain, null, null, null);
params.setSessionId(getSessionId());
params.setActionType(VdcActionType.LoginAdminUser);
VdcReturnValueBase returnValue = getBackend().Login(params);
return returnValue;
}
private String getSessionId() {
HttpServletRequest request = this.getThreadLocalRequest();
HttpSession session = request.getSession();
log.debug("IP [" + request.getRemoteAddr() + "], Session ID [" + session.getId() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return session.getId();
}
@Override
protected void doUnexpectedFailure (Throwable error) {
// If the user is using a version of the application different to what
// the server expects the names of the RPC serialization policy files
// will not match, and in that case GWT just sends the exception to the
// log, which is not very user or admin friendly, so we replace that
// with a more friendly message:
if (error instanceof SerializationException) {
error = new SerializationException(
"Can't find the serialization policy file. " + //$NON-NLS-1$
"This probably means that the user has an old " + //$NON-NLS-1$
"version of the application loaded in the " + //$NON-NLS-1$
"browser. To solve the issue the user needs " + //$NON-NLS-1$
"to close the browser and open it again, so " + //$NON-NLS-1$
"that the application is reloaded.", //$NON-NLS-1$
error
);
}
// Now that we replaced the message let GWT do what it uses to do:
super.doUnexpectedFailure(error);
}
}
|
package org.zanata.rest.service;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isOneOf;
import static org.hamcrest.Matchers.notNullValue;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import org.apache.commons.httpclient.URIException;
import org.dbunit.operation.DatabaseOperation;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.fedorahosted.tennera.jgettext.HeaderFields;
import org.fest.assertions.Assertions;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.seam.core.Events;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.zanata.ApplicationConfiguration;
import org.zanata.ZanataRestTest;
import org.zanata.common.ContentState;
import org.zanata.common.ContentType;
import org.zanata.common.LocaleId;
import org.zanata.common.ResourceType;
import org.zanata.dao.AccountDAO;
import org.zanata.dao.DocumentDAO;
import org.zanata.dao.LocaleDAO;
import org.zanata.dao.PersonDAO;
import org.zanata.dao.ProjectDAO;
import org.zanata.dao.ProjectIterationDAO;
import org.zanata.dao.TextFlowDAO;
import org.zanata.dao.TextFlowTargetDAO;
import org.zanata.dao.TextFlowTargetHistoryDAO;
import org.zanata.model.HAccount;
import org.zanata.model.HDocument;
import org.zanata.model.HProjectIteration;
import org.zanata.rest.RestUtil;
import org.zanata.rest.StringSet;
import org.zanata.rest.client.ITranslationResources;
import org.zanata.rest.dto.Person;
import org.zanata.rest.dto.extensions.comment.SimpleComment;
import org.zanata.rest.dto.extensions.gettext.HeaderEntry;
import org.zanata.rest.dto.extensions.gettext.PoHeader;
import org.zanata.rest.dto.extensions.gettext.PoTargetHeader;
import org.zanata.rest.dto.extensions.gettext.PotEntryHeader;
import org.zanata.rest.dto.resource.AbstractResourceMeta;
import org.zanata.rest.dto.resource.Resource;
import org.zanata.rest.dto.resource.ResourceMeta;
import org.zanata.rest.dto.resource.TextFlow;
import org.zanata.rest.dto.resource.TextFlowTarget;
import org.zanata.rest.dto.resource.TranslationsResource;
import org.zanata.security.ZanataIdentity;
import org.zanata.service.impl.LocaleServiceImpl;
import org.zanata.webtrans.server.TranslationWorkspace;
import org.zanata.webtrans.server.TranslationWorkspaceManager;
import org.zanata.webtrans.server.rpc.UpdateTransUnitHandler;
import org.zanata.webtrans.shared.model.ProjectIterationId;
import org.zanata.webtrans.shared.model.TransUnitId;
import org.zanata.webtrans.shared.model.WorkspaceContext;
import org.zanata.webtrans.shared.model.WorkspaceId;
import org.zanata.webtrans.shared.rpc.SessionEventData;
import org.zanata.webtrans.shared.rpc.UpdateTransUnit;
import org.zanata.webtrans.shared.rpc.UpdateTransUnitResult;
public class TranslationResourceRestTest extends ZanataRestTest
{
private static final Logger log = LoggerFactory.getLogger(TranslationResourceRestTest.class);
private static final String projectSlug = "sample-project";
private static final String iter = "1.1";
private static final String RESOURCE_PATH = "/projects/p/sample-project/iterations/i/1.0/r/";
private static final String BAD_RESOURCE_PATH = "/projects/p/nonexistentProject/iterations/i/99.9/r/";
private static final LocaleId DE = LocaleId.fromJavaName("de");
private static final LocaleId FR = LocaleId.fromJavaName("fr");
private static final String DOC2_NAME = "test.properties";
private static final String DOC1_NAME = "foo.properties";
StringSet extGettextComment = new StringSet("gettext;comment");
StringSet extComment = new StringSet("comment");
IMocksControl mockControl = EasyMock.createControl();
ZanataIdentity mockIdentity = mockControl.createMock(ZanataIdentity.class);
ApplicationConfiguration applicationConfiguration;
ProjectIterationDAO projectIterationDAO;
DocumentDAO documentDAO;
TextFlowDAO textFlowDAO;
TextFlowTargetDAO textFlowTargetDAO;
ResourceUtils resourceUtils;
Identity identity;
ETagUtils eTagUtils;
PersonDAO personDAO;
AccountDAO accountDAO;
TextFlowTargetHistoryDAO textFlowTargetHistoryDAO;
ProjectDAO projectDAO;
LocaleServiceImpl localeService;
Events events;
ITranslationResources transResource;
UpdateTransUnitHandler transUnitHandler;
@BeforeClass
void beforeClass()
{
Identity.setSecurityEnabled(false);
}
@BeforeMethod
void reset()
{
mockControl.reset();
}
@Override
protected void prepareDBUnitOperations()
{
beforeTestOperations.add(new DataSetOperation("org/zanata/test/model/ProjectsData.dbunit.xml", DatabaseOperation.CLEAN_INSERT));
beforeTestOperations.add(new DataSetOperation("org/zanata/test/model/LocalesData.dbunit.xml", DatabaseOperation.CLEAN_INSERT));
beforeTestOperations.add(new DataSetOperation("org/zanata/test/model/AccountData.dbunit.xml", DatabaseOperation.CLEAN_INSERT));
}
@SuppressWarnings("serial")
@Override
protected void prepareResources()
{
this.applicationConfiguration = new ApplicationConfiguration(true);
this.projectIterationDAO = new ProjectIterationDAO(getSession());
this.projectDAO = new ProjectDAO(getSession());
this.documentDAO = new DocumentDAO(getSession());
this.textFlowDAO = new TextFlowDAO(getSession());
this.textFlowTargetDAO = new TextFlowTargetDAO(getSession());
this.resourceUtils = new ResourceUtils();
this.identity = new Identity()
{
@Override
public boolean tryLogin()
{
return true;
}
};
this.eTagUtils = new ETagUtils(getSession(), documentDAO);
this.personDAO = new PersonDAO(getSession());
this.accountDAO = new AccountDAO(getSession());
this.textFlowTargetHistoryDAO = new TextFlowTargetHistoryDAO(getSession());
LocaleDAO localeDAO = new LocaleDAO(getSession());
projectDAO = new ProjectDAO(getSession());
this.localeService = new LocaleServiceImpl(localeDAO, projectDAO, projectIterationDAO, personDAO);
localeService.setLocaleDAO(localeDAO);
this.events = new Events()
{
@Override
public void raiseTransactionSuccessEvent(String type, Object... parameters)
{
}
};
// @formatter:off
TranslationResourcesService obj = new TranslationResourcesService(
applicationConfiguration,
projectIterationDAO,
projectDAO,
documentDAO,
textFlowDAO,
textFlowTargetDAO,
resourceUtils,
identity,
eTagUtils,
personDAO,
textFlowTargetHistoryDAO,
localeService,
events);
// @formatter:on
resources.add(obj);
}
@BeforeMethod(dependsOnMethods = "prepareRestEasyFramework")
public void createClient()
{
this.transResource = getClientRequestFactory().createProxy(ITranslationResources.class, createBaseURI(RESOURCE_PATH));
}
@Test
public void fetchEmptyListOfResources()
{
doGetandAssertThatResourceListContainsNItems(0);
}
@Test
public void createEmptyResource()
{
Resource sr = createSourceResource("my.txt");
ClientResponse<String> response = transResource.post(sr, null, true);
assertThat(response.getResponseStatus(), is(Status.CREATED));
List<String> locationHeader = response.getHeaders().get("Location");
assertThat(locationHeader.size(), is(1));
assertThat(locationHeader.get(0), endsWith("r/my.txt"));
doGetandAssertThatResourceListContainsNItems(1);
}
@Test
public void createResourceWithContentUsingPost()
{
Resource sr = createSourceResource("my.txt");
TextFlow stf = new TextFlow("tf1", LocaleId.EN, "tf1");
sr.getTextFlows().add(stf);
ClientResponse<String> postResponse = transResource.post(sr, null, true);
assertThat(postResponse.getResponseStatus(), is(Status.CREATED));
postResponse = transResource.post(sr, null, true);
ClientResponse<Resource> resourceGetResponse = transResource.getResource("my.txt", null);
assertThat(resourceGetResponse.getResponseStatus(), is(Status.OK));
Resource gotSr = resourceGetResponse.getEntity();
assertThat(gotSr.getTextFlows().size(), is(1));
assertThat(gotSr.getTextFlows().get(0).getContent(), is("tf1"));
}
@Test
public void createResourceWithContentUsingPut()
{
Resource sr = createSourceResource("my.txt");
TextFlow stf = new TextFlow("tf1", LocaleId.EN, "tf1");
sr.getTextFlows().add(stf);
ClientResponse<String> response = transResource.putResource("my.txt", sr, null);
assertThat(response.getResponseStatus(), is(Status.CREATED));
assertThat(response.getLocation().getHref(), endsWith("/r/my.txt"));
ClientResponse<Resource> resourceGetResponse = transResource.getResource("my.txt", null);
assertThat(resourceGetResponse.getResponseStatus(), is(Status.OK));
Resource gotSr = resourceGetResponse.getEntity();
assertThat(gotSr.getTextFlows().size(), is(1));
assertThat(gotSr.getTextFlows().get(0).getContent(), is("tf1"));
}
@Test
public void createPoResourceWithPoHeader()
{
String docName = "my.txt";
String docUri = RestUtil.convertToDocumentURIId(docName);
Resource sr = createSourceResource(docName);
TextFlow stf = new TextFlow("tf1", LocaleId.EN, "tf1");
sr.getTextFlows().add(stf);
// @formatter:off
/*
TODO: move this into an AbstractResourceMeta test (PoHeader is valid for source documents, not target)
PoHeader poHeaderExt = new PoHeader("comment", new HeaderEntry("h1", "v1"), new HeaderEntry("h2", "v2"));
sr.getExtensions(true).add(poHeaderExt);
*/
// @formatter:on
ClientResponse<String> postResponse = transResource.post(sr, null, true); // new
// StringSet(PoHeader.ID));
assertThat(postResponse.getResponseStatus(), is(Status.CREATED));
doGetandAssertThatResourceListContainsNItems(1);
ClientResponse<Resource> resourceGetResponse = transResource.getResource(docUri, null);// new
// StringSet(PoHeader.ID));
assertThat(resourceGetResponse.getResponseStatus(), is(Status.OK));
Resource gotSr = resourceGetResponse.getEntity();
assertThat(gotSr.getTextFlows().size(), is(1));
assertThat(gotSr.getTextFlows().get(0).getContent(), is("tf1"));
// @formatter:off
/*
TODO: move this into an AbstractResourceMeta test
assertThat(gotSr.getExtensions().size(), is(1));
PoHeader gotPoHeader = gotSr.getExtensions().findByType(PoHeader.class);
assertThat(gotPoHeader, notNullValue());
assertThat(poHeaderExt.getComment(), is(gotPoHeader.getComment()));
assertThat(poHeaderExt.getEntries(), is(gotPoHeader.getEntries()));
*/
// @formatter:on
}
// NB this test breaks in Maven if the dev profile is active (because of the
// imported testdata)
@Test
public void publishTranslations()
{
createResourceWithContentUsingPut();
TranslationsResource entity = new TranslationsResource();
TextFlowTarget target = new TextFlowTarget();
target.setResId("tf1");
target.setContent("hello world");
target.setState(ContentState.Approved);
target.setTranslator(new Person("root@localhost", "Admin user"));
entity.getTextFlowTargets().add(target);
LocaleId de_DE = new LocaleId("de");
ClientResponse<String> response = transResource.putTranslations("my.txt", de_DE, entity, null);
assertThat(response.getResponseStatus(), is(Status.OK));
ClientResponse<TranslationsResource> getResponse = transResource.getTranslations("my.txt", de_DE, null);
assertThat(getResponse.getResponseStatus(), is(Status.OK));
TranslationsResource entity2 = getResponse.getEntity();
assertThat(entity2.getTextFlowTargets().size(), is(entity.getTextFlowTargets().size()));
entity.getTextFlowTargets().clear();
// push an empty document
response = transResource.putTranslations("my.txt", de_DE, entity, null, MergeType.IMPORT.toString());
assertThat(response.getResponseStatus(), is(Status.OK));
getResponse = transResource.getTranslations("my.txt", de_DE, null);
assertThat(getResponse.getResponseStatus(), is(Status.NOT_FOUND));
}
@Test
public void getDocumentThatDoesntExist()
{
ClientResponse<Resource> clientResponse = transResource.getResource("my,doc,does,not,exist.txt", null);
assertThat(clientResponse.getResponseStatus(), is(Status.NOT_FOUND));
}
@Test
public void getDocument() throws URIException
{
String docName = "my/path/document.txt";
String docUri = RestUtil.convertToDocumentURIId(docName);
Resource resource = createSourceDoc(docName, false);
transResource.putResource(docUri, resource, null);
ClientResponse<ResourceMeta> response = transResource.getResourceMeta(docUri, null);
assertThat(response.getResponseStatus(), is(Status.OK));
ResourceMeta doc = response.getEntity();
assertThat(doc.getName(), is(docName));
assertThat(doc.getContentType(), is(ContentType.TextPlain));
assertThat(doc.getLang(), is(LocaleId.EN_US));
assertThat(doc.getRevision(), is(1));
/*
* Link link = doc.getLinks().findLinkByRel(Relationships.SELF);
* assertThat( link, notNullValue() ); assertThat(
* URIUtil.decode(link.getHref().toString()), endsWith(url+docUri) );
*
* link = doc.getLinks().findLinkByRel(Relationships.DOCUMENT_CONTAINER);
* assertThat( link, notNullValue() ); assertThat(
* link.getHref().toString(), endsWith("iterations/i/1.0") );
*/
}
@Test
public void getDocumentWithResources() throws URIException
{
LocaleId nbLocale = new LocaleId("de");
String docName = "my/path/document.txt";
String docUri = RestUtil.convertToDocumentURIId(docName);
Resource resource = createSourceDoc(docName, true);
transResource.putResource(docUri, resource, null);
TranslationsResource trans = createTargetDoc();
transResource.putTranslations(docUri, nbLocale, trans, null);
{
ClientResponse<Resource> response = transResource.getResource(docUri, null);
assertThat(response.getResponseStatus(), is(Status.OK));
Resource doc = response.getEntity();
assertThat(doc.getTextFlows().size(), is(1));
}
ClientResponse<TranslationsResource> response = transResource.getTranslations(docUri, nbLocale, null);
assertThat(response.getResponseStatus(), is(Status.OK));
TranslationsResource doc = response.getEntity();
assertThat("should have one textFlow", doc.getTextFlowTargets().size(), is(1));
TextFlowTarget tft = doc.getTextFlowTargets().get(0);
assertThat(tft, notNullValue());
assertThat("should have a textflow with this id", tft.getResId(), is("tf1"));
assertThat("expected de target", tft, notNullValue());
assertThat("expected translation for de", tft.getContent(), is("hei verden"));
}
@Test
public void putNewDocument()
{
String docName = "my/fancy/document.txt";
String docUrl = RestUtil.convertToDocumentURIId(docName);
Resource doc = createSourceDoc(docName, false);
Response response = transResource.putResource(docUrl, doc, null);
assertThat(response.getStatus(), is(Status.CREATED.getStatusCode()));
assertThat(response.getMetadata().getFirst("Location").toString(), endsWith(RESOURCE_PATH + docUrl));
ClientResponse<Resource> documentResponse = transResource.getResource(docUrl, null);
assertThat(documentResponse.getResponseStatus(), is(Status.OK));
doc = documentResponse.getEntity();
assertThat(doc.getRevision(), is(1));
/*
* Link link = doc.getLinks().findLinkByRel(Relationships.SELF);
* assertThat(link, notNullValue()); assertThat(link.getHref().toString(),
* endsWith(url + docUrl));
*
* link = doc.getLinks().findLinkByRel(Relationships.DOCUMENT_CONTAINER);
* assertThat(link, notNullValue()); assertThat(link.getType(),
* is(MediaTypes.APPLICATION_ZANATA_PROJECT_ITERATION_XML));
*/
}
@Test
public void putDocWithDuplicateTextFlowIds() throws Exception
{
String docName = "testDoc";
String docUrl = RestUtil.convertToDocumentURIId(docName);
Resource doc = createSourceDoc(docName, false);
List<TextFlow> textFlows = doc.getTextFlows();
for (int i = 0; i < 2; i++)
{
TextFlow textFlow = new TextFlow("tf1");
textFlow.setContent("hello world!");
textFlows.add(textFlow);
}
ClientResponse<?> response = transResource.putResource(docUrl, doc, null);
assertThat(response.getStatus(), is(Status.BAD_REQUEST.getStatusCode()));
String message = (String) response.getEntity();
assertThat(message, containsString("tf1"));
}
@Test
public void putNewDocumentWithResources() throws Exception
{
String docName = "my/fancy/document.txt";
String docUrl = RestUtil.convertToDocumentURIId(docName);
Resource doc = createSourceDoc(docName, false);
List<TextFlow> textFlows = doc.getTextFlows();
textFlows.clear();
TextFlow textFlow = new TextFlow("tf1");
textFlow.setContent("hello world!");
textFlows.add(textFlow);
TextFlow tf3 = new TextFlow("tf3");
tf3.setContent("more text");
textFlows.add(tf3);
Marshaller m = null;
JAXBContext jc = JAXBContext.newInstance(Resource.class);
m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(doc, System.out);
Response response = transResource.putResource(docUrl, doc, null);
assertThat(response.getStatus(), is(Status.CREATED.getStatusCode()));
assertThat(response.getMetadata().getFirst("Location").toString(), endsWith(RESOURCE_PATH + docUrl));
ClientResponse<Resource> documentResponse = transResource.getResource(docUrl, null);
assertThat(documentResponse.getResponseStatus(), is(Status.OK));
doc = documentResponse.getEntity();
assertThat(doc.getRevision(), is(1));
assertThat("Should have textFlows", doc.getTextFlows(), notNullValue());
assertThat("Should have 2 textFlows", doc.getTextFlows().size(), is(2));
assertThat("Should have tf1 textFlow", doc.getTextFlows().get(0).getId(), is("tf1"));
assertThat("Container1 should have tf3 textFlow", doc.getTextFlows().get(1).getId(), is(tf3.getId()));
textFlow = doc.getTextFlows().get(0);
textFlow.setId("tf2");
response = transResource.putResource(docUrl, doc, null);
// this WAS testing for status 205
assertThat(response.getStatus(), is(200));
documentResponse = transResource.getResource(docUrl, null);
assertThat(documentResponse.getResponseStatus(), is(Status.OK));
doc = documentResponse.getEntity();
assertThat(doc.getRevision(), is(2));
assertThat("Should have textFlows", doc.getTextFlows(), notNullValue());
assertThat("Should have two textFlows", doc.getTextFlows().size(), is(2));
assertThat("should have same id", doc.getTextFlows().get(0).getId(), is("tf2"));
}
@Test
public void getZero() throws Exception
{
expectDocs(true, false);
}
@Test
public void put1Get() throws Exception
{
getZero();
Resource doc1 = putDoc1(false);
doc1.setRevision(1);
TextFlow tf1 = doc1.getTextFlows().get(0);
tf1.setRevision(1);
TranslationsResource target1 = putTarget1();
TextFlowTarget tft1 = target1.getTextFlowTargets().get(0);
tft1.setTextFlowRevision(1);
tft1.setRevision(1);
expectDocs(true, false, doc1);
expectTarget1(target1);
}
@Test
public void put1Post2Get() throws Exception
{
getZero();
Resource doc1 = putDoc1(false);
doc1.setRevision(1);
TextFlow tf1 = doc1.getTextFlows().get(0);
tf1.setRevision(1);
TranslationsResource target1 = putTarget1();
TextFlowTarget tft1 = target1.getTextFlowTargets().get(0);
tft1.setTextFlowRevision(1);
tft1.setRevision(1);
expectDocs(true, false, doc1);
expectTarget1(target1);
Resource doc2 = postDoc2(false);
doc2.setRevision(1);
TextFlow tf2 = doc2.getTextFlows().get(0);
tf2.setRevision(1);
TranslationsResource target2 = putTarget2();
TextFlowTarget tft2 = target2.getTextFlowTargets().get(0);
tft2.setTextFlowRevision(1);
tft2.setRevision(1);
expectDocs(true, false, doc1, doc2);
expectTarget1(target1);
expectTarget2(target2);
}
@Test
public void put1Post2Put1() throws Exception
{
getZero();
Resource doc1 = putDoc1(false);
doc1.setRevision(1);
TextFlow tf1 = doc1.getTextFlows().get(0);
tf1.setRevision(1);
TranslationsResource target1 = putTarget1();
TextFlowTarget tft1 = target1.getTextFlowTargets().get(0);
tft1.setTextFlowRevision(1);
Resource doc2 = postDoc2(false);
doc2.setRevision(1);
TextFlow tf2 = doc2.getTextFlows().get(0);
tf2.setRevision(1);
TranslationsResource target2 = putTarget2();
TextFlowTarget tft2 = target2.getTextFlowTargets().get(0);
tft2.setTextFlowRevision(1);
expectDocs(true, false, doc1, doc2);
tft1.setRevision(1);
tft2.setRevision(1);
expectTarget1(target1);
expectTarget2(target2);
// this put should have the effect of deleting doc2
putDoc1(false);
deleteDoc2();
// should be identical to doc1 from before, including revisions
expectDocs(true, false, doc1);
expectTarget1(target1);
dontExpectTarget2();
// expectTargets(true, FR, target2);
// use dao to check that doc2 is marked obsolete
verifyObsoleteDocument(doc2.getName());
}
@Test
public void put1Delete1Put1() throws Exception
{
getZero();
Resource doc1 = putDoc1(false);
doc1.setRevision(1);
TextFlow tf1 = doc1.getTextFlows().get(0);
tf1.setRevision(1);
TranslationsResource target1 = putTarget1();
TextFlowTarget tft1 = target1.getTextFlowTargets().get(0);
tft1.setTextFlowRevision(1);
expectDocs(true, false, doc1);
tft1.setRevision(1);
expectTarget1(target1);
deleteDoc1(); // doc1 becomes obsolete
getZero();
dontExpectTarget1();
putDoc1(false); // doc1 resurrected, rev 1
doc1.setRevision(1);
tf1.setRevision(1);
tft1.setTextFlowRevision(1);
expectDocs(true, false, doc1);
expectTarget1(target1);
}
@Test
public void put1Put1Again() throws Exception
{
getZero();
Resource doc1 = putDoc1(false);
doc1.setRevision(1);
TextFlow tf1 = doc1.getTextFlows().get(0);
tf1.setRevision(1);
TranslationsResource target1 = putTarget1();
TextFlowTarget tft1 = target1.getTextFlowTargets().get(0);
tft1.setTextFlowRevision(1);
tft1.setRevision(1);
expectDocs(true, false, doc1);
expectTarget1(target1);
putDoc1(false); // docRev still 1
doc1.setRevision(1);
tf1.setRevision(1);
tft1.setTextFlowRevision(1);
expectDocs(true, false, doc1);
expectTarget1(target1);
}
public void put1Put1WithAnotherTextFlow()
{
// TODO make sure tft1 is still there even though the doc rev goes up
}
@Test
public void put1Delete1Put1a() throws Exception
{
getZero();
Resource doc1 = putDoc1(false);
doc1.setRevision(1);
TextFlow tf1 = doc1.getTextFlows().get(0);
tf1.setRevision(1);
TranslationsResource target1 = putTarget1();
TextFlowTarget tft1 = target1.getTextFlowTargets().get(0);
tft1.setTextFlowRevision(1);
expectDocs(true, false, doc1);
tft1.setRevision(1);
expectTarget1(target1);
deleteDoc1(); // doc1 becomes obsolete
getZero();
dontExpectTarget1();
Resource doc1a = putDoc1a(false); // doc1 resurrected, rev 2
doc1a.setRevision(2);
TextFlow tf1a = doc1a.getTextFlows().get(0);
tf1a.setRevision(doc1a.getRevision());
TranslationsResource target1a = putTarget1a();
TextFlowTarget tft1a = target1a.getTextFlowTargets().get(0);
tft1a.setTextFlowRevision(tf1a.getRevision());
tft1a.setRevision(1);
expectDocs(true, false, doc1a);
dontExpectTarget1();
expectTarget1a(target1a);
}
@Test
public void putPoPotGet() throws Exception
{
getZero();
Resource po1 = putPo1();
expectDocs(false, false, po1);
TranslationsResource poTarget1 = putPoTarget1();
expectTarget(false, po1.getName(), DE, poTarget1);
}
@Test
public void put1Put1aPut1() throws Exception
{
getZero();
Resource doc1 = putDoc1(false);
doc1.setRevision(1);
TextFlow tf1 = doc1.getTextFlows().get(0);
tf1.setRevision(1);
TranslationsResource target1 = putTarget1();
TextFlowTarget tft1 = target1.getTextFlowTargets().get(0);
tft1.setTextFlowRevision(1);
tft1.setRevision(1);
expectDocs(true, false, doc1);
expectTarget1(target1);
// this should completely replace doc1's textflow FOOD with HELLO
Resource doc1a = putDoc1a(false);
doc1a.setRevision(2);
TextFlow tf1a = doc1a.getTextFlows().get(0);
tf1a.setRevision(2);
TranslationsResource target1a = putTarget1a();
TextFlowTarget tft1a = target1a.getTextFlowTargets().get(0);
tft1a.setTextFlowRevision(2);
tft1a.setRevision(1);
expectDocs(true, false, doc1a);
dontExpectTarget1();
expectTarget1a(target1a);
// use dao to check that the HTextFlow FOOD (from doc1) is marked obsolete
verifyObsoleteResource(doc1.getName(), "FOOD");
putDoc1(false); // same as original doc1, but different doc rev
doc1.setRevision(3);
expectDocs(true, false, doc1);
// target 1 should be resurrected
expectTarget1(target1);
dontExpectTarget1a();
}
@Test
public void generatedPoHeaders() throws Exception
{
LocaleId de_DE = new LocaleId("de");
getZero();
publishTranslations(); // push some translations (with no headers)
// Get the translations with PO headers
ClientResponse<TranslationsResource> response = transResource.getTranslations("my.txt", de_DE, new StringSet("gettext"));
TranslationsResource translations = response.getEntity();
assertThat(translations.getExtensions().size(), greaterThan(0));
// List of custom Zanata headers that should be present
final String[] requiredHeaders = new String[]{HeaderFields.KEY_LastTranslator, HeaderFields.KEY_PoRevisionDate,
HeaderFields.KEY_LanguageTeam, "X-Generator", HeaderFields.KEY_Language};
for( String reqHeader : requiredHeaders )
{
boolean headerFound = false;
for( HeaderEntry entry : translations.getExtensions().findByType(PoTargetHeader.class).getEntries() )
{
if( entry.getKey().equals(reqHeader) )
{
headerFound = true;
}
}
assertThat("PO Target Header '" + reqHeader + "' was not present when pulling translations.", headerFound, is(true));
}
// Since it is a first push with no headers, the Last Translator and Last Revision Date header should be empty
for( HeaderEntry entry : translations.getExtensions().findByType(PoTargetHeader.class).getEntries() )
{
if( entry.getKey().equals(HeaderFields.KEY_LastTranslator) || entry.getKey().equals(HeaderFields.KEY_PoRevisionDate) )
{
assertThat( entry.getValue().trim(), is("") );
}
}
}
@Test
public void headersBeforeTranslating() throws Exception
{
LocaleId de_DE = new LocaleId("de");
getZero();
// Push a document with no translations
createResourceWithContentUsingPut();
// Get the translations with PO headers
ClientResponse<TranslationsResource> response = transResource.getTranslations("my.txt", de_DE, new StringSet("gettext"));
TranslationsResource translations = response.getEntity();
assertThat( translations.getTextFlowTargets().size(), is(0) ); // Expecting no translations
// Make sure the headers are populated
PoTargetHeader header = translations.getExtensions(true).findByType(PoTargetHeader.class);
assertThat(header, notNullValue());
assertThat(header.getEntries().size(), greaterThan(0));
// Make sure the header values are empty since the system does not have any information for them
for( HeaderEntry entry : header.getEntries() )
{
if( entry.getKey().equals(HeaderFields.KEY_LastTranslator) )
{
assertThat( entry.getValue().trim(), is("") );
}
else if( entry.getKey().equals(HeaderFields.KEY_PoRevisionDate) )
{
assertThat( entry.getValue().trim(), is("") );
}
}
}
@Test
public void headersFromOriginalPush() throws Exception
{
LocaleId de_DE = new LocaleId("de");
getZero();
// Push a document and its translations
createResourceWithContentUsingPut();
TranslationsResource entity = new TranslationsResource();
TextFlowTarget target = new TextFlowTarget();
target.setResId("tf1");
target.setContent("hello world");
target.setState(ContentState.Approved);
target.setTranslator(new Person("root@localhost", "Admin user"));
entity.getTextFlowTargets().add(target);
// Future Date for the PO Revision Date Header
Calendar poRevDate = Calendar.getInstance();
poRevDate.add(Calendar.YEAR, 1); // 1 year in the future
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mmZ");
// Add initial headers to the translations
PoTargetHeader transHeader = new PoTargetHeader();
transHeader.getEntries().add( new HeaderEntry(HeaderFields.KEY_LastTranslator, "Test User <test@zanata.org>") );
transHeader.getEntries().add( new HeaderEntry(HeaderFields.KEY_PoRevisionDate, dateFormat.format(poRevDate.getTime())) ); // Date in the future
entity.getExtensions(true).add( transHeader );
// Push the translations
ClientResponse<String> putResponse = transResource.putTranslations("my.txt", de_DE, entity, new StringSet("gettext"));
assertThat(putResponse.getResponseStatus(), is(Status.OK));
// Get the translations with PO headers
ClientResponse<TranslationsResource> transResponse = transResource.getTranslations("my.txt", de_DE, new StringSet("gettext"));
TranslationsResource translations = transResponse.getEntity();
// Make sure the headers are populated
PoTargetHeader header = translations.getExtensions(true).findByType(PoTargetHeader.class);
assertThat(header, notNullValue());
assertThat(header.getEntries().size(), greaterThan(0));
// Make sure the header values are the same as the ones pushed with the document
for( HeaderEntry entry : header.getEntries() )
{
if( entry.getKey().equals(HeaderFields.KEY_LastTranslator) )
{
assertThat( entry.getValue().trim(), is("Test User <test@zanata.org>") );
}
else if( entry.getKey().equals(HeaderFields.KEY_PoRevisionDate) )
{
assertThat( entry.getValue().trim(), is( dateFormat.format(poRevDate.getTime()) ) );
}
}
}
@Test
public void headersAfterTranslating() throws Exception
{
LocaleId de_DE = new LocaleId("de");
getZero();
// Push a document and its translations
createResourceWithContentUsingPut();
TranslationsResource entity = new TranslationsResource();
TextFlowTarget target = new TextFlowTarget();
target.setResId("tf1");
target.setContent("hello world");
target.setState(ContentState.Approved);
target.setTranslator(new Person("root@localhost", "Admin user"));
entity.getTextFlowTargets().add(target);
ClientResponse<String> putResponse = transResource.putTranslations("my.txt", de_DE, entity, null);
assertThat(putResponse.getResponseStatus(), is(Status.OK));
// Get the translations with PO headers
ClientResponse<TranslationsResource> response = transResource.getTranslations("my.txt", de_DE, new StringSet("gettext"));
TranslationsResource translations = response.getEntity();
assertThat( translations.getTextFlowTargets().size(), greaterThan(0) );
// Now translate and push them again
for( TextFlowTarget tft : translations.getTextFlowTargets() )
{
tft.setContent("Translated");
tft.setState(ContentState.Approved);
}
putResponse = transResource.putTranslations("my.txt", de_DE, translations, null);
assertThat(putResponse.getStatus(), is(Response.Status.OK.getStatusCode()));
// Fetch the translations again
response = transResource.getTranslations("my.txt", de_DE, new StringSet("gettext"));
translations = response.getEntity();
assertThat( translations.getTextFlowTargets().size(), greaterThan(0) );
// Make sure the headers are now populated
PoTargetHeader header = translations.getExtensions(true).findByType(PoTargetHeader.class);
assertThat(header, notNullValue());
assertThat(header.getEntries().size(), greaterThan(0));
// Make sure the headers have the correct value
for( HeaderEntry entry : header.getEntries() )
{
if( entry.getKey().equals(HeaderFields.KEY_LastTranslator) )
{
assertThat( entry.getValue().trim(), is("Administrator <root@localhost>") );
}
else if( entry.getKey().equals(HeaderFields.KEY_PoRevisionDate) )
{
assertThat( entry.getValue().trim().length(), greaterThan(0) );
}
}
}
@Test
public void headersAfterWebtransEdit() throws Exception
{
LocaleId de_DE = new LocaleId("de");
getZero();
// Push a document with no translations
createResourceWithContentUsingPut();
super.newSession();
// Translator
HAccount translator = accountDAO.getByUsername("demo");
// Translate using the web editor
this.simulateWebEditorTranslation("sample-project", "1.0", "my.txt", "tf1", translator, de_DE, "Translated", ContentState.Approved);
super.newSession();
// Fetch the translations again
ClientResponse<TranslationsResource> response = transResource.getTranslations("my.txt", de_DE, new StringSet("gettext"));
TranslationsResource translations = response.getEntity();
assertThat( translations.getTextFlowTargets().size(), greaterThan(0) );
// Make sure the headers are present
PoTargetHeader header = translations.getExtensions(true).findByType(PoTargetHeader.class);
assertThat(header, notNullValue());
assertThat(header.getEntries().size(), greaterThan(0));
// Make sure the headers have the correct value
for( HeaderEntry entry : header.getEntries() )
{
if( entry.getKey().equals(HeaderFields.KEY_LastTranslator) )
{
assertThat( entry.getValue().trim(), is("Sample User <user1@localhost>") );
}
else if( entry.getKey().equals(HeaderFields.KEY_PoRevisionDate) )
{
assertThat( entry.getValue().trim().length(), greaterThan(0) );
}
}
}
@Test
public void getBadProject() throws Exception
{
ITranslationResources badTransResource = getClientRequestFactory().createProxy(ITranslationResources.class, createBaseURI(BAD_RESOURCE_PATH));
ClientResponse<List<ResourceMeta>> response = badTransResource.get(null);
assertThat(response.getStatus(), is(404));
}
// END of tests
/**
* Simulates the translation of a Unit using the web editor.
*
* @param projectSlug Project
* @param iterationSlug Project Iteration
* @param docId Document Id
* @param textFlowContent Text Flow's content
* @param translator The user that does the translation
* @param localeId Locale for the translation
* @param translation The translated text
* @param translationState The new state for the translation (can be null if no changes are needed)
*/
private void simulateWebEditorTranslation(String projectSlug, String iterationSlug, String docId, String textFlowContent,
HAccount translator, LocaleId localeId, String translation, ContentState translationState )
throws Exception
{
// Mock certain objects
TranslationWorkspaceManager transWorkerManager = mockControl.createMock(TranslationWorkspaceManager.class);
TranslationWorkspace transWorkspace = mockControl.createMock(TranslationWorkspace.class);
WorkspaceId workspaceId = new WorkspaceId(new ProjectIterationId(projectSlug, iterationSlug), localeId);
WorkspaceContext workspaceContext = new WorkspaceContext(workspaceId, "sample-workspace", localeId.getId(), false);
Credentials mockCredentials = new Credentials();
mockCredentials.setInitialized(true);
mockCredentials.setUsername( translator.getUsername() );
// Set mock expectations
expect( transWorkerManager.getOrRegisterWorkspace( anyObject(WorkspaceId.class) ) ).andReturn( transWorkspace ).anyTimes();
expect( mockIdentity.getCredentials() ).andReturn( mockCredentials );
expect( transWorkspace.getWorkspaceContext() ).andReturn( workspaceContext );
mockIdentity.checkLoggedIn();
expectLastCall();
mockIdentity.checkPermission(anyObject(), anyObject(String.class));
expectLastCall();
transWorkspace.publish( anyObject(SessionEventData.class) );
expectLastCall();
mockControl.replay();
// @formatter:off
transUnitHandler = new UpdateTransUnitHandler(
getSession(),
mockIdentity,
projectDAO,
projectIterationDAO,
textFlowTargetHistoryDAO,
transWorkerManager,
localeService,
translator);
// @formatter:on
// Translation unit id to update
Long textFlowId = (Long)getSession().createQuery("select tf.id from HTextFlow tf where tf.content = ? and " +
"tf.document.docId = ? and " +
"tf.document.projectIteration.slug = ? and " +
"tf.document.projectIteration.project.slug = ?")
.setString(0, textFlowContent)
.setString(1, docId)
.setString(2, iterationSlug)
.setString(3, projectSlug)
.uniqueResult();
// Translate using webtrans
UpdateTransUnit action = new UpdateTransUnit(new TransUnitId(textFlowId), translation, translationState);
action.setWorkspaceId( workspaceId );
UpdateTransUnitResult result =
transUnitHandler.execute(action, null);
assertThat( result.isSuccess(), is(true) );
mockControl.verify();
}
private void expectDocs(boolean checkRevs, boolean checkLinksIgnored, Resource... docs)
{
expectResourceMetas(checkRevs, docs);
expectResources(checkRevs, docs);
}
private void expectResourceMetas(boolean checkRevs, AbstractResourceMeta... docs)
{
ClientResponse<List<ResourceMeta>> response = transResource.get(null);
assertThat(response.getStatus(), is(200));
List<ResourceMeta> actualDocs = response.getEntity();
assertThat(actualDocs, notNullValue());
Map<String, AbstractResourceMeta> expectedDocs = new HashMap<String, AbstractResourceMeta>();
for (AbstractResourceMeta doc : docs)
{
expectedDocs.put(doc.getName(), doc);
}
// Set<String> actualDocVals = new TreeSet<String>();
Map<String, AbstractResourceMeta> actualDocsMap = new HashMap<String, AbstractResourceMeta>();
for (ResourceMeta doc : actualDocs)
{
actualDocsMap.put(doc.getName(), doc);
log.debug("actual doc: " + doc.toString());
AbstractResourceMeta expectedDoc = expectedDocs.get(doc.getName());
if (checkRevs)
assertThat(doc.getRevision(), is(expectedDoc.getRevision()));
}
assertThat(actualDocsMap.keySet(), is(expectedDocs.keySet()));
}
private void expectResources(boolean checkRevs, Resource... docs)
{
for (Resource expectedDoc : docs)
{
if (!checkRevs)
ResourceTestUtil.clearRevs(expectedDoc);
ClientResponse<Resource> response = transResource.getResource(expectedDoc.getName(), extGettextComment);
assertThat(response.getStatus(), is(200));
Resource actualDoc = response.getEntity();
if (!checkRevs)
ResourceTestUtil.clearRevs(actualDoc);
createExtensionSets(expectedDoc);
createExtensionSets(actualDoc);
Assertions.assertThat(actualDoc).isEqualTo(expectedDoc);
}
}
protected void createExtensionSets(Resource resource)
{
resource.getExtensions(true);
for (TextFlow tf : resource.getTextFlows())
{
tf.getExtensions(true);
}
}
private void dontExpectTarget(String id, LocaleId locale)
{
ClientResponse<TranslationsResource> response = transResource.getTranslations(id, locale, null);
assertThat(response.getStatus(), is(404));
}
private void expectTarget(boolean checkRevs, String id, LocaleId locale, TranslationsResource expectedDoc)
{
ClientResponse<TranslationsResource> response = transResource.getTranslations(id, locale, extGettextComment);
assertThat(response.getStatus(), is(200));
TranslationsResource actualDoc = response.getEntity();
actualDoc.getLinks(true).clear();
actualDoc.getExtensions(true);
for (TextFlowTarget tft : expectedDoc.getTextFlowTargets())
{
tft.getExtensions(true);
}
for (TextFlowTarget tft : actualDoc.getTextFlowTargets())
{
tft.getExtensions(true);
}
expectedDoc.getLinks(true).clear();
expectedDoc.getExtensions(true);
if (!checkRevs)
{
ResourceTestUtil.clearRevs(actualDoc);
ResourceTestUtil.clearRevs(expectedDoc);
}
// Clear Po Headers since Zanata will generate custom ones
ResourceTestUtil.clearPoTargetHeaders(actualDoc, expectedDoc);
Assertions.assertThat(actualDoc.toString()).isEqualTo(expectedDoc.toString());
}
private Resource createSourceDoc(String name, boolean withTextFlow)
{
Resource resource = new Resource();
resource.setContentType(ContentType.TextPlain);
resource.setLang(LocaleId.EN_US);
resource.setName(name);
resource.setType(ResourceType.DOCUMENT);
if (withTextFlow)
resource.getTextFlows().add(new TextFlow("tf1", LocaleId.EN_US, "hello world"));
return resource;
}
private TranslationsResource createTargetDoc()
{
TranslationsResource trans = new TranslationsResource();
TextFlowTarget target = new TextFlowTarget();
target.setContent("hei verden");
target.setDescription("translation of hello world");
target.setResId("tf1");
target.setState(ContentState.Approved);
Person person = new Person("email@example.com", "Translator Name");
target.setTranslator(person);
trans.getTextFlowTargets().add(target);
return trans;
}
private Resource createSourceResource(String name)
{
Resource sr = new Resource(name);
sr.setContentType(ContentType.TextPlain);
sr.setLang(LocaleId.EN);
sr.setType(ResourceType.FILE);
return sr;
}
private void doGetandAssertThatResourceListContainsNItems(int n)
{
ClientResponse<List<ResourceMeta>> resources = transResource.get(null);
assertThat(resources.getResponseStatus(), is(Status.OK));
assertThat(resources.getEntity().size(), is(n));
}
private Resource newDoc(String id, TextFlow... textFlows)
{
Resource doc = new Resource(id);
doc.setLang(LocaleId.EN);
doc.setContentType(ContentType.TextPlain);
doc.setType(ResourceType.FILE);
doc.setRevision(null);
for (TextFlow textFlow : textFlows)
{
doc.getTextFlows().add(textFlow);
}
return doc;
}
private TextFlow newTextFlow(String id, String sourceContent, String sourceComment)
{
TextFlow textFlow = new TextFlow(id, LocaleId.EN);
textFlow.setContent(sourceContent);
if (sourceComment != null)
getOrAddComment(textFlow).setValue(sourceComment);
return textFlow;
}
private TextFlowTarget newTextFlowTarget(String id, String targetContent, String targetComment)
{
TextFlowTarget target = new TextFlowTarget();
target.setResId(id);
target.setState(ContentState.Approved);
target.setContent(targetContent);
if (targetComment != null)
getOrAddComment(target).setValue(targetComment);
return target;
}
SimpleComment getOrAddComment(TextFlow tf)
{
return tf.getExtensions(true).findOrAddByType(SimpleComment.class);
}
SimpleComment getOrAddComment(TextFlowTarget tft)
{
return tft.getExtensions(true).findOrAddByType(SimpleComment.class);
}
private Resource putPo1()
{
String id = "foo.pot";
TextFlow textflow = newTextFlow("FOOD", "Slime Mould", "POT comment");
PotEntryHeader poData = textflow.getExtensions(true).findOrAddByType(PotEntryHeader.class);
poData.setContext("context");
List<String> flags = poData.getFlags();
flags.add("no-c-format");
flags.add("flag2");
List<String> refs = poData.getReferences();
refs.add("ref1.xml:7");
refs.add("ref1.xml:21");
Resource doc = newDoc(id, textflow);
PoHeader poHeader = new PoHeader();
poHeader.setComment("poheader comment");
List<HeaderEntry> poEntries = poHeader.getEntries();
poEntries.add(new HeaderEntry("Project-Id-Version", "en"));
poEntries.add(new HeaderEntry("Content-Type", "application/x-publican; charset=UTF-8\n"));
doc.getExtensions(true).add(poHeader);
log.debug("{}", doc);
Response response = transResource.putResource(id, doc, extGettextComment);
assertThat(response.getStatus(), isOneOf(200, 201));
return doc;
}
private TranslationsResource putPoTarget1()
{
String id = "foo.pot";
TranslationsResource tr = new TranslationsResource();
TextFlowTarget target = newTextFlowTarget("FOOD", "Sauerkraut", "translator comment");
tr.getTextFlowTargets().add(target);
PoTargetHeader targetHeader = new PoTargetHeader();
targetHeader.setComment("target comment");
List<HeaderEntry> entries = targetHeader.getEntries();
entries.add(new HeaderEntry("Project-Id-Version", "ja"));
tr.getExtensions(true).add(targetHeader);
transResource.putTranslations(id, DE, tr, extGettextComment);
return tr;
}
private Resource putDoc1(boolean putTarget)
{
String id = DOC1_NAME;
Resource doc = newDoc(id, newTextFlow("FOOD", "Slime Mould", "slime mould comment"));
Response response = transResource.putResource(id, doc, extComment);
assertThat(response.getStatus(), isOneOf(200, 201));
if (putTarget)
putTarget1();
return doc;
}
protected TranslationsResource putTarget1()
{
String id = DOC1_NAME;
TranslationsResource tr = new TranslationsResource();
TextFlowTarget target = newTextFlowTarget("FOOD", "Sauerkraut", null);
tr.getTextFlowTargets().add(target);
transResource.putTranslations(id, DE, tr, extGettextComment);
return tr;
}
private void dontExpectTarget1()
{
String id = DOC1_NAME;
dontExpectTarget(id, DE);
}
private void expectTarget1(TranslationsResource target1)
{
String id = DOC1_NAME;
expectTarget(true, id, DE, target1);
}
private Resource putDoc1a(boolean putTarget)
{
String id = DOC1_NAME;
Resource doc = newDoc(id, newTextFlow("HELLO", "Hello World", null));
Response response = transResource.putResource(id, doc, extComment);
assertThat(response.getStatus(), isOneOf(200, 201));
if (putTarget)
putTarget1a();
return doc;
}
protected TranslationsResource putTarget1a()
{
String id = DOC1_NAME;
TranslationsResource tr = new TranslationsResource();
TextFlowTarget target = newTextFlowTarget("HELLO", "Bonjour le Monde", "bon jour comment");
tr.getTextFlowTargets().add(target);
transResource.putTranslations(id, FR, tr, extGettextComment);
return tr;
}
private void dontExpectTarget1a()
{
String id = DOC1_NAME;
dontExpectTarget(id, FR);
}
private void expectTarget1a(TranslationsResource target1a)
{
String id = DOC1_NAME;
expectTarget(true, id, FR, target1a);
}
private void deleteDoc1()
{
deleteDoc(DOC1_NAME);
}
private void deleteDoc2()
{
deleteDoc(DOC2_NAME);
}
protected void deleteDoc(String id)
{
Response response = transResource.deleteResource(id);
assertThat(response.getStatus(), is(200));
}
private Resource postDoc2(boolean putTarget)
{
String id = DOC2_NAME;
Resource doc = newDoc(id, newTextFlow("HELLO", "Hello World", "hello comment"));
Response response = transResource.post(doc, extComment, true);
assertThat(response.getStatus(), is(201));
if (putTarget)
putTarget2();
return doc;
}
protected TranslationsResource putTarget2()
{
String id = DOC2_NAME;
TranslationsResource tr = new TranslationsResource();
TextFlowTarget target = newTextFlowTarget("HELLO", "Bonjour le Monde", null);
tr.getTextFlowTargets().add(target);
transResource.putTranslations(id, FR, tr, extGettextComment);
return tr;
}
private void dontExpectTarget2()
{
String id = DOC2_NAME;
dontExpectTarget(id, FR);
}
private void expectTarget2(TranslationsResource target2)
{
String id = DOC2_NAME;
expectTarget(true, id, FR, target2);
}
private void verifyObsoleteDocument(final String docID) throws Exception
{
HProjectIteration iteration = projectIterationDAO.getBySlug(projectSlug, iter);
Map<String, HDocument> allDocuments = iteration.getAllDocuments();
HDocument hDocument = allDocuments.get(docID);
// FIXME hDocument is coming back null
// Assert.assertNotNull(hDocument);
// Assert.assertTrue(hDocument.isObsolete());
}
private void verifyObsoleteResource(final String docID, final String resourceID) throws Exception
{
HProjectIteration iteration = projectIterationDAO.getBySlug(projectSlug, iter);
Map<String, HDocument> allDocuments = iteration.getAllDocuments();
HDocument hDocument = allDocuments.get(docID);
// FIXME hDocument is coming back null
// HTextFlow hResource = hDocument.getAllTextFlows().get(resourceID);
// Assert.assertNotNull(hResource);
// Assert.assertTrue(hResource.isObsolete());
}
}
|
package task.timer.model;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
public class ManageEntity implements IEntityManager {
private SessionFactory factory;
private EntityType entityType;
public ManageEntity(EntityType entityType){
this.entityType = entityType;
try {
factory=new Configuration().configure().buildSessionFactory();}
catch(Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public ManageEntity(SessionFactory factory){
this.factory = factory;
}
public ManageEntity(SessionFactory factory, EntityType entityType){
this.factory = factory;
this.entityType = entityType;
}
@Override
public Integer add(AbstractEntity entity) {
Session session = factory.openSession();
Transaction tx = null;
Integer entityID = null;
try{
tx = session.beginTransaction();
entityID = (Integer) session.save(entity);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return entityID;
}
/*@Override
public void update(int id, AbstractEntity newEntity) throws ClassNotFoundException {
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
AbstractEntity existingEntity =
(AbstractEntity)session.get(Class.forName(entityType.toString()), id);
existingEntity = newEntity;
session.update(existingEntity);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}*/
@Override
public void update(AbstractEntity newEntity) throws ClassNotFoundException {
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
session.update(newEntity);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
@Override
public void delete(int id) throws ClassNotFoundException {
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
AbstractEntity existingEntity =
(AbstractEntity)session.get(Class.forName(entityType.getClassType()), id);
session.delete(existingEntity);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
@Override
public List<AbstractEntity> list(){
Session session = factory.openSession();
Transaction tx = null;
List<AbstractEntity> entities = null;
try{
tx = session.beginTransaction();
entities = session.createQuery("from " + entityType).list();
tx.commit();
return entities;
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return entities;
}
}
|
package org.eclipse.persistence.testing.tests.jpa.complexaggregate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.persistence.config.QueryHints;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.internal.sessions.DatabaseSessionImpl;
import org.eclipse.persistence.testing.framework.JoinedAttributeTestHelper;
import org.eclipse.persistence.testing.framework.TestErrorException;
import org.eclipse.persistence.testing.framework.junit.JUnitTestCase;
import org.eclipse.persistence.testing.models.jpa.complexaggregate.Body;
import org.eclipse.persistence.testing.models.jpa.complexaggregate.CitySlicker;
import org.eclipse.persistence.testing.models.jpa.complexaggregate.CoachVitals;
import org.eclipse.persistence.testing.models.jpa.complexaggregate.ComplexAggregateTableCreator;
import org.eclipse.persistence.testing.models.jpa.complexaggregate.CountryDweller;
import org.eclipse.persistence.testing.models.jpa.complexaggregate.Heart;
import org.eclipse.persistence.testing.models.jpa.complexaggregate.HockeyCoach;
import org.eclipse.persistence.testing.models.jpa.complexaggregate.HockeyPlayer;
import org.eclipse.persistence.testing.models.jpa.complexaggregate.HockeyTeam;
import org.eclipse.persistence.testing.models.jpa.complexaggregate.Name;
import org.eclipse.persistence.testing.models.jpa.complexaggregate.PersonalVitals;
import org.eclipse.persistence.testing.models.jpa.complexaggregate.Role;
import org.eclipse.persistence.testing.models.jpa.complexaggregate.TeamVitals;
import org.eclipse.persistence.testing.models.jpa.complexaggregate.Torso;
import org.eclipse.persistence.testing.models.jpa.complexaggregate.Vitals;
import org.eclipse.persistence.testing.models.jpa.complexaggregate.World;
/**
* <p><b>Purpose</b>: To JPA with the complex aggregate test model.
*/
public class ComplexAggregateTestSuite extends JUnitTestCase {
public ComplexAggregateTestSuite() {
}
public ComplexAggregateTestSuite(String name) {
super(name);
}
/**
* The setup is done as a test, both to record its failure, and to allow execution in the server.
*/
public void testSetup() {
new ComplexAggregateTableCreator().replaceTables(getDatabaseSession());
clearCache();
}
public static Test suite() {
TestSuite suite = new TestSuite();
suite.setName("ComplexAggregateTestSuite");
suite.addTest(new ComplexAggregateTestSuite("testSetup"));
suite.addTest(new ComplexAggregateTestSuite("testMapKeyColumnMerge"));
suite.addTest(new ComplexAggregateTestSuite("testAggregatePrimaryKey"));
suite.addTest(new ComplexAggregateTestSuite("testAggregatePrimaryKeyOrderBy"));
suite.addTest(new ComplexAggregateTestSuite("testNestedAggregate"));
suite.addTest(new ComplexAggregateTestSuite("testNestedAggregatePrimaryKey"));
suite.addTest(new ComplexAggregateTestSuite("testAggregateReadOnlyMapKey"));
suite.addTest(new ComplexAggregateTestSuite("testComplexAggregateJoin"));
return suite;
}
public void testMapKeyColumnMerge() {
clearCache();
EntityManager em = createEntityManager();
try {
HockeyPlayer player = new HockeyPlayer();
player.setFirstName("Guy");
player.setLastName("Flower");
// must have non null Vitals and TeamVitals because TeamVitals has a target foreign key mapping, therefore allowingNull automatically set to false
Vitals vitals = new Vitals();
vitals.setTeamVitals(new TeamVitals());
player.setVitals(vitals);
HockeyPlayer player2 = new HockeyPlayer();
player2.setFirstName("Power");
player2.setLastName("Flower");;
// must have non null Vitals and TeamVitals because TeamVitals has a target foreign key mapping, therefore allowingNull automatically set to false
Vitals vitals2 = new Vitals();
vitals2.setTeamVitals(new TeamVitals());
player2.setVitals(vitals2);
HockeyCoach coach = new HockeyCoach();
coach.setFirstName("Scott");
coach.setLastName("Arrowman");
CoachVitals cVitals = new CoachVitals();
PersonalVitals pVitals = new PersonalVitals();
pVitals.setAge(45);
pVitals.setHeight(3.3);
pVitals.setWeight(333);
cVitals.setPersonalVitals(pVitals);
coach.setVitals(cVitals);
beginTransaction(em);
em.persist(player);
em.persist(player2);
em.persist(coach);
Object playerId = player.getPlayerId();
Object player2Id = player2.getPlayerId();
Object coachId = coach.getId();
coach.addFavouritePlayer(player);
commitTransaction(em);
closeEntityManager(em);
em = createEntityManager();
beginTransaction(em);
// ((ChangeTracker)coach)._persistence_setPropertyChangeListener(null);
// ((IndirectMap)coach.getFavouritePlayers())._persistence_setPropertyChangeListener(null);
coach.addFavouritePlayer(player2);
em.merge(coach);
commitTransaction(em);
beginTransaction(em);
player = em.find(HockeyPlayer.class, playerId);
player2 = em.find(HockeyPlayer.class, player2Id);
coach = em.find(HockeyCoach.class, coachId);
if (player != null){
em.remove(player);
}
if (player2 != null){
em.remove(player2);
}
if (coach != null){
em.remove(coach);
}
commitTransaction(em);
} finally {
closeEntityManagerAndTransaction(em);
}
}
public void testAggregatePrimaryKey() {
clearCache();
EntityManager em = createEntityManager();
try {
Name name1 = new Name();
name1.setFirstName("Tom");
name1.setLastName("Ware");
CountryDweller countryDweller = new CountryDweller();
countryDweller.setAge(30);
countryDweller.setName(name1);
CitySlicker citySlicker = new CitySlicker();
citySlicker.setAge(53);
// Bug 300696 - Invalid tests: sharing embedded objects is not allowed
// Changed the test to use clone instead of sharing the same Name between the two Entities.
Name name1Clone = (Name)name1.clone();
citySlicker.setName(name1Clone);
Name name2 = new Name();
name2.setFirstName("Guy");
name2.setLastName("Pelletier");
CountryDweller countryDweller2 = new CountryDweller();
countryDweller2.setAge(65);
countryDweller2.setName(name2);
beginTransaction(em);
em.persist(countryDweller);
em.persist(countryDweller2);
em.persist(citySlicker);
commitTransaction(em);
// Clear the cache.
clearCache();
em.clear();
// Now read them back in and delete them.
beginTransaction(em);
// Note that in Identity case name1Clone may no longer have the same id as name1
CitySlicker cs = em.find(CitySlicker.class, name1Clone);
CountryDweller cd = em.merge(countryDweller);
CountryDweller cd2 = em.merge(countryDweller2);
em.remove(cs);
em.remove(cd);
em.remove(cd2);
commitTransaction(em);
} catch (RuntimeException e) {
closeEntityManagerAndTransaction(em);
throw e;
}
}
public void testAggregatePrimaryKeyOrderBy() {
clearCache();
EntityManager em = createEntityManager();
try {
beginTransaction(em);
World world = new World();
// First pair
Name name1 = new Name();
name1.setFirstName("Guy");
name1.setLastName("Pelletier");
CountryDweller countryDweller1 = new CountryDweller();
countryDweller1.setAge(30);
countryDweller1.setName(name1);
countryDweller1.setGender("Male");
em.persist(countryDweller1);
world.addCountryDweller(countryDweller1);
CitySlicker citySlicker1 = new CitySlicker();
citySlicker1.setAge(53);
// Bug 300696 - Invalid tests: sharing embedded objects is not allowed
// Changed the test to use clone instead of sharing the same Name between the two Entities.
Name name1Clone = (Name)name1.clone();
citySlicker1.setName(name1Clone);
citySlicker1.setGender("Male");
em.persist(citySlicker1);
world.addCitySlicker(citySlicker1);
// Second pair
Name name2 = new Name();
name2.setFirstName("Steve");
name2.setLastName("Harp");
CountryDweller countryDweller2 = new CountryDweller();
countryDweller2.setAge(28);
countryDweller2.setName(name2);
countryDweller2.setGender("Male");
em.persist(countryDweller2);
world.addCountryDweller(countryDweller2);
CitySlicker citySlicker2 = new CitySlicker();
citySlicker2.setAge(41);
// Bug 300696 - Invalid tests: sharing embedded objects is not allowed
// Changed the test to use clone instead of sharing the same Name between the two Entities.
Name name2Clone = (Name)name2.clone();
citySlicker2.setName(name2Clone);
citySlicker2.setGender("Male");
em.persist(citySlicker2);
world.addCitySlicker(citySlicker2);
// Third pair
Name name3 = new Name();
name3.setFirstName("Jesse");
name3.setLastName("Petoncle");
CountryDweller countryDweller3 = new CountryDweller();
countryDweller3.setAge(48);
countryDweller3.setName(name3);
countryDweller3.setGender("Male");
em.persist(countryDweller3);
world.addCountryDweller(countryDweller3);
CitySlicker citySlicker3 = new CitySlicker();
citySlicker3.setAge(76);
// Bug 300696 - Invalid tests: sharing embedded objects is not allowed
// Changed the test to use clone instead of sharing the same Name between the two Entities.
Name name3Clone = (Name)name3.clone();
citySlicker3.setName(name3Clone);
citySlicker3.setGender("Female");
em.persist(citySlicker3);
world.addCitySlicker(citySlicker3);
em.persist(world);
commitTransaction(em);
// Clear the cache.
clearCache();
em.clear();
// Now read them back in and delete them.
beginTransaction(em);
World w = em.find(World.class, world.getId());
Collection css = w.getCitySlickers();
css.toString();
Collection cds = w.getCountryDwellers();
cds.toString();
// Check the ordering
// JBS - Ordering check removed as order is random based on class method order which is not consistent in Java.
//citySlickersAreOrdered = ((CitySlicker) css.elementAt(0)).getName().getFirstName().equals("Guy") && ((CitySlicker) css.elementAt(1)).getName().getFirstName().equals("Jesse") && ((CitySlicker) css.elementAt(2)).getName().getFirstName().equals("Steve");
//countryDwellersAreOrdered = ((CountryDweller) cds.elementAt(0)).getAge() == 28 && ((CountryDweller) cds.elementAt(1)).getAge() == 30 && ((CountryDweller) cds.elementAt(2)).getAge() == 48;
// Make sure we delete them
// Note that in Identity case name1Clone may no longer have the same id as name1
CitySlicker cs1 = em.find(CitySlicker.class, name1Clone);
em.remove(cs1);
CitySlicker cs2 = em.find(CitySlicker.class, name2Clone);
em.remove(cs2);
CitySlicker cs3 = em.find(CitySlicker.class, name3Clone);
em.remove(cs3);
CountryDweller cd1 = em.merge(countryDweller1);
em.remove(cd1);
CountryDweller cd2 = em.merge(countryDweller2);
em.remove(cd2);
CountryDweller cd3 = em.merge(countryDweller3);
em.remove(cd3);
commitTransaction(em);
} catch (RuntimeException e) {
closeEntityManagerAndTransaction(em);
throw e;
}
}
public void testNestedAggregate() {
int[] teamIDs = new int[3];
clearCache();
//////// Team 1 ////////
HockeyTeam team1 = new HockeyTeam();
team1.setName("Axemen");
team1.setAwayColor("Red");
team1.setHomeColor("White");
team1.setLevel("Division 5");
//////// Team 2 ////////
HockeyTeam team2 = new HockeyTeam();
team2.setName("Cartier Partners");
team2.setAwayColor("Black");
team2.setHomeColor("White");
team2.setLevel("Division 2");
//////// Team 3 ////////
HockeyTeam team3 = new HockeyTeam();
team3.setName("Dead Last");
team3.setAwayColor("Blue");
team3.setHomeColor("White");
team3.setLevel("Division 4");
//////// Player 1 ////////
HockeyPlayer player1 = new HockeyPlayer();
player1.setFirstName("Guy");
player1.setLastName("Pelletier");
PersonalVitals personalVitals1 = new PersonalVitals();
personalVitals1.setAge(29);
personalVitals1.setHeight(1.80);
personalVitals1.setWeight(180);
TeamVitals teamVitals1 = new TeamVitals();
teamVitals1.setHockeyTeam(team2);
team2.getPlayers().add(player1);
teamVitals1.setJerseyNumber(20);
teamVitals1.setPosition("Goalie");
teamVitals1.getRoles().add(new Role("Stop pucks!"));
Vitals vitals1 = new Vitals();
vitals1.setPersonalVitals(personalVitals1);
vitals1.setTeamVitals(teamVitals1);
player1.setVitals(vitals1);
//////// Player 2 ////////
HockeyPlayer player2 = new HockeyPlayer();
player2.setFirstName("Dave");
player2.setLastName("McCann");
PersonalVitals personalVitals2 = new PersonalVitals();
personalVitals2.setAge(35);
personalVitals2.setHeight(1.77);
personalVitals2.setWeight(165);
TeamVitals teamVitals2 = new TeamVitals();
teamVitals2.setHockeyTeam(team1);
team1.getPlayers().add(player2);
teamVitals2.setJerseyNumber(70);
teamVitals2.setPosition("Left wing");
teamVitals2.getRoles().add(new Role("Power play unit"));
teamVitals2.getRoles().add(new Role("Face-off specialist"));
Vitals vitals2 = new Vitals();
vitals2.setPersonalVitals(personalVitals2);
vitals2.setTeamVitals(teamVitals2);
player2.setVitals(vitals2);
//////// Player 3 ////////
HockeyPlayer player3 = new HockeyPlayer();
player3.setFirstName("Tom");
player3.setLastName("Ware");
PersonalVitals personalVitals3 = new PersonalVitals();
personalVitals3.setAge(30);
personalVitals3.setHeight(1.83);
personalVitals3.setWeight(200);
TeamVitals teamVitals3 = new TeamVitals();
teamVitals3.setHockeyTeam(team1);
team1.getPlayers().add(player3);
teamVitals3.setJerseyNumber(12);
teamVitals3.setPosition("Defence");
teamVitals3.getRoles().add(new Role("Penalty kill unit"));
Vitals vitals3 = new Vitals();
vitals3.setPersonalVitals(personalVitals3);
vitals3.setTeamVitals(teamVitals3);
player3.setVitals(vitals3);
//////// Player 4 ////////
HockeyPlayer player4 = new HockeyPlayer();
player4.setFirstName("George");
player4.setLastName("Robinson");
PersonalVitals personalVitals4 = new PersonalVitals();
personalVitals4.setAge(32);
personalVitals4.setHeight(1.86);
personalVitals4.setWeight(210);
TeamVitals teamVitals4 = new TeamVitals();
teamVitals4.setHockeyTeam(team3);
team3.getPlayers().add(player4);
teamVitals4.setJerseyNumber(6);
teamVitals4.setPosition("Center");
teamVitals4.getRoles().add(new Role("Power play unit"));
teamVitals4.getRoles().add(new Role("Goon"));
Vitals vitals4 = new Vitals();
vitals4.setPersonalVitals(personalVitals4);
vitals4.setTeamVitals(teamVitals4);
player4.setVitals(vitals4);
//////// Player 5 ////////
HockeyPlayer player5 = new HockeyPlayer();
player5.setFirstName("Andrew");
player5.setLastName("Glennie");
PersonalVitals personalVitals5 = new PersonalVitals();
personalVitals5.setAge(31);
personalVitals5.setHeight(1.80);
personalVitals5.setWeight(205);
TeamVitals teamVitals5 = new TeamVitals();
teamVitals5.setHockeyTeam(team3);
team3.getPlayers().add(player5);
teamVitals5.setJerseyNumber(7);
teamVitals5.setPosition("Right wing");
Vitals vitals5 = new Vitals();
vitals5.setPersonalVitals(personalVitals5);
vitals5.setTeamVitals(teamVitals5);
player5.setVitals(vitals5);
//////// Player 6 ////////
HockeyPlayer player6 = new HockeyPlayer();
player6.setFirstName("David");
player6.setLastName("Whittaker");
PersonalVitals personalVitals6 = new PersonalVitals();
personalVitals6.setAge(32);
personalVitals6.setHeight(1.83);
personalVitals6.setWeight(190);
TeamVitals teamVitals6 = new TeamVitals();
teamVitals6.setHockeyTeam(team2);
team2.getPlayers().add(player6);
teamVitals6.setJerseyNumber(17);
teamVitals6.setPosition("Defence");
Vitals vitals6 = new Vitals();
vitals6.setPersonalVitals(personalVitals6);
vitals6.setTeamVitals(teamVitals6);
player6.setVitals(vitals6);
//////// Coach 1 ////////
HockeyCoach coach1 = new HockeyCoach();
coach1.setFirstName("Don");
coach1.setLastName("Hyslop");
PersonalVitals coachPersonalVitals1 = new PersonalVitals();
coachPersonalVitals1.setAge(55);
coachPersonalVitals1.setHeight(1.85);
coachPersonalVitals1.setWeight(200);
CoachVitals coachVitals1 = new CoachVitals();
coachVitals1.setPersonalVitals(coachPersonalVitals1);
coachVitals1.setHockeyTeam(team1);
team1.getCoaches().add(coach1);
coach1.setVitals(coachVitals1);
//////// Coach 2 ////////
HockeyCoach coach2 = new HockeyCoach();
coach2.setFirstName("Al");
coach2.setLastName("Montoya");
PersonalVitals coachPersonalVitals2 = new PersonalVitals();
coachPersonalVitals2.setAge(63);
coachPersonalVitals2.setHeight(1.86);
coachPersonalVitals2.setWeight(213);
CoachVitals coachVitals2 = new CoachVitals();
coachVitals2.setPersonalVitals(coachPersonalVitals2);
coachVitals2.setHockeyTeam(team2);
team2.getCoaches().add(coach2);
coach2.setVitals(coachVitals2);
//////// Coach 3 ////////
HockeyCoach coach3 = new HockeyCoach();
coach3.setFirstName("Guy");
coach3.setLastName("Carbonneau");
PersonalVitals coachPersonalVitals3 = new PersonalVitals();
coachPersonalVitals3.setAge(47);
coachPersonalVitals3.setHeight(1.91);
coachPersonalVitals3.setWeight(191);
CoachVitals coachVitals3 = new CoachVitals();
coachVitals3.setPersonalVitals(coachPersonalVitals3);
coachVitals3.setHockeyTeam(team3);
team3.getCoaches().add(coach3);
coach3.setVitals(coachVitals3);
//////// Coach 4 ////////
HockeyCoach coach4 = new HockeyCoach();
coach4.setFirstName("Walter");
coach4.setLastName("Mullen");
PersonalVitals coachPersonalVitals4 = new PersonalVitals();
coachPersonalVitals4.setAge(67);
coachPersonalVitals4.setHeight(1.94);
coachPersonalVitals4.setWeight(187);
CoachVitals coachVitals4 = new CoachVitals();
coachVitals4.setPersonalVitals(coachPersonalVitals4);
coachVitals4.setHockeyTeam(team1);
team1.getCoaches().add(coach4);
coach4.setVitals(coachVitals4);
//////// Coach 5 ////////
HockeyCoach coach5 = new HockeyCoach();
coach5.setFirstName("Ben");
coach5.setLastName("Gasket");
PersonalVitals coachPersonalVitals5 = new PersonalVitals();
coachPersonalVitals5.setAge(33);
coachPersonalVitals5.setHeight(1.67);
coachPersonalVitals5.setWeight(155);
CoachVitals coachVitals5 = new CoachVitals();
coachVitals5.setPersonalVitals(coachPersonalVitals5);
coachVitals5.setHockeyTeam(team2);
team2.getCoaches().add(coach5);
coach5.setVitals(coachVitals5);
//////// Coach 6 ////////
HockeyCoach coach6 = new HockeyCoach();
coach6.setFirstName("Jim");
coach6.setLastName("Balogna");
PersonalVitals coachPersonalVitals6 = new PersonalVitals();
coachPersonalVitals6.setAge(37);
coachPersonalVitals6.setHeight(1.77);
coachPersonalVitals6.setWeight(179);
CoachVitals coachVitals6 = new CoachVitals();
coachVitals6.setPersonalVitals(coachPersonalVitals5);
coachVitals6.setHockeyTeam(team3);
team3.getCoaches().add(coach6);
coach6.setVitals(coachVitals6);
EntityManager em = createEntityManager();
//////// Commit the new objects ////////
beginTransaction(em);
try{
em.persist(team1);
teamIDs[0] = team1.getId();
em.persist(team2);
teamIDs[1] = team2.getId();
em.persist(team3);
teamIDs[2] = team3.getId();
em.persist(player1);
em.persist(player2);
em.persist(player3);
em.persist(player4);
em.persist(player5);
em.persist(player6);
em.persist(coach1);
em.persist(coach2);
em.persist(coach3);
em.persist(coach4);
em.persist(coach5);
em.persist(coach6);
commitTransaction(em);
} catch (RuntimeException ex) {
closeEntityManagerAndTransaction(em);
throw ex;
}
em = createEntityManager();
// Check the cache for the objects
checkTeam(teamIDs[0], em);
checkTeam(teamIDs[1], em);
checkTeam(teamIDs[2], em);
// Initialize the identity map to make sure they were persisted
clearCache();
em = createEntityManager();
em.clear();
checkTeam(teamIDs[0], em);
checkTeam(teamIDs[1], em);
checkTeam(teamIDs[2], em);
// Verify the order by on coaches worked for team 1 (teamIDs[0])
HockeyTeam team = em.find(HockeyTeam.class, teamIDs[0]);
if (team.getCoaches().get(0).getVitals().getPersonalVitals().getAge() != 67) {
throw new TestErrorException("The order by specification on age for hockey coaches was not observed: " + team.getCoaches());
}
}
private void checkTeam(int id, EntityManager em) {
HockeyTeam team = em.find(HockeyTeam.class, id);
if (team == null){
throw new TestErrorException("Hockey team with ID: " + id + ", was not created.");
}
if (team.getPlayers().size() != 2) {
throw new TestErrorException("Hockey team with ID: " + id + ", did not have 2 players, had: " + team.getPlayers().size());
}
if (team.getCoaches().size() != 2) {
throw new TestErrorException("Hockey team with ID: " + id + ", did not have 2 coach, had: " + team.getCoaches().size());
}
}
public void testNestedAggregatePrimaryKey() {
clearCache();
Torso torso;
EntityManager em = createEntityManager();
try {
Body body = new Body();
torso = new Torso();
Heart heart = new Heart();
heart.setSize(8);
torso.setHeart(heart);
body.setTorso(torso);
beginTransaction(em);
em.persist(body);
commitTransaction(em);
} catch (Exception e) {
throw new TestErrorException("Exception caught when persisting the new body: " + e.getMessage());
} finally {
closeEntityManager(em);
}
em = createEntityManager();
Exception m_testException = null;
DatabaseSessionImpl m_session = getDatabaseSession();
Body m_refreshedBody = null;
// Try to read the body back, clear the cache first.
try {
em.clear();
m_session.getIdentityMapAccessor().initializeAllIdentityMaps();
m_refreshedBody = em.find(Body.class, torso);
} catch (Exception e) {
m_testException = e;
}
if (m_testException != null) {
throw new TestErrorException("Exception caught reading back the persisted body: " + m_testException);
}
if (m_refreshedBody == null) {
throw new TestErrorException("Unable to read back the persisted body");
}
ClassDescriptor descriptor = getDatabaseSession().getClassDescriptor(Body.class);
Object pks = descriptor.getObjectBuilder().extractPrimaryKeyFromObject(m_refreshedBody, m_session);
Torso createdTorso = (Torso) descriptor.getCMPPolicy().createPrimaryKeyInstanceFromId(pks, m_session);
assertTrue("PK's do not match.", m_refreshedBody.getTorso().equals(createdTorso));
}
public void testAggregateReadOnlyMapKey() {
clearCache();
HockeyPlayer player = new HockeyPlayer();
player.setFirstName("Guy");
player.setLastName("Flower");
PersonalVitals personalVitals2 = new PersonalVitals();
personalVitals2.setAge(45);
personalVitals2.setHeight(1.80);
personalVitals2.setWeight(185);
TeamVitals teamVitals2 = new TeamVitals();
teamVitals2.setJerseyNumber(70);
teamVitals2.setPosition("Right wing");
Vitals vitals2 = new Vitals();
vitals2.setPersonalVitals(personalVitals2);
vitals2.setTeamVitals(teamVitals2);
player.setVitals(vitals2);
HockeyCoach coach = new HockeyCoach();
coach.setFirstName("Scott");
coach.setLastName("Arrowman");
PersonalVitals coachPersonalVitals1 = new PersonalVitals();
coachPersonalVitals1.setAge(65);
coachPersonalVitals1.setHeight(1.85);
coachPersonalVitals1.setWeight(200);
CoachVitals coachVitals1 = new CoachVitals();
coachVitals1.setPersonalVitals(coachPersonalVitals1);
coach.setVitals(coachVitals1);
EntityManager em = createEntityManager();
beginTransaction(em);
try {
em.persist(player);
em.persist(coach);
commitTransaction(em);
Object playerId = player.getPlayerId();
Object coachId = coach.getId();
clearCache();
em.clear();
beginTransaction(em);
player = em.find(HockeyPlayer.class, player.getPlayerId());
coach = em.find(HockeyCoach.class, coach.getId());
coach.addFavouritePlayer(player);
commitTransaction(em);
beginTransaction(em);
player = em.find(HockeyPlayer.class, playerId);
coach = em.find(HockeyCoach.class, coachId);
if (player != null){
em.remove(player);
}
if (coach != null){
em.remove(coach);
}
commitTransaction(em);
} finally {
closeEntityManagerAndTransaction(em);
}
}
public void testComplexAggregateJoin() {
clearCache();
HockeyTeam team1 = new HockeyTeam();
team1.setName("Axemen");
team1.setAwayColor("Red");
team1.setHomeColor("White");
team1.setLevel("Division 5");
////////Player 1 ////////
HockeyPlayer player1 = new HockeyPlayer();
player1.setFirstName("Guy");
player1.setLastName("Pelletier");
PersonalVitals personalVitals1 = new PersonalVitals();
personalVitals1.setAge(29);
personalVitals1.setHeight(1.80);
personalVitals1.setWeight(180);
TeamVitals teamVitals1 = new TeamVitals();
teamVitals1.setJerseyNumber(20);
teamVitals1.setPosition("Goalie");
teamVitals1.getRoles().add(new Role("Stop pucks!"));
Vitals vitals1 = new Vitals();
vitals1.setPersonalVitals(personalVitals1);
vitals1.setTeamVitals(teamVitals1);
player1.setVitals(vitals1);
////////Coach 1 ////////
HockeyCoach coach1 = new HockeyCoach();
coach1.setFirstName("Don");
coach1.setLastName("Hyslop");
PersonalVitals coachPersonalVitals1 = new PersonalVitals();
coachPersonalVitals1.setAge(55);
coachPersonalVitals1.setHeight(1.85);
coachPersonalVitals1.setWeight(200);
CoachVitals coachVitals1 = new CoachVitals();
coachVitals1.setPersonalVitals(coachPersonalVitals1);
coach1.setVitals(coachVitals1);
////////persist the new objects ////////
EntityManager em = createEntityManager();
beginTransaction(em);
em.persist(team1);
em.persist(player1);
em.persist(coach1);
//setup relationships:
teamVitals1.setHockeyTeam(team1);
team1.getPlayers().add(player1);
team1.getCoaches().add(coach1);
coachVitals1.setHockeyTeam(team1);
em.flush();
DatabaseSessionImpl m_session = getDatabaseSession();
List hockeyCoachResults = null;
List controledCoachList = null;
List controledPlayerList = null;
List hockeyPlayerResults = null;
try {
em.clear();
m_session.getIdentityMapAccessor().initializeAllIdentityMaps();
Query query1 = em.createQuery("Select a from HockeyCoach a where a.id = "+coach1.getId());
query1.setHint(QueryHints.LEFT_FETCH, "a.vitals.hockeyTeam");
hockeyCoachResults = query1.getResultList();
em.clear();
m_session.getIdentityMapAccessor().initializeAllIdentityMaps();
Query query2 = em.createQuery("Select z from HockeyPlayer z where z.playerId = "+player1.getPlayerId());
//query2.setHint(QueryHints.LEFT_FETCH, "z.coach");
query2.setHint(QueryHints.LEFT_FETCH, "z.vitals.teamVitals.hockeyTeam.coaches");
hockeyPlayerResults = query2.getResultList();
em.clear();
m_session.getIdentityMapAccessor().initializeAllIdentityMaps();
HockeyCoach expectedCoach = em.find(HockeyCoach.class, coach1.getId());
expectedCoach.getVitals().getHockeyTeam();
controledCoachList = new ArrayList<HockeyCoach>(1);
controledCoachList.add(expectedCoach);
em.clear();
m_session.getIdentityMapAccessor().initializeAllIdentityMaps();
HockeyPlayer expectedPlayer = em.find(HockeyPlayer.class, player1.getPlayerId());
expectedPlayer.getVitals().getTeamVitals().getHockeyTeam().getCoaches().size();
controledPlayerList = new ArrayList<HockeyPlayer>(1);
controledPlayerList.add(expectedPlayer);
em.clear();
m_session.getIdentityMapAccessor().initializeAllIdentityMaps();
} finally {
try {
closeEntityManagerAndTransaction(em);
} catch (RuntimeException re){
//ignore
}
}
String errorMsg = JoinedAttributeTestHelper.compareCollections(controledCoachList, hockeyCoachResults, m_session.getClassDescriptor(HockeyCoach.class), m_session);
if (errorMsg.length() > 0) {
throw new TestErrorException(errorMsg);
}
errorMsg = JoinedAttributeTestHelper.compareCollections(controledPlayerList, hockeyPlayerResults, m_session.getClassDescriptor(HockeyPlayer.class), m_session);
if (errorMsg.length() > 0) {
throw new TestErrorException(errorMsg);
}
}
}
|
package io.subutai.core.peer.impl.entity;
import org.junit.Test;
import io.subutai.core.peer.impl.entity.PeerData;
import static junit.framework.TestCase.assertEquals;
public class PeerDataTest
{
private static final String ID = "id";
private static final String SOURCE = "source";
private static final String INFO = "info";
PeerData peerData = new PeerData(ID, INFO,"","{}",1);
@Test
public void testSetNGetId() throws Exception
{
peerData.setId( ID );
assertEquals( ID, peerData.getId() );
}
// @Test
// public void testSetNGetSource() throws Exception
// peerData.setSource( SOURCE );
// assertEquals( SOURCE, peerData.getSource() );
@Test
public void testSetNGetInfo() throws Exception
{
peerData.setInfo( INFO );
assertEquals( INFO, peerData.getInfo() );
}
}
|
package net.sf.mmm.search.parser.impl;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This is the implementation of the
* {@link net.sf.mmm.search.parser.api.ContentParser} interface for Java sources
* (content with the mimetype "text/java-source").
*
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
*/
public class ContentParserJava extends ContentParserText {
/** the string used to separate package names */
private static final String PACKAGE_SEPARATOR = ".";
/** pattern to extract the package name */
private static final Pattern PACKAGE_PATTERN = Pattern.compile("package\\s+([\\w\\.]*).*");
/** pattern to extract the class name */
private static final Pattern CLASS_PATTERN = Pattern.compile("[\\sa-z]*(class|interface)\\s+(\\w*).*");
/** pattern to extract the author */
/**
* The constructor
*/
public ContentParserJava() {
super();
}
/**
* @see net.sf.mmm.search.parser.impl.ContentParserText#parseLine(java.util.Properties,
* java.lang.String)
*/
@Override
protected String parseLine(Properties properties, String line) {
String title = properties.getProperty(PROPERTY_KEY_TITLE);
if (title == null) {
Matcher m = PACKAGE_PATTERN.matcher(line);
if (m.matches()) {
title = m.group(1) + PACKAGE_SEPARATOR;
properties.setProperty(PROPERTY_KEY_TITLE, title);
}
}
if ((title != null) && (title.endsWith(PACKAGE_SEPARATOR))) {
Matcher m = CLASS_PATTERN.matcher(line);
if (m.matches()) {
title = title + m.group(2);
properties.setProperty(PROPERTY_KEY_TITLE, title);
}
// author tag can only appear before class name was detected...
parseProperty(properties, line, AUTHOR_PATTERN, PROPERTY_KEY_AUTHOR);
}
return line;
}
}
|
package net.stickycode.configured;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.stickycode.stereotype.component.StickyRepository;
@StickyRepository
public class InlineConfigurationRepository
implements ConfigurationRepository {
private Logger log = LoggerFactory.getLogger(getClass());
private List<Configuration> configurations = new ArrayList<Configuration>();
@Override
public Iterator<Configuration> iterator() {
return Collections.unmodifiableList(configurations).iterator();
}
@Override
public void register(Configuration configuration) {
assert configuration != null;
log.info("registering {}", configuration);
configurations.add(configuration);
}
}
|
package org.slc.sli.ingestion.transformation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.slc.sli.ingestion.NeutralRecord;
/**
* Transformer for Assessment Entities
*
* @author ifaybyshev
*
*/
public class AssessmentCombiner extends AbstractTransformationStrategy {
private static final Logger LOG = LoggerFactory.getLogger(AssessmentCombiner.class);
private Map<String, Map<Object, NeutralRecord>> collections;
private Map<String, Map<Object, NeutralRecord>> transformedCollections;
public AssessmentCombiner() {
this.collections = new HashMap<String, Map<Object, NeutralRecord>>();
this.transformedCollections = new HashMap<String, Map<Object, NeutralRecord>>();
}
/**
* The chaining of transformation steps. This implementation assumes that all data will be
* processed in "one-go"
*
*/
@Override
public void performTransformation() {
loadData();
transform();
persist();
}
public void loadData() {
LOG.info("Loading data for transformation.");
loadCollectionFromDb("assessment");
LOG.info("Assessment is loaded into local storage. Total Count = " + collections.get("assessment").size());
loadCollectionFromDb("assessmentFamily");
LOG.info("AssessmentFamily is loaded into local storage. Total Count = "
+ collections.get("assessmentFamily").size());
}
public void transform() {
LOG.debug("Transforming data: Injecting assessmentFamilies into assessment");
HashMap<Object, NeutralRecord> newCollection = new HashMap<Object, NeutralRecord>();
String key;
for (Map.Entry<Object, NeutralRecord> neutralRecordEntry : collections.get("assessment").entrySet()) {
NeutralRecord neutralRecord = neutralRecordEntry.getValue();
// get the key of parent
Map<String, Object> attrs = neutralRecord.getAttributes();
key = (String) attrs.get("parentAssessmentFamilyId");
String familyHierarchyName = "";
familyHierarchyName = getAssocationFamilyMap(key, new HashMap<String, Map<String, Object>>(),
familyHierarchyName);
attrs.put("assessmentFamilyHierarchyName", familyHierarchyName);
@SuppressWarnings("unchecked")
List<String> objectiveAssessmentRefs = (List<String>) attrs.get("objectiveAssessmentRefs");
List<Map<String, Object>> objectiveAssessments = new ArrayList<Map<String, Object>>();
if (objectiveAssessmentRefs != null && !(objectiveAssessmentRefs.isEmpty())) {
for (String objectiveAssessmentRef : objectiveAssessmentRefs) {
objectiveAssessments.add(getObjectiveAssessment(objectiveAssessmentRef));
}
attrs.put("objectiveAssessment", objectiveAssessments);
}
String assessmentPeriodDescriptorRef = (String) attrs.get("periodDescriptorRef");
if (assessmentPeriodDescriptorRef != null) {
attrs.put("assessmentPeriodDescriptor", getAssessmentPeriodDescriptor(assessmentPeriodDescriptorRef));
}
neutralRecord.setAttributes(attrs);
newCollection.put(neutralRecord.getRecordId(), neutralRecord);
}
transformedCollections.put("assessment", newCollection);
}
private Map<String, Object> getAssessmentPeriodDescriptor(String assessmentPeriodDescriptorRef) {
Map<String, String> paths = new HashMap<String, String>();
paths.put("body.codeValue", assessmentPeriodDescriptorRef);
Iterable<NeutralRecord> data = getNeutralRecordMongoAccess().getRecordRepository().findByPaths(
"assessmentPeriodDescriptor", paths);
if (data.iterator().hasNext()) {
return data.iterator().next().getAttributes();
}
return null;
}
private Map<String, Object> getObjectiveAssessment(String objectiveAssessmentRef) {
Map<String, String> paths = new HashMap<String, String>();
paths.put("body.id", objectiveAssessmentRef);
Iterable<NeutralRecord> data = getNeutralRecordMongoAccess().getRecordRepository().findByPaths(
"objectiveAssessment", paths);
Map<String, Object> objectiveAssessment = data.iterator().next().getAttributes();
objectiveAssessment.remove("id");
return objectiveAssessment;
// return null;
}
@SuppressWarnings("unchecked")
private String getAssocationFamilyMap(String key, HashMap<String, Map<String, Object>> deepFamilyMap,
String familyHierarchyName) {
Map<String, String> paths = new HashMap<String, String>();
paths.put("body.AssessmentFamilyIdentificationCode.ID", key);
Iterable<NeutralRecord> data = getNeutralRecordMongoAccess().getRecordRepository().findByPaths(
"assessmentFamily", paths);
Map<String, Object> associationAttrs;
ArrayList<Map<String, Object>> tempIdentificationCodes;
Map<String, Object> tempMap;
for (NeutralRecord tempNr : data) {
associationAttrs = tempNr.getAttributes();
if (associationAttrs.get("AssessmentFamilyIdentificationCode") instanceof ArrayList<?>) {
tempIdentificationCodes = (ArrayList<Map<String, Object>>) associationAttrs
.get("AssessmentFamilyIdentificationCode");
tempMap = tempIdentificationCodes.get(0);
if (familyHierarchyName.equals("")) {
familyHierarchyName = (String) associationAttrs.get("AssessmentFamilyTitle");
} else {
familyHierarchyName = associationAttrs.get("AssessmentFamilyTitle") + "." + familyHierarchyName;
}
deepFamilyMap.put((String) tempMap.get("ID"), associationAttrs);
}
// check if there are parent nodes
if (associationAttrs.containsKey("parentAssessmentFamilyId")
&& !deepFamilyMap.containsKey(associationAttrs.get("parentAssessmentFamilyId"))) {
familyHierarchyName = getAssocationFamilyMap((String) associationAttrs.get("parentAssessmentFamilyId"),
deepFamilyMap, familyHierarchyName);
}
}
return familyHierarchyName;
}
public void persist() {
LOG.info("Persisting transformed data to storage.");
// transformedCollections should have been populated in the transform() step.
for (Map.Entry<String, Map<Object, NeutralRecord>> collectionEntry : transformedCollections.entrySet()) {
for (Map.Entry<Object, NeutralRecord> neutralRecordEntry : collectionEntry.getValue().entrySet()) {
NeutralRecord neutralRecord = neutralRecordEntry.getValue();
neutralRecord.setRecordType(neutralRecord.getRecordType() + "_transformed");
getNeutralRecordMongoAccess().getRecordRepository().create(neutralRecord);
}
}
}
/**
* Stores all items in collection found in database to local storage (HashMap)
*
* @param collectionName
*/
private void loadCollectionFromDb(String collectionName) {
Criteria jobIdCriteria = Criteria.where(BATCH_JOB_ID_KEY).is(getBatchJobId());
Iterable<NeutralRecord> data = getNeutralRecordMongoAccess().getRecordRepository().findByQuery(collectionName,
new Query(jobIdCriteria), 0, 0);
Map<Object, NeutralRecord> collection = new HashMap<Object, NeutralRecord>();
NeutralRecord tempNr;
Iterator<NeutralRecord> iter = data.iterator();
while (iter.hasNext()) {
tempNr = iter.next();
collection.put(tempNr.getRecordId(), tempNr);
}
collections.put(collectionName, collection);
}
}
|
package gov.nih.nci.evs.reportwriter.bean;
import java.io.*;
import gov.nih.nci.evs.reportwriter.utils.*;
import gov.nih.nci.evs.reportwriter.service.*;
import gov.nih.nci.evs.reportwriter.properties.*;
import java.util.*;
import javax.faces.context.*;
import javax.faces.event.*;
import javax.faces.model.*;
import javax.servlet.http.*;
import org.apache.log4j.*;
import org.LexGrid.concepts.*;
/**
* @author EVS Team
* @version 1.0
*/
public class UserSessionBean extends Object {
private static Logger _logger = Logger.getLogger(UserSessionBean.class);
private Boolean _isAdmin = null;
private String _selectedTask = null;
// for templates with reports already been generated
private List<SelectItem> _standardReportTemplateList_draft =
new ArrayList<SelectItem>();
// for templates with reports already been generated
private List<SelectItem> _standardReportTemplateList_approved =
new ArrayList<SelectItem>();
private String _selectedStandardReportTemplate = null;
private String _selectedStandardReportTemplate_draft = null;
private String _selectedStandardReportTemplate_approved = null;
private String _selectedPropertyType = null;
private String _rootConceptCode = null;
private String _selectedOntology = null;
private String _selectedReportStatus = null;
private List<SelectItem> _reportStatusList = null;
private Vector<String> _reportStatusListData = null;
private String _selectedReportFormat = null;
private List<SelectItem> _reportFormatList = null;
private Vector<String> _reportFormatListData = null;
public void setIsAdmin(Boolean isAdmin) {
_isAdmin = isAdmin;
}
public Boolean getIsAdmin() {
return _isAdmin;
}
public String getSelectedTask() {
return _selectedTask;
}
public void setSelectedTask(String selectedTask) {
_selectedTask = selectedTask;
}
public String getSelectedPropertyType() {
return _selectedPropertyType;
}
public void setSelectedPropertyType(String selectedPropertyType) {
_selectedPropertyType = selectedPropertyType;
HttpServletRequest request = SessionUtil.getRequest();
request.getSession().setAttribute("selectedPropertyType",
selectedPropertyType);
}
public void propertyTypeSelectionChanged(ValueChangeEvent event) {
if (event.getNewValue() == null)
return;
String newValue = (String) event.getNewValue();
setSelectedPropertyType(newValue);
}
public String getSelectedOntology() {
return _selectedOntology;
}
public void setSelectedOntology(String selectedOntology) {
_selectedOntology = selectedOntology;
}
public List<SelectItem> getTaskList() {
HttpServletRequest request = SessionUtil.getRequest();
HttpSession session = request.getSession(false);
Boolean isAdmin = null;
if (session != null) {
isAdmin =
(Boolean) request.getSession(true).getAttribute("isAdmin");
}
List<SelectItem> list = DataUtils.getTaskList(isAdmin);
if (list != null) {
SelectItem item = (SelectItem) list.get(0);
_selectedTask = item.getLabel();
}
// return DataUtils.getTaskList(isAdmin);
return list;
}
public List<SelectItem> getPropertyTypeList() {
List<SelectItem> list = DataUtils.getPropertyTypeList();
if (_selectedPropertyType == null) {
SelectItem item = (SelectItem) list.get(0);
_selectedPropertyType = item.getLabel();
}
return list;
}
public void changeTaskSelection(ValueChangeEvent vce) {
String newValue = (String) vce.getNewValue();
_selectedTask = newValue;
}
public void reportSelectionChanged(ValueChangeEvent vce) {
String newValue = (String) vce.getNewValue();
setSelectedStandardReportTemplate(newValue);
}
public void reportSelectionChanged_draft(ValueChangeEvent vce) {
String newValue = (String) vce.getNewValue();
setSelectedStandardReportTemplate_draft(newValue);
}
public void reportSelectionChanged_approved(ValueChangeEvent vce) {
String newValue = (String) vce.getNewValue();
setSelectedStandardReportTemplate_approved(newValue);
}
public List<SelectItem> getStandardReportTemplateList() {
List<SelectItem> list = DataUtils.getStandardReportTemplateList();
if (_selectedStandardReportTemplate == null) {
if (list != null && list.size() > 0) {
if (getSelectedStandardReportTemplate() == null) {
SelectItem item = (SelectItem) list.get(0);
setSelectedStandardReportTemplate(item.getLabel());
}
}
}
return list;
}
public String getSelectedStandardReportTemplate() {
return _selectedStandardReportTemplate;
}
public void setSelectedStandardReportTemplate(
String selectedStandardReportTemplate) {
_selectedStandardReportTemplate = selectedStandardReportTemplate;
HttpServletRequest request = SessionUtil.getRequest();
request.getSession().setAttribute("selectedStandardReportTemplate",
selectedStandardReportTemplate);
}
public List<SelectItem> getStandardReportTemplateList_draft() {
// Find all templates with reports already been generated
List<SelectItem> list = new ArrayList<SelectItem>();
HashSet<String> hset = new HashSet<String>();
try {
SDKClientUtil sdkclientutil = new SDKClientUtil();
StandardReportTemplate standardReportTemplate = null;
String FQName = "gov.nih.nci.evs.reportwriter.bean.StandardReport";
Object[] objs = sdkclientutil.search(FQName);
if (objs != null && objs.length > 0) {
for (int i = 0; i < objs.length; i++) {
StandardReport standardReport = (StandardReport) objs[i];
ReportStatus rs = standardReport.getStatus();
String status = rs.getLabel();
standardReportTemplate = standardReport.getTemplate();
if (standardReportTemplate != null) {
if (status.compareToIgnoreCase("DRAFT") == 0) {
if (!hset.contains(standardReportTemplate
.getLabel())) {
hset.add(standardReportTemplate.getLabel());
list.add(new SelectItem(standardReportTemplate
.getLabel()));
}
}
}
}
if (list != null && list.size() > 0) {
SelectItem item = list.get(0);
setSelectedStandardReportTemplate_draft(item.getLabel());
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return list;
}
public String getSelectedStandardReportTemplate_draft() {
return _selectedStandardReportTemplate_draft;
}
public void setSelectedStandardReportTemplate_draft(
String selectedStandardReportTemplate_draft) {
_selectedStandardReportTemplate_draft =
selectedStandardReportTemplate_draft;
HttpServletRequest request = SessionUtil.getRequest();
request.getSession().setAttribute(
"selectedStandardReportTemplate_draft",
selectedStandardReportTemplate_draft);
}
public List<SelectItem> getStandardReportTemplateList_approved() {
List<SelectItem> list = new ArrayList<SelectItem>();
HashSet<String> hset = new HashSet<String>();
try {
SDKClientUtil sdkclientutil = new SDKClientUtil();
StandardReportTemplate standardReportTemplate = null;
String FQName = "gov.nih.nci.evs.reportwriter.bean.StandardReport";
Object[] objs = sdkclientutil.search(FQName);
if (objs != null && objs.length > 0) {
for (int i = 0; i < objs.length; i++) {
StandardReport standardReport = (StandardReport) objs[i];
ReportStatus rs = standardReport.getStatus();
String status = rs.getLabel();
if (status.compareTo("APPROVED") == 0) {
standardReportTemplate = standardReport.getTemplate();
if (!hset.contains(standardReportTemplate.getLabel())) {
hset.add(standardReportTemplate.getLabel());
list.add(new SelectItem(standardReportTemplate
.getLabel()));
}
}
}
if (list == null) {
if (list != null && list.size() > 0) {
SelectItem item = list.get(0);
setSelectedStandardReportTemplate_approved(item
.getLabel());
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return list;
}
public String getSelectedStandardReportTemplate_approved() {
return _selectedStandardReportTemplate_approved;
}
public void setSelectedStandardReportTemplate_approved(
String selectedStandardReportTemplate_draft) {
HttpServletRequest request = SessionUtil.getRequest();
request.getSession().setAttribute(
"selectedStandardReportTemplate_approved",
_selectedStandardReportTemplate_approved);
}
// taskSelectionChanged
public void taskSelectionChanged(ValueChangeEvent event) {
if (event.getNewValue() == null)
return;
String task = (String) event.getNewValue();
setSelectedTask(task);
}
public String performTask() {
if (_selectedTask.compareTo("Administer Standard Reports") == 0) {
List<SelectItem> list = getStandardReportTemplateList();
if (list == null || list.size() == 0) {
return "add_standard_report_template";
}
return "administer_standard_reports";
} else if (_selectedTask.compareTo("Maintain Report Status") == 0)
return "report_status";
else if (_selectedTask.compareTo("Assign Report Status") == 0) {
// Check if there is any DRAFT report waiting for approval:
_standardReportTemplateList_draft =
getStandardReportTemplateList_draft();
if (_standardReportTemplateList_draft != null
&& _standardReportTemplateList_draft.size() > 0) {
return "assign_report_status";
} else {
String message = "No draft report is found. ";
HttpServletRequest request = SessionUtil.getRequest();
request.getSession().setAttribute("message", message);
return "message";
}
} else if (_selectedTask.compareTo("Retrieve Standard Reports") == 0) {
HttpServletRequest request = SessionUtil.getRequest();
Boolean isAdmin =
(Boolean) request.getSession().getAttribute("isAdmin");
if (isAdmin != null && isAdmin.equals(Boolean.TRUE)) {
return "retrieve_standard_reports";
} else {
// Check if there is any APPROVED report waiting for approval:
_standardReportTemplateList_approved =
getStandardReportTemplateList_approved();
if (_standardReportTemplateList_approved != null
&& _standardReportTemplateList_approved.size() > 0) {
return "retrieve_standard_reports";
} else {
String message = "No approved report is found. ";
request.getSession().setAttribute("message", message);
return "message";
}
}
}
return null;
}
public String addColumnAction() {
// add_standard_report_column.jsp
return "add_standard_report_column";
}
public String modifyColumnAction() {
// not functional, to be modifid need to track coding scheme
// need to populate selected report_column data
return "add_standard_report_column";
}
public String insertbeforeColumnAction() {
// not functional, to be modifid need to track coding scheme
// track selected column number
return "add_standard_report_column";
}
public String insertafterColumnAction() {
// not functional, to be modifid need to track coding scheme
// track selected column number
return "add_standard_report_column";
}
public String deleteColumnAction() {
// not functional, to be modifid need to track coding scheme
// track selected column number
// selectedcolumn
HttpServletRequest request = SessionUtil.getRequest();
String id_str = (String) request.getParameter("selectedcolumn");
int id = Integer.parseInt(id_str);
_logger.debug("deleting column with ID = " + id
+ " (yet to be implemented)");
try {
ReportColumn reportColumn = getReportColumn(id);
SDKClientUtil sdkclientutil = new SDKClientUtil();
sdkclientutil.deleteReportColumn(reportColumn);
// setSelectedStandardReportTemplate(label);
} catch (Exception e) {
e.printStackTrace();
}
return "standard_report_column";
}
public String getRootConceptCode() {
return _rootConceptCode;
}
public void setRootConceptCode(String rootConceptCode) {
if (rootConceptCode == null)
return;
_rootConceptCode = rootConceptCode;
}
// public String addReportAction() {
public String saveTemplateAction() {
HttpServletRequest request = SessionUtil.getRequest();
String codingSchemeNameAndVersion =
(String) request.getSession().getAttribute("selectedOntology");
String codingSchemeName =
DataUtils.getCodingSchemeName(codingSchemeNameAndVersion);
String codingSchemeVersion =
DataUtils.getCodingSchemeVersion(codingSchemeNameAndVersion);
String label = (String) request.getParameter("label");
String rootConceptCode =
(String) request.getParameter("rootConceptCode");
String selectedAssociation =
(String) request.getSession().getAttribute("selectedAssociation");
String selectedLevel =
(String) request.getSession().getAttribute("selectedLevel");
// String selectedDirection = (String)
// request.getSession().getAttribute("selectedDirection");
String direction_str = (String) request.getParameter("direction");
Boolean direction = null;
// return to error page
if (label == null || label.compareTo("") == 0) {
_logger.warn("Incomplete data entry -- form not saved.");
return "add_standard_report_template";
}
if (rootConceptCode == null || rootConceptCode.compareTo("") == 0) {
_logger.warn("Incomplete data entry -- form not saved.");
return "add_standard_report_template";
}
if (selectedLevel == null || selectedLevel.compareTo("") == 0) {
_logger.warn("Incomplete data entry -- form not saved.");
return "add_standard_report_template";
}
if (direction_str.compareToIgnoreCase("source") == 0)
direction = Boolean.FALSE;
else
direction = Boolean.TRUE;
char delimiter = '$';
_logger.warn("==========");
_logger.warn("label: " + label);
_logger.warn("codingSchemeName: " + codingSchemeName);
_logger.warn("codingSchemeVersion: " + codingSchemeVersion);
_logger.warn("rootConceptCode: " + rootConceptCode);
_logger.warn("associationname: " + selectedAssociation);
_logger.warn("direction: " + direction);
_logger.warn("level: " + selectedLevel);
_logger.warn("delimiter: " + delimiter);
// Save results using SDK writable API.
try {
SDKClientUtil sdkclientutil = new SDKClientUtil();
String FQName =
"gov.nih.nci.evs.reportwriter.bean.StandardReportTemplate";
String methodName = "setLabel";
String key = label;
Object standardReportTemplate_obj =
sdkclientutil.search(FQName, methodName, key);
standardReportTemplate_obj =
sdkclientutil.search(FQName, methodName, key);
if (standardReportTemplate_obj != null) {
String message =
"Unable to save -- the report template with the specified label, "
+ label + ", already exists. ";
request.getSession().setAttribute("message", message);
return "message";
}
if (selectedLevel.equalsIgnoreCase(OntologyBean.LEVEL_ALL)) {
selectedLevel = "-1";
}
sdkclientutil.insertStandardReportTemplate(label, codingSchemeName,
codingSchemeVersion, rootConceptCode, selectedAssociation,
direction, Integer.parseInt(selectedLevel), delimiter);
setSelectedStandardReportTemplate(label);
} catch (Exception e) {
e.printStackTrace();
}
// return "generate_standard_report";
return "standard_report_template";
}
public String saveModifiedTemplateAction() {
HttpServletRequest request = SessionUtil.getRequest();
String label =
(String) request.getSession().getAttribute(
"selectedStandardReportTemplate");
String codingScheme = (String) request.getParameter("codingScheme");
String version = (String) request.getParameter("version");
_logger
.debug("saveModifiedTemplateAction: codingScheme " + codingScheme);
_logger.debug("saveModifiedTemplateAction: version " + version);
if (codingScheme == null || version == null) {
String message =
"Software Error: codingScheme and version can not be null:"
+ "\n * Coding scheme: " + codingScheme
+ "\n * version: " + version
+ "\nPlease report this issue.";
request.getSession().setAttribute("message", message);
return "message";
}
Boolean csnv_valid =
DataUtils.validateCodingScheme(codingScheme, version);
if (csnv_valid == null || csnv_valid.equals(Boolean.FALSE)) {
String message =
"Invalid coding scheme name "
+ codingScheme
+ " or version "
+ version
+ " -- The report template may be out of date. Please modify it and resubmit.";
request.getSession().setAttribute("message", message);
return "message";
}
String rootConceptCode =
(String) request.getParameter("rootConceptCode");
if (rootConceptCode == null || rootConceptCode.trim().length() == 0) {
String message =
"Invalid root concept code " + rootConceptCode
+ " -- Please complete data entry.";
request.getSession().setAttribute("message", message);
return "message";
}
rootConceptCode = rootConceptCode.trim();
_logger.debug("saveModifiedTemplateAction: rootConceptCode: "
+ rootConceptCode);
OntologyBean ontologyBean = BeanUtils.getOntologyBean();
String associationName = ontologyBean.getSelectedAssociation();
_logger.debug("saveModifiedTemplateAction: associationName: "
+ associationName);
if (associationName == null) {
String message =
"Software Error: associationName can not be null:"
+ "\nPlease report this issue.";
request.getSession().setAttribute("message", message);
return "message";
}
String direction_str = (String) request.getParameter("direction");
Boolean direction = null;
if (direction_str.compareTo("source") == 0)
direction = Boolean.FALSE;
else
direction = Boolean.TRUE;
String level_str = ontologyBean.getSelectedLevel();
// return to error page
if (label == null || label.compareTo("") == 0) {
_logger.warn("Incomplete data entry -- form not saved.");
return "modify_standard_report_template";
}
if (rootConceptCode == null || rootConceptCode.compareTo("") == 0) {
_logger.warn("Incomplete data entry -- form not saved.");
return "modify_standard_report_template";
}
if (level_str == null || level_str.compareTo("") == 0) {
_logger.warn("Incomplete data entry -- form not saved.");
return "modify_standard_report_template";
}
Integer level = OntologyBean.levelToInt(level_str);
if (level < -1) {
String message =
"Invalid level " + level
+ " -- Please modify the report template and resubmit.";
request.getSession().setAttribute("message", message);
return "message";
}
// char delimiter = '$';
try {
SDKClientUtil sdkclientutil = new SDKClientUtil();
StandardReportTemplate standardReportTemplate = null;
String FQName =
"gov.nih.nci.evs.reportwriter.bean.StandardReportTemplate";
String methodName = "setLabel";
String key = label;
Object standardReportTemplate_obj =
sdkclientutil.search(FQName, methodName, key);
if (standardReportTemplate_obj == null) {
String message =
"Unable to update template -- the report template with the specified label, "
+ label + " is not found. ";
request.getSession().setAttribute("message", message);
return "message";
}
standardReportTemplate =
(StandardReportTemplate) standardReportTemplate_obj;
standardReportTemplate.setLabel(label);
standardReportTemplate.setCodingSchemeName(codingScheme);
standardReportTemplate.setCodingSchemeVersion(version);
standardReportTemplate.setRootConceptCode(rootConceptCode);
standardReportTemplate.setAssociationName(associationName);
standardReportTemplate.setDirection(direction);
standardReportTemplate.setLevel(level);
sdkclientutil.updateStandardReportTemplate(standardReportTemplate);
key = codingScheme + " (version: " + version + ")";
request.getSession().setAttribute("selectedOntology", key);
} catch (Exception e) {
e.printStackTrace();
}
return "standard_report_template";
}
public String deleteReportTemplateAction() {
HttpServletRequest request = SessionUtil.getRequest();
String template_label =
(String) request.getSession().getAttribute(
"selectedStandardReportTemplate");
_logger.warn("deleteReportTemplateAction: " + template_label);
try {
StandardReportTemplate template =
getStandardReportTemplate(template_label);
SDKClientUtil sdkclientutil = new SDKClientUtil();
sdkclientutil.deleteStandardReportTemplate(template);
// setSelectedStandardReportTemplate(label);
getStandardReportTemplateList();
} catch (Exception e) {
e.printStackTrace();
}
return "standard_report_template";
}
public StandardReportTemplate getStandardReportTemplate(String label) {
try {
SDKClientUtil sdkclientutil = new SDKClientUtil();
String FQName =
"gov.nih.nci.evs.reportwriter.bean.StandardReportTemplate";
String methodName = "setLabel";
Object obj = sdkclientutil.search(FQName, methodName, label);
StandardReportTemplate standardReportTemplate =
(StandardReportTemplate) obj;
return standardReportTemplate;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public ReportColumn getReportColumn(int id) {
try {
SDKClientUtil sdkclientutil = new SDKClientUtil();
String FQName = "gov.nih.nci.evs.reportwriter.bean.ReportColumn";
String methodName = "setId";
Object obj = sdkclientutil.search(FQName, methodName, id);
ReportColumn reportColumn = (ReportColumn) obj;
return reportColumn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// public String addReportColumnAction() {
public String saveReportColumnAction() {
HttpServletRequest request = SessionUtil.getRequest();
StandardReportTemplate standardReportTemplate = null;
standardReportTemplate =
getStandardReportTemplate(_selectedStandardReportTemplate);
if (standardReportTemplate == null) {
String message =
"ERROR saving ReportColumn -- Unable to identify report template "
+ _selectedStandardReportTemplate;
request.getSession().setAttribute("message", message);
return "message";
}
String fieldlabel = (String) request.getParameter("fieldlabel");
String columnNumber_str = (String) request.getParameter("columnNumber");
String fieldType =
(String) request.getSession().getAttribute("selectedDataCategory");
String propertyType =
(String) request.getSession().getAttribute("selectedPropertyType");
String propertyName =
(String) request.getSession().getAttribute("selectedPropertyName");
String representationalForm =
(String) request.getSession().getAttribute(
"selectedRepresentationalForm");
String source =
(String) request.getSession().getAttribute("selectedSource");
String propertyQualifier =
(String) request.getSession().getAttribute(
"selectedPropertyQualifier");
String qualifierValue = (String) request.getParameter("qualifiervalue");
String conditionalColumnId =
(String) request.getParameter("dependentfield");
if (columnNumber_str == null || fieldlabel == null) {
String message =
"Unable to save ReportColumn -- please complete data entry.";
request.getSession().setAttribute("message", message);
return "message";
}
columnNumber_str = columnNumber_str.trim();
fieldlabel = fieldlabel.trim();
if (columnNumber_str.length() == 0 || fieldlabel.length() == 0) {
String message =
"Unable to save ReportColumn -- please complete data entry.";
request.getSession().setAttribute("message", message);
return "message";
}
int columnNumber = Integer.parseInt(columnNumber_str);
int ccid = -1;
if (conditionalColumnId != null && conditionalColumnId != "") {
ccid = Integer.parseInt(conditionalColumnId);
}
String preferred = (String) request.getParameter("preferred");
Boolean isPreferred = null;
if (preferred != null) {
if (preferred.equalsIgnoreCase("yes"))
isPreferred = Boolean.TRUE;
if (preferred.equalsIgnoreCase("no"))
isPreferred = Boolean.FALSE;
}
String delim =
(String) request.getSession().getAttribute("selectedDelimiter");
char delimiter = ' ';
if (delim != null) {
if (delim.length() > 0) {
delimiter = delim.charAt(0);
}
}
_logger.debug("==========");
_logger.debug("columnNumber: " + columnNumber);
_logger.debug("fieldlabel: " + fieldlabel);
_logger.debug("fieldType: " + fieldType);
_logger.debug("propertyType: " + propertyType);
_logger.debug("propertyName: " + propertyName);
_logger.debug("isPreferred: " + isPreferred);
_logger.debug("representationalForm: " + representationalForm);
_logger.debug("source: " + source);
_logger.debug("propertyQualifier: " + propertyQualifier);
_logger.debug("qualifierValue: " + qualifierValue);
_logger.debug("delim: " + delim);
// Save results using SDK writable API.
try {
SDKClientUtil sdkclientutil = new SDKClientUtil();
// check duplicate column number and column label
Collection<ReportColumn> cc =
standardReportTemplate.getColumnCollection();
if (cc != null) {
Object[] objs = cc.toArray();
if (objs.length > 0) {
for (int i = 0; i < objs.length; i++) {
gov.nih.nci.evs.reportwriter.bean.ReportColumn c =
(gov.nih.nci.evs.reportwriter.bean.ReportColumn) objs[i];
String col_label = c.getLabel();
if (col_label.compareToIgnoreCase(fieldlabel) == 0) {
String message =
"Unable to save ReportColumn -- the column label already exists.";
request.getSession().setAttribute("message",
message);
return "message";
}
Integer col_num = c.getColumnNumber();
if (col_num.intValue() == columnNumber) {
String message =
"Unable to save ReportColumn -- the column number already exists.";
request.getSession().setAttribute("message",
message);
return "message";
}
}
}
}
ReportColumn col =
sdkclientutil.createReportColumn(fieldlabel, columnNumber,
fieldType, propertyType, propertyName, isPreferred,
representationalForm, source, propertyQualifier,
qualifierValue, delimiter, ccid);
col.setReportTemplate(standardReportTemplate);
sdkclientutil.insertReportColumn(col);
_logger.debug("completed insertReportColumn: ");
request.getSession().setAttribute("selectedStandardReportTemplate",
_selectedStandardReportTemplate);
} catch (Exception e) {
e.printStackTrace();
}
return "standard_report_column";
}
public List<SelectItem> getReportFormatList() {
_reportFormatListData = DataUtils.getReportFormatListData();
_reportFormatList = new ArrayList<SelectItem>();
for (int i = 0; i < _reportFormatListData.size(); i++) {
String t = _reportFormatListData.elementAt(i);
_reportFormatList.add(new SelectItem(t));
}
if (_reportFormatList != null && _reportFormatList.size() > 0) {
_selectedReportFormat = _reportFormatList.get(0).getLabel();
}
return _reportFormatList;
}
public void setSelectedReportFormat(String selectedReportFormat) {
_selectedReportFormat = selectedReportFormat;
HttpServletRequest request = SessionUtil.getRequest();
request.getSession().setAttribute("selectedReportFormat",
selectedReportFormat);
}
public String getSelectedReportFormat() {
return _selectedReportFormat;
}
public void ReportFormatSelectionChanged(ValueChangeEvent event) {
if (event.getNewValue() == null)
return;
setSelectedReportFormat(_selectedReportFormat);
}
public List<SelectItem> getReportStatusList() {
_reportStatusListData = DataUtils.getReportStatusListData();
_reportStatusList = new ArrayList<SelectItem>();
for (int i = 0; i < _reportStatusListData.size(); i++) {
String t = _reportStatusListData.elementAt(i);
_reportStatusList.add(new SelectItem(t));
}
if (_reportStatusList != null && _reportStatusList.size() > 0) {
_selectedReportStatus = _reportStatusList.get(0).getLabel();
}
return _reportStatusList;
}
public void setSelectedReportStatus(String selectedReportStatus) {
_selectedReportStatus = selectedReportStatus;
HttpServletRequest request = SessionUtil.getRequest();
request.getSession().setAttribute("selectedReportStatus",
selectedReportStatus);
}
public String getSelectedReportStatus() {
return _selectedReportStatus;
}
public void reportStatusSelectionChanged(ValueChangeEvent event) {
if (event.getNewValue() == null)
return;
setSelectedReportStatus(_selectedReportStatus);
}
public String addStatusAction() {
// HttpServletRequest request = (HttpServletRequest) FacesContext
// .getCurrentInstance().getExternalContext().getRequest();
// String statusValue = (String) request.getParameter("statusValue");
return "report_status";
}
public String assignStatusAction() {
HttpServletRequest request = SessionUtil.getRequest();
// save to database
String reportTemplate =
(String) request.getSession().getAttribute(
"selectedStandardReportTemplate_draft");
String statusValue =
(String) request.getSession().getAttribute("selectedReportStatus");
try {
SDKClientUtil sdkclientutil = new SDKClientUtil();
StandardReportTemplate standardReportTemplate = null;
String FQName = "gov.nih.nci.evs.reportwriter.bean.StandardReport";
Object[] objs = sdkclientutil.search(FQName);
if (objs != null && objs.length > 0) {
for (int i = 0; i < objs.length; i++) {
StandardReport standardReport = (StandardReport) objs[i];
standardReportTemplate = standardReport.getTemplate();
if (standardReportTemplate != null) {
if (reportTemplate.compareTo(standardReportTemplate
.getLabel()) == 0) {
FQName =
"gov.nih.nci.evs.reportwriter.bean.ReportStatus";
String methodName = "setLabel";
String key = statusValue;
Object status_obj =
sdkclientutil.search(FQName, methodName, key);
if (status_obj != null) {
standardReport
.setStatus((ReportStatus) status_obj);
java.util.Date lastModified = new Date(); // system
// date
standardReport.setLastModified(lastModified);
sdkclientutil
.updateStandardReport(standardReport);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
_standardReportTemplateList_draft =
getStandardReportTemplateList_draft();
return "assign_report_status";
}
public String addReportTemplateAction() {
OntologyBean ontologyBean = BeanUtils.getOntologyBean();
ontologyBean.setSelectedAssociation(OntologyBean.DEFAULT_ASSOCIATION);
ontologyBean.setSelectedLevel(null);
return "add_standard_report_template";
}
public String modifyReportTemplateAction() {
HttpServletRequest request = SessionUtil.getRequest();
String templateLabel =
(String) request.getSession().getAttribute(
"selectedStandardReportTemplate");
// find thesaurus name through template
try {
SDKClientUtil sdkclientutil = new SDKClientUtil();
_logger.debug("modifyReportTemplateAction" + " " + templateLabel);
StandardReportTemplate standardReportTemplate = null;
String FQName =
"gov.nih.nci.evs.reportwriter.bean.StandardReportTemplate";
String methodName = "setLabel";
String key = templateLabel;
Object standardReportTemplate_obj =
sdkclientutil.search(FQName, methodName, key);
if (standardReportTemplate_obj != null) {
standardReportTemplate =
(StandardReportTemplate) standardReportTemplate_obj;
_logger.debug("modifyReportTemplateAction" + " "
+ standardReportTemplate.getCodingSchemeName());
_versionList =
getVersionList(standardReportTemplate.getCodingSchemeName());
// StandardReportTemplate standardReportTemplate =
// getStandardReportTemplate(selectedStandardReportTemplate);
String ontologyNameAndVersion =
standardReportTemplate.getCodingSchemeName()
+ " (version: "
+ standardReportTemplate.getCodingSchemeVersion() + ")";
request.getSession().setAttribute("selectedOntology",
ontologyNameAndVersion);
OntologyBean ontologyBean = BeanUtils.getOntologyBean();
String associationName =
standardReportTemplate.getAssociationName();
ontologyBean.setSelectedAssociation(associationName);
Integer level = standardReportTemplate.getLevel();
ontologyBean.setSelectedLevel(level.toString());
}
} catch (Exception ex) {
String message =
"Unable to construct available coding scheme version list."
+ "\n* Exception: " + ex.getLocalizedMessage();
request.getSession().setAttribute("message", message);
return "message";
}
return "modify_standard_report_template";
}
public String editReportContentAction() {
HttpServletRequest request = SessionUtil.getRequest();
request.getSession().setAttribute("selectedStandardReportTemplate",
_selectedStandardReportTemplate);
StandardReportTemplate standardReportTemplate =
getStandardReportTemplate(_selectedStandardReportTemplate);
String ontologyNameAndVersion =
standardReportTemplate.getCodingSchemeName() + " (version: "
+ standardReportTemplate.getCodingSchemeVersion() + ")";
request.getSession().setAttribute("selectedOntology",
ontologyNameAndVersion);
return "standard_report_column";
}
public String generateStandardReportAction() {
HttpServletRequest request = SessionUtil.getRequest();
String templateId =
(String) request.getSession().getAttribute(
"selectedStandardReportTemplate");
_logger.debug("generateStandardReportAction: " + templateId);
// boolean set_defined_by_code = true;
String defining_set_desc = null;
try {
SDKClientUtil sdkclientutil = new SDKClientUtil();
StandardReportTemplate standardReportTemplate = null;
String FQName =
"gov.nih.nci.evs.reportwriter.bean.StandardReportTemplate";
String methodName = "setLabel";
String key = templateId;
Object standardReportTemplate_obj =
sdkclientutil.search(FQName, methodName, key);
if (standardReportTemplate_obj != null) {
standardReportTemplate =
(StandardReportTemplate) standardReportTemplate_obj;
String codingscheme =
standardReportTemplate.getCodingSchemeName();
String version =
standardReportTemplate.getCodingSchemeVersion();
_logger.debug("generateStandardReportAction: codingscheme "
+ codingscheme);
_logger
.debug("generateStandardReportAction: version " + version);
Boolean csnv_valid =
DataUtils.validateCodingScheme(codingscheme, version);
if (csnv_valid == null || csnv_valid.equals(Boolean.FALSE)) {
String message =
"Invalid coding scheme name "
+ codingscheme
+ " or version "
+ version
+ " -- The report template may be out of date. Please modify it and resubmit.";
request.getSession().setAttribute("message", message);
return "message";
}
defining_set_desc = standardReportTemplate.getRootConceptCode();
String rootConceptCode = null;
if (defining_set_desc.indexOf("|") == -1) {
rootConceptCode =
standardReportTemplate.getRootConceptCode();
String ltag = null;
Concept rootConcept =
DataUtils.getConceptByCode(codingscheme, version, ltag,
rootConceptCode);
if (rootConcept == null) {
String message =
"Invalid root concept code "
+ rootConceptCode
+ " -- Please modify the report template and resubmit.";
request.getSession().setAttribute("message", message);
return "message";
}
String associationName =
standardReportTemplate.getAssociationName();
key = codingscheme + " (version: " + version + ")";
Vector<String> associationname_vec =
DataUtils.getSupportedAssociationNames(key);
if (!associationname_vec.contains(associationName)) {
String message =
"Invalid association name "
+ associationName
+ " -- Please modify the report template and resubmit.";
request.getSession().setAttribute("message", message);
return "message";
}
} else {
// set_defined_by_code = false;
}
}
} catch (Exception ex) {
String message =
"Exception encountered when generating " + templateId + ".";
request.getSession().setAttribute("message", message);
return "message";
}
String uid = (String) request.getSession().getAttribute("uid");
if (uid == null) {
String message = "You must first login to perform this function.";
request.getSession().setAttribute("message", message);
return "message";
}
String reportFormat_value = "Text (tab delimited)";
String reportStatus_value = "DRAFT";
String message =
new StandardReportService().validReport(
_selectedStandardReportTemplate, reportFormat_value,
reportStatus_value, uid);
if (message.compareTo("success") != 0) {
request.getSession().setAttribute("message", message);
return "message";
}
String download_dir = null;
try {
download_dir =
ReportWriterProperties
.getProperty(ReportWriterProperties.REPORT_DOWNLOAD_DIRECTORY);
} catch (Exception ex) {
}
_logger.debug("download_dir " + download_dir);
if (download_dir == null) {
message =
"The download directory has not been set up properly -- ask your administrator to check JBoss setting in properties-service.xml.";
request.getSession().setAttribute("message", message);
return "message";
}
new StandardReportService().generateStandardReport(download_dir,
_selectedStandardReportTemplate, uid);
message =
"You request has been received. The report, "
+ templateId
+ ", in tab-delimited and Microsft Excel formats will be generated and placed in the designated output directory."
+ " Please review and assign an APPROVED status before making it available to the users.";
request.getSession().setAttribute("message", message);
return "message"; // replaced by a messsage page (back button)
}
public String downloadReportAction() {
HttpServletRequest request = SessionUtil.getRequest();
request.getSession().setAttribute("selectedStandardReportTemplate",
_selectedStandardReportTemplate);
getStandardReportTemplate(_selectedStandardReportTemplate);
// String ontologyNameAndVersion =
// standardReportTemplate.getCodingSchemeVersion() + ")";
_logger.debug("downloading report " + _selectedStandardReportTemplate);
String download_dir = null;
try {
download_dir =
ReportWriterProperties
.getProperty(ReportWriterProperties.REPORT_DOWNLOAD_DIRECTORY);
// logger.debug("download_dir " + download_dir);
} catch (Exception ex) {
String message =
"Unable to download the specified report -- download directory does not exist -- check with system administrator.";
request.getSession().setAttribute("message", message);
return "message";
}
File dir = new File(download_dir);
if (!dir.exists()) {
_logger
.debug("Unable to download the specified report -- download directory does not exist. ");
String message =
"Unable to download " + _selectedStandardReportTemplate
+ " -- download directory does not exist. ";
request.getSession().setAttribute("message", message);
return "message";
}
File[] fileList = dir.listFiles();
int len = fileList.length;
while (len > 0) {
len
if (!fileList[len].isDirectory()) {
String name = fileList[len].getName();
_logger.debug("File found in the download directory: " + name);
}
}
// request.getSession().setAttribute("selectedOntology",
// ontologyNameAndVersion);
// find available reports in the download directory
// Check if selectedStandardReportTemplate has been approved.
// to be implemented:
boolean approved = true;
if (approved) {
return "download";
} else {
String message =
"The " + _selectedStandardReportTemplate
+ " has not been approved for download.";
request.getSession().setAttribute("message", message);
return "message";
}
// if not, display a message page indicating such.
// otherwise, route to generate_standard_report
// return "generate_standard_report";
}
public String saveStatusAction() {
HttpServletRequest request = SessionUtil.getRequest();
request.getSession().setAttribute("selectedStandardReportTemplate",
_selectedStandardReportTemplate);
StandardReportTemplate standardReportTemplate =
getStandardReportTemplate(_selectedStandardReportTemplate);
String message =
"The status of the " + standardReportTemplate.getLabel()
+ " has been updated successfully.";
request.getSession().setAttribute("message", message);
return "message"; // replaced by a messsage page (back button)
}
private String _selectedVersion = null;
private List<SelectItem> _versionList = null;
private Vector<String> _versionListData = null;
public List<SelectItem> getVersionList(String codingschemename) {
_versionListData = DataUtils.getVersionListData(codingschemename);
_versionList = new ArrayList<SelectItem>();
for (int i = 0; i < _versionListData.size(); i++) {
String t = _versionListData.elementAt(i);
_logger.debug("version: " + t);
_versionList.add(new SelectItem(t));
}
if (_versionList != null && _versionList.size() > 0) {
_selectedVersion = _versionList.get(0).getLabel();
}
return _versionList;
}
public void setSelectedVersion(String selectedVersion) {
_selectedVersion = selectedVersion;
HttpServletRequest request = SessionUtil.getRequest();
request.getSession().setAttribute("selectedVersion", selectedVersion);
}
public String getSelectedVersion() {
return _selectedVersion;
}
public void versionSelectionChanged(ValueChangeEvent event) {
if (event.getNewValue() == null)
return;
// int id = Integer.parseInt((String) event.getNewValue());
setSelectedVersion(_selectedVersion);
}
}
|
package org.opennms.netmgt.provision.service;
import org.opennms.core.utils.InetAddressUtils;
import org.opennms.netmgt.model.OnmsSnmpInterface;
import org.opennms.netmgt.snmp.RowCallback;
import org.opennms.netmgt.snmp.SnmpInstId;
import org.opennms.netmgt.snmp.SnmpObjId;
import org.opennms.netmgt.snmp.SnmpRowResult;
import org.opennms.netmgt.snmp.SnmpValue;
import org.opennms.netmgt.snmp.TableTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* PhysInterfaceTableTracker
*
* @author brozow
* @version $Id: $
*/
public class PhysInterfaceTableTracker extends TableTracker {
private static final Logger LOG = LoggerFactory.getLogger(PhysInterfaceTableTracker.class);
/** Constant <code>IF_TABLE_ENTRY</code> */
public static final SnmpObjId IF_TABLE_ENTRY = SnmpObjId.get(".1.3.6.1.2.1.2.2.1");
/** Constant <code>IF_INDEX</code> */
public static final SnmpObjId IF_INDEX = SnmpObjId.get(IF_TABLE_ENTRY, "1");
/** Constant <code>IF_DESCR</code> */
public static final SnmpObjId IF_DESCR = SnmpObjId.get(IF_TABLE_ENTRY, "2");
/** Constant <code>IF_TYPE</code> */
public static final SnmpObjId IF_TYPE = SnmpObjId.get(IF_TABLE_ENTRY, "3");
/** Constant <code>IF_MTU</code> */
public static final SnmpObjId IF_MTU = SnmpObjId.get(IF_TABLE_ENTRY, "4");
/** Constant <code>IF_SPEED</code> */
public static final SnmpObjId IF_SPEED = SnmpObjId.get(IF_TABLE_ENTRY, "5");
/** Constant <code>IF_PHYS_ADDR</code> */
public static final SnmpObjId IF_PHYS_ADDR = SnmpObjId.get(IF_TABLE_ENTRY, "6");
/** Constant <code>IF_ADMIN_STATUS</code> */
public static final SnmpObjId IF_ADMIN_STATUS = SnmpObjId.get(IF_TABLE_ENTRY, "7");
/** Constant <code>IF_OPER_STATUS</code> */
public static final SnmpObjId IF_OPER_STATUS = SnmpObjId.get(IF_TABLE_ENTRY, "8");
/** Constant <code>IF_LAST_CHANGE</code> */
public static final SnmpObjId IF_LAST_CHANGE = SnmpObjId.get(IF_TABLE_ENTRY, "9");
/** Constant <code>IF_XTABLE_ENTRY</code> */
public static final SnmpObjId IF_XTABLE_ENTRY = SnmpObjId.get( ".1.3.6.1.2.1.31.1.1.1");
/** Constant <code>IF_NAME</code> */
public static final SnmpObjId IF_NAME = SnmpObjId.get(IF_XTABLE_ENTRY, "1");
/** Constant <code>IF_IN_MCAST_PKTS</code> */
public static final SnmpObjId IF_IN_MCAST_PKTS = SnmpObjId.get(IF_XTABLE_ENTRY, "2");
/** Constant <code>IF_IN_BCAST_PKTS</code> */
public static final SnmpObjId IF_IN_BCAST_PKTS = SnmpObjId.get(IF_XTABLE_ENTRY, "3");
/** Constant <code>IF_OUT_MCAST_PKTS</code> */
public static final SnmpObjId IF_OUT_MCAST_PKTS = SnmpObjId.get(IF_XTABLE_ENTRY, "4");
/** Constant <code>IF_LINK_UP_DOWN_TRAP_ENABLE</code> */
public static final SnmpObjId IF_LINK_UP_DOWN_TRAP_ENABLE = SnmpObjId.get(IF_XTABLE_ENTRY, "14");
/** Constant <code>IF_HIGH_SPEED</code> */
public static final SnmpObjId IF_HIGH_SPEED = SnmpObjId.get(IF_XTABLE_ENTRY, "15");
/** Constant <code>IF_PROMISCUOUS_MODE</code> */
public static final SnmpObjId IF_PROMISCUOUS_MODE = SnmpObjId.get(IF_XTABLE_ENTRY, "16");
/** Constant <code>IF_CONNECTOR_PRESENT</code> */
public static final SnmpObjId IF_CONNECTOR_PRESENT = SnmpObjId.get(IF_XTABLE_ENTRY, "17");
/** Constant <code>IF_ALIAS</code> */
public static final SnmpObjId IF_ALIAS = SnmpObjId.get(IF_XTABLE_ENTRY, "18");
/** Constant <code>IF_COUNTER_DISCONTINUITY_TIME</code> */
public static final SnmpObjId IF_COUNTER_DISCONTINUITY_TIME = SnmpObjId.get(IF_XTABLE_ENTRY, "19");
private static SnmpObjId[] s_tableColumns = new SnmpObjId[] {
IF_INDEX,
IF_DESCR,
IF_TYPE,
IF_MTU,
IF_SPEED,
IF_PHYS_ADDR,
IF_ADMIN_STATUS,
IF_OPER_STATUS,
IF_LAST_CHANGE,
IF_NAME,
IF_ALIAS,
IF_HIGH_SPEED
};
class PhysicalInterfaceRow extends SnmpRowResult {
public PhysicalInterfaceRow(final int columnCount, final SnmpInstId instance) {
super(columnCount, instance);
}
public Integer getIfIndex() {
final SnmpValue value = getValue(IF_INDEX);
if (value != null) {
return value.toInt();
} else {
// ifIndex is the instance id as well
final SnmpInstId inst = getInstance();
if (inst != null && inst.length() == 1) {
return inst.toInt();
}
}
return null;
}
private Integer getIfType() {
final SnmpValue value = getValue(IF_TYPE);
return value == null ? null : value.toInt();
}
private Long getIfSpeed() {
final SnmpValue value = getValue(IF_SPEED);
return value == null ? null : value.toLong();
}
private Long getIfHighSpeed() {
final SnmpValue value = getValue(IF_HIGH_SPEED);
return value == null ? null : value.toLong();
}
private Long getSpeed() {
final Long highSpeed = getIfHighSpeed();
return (highSpeed != null && highSpeed > 4294) ? (highSpeed*1000000L) : getIfSpeed();
}
private Integer getIfOperStatus() {
final SnmpValue value = getValue(IF_OPER_STATUS);
return value == null ? null : value.toInt();
}
private String getIfName() {
final SnmpValue value = getValue(IF_NAME);
return value == null ? null : value.toDisplayString();
}
private String getIfDescr() {
final SnmpValue value = getValue(IF_DESCR);
return value == null ? null : value.toDisplayString();
}
private String getIfAlias() {
final SnmpValue value = getValue(IF_ALIAS);
return value == null ? null : value.toDisplayString();
}
private Integer getIfAdminStatus() {
final SnmpValue value = getValue(IF_ADMIN_STATUS);
return value == null ? null : value.toInt();
}
private String getPhysAddr() {
final SnmpValue value = getValue(IF_PHYS_ADDR);
String hexString = value == null ? null : value.toHexString();
String displayString = value == null ? null : value.toDisplayString();
// See ifTableEntry: NMS-4902 (revision cee964fe979e6465aeb4e2efd4772e50ebc54831)
try {
if (hexString != null && hexString.length() == 12) {
// If the hex string is 12 characters long, than the agent is kinda weird and
// is returning the value as a raw binary value that is 6 bytes in length.
// But that's OK, as long as we can convert it into a string, that's fine.
return hexString;
} else {
// This is the normal case that most agents conform to: the value is an ASCII
// string representing the colon-separated MAC address. We just need to reformat
// it to remove the colons and convert it into a 12-character string.
return displayString == null ? null : InetAddressUtils.normalizeMacAddress(displayString);
}
} catch (IllegalArgumentException e) {
LOG.warn(e.getMessage(), e);
return displayString;
}
}
public OnmsSnmpInterface createInterfaceFromRow() {
final OnmsSnmpInterface snmpIface = new OnmsSnmpInterface(null, getIfIndex());
snmpIface.setIfAdminStatus(getIfAdminStatus());
snmpIface.setIfAlias(getIfAlias());
snmpIface.setIfDescr(getIfDescr());
snmpIface.setIfName(getIfName());
snmpIface.setIfOperStatus(getIfOperStatus());
snmpIface.setIfSpeed(getSpeed());
snmpIface.setIfType(getIfType());
snmpIface.setPhysAddr(getPhysAddr());
return snmpIface;
}
}
/**
* <p>Constructor for PhysInterfaceTableTracker.</p>
*/
public PhysInterfaceTableTracker() {
super(s_tableColumns);
}
/**
* <p>Constructor for PhysInterfaceTableTracker.</p>
*
* @param rowProcessor a {@link org.opennms.netmgt.snmp.RowCallback} object.
*/
public PhysInterfaceTableTracker(final RowCallback rowProcessor) {
super(rowProcessor, s_tableColumns);
}
/** {@inheritDoc} */
@Override
public SnmpRowResult createRowResult(final int columnCount, final SnmpInstId instance) {
return new PhysicalInterfaceRow(columnCount, instance);
}
/** {@inheritDoc} */
@Override
public void rowCompleted(final SnmpRowResult row) {
processPhysicalInterfaceRow((PhysicalInterfaceRow)row);
}
/**
* <p>processPhysicalInterfaceRow</p>
*
* @param row a {@link org.opennms.netmgt.provision.service.PhysInterfaceTableTracker.PhysicalInterfaceRow} object.
*/
public void processPhysicalInterfaceRow(final PhysicalInterfaceRow row) {
}
}
|
package solver.propagation.generator.sorter.evaluator;
import solver.constraints.propagators.Propagator;
import solver.recorders.IEventRecorder;
import solver.variables.IntVar;
import solver.variables.Variable;
/**
* A factory of most common evaluators.
* <br/>
*
* @author Charles Prud'homme
* @since 09/03/12
*/
public class EvtRecEvaluators {
private EvtRecEvaluators() {
}
/**
* Evaluate the maximum priority among propagators of an event recorder
*/
public static IEvaluator<IEventRecorder> MaxPriorityC = new IEvaluator<IEventRecorder>() {
@Override
public int eval(IEventRecorder eventRecorder) {
Propagator[] propagators = eventRecorder.getPropagators();
int p = propagators[0].getPriority().priority;
for (int i = 1; i < propagators.length; i++) {
int pp = propagators[i].getPriority().priority;
if (pp > p) {
p = pp;
}
}
return p;
}
};
/**
* Evaluate the maximum priority among propagators of an event recorder
*/
public static IEvaluator<IEventRecorder> MaxDynPriorityC = new IEvaluator<IEventRecorder>() {
@Override
public int eval(IEventRecorder eventRecorder) {
Propagator[] propagators = eventRecorder.getPropagators();
int a = propagators[0].dynPriority();
for (int i = 1; i < propagators.length; i++) {
int pp = propagators[i].arity();
if (pp > a) {
a = pp;
}
}
return a;
}
};
/**
* Evaluate the minimum priority among propagators of an event recorder
*/
public static IEvaluator<IEventRecorder> MinPriorityC = new IEvaluator<IEventRecorder>() {
@Override
public int eval(IEventRecorder eventRecorder) {
Propagator[] propagators = eventRecorder.getPropagators();
int p = propagators[0].getPriority().priority;
for (int i = 1; i < propagators.length; i++) {
int pp = propagators[i].getPriority().priority;
if (pp < p) {
p = pp;
}
}
return p;
}
};
/**
* Evaluate the maximum arity among propagators of an event recorder
*/
public static IEvaluator<IEventRecorder> MaxArityC = new IEvaluator<IEventRecorder>() {
@Override
public int eval(IEventRecorder eventRecorder) {
Propagator[] propagators = eventRecorder.getPropagators();
int p = propagators[0].arity();
for (int i = 1; i < propagators.length; i++) {
int pp = propagators[i].arity();
if (pp > p) {
p = pp;
}
}
return p;
}
};
/**
* Evaluate the minimum arity among propagators of an event recorder
*/
public static IEvaluator<IEventRecorder> MinArityC = new IEvaluator<IEventRecorder>() {
@Override
public int eval(IEventRecorder eventRecorder) {
Propagator[] propagators = eventRecorder.getPropagators();
int p = propagators[0].getPriority().priority;
for (int i = 1; i < propagators.length; i++) {
int pp = propagators[i].arity();
if (pp < p) {
p = pp;
}
}
return p;
}
};
/**
* Evaluate the maximum arity among variables of an event recorder
*/
public static IEvaluator<IEventRecorder> MaxArityV = new IEvaluator<IEventRecorder>() {
@Override
public int eval(IEventRecorder eventRecorder) {
Variable[] variables = eventRecorder.getVariables();
int a = variables[0].nbConstraints();
for (int i = 1; i < variables.length; i++) {
int aa = variables[i].nbConstraints();
if (aa > a) {
a = aa;
}
}
return a;
}
};
/**
* Evaluate the minimum arity among variables of an event recorder
*/
public static IEvaluator<IEventRecorder> MinArityV = new IEvaluator<IEventRecorder>() {
@Override
public int eval(IEventRecorder eventRecorder) {
Variable[] variables = eventRecorder.getVariables();
int a = variables[0].nbConstraints();
for (int i = 1; i < variables.length; i++) {
int aa = variables[i].nbConstraints();
if (aa < a) {
a = aa;
}
}
return a;
}
};
/**
* Evaluate the maximum domain ssize among integer variables of an event recorder
*/
public static IEvaluator<IEventRecorder<IntVar>> MaxDomSize = new IEvaluator<IEventRecorder<IntVar>>() {
@Override
public int eval(IEventRecorder<IntVar> eventRecorder) {
Variable[] variables = eventRecorder.getVariables();
int a = ((IntVar)variables[0]).getDomainSize();
for (int i = 1; i < variables.length; i++) {
int aa = ((IntVar) variables[i]).getDomainSize();
if (aa < a) {
a = aa;
}
}
return a;
}
};
/**
* Evaluate the mimimum domain ssize among integer variables of an event recorder
*/
public static IEvaluator<IEventRecorder<IntVar>> MinDomSize = new IEvaluator<IEventRecorder<IntVar>>() {
@Override
public int eval(IEventRecorder<IntVar> eventRecorder) {
Variable[] variables = eventRecorder.getVariables();
int a = ((IntVar)variables[0]).getDomainSize();
for (int i = 1; i < variables.length; i++) {
int aa = ((IntVar) variables[i]).getDomainSize();
if (aa < a) {
a = aa;
}
}
return a;
}
};
}
|
package foam.dao;
import foam.core.*;
import foam.dao.index.*;
import foam.mlang.order.Comparator;
import foam.mlang.predicate.Or;
import foam.mlang.predicate.Predicate;
import foam.mlang.sink.GroupBy;
import foam.nanos.logger.Logger;
import java.util.ArrayList;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.List;
// TODO: clone and freeze objects stored in memory
public class MDAO
extends AbstractDAO
{
protected AltIndex index_;
protected Object state_;
protected ReadWriteLock lock_ = new ReentrantReadWriteLock();
public MDAO(ClassInfo of) {
setOf(of);
state_ = null;
index_ = new AltIndex(new TreeIndex((PropertyInfo) this.of_.getAxiomByName("id")));
}
public void addUniqueIndex(PropertyInfo prop) {
index_.addIndex(new TreeIndex(prop, new TreeIndex((PropertyInfo) this.of_.getAxiomByName("id"))));
}
public void addIndex(Index index) {
index_.addIndex(index);
}
public void addIndex(PropertyInfo... props) {
for ( PropertyInfo prop : props ) addUniqueIndex(prop);
}
public FObject put_(X x, FObject obj) {
// Clone and freeze outside of lock to minimize time spent under lock
obj = obj.fclone();
obj.freeze();
synchronized ( lock_.writeLock() ) {
FObject oldValue = find(obj);
if ( oldValue != null ) {
state_ = index_.remove(state_, oldValue);
}
state_ = index_.put(state_, obj);
}
onPut(obj);
return obj;
}
public FObject remove_(X x, FObject obj) {
if ( obj == null ) return null;
FObject found;
synchronized ( lock_.writeLock() ) {
found = find(obj);
if ( found != null ) {
state_ = index_.remove(state_, found);
}
}
if ( found != null ) {
onRemove(found);
}
return found;
}
public FObject find_(X x, Object o) {
Object state;
synchronized ( lock_.readLock() ) {
state = state_;
}
if ( o == null ) return null;
return AbstractFObject.maybeClone(
getOf().isInstance(o)
? (FObject) index_.planFind(state, getPrimaryKey().get(o)).find(state, getPrimaryKey().get(o))
: (FObject) index_.planFind(state, o).find(state,o)
);
}
public Sink select_(X x, Sink sink, long skip, long limit, Comparator order, Predicate predicate) {
SelectPlan plan;
Predicate simplePredicate = null;
// use partialEval to wipe out such useless predicate such as: And(EQ()) ==> EQ(), And(And(EQ()),GT()) ==> And(EQ(),GT())
if ( predicate != null ) simplePredicate = predicate.partialEval();
Object state;
synchronized ( lock_.readLock() ) {
state = state_;
}
// We handle OR logic by seperate request from MDAO. We return different plan for each parameter of OR logic.
if ( simplePredicate instanceof Or ) {
Sink dependSink = new ArraySink();
// When we have groupBy, order, skip, limit such requirement, we can't do it separately so I replace a array sink to temporarily holde the whole data
//Then after the plan wa slelect we change it to the origin sink
int length = ( (Or) simplePredicate ).getArgs().length;
List<Plan> planList = new ArrayList<>();
for ( int i = 0; i < length; i++ ) {
Predicate arg = ( (Or) simplePredicate ).getArgs()[i];
planList.add(index_.planSelect(state, dependSink, 0, AbstractDAO.MAX_SAFE_INTEGER, null, arg));
}
plan = new OrPlan(simplePredicate, planList);
} else {
plan = index_.planSelect(state, sink, skip, limit, order, simplePredicate);
}
// TODO: if plan cost is >= size, log a warning
if ( state != null && predicate != null && plan.cost() > 1000 && plan.cost() >= index_.size(state_) ) {
Logger logger = (Logger) x.get("logger");
logger.error(predicate.createStatement(), " Unindexed search on MDAO");
}
plan.select(state, sink, skip, limit, order, simplePredicate);
return sink;
}
public void removeAll_(X x, long skip, long limit, Comparator order, Predicate predicate) {
synchronized ( lock_.writeLock() ) {
this.where(predicate).select( new AbstractSink() {
@Override
public void put(Object obj, Detachable sub) {
MDAO.this.remove((FObject) obj);
}
});
}
}
}
|
package org.csstudio.display.builder.runtime.script.internal;
import static org.csstudio.display.builder.runtime.RuntimePlugin.logger;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Collections;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.logging.Level;
import org.csstudio.display.builder.model.Widget;
import org.csstudio.display.builder.runtime.Preferences;
import org.csstudio.display.builder.runtime.pv.RuntimePV;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;
import org.python.core.Py;
import org.python.core.PyCode;
import org.python.core.PyList;
import org.python.core.PySystemState;
import org.python.util.PythonInterpreter;
/** Jython script support
*
* <p>To debug, see python.verbose which can also be set
* as VM property.
*
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
class JythonScriptSupport implements AutoCloseable
{
private final ScriptSupport support;
final static boolean initialized = init();
/** Scripts that have been submitted, awaiting execution, to avoid queuing them again.
*
* <p>Relies on the fact that each script is unique identified by the script itself,
* they're not submitted with different widget and pvs parameters.
*/
private final Set<JythonScript> queued_scripts = Collections.newSetFromMap(new ConcurrentHashMap<JythonScript, Boolean>());
private final PythonInterpreter python;
/** Perform static, one-time initialization */
private static boolean init()
{
try
{
final Properties pre_props = System.getProperties();
final Properties props = new Properties();
// Locate the jython plugin for 'home' to allow use of /Lib in there
final String home = getPluginPath("org.python.jython", "/");
if (home == null)
throw new Exception("Cannot locate jython bundle. No OSGi?");
// Jython 2.7(b3) needs these to set sys.prefix and sys.executable.
// If left undefined, initialization of Lib/site.py fails with
// posixpath.py", line 394, in normpath AttributeError:
// 'NoneType' object has no attribute 'startswith'
props.setProperty("python.home", home);
props.setProperty("python.executable", "None");
// Disable cachedir to avoid creation of cachedir folder.
// See http://www.jython.org/jythonbook/en/1.0/ModulesPackages.html#java-package-scanning
props.setProperty(PySystemState.PYTHON_CACHEDIR_SKIP, "true");
// With python.home defined, there is no more
// "ImportError: Cannot import site module and its dependencies: No module named site"
// Skipping the site import still results in faster startup
props.setProperty("python.import.site", "false");
// Prevent: console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.
props.setProperty("python.console.encoding", "UTF-8");
// This will replace entries found on JYTHONPATH
final String python_path = Preferences.getPythonPath();
if (! python_path.isEmpty())
props.setProperty("python.path", python_path);
// Options: error, warning, message (default), comment, debug
// props.setProperty("python.verbose", "debug");
// Options.verbose = Py.DEBUG;
PythonInterpreter.initialize(pre_props, props, new String[0]);
final PyList paths = Py.getSystemState().path;
paths.add(getPluginPath("org.csstudio.display.builder.runtime", "scripts"));
return true;
}
catch (Exception ex)
{
logger.log(Level.SEVERE, "Once this worked OK, but now the Jython initialization failed. Don't you hate computers?", ex);
}
return false;
}
/** Locate a path inside a bundle.
*
* <p>If the bundle is JAR-ed up, the {@link FileLocator} will
* return a location with "file:" and "..jar!/path".
* This method patches the location such that it can be used
* on the Jython path.
*
* @param bundle_name Name of bundle
* @param path_in_bundle Path within bundle
* @return Location of that path within bundle, or <code>null</code> if not found or no bundle support
* @throws IOException on error
*/
private static String getPluginPath(final String bundle_name, final String path_in_bundle) throws IOException
{
final Bundle bundle = Platform.getBundle(bundle_name);
if (bundle == null)
return null;
final URL url = FileLocator.find(bundle, new Path(path_in_bundle), null);
if (url == null)
return null;
String path = FileLocator.resolve(url).getPath();
// Turn politically correct URL into path digestible by jython
if (path.startsWith("file:/"))
path = path.substring(5);
path = path.replace(".jar!", ".jar");
return path;
}
/** Create executor for jython scripts
* @param support {@link ScriptSupport}
*/
public JythonScriptSupport(final ScriptSupport support) throws Exception
{
this.support = support;
// Concurrent creation of python interpreters has in past resulted in
// Lib/site.py", line 571, in <module> ..
// Lib/sysconfig.py", line 159, in _subst_vars AttributeError: {'userbase'}
// or Lib/site.py", line 122, in removeduppaths java.util.ConcurrentModificationException
// Sync. on JythonScriptSupport to serialize the interpreter creation and avoid above errors.
final long start = System.currentTimeMillis();
synchronized (JythonScriptSupport.class)
{
// Could create a new 'state' for each interpreter
// ++ Seems 'correct' since each interpreter then has its own path etc.
// -- In scan server, some instances of the PythonInterpreter seemed
// to fall back to the default PySystemState even though
// a custom state was provided. Seemed related to thread local,
// not fully understood.
// -- Using a new PySystemState adds about 3 second startup time,
// while using the default state only incurs that 3 second delay
// on very first access.
// ==> Not using state = new PySystemState();
final PySystemState state = null;
python = new PythonInterpreter(null, state);
}
final long end = System.currentTimeMillis();
logger.log(Level.FINE, "Time to create jython: {0} ms", (end - start));
}
/** @param path Path to add to head of python search path */
private void addToPythonPath(final String path)
{
// Since using default PySystemState (see above), check if already in paths
final PyList paths = python.getSystemState().path;
// Prevent concurrent modification
synchronized (JythonScriptSupport.class)
{
final int index = paths.indexOf(path);
// Already top entry?
if (index == 0)
return;
// Remove if further down in the list
if (index > 0)
paths.remove(index);
// Add to front of list
paths.add(0, path);
}
logger.log(Level.FINE, "Adding to jython path: {0}", path);
}
/** Parse and compile script file
*
* @param path Path to add to search path, or <code>null</code>
* @param name Name of script (file name, URL)
* @param stream Stream for the script content
* @return {@link Script}
* @throws Exception on error
*/
public Script compile(final String path, final String name, final InputStream stream) throws Exception
{
if (path != null)
addToPythonPath(path);
final long start = System.currentTimeMillis();
final PyCode code = python.compile(new InputStreamReader(stream), name);
final long end = System.currentTimeMillis();
logger.log(Level.FINE, "Time to compile {0}: {1} ms", new Object[] { name, (end - start) });
return new JythonScript(this, name, code);
}
/** Request that a script gets executed
* @param script {@link JythonScript}
* @param widget Widget that requests execution
* @param pvs PVs that are available to the script
* @return Future for script that was just started
*/
public Future<Object> submit(final JythonScript script, final Widget widget, final RuntimePV... pvs)
{
// Skip script that's already in the queue.
// Check-then-set, no atomic submit-unless-queued logic.
// Might still add some scripts twice, but good enough.
if (queued_scripts.contains(script))
{
logger.log(Level.FINE, "Skipping script {0}, already queued for execution", script);
return null;
}
queued_scripts.add(script);
// System.out.println("Submit on " + Thread.currentThread().getName());
return support.submit(() ->
{
// System.out.println("Executing " + script + " on " + Thread.currentThread().getName());
// Script may be queued again
queued_scripts.remove(script);
try
{
// Executor is single-threaded.
// OK to set 'widget' etc.
// of the shared python interpreter
// because only one script will execute at a time.
python.set("widget", widget);
python.set("pvs", pvs);
python.exec(script.getCode());
}
catch (final Throwable ex)
{
logger.log(Level.WARNING, "Execution of '" + script + "' failed for " + widget, ex);
}
// System.out.println("Finished " + script);
return null;
});
}
/** Release resources (interpreter, ...) */
@Override
public void close()
{
python.close();
}
}
|
package org.springsource.ide.eclipse.commons.livexp.ui;
import java.util.Arrays;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.widgets.SharedScrolledComposite;
import org.eclipse.ui.progress.UIJob;
import org.springsource.ide.eclipse.commons.livexp.Activator;
import org.springsource.ide.eclipse.commons.livexp.core.CompositeValidator;
import org.springsource.ide.eclipse.commons.livexp.core.LiveExpression;
import org.springsource.ide.eclipse.commons.livexp.core.ValidationResult;
import org.springsource.ide.eclipse.commons.livexp.core.Validator;
import org.springsource.ide.eclipse.commons.livexp.core.ValueListener;
import org.springsource.ide.eclipse.commons.livexp.util.ExceptionUtil;
/**
* Single page dialog with status bar and ok cancel buttons capable of hosting
* {@link PageSection}s.
*
* @author Kris De Volder
*/
public abstract class DialogWithSections
extends TitleAreaDialog
implements ValueListener<ValidationResult>, IPageWithSections, IPageWithOkButton, Reflowable {
private String title;
private final OkButtonHandler model;
private SharedScrolledComposite scroller;
public DialogWithSections(String title, OkButtonHandler model, Shell shell) {
super(shell);
this.title = title;
this.model = model;
this.setHelpAvailable(false); // A better default for our dialogs since we don't provide a
// helpcontext in most (all!) of our dialogs anyhow.
}
public void create() {
super.create();
setTitle(title);
}
protected Control createDialogArea(Composite parent) {
// readSettings();
scroller = new SharedScrolledComposite(parent, SWT.V_SCROLL | SWT.H_SCROLL) {};
scroller.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
// GridDataFactory.fillDefaults()/*.grab(true, true)*/.applyTo(scroller);
// scroller.setWidthHint(500); // Avoid excessively wide dialogs
// Display display = Display.getCurrent();
// Color blue = display.getSystemColor(SWT.COLOR_BLUE);
// scroller.setBackground(blue);
scroller.setExpandHorizontal(true);
scroller.setExpandVertical(true);
Composite page = new Composite(scroller, SWT.NONE);
applyDialogFont(page);
GridLayout layout = new GridLayout(1, false);
layout.marginHeight = 12;
layout.marginWidth = 12;
page.setLayout(layout);
validator = new CompositeValidator();
for (PageSection section : getSections()) {
section.createContents(page);
validator.addChild(section.getValidator());
}
validator.addListener(this);
page.pack(true);
scroller.setContent(page);
// scroller.setMinWidth(600);
// scroller.setMinHeight(400);
// setControl(scroller);
return parent;
}
private UIJob reflowJob;
@Override
public boolean reflow() {
if (reflowJob==null) {
reflowJob = new UIJob(Display.getDefault(), "Reflow Wizard Contents") {
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
if (scroller!=null && !scroller.isDisposed()) {
scroller.reflow(true);
}
return Status.OK_STATUS;
}
};
reflowJob.setSystem(true);
}
reflowJob.schedule();
return true;
}
/**
* A delay used for posting status messages to the dialog area after a status update happens.
* This is to get rid of spurious message that only appear for a fraction of a second as
* some auto updating states in models are inconsistent. E.g. in new boot project wizard
* when project name is entered it is temporarily inconsistent with default project location until
* that project location itself is updated in response to the change event from the project name.
* If the project location validator runs before the location update, a spurious validation error
* temporarily results.
*
* Note: this is a hacky solution. It would be better if the LiveExp framework solved this by
* tracking and scheduling refreshes based on the depedency graph. Thus it might guarantee
* that the validator never sees the inconsistent state because it is refreshed last.
*/
private static final long MESSAGE_DELAY = 250;
private List<WizardPageSection> sections = null;
private CompositeValidator validator;
private UIJob updateJob;
protected synchronized List<WizardPageSection> getSections() {
if (sections==null) {
sections = safeCreateSections();
}
return sections;
}
private List<WizardPageSection> safeCreateSections() {
try {
return createSections();
} catch (CoreException e) {
Activator.log(e);
return Arrays.asList(
new CommentSection(this, "Dialog couldn't be created because of an unexpected error:+\n"+ExceptionUtil.getMessage(e)+"\n\n"
+ "Check the error log for details"),
new ValidatorSection(Validator.alwaysError(ExceptionUtil.getMessage(e)), this)
);
}
}
/**
* This method should be implemented to generate the contents of the page.
*/
protected List<WizardPageSection> createSections() throws CoreException {
//This default implementation is meant to be overridden
return Arrays.asList(
new CommentSection(this, "Override DialogWithSections.createSections() to provide real content."),
new ValidatorSection(Validator.alwaysError("Subclass must implement validation logic"), this)
);
}
public void gotValue(LiveExpression<ValidationResult> exp, final ValidationResult status) {
scheduleUpdateJob();
}
private synchronized void scheduleUpdateJob() {
Shell shell = getShell();
if (shell!=null) {
if (this.updateJob==null) {
this.updateJob = new UIJob("Update Wizard message") {
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
updateStatus(validator.getValue());
// IStatus status = toStatus(validator.getValue());
// updateStatus(status);
return Status.OK_STATUS;
}
};
updateJob.setSystem(true);
}
updateJob.schedule(MESSAGE_DELAY);
}
}
private void updateStatus(ValidationResult status) {
boolean enableOk = true;
if (status==null || status.isOk()) {
setMessage("", IMessageProvider.NONE);
} else {
setMessage(status.msg, status.getMessageProviderStatus());
enableOk = status.status<IStatus.ERROR;
}
Button okButton = getButton(IDialogConstants.OK_ID);
if (okButton!=null) {
okButton.setEnabled(enableOk);
}
}
public void dispose() {
for (WizardPageSection s : sections) {
s.dispose();
}
}
@Override
protected void cancelPressed() {
super.cancelPressed();
}
@Override
protected final void okPressed() {
super.okPressed();
try {
model.performOk();
} catch (Exception e) {
Activator.log(e);
MessageDialog.openError(getShell(), "Error", ExceptionUtil.getMessage(e));
}
}
/**
* Simulate clicking the ok button. Does nothing if ok button is not found or disabled.
*/
public boolean clickOk() {
Button button = getButton(OK);
if (button!=null && button.isEnabled()) {
okPressed();
return true;
}
return false;
}
@Override
public IRunnableContext getRunnableContext() {
return PlatformUI.getWorkbench().getProgressService();
}
}
|
package com.vangent.hieos.DocViewer.client.controller;
//import com.google.gwt.user.client.Window;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;
import com.smartgwt.client.widgets.tab.events.CloseClickHandler;
import com.smartgwt.client.widgets.tab.events.TabCloseClickEvent;
import com.smartgwt.client.widgets.tab.events.TabDeselectedEvent;
import com.smartgwt.client.widgets.tab.events.TabDeselectedHandler;
import com.vangent.hieos.DocViewer.client.model.authentication.AuthenticationContext;
import com.vangent.hieos.DocViewer.client.model.authentication.Credentials;
import com.vangent.hieos.DocViewer.client.model.config.Config;
import com.vangent.hieos.DocViewer.client.helper.TimeOutHelper;
import com.vangent.hieos.DocViewer.client.model.document.DocumentSearchCriteria;
import com.vangent.hieos.DocViewer.client.model.patient.Patient;
import com.vangent.hieos.DocViewer.client.model.patient.PatientRecord;
import com.vangent.hieos.DocViewer.client.model.patient.PatientSearchCriteria;
import com.vangent.hieos.DocViewer.client.services.proxy.AuthenticationService;
import com.vangent.hieos.DocViewer.client.services.proxy.ConfigRetrieveService;
import com.vangent.hieos.DocViewer.client.services.proxy.DocumentQueryService;
import com.vangent.hieos.DocViewer.client.services.proxy.PatientQueryService;
import com.vangent.hieos.DocViewer.client.view.document.DocumentListObserver;
import com.vangent.hieos.DocViewer.client.view.document.DocumentViewContainer;
import com.vangent.hieos.DocViewer.client.view.patient.PatientListObserver;
import com.vangent.hieos.DocViewer.client.view.patient.PatientViewContainer;
//import com.vangent.hieos.DocViewer.client.services.PDSRemoteService.Util;
/**
*
* @author Bernie Thuman
*
*/
public class DocViewerController {
private Canvas mainCanvas;
private AuthenticationContext authContext;
private PatientViewContainer patientViewContainer;
private TabSet patientTabSet = null;
private Config config = null;
public DocViewerController() {
}
/**
*
* @param authObserver
* @param userid
* @param password
*/
public void authenticateUser(AuthenticationObserver authObserver,
String userid, String password) {
Credentials creds = new Credentials();
creds.setPassword(password);
creds.setUserId(userid);
TimeOutHelper progressHelper = new TimeOutHelper();
AuthenticationService service = new AuthenticationService(creds,
authObserver, progressHelper);
service.doWork();
}
public void loadConfig() {
ConfigObserver observer = new ConfigObserver(this);
TimeOutHelper timeOutHelper = new TimeOutHelper();
ConfigRetrieveService service = new ConfigRetrieveService(observer,
timeOutHelper);
service.doWork();
}
/**
*
* @param config
*/
public void setConfig(Config config) {
this.config = config;
}
/**
*
* @return
*/
public Config getConfig() {
return this.config;
}
/**
*
* @return
*/
public AuthenticationContext getAuthContext() {
return authContext;
}
/**
*
* @param authContext
*/
public void setAuthContext(AuthenticationContext authContext) {
this.authContext = authContext;
}
/**
*
* @param canvas
*/
public void setMainCanvas(Canvas canvas) {
mainCanvas = canvas;
}
/**
*
* @param patientViewContainer
*/
public void setPatientViewContainer(
PatientViewContainer patientViewContainer) {
this.patientViewContainer = patientViewContainer;
}
/**
*
* @param criteria
*/
public void findPatients(PatientSearchCriteria criteria) {
PatientListObserver observer = new PatientListObserver(
patientViewContainer);
this.findPatients(criteria, observer);
}
/**
*
* @param criteria
* @param observer
*/
public void findPatients(PatientSearchCriteria criteria,
final PatientListObserver observer) {
TimeOutHelper progressHelper = new TimeOutHelper();
PatientQueryService service = new PatientQueryService(criteria,
observer, progressHelper);
service.doWork();
}
/**
*
* @param patientRecord
*/
public void findDocuments(PatientRecord patientRecord) {
DocumentSearchCriteria criteria = new DocumentSearchCriteria();
criteria.setPatient(patientRecord.getPatient());
String searchMode = this.getConfig().get(Config.KEY_SEARCH_MODE);
criteria.setSearchMode(searchMode);
DocumentListObserver observer = new DocumentListObserver(patientRecord,
this);
this.findDocuments(criteria, observer);
}
/**
*
* @param criteria
* @param observer
*/
private void findDocuments(final DocumentSearchCriteria criteria,
final DocumentListObserver observer) {
TimeOutHelper progressHelper = new TimeOutHelper();
DocumentQueryService service = new DocumentQueryService(criteria,
observer, progressHelper);
service.doWork();
}
public void showPatients() {
if (patientTabSet != null) {
this.addPaneToMainCanvas(patientTabSet);
} else {
SC.warn("You must choose \"Find Patients\" before being able to view documents");
}
}
public void showFindPatients() {
if (patientViewContainer == null) {
patientViewContainer = new PatientViewContainer(this);
}
this.addPaneToMainCanvas(patientViewContainer);
}
/**
*
* @param patientRecord
* @param documentViewContainer
*/
public void addPatientTab(PatientRecord patientRecord,
DocumentViewContainer documentViewContainer) {
// Add the document view container to the patient tab.
final Tab patientTab = this.getPatientTab(patientRecord);
patientTab.setPane(documentViewContainer);
this.addPaneToMainCanvas(patientTabSet);
// Show the patient as the current tab.
patientTabSet.selectTab(patientTab);
}
/**
*
* @param patientRecord
* @return
*/
private Tab getPatientTab(PatientRecord patientRecord) {
// Create patient tab set if it does not already exist.
if (patientTabSet == null) {
this.createPatientTabSet();
}
// Create a new tab for the patient.
final Tab patientTab = new Tab();
String imageName = "person.png";
Patient patient = patientRecord.getPatient();
if (patient.getGender() != null) {
if (patient.getGender().equals("M")) {
imageName = "gender_male.png";
} else if (patient.getGender().equals("F")) {
imageName = "gender_female.png";
}
}
patientTab.setTitle(Canvas.imgHTML(imageName) + " "
+ patientRecord.getFormattedName());
patientTab.setCanClose(true);
// Add tab to the tab set.
patientTabSet.addTab(patientTab);
return patientTab;
}
private void createPatientTabSet() {
// Create patient tab set if it does not already exist.
patientTabSet = new TabSet();
patientTabSet.setWidth100();
patientTabSet.setHeight100();
patientTabSet.addCloseClickHandler(new CloseClickHandler() {
public void onCloseClick(TabCloseClickEvent event) {
// Tab tab = event.getTab();
int numTabs = patientTabSet.getTabs().length;
if (numTabs == 1) {
// Clear out the tabs.
patientTabSet = null;
// Show the find patients view.
showFindPatients();
}
}
});
}
/**
*
* @param childPane
*/
private void addPaneToMainCanvas(Canvas childPane) {
Canvas[] children = mainCanvas.getChildren();
boolean foundPane = false;
for (int i = 0; i < children.length; i++) {
if (children[i] != childPane) {
// A bit of a hack: should only have one item (so we can break
// here).
mainCanvas.removeChild(children[i]);
mainCanvas.addChild(childPane);
foundPane = true;
break;
}
}
if (foundPane == false) {
mainCanvas.addChild(childPane);
}
}
}
|
package tools.devnull.boteco.plugins.subscription;
import tools.devnull.boteco.message.IncomeMessage;
public class SubscriptionParameters {
private final String event;
private final String channel;
private final String target;
private final boolean requestConfirmation;
public SubscriptionParameters(IncomeMessage message, String event) {
if (message.user() != null && !message.isGroup()) {
this.target = message.user().id();
this.channel = "user";
} else {
this.target = message.isGroup() ? message.target() : message.sender().id();
this.channel = message.channel().id();
}
this.event = event.toLowerCase();
this.requestConfirmation = false;
}
public SubscriptionParameters(String event, String channel, String target) {
this.event = event.toLowerCase();
this.target = target;
this.channel = channel;
this.requestConfirmation = true;
}
public String event() {
return event;
}
public String channel() {
return channel;
}
public String target() {
return target;
}
public boolean shouldRequestConfirmation() {
return requestConfirmation;
}
}
|
package com.mentor.nucleus.bp.debug.ui.model;
import java.util.UUID;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.model.IDebugTarget;
import org.eclipse.debug.core.model.IValue;
import org.eclipse.debug.core.model.IVariable;
import com.mentor.nucleus.bp.core.ArrayValue_c;
import com.mentor.nucleus.bp.core.AttributeValue_c;
import com.mentor.nucleus.bp.core.ComponentInstance_c;
import com.mentor.nucleus.bp.core.ComponentReferenceValue_c;
import com.mentor.nucleus.bp.core.CorePlugin;
import com.mentor.nucleus.bp.core.DataItemValue_c;
import com.mentor.nucleus.bp.core.DataType_c;
import com.mentor.nucleus.bp.core.InstanceInReference_c;
import com.mentor.nucleus.bp.core.InstanceReferenceDataType_c;
import com.mentor.nucleus.bp.core.InstanceReferenceValue_c;
import com.mentor.nucleus.bp.core.Instance_c;
import com.mentor.nucleus.bp.core.LocalReference_c;
import com.mentor.nucleus.bp.core.LocalValue_c;
import com.mentor.nucleus.bp.core.Local_c;
import com.mentor.nucleus.bp.core.PropertyParameter_c;
import com.mentor.nucleus.bp.core.RuntimeValue_c;
import com.mentor.nucleus.bp.core.SimpleCoreValue_c;
import com.mentor.nucleus.bp.core.SimpleValue_c;
import com.mentor.nucleus.bp.core.StructuredValue_c;
import com.mentor.nucleus.bp.core.ValueInArray_c;
import com.mentor.nucleus.bp.core.ValueInStructure_c;
public class BPValue extends BPDebugElement implements IValue {
Object value = null;
public BPValue(IDebugTarget debugTarget, ILaunch launch, Object val) {
super((BPDebugTarget)debugTarget, launch);
value = val;
}
public String getReferenceTypeName() throws DebugException {
// TODO Auto-generated method stub
return null;
}
public String getValueString(RuntimeValue_c p_rv) throws DebugException {
String result = "";
SimpleValue_c simVal = SimpleValue_c.getOneRV_SMVOnR3300(p_rv);
StructuredValue_c strVal = StructuredValue_c.getOneRV_SVLOnR3300(p_rv);
ArrayValue_c arrVal = ArrayValue_c.getOneRV_AVLOnR3300(p_rv);
DataType_c dt = DataType_c.getOneS_DTOnR3307(p_rv);
InstanceReferenceDataType_c irdt = InstanceReferenceDataType_c.getOneS_IRDTOnR17(dt);
if ( simVal != null){
SimpleCoreValue_c scv = SimpleCoreValue_c.getOneRV_SCVOnR3308(simVal);
ComponentReferenceValue_c crv = ComponentReferenceValue_c.getOneRV_CRVOnR3308(simVal);
InstanceReferenceValue_c irv = InstanceReferenceValue_c.getOneRV_IRVOnR3308(simVal);
if ( scv != null){
if ( irdt != null )
{
return "empty";
}
Object value = scv.getValue();
if (value == null){
value = "empty";
}
result = value.toString();
if (dt != null && dt.getName().equals("string")) {
result = "\"" + result + "\"";
}
return result;
}
else if ( crv != null){
result = "Component not found";
ComponentInstance_c exe = ComponentInstance_c.getOneI_EXEOnR3309(crv);
if (exe != null) {
result = exe.getLabel() + "[" + exe.Getenginenumber() + "]";
}
return result;
}
else if ( irv != null){
Instance_c [] insts = Instance_c.getManyI_INSsOnR3013(
InstanceInReference_c.getManyL_IIRsOnR3311(irv));
String sep = "";
if (insts.length == 0)
return "empty";
else {
for (int i=0; i<insts.length;i++) {
result = result + sep + insts[i].getLabel();
sep = ", ";
}
}
return result;
}
else {
Throwable t = new Throwable();
t.fillInStackTrace();
CorePlugin
.logError(
"No subtype found for simple value.",
t);
return "Unknown simple runtime value";
}
}
else if ( strVal != null){
return p_rv.getLabel();
}
else if (arrVal !=null ){
return p_rv.getLabel();
}
else {
Throwable t = new Throwable();
t.fillInStackTrace();
CorePlugin
.logError(
"No subtype found for runtime value.",
t);
return "Unknown Runtime Value";
}
}
public String getValueString() throws DebugException {
if (value instanceof LocalValue_c) {
LocalValue_c localValue = (LocalValue_c)value;
Local_c local = Local_c.getOneL_LCLOnR3001(localValue);
if (local != null) {
UUID rtVal_ID = localValue.Getruntimevalue(local.getStack_frame_id());
RuntimeValue_c rtVal = (RuntimeValue_c)local.getModelRoot().
getInstanceList(RuntimeValue_c.class).getGlobal(rtVal_ID.toString());
return getValueString(rtVal);
}
else {
RuntimeValue_c rtVal = RuntimeValue_c.getOneRV_RVLOnR3306(
Local_c.getOneL_LCLOnR3001(localValue));
SimpleValue_c smplVal = SimpleValue_c.getOneRV_SMVOnR3300(rtVal);
if (smplVal != null) {
if (smplVal.Getvalue() != null) {
String result = smplVal.Getvalue().toString();
DataType_c dt = DataType_c.getOneS_DTOnR3307(rtVal);
if (dt.getName().equals("string")) {
result = "\"" + result + "\"";
}
return result;
}
}
}
}
else if (value instanceof DataItemValue_c) {
DataItemValue_c div = (DataItemValue_c)value;
RuntimeValue_c rtVal = RuntimeValue_c.getOneRV_RVLOnR3303(div);
return getValueString(rtVal);
}
else if (value instanceof AttributeValue_c) {
AttributeValue_c attrVal = (AttributeValue_c)value;
RuntimeValue_c rtVal = RuntimeValue_c.getOneRV_RVLOnR3304(attrVal);
if ( rtVal == null){
// Referential attribute
rtVal = (RuntimeValue_c) ((AttributeValue_c)value).getModelRoot().getInstanceList(
RuntimeValue_c.class).getGlobal(null, attrVal.Getruntimevalue());
String valueString = getValueString(rtVal);
if ("Unknown Runtime Value".equalsIgnoreCase(valueString)){
return "not participating";
}
}
return getValueString(rtVal);
}
else if (value instanceof LocalReference_c) {
RuntimeValue_c rtVal = RuntimeValue_c.getOneRV_RVLOnR3306( Local_c.getOneL_LCLOnR3001(
(LocalReference_c) value));
if ( rtVal != null){
return getValueString(rtVal);
}else{
return "empty";
}
}
else if (value instanceof RuntimeValue_c) {
return getValueString((RuntimeValue_c)value);
}
else if (value instanceof Instance_c){
Instance_c inst = (Instance_c)value;
return inst.getLabel();
}
return "Undefined";
}
public boolean isAllocated() throws DebugException {
// TODO Auto-generated method stub
return false;
}
public IVariable[] getVariables(RuntimeValue_c p_rv) throws DebugException {
SimpleValue_c simVal = SimpleValue_c.getOneRV_SMVOnR3300(p_rv);
StructuredValue_c strVal = StructuredValue_c.getOneRV_SVLOnR3300(p_rv);
ArrayValue_c arrVal = ArrayValue_c.getOneRV_AVLOnR3300(p_rv);
RuntimeValue_c [] rvs = new RuntimeValue_c[0];
if ( simVal != null){
SimpleCoreValue_c scv = SimpleCoreValue_c.getOneRV_SCVOnR3308(simVal);
ComponentReferenceValue_c crv = ComponentReferenceValue_c.getOneRV_CRVOnR3308(simVal);
InstanceReferenceValue_c irv = InstanceReferenceValue_c.getOneRV_IRVOnR3308(simVal);
if ( scv != null){
rvs = new RuntimeValue_c[0];
return getChildern(rvs);
}
else if ( crv != null){
rvs = new RuntimeValue_c[0];
return getChildern(rvs);
}
else if ( irv != null){
Instance_c [] insts = Instance_c.getManyI_INSsOnR3013(
InstanceInReference_c.getManyL_IIRsOnR3311(irv));
if (insts.length == 1) {
AttributeValue_c[] vals = AttributeValue_c.
getManyI_AVLsOnR2909(insts[0]);
return getChildern(vals);
}
else if (insts.length > 1) {
return getChildern(insts);
}
else if (insts.length == 0) {
rvs = new RuntimeValue_c[0];
return getChildern(rvs);
}
}
else {
}
}
else if ( strVal != null){
rvs = RuntimeValue_c.getManyRV_RVLsOnR3301(
ValueInStructure_c.getManyRV_VISsOnR3301(strVal));
return getChildern(rvs);
}
else if (arrVal !=null ){
ValueInArray_c [] vias = ValueInArray_c.getManyRV_VIAsOnR3302(arrVal);
rvs = RuntimeValue_c.getManyRV_RVLsOnR3302(vias);
return getChildern(rvs);
}
else {
}
return getChildern(rvs);
}
/**
* @param objects : represents the child values for the select variable in Variable View
* @return
*/
private IVariable[] getChildern(Object[] objects) {
IVariable [] result = new IVariable[objects.length];
for (int i=0; i< objects.length; i++) {
result[i] = new BPVariable(getDebugTarget(), getLaunch(), objects[i]);
}
return result;
}
public IVariable[] getVariables() throws DebugException {
if (value instanceof DataItemValue_c) {
DataItemValue_c div = (DataItemValue_c)value;
RuntimeValue_c rtVal = RuntimeValue_c.getOneRV_RVLOnR3303(div);
return getVariables(rtVal);
}
else if (value instanceof LocalReference_c) {
RuntimeValue_c rtVal = RuntimeValue_c.getOneRV_RVLOnR3306(Local_c
.getOneL_LCLOnR3001((LocalReference_c) value));
return getVariables(rtVal);
}
else if (value instanceof AttributeValue_c) {
AttributeValue_c av = (AttributeValue_c)value;
RuntimeValue_c rootRv = RuntimeValue_c.getOneRV_RVLOnR3304(av);
return getVariables(rootRv);
}
else if (value instanceof LocalValue_c) {
LocalValue_c lv = (LocalValue_c)value;
Local_c local = Local_c.getOneL_LCLOnR3001(lv);
if (local != null) {
PropertyParameter_c pp = PropertyParameter_c.getOneC_PPOnR3017(lv);
UUID rtVal_ID = lv.Getruntimevalue(local.getStack_frame_id());
RuntimeValue_c rootRv = (RuntimeValue_c)local.getModelRoot().
getInstanceList(RuntimeValue_c.class).getGlobal(rtVal_ID.toString());
return getVariables(rootRv);
}
}
else if (value instanceof RuntimeValue_c) {
return getVariables((RuntimeValue_c)value);
}
else if (value instanceof Instance_c){
AttributeValue_c[] vals = AttributeValue_c
.getManyI_AVLsOnR2909((Instance_c)value);
return getChildern(vals);
}
else
{
// report error
}
return new IVariable[0];
}
public boolean hasVariables() throws DebugException {
return getVariables().length > 0;
}
public String getName() {
return "Value ";
}
}
|
package com.jaquadro.minecraft.storagedrawers.client.renderer;
import com.jaquadro.minecraft.storagedrawers.StorageDrawers;
import com.jaquadro.minecraft.storagedrawers.api.render.IRenderLabel;
import com.jaquadro.minecraft.storagedrawers.api.storage.IDrawer;
import com.jaquadro.minecraft.storagedrawers.block.BlockDrawers;
import com.jaquadro.minecraft.storagedrawers.block.tile.TileEntityDrawers;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.*;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.common.util.ForgeDirection;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import java.util.ArrayList;
import java.util.List;
@SideOnly(Side.CLIENT)
public class TileEntityDrawersRenderer extends TileEntitySpecialRenderer
{
private static final ResourceLocation RES_ITEM_GLINT = new ResourceLocation("textures/misc/enchanted_item_glint.png");
private RenderItem itemRenderer = new RenderItem() {
private RenderBlocks renderBlocksRi = new RenderBlocks();
@Override
public byte getMiniBlockCount (ItemStack stack, byte original) {
return 1;
}
@Override
public boolean shouldBob () {
return false;
}
@Override
public boolean shouldSpreadItems () {
return false;
}
// The default Mojang code for item render does not handle glinted or multi-pass items gracefully in a non-UI
// setting. This modified implementation will render these items without unsightly Z-fighting.
@Override
public void renderItemIntoGUI (FontRenderer fontRenderer, TextureManager texManager, ItemStack itemStack, int x, int y, boolean renderEffect) {
if (itemStack.getItemSpriteNumber() == 0 && RenderBlocks.renderItemIn3d(Block.getBlockFromItem(itemStack.getItem()).getRenderType())) {
renderItemIntoGUIBlock(fontRenderer, texManager, itemStack, x, y, renderEffect);
return;
}
Item item = itemStack.getItem();
int meta = itemStack.getItemDamage();
ResourceLocation loc = itemStack.getItem().requiresMultipleRenderPasses()
? (item.getSpriteNumber() == 0 ? TextureMap.locationBlocksTexture : TextureMap.locationItemsTexture)
: (texManager.getResourceLocation(itemStack.getItemSpriteNumber()));
for (int i = 0; i < item.getRenderPasses(meta); ++i) {
OpenGlHelper.glBlendFunc(770, 771, 1, 0);
texManager.bindTexture(loc);
IIcon icon = itemStack.getItem().requiresMultipleRenderPasses()
? item.getIcon(itemStack, i)
: itemStack.getIconIndex();
if (icon == null)
continue;
int color = itemStack.getItem().getColorFromItemStack(itemStack, i);
float r = (float)(color >> 16 & 255) / 255.0F;
float g = (float)(color >> 8 & 255) / 255.0F;
float b = (float)(color & 255) / 255.0F;
if (renderWithColor)
GL11.glColor4f(r, g, b, 1.0F);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_ALPHA_TEST);
renderIcon(x, y, icon, 16, 16);
GL11.glDisable(GL11.GL_ALPHA_TEST);
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_LIGHTING);
if (renderEffect && itemStack.hasEffect(i))
renderEffect(texManager, x, y);
}
}
@Override
public void renderEffect (TextureManager manager, int x, int y) {
GL11.glDepthFunc(GL11.GL_EQUAL);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glDepthMask(false);
manager.bindTexture(RES_ITEM_GLINT);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_BLEND);
GL11.glColor4f(0.5F, 0.25F, 0.8F, 1.0F);
renderGlint(x, y, 16, 16);
GL11.glDepthMask(true);
GL11.glDisable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glDepthFunc(GL11.GL_LEQUAL);
}
private void renderGlint (int x, int y, int w, int h)
{
for (int i = 0; i < 2; ++i)
{
OpenGlHelper.glBlendFunc(772, 1, 0, 0);
float uScale = 0.00390625F;
float vScale = 0.00390625F;
float u = (Minecraft.getSystemTime() % (3000 + i * 1873)) / (3000.0F + i * 1873) * 256.0F;
float v = 0.0F;
float hScale = (i < 1) ? 4.0F : -1.0F;
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV(x + 0, y + h, 0, (u + (float)h * hScale) * uScale, (v + (float)h) * vScale);
tessellator.addVertexWithUV(x + w, y + h, 0, (u + (float)w + (float)h * hScale) * uScale, (v + (float)h) * vScale);
tessellator.addVertexWithUV(x + w, y + 0, 0, (u + (float)w) * uScale, (v + 0.0F) * vScale);
tessellator.addVertexWithUV(x + 0, y + 0, 0, (u + 0.0F) * uScale, (v + 0.0F) * vScale);
tessellator.draw();
}
}
private void renderItemIntoGUIBlock (FontRenderer fontRenderer, TextureManager texManager, ItemStack itemStack, int x, int y, boolean renderEffect) {
texManager.bindTexture(TextureMap.locationBlocksTexture);
Block block = Block.getBlockFromItem(itemStack.getItem());
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
GL11.glDisable(GL11.GL_NORMALIZE);
if (block.getRenderBlockPass() != 0) {
GL11.glAlphaFunc(GL11.GL_GREATER, 0.1F);
GL11.glEnable(GL11.GL_BLEND);
OpenGlHelper.glBlendFunc(770, 771, 1, 0);
}
else {
GL11.glAlphaFunc(GL11.GL_GREATER, 0.5F);
GL11.glDisable(GL11.GL_BLEND);
}
// Orient lighting for on-block item render. Standard GUI RenderHelper method is wrong for this.
GL11.glPushMatrix();
GL11.glRotatef(-170.0F, 1.0F, 0.0F, 1.0F);
GL11.glRotatef(-2, 1, 0, 0);
//GL11.glRotatef(-135.0F, 0.0F, 1.0F, 0.0F);
//GL11.glRotatef(142.0F, 1.0F, 0.0F, 0.0F);
RenderHelper.enableStandardItemLighting();
GL11.glPopMatrix();
GL11.glPushMatrix();
GL11.glTranslatef(x - 2, y + 3, zLevel - 3);
GL11.glScalef(10, 10, 10);
GL11.glTranslatef(1, 0.5f, 1);
GL11.glScalef(1, 1, -1);
GL11.glRotatef(210, 1, 0, 0);
GL11.glRotatef(45, 0, 1, 0);
int color = itemStack.getItem().getColorFromItemStack(itemStack, 0);
float r = (float)(color >> 16 & 255) / 255.0F;
float g = (float)(color >> 8 & 255) / 255.0F;
float b = (float)(color & 255) / 255.0F;
if (this.renderWithColor)
GL11.glColor4f(r * 1, g * 1, b * 1, 1.0F);
GL11.glRotatef(-90, 0, 1, 0);
this.renderBlocksRi.useInventoryTint = this.renderWithColor;
this.renderBlocksRi.renderBlockAsItem(block, itemStack.getItemDamage(), 1);
this.renderBlocksRi.useInventoryTint = true;
if (block.getRenderBlockPass() == 0)
GL11.glAlphaFunc(GL11.GL_GREATER, 0.1F);
GL11.glPopMatrix();
}
};
private float itemOffset1X[] = new float[] { .5f };
private float itemOffset1Y[] = new float[] { 8.25f };
private float itemOffset2X[] = new float[] { .5f, .5f };
private float itemOffset2Y[] = new float[] { 10.25f, 2.25f };
private float itemOffset4X[] = new float[] { .25f, .25f, .75f, .75f };
private float itemOffset4Y[] = new float[] { 10.25f, 2.25f, 10.25f, 2.25f };
private float itemOffset3X[] = new float[] { .5f, .25f, .75f };
private float itemOffset3Y[] = new float[] { 9.75f, 2.25f, 2.25f };
private RenderBlocks renderBlocks = new RenderBlocks();
private float brightness;
private static final float unit = .0625f;
private static int[] glStateRender = { GL11.GL_LIGHTING, GL11.GL_BLEND };
private List<int[]> savedGLStateRender = GLUtil.makeGLState(glStateRender);
private static int[] glStateItemRender = { GL11.GL_LIGHTING, GL11.GL_ALPHA_TEST, GL11.GL_BLEND };
private List<int[]> savedGLStateItemRender = GLUtil.makeGLState(glStateItemRender);
private static int[] glLightRender = { GL11.GL_LIGHT0, GL11.GL_LIGHT1, GL11.GL_COLOR_MATERIAL, GL12.GL_RESCALE_NORMAL };
private List<int[]> savedGLLightRender = GLUtil.makeGLState(glLightRender);
private List<IRenderLabel> preLabelRenderHandlers = new ArrayList<IRenderLabel>();
@Override
public void renderTileEntityAt (TileEntity tile, double x, double y, double z, float partialTickTime) {
TileEntityDrawers tileDrawers = (TileEntityDrawers) tile;
if (tileDrawers == null)
return;
float depth;
Block block = tile.getWorldObj().getBlock(tile.xCoord, tile.yCoord, tile.zCoord);
if (block instanceof BlockDrawers)
depth = ((BlockDrawers) block).halfDepth ? .5f : 1;
else
return;
GL11.glPushMatrix();
GL11.glTranslated(x, y, z);
itemRenderer.setRenderManager(RenderManager.instance);
ForgeDirection side = ForgeDirection.getOrientation(tileDrawers.getDirection());
int ambLight = tile.getWorldObj().getLightBrightnessForSkyBlocks(tile.xCoord + side.offsetX, tile.yCoord + side.offsetY, tile.zCoord + side.offsetZ, 0);
int lu = ambLight % 65536;
int lv = ambLight / 65536;
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, lu, lv);
brightness = tile.getWorldObj().getLightBrightness(tile.xCoord + side.offsetX, tile.yCoord + side.offsetY, tile.zCoord + side.offsetZ) * 1.25f;
if (brightness > 1)
brightness = 1;
Minecraft mc = Minecraft.getMinecraft();
boolean cache = mc.gameSettings.fancyGraphics;
mc.gameSettings.fancyGraphics = true;
if (StorageDrawers.config.isFancyItemRenderEnabled())
renderFancyItemSet(tileDrawers, side, depth, partialTickTime);
else
renderFastItemSet(tileDrawers, side, depth, partialTickTime);
mc.gameSettings.fancyGraphics = cache;
GL11.glPopMatrix();
}
private void renderFancyItemSet (TileEntityDrawers tile, ForgeDirection side, float depth, float partialTickTime) {
boolean restoreGLState = false;
int drawerCount = tile.getDrawerCount();
for (int i = 0; i < drawerCount; i++) {
if (!tile.isDrawerEnabled(i))
continue;
IDrawer drawer = tile.getDrawer(i);
ItemStack itemStack = drawer.getStoredItemPrototype();
if (itemStack == null)
continue;
if (!restoreGLState) {
restoreGLState = true;
GLUtil.saveGLState(savedGLStateRender, glStateRender);
}
renderFancyItem(itemStack, tile, i, side, depth, partialTickTime);
}
if (restoreGLState)
GLUtil.restoreGLState(savedGLStateRender);
}
private boolean[] renderAsBlock = new boolean[4];
private ItemStack[] renderStacks = new ItemStack[4];
private void renderFastItemSet (TileEntityDrawers tile, ForgeDirection side, float depth, float partialTickTime) {
int drawerCount = tile.getDrawerCount();
boolean restoreItemState = false;
boolean restoreBlockState = false;
for (int i = 0; i < drawerCount; i++) {
renderStacks[i] = null;
if (!tile.isDrawerEnabled(i))
continue;
IDrawer drawer = tile.getDrawer(i);
ItemStack itemStack = drawer.getStoredItemPrototype();
if (itemStack == null)
continue;
renderStacks[i] = itemStack;
renderAsBlock[i] = isItemBlockType(itemStack);
if (renderAsBlock[i])
restoreBlockState = true;
else
restoreItemState = true;
}
if (restoreItemState || restoreBlockState)
GLUtil.saveGLState(savedGLStateItemRender, glStateItemRender);
for (int i = 0; i < drawerCount; i++) {
if (renderStacks[i] != null && !renderAsBlock[i])
renderFastItem(renderStacks[i], tile, i, side, depth, partialTickTime);
}
if (restoreBlockState) {
GLUtil.saveGLState(savedGLLightRender, glLightRender);
GL11.glPushAttrib(GL11.GL_LIGHTING_BIT);
}
for (int i = 0; i < drawerCount; i++) {
if (renderStacks[i] != null && renderAsBlock[i])
renderFastItem(renderStacks[i], tile, i, side, depth, partialTickTime);
}
if (restoreBlockState) {
GLUtil.restoreGLState(savedGLLightRender);
GL11.glPopAttrib();
}
if (restoreItemState || restoreBlockState)
GLUtil.restoreGLState(savedGLStateItemRender);
}
private void renderFancyItem (ItemStack itemStack, TileEntityDrawers tile, int slot, ForgeDirection side, float depth, float partialTickTime) {
int drawerCount = tile.getDrawerCount();
boolean isBlockType = isItemBlockType(itemStack);
BlockDrawers block = (BlockDrawers)tile.getBlockType();
float xunit = getXOffset(drawerCount, slot);
float yunit = getYOffset(drawerCount, slot);
float zunit = isBlockType ? 1.95f * block.trimDepth : block.trimDepth;
float xc = 0, zc = 0;
float itemDepth = depth + .001f;
float relScale = (tile.getDrawerCount() == 1) ? 2 : 1;
if (isBlockType) {
try {
Block itemBlock = Block.getBlockFromItem(itemStack.getItem());
itemBlock.setBlockBoundsBasedOnState(tile.getWorldObj(), 0, 0, 0);
itemBlock.setBlockBoundsForItemRender();
double zDepth = 1 / relScale - itemBlock.getBlockBoundsMaxZ();
itemDepth += zDepth * zunit;
}
catch (Exception e) { };
}
switch (tile.getDirection()) {
case 3:
xc = xunit;
zc = itemDepth - zunit;
break;
case 2:
xc = 1 - xunit;
zc = 1 - itemDepth + zunit;
break;
case 5:
xc = itemDepth - zunit;
zc = 1 - xunit;
break;
case 4:
xc = 1 - itemDepth + zunit;
zc = xunit;
break;
}
float yAdj = 0;
if (drawerCount == 2 || drawerCount == 4)
yAdj = -.5f;
else if (drawerCount == 1)
yAdj = -3f;
GL11.glPushMatrix();
if (isBlockType) {
GL11.glTranslatef(xc, unit * (yunit + 1.75f + yAdj), zc);
GL11.glScalef(1 * relScale, 1 * relScale, 1 * relScale);
GL11.glRotatef(getRotationYForSide(side) + 90.0F, 0.0F, 1.0F, 0.0F);
} else {
GL11.glTranslatef(xc, unit * (yunit + 0.75f + yAdj), zc);
GL11.glScalef(.5f * relScale, .5f * relScale, .5f * relScale);
GL11.glRotatef(getRotationYForSide(side), 0.0F, 1.0F, 0.0F);
}
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_LIGHTING);
EntityItem itemEnt = new EntityItem(null, 0, 0, 0, itemStack);
itemEnt.hoverStart = 0;
itemRenderer.doRender(itemEnt, 0, 0, 0, 0, 0);
GL11.glPopMatrix();
}
private void renderFastItem (ItemStack itemStack, TileEntityDrawers tile, int slot, ForgeDirection side, float depth, float partialTickTime) {
Minecraft mc = Minecraft.getMinecraft();
int drawerCount = tile.getDrawerCount();
float xunit = getXOffset(drawerCount, slot);
float yunit = getYOffset(drawerCount, slot);
float size = (drawerCount == 1) ? .5f : .25f;
BlockDrawers block = (BlockDrawers)tile.getBlockType();
GL11.glPushMatrix();
alignRendering(side);
moveRendering(size, getOffsetXForSide(side, xunit) * 16 - (8 * size), 12.25f - yunit, .999f - depth + block.trimDepth);
List<IRenderLabel> renderHandlers = StorageDrawers.renderRegistry.getRenderHandlers();
for (int i = 0, n = renderHandlers.size(); i < n; i++) {
renderHandlers.get(i).render(tile, tile, slot, brightness, partialTickTime);
}
if (!ForgeHooksClient.renderInventoryItem(this.renderBlocks, mc.renderEngine, itemStack, true, 0, 0, 0))
itemRenderer.renderItemIntoGUI(mc.fontRenderer, mc.renderEngine, itemStack, 0, 0, true);
GL11.glPopMatrix();
}
private boolean isItemBlockType (ItemStack itemStack) {
return itemStack.getItemSpriteNumber() == 0
&& itemStack.getItem() instanceof ItemBlock
&& RenderBlocks.renderItemIn3d(Block.getBlockFromItem(itemStack.getItem()).getRenderType());
}
private float getXOffset (int drawerCount, int slot) {
switch (drawerCount) {
case 1: return itemOffset1X[slot];
case 2: return itemOffset2X[slot];
case 3: return itemOffset3X[slot];
case 4: return itemOffset4X[slot];
default: return 0;
}
}
private float getYOffset (int drawerCount, int slot) {
switch (drawerCount) {
case 1: return itemOffset1Y[slot];
case 2: return itemOffset2Y[slot];
case 3: return itemOffset3Y[slot];
case 4: return itemOffset4Y[slot];
default: return 0;
}
}
private void alignRendering (ForgeDirection side) {
GL11.glTranslatef(.5f, .5f, .5f);
GL11.glRotatef(180f, 0, 0, 1f); // Render is upside-down: correct it.
GL11.glRotatef(getRotationYForSide2D(side), 0, 1, 0);
GL11.glTranslatef(-.5f, -.5f, -.5f);
}
private void moveRendering (float size, float offsetX, float offsetY, float offsetZ) {
GL11.glTranslatef(0, 0, offsetZ);
GL11.glScalef(1 / 16f, 1 / 16f, -.0001f);
GL11.glTranslatef(offsetX, offsetY, 0);
GL11.glScalef(size, size, 1);
}
private static final float[] sideRotationY = { 0, 0, 0, 2, 1, 3 };
private float getRotationYForSide (ForgeDirection side) {
return sideRotationY[side.ordinal()] * 90;
}
private static final float[] sideRotationY2D = { 0, 0, 0, 2, 3, 1 };
private float getRotationYForSide2D (ForgeDirection side) {
return sideRotationY2D[side.ordinal()] * 90;
}
private static final float[] offsetX = { 0, 0, 0, 0, 0, 0 };
private float getOffsetXForSide (ForgeDirection side, float x) {
return Math.abs(offsetX[side.ordinal()] - x);
}
}
|
package org.sagebionetworks.repo.manager.doi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.mock;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sagebionetworks.doi.DoiClient;
import org.sagebionetworks.doi.EzidAsyncClient;
import org.sagebionetworks.repo.manager.NodeManager;
import org.sagebionetworks.repo.model.DoiAdminDao;
import org.sagebionetworks.repo.model.EntityType;
import org.sagebionetworks.repo.model.Node;
import org.sagebionetworks.repo.model.UserInfo;
import org.sagebionetworks.repo.model.doi.Doi;
import org.sagebionetworks.repo.model.doi.DoiObjectType;
import org.sagebionetworks.repo.model.doi.DoiStatus;
import org.sagebionetworks.repo.web.util.UserProvider;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.util.ReflectionTestUtils;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:test-context.xml" })
public class EntityDoiManagerImplAutowiredTest {
@Autowired private EntityDoiManager entityDoiManager;
@Autowired private NodeManager nodeManager;
@Autowired private UserProvider userProvider;
@Autowired private DoiAdminDao doiAdminDao;
private UserInfo testUserInfo;
private List<String> toClearList;
@Before
public void before() throws Exception {
assertNotNull(entityDoiManager);
assertNotNull(nodeManager);
assertNotNull(userProvider);
assertNotNull(doiAdminDao);
testUserInfo = userProvider.getTestUserInfo();
assertNotNull(testUserInfo);
// Inject a mock DOI client
// If the DOI already exists, EZID will return an error
// We want to avoid the error, thus the mocking
DoiClient mockDoiClient = mock(EzidAsyncClient.class);
EntityDoiManager toInject = entityDoiManager;
if(AopUtils.isAopProxy(toInject) && toInject instanceof Advised) {
Object target = ((Advised)toInject).getTargetSource().getTarget();
toInject = (EntityDoiManager)target;
}
ReflectionTestUtils.setField(toInject, "ezidAsyncClient", mockDoiClient);
toClearList = new ArrayList<String>();
}
@After
public void after() throws Exception {
for (String nodeId : toClearList) {
nodeManager.delete(userProvider.getTestAdminUserInfo(), nodeId);
}
doiAdminDao.clear();
}
@Test
public void testRoundTrip() throws Exception {
Node node = new Node();
final String nodeName = "EntityDoiManagerImplAutowiredTest.testRoundTrip()";
node.setName(nodeName);
node.setNodeType(EntityType.project.name());
final String nodeId = nodeManager.createNewNode(node, testUserInfo);
toClearList.add(nodeId);
assertNotNull(nodeId);
Doi doiCreate = entityDoiManager.createDoi(
testUserInfo.getIndividualGroup().getName(), nodeId, null);
assertNotNull(doiCreate);
assertNotNull(doiCreate.getId());
assertEquals(nodeId, doiCreate.getObjectId());
assertEquals(DoiObjectType.ENTITY, doiCreate.getDoiObjectType());
assertNull(doiCreate.getObjectVersion());
assertNotNull(doiCreate.getCreatedOn());
assertEquals(testUserInfo.getIndividualGroup().getId(), doiCreate.getCreatedBy());
assertNotNull(doiCreate.getUpdatedOn());
assertEquals(DoiStatus.IN_PROCESS, doiCreate.getDoiStatus());
Doi doiGet = entityDoiManager.getDoi(
testUserInfo.getIndividualGroup().getName(), nodeId, null);
assertNotNull(doiGet);
assertNotNull(doiGet.getId());
assertEquals(nodeId, doiGet.getObjectId());
assertEquals(DoiObjectType.ENTITY, doiGet.getDoiObjectType());
assertNull(doiGet.getObjectVersion());
assertNotNull(doiGet.getCreatedOn());
assertEquals(testUserInfo.getIndividualGroup().getId(), doiGet.getCreatedBy());
assertNotNull(doiGet.getUpdatedOn());
assertEquals(DoiStatus.IN_PROCESS, doiGet.getDoiStatus());
}
}
|
package fi.tnie.db.model;
public class LongAdditionModel<A extends Number, B extends Number>
extends AbstractArithmeticLongModel<A, B> {
public LongAdditionModel(ValueModel<A> a, ValueModel<B> b) {
super(a, b);
}
@Override
protected Long compute(A a, B b) {
if (a == null || b == null) {
return null;
}
return Long.valueOf(a.longValue() + b.longValue() + getConstant());
}
public long getConstant() {
return 0;
}
}
|
package fitnesse.fixtures;
import fit.ColumnFixture;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.*;
import fitnesse.wikitext.Utils;
public class ResponseExaminer extends ColumnFixture
{
public String type;
public String pattern;
public String value;
public int number;
private Matcher matcher;
private int currentLine = 0;
public String contents() throws Exception
{
return Utils.escapeText(FitnesseFixtureContext.sender.sentData());
}
public String fullContents() throws Exception
{
return Utils.escapeText(FitnesseFixtureContext.sender.sentData());
}
public boolean inOrder() throws Exception
{
if (value == null) {
return false;
}
String pageContent = FitnesseFixtureContext.sender.sentData();
String[] lines = arrayifyLines(pageContent);
for(int i = currentLine; i < lines.length; i++)
{
if (value.equals(lines[i].trim()))
{
currentLine = i;
return true;
}
}
return false;
}
public int matchCount() throws Exception
{
Pattern p = Pattern.compile(Utils.escapeText(pattern), Pattern.MULTILINE + Pattern.DOTALL);
value = null;
if(type.equals("contents"))
value = contents();
else if(type.equals("fullContents"))
value = fullContents();
else if(type.equals("status"))
value = "" + FitnesseFixtureContext.response.getStatus();
else if(type.equals("headers"))
{
String text = FitnesseFixtureContext.sender.sentData();
int headerEnd = text.indexOf("\r\n\r\n");
value = text.substring(0, headerEnd + 2);
}
matcher = p.matcher(value);
int matches = 0;
for(matches = 0; matcher.find(); matches++) ;
return matches;
}
public boolean matches() throws Exception
{
return matchCount() > 0;
}
public String string() throws Exception
{
String value = null;
if(type.equals("contents"))
{
return FitnesseFixtureContext.page.getData().getHtml();
}
else if(type.equals("line"))
{
String pageContent = FitnesseFixtureContext.page.getData().getHtml();
String lineizedContent = convertBreaksToLineSeparators(pageContent);
StringTokenizer tokenizedLines = tokenizeLines(lineizedContent);
for(int i = number; i != 0; i
value = tokenizedLines.nextToken();
return value.trim();
}
else
{
throw new Exception("Bad type in ResponseExaminer");
}
}
private StringTokenizer tokenizeLines(String lineizedContent)
{
return new StringTokenizer(lineizedContent, System.getProperty("line.separator"));
}
private String[] arrayifyLines(String lineizedContent)
{
return lineizedContent.split(System.getProperty("line.separator"));
}
private String convertBreaksToLineSeparators(String pageContent)
{
String lineizedContent = pageContent.replaceAll("<br>", System.getProperty("line.separator"));
return lineizedContent;
}
public String found()
{
return matcher.group(0);
}
public String source()
{
return value;
}
}
|
package fitnesse.slim;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class ListDeserializerTest {
private List<Object> list;
@Before
public void setUp() {
list = new ArrayList<Object>();
}
private void check() {
String serialized = ListSerializer.serialize(list);
List<Object> deserialized = ListDeserializer.deserialize(serialized);
Assert.assertEquals(list, deserialized);
}
@Test(expected = ListDeserializer.SyntaxError.class)
public void cantDeserializeNullString() throws Exception {
ListDeserializer.deserialize(null);
}
@Test(expected = ListDeserializer.SyntaxError.class)
public void cantDeserializeEmptyString() throws Exception {
ListDeserializer.deserialize("");
}
@Test(expected = ListDeserializer.SyntaxError.class)
public void cantDeserializeStringThatDoesntStartWithBracket() throws Exception {
ListDeserializer.deserialize("hello");
}
@Test(expected = ListDeserializer.SyntaxError.class)
public void cantDeserializeStringThatDoesntEndWithBracket() throws Exception {
ListDeserializer.deserialize("[000000:");
}
@Test
public void emptyList() throws Exception {
check();
}
@Test
public void listWithOneElement() throws Exception {
list.add("hello");
check();
}
@Test
public void listWithTwoElements() throws Exception {
list.add("hello");
list.add("world");
check();
}
@Test
public void listWithSubList() throws Exception {
List<String> sublist = new ArrayList<String>();
sublist.add("hello");
sublist.add("world");
list.add(sublist);
list.add("single");
check();
}
@Test
public void listWithElementsWithBrackets() throws Exception {
list.add("hello");
list.add("[world, world2]");
check();
}
}
|
package eu.dzhw.fdz.metadatamanagement.instrumentmanagement.domain;
import java.util.List;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.BeanUtils;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import com.google.common.base.MoreObjects;
import eu.dzhw.fdz.metadatamanagement.common.domain.AbstractRdcDomainObject;
import eu.dzhw.fdz.metadatamanagement.common.domain.I18nString;
import eu.dzhw.fdz.metadatamanagement.common.domain.util.Patterns;
import eu.dzhw.fdz.metadatamanagement.common.domain.validation.I18nStringNotEmpty;
import eu.dzhw.fdz.metadatamanagement.common.domain.validation.I18nStringSize;
import eu.dzhw.fdz.metadatamanagement.common.domain.validation.StringLengths;
import eu.dzhw.fdz.metadatamanagement.instrumentmanagement.domain.validation.ValidInstrumentIdPattern;
import eu.dzhw.fdz.metadatamanagement.instrumentmanagement.domain.validation.ValidInstrumentType;
import eu.dzhw.fdz.metadatamanagement.instrumentmanagement.domain.validation.ValidUniqueInstrumentNumber;
import io.searchbox.annotations.JestId;
import net.karneim.pojobuilder.GeneratePojoBuilder;
/**
* A Instrument.
*
* @author Daniel Katzberg
*
*/
@Document(collection = "instruments")
@GeneratePojoBuilder(
intoPackage = "eu.dzhw.fdz.metadatamanagement.instrumentmanagement.domain.builders")
@ValidInstrumentIdPattern(message = "instrument-management.error"
+ ".instrument.valid-instrument-id-pattern")
@ValidUniqueInstrumentNumber(message = "instrument-management.error"
+ ".instrument.unique-instrument-number")
@CompoundIndex(def = "{number: 1, dataAcquisitionProjectId: 1}", unique = true)
public class Instrument extends AbstractRdcDomainObject {
@Id
@JestId
@NotEmpty(message = "instrument-management.error.instrument.id.not-empty")
@Pattern(regexp = Patterns.GERMAN_ALPHANUMERIC_WITH_UNDERSCORE_AND_MINUS_AND_DOLLAR,
message = "instrument-management.error.instrument.id.pattern")
@Size(max = StringLengths.MEDIUM, message = "instrument-management.error.instrument.id.size")
private String id;
@Indexed
@NotEmpty(message =
"instrument-management.error.instrument.data-acquisition-project-id.not-empty")
private String dataAcquisitionProjectId;
@NotNull(message = "instrument-management.error.instrument.title.not-null")
@I18nStringSize(max = StringLengths.MEDIUM, message = "instrument-"
+ "management.error.instrument.title.i18n-string-size")
@I18nStringNotEmpty(message = "instrument-management.error.instrument.title."
+ "i18n-string-not-empty")
private I18nString title;
@NotNull(message = "instrument-management.error.instrument.description.not-null")
@I18nStringSize(max = StringLengths.MEDIUM, message = "instrument-"
+ "management.error.instrument.description.i18n-string-size")
@I18nStringNotEmpty(message = "instrument-management.error.instrument.description."
+ "i18n-string-not-empty")
private I18nString description;
@NotNull(message = "instrument-management.error.instrument.number.not-null")
private Integer number;
@NotEmpty(message = "instrument-management.error.instrument.type.not-empty")
@ValidInstrumentType(message = "instrument-management.error.instrument.type.valid")
private String type;
@I18nStringSize(max = StringLengths.LARGE,
message = "instrument-management.error.instrument.annotations.i18n-string-size")
private I18nString annotations;
@Indexed
private List<String> surveyIds;
@NotEmpty(message = "instrument-management.error.instrument.survey-numbers.not-empty")
private List<Integer> surveyNumbers;
@Indexed
@NotEmpty(message = "instrument-management.error.instrument.study-id.not-empty")
private String studyId;
public Instrument() {
super();
}
public Instrument(Instrument instrument) {
super();
BeanUtils.copyProperties(instrument, this);
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDataAcquisitionProjectId() {
return dataAcquisitionProjectId;
}
public void setDataAcquisitionProjectId(String dataAcquisitionProjectId) {
this.dataAcquisitionProjectId = dataAcquisitionProjectId;
}
public I18nString getTitle() {
return title;
}
public void setTitle(I18nString title) {
this.title = title;
}
public I18nString getDescription() {
return description;
}
public void setDescription(I18nString description) {
this.description = description;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
/*
* (non-Javadoc)
* @see eu.dzhw.fdz.metadatamanagement.common.domain.AbstractRdcDomainObject#toString()
*/
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("super", super.toString())
.add("id", id)
.add("title", title)
.add("description", description)
.add("type", type)
.add("dataAcquisitionProjectId", dataAcquisitionProjectId)
.add("surveyIds", surveyIds)
.add("surveyNumbers", surveyNumbers)
.add("number", number)
.add("annotations", annotations)
.add("studyId", studyId)
.toString();
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<String> getSurveyIds() {
return surveyIds;
}
public void setSurveyIds(List<String> surveyIds) {
this.surveyIds = surveyIds;
}
public List<Integer> getSurveyNumbers() {
return surveyNumbers;
}
public void setSurveyNumbers(List<Integer> surveyNumbers) {
this.surveyNumbers = surveyNumbers;
}
public String getStudyId() {
return studyId;
}
public void setStudyId(String studyId) {
this.studyId = studyId;
}
public I18nString getAnnotations() {
return annotations;
}
public void setAnnotations(I18nString annotations) {
this.annotations = annotations;
}
}
|
package net.sf.taverna.t2.activities.wsdl.views;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
//import org.apache.log4j.Logger;
import net.sf.taverna.t2.activities.wsdl.WSDLActivityConfigurationBean;
import net.sf.taverna.t2.activities.wsdl.security.SecurityProfiles;
import net.sf.taverna.t2.lang.ui.DialogTextArea;
import net.sf.taverna.t2.workbench.ui.credentialmanager.CredentialManagerUI;
/**
* Configuration dialog for WSDL activity.
*
* @author Alex Nenadic
*
*/
@SuppressWarnings("serial")
public class WSDLActivityConfigurationView extends JDialog implements ItemListener{
private WSDLActivityConfigurationBean oldBean;
private WSDLActivityConfigurationBean newBean;
private ButtonGroup buttonGroup;
private JRadioButton noSecurityRadioButton;
private JLabel noSecurityLabel;
private JRadioButton httpSecurityAuthNRadioButton;
private JLabel httpSecurityAuthNLabel;
private JRadioButton wsSecurityAuthNRadioButton;
private JLabel wsSecurityAuthNLabel;
// Password types
private final String PLAINTEXT_PASSWORD = "Plaintext password";
private final String DIGEST_PASSWORD = "Digest password";
private String[] passwordTypes = new String[]{PLAINTEXT_PASSWORD, DIGEST_PASSWORD};
private String[] tooltips = new String[]{ "Password will be sent in plaintext (which is OK if service is using HTTPS)",
"Password will be digested (cryptographically hashed) before sending"};
private JComboBox passwordTypeComboBox;
private JCheckBox addTimestampCheckBox;
private JButton setHttpUsernamePasswordButton;
private JButton setWsdlUsernamePasswordButton;
//private Logger logger = Logger.getLogger(WSDLActivityConfigurationView.class);
public WSDLActivityConfigurationView(WSDLActivityConfigurationBean bean){
super((Frame)null, "Web service configuration", true); //create a modal dialog
this.oldBean = bean;
newBean = copy(oldBean);
initComponents();
}
public WSDLActivityConfigurationView(Frame owner, WSDLActivityConfigurationBean bean){
super(owner, "WSDL service configuration", true); //create a modal dialog
this.oldBean = bean;
newBean = copy(oldBean);
initComponents();
}
/**
* Creates a copy of the bean.
*/
private WSDLActivityConfigurationBean copy(
WSDLActivityConfigurationBean oldBean) {
WSDLActivityConfigurationBean newBean = new WSDLActivityConfigurationBean();
newBean.setOperation(oldBean.getOperation());
newBean.setWsdl(oldBean.getWsdl());
newBean.setSecurityProfile(oldBean.getSecurityProfile());
return newBean;
}
private void initComponents() {
int gridy = 0;
// title panel
JPanel titlePanel = new JPanel(new BorderLayout());
titlePanel.setBackground(Color.WHITE);
JLabel titleLabel = new JLabel("Security configuration");
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 13.5f));
titleLabel.setBorder(new EmptyBorder(10, 10, 0, 10));
DialogTextArea titleMessage = new DialogTextArea("Select a security profile for the service");
titleMessage.setMargin(new Insets(5, 20, 10, 10));
titleMessage.setFont(titleMessage.getFont().deriveFont(11f));
titleMessage.setEditable(false);
titleMessage.setFocusable(false);
titlePanel.setBorder( new EmptyBorder(10, 10, 0, 10));
titlePanel.add(titleLabel, BorderLayout.NORTH);
titlePanel.add(titleMessage, BorderLayout.CENTER);
addDivider(titlePanel, SwingConstants.BOTTOM, true);
// Main panel
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
//Create the radio buttons
noSecurityRadioButton = new JRadioButton("None");
noSecurityRadioButton.addItemListener(this);
wsSecurityAuthNRadioButton = new JRadioButton("WS-Security username and password authentication");
wsSecurityAuthNRadioButton.addItemListener(this);
httpSecurityAuthNRadioButton = new JRadioButton("HTTP username and password authentication");
httpSecurityAuthNRadioButton.addItemListener(this);
//Group the radio buttons
buttonGroup = new ButtonGroup();
buttonGroup.add(noSecurityRadioButton);
buttonGroup.add(wsSecurityAuthNRadioButton);
buttonGroup.add(httpSecurityAuthNRadioButton);
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1.0;
gbc.weighty = 0.0;
gbc.gridx = 0;
gbc.gridy = gridy++;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5, 10, 0, 0);
mainPanel.add(noSecurityRadioButton, gbc);
noSecurityLabel = new JLabel("Service requires no security");
noSecurityLabel.setFont(noSecurityLabel.getFont().deriveFont(11f));
// addDivider(noSecurityLabel, SwingConstants.BOTTOM, false);
gbc.gridx = 0;
gbc.gridy = gridy++;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(0, 40, 10, 10);
mainPanel.add(noSecurityLabel, gbc);
gbc.gridx = 0;
gbc.gridy = gridy++;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5, 10, 0, 0);
mainPanel.add(httpSecurityAuthNRadioButton, gbc);
ActionListener usernamePasswordListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Get Credential Manager UI to get the username and password for the service
CredentialManagerUI credManagerUI = CredentialManagerUI.getInstance();
if (credManagerUI != null)
credManagerUI.newPasswordForService(oldBean.getWsdl());
}
};
httpSecurityAuthNLabel = new JLabel("Service requires HTTP username and password in order to authenticate the user");
httpSecurityAuthNLabel.setFont(httpSecurityAuthNLabel.getFont().deriveFont(11f));
gbc.gridx = 0;
gbc.gridy = gridy++;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(0, 40, 10, 10);
mainPanel.add(httpSecurityAuthNLabel, gbc);
// Set username and password button;
setHttpUsernamePasswordButton = new JButton("Set username and password");
gbc.gridx = 0;
gbc.gridy = gridy++;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(0, 40, 10, 10);
gbc.weightx = 1.0;
gbc.weighty = 1.0; // add any vertical space to this component
mainPanel.add(setHttpUsernamePasswordButton, gbc);
setHttpUsernamePasswordButton.addActionListener(usernamePasswordListener);
gbc.gridx = 0;
gbc.gridy = gridy++;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5, 10, 0, 0);
mainPanel.add(wsSecurityAuthNRadioButton, gbc);
wsSecurityAuthNLabel = new JLabel("Service requires WS-Security username and password in order to authenticate the user");
wsSecurityAuthNLabel.setFont(wsSecurityAuthNLabel.getFont().deriveFont(11f));
gbc.gridx = 0;
gbc.gridy = gridy++;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(0, 40, 0, 0);
mainPanel.add(wsSecurityAuthNLabel, gbc);
// Password type list
passwordTypeComboBox = new JComboBox(passwordTypes);
passwordTypeComboBox.setRenderer(new ComboBoxTooltipRenderer());
gbc.gridx = 0;
gbc.gridy = gridy++;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(10, 40, 0, 0);
mainPanel.add(passwordTypeComboBox, gbc);
// 'Add timestamp' checkbox
addTimestampCheckBox = new JCheckBox("Add a timestamp to SOAP message");
gbc.gridx = 0;
gbc.gridy = gridy++;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5, 40, 10, 10);
mainPanel.add(addTimestampCheckBox, gbc);
// Set username and password button;
setWsdlUsernamePasswordButton = new JButton("Set username and password");
gbc.gridx = 0;
gbc.gridy = gridy++;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(0, 40, 10, 10);
gbc.weightx = 1.0;
gbc.weighty = 1.0; // add any vertical space to this component
mainPanel.add(setWsdlUsernamePasswordButton, gbc);
setWsdlUsernamePasswordButton.addActionListener(usernamePasswordListener);
addDivider(mainPanel, SwingConstants.BOTTOM, true);
// OK/Cancel button panel
JPanel okCancelPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
okPressed();
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
cancelPressed();
}
});
okCancelPanel.add(cancelButton);
okCancelPanel.add(okButton);
// Enable/disable controls based on what is the current security profiles
String securityProfile = oldBean.getSecurityProfile();
if (securityProfile == null){
noSecurityRadioButton.setSelected(true);
}
else{
if (securityProfile.equals(SecurityProfiles.WSSECURITY_USERNAMETOKEN_PLAINTEXTPASSWORD) ||
securityProfile.equals(SecurityProfiles.WSSECURITY_USERNAMETOKEN_DIGESTPASSWORD) ||
securityProfile.equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_PLAINTEXTPASSWORD) ||
securityProfile.equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_DIGESTPASSWORD) ){
wsSecurityAuthNRadioButton.setSelected(true);
}
if (securityProfile.equals(SecurityProfiles.HTTP_BASIC_AUTHN) ||
securityProfile.equals(SecurityProfiles.HTTP_DIGEST_AUTHN)) {
httpSecurityAuthNRadioButton.setSelected(true);
}
if (securityProfile.equals(SecurityProfiles.WSSECURITY_USERNAMETOKEN_PLAINTEXTPASSWORD) ||
securityProfile.equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_PLAINTEXTPASSWORD)){
passwordTypeComboBox.setSelectedItem(PLAINTEXT_PASSWORD);
}
else if (securityProfile.equals(SecurityProfiles.WSSECURITY_USERNAMETOKEN_DIGESTPASSWORD) ||
securityProfile.equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_DIGESTPASSWORD)){
passwordTypeComboBox.setSelectedItem(DIGEST_PASSWORD);
}
if (securityProfile.equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_DIGESTPASSWORD) ||
securityProfile.equals(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_PLAINTEXTPASSWORD)){
addTimestampCheckBox.setSelected(true);
}
else {
addTimestampCheckBox.setSelected(false);
}
}
// Put everything together
JPanel layoutPanel = new JPanel(new BorderLayout());
layoutPanel.add(titlePanel, BorderLayout.NORTH);
layoutPanel.add(mainPanel, BorderLayout.CENTER);
layoutPanel.add(okCancelPanel, BorderLayout.SOUTH);
layoutPanel.setPreferredSize(new Dimension(550,400));
this.getContentPane().add(layoutPanel);
this.pack();
}
private void okPressed() {
if (noSecurityRadioButton.isSelected()){
newBean.setSecurityProfile(null); // no security required
}
else if (httpSecurityAuthNRadioButton.isSelected()) {
newBean.setSecurityProfile(SecurityProfiles.HTTP_BASIC_AUTHN);
}
else if (wsSecurityAuthNRadioButton.isSelected()){ // plaintext password
if (passwordTypeComboBox.getSelectedItem().equals(PLAINTEXT_PASSWORD)){
if (addTimestampCheckBox.isSelected()){
newBean.setSecurityProfile(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_PLAINTEXTPASSWORD);
}
else{
newBean.setSecurityProfile(SecurityProfiles.WSSECURITY_USERNAMETOKEN_PLAINTEXTPASSWORD);
}
}
else { //digest password
if (addTimestampCheckBox.isSelected()){
newBean.setSecurityProfile(SecurityProfiles.WSSECURITY_TIMESTAMP_USERNAMETOKEN_DIGESTPASSWORD);
}
else{
newBean.setSecurityProfile(SecurityProfiles.WSSECURITY_USERNAMETOKEN_DIGESTPASSWORD);
}
}
}
closeDialog();
}
private void cancelPressed() {
newBean = null; // to indicate that user has cancelled
closeDialog();
}
/**
* Close the dialog.
*/
private void closeDialog()
{
setVisible(false);
dispose();
}
/**
* Disable/enable items on the panel based on this radio button
* has been selected.
*/
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
if (source == noSecurityRadioButton) {
httpSecurityAuthNLabel.setEnabled(false);
wsSecurityAuthNLabel.setEnabled(false);
passwordTypeComboBox.setEnabled(false);
setHttpUsernamePasswordButton.setEnabled(false);
setWsdlUsernamePasswordButton.setEnabled(false);
addTimestampCheckBox.setEnabled(false);
noSecurityLabel.setEnabled(true);
}
else if (source == httpSecurityAuthNRadioButton) {
noSecurityLabel.setEnabled(false);
httpSecurityAuthNLabel.setEnabled(true);
wsSecurityAuthNLabel.setEnabled(false);
passwordTypeComboBox.setEnabled(false);
setHttpUsernamePasswordButton.setEnabled(true);
setWsdlUsernamePasswordButton.setEnabled(false);
addTimestampCheckBox.setEnabled(false);
}
else if (source == wsSecurityAuthNRadioButton) {
noSecurityLabel.setEnabled(false);
httpSecurityAuthNLabel.setEnabled(false);
wsSecurityAuthNLabel.setEnabled(true);
passwordTypeComboBox.setEnabled(true);
setHttpUsernamePasswordButton.setEnabled(false);
setWsdlUsernamePasswordButton.setEnabled(true);
addTimestampCheckBox.setEnabled(true);
}
}
/**
* A renderer for JComboBox that will display a tooltip for
* the selected item.
*
*/
class ComboBoxTooltipRenderer extends BasicComboBoxRenderer {
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
if (-1 < index) {
list.setToolTipText(tooltips[index]);
}
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
setFont(list.getFont());
setText((value == null) ? "" : value.toString());
return this;
}
}
/**
* Adds a light gray or etched border to the top or bottom of a JComponent.
*
* @author David Withers
* @param component
*/
protected void addDivider(JComponent component, final int position, final boolean etched) {
component.setBorder(new Border() {
private final Color borderColor = new Color(.6f, .6f, .6f);
public Insets getBorderInsets(Component c) {
if (position == SwingConstants.TOP) {
return new Insets(5, 0, 0, 0);
} else {
return new Insets(0, 0, 5, 0);
}
}
public boolean isBorderOpaque() {
return false;
}
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
if (position == SwingConstants.TOP) {
if (etched) {
g.setColor(borderColor);
g.drawLine(x, y, x + width, y);
g.setColor(Color.WHITE);
g.drawLine(x, y + 1, x + width, y + 1);
} else {
g.setColor(Color.LIGHT_GRAY);
g.drawLine(x, y, x + width, y);
}
} else {
if (etched) {
g.setColor(borderColor);
g.drawLine(x, y + height - 2, x + width, y + height - 2);
g.setColor(Color.WHITE);
g.drawLine(x, y + height - 1, x + width, y + height - 1);
} else {
g.setColor(Color.LIGHT_GRAY);
g.drawLine(x, y + height - 1, x + width, y + height - 1);
}
}
}
});
}
/**
* Gets the new bean after user has finished with configuring it.
*/
public WSDLActivityConfigurationBean getNewBean() {
return newBean;
}
}
|
package org.asciidoc.intellij.actions;
import com.intellij.codeInsight.AutoPopupController;
import com.intellij.codeInsight.editorActions.TypedHandlerDelegate;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import org.asciidoc.intellij.file.AsciiDocFileType;
import org.jetbrains.annotations.NotNull;
/**
* Show the autocomplete lookup list automatically in places where it could be helpful to the user.
*/
public class AsciiDocTriggerAutoCompleteTypedHandler extends TypedHandlerDelegate {
@Override
public @NotNull Result charTyped(char charTyped, @NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
if (file.getFileType().equals(AsciiDocFileType.INSTANCE)) {
// will not see single quotes (') and double quotes (") as they will be handled by the quote handler
if (charTyped == ':' // might be the start of an attribute declaration: ':attribute:', or the body of a macro: 'xref:file.adoc[]`
|| charTyped == '!' // might be the start of an attribute unset like ':!attribute:'
|| charTyped == '{' // might be the start of an attribute reference: '{attribute}'
|| charTyped == '<' // might be the start of an anchor reference: '<<anchor>>'
|| charTyped == '#' // might be the start of an anchor in an xref: 'xref:file.adoc#anchor[]'
|| charTyped == '=' // might be the start of a tag like 'include::file.adoc[tag=name]'
) {
// for now, always try to show the lookup. The condition could try to be more specific in the future.
AutoPopupController.getInstance(project).autoPopupMemberLookup(editor, null);
}
}
return Result.CONTINUE;
}
}
|
package org.voltdb.elt;
import java.util.*;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.voltdb.catalog.*;
import org.voltdb.dtxn.SiteTracker;
import org.voltdb.elt.processors.RawProcessor.ELTInternalMessage;
import org.voltdb.utils.*;
/**
* Bridges the connection to an OLAP system and the buffers passed
* between the OLAP connection and the execution engine. Each processor
* implements ELTDataProcessor interface. The processors are passed one
* or more ELTDataSources. The sources map, currently, 1:1 with ELT
* enabled tables. The ELTDataSource has poll() and ack() methods that
* processors may use to pull and acknowledge as processed, EE ELT data.
* Data passed to processors is wrapped in ELTDataBlocks which in turn
* wrap a BBContainer.
*
* Processors are loaded by reflection based on configuration in project.xml.
*/
public class ELTManager
{
/**
* Processors also log using this facility.
*/
private static final Logger eltLog =
Logger.getLogger("ELT", VoltLoggerFactory.instance());
/**
* Thrown if the initial setup of the loader fails
*/
public static class SetupException extends Exception {
private static final long serialVersionUID = 1L;
private final String m_msg;
SetupException(final String msg) {
m_msg = msg;
}
@Override
public String getMessage() {
return m_msg;
}
}
/**
* Connections OLAP loaders. Currently at most one loader allowed.
* Supporting multiple loaders mainly involves reference counting
* the EE data blocks and bookkeeping ACKs from processors.
*/
ArrayDeque<ELTDataProcessor> m_processors = new ArrayDeque<ELTDataProcessor>();
/** Obtain the global ELTManager via its instance() method */
private static ELTManager m_self;
/**
* Construct ELTManager using catalog.
* @param myHostId
* @param catalog
* @param siteTracker
* @throws ELTManager.SetupException
*/
public static synchronized void initialize(int myHostId, final Catalog catalog, SiteTracker siteTracker)
throws ELTManager.SetupException
{
ELTManager tmp = new ELTManager(myHostId, catalog, siteTracker);
m_self = tmp;
}
/**
* Get the global instance of the ELTManager.
* @return The global single instance of the ELTManager.
*/
public static ELTManager instance() {
assert (m_self != null);
return m_self;
}
/** Read the catalog to setup manager and loader(s)
* @param myHostId
* @param siteTracker */
private ELTManager(int myHostId, final Catalog catalog, SiteTracker siteTracker) throws ELTManager.SetupException {
final Cluster cluster = catalog.getClusters().get("cluster");
final Database db = cluster.getDatabases().get("database");
final Connector conn= db.getConnectors().get("0");
if (conn == null) {
return;
}
if (conn.getEnabled() == false) {
eltLog.info("Export is disabled by user configuration.");
return;
}
final String elloader = conn.getLoaderclass();
try {
eltLog.info("Creating connector " + elloader);
ELTDataProcessor newProcessor = null;
final Class<?> loaderClass = Class.forName(elloader);
newProcessor = (ELTDataProcessor)loaderClass.newInstance();
newProcessor.addLogger(eltLog);
Iterator<ConnectorTableInfo> tableInfoIt = conn.getTableinfo().iterator();
while (tableInfoIt.hasNext()) {
ConnectorTableInfo next = tableInfoIt.next();
Table table = next.getTable();
addDataSources(newProcessor, table, myHostId, siteTracker);
}
newProcessor.readyForData();
m_processors.add(newProcessor);
}
catch (final ClassNotFoundException e) {
eltLog.l7dlog( Level.ERROR, LogKeys.elt_ELTManager_NoLoaderExtensions.name(), e);
throw new ELTManager.SetupException(e.getMessage());
}
catch (final Throwable e) {
throw new ELTManager.SetupException(e.getMessage());
}
}
// silly helper to add datasources for a table catalog object
private void addDataSources(ELTDataProcessor newProcessor,
Table table, int hostId, SiteTracker siteTracker)
{
ArrayList<Integer> sites = siteTracker.getLiveExecutionSitesForHost(hostId);
for (Integer site : sites) {
newProcessor.addDataSource(
new ELTDataSource("database",
table.getTypeName(),
siteTracker.getPartitionForSite(site),
site,
table.getRelativeIndex(),
table.getColumns())
);
}
}
/**
* Add a message to the processor "mailbox".
* @param mbp
*/
public void queueMessage(ELTInternalMessage mbp) {
// TODO: supporting multiple processors requires slicing the
// data buffer so each processor gets a readonly buffer.
m_processors.getFirst().queueMessage(mbp);
}
public void shutdown() {
for (ELTDataProcessor p : m_processors) {
p.shutdown();
}
}
}
|
package org.voltdb.snmp;
import static com.google_voltpatches.common.base.Preconditions.checkArgument;
import java.util.List;
import com.google_voltpatches.common.collect.ImmutableList;
public enum FaultCode {
__unsmnp__, // ordinal 0 doesn't map to SNMP enumerations
HOST_DOWN,
HOST_UP,
RESOURCE_TRIGGER,
RESOURCE_CLEAR,
CRASH,
STATISTICS_TRIGGER,
STATISTICS_CLEAR,
PAUSE,
RESUME,
STREAM_BLOCKED;
public final static List<FaultCode> values = ImmutableList.copyOf(values());
static final public FaultCode valueOf(int ordinal) {
checkArgument(ordinal > __unsmnp__.ordinal() && ordinal < values.size());
return values.get(ordinal);
}
}
|
package org.realityforge.replicant.client.transport;
import com.google.web.bindery.event.shared.EventBus;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.realityforge.replicant.client.Change;
import org.realityforge.replicant.client.ChangeMapper;
import org.realityforge.replicant.client.ChangeSet;
import org.realityforge.replicant.client.ChannelAction;
import org.realityforge.replicant.client.ChannelDescriptor;
import org.realityforge.replicant.client.ChannelSubscriptionEntry;
import org.realityforge.replicant.client.EntityChangeBroker;
import org.realityforge.replicant.client.EntityRepository;
import org.realityforge.replicant.client.EntityRepositoryDebugger;
import org.realityforge.replicant.client.EntityRepositoryValidator;
import org.realityforge.replicant.client.EntitySubscriptionEntry;
import org.realityforge.replicant.client.EntitySubscriptionManager;
import org.realityforge.replicant.client.Linkable;
import org.realityforge.replicant.client.transport.AreaOfInterestAction.Action;
/**
* Class from which to extend to implement a service that loads data from a change set.
* Data can be loaded by bulk or incrementally and the load can be broken up into several
* steps to avoid locking a thread such as in GWT.
*/
public abstract class AbstractDataLoaderService<T extends ClientSession<T, G>, G extends Enum>
{
protected static final Logger LOG = Logger.getLogger( AbstractDataLoaderService.class.getName() );
private static final int DEFAULT_CHANGES_TO_PROCESS_PER_TICK = 100;
private static final int DEFAULT_LINKS_TO_PROCESS_PER_TICK = 100;
private final ChangeMapper _changeMapper;
private final EntityChangeBroker _changeBroker;
private final EntityRepository _repository;
private final CacheService _cacheService;
private final EntitySubscriptionManager _subscriptionManager;
private final SessionContext _sessionContext;
private final EventBus _eventBus;
private DataLoadAction _currentAction;
private AreaOfInterestAction<G> _currentAoiAction;
private int _changesToProcessPerTick = DEFAULT_CHANGES_TO_PROCESS_PER_TICK;
private int _linksToProcessPerTick = DEFAULT_LINKS_TO_PROCESS_PER_TICK;
private T _session;
protected AbstractDataLoaderService( @Nonnull final SessionContext sessionContext,
@Nonnull final ChangeMapper changeMapper,
@Nonnull final EntityChangeBroker changeBroker,
@Nonnull final EntityRepository repository,
@Nonnull final CacheService cacheService,
@Nonnull final EntitySubscriptionManager subscriptionManager,
@Nonnull final EventBus eventBus )
{
_sessionContext = sessionContext;
_changeMapper = changeMapper;
_changeBroker = changeBroker;
_repository = repository;
_cacheService = cacheService;
_subscriptionManager = subscriptionManager;
_eventBus = eventBus;
}
protected SessionContext getSessionContext()
{
return _sessionContext;
}
/**
* Action invoked after current action completes to reset session state.
*/
private Runnable _resetAction;
protected boolean shouldPurgeOnSessionChange()
{
return true;
}
protected void setSession( @Nullable final T session, @Nullable final Runnable postAction )
{
final Runnable runnable = new Runnable()
{
@Override
public void run()
{
doSetSession( session, postAction );
}
};
if ( null == _currentAction )
{
runnable.run();
}
else
{
_resetAction = runnable;
}
}
private void doSetSession( final T session, final Runnable postAction )
{
if ( session != _session )
{
_session = session;
// This should probably be moved elsewhere ... but where?
_sessionContext.setSession( session );
if ( shouldPurgeOnSessionChange() )
{
final boolean enabled = _changeBroker.isEnabled();
if ( enabled )
{
_changeBroker.disable( getSystemKey() );
}
//TODO: else schedule action so that it runs in loop
// until it can disable broker. This will involve replacing _resetAction
// with something more like existing action setup.
purgeSubscriptions();
if ( enabled )
{
_changeBroker.enable( getSystemKey() );
}
}
}
if ( null != postAction )
{
postAction.run();
}
}
protected final CacheService getCacheService()
{
return _cacheService;
}
protected final EntityChangeBroker getChangeBroker()
{
return _changeBroker;
}
protected final ChangeMapper getChangeMapper()
{
return _changeMapper;
}
protected final EntitySubscriptionManager getSubscriptionManager()
{
return _subscriptionManager;
}
public final T getSession()
{
return _session;
}
/**
* Return the id of the session associated with the service.
*
* @return the id of the session associated with the service.
* @throws BadSessionException if the service is not currently associated with the session.
*/
protected final String getSessionID()
throws BadSessionException
{
final T session = getSession();
if ( null == session )
{
throw new BadSessionException( "Missing session." );
}
return session.getSessionID();
}
protected void purgeSubscriptions()
{
final EntitySubscriptionManager subscriptionManager = getSubscriptionManager();
for ( final Enum graph : sortGraphs( subscriptionManager.getInstanceSubscriptionKeys() ) )
{
unsubscribeInstanceGraphs( graph );
}
for ( final Enum graph : sortGraphs( subscriptionManager.getTypeSubscriptions() ) )
{
subscriptionManager.unsubscribe( graph );
}
}
protected void unsubscribeInstanceGraphs( final Enum graph )
{
final EntitySubscriptionManager subscriptionManager = getSubscriptionManager();
for ( final Object id : new ArrayList<>( subscriptionManager.getInstanceSubscriptions( graph ) ) )
{
subscriptionManager.unsubscribe( graph, id );
}
}
private ArrayList<Enum> sortGraphs( final Set<Enum> enums )
{
final ArrayList<Enum> list = new ArrayList<>( enums );
Collections.sort( list );
Collections.reverse( list );
return list;
}
/**
* Ugly hack, should split into two (schedule subscribe, schedule data)
*/
protected abstract void scheduleDataLoad();
protected final void setChangesToProcessPerTick( final int changesToProcessPerTick )
{
_changesToProcessPerTick = changesToProcessPerTick;
}
protected final void setLinksToProcessPerTick( final int linksToProcessPerTick )
{
_linksToProcessPerTick = linksToProcessPerTick;
}
protected abstract ChangeSet parseChangeSet( String rawJsonData );
protected final boolean progressAreaOfInterestActions()
{
if ( null == _currentAoiAction )
{
final LinkedList<AreaOfInterestAction<G>> actions = getSession().getPendingAreaOfInterestActions();
if ( 0 == actions.size() )
{
return false;
}
_currentAoiAction = actions.removeFirst();
}
if ( _currentAoiAction.isInProgress() )
{
return false;
}
else
{
_currentAoiAction.markAsInProgress();
final G graph = _currentAoiAction.getGraph();
final Object id = _currentAoiAction.getId();
final Object filterParameter = _currentAoiAction.getFilterParameter();
final String label =
graph.name() +
( null == id ? "" : "(" + id + ")" ) +
( null == filterParameter ? "" : "[" + filterParameter + "]" );
final Runnable userAction = _currentAoiAction.getUserAction();
final String cacheKey = _currentAoiAction.getCacheKey();
final Action action = _currentAoiAction.getAction();
if ( action == Action.ADD )
{
final ChannelSubscriptionEntry entry = findSubscription( graph, id );
//Already subscribed
if ( null != entry )
{
LOG.warning( "Subscription to " + label + " requested but already subscribed." );
completeAoiAction( userAction );
return true;
}
final Runnable cacheAction;
final String eTag;
if ( null != cacheKey )
{
final CacheEntry cacheEntry = _cacheService.lookup( cacheKey );
eTag = null != cacheEntry ? cacheEntry.getETag() : null;
final String content = null != cacheEntry ? cacheEntry.getContent() : null;
if ( null != content )
{
final String message =
"Found locally cached data for graph " + label + " with etag " + eTag + ".";
LOG.info( message );
cacheAction = new Runnable()
{
public void run()
{
LOG.info( "Loading cached data for graph " + label + " with etag " + eTag );
//TODO: Figure out how to make the bulkLoad configurable
final Runnable runnable = new Runnable()
{
@Override
public void run()
{
completeAoiAction( userAction );
}
};
getSession().enqueueOOB( content, runnable, true );
}
};
}
else
{
cacheAction = null;
}
}
else
{
eTag = null;
cacheAction = null;
}
final Runnable runnable = new Runnable()
{
@Override
public void run()
{
LOG.info( "Subscription to " + label + " completed." );
completeAoiAction( userAction );
}
};
LOG.info( "Subscription to " + label + " requested." );
requestSubscribeToGraph( graph, id, filterParameter, eTag, cacheAction, runnable );
return true;
}
else if ( action == Action.REMOVE )
{
final ChannelSubscriptionEntry entry = findSubscription( graph, id );
//Not subscribed
if ( null == entry )
{
LOG.warning( "Unsubscribe from " + label + " requested but not subscribed." );
completeAoiAction( userAction );
return true;
}
LOG.info( "Unsubscribe from " + label + " requested." );
final Runnable runnable = new Runnable()
{
@Override
public void run()
{
LOG.info( "Unsubscribe from " + label + " completed." );
completeAoiAction( userAction );
}
};
requestUnsubscribeFromGraph( graph, id, runnable );
return true;
}
else
{
final ChannelSubscriptionEntry entry = findSubscription( graph, id );
//Not subscribed
if ( null == entry )
{
LOG.warning( "Subscription update of " + label + " requested but not subscribed." );
completeAoiAction( userAction );
return true;
}
final Runnable runnable = new Runnable()
{
@Override
public void run()
{
LOG.warning( "Subscription update of " + label + " completed." );
completeAoiAction( userAction );
}
};
LOG.warning( "Subscription update of " + label + " requested." );
assert null != filterParameter;
requestUpdateSubscription( graph, id, filterParameter, runnable );
return true;
}
}
}
private ChannelSubscriptionEntry findSubscription( final G graph, final Object id )
{
final ChannelSubscriptionEntry entry;
if ( null == id )
{
entry = _subscriptionManager.findSubscription( graph );
}
else
{
entry = _subscriptionManager.findSubscription( graph, id );
}
return entry;
}
private void completeAoiAction( final Runnable userAction )
{
scheduleDataLoad();
if ( null != userAction )
{
userAction.run();
}
_currentAoiAction.markAsComplete();
_currentAoiAction = null;
}
protected abstract void requestSubscribeToGraph( @Nonnull G graph,
@Nullable Object id,
@Nullable Object filterParameter,
@Nullable String eTag,
@Nullable Runnable cacheAction,
@Nonnull Runnable completionAction );
protected abstract void requestUnsubscribeFromGraph( @Nonnull G graph,
@Nullable Object id,
@Nonnull Runnable completionAction );
protected abstract void requestUpdateSubscription( @Nonnull G graph,
@Nullable Object id,
@Nonnull Object filterParameter,
@Nonnull Runnable completionAction );
protected final boolean isSubscribed( @Nonnull final G graph, @Nonnull final Object id )
{
return null != _subscriptionManager.findSubscription( graph, id );
}
protected final boolean isSubscribed( @Nonnull final G graph )
{
return null != _subscriptionManager.findSubscription( graph );
}
final DataLoadAction getCurrentAction()
{
return _currentAction;
}
protected final boolean progressDataLoad()
{
// Step: Retrieve any out of band actions
final LinkedList<DataLoadAction> oobActions = getSession().getOobActions();
if ( null == _currentAction && !oobActions.isEmpty() )
{
_currentAction = oobActions.removeFirst();
return true;
}
//Step: Retrieve the action from the parsed queue if it is the next in the sequence
final LinkedList<DataLoadAction> parsedActions = getSession().getParsedActions();
if ( null == _currentAction && !parsedActions.isEmpty() )
{
final DataLoadAction action = parsedActions.get( 0 );
final ChangeSet changeSet = action.getChangeSet();
assert null != changeSet;
if ( action.isOob() || getSession().getLastRxSequence() + 1 == changeSet.getSequence() )
{
_currentAction = parsedActions.remove();
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Parsed Action Selected: " + _currentAction );
}
return true;
}
}
// Abort if there is no pending data load actions to take
final LinkedList<DataLoadAction> pendingActions = getSession().getPendingActions();
if ( null == _currentAction && pendingActions.isEmpty() )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "No data to load. Terminating incremental load process." );
}
onTerminatingIncrementalDataLoadProcess();
return false;
}
//Step: Retrieve the action from the un-parsed queue
if ( null == _currentAction )
{
_currentAction = pendingActions.remove();
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Un-parsed Action Selected: " + _currentAction );
}
return true;
}
//Step: Parse the json
final String rawJsonData = _currentAction.getRawJsonData();
if ( null != rawJsonData )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Parsing JSON: " + _currentAction );
}
final ChangeSet changeSet = parseChangeSet( _currentAction.getRawJsonData() );
// OOB messages are not in response to requests as such
final String requestID = _currentAction.isOob() ? null : changeSet.getRequestID();
// OOB messages have no etags as from local cache or generated locally
final String eTag = _currentAction.isOob() ? null : changeSet.getETag();
final int sequence = _currentAction.isOob() ? 0 : changeSet.getSequence();
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(),
"Parsed ChangeSet:" +
" oob=" + _currentAction.isOob() +
" seq=" + sequence +
" requestID=" + requestID +
" eTag=" + eTag +
" changeCount=" + changeSet.getChangeCount()
);
}
final RequestEntry request;
if ( _currentAction.isOob() )
{
request = null;
}
else
{
request = null != requestID ? getSession().getRequest( requestID ) : null;
if ( null == request && null != requestID )
{
final String message =
"Unable to locate requestID '" + requestID + "' specified for ChangeSet: seq=" + sequence +
" Existing Requests: " + getSession().getRequests();
if ( LOG.isLoggable( Level.WARNING ) )
{
LOG.warning( message );
}
throw new IllegalStateException( message );
}
else if ( null != request )
{
final String cacheKey = request.getCacheKey();
if ( null != eTag && null != cacheKey )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Caching ChangeSet: seq=" + sequence + " cacheKey=" + cacheKey );
}
getCacheService().store( cacheKey, eTag, rawJsonData );
}
}
}
_currentAction.setChangeSet( changeSet, request );
parsedActions.add( _currentAction );
Collections.sort( parsedActions );
_currentAction = null;
return true;
}
//Step: Setup the change recording state
if ( _currentAction.needsBrokerPause() )
{
if ( getChangeBroker().isInTransaction() )
{
// Another DataLoaderService has temporarily paused/disabled the broker. So we will
// just spin waiting for it to be released.
return true;
}
_currentAction.markBrokerPaused();
if ( _currentAction.isBulkLoad() )
{
getChangeBroker().disable( getSystemKey() );
}
else
{
getChangeBroker().pause( getSystemKey() );
}
return true;
}
if ( _currentAction.needsChannelActionsProcessed() )
{
_currentAction.markChannelActionsProcessed();
final ChangeSet changeSet = _currentAction.getChangeSet();
assert null != changeSet;
final int channelActionCount = changeSet.getChannelActionCount();
for ( int i = 0; i < channelActionCount; i++ )
{
final ChannelAction action = changeSet.getChannelAction( i );
final int channel = action.getChannelID();
final Object subChannelID = action.getSubChannelID();
final Object filter = action.getChannelFilter();
final ChannelAction.Action actionType = action.getAction();
if ( LOG.isLoggable( getLogLevel() ) )
{
final String message =
"ChannelAction:: " + actionType.name() + " " +
channel + ( null == subChannelID ? "" : ( "-" + subChannelID ) ) +
" filter=" + filter;
LOG.log( getLogLevel(), message );
}
final G graph = channelToGraph( channel );
final ChannelDescriptor descriptor = new ChannelDescriptor( graph, subChannelID );
if ( ChannelAction.Action.ADD == actionType )
{
_currentAction.recordChannelSubscribe( new ChannelChangeStatus( descriptor, filter, 0 ) );
if ( null == subChannelID )
{
_subscriptionManager.subscribe( graph, filter );
}
else
{
_subscriptionManager.subscribe( graph, subChannelID, filter );
}
}
else if ( ChannelAction.Action.REMOVE == actionType )
{
final ChannelSubscriptionEntry entry;
if ( null == subChannelID )
{
entry = _subscriptionManager.unsubscribe( graph );
}
else
{
entry = _subscriptionManager.unsubscribe( graph, subChannelID );
}
final int removedEntities = deregisterUnOwnedEntities( entry );
_currentAction.recordChannelUnsubscribe( new ChannelChangeStatus( descriptor, filter, removedEntities ) );
}
else if ( ChannelAction.Action.UPDATE == actionType )
{
final ChannelSubscriptionEntry entry;
if ( null == subChannelID )
{
entry = _subscriptionManager.updateSubscription( graph, filter );
}
else
{
entry = _subscriptionManager.updateSubscription( graph, subChannelID, filter );
}
final int removedEntities = updateSubscriptionForFilteredEntities( entry, filter );
final ChannelChangeStatus status = new ChannelChangeStatus( descriptor, filter, removedEntities );
_currentAction.recordChannelSubscriptionUpdate( status );
}
else
{
throw new IllegalStateException();
}
}
return true;
}
//Step: Process a chunk of changes
if ( _currentAction.areChangesPending() )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Processing ChangeSet: " + _currentAction );
}
Change change;
for ( int i = 0; i < _changesToProcessPerTick && null != ( change = _currentAction.nextChange() ); i++ )
{
final Object entity = getChangeMapper().applyChange( change );
if ( LOG.isLoggable( Level.INFO ) )
{
if ( change.isUpdate() )
{
_currentAction.incUpdateCount();
}
else
{
_currentAction.incRemoveCount();
}
}
_currentAction.changeProcessed( change.isUpdate(), entity );
}
return true;
}
//Step: Calculate the entities that need to be linked
if ( !_currentAction.areEntityLinksCalculated() )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Calculating Link list: " + _currentAction );
}
_currentAction.calculateEntitiesToLink();
return true;
}
//Step: Process a chunk of links
if ( _currentAction.areEntityLinksPending() )
{
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Linking Entities: " + _currentAction );
}
Linkable linkable;
for ( int i = 0; i < _linksToProcessPerTick && null != ( linkable = _currentAction.nextEntityToLink() ); i++ )
{
linkable.link();
if ( LOG.isLoggable( Level.INFO ) )
{
_currentAction.incLinkCount();
}
}
return true;
}
final ChangeSet set = _currentAction.getChangeSet();
assert null != set;
//Step: Finalize the change set
if ( !_currentAction.hasWorldBeenNotified() )
{
_currentAction.markWorldAsNotified();
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Finalizing action: " + _currentAction );
}
// OOB messages are not sequenced
if ( !_currentAction.isOob() )
{
getSession().setLastRxSequence( set.getSequence() );
}
if ( _currentAction.isBulkLoad() )
{
if ( _currentAction.hasBrokerBeenPaused() )
{
getChangeBroker().enable( getSystemKey() );
}
}
else
{
if ( _currentAction.hasBrokerBeenPaused() )
{
getChangeBroker().resume( getSystemKey() );
}
}
if ( shouldValidateOnLoad() )
{
validateRepository();
}
if ( repositoryDebugOutputEnabled() )
{
outputRepositoryDebug();
}
if ( subscriptionsDebugOutputEnabled() )
{
outputSubscriptionDebug();
}
return true;
}
final DataLoadStatus status = _currentAction.toStatus( getSystemKey() );
if ( LOG.isLoggable( Level.INFO ) )
{
LOG.info( status.getSystemKey() + ": ChangeSet " + set.getSequence() + " involved " +
status.getChannelAdds().size() + " subscribes, " +
status.getChannelUpdates().size() + " subscription updates, " +
status.getChannelRemoves().size() + " un-subscribes, " +
status.getEntityUpdateCount() + " updates, " +
status.getEntityRemoveCount() + " removes and " +
status.getEntityLinkCount() + " links." );
for ( final ChannelChangeStatus changeStatus : status.getChannelUpdates() )
{
LOG.info( status.getSystemKey() + ": ChangeSet " + set.getSequence() + " subscription update " +
changeStatus.getDescriptor() + " caused " +
changeStatus.getEntityRemoveCount() + " entity removes." );
}
for ( final ChannelChangeStatus changeStatus : status.getChannelRemoves() )
{
LOG.info( status.getSystemKey() + ": ChangeSet " + set.getSequence() + " un-subscribe " +
changeStatus.getDescriptor() + " caused " +
changeStatus.getEntityRemoveCount() + " entity removes." );
}
}
//Step: Run the post actions
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(), "Running post action and cleaning action: " + _currentAction );
}
final RequestEntry request = _currentAction.getRequest();
if ( null != request )
{
request.markResultsAsArrived();
}
final Runnable runnable = _currentAction.getRunnable();
if ( null != runnable )
{
runnable.run();
// OOB messages are not in response to requests as such
final String requestID = _currentAction.isOob() ? null : _currentAction.getChangeSet().getRequestID();
if ( null != requestID )
{
// We can remove the request because this side ran second and the
// RPC channel has already returned.
final boolean removed = getSession().removeRequest( requestID );
if ( !removed )
{
LOG.severe( "ChangeSet " + set.getSequence() + " expected to complete request '" +
requestID + "' but no request was registered with session." );
}
if ( requestDebugOutputEnabled() )
{
outputRequestDebug();
}
}
}
onDataLoadComplete( status );
_currentAction = null;
if ( null != _resetAction )
{
_resetAction.run();
_resetAction = null;
}
return true;
}
private int deregisterUnOwnedEntities( @Nonnull final ChannelSubscriptionEntry entry )
{
int removedEntities = 0;
for ( final Entry<Class<?>, Map<Object, EntitySubscriptionEntry>> entitySet : entry.getEntities().entrySet() )
{
final Class<?> type = entitySet.getKey();
for ( Entry<Object, EntitySubscriptionEntry> entityEntry : entitySet.getValue().entrySet() )
{
final Object entityID = entityEntry.getKey();
final EntitySubscriptionEntry entitySubscription = entityEntry.getValue();
final ChannelSubscriptionEntry element = entitySubscription.deregisterGraph( entry.getDescriptor() );
if ( null != element && 0 == entitySubscription.getGraphSubscriptions().size() )
{
removedEntities += 1;
_repository.deregisterEntity( type, entityID );
}
}
}
return removedEntities;
}
@Nonnull
protected abstract String getSystemKey();
protected abstract int updateSubscriptionForFilteredEntities( @Nonnull ChannelSubscriptionEntry graphEntry,
@Nonnull Object filter );
protected final int updateSubscriptionForFilteredEntities( @Nonnull final ChannelSubscriptionEntry graphEntry,
@Nullable final Object filter,
@Nonnull final Collection<EntitySubscriptionEntry> entities )
{
int removedEntities = 0;
final ChannelDescriptor descriptor = graphEntry.getDescriptor();
final EntitySubscriptionEntry[] subscriptionEntries =
entities.toArray( new EntitySubscriptionEntry[ entities.size() ] );
for ( final EntitySubscriptionEntry entry : subscriptionEntries )
{
final Class<?> entityType = entry.getType();
final Object entityID = entry.getID();
if ( !doesEntityMatchFilter( descriptor, filter, entityType, entityID ) )
{
final EntitySubscriptionEntry entityEntry =
_subscriptionManager.removeEntityFromGraph( entityType, entityID, descriptor );
final boolean deregisterEntity = 0 == entityEntry.getGraphSubscriptions().size();
if ( LOG.isLoggable( getLogLevel() ) )
{
LOG.log( getLogLevel(),
"Removed entity " + entityType.getSimpleName() + "/" + entityID +
" from graph " + descriptor + " resulting in " +
entityEntry.getGraphSubscriptions().size() + " subscriptions left for entity." +
( deregisterEntity ? " De-registering entity!" : "" ) );
}
// If there is only one subscriber then lets delete it
if ( deregisterEntity )
{
_subscriptionManager.removeEntity( entityType, entityID );
_repository.deregisterEntity( entityType, entityID );
removedEntities += 1;
}
}
}
return removedEntities;
}
protected abstract boolean doesEntityMatchFilter( @Nonnull ChannelDescriptor descriptor,
@Nullable Object filter,
@Nonnull Class<?> entityType,
@Nonnull Object entityID );
@Nonnull
protected abstract G channelToGraph( int channel )
throws IllegalArgumentException;
/**
* Template method invoked when progressDataLoad() is about to return false and terminate load process.
*/
protected void onTerminatingIncrementalDataLoadProcess()
{
}
/**
* Invoked when a change set has been completely processed.
*
* @param status the status describing the results of data load.
*/
protected void onDataLoadComplete( @Nonnull final DataLoadStatus status )
{
fireDataLoadCompleteEvent( status );
}
/**
* Invoked to fire an event when data load has completed.
*/
protected void fireDataLoadCompleteEvent( @Nonnull final DataLoadStatus status )
{
getEventBus().fireEvent( new DataLoadCompleteEvent( status ) );
}
/**
* Return the event bus associated with the service.
*/
@Nonnull
protected final EventBus getEventBus()
{
return _eventBus;
}
protected Level getLogLevel()
{
return Level.FINEST;
}
protected final EntityRepository getRepository()
{
return _repository;
}
/**
* @return true if a load action should result in the EntityRepository being validated.
*/
protected boolean shouldValidateOnLoad()
{
return false;
}
/**
* Perform a validation of the EntityRepository.
*/
protected void validateRepository()
{
getEntityRepositoryValidator().validate( getRepository() );
}
protected EntityRepositoryValidator getEntityRepositoryValidator()
{
return new EntityRepositoryValidator();
}
protected boolean requestDebugOutputEnabled()
{
return false;
}
protected boolean subscriptionsDebugOutputEnabled()
{
return false;
}
protected boolean repositoryDebugOutputEnabled()
{
return false;
}
protected void outputRepositoryDebug()
{
getEntityRepositoryDebugger().outputRepository( getRepository() );
}
protected EntityRepositoryDebugger getEntityRepositoryDebugger()
{
return new EntityRepositoryDebugger();
}
protected void outputSubscriptionDebug()
{
getSubscriptionDebugger().outputSubscriptionManager( getSubscriptionManager() );
}
protected EntitySubscriptionDebugger getSubscriptionDebugger()
{
return new EntitySubscriptionDebugger();
}
protected void outputRequestDebug()
{
getRequestDebugger().outputRequests( getSessionContext().getKey() + ":", getSession() );
}
protected RequestDebugger getRequestDebugger()
{
return new RequestDebugger();
}
}
|
package org.spongepowered.common.mixin.core.network;
import com.flowpowered.math.vector.Vector3d;
import io.netty.util.collection.LongObjectHashMap;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.item.EntityXPOrb;
import net.minecraft.entity.passive.AbstractChestHorse;
import net.minecraft.entity.passive.EntityPig;
import net.minecraft.entity.passive.EntitySheep;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketThreadUtil;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.play.INetHandlerPlayServer;
import net.minecraft.network.play.client.CPacketAnimation;
import net.minecraft.network.play.client.CPacketClickWindow;
import net.minecraft.network.play.client.CPacketCreativeInventoryAction;
import net.minecraft.network.play.client.CPacketKeepAlive;
import net.minecraft.network.play.client.CPacketPlayer;
import net.minecraft.network.play.client.CPacketPlayerDigging;
import net.minecraft.network.play.client.CPacketPlayerTryUseItem;
import net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock;
import net.minecraft.network.play.client.CPacketResourcePackStatus;
import net.minecraft.network.play.client.CPacketUpdateSign;
import net.minecraft.network.play.client.CPacketUseEntity;
import net.minecraft.network.play.client.CPacketVehicleMove;
import net.minecraft.network.play.server.SPacketEntityAttach;
import net.minecraft.network.play.server.SPacketKeepAlive;
import net.minecraft.network.play.server.SPacketMoveVehicle;
import net.minecraft.network.play.server.SPacketPlayerListItem;
import net.minecraft.network.play.server.SPacketResourcePackSend;
import net.minecraft.network.play.server.SPacketSetExperience;
import net.minecraft.network.play.server.SPacketSetSlot;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.management.PlayerInteractionManager;
import net.minecraft.server.management.PlayerList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntitySign;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.IntHashMap;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.WorldServer;
import org.apache.logging.log4j.Logger;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.block.tileentity.Sign;
import org.spongepowered.api.data.manipulator.mutable.tileentity.SignData;
import org.spongepowered.api.data.type.HandType;
import org.spongepowered.api.data.type.HandTypes;
import org.spongepowered.api.data.value.mutable.ListValue;
import org.spongepowered.api.entity.Transform;
import org.spongepowered.api.entity.living.Humanoid;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.CauseStackManager;
import org.spongepowered.api.event.CauseStackManager.StackFrame;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.block.tileentity.ChangeSignEvent;
import org.spongepowered.api.event.cause.EventContextKeys;
import org.spongepowered.api.event.entity.MoveEntityEvent;
import org.spongepowered.api.event.entity.living.humanoid.AnimateHandEvent;
import org.spongepowered.api.event.item.inventory.ClickInventoryEvent;
import org.spongepowered.api.event.message.MessageEvent;
import org.spongepowered.api.event.network.ClientConnectionEvent;
import org.spongepowered.api.network.PlayerConnection;
import org.spongepowered.api.resourcepack.ResourcePack;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.channel.MessageChannel;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.LocalCapture;
import org.spongepowered.common.SpongeImpl;
import org.spongepowered.common.SpongeImplHooks;
import org.spongepowered.common.entity.player.tab.SpongeTabList;
import org.spongepowered.common.event.ShouldFire;
import org.spongepowered.common.event.SpongeCommonEventFactory;
import org.spongepowered.common.event.tracking.PhaseData;
import org.spongepowered.common.event.tracking.PhaseTracker;
import org.spongepowered.common.event.tracking.phase.packet.PacketContext;
import org.spongepowered.common.event.tracking.phase.packet.PacketPhaseUtil;
import org.spongepowered.common.event.tracking.phase.tick.PlayerTickContext;
import org.spongepowered.common.event.tracking.phase.tick.TickPhase;
import org.spongepowered.common.interfaces.IMixinContainer;
import org.spongepowered.common.interfaces.IMixinNetworkManager;
import org.spongepowered.common.interfaces.IMixinPacketResourcePackSend;
import org.spongepowered.common.interfaces.entity.player.IMixinEntityPlayer;
import org.spongepowered.common.interfaces.entity.player.IMixinEntityPlayerMP;
import org.spongepowered.common.interfaces.entity.player.IMixinInventoryPlayer;
import org.spongepowered.common.interfaces.inventory.IMixinContainerPlayer;
import org.spongepowered.common.interfaces.network.IMixinNetHandlerPlayServer;
import org.spongepowered.common.item.inventory.util.ItemStackUtil;
import org.spongepowered.common.text.SpongeTexts;
import org.spongepowered.common.util.VecHelper;
import java.lang.ref.WeakReference;
import java.net.InetSocketAddress;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
@Mixin(NetHandlerPlayServer.class)
public abstract class MixinNetHandlerPlayServer implements PlayerConnection, IMixinNetHandlerPlayServer {
private static final String UPDATE_SIGN = "Lnet/minecraft/network/play/client/CPacketUpdateSign;getLines()[Ljava/lang/String;";
@Shadow @Final private static Logger LOGGER;
@Shadow @Final public NetworkManager netManager;
@Shadow @Final private MinecraftServer server;
@Shadow @Final private IntHashMap<Short> pendingTransactions;
@Shadow public EntityPlayerMP player;
@Shadow private Entity lowestRiddenEnt;
@Shadow private int itemDropThreshold;
@Shadow private double firstGoodX;
@Shadow private double firstGoodY;
@Shadow private double firstGoodZ;
@Shadow private double lastGoodX;
@Shadow private double lastGoodY;
@Shadow private double lastGoodZ;
@Shadow private int lastPositionUpdate;
@Shadow private Vec3d targetPos;
@Shadow private int networkTickCount;
@Shadow private int movePacketCounter;
@Shadow private int lastMovePacketCounter;
@Shadow private boolean floating;
@Shadow public abstract void sendPacket(final Packet<?> packetIn);
@Shadow public abstract void disconnect(ITextComponent reason);
@Shadow private void captureCurrentPosition() {}
@Shadow public abstract void setPlayerLocation(double x, double y, double z, float yaw, float pitch);
@Shadow private static boolean isMovePlayerPacketInvalid(CPacketPlayer packetIn) { return false; } // Shadowed
@Shadow protected abstract long currentTimeMillis();
// Appears to be the last keep-alive packet ID. Currently the same as
// field_194402_f, but _f is time (which the ID just so happens to match).
@Shadow private long field_194404_h;
private boolean justTeleported = false;
@Nullable private Location<World> lastMoveLocation = null;
private final AtomicInteger numResourcePacksInTransit = new AtomicInteger();
@Nullable private ResourcePack lastReceivedPack, lastAcceptedPack;
private final LongObjectHashMap<Runnable> customKeepAliveCallbacks = new LongObjectHashMap<>();
// Store the last block right-clicked
@Nullable private Item lastItem;
@Override
public void captureCurrentPlayerPosition() {
this.captureCurrentPosition();
}
@Override
public Player getPlayer() {
return (Player) this.player;
}
@Override
public InetSocketAddress getAddress() {
return ((IMixinNetworkManager) this.netManager).getAddress();
}
@Override
public InetSocketAddress getVirtualHost() {
return ((IMixinNetworkManager) this.netManager).getVirtualHost();
}
@Override
public int getLatency() {
return this.player.ping;
}
@Redirect(method = "update", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/EntityPlayerMP;onUpdateEntity()V"))
private void onPlayerTick(EntityPlayerMP player) {
if (player.world.isRemote) {
player.onUpdateEntity();
return;
}
try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame();
PlayerTickContext context = TickPhase.Tick.PLAYER.createPhaseContext().source(player)) {
context.buildAndSwitch();
frame.pushCause(player);
player.onUpdateEntity();
}
}
/**
* @param manager The player network connection
* @param packet The original packet to be sent
* @author kashike
*/
@Redirect(method = "sendPacket(Lnet/minecraft/network/Packet;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/NetworkManager;sendPacket(Lnet/minecraft/network/Packet;)V"))
public void onSendPacket(NetworkManager manager, Packet<?> packet) {
packet = this.rewritePacket(packet);
if (packet != null) {
manager.sendPacket(packet);
}
}
@Inject(method = "processKeepAlive", at = @At("HEAD"), cancellable = true)
private void checkSpongeKeepAlive(CPacketKeepAlive packetIn, CallbackInfo ci) {
Runnable callback = this.customKeepAliveCallbacks.get(packetIn.getKey());
if (callback != null) {
PacketThreadUtil.checkThreadAndEnqueue(packetIn, (INetHandlerPlayServer) this, this.player.getServerWorld());
this.customKeepAliveCallbacks.remove(packetIn.getKey());
callback.run();
ci.cancel();
}
}
/**
* This method wraps packets being sent to perform any additional actions,
* such as rewriting data in the packet.
*
* @param packetIn The original packet to be sent
* @return The rewritten packet if we performed any changes, the original
* packet if we did not perform any changes, or {@code null} to not
* send anything
* @author kashike
*/
@Nullable
private Packet<?> rewritePacket(final Packet<?> packetIn) {
// Update the tab list data
if (packetIn instanceof SPacketPlayerListItem) {
((SpongeTabList) ((Player) this.player).getTabList()).updateEntriesOnSend((SPacketPlayerListItem) packetIn);
} else if (packetIn instanceof SPacketResourcePackSend) {
// Send a custom keep-alive packet that doesn't match vanilla.
long now = this.currentTimeMillis() - 1;
while (now == this.field_194404_h || this.customKeepAliveCallbacks.containsKey(now)) {
now
}
final ResourcePack resourcePack = ((IMixinPacketResourcePackSend) packetIn).getResourcePack();
this.numResourcePacksInTransit.incrementAndGet();
this.customKeepAliveCallbacks.put(now, () -> {
this.lastReceivedPack = resourcePack; // TODO do something with the old value
this.numResourcePacksInTransit.decrementAndGet();
});
this.netManager.sendPacket(new SPacketKeepAlive(now));
} else if (packetIn instanceof SPacketSetExperience) {
// Ensures experience is in sync server-side.
((IMixinEntityPlayer) player).recalculateTotalExperience();
}
return packetIn;
}
/**
* @author Zidane
*
* Invoke before {@code System.arraycopy(packetIn.getLines(), 0, tileentitysign.signText, 0, 4);} (line 1156 in source) to call SignChangeEvent.
* @param packetIn Injected packet param
* @param ci Info to provide mixin on how to handle the callback
* @param worldserver Injected world param
* @param blockpos Injected blockpos param
* @param tileentity Injected tilentity param
* @param tileentitysign Injected tileentitysign param
*/
@Inject(method = "processUpdateSign", at = @At(value = "INVOKE", target = UPDATE_SIGN), cancellable = true, locals = LocalCapture.CAPTURE_FAILHARD)
public void callSignChangeEvent(CPacketUpdateSign packetIn, CallbackInfo ci, WorldServer worldserver, BlockPos blockpos, IBlockState iblockstate, TileEntity tileentity, TileEntitySign tileentitysign) {
ci.cancel();
final Optional<SignData> existingSignData = ((Sign) tileentitysign).get(SignData.class);
if (!existingSignData.isPresent()) {
// TODO Unsure if this is the best to do here...
throw new RuntimeException("Critical error! Sign data not present on sign!");
}
final SignData changedSignData = existingSignData.get().copy();
final ListValue<Text> lines = changedSignData.lines();
for (int i = 0; i < packetIn.getLines().length; i++) {
lines.set(i, SpongeTexts.toText(new TextComponentString(packetIn.getLines()[i])));
}
changedSignData.set(lines);
// I pass changedSignData in here twice to emulate the fact that even-though the current sign data doesn't have the lines from the packet
// applied, this is what it "is" right now. If the data shown in the world is desired, it can be fetched from Sign.getData
Sponge.getCauseStackManager().pushCause(this.player);
final ChangeSignEvent event =
SpongeEventFactory.createChangeSignEvent(Sponge.getCauseStackManager().getCurrentCause(),
changedSignData.asImmutable(), changedSignData, (Sign) tileentitysign);
if (!SpongeImpl.postEvent(event)) {
((Sign) tileentitysign).offer(event.getText());
} else {
// If cancelled, I set the data back that was fetched from the sign. This means that if its a new sign, the sign will be empty else
// it will be the text of the sign that was showing in the world
((Sign) tileentitysign).offer(existingSignData.get());
}
Sponge.getCauseStackManager().popCause();
tileentitysign.markDirty();
worldserver.getPlayerChunkMap().markBlockForUpdate(blockpos);
}
/**
* @author blood - June 6th, 2016
* @author gabizou - June 20th, 2016 - Update for 1.9.4 and minor refactors.
* @reason Since mojang handles creative packets different than survival, we need to
* restructure this method to prevent any packets being sent to client as we will
* not be able to properly revert them during drops.
*
* @param packetIn The creative inventory packet
*/
@Overwrite
public void processCreativeInventoryAction(CPacketCreativeInventoryAction packetIn) {
PacketThreadUtil.checkThreadAndEnqueue(packetIn, (NetHandlerPlayServer) (Object) this, this.player.getServerWorld());
if (this.player.interactionManager.isCreative()) {
final PhaseData peek = PhaseTracker.getInstance().getCurrentPhaseData();
final PacketContext<?> context = (PacketContext<?>) peek.context;
final boolean ignoresCreative = context.getIgnoringCreative();
boolean clickedOutside = packetIn.getSlotId() < 0;
ItemStack itemstack = packetIn.getStack();
if (!itemstack.isEmpty() && itemstack.hasTagCompound() && itemstack.getTagCompound().hasKey("BlockEntityTag", 10)) {
NBTTagCompound nbttagcompound = itemstack.getTagCompound().getCompoundTag("BlockEntityTag");
if (nbttagcompound.hasKey("x") && nbttagcompound.hasKey("y") && nbttagcompound.hasKey("z")) {
BlockPos blockpos = new BlockPos(nbttagcompound.getInteger("x"), nbttagcompound.getInteger("y"), nbttagcompound.getInteger("z"));
TileEntity tileentity = this.player.world.getTileEntity(blockpos);
if (tileentity != null) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
tileentity.writeToNBT(nbttagcompound1);
nbttagcompound1.removeTag("x");
nbttagcompound1.removeTag("y");
nbttagcompound1.removeTag("z");
itemstack.setTagInfo("BlockEntityTag", nbttagcompound1);
}
}
}
boolean clickedInsideNotOutput = packetIn.getSlotId() >= 1 && packetIn.getSlotId() <= 45;
boolean itemValidCheck = itemstack.isEmpty() || itemstack.getMetadata() >= 0 && itemstack.getCount() <= itemstack.getMaxStackSize() && !itemstack.isEmpty();
// Sponge start - handle CreativeInventoryEvent
if (itemValidCheck) {
if (!ignoresCreative) {
ClickInventoryEvent.Creative clickEvent = SpongeCommonEventFactory.callCreativeClickInventoryEvent(this.player, packetIn);
if (clickEvent.isCancelled()) {
// Reset slot on client
if (packetIn.getSlotId() >= 0 && packetIn.getSlotId() < this.player.inventoryContainer.inventorySlots.size()) {
this.player.connection.sendPacket(
new SPacketSetSlot(this.player.inventoryContainer.windowId, packetIn.getSlotId(),
this.player.inventoryContainer.getSlot(packetIn.getSlotId()).getStack()));
this.player.connection.sendPacket(new SPacketSetSlot(-1, -1, ItemStack.EMPTY));
}
return;
}
}
if (clickedInsideNotOutput) {
if (itemstack.isEmpty()) {
this.player.inventoryContainer.putStackInSlot(packetIn.getSlotId(), ItemStack.EMPTY);
} else {
this.player.inventoryContainer.putStackInSlot(packetIn.getSlotId(), itemstack);
}
this.player.inventoryContainer.setCanCraft(this.player, true);
} else if (clickedOutside && this.itemDropThreshold < 200) {
this.itemDropThreshold += 20;
EntityItem entityitem = this.player.dropItem(itemstack, true);
if (entityitem != null)
{
entityitem.setAgeToCreativeDespawnTime();
}
}
}
// Sponge end
}
}
@Inject(method = "processClickWindow", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/IntHashMap;addKey(ILjava/lang/Object;)V"))
public void onInvalidClick(CPacketClickWindow packet, CallbackInfo ci) {
// We want to treat an 'invalid' click just like a regular click - we still fire events, do restores, etc.
// Vanilla doesn't call detectAndSendChanges for 'invalid' clicks, since it restores the entire inventory
// Passing 'captureOnly' as 'true' allows capturing to happen for event firing, but doesn't send any pointless packets
((IMixinContainer) this.player.openContainer).detectAndSendChanges(true);
}
@Redirect(method = "processChatMessage", at = @At(value = "INVOKE", target = "Lorg/apache/commons/lang3/StringUtils;normalizeSpace(Ljava/lang/String;)Ljava/lang/String;", remap = false))
public String onNormalizeSpace(String input) {
return input;
}
@Inject(method = "setPlayerLocation(DDDFFLjava/util/Set;)V", at = @At(value = "RETURN"))
public void setPlayerLocation(double x, double y, double z, float yaw, float pitch, Set<?> relativeSet, CallbackInfo ci) {
this.justTeleported = true;
}
/**
* @author gabizou - June 22nd, 2016
* @reason Sponge has to throw the movement events before we consider moving the player and there's
* no clear way to go about it with the target position being null and the last position update checks.
* @param packetIn
*/
@Redirect(method = "processPlayer", at = @At(value = "FIELD", target = "Lnet/minecraft/entity/player/EntityPlayerMP;queuedEndExit:Z"))
private boolean throwMoveEvent(EntityPlayerMP playerMP, CPacketPlayer packetIn) {
if (!playerMP.queuedEndExit) {
// During login, minecraft sends a packet containing neither the 'moving' or 'rotating' flag set - but only once.
// We don't fire an event to avoid confusing plugins.
if (!packetIn.moving && !packetIn.rotating) {
return playerMP.queuedEndExit;
}
// Sponge Start - Movement event
Player player = (Player) this.player;
IMixinEntityPlayerMP mixinPlayer = (IMixinEntityPlayerMP) this.player;
Vector3d fromrot = player.getRotation();
// If Sponge used the player's current location, the delta might never be triggered which could be exploited
Location<World> from = player.getLocation();
if (this.lastMoveLocation != null) {
from = this.lastMoveLocation;
}
Vector3d torot = new Vector3d(packetIn.pitch, packetIn.yaw, 0);
Location<World> to = new Location<>(player.getWorld(), packetIn.x, packetIn.y, packetIn.z);
// Minecraft sends a 0, 0, 0 position when rotation only update occurs, this needs to be recognized and corrected
boolean rotationOnly = !packetIn.moving && packetIn.rotating;
if (rotationOnly) {
// Correct the to location so it's not misrepresented to plugins, only when player rotates without moving
// In this case it's only a rotation update, which isn't related to the to location
from = player.getLocation();
to = from;
}
// Minecraft does the same with rotation when it's only a positional update
boolean positionOnly = packetIn.moving && !packetIn.rotating;
if (positionOnly) {
// Correct the new rotation to match the old rotation
torot = fromrot;
}
((IMixinEntityPlayerMP) this.player).setVelocityOverride(to.getPosition().sub(from.getPosition()));
double deltaSquared = to.getPosition().distanceSquared(from.getPosition());
double deltaAngleSquared = fromrot.distanceSquared(torot);
// These magic numbers are sad but help prevent excessive lag from this event.
// eventually it would be nice to not have them
if (deltaSquared > ((1f / 16) * (1f / 16)) || deltaAngleSquared > (.15f * .15f)) {
Transform<World> fromTransform = player.getTransform().setLocation(from).setRotation(fromrot);
Transform<World> toTransform = player.getTransform().setLocation(to).setRotation(torot);
Transform<World> originalToTransform = toTransform;
if (ShouldFire.MOVE_ENTITY_EVENT) {
try (StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
Sponge.getCauseStackManager().pushCause(player);
MoveEntityEvent event = SpongeEventFactory.createMoveEntityEvent(Sponge.getCauseStackManager().getCurrentCause(), fromTransform, toTransform, player);
SpongeImpl.postEvent(event);
Sponge.getCauseStackManager().popCause();
if (event.isCancelled()) {
mixinPlayer.setLocationAndAngles(fromTransform);
this.lastMoveLocation = from;
((IMixinEntityPlayerMP) this.player).setVelocityOverride(null);
return true;
}
toTransform = event.getToTransform();
}
}
if (!toTransform.equals(originalToTransform)) {
mixinPlayer.setLocationAndAngles(toTransform);
this.lastMoveLocation = toTransform.getLocation();
((IMixinEntityPlayerMP) this.player).setVelocityOverride(null);
return true;
} else if (!from.equals(player.getLocation()) && this.justTeleported) {
this.lastMoveLocation = player.getLocation();
// Prevent teleports during the move event from causing odd behaviors
this.justTeleported = false;
((IMixinEntityPlayerMP) this.player).setVelocityOverride(null);
return true;
} else {
this.lastMoveLocation = toTransform.getLocation();
}
this.resendLatestResourcePackRequest();
}
}
return playerMP.queuedEndExit;
}
/**
* @author gabizou - June 22nd, 2016
* @author blood - May 6th, 2017
* @reason Redirects the {@link Entity#getLowestRidingEntity()} call to throw our
* {@link MoveEntityEvent}. The peculiarity of this redirect is that the entity
* returned is perfectly valid to be {@link this#player} since, if the player
* is NOT riding anything, the lowest riding entity is themselves. This way, if
* the event is cancelled, the player can be returned instead of the actual riding
* entity.
*
* @param playerMP The player
* @param packetIn The packet movement
* @return The lowest riding entity
*/
@Redirect(method = "processVehicleMove", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/EntityPlayerMP;getLowestRidingEntity()Lnet/minecraft/entity/Entity;"))
private Entity processVehicleMoveEvent(EntityPlayerMP playerMP, CPacketVehicleMove packetIn) {
final Entity ridingEntity = this.player.getLowestRidingEntity();
if (ridingEntity == this.player || ridingEntity.getControllingPassenger() != this.player || ridingEntity != this.lowestRiddenEnt) {
return ridingEntity;
}
// Sponge Start - Movement event
org.spongepowered.api.entity.Entity spongeEntity = (org.spongepowered.api.entity.Entity) ridingEntity;
Vector3d fromrot = spongeEntity.getRotation();
Location<World> from = spongeEntity.getLocation();
Vector3d torot = new Vector3d(packetIn.getPitch(), packetIn.getYaw(), 0);
Location<World> to = new Location<>(spongeEntity.getWorld(), packetIn.getX(), packetIn.getY(), packetIn.getZ());
Transform<World> fromTransform = spongeEntity.getTransform().setLocation(from).setRotation(fromrot);
Transform<World> toTransform = spongeEntity.getTransform().setLocation(to).setRotation(torot);
MoveEntityEvent event = SpongeEventFactory.createMoveEntityEvent(Sponge.getCauseStackManager().getCurrentCause(), fromTransform, toTransform, this.getPlayer());
SpongeImpl.postEvent(event);
if (event.isCancelled()) {
// There is no need to change the current riding entity position as it hasn't changed yet.
// Send packet to client in order to update rider position.
this.netManager.sendPacket(new SPacketMoveVehicle(ridingEntity));
return this.player;
}
return ridingEntity;
}
@Redirect(method = "onDisconnect", at = @At(value = "INVOKE",
target = "Lnet/minecraft/server/management/PlayerList;sendMessage(Lnet/minecraft/util/text/ITextComponent;)V"))
public void onDisconnectHandler(PlayerList this$0, ITextComponent component) {
// If this happens, the connection has not been fully established yet so we've kicked them during ClientConnectionEvent.Login,
// but FML has created this handler earlier to send their handshake. No message should be sent, no disconnection event should
// be fired either.
if (this.player.connection == null) {
return;
}
final Player player = ((Player) this.player);
final Text message = SpongeTexts.toText(component);
final MessageChannel originalChannel = player.getMessageChannel();
Sponge.getCauseStackManager().pushCause(player);
final ClientConnectionEvent.Disconnect event = SpongeEventFactory.createClientConnectionEventDisconnect(
Sponge.getCauseStackManager().getCurrentCause(), originalChannel, Optional.of(originalChannel), new MessageEvent.MessageFormatter(message),
player, false
);
SpongeImpl.postEvent(event);
Sponge.getCauseStackManager().popCause();
if (!event.isMessageCancelled()) {
event.getChannel().ifPresent(channel -> channel.send(player, event.getMessage()));
}
((IMixinEntityPlayerMP) this.player).getWorldBorderListener().onPlayerDisconnect();
}
@Redirect(method = "processTryUseItemOnBlock", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/management/PlayerInteractionManager;processRightClickBlock(Lnet/minecraft/entity/player/EntityPlayer;Lnet/minecraft/world/World;Lnet/minecraft/item/ItemStack;Lnet/minecraft/util/EnumHand;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/EnumFacing;FFF)Lnet/minecraft/util/EnumActionResult;"))
public EnumActionResult onProcessRightClickBlock(PlayerInteractionManager interactionManager, EntityPlayer player, net.minecraft.world.World worldIn, @Nullable ItemStack stack, EnumHand hand, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ) {
EnumActionResult actionResult = interactionManager.processRightClickBlock(this.player, worldIn, stack, hand, pos, facing, hitX, hitY, hitZ);
final PhaseData peek = PhaseTracker.getInstance().getCurrentPhaseData();
// If a plugin or mod has changed the item, avoid restoring
if (!((PacketContext<?>) peek.context).getInteractItemChanged()) {
final ItemStack itemStack = ItemStackUtil.toNative(((PacketContext<?>) peek.context).getItemUsed());
// Only do a restore if something actually changed. The client does an identity check ('==')
// to determine if it should continue using an itemstack. If we always resend the itemstack, we end up
// cancelling item usage (e.g. eating food) that occurs while targeting a block
if (!ItemStack.areItemStacksEqual(itemStack, player.getHeldItem(hand)) && SpongeCommonEventFactory.interactBlockRightClickEventCancelled) {
PacketPhaseUtil.handlePlayerSlotRestore((EntityPlayerMP) player, itemStack, hand);
}
}
((PacketContext<?>) peek.context).interactItemChanged(false);
SpongeCommonEventFactory.interactBlockRightClickEventCancelled = false;
return actionResult;
}
@Redirect(method = "processTryUseItem", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/management/PlayerInteractionManager;processRightClick(Lnet/minecraft/entity/player/EntityPlayer;Lnet/minecraft/world/World;Lnet/minecraft/item/ItemStack;Lnet/minecraft/util/EnumHand;)Lnet/minecraft/util/EnumActionResult;"))
public EnumActionResult onProcessRightClick(PlayerInteractionManager interactionManager, EntityPlayer player, net.minecraft.world.World worldIn, @Nullable ItemStack stack, EnumHand hand) {
EnumActionResult actionResult = interactionManager.processRightClick(this.player, worldIn, stack, hand);
final PhaseData peek = PhaseTracker.getInstance().getCurrentPhaseData();
// If a plugin or mod has changed the item, avoid restoring
if (!((PacketContext<?>) peek.context).getInteractItemChanged()) {
final ItemStack itemStack = ItemStackUtil.toNative(((PacketContext<?>) peek.context).getItemUsed());
// Only do a restore if something actually changed. The client does an identity check ('==')
// to determine if it should continue using an itemstack. If we always resend the itemstack, we end up
// cancelling item usage (e.g. eating food) that occurs while targeting a block
if (!ItemStack.areItemStacksEqual(itemStack, player.getHeldItem(hand)) && SpongeCommonEventFactory.interactBlockRightClickEventCancelled) {
PacketPhaseUtil.handlePlayerSlotRestore((EntityPlayerMP) player, itemStack, hand);
}
}
((PacketContext<?>) peek.context).interactItemChanged(false);
SpongeCommonEventFactory.interactBlockRightClickEventCancelled = false;
return actionResult;
}
@Nullable
@Redirect(method = "processPlayerDigging", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/EntityPlayerMP;dropItem(Z)Lnet/minecraft/entity/item/EntityItem;"))
public EntityItem onPlayerDropItem(EntityPlayerMP player, boolean dropAll) {
EntityItem item = null;
ItemStack stack = this.player.inventory.getCurrentItem();
if (!stack.isEmpty()) {
int size = stack.getCount();
item = this.player.dropItem(dropAll);
// force client itemstack update if drop event was cancelled
if (item == null && ((IMixinEntityPlayer) player).shouldRestoreInventory()) {
Slot slot = this.player.openContainer.getSlotFromInventory(this.player.inventory, this.player.inventory.currentItem);
int windowId = this.player.openContainer.windowId;
stack.setCount(size);
this.sendPacket(new SPacketSetSlot(windowId, slot.slotNumber, stack));
}
}
return item;
}
/**
* Attempts to find the {@link DataParameter} that was potentially modified
* when a player interacts with an entity.
*
* @param stack The item the player is holding
* @param entity The entity
* @return A possible data parameter or null if unknown
*/
@Nullable
private static DataParameter<?> findModifiedEntityInteractDataParameter(ItemStack stack, Entity entity) {
Item item = stack.getItem();
if (item == Items.DYE) {
// ItemDye.itemInteractionForEntity
if (entity instanceof EntitySheep) {
return EntitySheep.DYE_COLOR;
}
// EntityWolf.processInteract
if (entity instanceof EntityWolf) {
return EntityWolf.COLLAR_COLOR;
}
return null;
}
if (item == Items.NAME_TAG) {
// ItemNameTag.itemInteractionForEntity
return entity instanceof EntityLivingBase && !(entity instanceof EntityPlayer) && stack.hasDisplayName() ? Entity.CUSTOM_NAME : null;
}
if (item == Items.SADDLE) {
// ItemSaddle.itemInteractionForEntity
return entity instanceof EntityPig ? EntityPig.SADDLED : null;
}
if (item instanceof ItemBlock && ((ItemBlock) item).getBlock() == Blocks.CHEST) {
// AbstractChestHorse.processInteract
return entity instanceof AbstractChestHorse ? AbstractChestHorse.DATA_ID_CHEST : null;
}
return null;
}
@Inject(method = "handleAnimation", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/EntityPlayerMP;markPlayerActive()V"), cancellable = true)
public void onHandleAnimation(CPacketAnimation packetIn, CallbackInfo ci)
{
SpongeCommonEventFactory.lastAnimationPacketTick = SpongeImpl.getServer().getTickCounter();
SpongeCommonEventFactory.lastAnimationPlayer = new WeakReference<>(this.player);
if (ShouldFire.ANIMATE_HAND_EVENT) {
HandType handType = packetIn.getHand() == EnumHand.MAIN_HAND ? HandTypes.MAIN_HAND : HandTypes.OFF_HAND;
final ItemStack heldItem = this.player.getHeldItem(packetIn.getHand());
Sponge.getCauseStackManager().addContext(EventContextKeys.USED_ITEM, ItemStackUtil.snapshotOf(heldItem));
AnimateHandEvent event =
SpongeEventFactory.createAnimateHandEvent(Sponge.getCauseStackManager().getCurrentCause(), handType, (Humanoid) this.player);
if (SpongeImpl.postEvent(event)) {
ci.cancel();
}
}
}
@Inject(method = "processPlayerDigging", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;getWorld(I)Lnet/minecraft/world/WorldServer;"))
public void onProcessPlayerDigging(CPacketPlayerDigging packetIn, CallbackInfo ci) {
SpongeCommonEventFactory.lastPrimaryPacketTick = SpongeImpl.getServer().getTickCounter();
}
@Inject(method = "processPlayerDigging", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/player/EntityPlayerMP;dropItem(Z)Lnet/minecraft/entity/item/EntityItem;"))
public void onProcessPlayerDiggingDropItem(CPacketPlayerDigging packetIn, CallbackInfo ci) {
final ItemStack stack = this.player.getHeldItemMainhand();
if (!stack.isEmpty()) {
((IMixinEntityPlayerMP) this.player).setPacketItem(stack.copy());
}
}
@Inject(method = "processTryUseItem", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;getWorld(I)Lnet/minecraft/world/WorldServer;"), cancellable = true)
public void onProcessTryUseItem(CPacketPlayerTryUseItem packetIn, CallbackInfo ci) {
SpongeCommonEventFactory.lastSecondaryPacketTick = SpongeImpl.getServer().getTickCounter();
long packetDiff = System.currentTimeMillis() - SpongeCommonEventFactory.lastTryBlockPacketTimeStamp;
// If the time between packets is small enough, use the last result.
if (packetDiff < 100) {
// Use previous result and avoid firing a second event
if (SpongeCommonEventFactory.lastInteractItemOnBlockCancelled) {
ci.cancel();
}
}
}
@Inject(method = "processTryUseItemOnBlock", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;getWorld(I)Lnet/minecraft/world/WorldServer;"))
public void onProcessTryUseItemOnBlock(CPacketPlayerTryUseItemOnBlock packetIn, CallbackInfo ci) {
// InteractItemEvent on block must be handled in PlayerInteractionManager to support item/block results.
// Only track the timestamps to support our block animation events
SpongeCommonEventFactory.lastTryBlockPacketTimeStamp = System.currentTimeMillis();
SpongeCommonEventFactory.lastSecondaryPacketTick = SpongeImpl.getServer().getTickCounter();
}
/**
* @author blood - April 5th, 2016
*
* @reason Due to all the changes we now do for this packet, it is much easier
* to read it all with an overwrite. Information detailing on why each change
* was made can be found in comments below.
*
* @param packetIn The entity use packet
*/
@Overwrite
public void processUseEntity(CPacketUseEntity packetIn) {
// Sponge start
// All packets received by server are handled first on the Netty Thread
if (!SpongeImpl.getServer().isCallingFromMinecraftThread()) {
if (packetIn.getAction() == CPacketUseEntity.Action.INTERACT) {
// This packet is only sent by client when CPacketUseEntity.Action.INTERACT_AT is
// not successful. We can safely ignore this packet as we handle the INTERACT logic
// when INTERACT_AT does not return a successful result.
return;
} else { // queue packet for main thread
PacketThreadUtil.checkThreadAndEnqueue(packetIn, (NetHandlerPlayServer) (Object) this, this.player.getServerWorld());
return;
}
}
// Sponge end
WorldServer worldserver = this.server.getWorld(this.player.dimension);
Entity entity = packetIn.getEntityFromWorld(worldserver);
this.player.markPlayerActive();
if (entity != null) {
boolean flag = this.player.canEntityBeSeen(entity);
double d0 = 36.0D; // 6 blocks
if (!flag) {
d0 = 9.0D; // 1.5 blocks
}
if (this.player.getDistanceSq(entity) < d0) {
// Sponge start - Ignore CPacketUseEntity.Action.INTERACT
/*if (packetIn.getAction() == CPacketUseEntity.Action.INTERACT) {
// The client will only send this packet if INTERACT_AT is not successful.
// We can safely ignore this as we handle interactOn below during INTERACT_AT.
//EnumHand enumhand = packetIn.getHand();
//this.player.interactOn(entity, enumhand);
} else */
// Sponge end
if (packetIn.getAction() == CPacketUseEntity.Action.INTERACT_AT) {
// Sponge start - Fire interact events
try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) {
EnumHand hand = packetIn.getHand();
ItemStack itemstack = hand != null ? this.player.getHeldItem(hand) : ItemStack.EMPTY;
SpongeCommonEventFactory.lastSecondaryPacketTick = this.server.getTickCounter();
// Is interaction allowed with item in hand
if (SpongeCommonEventFactory.callInteractItemEventSecondary(this.player, itemstack, hand, VecHelper.toVector3d(packetIn
.getHitVec()), entity).isCancelled() || SpongeCommonEventFactory.callInteractEntityEventSecondary(this.player,
entity, hand, VecHelper.toVector3d(entity.getPositionVector().add(packetIn.getHitVec()))).isCancelled()) {
// Restore held item in hand
int index = ((IMixinInventoryPlayer) this.player.inventory).getHeldItemIndex(hand);
if (hand == EnumHand.OFF_HAND) {
// A window id of -2 can be used to set the off hand, even if a container is open.
sendPacket(new SPacketSetSlot(-2, ((IMixinContainerPlayer) this.player.inventoryContainer).getOffHandSlot(), itemstack));
} else {
Slot slot = this.player.openContainer.getSlotFromInventory(this.player.inventory, index);
sendPacket(new SPacketSetSlot(this.player.openContainer.windowId, slot.slotNumber, itemstack));
}
// Handle a few special cases where the client assumes that the interaction is successful,
// which means that we need to force an update
if (itemstack.getItem() == Items.LEAD) {
// Detach entity again
sendPacket(new SPacketEntityAttach(entity, null));
} else {
// Other cases may involve a specific DataParameter of the entity
// We fix the client state by marking it as dirty so it will be updated on the client the next tick
DataParameter<?> parameter = findModifiedEntityInteractDataParameter(itemstack, entity);
if (parameter != null) {
entity.getDataManager().setDirty(parameter);
}
}
return;
}
// If INTERACT_AT is not successful, run the INTERACT logic
if (entity.applyPlayerInteraction(this.player, packetIn.getHitVec(), hand) != EnumActionResult.SUCCESS) {
this.player.interactOn(entity, hand);
}
}
// Sponge end
} else if (packetIn.getAction() == CPacketUseEntity.Action.ATTACK) {
// Sponge start - Call interact event
EnumHand hand = EnumHand.MAIN_HAND; // Will be null in the packet during ATTACK
ItemStack itemstack = this.player.getHeldItem(hand);
SpongeCommonEventFactory.lastPrimaryPacketTick = this.server.getTickCounter();
Vector3d hitVec = null;
if (packetIn.getHitVec() == null) {
final RayTraceResult result = SpongeImplHooks.rayTraceEyes(player, SpongeImplHooks.getBlockReachDistance(player));
hitVec = result == null ? null : VecHelper.toVector3d(result.hitVec);
}
if (SpongeCommonEventFactory.callInteractItemEventPrimary(this.player, itemstack, hand, hitVec, entity).isCancelled()) {
((IMixinEntityPlayerMP) this.player).restorePacketItem(hand);
return;
}
// Sponge end
if (entity instanceof EntityItem || entity instanceof EntityXPOrb || entity instanceof EntityArrow || entity == this.player) {
this.disconnect(new TextComponentTranslation("multiplayer.disconnect.invalid_entity_attacked"));
this.server.logWarning("Player " + this.player.getName() + " tried to attack an invalid entity");
return;
}
// Sponge start
if (SpongeCommonEventFactory.callInteractEntityEventPrimary(this.player, entity, hand, hitVec).isCancelled()) {
((IMixinEntityPlayerMP) this.player).restorePacketItem(hand);
return;
}
// Sponge end
this.player.attackTargetEntityWithCurrentItem(entity);
}
}
}
}
@Override
public void setLastMoveLocation(Location<World> location) {
this.lastMoveLocation = location;
}
@Inject(method = "handleResourcePackStatus(Lnet/minecraft/network/play/client/CPacketResourcePackStatus;)V", at = @At("HEAD"))
private void onProcessResourcePackStatus(CPacketResourcePackStatus packet, CallbackInfo ci) {
// Propagate the packet to the main thread so the cause tracker picks
// it up. See MixinPacketThreadUtil.
PacketThreadUtil.checkThreadAndEnqueue(packet, (INetHandlerPlayServer) this, this.player.getServerWorld());
}
@Override
public void resendLatestResourcePackRequest() {
ResourcePack pack = this.lastReceivedPack;
if (this.numResourcePacksInTransit.get() > 0 || pack == null) {
return;
}
this.lastReceivedPack = null;
((Player) this.player).sendResourcePack(pack);
}
@Override
public ResourcePack popReceivedResourcePack(boolean markAccepted) {
ResourcePack pack = this.lastReceivedPack;
this.lastReceivedPack = null;
if (markAccepted) {
this.lastAcceptedPack = pack; // TODO do something with the old value
}
return pack;
}
@Override
public ResourcePack popAcceptedResourcePack() {
ResourcePack pack = this.lastAcceptedPack;
this.lastAcceptedPack = null;
return pack;
}
}
|
package org.synyx.urlaubsverwaltung.absence.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.synyx.urlaubsverwaltung.application.domain.Application;
import org.synyx.urlaubsverwaltung.application.domain.ApplicationStatus;
import org.synyx.urlaubsverwaltung.application.service.ApplicationService;
import org.synyx.urlaubsverwaltung.department.Department;
import org.synyx.urlaubsverwaltung.department.DepartmentService;
import org.synyx.urlaubsverwaltung.period.Period;
import org.synyx.urlaubsverwaltung.person.Person;
import org.synyx.urlaubsverwaltung.person.PersonService;
import org.synyx.urlaubsverwaltung.sicknote.SickNote;
import org.synyx.urlaubsverwaltung.sicknote.SickNoteService;
import java.time.Clock;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Year;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static java.lang.Integer.parseInt;
import static java.time.DayOfWeek.SATURDAY;
import static java.time.DayOfWeek.SUNDAY;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static org.springframework.util.StringUtils.hasText;
import static org.synyx.urlaubsverwaltung.person.Role.BOSS;
import static org.synyx.urlaubsverwaltung.person.Role.OFFICE;
import static org.synyx.urlaubsverwaltung.security.SecurityRules.IS_PRIVILEGED_USER;
@RequestMapping("/web/absences")
@Controller
public class AbsenceOverviewViewController {
private final PersonService personService;
private final DepartmentService departmentService;
private final ApplicationService applicationService;
private final SickNoteService sickNoteService;
private final MessageSource messageSource;
private final Clock clock;
@Autowired
public AbsenceOverviewViewController(PersonService personService, DepartmentService departmentService,
ApplicationService applicationService, SickNoteService sickNoteService,
MessageSource messageSource, Clock clock) {
this.personService = personService;
this.departmentService = departmentService;
this.applicationService = applicationService;
this.sickNoteService = sickNoteService;
this.messageSource = messageSource;
this.clock = clock;
}
@PreAuthorize(IS_PRIVILEGED_USER)
@GetMapping
public String absenceOverview(
@RequestParam(required = false) Integer year,
@RequestParam(required = false) String month,
@RequestParam(required = false) String department,
Model model, Locale locale) {
final Person signedInUser = personService.getSignedInUser();
final List<Department> departments = departmentService.getAllowedDepartmentsOfPerson(signedInUser);
model.addAttribute("departments", departments);
final String fallbackDepartment = departments.isEmpty() ? "" : departments.get(0).getName();
final String selectedDepartmentName = hasText(department) ? department : fallbackDepartment;
model.addAttribute("selectedDepartment", selectedDepartmentName);
final LocalDate startDate = getStartDate(year, month);
final LocalDate endDate = getEndDate(year, month);
model.addAttribute("currentYear", Year.now(clock).getValue());
model.addAttribute("selectedYear", startDate.getYear());
final String selectedMonth = getSelectedMonth(month, startDate);
model.addAttribute("selectedMonth", selectedMonth);
final List<Person> overviewPersons = getOverviewPersonsForUser(signedInUser, departments, selectedDepartmentName);
final List<SickNote> sickNotes = sickNoteService.getAllActiveByYear(year == null ? Year.now(clock).getValue() : year);
final HashMap<String, List<Application>> vacationsByEmail = new HashMap<>();
for (Person person : overviewPersons) {
List<Application> apps = applicationService.getApplicationsForACertainPeriodAndPerson(startDate, endDate, person);
vacationsByEmail.put(person.getEmail(), apps);
}
HashMap<Integer, AbsenceOverviewMonthDto> monthsByNr = new HashMap<>();
new DateRange(startDate, endDate).iterator().forEachRemaining(date -> {
final AbsenceOverviewMonthDto monthView = monthsByNr.computeIfAbsent(date.getMonthValue(),
monthValue -> this.initializeAbsenceOverviewMonthDto(date, overviewPersons, locale));
final AbsenceOverviewMonthDayDto tableHeadDay = tableHeadDay(date);
monthView.getDays().add(tableHeadDay);
final Map<String, SickNote> sickNotesOnThisDayByEmail = sickNotesForDate(date, sickNotes,
sickNote -> sickNote.getPerson().getEmail());
// create an absence day dto for every person of the department
for (AbsenceOverviewMonthPersonDto personView : monthView.getPersons()) {
final SickNote sickNote = sickNotesOnThisDayByEmail.get(personView.getEmail());
final List<Application> applications = vacationsByEmail.get(personView.getEmail());
final AbsenceOverviewDayType personViewDayType = getAbsenceOverviewDayType(date, sickNote, applications);
personView
.getDays()
.add(new AbsenceOverviewPersonDayDto(personViewDayType, isWeekend(date)));
}
});
AbsenceOverviewDto absenceOverview = new AbsenceOverviewDto(new ArrayList<>(monthsByNr.values()));
model.addAttribute("absenceOverview", absenceOverview);
return "absences/absences_overview";
}
private AbsenceOverviewMonthDto initializeAbsenceOverviewMonthDto(LocalDate date, List<Person> personList, Locale locale) {
final List<AbsenceOverviewMonthPersonDto> monthViewPersons = personList.stream()
.map(AbsenceOverviewViewController::initializeAbsenceOverviewMonthPersonDto)
.collect(toList());
return new AbsenceOverviewMonthDto(getMonthText(date, locale), new ArrayList<>(), monthViewPersons);
}
private static AbsenceOverviewMonthPersonDto initializeAbsenceOverviewMonthPersonDto(Person person) {
final String firstName = person.getFirstName();
final String lastName = person.getLastName();
final String email = person.getEmail();
return new AbsenceOverviewMonthPersonDto(firstName, lastName, email, new ArrayList<>());
}
private static Map<String, SickNote> sickNotesForDate(LocalDate date, List<SickNote> sickNotes, Function<SickNote, String> keySupplier) {
return sickNotes.stream()
.filter(sickNote -> isDateInPeriod(date, sickNote.getPeriod()))
.collect(toMap(keySupplier, Function.identity()));
}
private AbsenceOverviewDayType getAbsenceOverviewDayType(LocalDate date, SickNote sickNote, List<Application> applications) {
if (sickNote == null) {
return applications.stream()
.filter(application -> isDateInPeriod(date, application.getPeriod()))
.findFirst()
.map(this::getAbsenceOverviewDayType)
.orElse(null);
}
return getAbsenceOverviewDayType(sickNote);
}
private String getSelectedMonth(String month, LocalDate startDate) {
if (month == null) {
return String.valueOf(startDate.getMonthValue());
} else if (hasText(month)) {
return month;
}
return "";
}
private List<Person> getOverviewPersonsForUser(Person signedInUser, List<Department> departments,
String selectedDepartmentName) {
if (departments.isEmpty() && (signedInUser.hasRole(BOSS) || signedInUser.hasRole(OFFICE))) {
return personService.getActivePersons();
}
return departments.stream()
.filter(department -> department.getName().equals(selectedDepartmentName))
.map(Department::getMembers)
.flatMap(List::stream)
.sorted(comparing(Person::getFirstName))
.collect(toList());
}
private AbsenceOverviewMonthDayDto tableHeadDay(LocalDate localDate) {
String tableHeadDayText = String.format("%02d", localDate.getDayOfMonth());
boolean weekend = isWeekend(localDate);
return new AbsenceOverviewMonthDayDto(tableHeadDayText, weekend);
}
private String getMonthText(LocalDate date, Locale locale) {
return messageSource.getMessage(getMonthMessageCode(date), new Object[]{}, locale);
}
private String getMonthMessageCode(LocalDate localDate) {
switch (localDate.getMonthValue()) {
case 1:
return "month.january";
case 2:
return "month.february";
case 3:
return "month.march";
case 4:
return "month.april";
case 5:
return "month.may";
case 6:
return "month.june";
case 7:
return "month.july";
case 8:
return "month.august";
case 9:
return "month.september";
case 10:
return "month.october";
case 11:
return "month.november";
case 12:
return "month.december";
default:
throw new IllegalStateException("month value not in range of 1 to 12 cannot be mapped to a message key.");
}
}
private AbsenceOverviewDayType getAbsenceOverviewDayType(SickNote sickNote) {
switch (sickNote.getDayLength()) {
case MORNING:
return AbsenceOverviewDayType.ACTIVE_SICKNOTE_MORNING;
case NOON:
return AbsenceOverviewDayType.ACTIVE_SICKNOTE_NOON;
default:
return AbsenceOverviewDayType.ACTIVE_SICKNOTE_FULL;
}
}
private AbsenceOverviewDayType getAbsenceOverviewDayType(Application application) {
ApplicationStatus status = application.getStatus();
if (status == ApplicationStatus.WAITING) {
switch (application.getDayLength()) {
case MORNING:
return AbsenceOverviewDayType.WAITING_VACATION_MORNING;
case NOON:
return AbsenceOverviewDayType.WAITING_VACATION_NOON;
default:
return AbsenceOverviewDayType.WAITING_VACATION_FULL;
}
} else if (status == ApplicationStatus.ALLOWED) {
switch (application.getDayLength()) {
case MORNING:
return AbsenceOverviewDayType.ALLOWED_VACATION_MORNING;
case NOON:
return AbsenceOverviewDayType.ALLOWED_VACATION_NOON;
default:
return AbsenceOverviewDayType.ALLOWED_VACATION_FULL;
}
}
return null;
}
private static boolean isDateInPeriod(LocalDate date, Period period) {
LocalDate startDate = period.getStartDate();
if (startDate.isEqual(date)) {
return true;
}
LocalDate endDate = period.getEndDate();
if (endDate.isEqual(date)) {
return true;
}
return startDate.isBefore(date) && date.isBefore(endDate);
}
private LocalDate getStartDate(Integer year, String month) {
return getStartOrEndDate(year, month, TemporalAdjusters::firstDayOfYear, TemporalAdjusters::firstDayOfMonth);
}
private LocalDate getEndDate(Integer year, String month) {
return getStartOrEndDate(year, month, TemporalAdjusters::lastDayOfYear, TemporalAdjusters::lastDayOfMonth);
}
private LocalDate getStartOrEndDate(Integer year, String month, Supplier<TemporalAdjuster> firstOrLastOfYearSupplier,
Supplier<TemporalAdjuster> firstOrLastOfMonthSupplier) {
final LocalDate now = LocalDate.now(clock);
if (year != null) {
if (hasText(month)) {
return now.withYear(year).withMonth(parseInt(month)).with(firstOrLastOfMonthSupplier.get());
}
if ("".equals(month)) {
return now.withYear(year).with(firstOrLastOfYearSupplier.get());
}
return now.withYear(year).with(firstOrLastOfMonthSupplier.get());
}
if (hasText(month)) {
return now.withMonth(parseInt(month)).with(firstOrLastOfMonthSupplier.get());
}
return now.with(firstOrLastOfMonthSupplier.get());
}
private static boolean isWeekend(LocalDate date) {
final DayOfWeek dayOfWeek = date.getDayOfWeek();
return dayOfWeek == SATURDAY || dayOfWeek == SUNDAY;
}
}
|
package shibauth.confluence.authentication.shibboleth;
import com.atlassian.confluence.user.ConfluenceAuthenticator;
import com.atlassian.confluence.user.UserAccessor;
import com.atlassian.seraph.config.SecurityConfig;
import com.atlassian.user.Group;
import com.atlassian.user.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.*;
/**
* An authenticator that uses the REMOTE_USER header as proof of authentication.
* <p/>
* Configuration properties are looked for in
* <i>/remoteUserAuthenticator.properties</i> on the classpath. This file
* may contain the following properties:
* <ul>
* <li><strong>convert.to.utf8</strong> - Convert all incoming header values to UTF-8</li>
* <li><strong>create.users</strong> - Indicates whether accounts should be
* created for individuals the first they are encountered
* (acceptable values: true/false)</li>
* <li><strong>update.info</strong> - Indicates whether existing accounts
* should have their name and email address information
* updated when the user logs in (acceptable values: true/false)</li>
* <li><strong>default.roles</strong> - The default roles newly created
* accounts will be given (format: comma seperated list)</li>
* <li><strong>header.fullname</strong> - The name of the HTTP header that
* will carry the full name of the user</li>
* <li><strong>header.email</strong> - The name of the HTTP header that will
* carry the email address for the user</li>
*
* <li><strong>update.roles</strong> - Indicates whether the existing accounts
* should have their roles updated based on the header information. note: old
* roles are not removed if the header doesn't contain it. (Acceptable values:
* true/false. Default to false)</li>
* <li><strong>header.dynamicroles.attributenames</strong> - The name of the
* HTTP header that will carry the attribute name as indication of user's roles
* (i.e. SHIB_EP_ENTITLEMENT). Case insensitive. Names separated by comma or
* semicolon or space. If this entry is empty or not existing, then no dynamic
* role mapping loaded</li>
* <li><strong>header.dynamicroles.attributeValue1</strong> - The incoming
* attribute value (from header.dynamicroles.attributenames headers) to be
* mapped to group membership within confluence. See examples in properties
* file for details.</li>
* </ul>
*/
public class RemoteUserAuthenticator extends ConfluenceAuthenticator {
/**
* Serial version UID
*/
private static final long serialVersionUID = -5608187140008286795L;
/**
* Logger
*/
private final static Log log =
LogFactory.getLog(RemoteUserAuthenticator.class);
private static ShibAuthConfiguration config;
/**
* Initialize properties from property file
*/
static {
//TODO: use UI to configure if possible
//TODO: use Spring to configure config loader, etc.
config = ShibAuthConfigLoader.getShibAuthConfiguration();
}
/**
* Assigns a user to the roles.
*
* @param user the user to assign to the roles.
*/
private void assignUserToRoles(User user, Collection roles) {
if (roles.size() == 0) {
if (log.isDebugEnabled()) {
log.debug("No roles specified, not adding any roles...");
}
} else {
UserAccessor userAccessor = getUserAccessor();
if (log.isDebugEnabled()) {
log.debug("Assigning roles to user " + user.getName());
}
String role;
Group group;
for (Iterator it = roles.iterator(); it.hasNext(); ) {
role = it.next().toString().trim();
if (role.length() == 0) {
continue;
}
if (log.isDebugEnabled()) {
log.debug("Assigning " + user.getName() + " to role "
+ role);
}
try {
group = userAccessor.getGroup(role);
userAccessor.addMembership(group, user);
} catch (Throwable e) {
log.error("Attempted to add user " + user + " to role "
+ role + " but the role does not exist.");
}
}
}
}
/**
* Change userid to lower case.
*
* @param userid userid to be changed
* @return lower case version of it
*/
private String convertUsername(String userid) {
if (userid != null) {
userid = userid.toLowerCase();
}
return userid;
}
/**
* Creates a new user if the configuration allows it.
*
* @param userid user name for the new user
* @return the new user
*/
private Principal createUser(String userid) {
UserAccessor userAccessor = getUserAccessor();
Principal user = null;
if (config.isCreateUsers()) {
if (log.isInfoEnabled()) {
log.info("Creating user account for " + userid);
}
try {
user = userAccessor.createUser(userid);
} catch (Throwable t) {
// Note: just catching EntityException like we used to do didn't
// seem to cover Confluence massive with Oracle
if (log.isDebugEnabled()) {
log.debug(
"Error creating user " + userid
+ ". Will ignore and try to get the user (maybe it was already created)", t);
}
user = getUser(userid);
if (user == null) {
log.error(
"Error creating user " + userid
+ ". Got null user after attempted to create user (so it probably was not a duplicate).", t);
}
}
} else {
if (log.isDebugEnabled()) {
log.debug(
"Configuration does NOT allow for creation of new user accounts, authentication will fail for "
+ userid);
}
}
return user;
}
/**
* Initialize properties
*
* @param params
* @param config
*/
public void init(Map params, SecurityConfig config) {
super.init(params, config);
}
private void updateUser(Principal user, String fullName,
String emailAddress) {
UserAccessor userAccessor = getUserAccessor();
// If we have new values for name or email, update the user object
if ((user != null) && (user instanceof User)) {
User userToUpdate = (User) user;
boolean updated = false;
if ((fullName != null)
&&!fullName.equals(userToUpdate.getFullName())) {
if (log.isDebugEnabled()) {
log.debug("updating user fullName to '" + fullName + "'");
}
userToUpdate.setFullName(fullName);
updated = true;
} else {
if (log.isDebugEnabled()) {
log.debug("new user fullName is same as old one: '"
+ fullName + "'");
}
}
if ((emailAddress != null)
&&!emailAddress.equals(userToUpdate.getEmail())) {
if (log.isDebugEnabled()) {
log.debug("updating user emailAddress to '" + emailAddress
+ "'");
}
userToUpdate.setEmail(emailAddress);
updated = true;
} else {
if (log.isDebugEnabled()) {
log.debug("new user emailAddress is same as old one: '"
+ emailAddress + "'");
}
}
if (updated) {
try {
userAccessor.saveUser(userToUpdate);
} catch (Throwable t) {
log.error("Couldn't update user " + userToUpdate.getName(),
t);
}
}
}
}
private String getEmailAddress(HttpServletRequest request) {
String emailAddress = null;
// assumes it is first value in list, if header is defined multiple times. Otherwise would need to call getHeaders()
String headerValue = request.getHeader(config.getEmailHeaderName());
// the Shibboleth SP sends multiple values as single value, separated by comma or semicolon
List values = StringUtil.toListOfNonEmptyStringsDelimitedByCommaOrSemicolon(headerValue);
if (values!=null && values.size()>0) {
// use the first email in the list
emailAddress = (String)values.get(0);
if (log.isDebugEnabled()) {
log.debug("Got emailAddress '" + emailAddress + "' for header '"
+ config.getEmailHeaderName() + "'");
}
if (config.isConvertToUTF8()) {
String tmp = StringUtil.convertToUTF8(emailAddress);
if (tmp != null) {
emailAddress = tmp;
if (log.isDebugEnabled()) {
log.debug("emailAddress converted to UTF-8 '" + emailAddress + "' for header '"
+ config.getEmailHeaderName() + "'");
}
}
}
}
if ((emailAddress != null) && (emailAddress.length() > 0)) {
emailAddress = emailAddress.toLowerCase();
}
return emailAddress;
}
private String getFullName(HttpServletRequest request, String userid) {
String fullName = null;
// assumes it is first value in list, if header is defined multiple times. Otherwise would need to call getHeaders()
String headerValue = request.getHeader(config.getFullNameHeaderName());
// the Shibboleth SP sends multiple values as single value, separated by comma or semicolon
List values = StringUtil.toListOfNonEmptyStringsDelimitedByCommaOrSemicolon(headerValue);
if (values!=null && values.size()>0) {
// use the first full name in the list
fullName = (String)values.get(0);
if (log.isDebugEnabled()) {
log.debug("Got fullName '" + fullName + "' for header '"
+ config.getFullNameHeaderName() + "'");
}
if (config.isConvertToUTF8()) {
String tmp = StringUtil.convertToUTF8(fullName);
if (tmp != null) {
fullName = tmp;
if (log.isDebugEnabled()) {
log.debug("fullName converted to UTF-8 '" + fullName + "' for header '"
+ config.getFullNameHeaderName() + "'");
}
}
}
}
if ((fullName == null) || (fullName.length() == 0)) {
fullName = userid;
}
return fullName;
}
private Collection getRolesFromHeader(HttpServletRequest request) {
Set attribHeaders = config.getAttribHeaders();
// check if we're interested in some headers
if (attribHeaders.isEmpty()) {
return Collections.emptyList();
}
// effective roles as in presented in headers if it existed in
// mapRoleNames
Set dynamicRoles = new HashSet();
for (Enumeration en =
request.getHeaderNames(); en.hasMoreElements(); ) {
String headerName = en.nextElement().toString();
String trimmedLowercasedHeaderName = headerName.trim().toLowerCase();
if (log.isDebugEnabled()) {
log.debug("Analyzing header \"" + headerName
+ "\" for a mapped role = "
+ request.getHeader(headerName));
}
// see if this header is something we'd be interested in
if (attribHeaders.contains(trimmedLowercasedHeaderName)) {
Enumeration headerValues = request.getHeaders(headerName);
if (headerValues!=null) {
while (headerValues.hasMoreElements()) {
String headerValue = (String)headerValues.nextElement();
if (headerValue!=null) {
if (config.isConvertToUTF8()) {
String tmp = StringUtil.convertToUTF8(headerName);
if (tmp != null) {
headerValue = tmp;
if (log.isDebugEnabled()) {
log.debug("header value converted to UTF-8 '" + headerValue + "' for header '" +
trimmedLowercasedHeaderName + "'");
}
}
}
// the Shibboleth SP sends multiple values as single value, separated by comma or semicolon
List roles = StringUtil.toListOfNonEmptyStringsDelimitedByCommaOrSemicolon(headerValue);
for (int i = 0; i < roles.size(); i++) {
// According to Bruc Liong, this is case-insensitive to make it easier on the admin.
String lowercaseRole = ((String)roles.get(i)).toLowerCase();
List confluenceGroups = (List) config.getMapRole().get(lowercaseRole);
if (confluenceGroups != null) {
dynamicRoles.addAll(confluenceGroups);
if (log.isDebugEnabled()) {
StringBuffer confRoles = new StringBuffer();
for(int j=confluenceGroups.size()-1; j>-1; j
confRoles.append(confluenceGroups.get(j).toString());
if (j != 0) {
confRoles.append(",");
}
}
if (log.isDebugEnabled()) {
log.debug("Mapping role \"" + lowercaseRole + "\" to \""
+ confRoles + "\"");
}
}
}
}
}
else {
if (log.isDebugEnabled()) {
log.debug("One of header values for headerName '" + headerName +
"' was null, so was ignored");
}
}
}
}
}
}
//clean up a bit, in case these came into the list
dynamicRoles.remove(null);
dynamicRoles.remove("");
return dynamicRoles;
}
// Tried overriding login(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse), but
// it doesn't get called at all. That sucks because this method can often be called > 20 times per page.
/**
* @see com.atlassian.seraph.auth.Authenticator#getUser(
* javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*
* @param request
* @param response
*
* @return
*/
public Principal getUser(HttpServletRequest request,
HttpServletResponse response) {
if (log.isDebugEnabled()) {
log.debug("Request made to " + request.getRequestURL()
+ " triggered this AuthN check");
}
HttpSession httpSession = request.getSession();
Principal user;
// Check if the user is already logged in
if ((httpSession != null)
&& (httpSession.getAttribute(
ConfluenceAuthenticator.LOGGED_IN_KEY) != null)) {
user = (Principal) httpSession.getAttribute(
ConfluenceAuthenticator.LOGGED_IN_KEY);
if (log.isDebugEnabled()) {
log.debug(user.getName() + " already logged in, returning.");
}
return user;
}
// Since they aren't logged in, get the user name from
// the REMOTE_USER header
String userid = request.getRemoteUser();
if ((userid == null) || (userid.length() <= 0)) {
if (log.isDebugEnabled()) {
log.debug(
"Remote user was null or empty, can not perform authentication");
}
return null;
}
// Convert username to all lowercase
userid = convertUsername(userid);
// Pull name and address from headers
String fullName = getFullName(request, userid);
String emailAddress = getEmailAddress(request);
// Try to get the user's account based on the user name
user = getUser(userid);
boolean newUser = false;
// User didn't exist or was problem getting it. we'll try to create it
// if we can, otherwise will try to get it again.
if (user == null) {
user = createUser(userid);
if (user != null) {
newUser = true;
updateUser(user, fullName, emailAddress);
}
} else {
if (config.isUpdateInfo()) {
updateUser(user, fullName, emailAddress);
}
}
if (config.isUpdateRoles() || newUser) {
assignUserToRoles((User) user, config.getDefaultRoles());
assignUserToRoles((User) user, getRolesFromHeader(request));
}
// Now that we have the user's account, add it to the session and return
if (log.isDebugEnabled()) {
log.debug("Logging in user " + user.getName());
}
request.getSession().setAttribute(
ConfluenceAuthenticator.LOGGED_IN_KEY, user);
request.getSession().setAttribute(
ConfluenceAuthenticator.LOGGED_OUT_KEY, null);
return user;
}
/**
* {@inheritDoc}
*
* @param userid
*
* @return
*/
public Principal getUser(String userid) {
if (log.isDebugEnabled()) {
log.debug("Getting user " + userid);
}
UserAccessor userAccessor = getUserAccessor();
Principal user = null;
try {
user = userAccessor.getUser(userid);
if (user == null) {
if (log.isDebugEnabled()) {
log.debug("No user account exists for " + userid);
}
}
} catch (Throwable t) {
log.error("Error getting user", t);
}
return user;
}
}
|
package tk.ainiyue.danyuan.application.crawler.param.po;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.format.annotation.DateTimeFormat;
/**
* SysSeedRolerColumInfo.java
* tk.ainiyue.danyuan.application.crawler.seed.po
* TODO()
*
* ID
* wang
* 2017720 4:36:37
* V1.0
*/
@Entity
@Table(name = "sys_seed_ruler_colum_info")
public class SysSeedRulerColumInfo {
@Id
@GenericGenerator(name = "idGenerator", strategy = "uuid")
@Column(name = "uuid", columnDefinition = " varchar(36) COMMENT ''")
private String uuid; // uuid id
@Column(name = "ruler_uuid", columnDefinition = "varchar(32) COMMENT 'id'")
private String rulerUuid; // roler_uuid id
@Column(name = "colum_name", columnDefinition = "varchar(30) COMMENT ''")
private String columName; // colum_name
@Column(name = "ruler", columnDefinition = "varchar(300) COMMENT ''")
private String ruler; // roler
@Column(name = "type", columnDefinition = "varchar(30) COMMENT ''")
private String type; // type
@Column(name = "spl1", columnDefinition = "varchar(30) COMMENT 'split 1'")
private String spl1; // spl1 split 1
@Column(name = "spl2", columnDefinition = "int COMMENT '2'")
private String spl2; // spl2 split 2
@Column(name = "app1", columnDefinition = "varchar(30) COMMENT 'apand '")
private String app1; // app1 apand
@Column(name = "app2", columnDefinition = "varchar(30) COMMENT 'apand '")
private String app2; // app2 apand
@Column(name = "arr", columnDefinition = "int COMMENT ' '")
private String arr; // arr array
@Column(name = "discription", columnDefinition = "varchar(200) COMMENT ''")
private String discription; // discription
@Column(name = "create_time", updatable = false, columnDefinition = " timestamp default CURRENT_TIMESTAMP COMMENT ''")
@DateTimeFormat(style = "yyyy-MM-dd HH:mm:ss")
private Date createTime; // create_time
@Column(name = "create_user", updatable = false, columnDefinition = " varchar(50) default 'system' COMMENT ''")
private String createUser; // create_user
@Column(name = "updata_time", insertable = false, columnDefinition = " timestamp default CURRENT_TIMESTAMP COMMENT ''")
@DateTimeFormat(style = "yyyy-MM-dd HH:mm:ss")
private String updataTime; // updata_time
@Column(name = "updata_user", insertable = false, columnDefinition = " varchar(50) default 'system' COMMENT ''")
private String updataUser; // updata_user
@Column(name = "delete_flag", columnDefinition = " int default 0 COMMENT ''")
private Integer deleteFlag; // delete_flag
/**
* getUuid
* uuid
*
* @return: String
*/
public String getUuid() {
return uuid;
}
/**
* setUuid
* uuid
*/
public void setUuid(String uuid) {
this.uuid = uuid;
}
/**
* getRolerUuid
* rolerUuid
*
* @return: String
*/
public String getRulerUuid() {
return rulerUuid;
}
/**
* setRolerUuid
* rolerUuid
*/
public void setRulerUuid(String rulerUuid) {
this.rulerUuid = rulerUuid;
}
/**
* getColumName
* columName
*
* @return: String
*/
public String getColumName() {
return columName;
}
/**
* setColumName
* columName
*/
public void setColumName(String columName) {
this.columName = columName;
}
/**
* getRoler
* roler
*
* @return: String
*/
public String getRuler() {
return ruler;
}
/**
* setRoler
* roler
*/
public void setRuler(String ruler) {
this.ruler = ruler;
}
/**
* getType
* type
*
* @return: String
*/
public String getType() {
return type;
}
/**
* setType
* type
*/
public void setType(String type) {
this.type = type;
}
/**
* getSpl1
* spl1
*
* @return: String
*/
public String getSpl1() {
return spl1;
}
/**
* setSpl1
* spl1
*/
public void setSpl1(String spl1) {
this.spl1 = spl1;
}
/**
* getSpl2
* spl2
*
* @return: String
*/
public String getSpl2() {
return spl2;
}
/**
* setSpl2
* spl2
*/
public void setSpl2(String spl2) {
this.spl2 = spl2;
}
/**
* getApp1
* app1
*
* @return: String
*/
public String getApp1() {
return app1;
}
/**
* setApp1
* app1
*/
public void setApp1(String app1) {
this.app1 = app1;
}
/**
* getApp2
* app2
*
* @return: String
*/
public String getApp2() {
return app2;
}
/**
* setApp2
* app2
*/
public void setApp2(String app2) {
this.app2 = app2;
}
/**
* getArr
* arr
*
* @return: String
*/
public String getArr() {
return arr;
}
/**
* setArr
* arr
*/
public void setArr(String arr) {
this.arr = arr;
}
/**
* getDiscription
* discription
*
* @return: String
*/
public String getDiscription() {
return discription;
}
/**
* setDiscription
* discription
*/
public void setDiscription(String discription) {
this.discription = discription;
}
/**
* getCreateTime
* createTime
*
* @return: Date
*/
public Date getCreateTime() {
return createTime;
}
/**
* setCreateTime
* createTime
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* getCreateUser
* createUser
*
* @return: String
*/
public String getCreateUser() {
return createUser;
}
/**
* setCreateUser
* createUser
*/
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
/**
* getUpdataTime
* updataTime
*
* @return: String
*/
public String getUpdataTime() {
return updataTime;
}
/**
* setUpdataTime
* updataTime
*/
public void setUpdataTime(String updataTime) {
this.updataTime = updataTime;
}
/**
* getUpdataUser
* updataUser
*
* @return: String
*/
public String getUpdataUser() {
return updataUser;
}
/**
* setUpdataUser
* updataUser
*/
public void setUpdataUser(String updataUser) {
this.updataUser = updataUser;
}
/**
* getDeleteFlag
* deleteFlag
*
* @return: Integer
*/
public Integer getDeleteFlag() {
return deleteFlag;
}
/**
* setDeleteFlag
* deleteFlag
*/
public void setDeleteFlag(Integer deleteFlag) {
this.deleteFlag = deleteFlag;
}
/**
* toString
* TODO()
* @return
* @see java.lang.Object#toString()
* wang
*/
@Override
public String toString() {
return "SysSeedRolerColumInfo [uuid=" + uuid + ", rulerUuid=" + rulerUuid + ", columName=" + columName + ", ruler=" + ruler + ", type=" + type + ", spl1=" + spl1 + ", spl2=" + spl2 + ", app1=" + app1 + ", app2=" + app2 + ", arr=" + arr + ", discription=" + discription + ", createTime=" + createTime + ", createUser=" + createUser + ", updataTime=" + updataTime + ", updataUser=" + updataUser + ", deleteFlag=" + deleteFlag + "]";
}
}
|
package com.mijecu25.sqlplus.compiler.core.statement;
import java.sql.SQLException;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Test StatementUseDatabase
*
* @author Miguel Velez - miguelvelezmj25
* @version 0.1.0.3
*/
public class TestStatementUseDatabase extends TestStatement {
protected static StatementUseDatabase statement;
@BeforeClass
public static void initialize() throws SQLException {
TestStatement.initialize();
// TODO this might not work in all computers since they might not have this database
TestStatementUseDatabase.statement = new StatementUseDatabase("information_schema");
}
@AfterClass
public static void terminate() throws SQLException {
TestStatement.terminate();
}
@Test
public void testStatementUseDatabase() {
StatementUseDatabase statement = new StatementUseDatabase("information_schema");
Assert.assertNotNull(statement);
}
@Test
public void testExecute() throws SQLException {
TestStatementUseDatabase.statement.execute(TestStatementUseDatabase.connection);
}
}
|
package makyu.view;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetAsyncTask extends AsyncTask<Integer, Integer, String> {
private TextView textView;
private static final String RANK_API_URL = "http://yige.cc/api/rs_rank100";
private static final String ACTIVITY_TAG = "NetworkDemo";
public NetAsyncTask(TextView textView) {
super();
this.textView = textView;
}
@Override
protected String doInBackground(Integer... params) {
String msg = getData();
return msg;
}
/**
* StringAsyncTaskdoInBackground
* doInBackgroundUI UI
*/
@Override
protected void onPostExecute(String result) {
textView.setText("\n" + result);
}
//UI,UI UI
@Override
protected void onPreExecute() {
textView.setText("");
}
public String getData() {
String msg;
try {
URL url = new URL(RANK_API_URL);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(6 * 1000);
conn.setRequestProperty("Charset", "UTF-8");
int code = conn.getResponseCode();
if(code != 200) {
msg = "" + code;
}else{
InputStream inputStream = conn.getInputStream();
String res = streamToString(inputStream);
msg = "" + code + "\n" + res;
}
} catch (Exception e) {
msg = "";
e.printStackTrace();
}
return msg;
}
/**
*
* @param is
* @return
*/
public static String streamToString(InputStream is) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
is.close();
byte[] byteArray = baos.toByteArray();
return new String(byteArray, "UTF-8");
} catch (Exception e) {
Log.e(ACTIVITY_TAG, e.toString());
return null;
}
}
}
|
package libs;
import java.util.HashMap;
import java.util.Map;
public class DeviceConfiguration {
CommandPrompt cmd = new CommandPrompt();
Map<String, String> devices = new HashMap<String, String>();
public void startADB() throws Exception{
String output = cmd.runCommand("adb start-server");
String[] lines = output.split("\n");
if(lines[1].equalsIgnoreCase("* daemon started successfully *"))
System.out.println("adb service started");
else if(lines[0].contains("internal or external command")){
System.out.println("adb path not set in system varibale");
System.exit(0);
}
}
public void stopADB() throws Exception{
cmd.runCommand("adb kill-server");
}
public Map<String, String> getDivces() throws Exception {
startADB(); // start adb service
String output = cmd.runCommand("adb devices");
String[] lines = output.split("\n");
if(lines.length<=1){
System.out.println("No Device Connected");
System.exit(0); // exit if no connected devices found
}
for(int i=1;i<lines.length;i++){
lines[i]=lines[i].replaceAll("\\s+", "");
if(lines[i].contains("device")){
lines[i]=lines[i].replaceAll("device", "");
String deviceID = lines[i];
String model = cmd.runCommand("adb -s "+deviceID+" shell getprop ro.product.model").replaceAll("\\s+", "");
String brand = cmd.runCommand("adb -s "+deviceID+" shell getprop ro.product.brand").replaceAll("\\s+", "");
String osVersion = cmd.runCommand("adb -s "+deviceID+" shell getprop ro.build.version.release").replaceAll("\\s+", "");
String deviceName = brand+" "+model;
devices.put("deviceID"+i, deviceID);
devices.put("deviceName"+i, deviceName);
devices.put("osVersion"+i, osVersion);
System.out.println("Following device is connected");
System.out.println(deviceID+" "+deviceName+" "+osVersion+"\n");
}else if(lines[i].contains("unauthorized")){
lines[i]=lines[i].replaceAll("unauthorized", "");
String deviceID = lines[i];
System.out.println("Following device is unauthorized");
System.out.println(deviceID+"\n");
}else if(lines[i].contains("offline")){
lines[i]=lines[i].replaceAll("offline", "");
String deviceID = lines[i];
System.out.println("Following device is offline");
System.out.println(deviceID+"\n");
}
}
return devices;
}
// public static void main(String[] args) throws Exception {
// DeviceConfiguration gd = new DeviceConfiguration();
// gd.startADB();
// gd.getDivces();
// gd.stopADB();
}
|
package info.tregmine.tools;
import info.tregmine.Tregmine;
import info.tregmine.api.TregminePlayer;
import java.io.IOException;
import java.util.*;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.FallingBlock;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector;
public class PortalListener implements Listener
{
public static class GravityTask implements Runnable
{
private TregminePlayer player;
private Location srcLocation;
private Location dstLocation;
private FallingBlock currentBlock = null;
private Material material;
private byte data;
private BukkitTask task = null;
public GravityTask(TregminePlayer player)
{
this.player = player;
}
public Location getSrcLocation() { return srcLocation; }
public void setSrcLocation(Location v) { this.srcLocation = v; }
public Location getDstLocation() { return dstLocation; }
public void setDstLocation(Location v) { this.dstLocation = v; }
public Material getMaterial() { return material; }
public void setMaterial(Material v) { this.material = v; }
public byte getData() { return data; }
public void setData(byte v) { this.data = v; }
@Override
public void run()
{
int distance = 5;
Block block = null;
while (distance > 0) {
block = player.getDelegate().getTargetBlock(null, distance);
if (block.getType().equals(Material.AIR)) {
break;
}
distance
}
if (currentBlock != null) {
currentBlock.remove();
currentBlock = null;
}
FallingBlock gravityBlock =
player.getWorld().spawnFallingBlock(block.getLocation(),
material,
data);
gravityBlock.setDropItem(false);
gravityBlock.setFallDistance(0f);
gravityBlock.setVelocity(new Vector(0, 0.1, 0));
dstLocation = gravityBlock.getLocation();
currentBlock = gravityBlock;
}
public void start()
{
BukkitScheduler scheduler = player.getServer().getScheduler();
task = scheduler.runTaskTimer(player.getPlugin(), this, 0L, 1L);
}
public void cancel()
{
task.cancel();
}
}
public final static Set<Material> disallowedBlocks =
EnumSet.of(
Material.BED,
Material.WOOD_DOOR,
Material.WOODEN_DOOR,
Material.IRON_DOOR,
Material.IRON_DOOR_BLOCK,
Material.DOUBLE_PLANT,
Material.PISTON_EXTENSION,
Material.BEDROCK,
Material.ENDER_PORTAL_FRAME,
Material.CHEST,
Material.HOPPER,
Material.MOB_SPAWNER,
Material.DROPPER,
Material.DISPENSER,
Material.FURNACE,
Material.BREWING_STAND
);
private Tregmine plugin;
private Map<TregminePlayer, GravityTask> gravityTasks = null;
public PortalListener(Tregmine instance)
{
this.plugin = instance;
this.gravityTasks = new HashMap<TregminePlayer, GravityTask>();
}
@EventHandler
public void dropBlock(PlayerInteractEvent event)
{
if (event.getAction() != Action.RIGHT_CLICK_AIR &&
event.getAction() != Action.RIGHT_CLICK_BLOCK) {
return;
}
TregminePlayer player = plugin.getPlayer(event.getPlayer());
if (!gravityTasks.containsKey(player)) {
return;
}
GravityTask task = gravityTasks.get(player);
if (!player.hasBlockPermission(task.getDstLocation(), false)) {
player.sendMessage(ChatColor.RED + "Can not place it here!");
return;
}
gravityTasks.remove(player);
task.cancel();
player.sendMessage(ChatColor.GREEN + "Successfully dropped block!");
}
@SuppressWarnings("deprecation")
@EventHandler
public void pickupBlock(PlayerInteractEvent event)
throws IOException
{
if (event.getAction() != Action.LEFT_CLICK_BLOCK) {
return;
}
if (event.getItem() == null ||
!Material.DIAMOND_HOE.equals(event.getItem().getType())) {
return;
}
TregminePlayer p = plugin.getPlayer(event.getPlayer());
if (!p.getRank().canUseTools()) return;
List<String> lore = p.getItemInHand().getItemMeta().getLore();
if (lore.isEmpty()) return;
if (!lore.get(0).equals(ToolsRegistry.GravityGunLoreTag)) return;
Block block = event.getClickedBlock();
if (!block.getType().isSolid() ||
disallowedBlocks.contains(block.getType())) {
p.sendMessage(ChatColor.RED + "Denied use of Gravity Gun!");
p.sendMessage(ChatColor.AQUA + "Try using blocks!");
return;
}
if (plugin.getBlessedBlocks().containsKey(block.getLocation())) {
p.sendMessage(ChatColor.RED + "This block is blessed!");
return;
}
if (plugin.getFishyBlocks().containsKey(block.getLocation())) {
p.sendMessage(ChatColor.RED + "Can not move fishyblocks!");
return;
}
if (!p.hasBlockPermission(block.getLocation(), false)) {
p.sendMessage(ChatColor.RED + "Can not pick up from here!");
return;
}
if (gravityTasks.containsKey(p)) {
p.sendMessage(ChatColor.RED + "You are already carrying a block, You're not that strong!");
return;
}
String[] durability = lore.get(1).split("/");
if (Integer.parseInt(durability[0]) == 0) {
p.sendMessage(ChatColor.RED + "You are out of durability, Try repairing!");
return;
}
lore.remove(1);
lore.add(Integer.parseInt(durability[0]) - 1 + "/1000");
GravityTask task = new GravityTask(p);
task.setMaterial(block.getType());
task.setData(block.getData());
task.setDstLocation(block.getLocation());
task.setSrcLocation(block.getLocation());
gravityTasks.put(p, task);
task.start();
block.setType(Material.AIR);
}
public void clearUp(PlayerQuitEvent event) {
if (gravityTasks.containsKey(event.getPlayer())) {
GravityTask task = gravityTasks.get(event.getPlayer());
task.currentBlock.remove();
event.getPlayer().getWorld().getBlockAt(task.srcLocation).setType(task.material);
event.getPlayer().getWorld().getBlockAt(task.srcLocation).setData(task.data);
gravityTasks.remove(event.getPlayer());
}
}
}
|
package info.tregmine.web;
import java.util.List;
import java.io.PrintWriter;
import org.eclipse.jetty.server.Request;
import static org.bukkit.ChatColor.*;
import org.bukkit.Server;
import org.json.JSONWriter;
import org.json.JSONException;
import info.tregmine.Tregmine;
import info.tregmine.WebHandler;
import info.tregmine.api.TregminePlayer;
import info.tregmine.api.PlayerReport;
import info.tregmine.database.DAOException;
import info.tregmine.database.IContext;
import info.tregmine.database.IPlayerReportDAO;
public class PlayerKickAction implements WebHandler.Action
{
public static class Factory implements WebHandler.ActionFactory
{
public Factory()
{
}
@Override
public String getName()
{
return "/playerkick";
}
@Override
public WebHandler.Action createAction(Request request)
throws WebHandler.WebException
{
try {
int subjectId = Integer.parseInt(request.getParameter("subjectId"));
int issuerId = Integer.parseInt(request.getParameter("issuerId"));
String message = request.getParameter("message");
return new PlayerKickAction(subjectId, issuerId, message);
}
catch (NullPointerException e) {
throw new WebHandler.WebException(e);
}
catch (NumberFormatException e) {
throw new WebHandler.WebException(e);
}
}
}
private int subjectId;
private int issuerId;
private String message;
private boolean status;
private String error;
public PlayerKickAction(int subjectId, int issuerId, String message)
{
this.subjectId = subjectId;
this.issuerId = issuerId;
this.message = message;
this.status = true;
this.error = null;
}
@Override
public void queryGameState(Tregmine tregmine)
{
TregminePlayer subject = tregmine.getPlayer(subjectId);
if (subject == null) {
status = false;
error = "Subject not found.";
return;
}
TregminePlayer issuer = tregmine.getPlayer(issuerId);
if (issuer == null) {
issuer = tregmine.getPlayerOffline(issuerId);
}
subject.kickPlayer(tregmine, "Kicked by " + issuer.getChatName() + ": " + message);
Tregmine.LOGGER.info(subject.getChatName() + " was kicked by " +
issuer.getChatName() + " (from web)");
Server server = tregmine.getServer();
server.broadcastMessage(issuer.getChatName() + AQUA + " kicked "
+ subject.getChatName() + AQUA + ": " + message);
if (status) {
try (IContext ctx = tregmine.createContext()) {
PlayerReport report = new PlayerReport();
report.setSubjectId(subjectId);
report.setIssuerId(issuerId);
report.setAction(PlayerReport.Action.KICK);
report.setMessage(message);
IPlayerReportDAO reportDAO = ctx.getPlayerReportDAO();
reportDAO.insertReport(report);
} catch (DAOException e) {
throw new RuntimeException(e);
}
}
}
@Override
public void generateResponse(PrintWriter writer)
throws WebHandler.WebException
{
try {
JSONWriter json = new JSONWriter(writer);
json.object()
.key("status").value(status ? "ok" : "error")
.key("error").value(error)
.endObject();
writer.close();
}
catch (JSONException e) {
throw new WebHandler.WebException(e);
}
}
}
|
package inpro.incremental.source;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import javaFlacEncoder.FLACFileWriter;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import org.json.JSONArray;
import org.json.JSONObject;
import inpro.annotation.Label;
import inpro.audio.FrontEndBackedAudioInputStream;
import inpro.incremental.FrameAware;
import inpro.incremental.PushBuffer;
import inpro.incremental.unit.EditMessage;
import inpro.incremental.unit.EditType;
import inpro.incremental.unit.IU;
import inpro.incremental.unit.IUList;
import inpro.incremental.unit.SegmentIU;
import inpro.incremental.unit.TextualWordIU;
import inpro.incremental.unit.WordIU;
import edu.cmu.sphinx.frontend.BaseDataProcessor;
import edu.cmu.sphinx.util.props.PropertyException;
import edu.cmu.sphinx.util.props.PropertySheet;
import edu.cmu.sphinx.util.props.S4String;
public class GoogleASR extends IUSourceModule {
@S4String(defaultValue = "en-US")
public final static String PROP_ASR_LANG = "lang";
@S4String(defaultValue = "AIzaSyCXHs3mzb1IyfGx2tYxDC1ClgYUv0x8Kw8") // default to Timo's key! Really you should use your own.
public final static String PROP_API_KEY = "apiKey";
private String languageCode;
private GoogleJSONListener jsonlistener;
private FrontEndBackedAudioInputStream ais;
private String googleAPIkey;
public GoogleASR(BaseDataProcessor frontend) {
ais = new FrontEndBackedAudioInputStream(frontend);
}
@Override
public void newProperties(PropertySheet ps) throws PropertyException {
super.newProperties(ps);
languageCode = ps.getString(PROP_ASR_LANG);
googleAPIkey = ps.getString(PROP_API_KEY);
}
public void recognize() {
try {
String pair = getPair();
// setup connection with Google
HttpURLConnection upCon = getUpConnection(pair);
// start listening on return connection (separate thread)
jsonlistener = new GoogleJSONListener(pair);
Thread listenerThread = new Thread(jsonlistener);
listenerThread.start();
// push audio to Google (on this thread)
DataOutputStream stream = new DataOutputStream(upCon.getOutputStream());
// write to stream
writeToStream(stream, ais);
upCon.disconnect();
// on data end, end listening thread and tear down connection with google
Thread.sleep(100);
jsonlistener.shutdown();
listenerThread.join();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/** get connection to Google */
private HttpURLConnection getUpConnection(String pair) throws IOException {
HttpURLConnection connection;
String upstream = "https:
+ "key="
+ googleAPIkey
+ "&pair="
+ pair
+ "&lang=" + languageCode
+ "&maxAlternatives=10&client=chromium&continuous&interim&output=json&xjerr=1";
URL url = new URL(upstream);
connection = (HttpURLConnection) url.openConnection();
// adjust the connection
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setChunkedStreamingMode(1200);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Transfer-Encoding", "chunked");
connection.setRequestProperty("Content-Type", "audio/x-flac; rate=16000");
connection.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36");
connection.setConnectTimeout(60000);
connection.setUseCaches(false);
return connection;
}
private HttpURLConnection getDownConnection(String pair) throws IOException {
HttpURLConnection connection = null;
// "xjerr=1&client=chromium&lang=en-US&maxresults=10&pfilter=0&key="+key+"&output=json";
String downstream = "https:
URL url = null;
url = new URL(downstream);
connection = (HttpURLConnection) url.openConnection();
// adjust the connection
//connection.setDoInput(true);
connection.setDoOutput(true);
//connection.setChunkedStreamingMode(0);
//connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36");
connection.setConnectTimeout(60000);
connection.setUseCaches(false);
return connection;
}
private String getPair() {
SecureRandom random = new SecureRandom();
return new BigInteger(96, random).toString(32);
}
private final static byte[] FINAL_CHUNK = new byte[] { '0', '\r', '\n', '\r', '\n' };
/** write audio data to the stream
* @throws IOException
* @throws LineUnavailableException */
private void writeToStream(DataOutputStream stream, AudioInputStream ai) throws IOException, LineUnavailableException {
int buffer_size = 320; // 2000 samples = 250ms; 320 = 10ms
byte tempBuffer[] = new byte[buffer_size];
// Printer.printWithTime(TAG, "buffer size: " + buffer_size);
boolean run = true;
InputStream byteInputStream;
FLACFileWriter ffw = new FLACFileWriter();
ByteArrayOutputStream boas = new ByteArrayOutputStream();
AudioInputStream ais;
// Printer.printWithTime(TAG, "recording started");
int i = 0;
while (run) {
// System.err.println("sending chunk " + i);
i++;
int cnt = -1;
// read data from the audio input stream
cnt = ai.read(tempBuffer, 0, buffer_size);
if (cnt > 0) {// if there is data
byteInputStream = new ByteArrayInputStream(tempBuffer);
ais = new AudioInputStream(byteInputStream, ai.getFormat(),
cnt); // open a new audiostream
ffw.write(ais, FLACFileWriter.FLAC, boas);// convert audio
stream.write(boas.toByteArray());// write FLAC audio data to
// the output stream to
// google
boas.reset();
} else {
if (ai instanceof FrontEndBackedAudioInputStream && (((FrontEndBackedAudioInputStream) ai).hasMoreAudio())) {
// stream.write(FINAL_CHUNK);
// stream.flush();
// then get more audio in next step
} else
run = false;
}
}
stream.write(FINAL_CHUNK);
stream.flush();
stream.close();
}
public GoogleJSONListener getJSONListener() {
return this.jsonlistener;
}
public class GoogleJSONListener implements Runnable {
HttpURLConnection con;
boolean inShutdown = false;
private double startTime;
private double prevTime;
private IUList<WordIU> chunkHyps;
private int lastResultIndex;
private WordIU prev;
private double initialTime;
public GoogleJSONListener(String pair) throws IOException {
prevTime = 0;
chunkHyps = new IUList<WordIU>();
setLastResultIndex(-1);
prev = TextualWordIU.FIRST_ATOMIC_WORD_IU;
this.con = getDownConnection(pair);
setInitialTime(getTimestamp());
setStartTime(getTimestamp());
}
private void setInitialTime(double timestamp) {
initialTime = timestamp;
}
private double getInitialTime() {
return initialTime;
}
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
while (!inShutdown) {
// get JSON result
String decodedString;
while ((decodedString = in.readLine()) != null) {
parseJSON(decodedString);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void parseJSON(String decodedString) {
JSONObject json = new JSONObject(decodedString);
JSONArray result = json.getJSONArray("result");
if (result.length() == 0) return;
String transcript = result.getJSONObject(0).getJSONArray("alternative").getJSONObject(0).getString("transcript");
int resultIndex = json.getInt("result_index");
boolean isFinal = result.getJSONObject(0).has("final");
updateCurrentHyps(transcript, resultIndex, isFinal);
setLastResultIndex(resultIndex);
}
private void updateCurrentHyps(String transcript, int resultIndex, boolean isFinal) {
List<String> words = Arrays.asList(transcript.toLowerCase().trim().split("\\s+"));
IUList<WordIU> currentHyps = new IUList<WordIU>();
// keep working on the frontier
if (startNewChunk(resultIndex)) {
currentHyps.clear();
chunkHyps.clear();
}
double currentTimestamp = getTimestamp();
double delta = (currentTimestamp - getStartTime()) / (double) words.size();
int currentFrame = (int) (currentTimestamp - getInitialTime()) / 10; // I have no clue why
int i = 1;
for (String word : words) {
double startTime = prevTime + delta * (i-1);
double endTime = prevTime + delta * i;
SegmentIU siu = new SegmentIU(new Label(startTime/1000.0, endTime/1000.0, word));
List<IU> gIns = new LinkedList<IU>();
gIns.add(siu);
WordIU wiu = new WordIU(word, null, gIns);
wiu.setSameLevelLink(prev);
prev = wiu;
currentHyps.add(wiu);
i++;
}
// This calculates the differences between the current IU list and the previous, based on payload
List<EditMessage<WordIU>> diffs = chunkHyps.diffByPayload(currentHyps);
chunkHyps.clear();
chunkHyps.addAll(currentHyps);
if (isFinal) {
// add remaining WordIUs and commit
for (WordIU wordIU : chunkHyps) {
diffs.add(new EditMessage<WordIU>(EditType.COMMIT, wordIU));
}
currentHyps.clear();
chunkHyps.clear();
prev = TextualWordIU.FIRST_ATOMIC_WORD_IU;
}
if (startNewChunk(i)) {
setStartTime(getTimestamp());
prevTime += delta;
}
// The diffs represents what edits it takes to get from prevList to list, send that to the right buffer
for (PushBuffer listener : iulisteners) {
if (listener instanceof FrameAware)
((FrameAware) listener).setCurrentFrame(currentFrame);
// update frame count in frame-aware pushbuffers
if (diffs != null && !diffs.isEmpty())
listener.hypChange(null, diffs);
}
}
public double getTimestamp() {
return (System.currentTimeMillis());
}
public IUList<WordIU> getChunkHyps() {
return chunkHyps;
}
public void shutdown() {
inShutdown = true;
}
public int getLastResultIndex() {
return lastResultIndex;
}
public void setLastResultIndex(int lastResultIndex) {
this.lastResultIndex = lastResultIndex;
}
public boolean startNewChunk(int i) {
return i > getLastResultIndex();
}
public double getStartTime() {
return startTime;
}
public void setStartTime(double startTime) {
this.startTime = startTime;
}
}
}
|
package iot.pi.queue.domain;
import java.net.MalformedURLException;
import java.util.List;
import iot.pi.queue.constants.QueueVoices;
import iot.pi.queue.util.Pause;
import iot.pi.queue.util.SoundPlayer;
public class DigitAnnouncer implements Announcer {
public void announce(List<Announceable> announceables) throws MalformedURLException {
if (announceables.size() == 1 && announceables.get(0) == QueueVoices.NEUNG) {
Pause.delay(0.1);
}
for (Announceable digit : announceables) {
SoundPlayer.play(((QueueVoices)digit).getAudioFile());
Pause.delay(0.1);
}
}
public void announce(List<Announceable> announceables, int slot) throws MalformedURLException {
SoundPlayer.play(QueueVoices.NUMBER.getAudioFile());
announce(announceables);
SoundPlayer.play(QueueVoices.DEQUEUE.getAudioFile());
Pause.delay(0.1);
SoundPlayer.play(QueueVoices.NUMBER.getAudioFile());
Pause.delay(0.1);
switch (slot) {
case 1: SoundPlayer.play(QueueVoices.NEUNG.getAudioFile()); break;
case 2: SoundPlayer.play(QueueVoices.SONG.getAudioFile()); break;
case 3: SoundPlayer.play(QueueVoices.SARM.getAudioFile()); break;
default: break;
}
Pause.delay(0.1);
SoundPlayer.play(QueueVoices.KAA.getAudioFile());
}
}
|
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.util;
import java.lang.ref.SoftReference;
import java.util.HashMap;
/**
* Implements a {@link SoftReference} cache wherein the values in the hashmap are not prevented
* from being garbage collected.
*/
public class SoftCache<K,V>
{
public SoftCache (int initialCapacity, float loadFactor)
{
_map = new HashMap<K,SoftReference<V>>(initialCapacity, loadFactor);
}
public SoftCache (int initialCapacity)
{
_map = new HashMap<K,SoftReference<V>>(initialCapacity);
}
public SoftCache ()
{
_map = new HashMap<K,SoftReference<V>>();
}
/**
* Returns a reference to the underlying map.
*/
public HashMap<K,SoftReference<V>> getMap ()
{
return _map;
}
/**
* Returns true if the supplied key exists in this map and is mapped to an active value.
*/
public boolean containsKey (K key)
{
return (get(key) != null);
}
/**
* Looks up and returns the value associated with the supplied key.
*/
public V get (K key)
{
V value = null;
SoftReference<V> ref = _map.get(key);
if (ref != null) {
value = ref.get();
if (value == null) {
_map.remove(key);
}
}
return value;
}
/**
* Maps the specified key to the specified value.
*/
public V put (K key, V value)
{
SoftReference<V> old = _map.put(key, createReference(value));
return (old == null) ? null : old.get();
}
/**
* Removes the specified key from the map. Returns the value to which the key was previously
* mapped or null.
*/
public V remove (K key)
{
SoftReference<V> ref = _map.remove(key);
return (ref == null) ? null : ref.get();
}
/**
* Clears all mappings.
*/
public void clear ()
{
_map.clear();
}
/**
* Creates and returns a {@link SoftReference} to the supplied value. Subclasses can override
* to return custom subclasses.
*/
protected SoftReference<V> createReference (V value)
{
return new SoftReference<V>(value);
}
protected HashMap<K,SoftReference<V>> _map;
}
|
package org.jaxen.expr;
import java.io.Serializable;
import java.util.List;
import org.jaxen.Context;
import org.jaxen.JaxenException;
/**
* A wrapper around an XPath expression.
*
*/
public interface XPathExpr extends Serializable
{
/**
* Returns the wrapped expression object.
*
* @return the wrapped Expr object
*/
Expr getRootExpr();
/**
* Changes the wrapped expression object.
*
* @param the new expression object to wrap
*/
void setRootExpr(Expr rootExpr);
/**
* Returns a String containing the XPath expression.
*
* @return the text form of this XPath expression
*/
String getText();
/**
* Simplifies the XPath expression. For example, the expression
* <code>//para[1 = 1]</code> could be simplified to
* <code>//para</code>. In practice, this is usually a noop.
* Jaxen does not currently perform any simplification.
*/
void simplify();
/**
* Evaluates the expression and returns a list cintaing the resulting nodes,
* or a singleton list containing a <code>Double</code>, <code>String</code>,
* or <code>Boolean</code>.
*
* @param context the context in which to evaluate this expression
* @return a list
* @throws JaxenException
*/
List asList(Context context) throws JaxenException;
}
|
package net.sf.picard.util;
import net.sf.picard.PicardException;
import java.io.File;
import java.security.InvalidParameterException;
import java.text.*;
import java.util.Date;
import java.math.RoundingMode;
/**
* Simple class used to format object values into a standard format for printing.
*
* @author Tim Fennell
*/
public class FormatUtil {
private DateFormat dateFormat;
private NumberFormat integerFormat;
private NumberFormat floatFormat;
/** Constructs a new FormatUtil and initializes various internal formatters. */
public FormatUtil() {
this.dateFormat = new SimpleDateFormat("yyyy-MM-dd");
this.integerFormat = NumberFormat.getIntegerInstance();
this.integerFormat.setGroupingUsed(false);
this.floatFormat = NumberFormat.getNumberInstance();
this.floatFormat.setGroupingUsed(false);
this.floatFormat.setMaximumFractionDigits(6);
this.floatFormat.setRoundingMode(RoundingMode.HALF_DOWN);
if (this.floatFormat instanceof DecimalFormat) {
final DecimalFormat decimalFormat = (DecimalFormat)this.floatFormat;
final DecimalFormatSymbols decimalFormatSymbols = decimalFormat.getDecimalFormatSymbols();
decimalFormatSymbols.setNaN("?");
decimalFormatSymbols.setInfinity("?");
decimalFormat.setDecimalFormatSymbols(decimalFormatSymbols);
}
}
/** Formats a short to an integer string. */
public String format(short value) { return this.integerFormat.format(value); }
/** Formats an int to an integer string. */
public String format(int value) { return this.integerFormat.format(value); }
/** Formats a long to an integer string. */
public String format(long value) { return this.integerFormat.format(value); }
/** Formats a float to a floating point string. */
public String format(float value) {return this.floatFormat.format(value); }
/** Formats a double to a floating point string. */
public String format(double value) {return this.floatFormat.format(value); }
/** Formats an enum to the String representation of an enum. */
public String format(Enum value) { return value.name(); }
/** Formats a date to a date string without time. */
public String format(Date value) { return this.dateFormat.format(value); }
/** Formats a boolean value to a String. */
public String format(boolean value) { if (value) return "Y"; else return "N"; }
/** Attempts to determine the type of value and format it appropriately. */
public String format(Object value) {
if (value == null) return "";
if (value instanceof Short) return format( ((Short) value).shortValue() );
if (value instanceof Integer) return format( ((Integer) value).intValue() );
if (value instanceof Long) return format( ((Long) value).longValue() );
if (value instanceof Float) return format( ((Float) value).floatValue() );
if (value instanceof Double) return format( ((Double) value).doubleValue() );
if (value instanceof Enum) return format( ((Enum) value) );
if (value instanceof Date) return format( ((Date) value) );
if (value instanceof Boolean) return format( ((Boolean) value).booleanValue() );
return value.toString();
}
// Parsing methods
/** Parses a String into a short. */
public short parseShort(String value) { return Short.parseShort(value); }
/** Parses a String into an int. */
public int parseInt(String value) { return Integer.parseInt(value); }
/** Parses a String into a long. */
public long parseLong(String value) { return Long.parseLong(value); }
/** Parses a String into a float. */
public float parseFloat(String value) {
if ("?".equals(value)) return Float.NaN;
else return Float.parseFloat(value);
}
/** Parses a String into a double. */
public double parseDouble(String value) {
if ("?".equals(value)) return Double.NaN;
else return Double.parseDouble(value);
}
/** Parses a String into an Enum of the given type. */
public <E extends Enum> E parseEnum(String value, Class<E> type) { return (E) Enum.valueOf(type, value); }
/** Parses a String into a date. */
public Date parseDate(String value) {
try {
return this.dateFormat.parse(value);
}
catch (ParseException pe) {
throw new PicardException("Could not parse value as date: " + value, pe);
}
}
/** Parses a String into a boolean. */
public boolean parseBoolean(String value) {
if (value == null || value.length() == 0) return false;
char ch = Character.toUpperCase(value.charAt(0));
return (ch == 'Y');
}
/**
* Attempts to determine the correct parse method to call based on the desired
* return type and then parses the String and returns the value.
*
* @param value the String value to be parsed
* @param returnType the desired return type
* @return an object of the returnType
*/
public Object parseObject(String value, Class<?> returnType) {
if (returnType == Short.class || returnType == Short.TYPE) return parseShort(value);
if (returnType == Integer.class || returnType == Integer.TYPE) return parseInt(value);
if (returnType == Long.class || returnType == Long.TYPE) return parseLong(value);
if (returnType == Float.class || returnType == Float.TYPE) return parseFloat(value);
if (returnType == Double.class || returnType == Double.TYPE) return parseDouble(value);
if (returnType == Boolean.class || returnType == Boolean.TYPE) return parseBoolean(value);
if (returnType == Date.class) return parseDate(value);
if (returnType == Byte.class || returnType == Byte.TYPE) return parseInt(value);
if (returnType == File.class) return new File(value);
if (Enum.class.isAssignableFrom(returnType)) return parseEnum(value, (Class<? extends Enum>)returnType);
if (returnType == String.class) return value;
throw new InvalidParameterException("Don't know how to convert a String to a " + returnType.getName());
}
}
|
package okio;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import javax.annotation.Nullable;
final class RealBufferedStore implements BufferedStore {
private static final boolean STATE_READ = false;
private static final boolean STATE_WRITE = true;
private final Store store;
private final BufferedSource source;
private final BufferedSink sink;
private boolean state = STATE_READ;
RealBufferedStore(Store store) {
if (store == null) throw new NullPointerException("store == null");
this.store = store;
this.source = new RealBufferedSource(store);
this.sink = new RealBufferedSink(store);
}
private void switchToRead() throws IOException {
if (state == STATE_WRITE) {
// Flush the buffer of the sink
sink.emit();
state = STATE_READ;
}
}
private void switchToWrite() throws IOException {
if (state == STATE_READ) {
// Clear the buffer of the source, seek store back
Buffer buffer = source.buffer();
if (buffer.size != 0) {
store.seek(store.tell() - buffer.size);
buffer.clear();
}
state = STATE_WRITE;
}
}
// Source
@Override
public long read(Buffer sink, long byteCount) throws IOException {
switchToRead();
return source.read(sink, byteCount);
}
// BufferedSource
@Override
public boolean exhausted() throws IOException {
switchToRead();
return source.exhausted();
}
@Override
public void require(long byteCount) throws IOException {
switchToRead();
source.require(byteCount);
}
@Override
public boolean request(long byteCount) throws IOException {
switchToRead();
return source.request(byteCount);
}
@Override
public byte readByte() throws IOException {
switchToRead();
return source.readByte();
}
@Override
public short readShort() throws IOException {
switchToRead();
return source.readShort();
}
@Override
public short readShortLe() throws IOException {
switchToRead();
return source.readShortLe();
}
@Override
public int readInt() throws IOException {
switchToRead();
return source.readInt();
}
@Override
public int readIntLe() throws IOException {
switchToRead();
return source.readIntLe();
}
@Override
public long readLong() throws IOException {
switchToRead();
return source.readLong();
}
@Override
public long readLongLe() throws IOException {
switchToRead();
return source.readLongLe();
}
@Override
public long readDecimalLong() throws IOException {
switchToRead();
return source.readDecimalLong();
}
@Override
public long readHexadecimalUnsignedLong() throws IOException {
switchToRead();
return source.readHexadecimalUnsignedLong();
}
@Override
public void skip(long byteCount) throws IOException {
switchToRead();
source.skip(byteCount);
}
@Override
public ByteString readByteString() throws IOException {
switchToRead();
return source.readByteString();
}
@Override
public ByteString readByteString(long byteCount) throws IOException {
switchToRead();
return source.readByteString(byteCount);
}
@Override
public int select(Options options) throws IOException {
switchToRead();
return source.select(options);
}
@Override
public byte[] readByteArray() throws IOException {
switchToRead();
return source.readByteArray();
}
@Override
public byte[] readByteArray(long byteCount) throws IOException {
switchToRead();
return source.readByteArray(byteCount);
}
@Override
public int read(byte[] sink) throws IOException {
switchToRead();
return source.read(sink);
}
@Override
public void readFully(byte[] sink) throws IOException {
switchToRead();
source.readFully(sink);
}
@Override
public int read(byte[] sink, int offset, int byteCount) throws IOException {
switchToRead();
return source.read(sink, offset, byteCount);
}
@Override
public void readFully(Buffer sink, long byteCount) throws IOException {
switchToRead();
source.readFully(sink, byteCount);
}
@Override
public long readAll(Sink sink) throws IOException {
switchToRead();
return source.readAll(sink);
}
@Override
public String readUtf8() throws IOException {
switchToRead();
return source.readUtf8();
}
@Override
public String readUtf8(long byteCount) throws IOException {
switchToRead();
return source.readUtf8(byteCount);
}
@Nullable
@Override
public String readUtf8Line() throws IOException {
switchToRead();
return source.readUtf8Line();
}
@Override
public String readUtf8LineStrict() throws IOException {
switchToRead();
return source.readUtf8LineStrict();
}
@Override
public String readUtf8LineStrict(long limit) throws IOException {
switchToRead();
return source.readUtf8LineStrict(limit);
}
@Override
public int readUtf8CodePoint() throws IOException {
switchToRead();
return source.readUtf8CodePoint();
}
@Override
public String readString(Charset charset) throws IOException {
switchToRead();
return source.readString(charset);
}
@Override
public String readString(long byteCount, Charset charset) throws IOException {
switchToRead();
return source.readString(byteCount, charset);
}
@Override
public long indexOf(byte b) throws IOException {
switchToRead();
return source.indexOf(b);
}
@Override
public long indexOf(byte b, long fromIndex) throws IOException {
switchToRead();
return source.indexOf(b, fromIndex);
}
@Override
public long indexOf(byte b, long fromIndex, long toIndex) throws IOException {
switchToRead();
return source.indexOf(b, fromIndex, toIndex);
}
@Override
public long indexOf(ByteString bytes) throws IOException {
switchToRead();
return source.indexOf(bytes);
}
@Override
public long indexOf(ByteString bytes, long fromIndex) throws IOException {
switchToRead();
return source.indexOf(bytes, fromIndex);
}
@Override
public long indexOfElement(ByteString targetBytes) throws IOException {
switchToRead();
return source.indexOfElement(targetBytes);
}
@Override
public long indexOfElement(ByteString targetBytes, long fromIndex) throws IOException {
switchToRead();
return source.indexOfElement(targetBytes, fromIndex);
}
@Override
public boolean rangeEquals(long offset, ByteString bytes) throws IOException {
switchToRead();
return source.rangeEquals(offset, bytes);
}
@Override
public boolean rangeEquals(long offset, ByteString bytes, int bytesOffset, int byteCount)
throws IOException {
switchToRead();
return source.rangeEquals(offset, bytes, bytesOffset, byteCount);
}
@Override
public InputStream inputStream() {
return new InputStream() {
private InputStream inputStream = source.inputStream();
@Override
public int read() throws IOException {
switchToRead();
return inputStream.read();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
switchToRead();
return inputStream.read(b, off, len);
}
@Override
public int available() throws IOException {
switchToRead();
return inputStream.available();
}
@Override
public void close() throws IOException {
try {
switchToRead();
} finally {
try {
inputStream.close();
} finally {
RealBufferedStore.this.close();
}
}
}
@Override
public String toString() {
return RealBufferedStore.this + ".inputStream()";
}
};
}
// Sink
@Override
public void write(Buffer source, long byteCount) throws IOException {
switchToWrite();
sink.write(source, byteCount);
}
@Override
public void flush() throws IOException {
switchToWrite();
sink.flush();
}
// BufferedSink
@Override
public BufferedSink write(ByteString byteString) throws IOException {
switchToWrite();
return sink.write(byteString);
}
@Override
public BufferedSink write(byte[] source) throws IOException {
switchToWrite();
return sink.write(source);
}
@Override
public BufferedSink write(byte[] source, int offset, int byteCount) throws IOException {
switchToWrite();
return sink.write(source, offset, byteCount);
}
@Override
public long writeAll(Source source) throws IOException {
switchToWrite();
return sink.writeAll(source);
}
@Override
public BufferedSink write(Source source, long byteCount) throws IOException {
switchToWrite();
return sink.write(source, byteCount);
}
@Override
public BufferedSink writeUtf8(String string) throws IOException {
switchToWrite();
return sink.writeUtf8(string);
}
@Override
public BufferedSink writeUtf8(String string, int beginIndex, int endIndex) throws IOException {
switchToWrite();
return sink.writeUtf8(string, beginIndex, endIndex);
}
@Override
public BufferedSink writeUtf8CodePoint(int codePoint) throws IOException {
switchToWrite();
return sink.writeUtf8CodePoint(codePoint);
}
@Override
public BufferedSink writeString(String string, Charset charset) throws IOException {
switchToWrite();
return sink.writeString(string, charset);
}
@Override
public BufferedSink writeString(String string, int beginIndex, int endIndex, Charset charset)
throws IOException {
switchToWrite();
return sink.writeString(string, beginIndex, endIndex, charset);
}
@Override
public BufferedSink writeByte(int b) throws IOException {
switchToWrite();
return sink.writeByte(b);
}
@Override
public BufferedSink writeShort(int s) throws IOException {
switchToWrite();
return sink.writeShort(s);
}
@Override
public BufferedSink writeShortLe(int s) throws IOException {
switchToWrite();
return sink.writeShortLe(s);
}
@Override
public BufferedSink writeInt(int i) throws IOException {
switchToWrite();
return sink.writeInt(i);
}
@Override
public BufferedSink writeIntLe(int i) throws IOException {
switchToWrite();
return sink.writeIntLe(i);
}
@Override
public BufferedSink writeLong(long v) throws IOException {
switchToWrite();
return sink.writeLong(v);
}
@Override
public BufferedSink writeLongLe(long v) throws IOException {
switchToWrite();
return sink.writeLongLe(v);
}
@Override
public BufferedSink writeDecimalLong(long v) throws IOException {
switchToWrite();
return sink.writeDecimalLong(v);
}
@Override
public BufferedSink writeHexadecimalUnsignedLong(long v) throws IOException {
switchToWrite();
return sink.writeHexadecimalUnsignedLong(v);
}
@Override
public BufferedSink emit() throws IOException {
switchToWrite();
return sink.emit();
}
@Override
public BufferedSink emitCompleteSegments() throws IOException {
switchToWrite();
return sink.emitCompleteSegments();
}
@Override
public OutputStream outputStream() {
return new OutputStream() {
private OutputStream outputStream = sink.outputStream();
@Override
public void write(int b) throws IOException {
switchToWrite();
outputStream.write(b);
}
@Override
public void write(byte[] data, int offset, int byteCount) throws IOException {
switchToWrite();
outputStream.write(data, offset, byteCount);
}
@Override
public void flush() throws IOException {
switchToWrite();
outputStream.flush();
}
@Override
public void close() throws IOException {
try {
switchToWrite();
} finally {
try {
outputStream.close();
} finally {
RealBufferedStore.this.close();
}
}
}
@Override
public String toString() {
return RealBufferedStore.this + ".outputStream()";
}
};
}
// Store
@Override
public void seek(long position) throws IOException {
if (state == STATE_READ) {
source.buffer().clear();
} else {
sink.emit();
}
store.seek(position);
}
@Override
public long tell() throws IOException {
if (state == STATE_READ) {
return store.tell() - source.buffer().size();
} else {
return store.tell() + sink.buffer().size();
}
}
@Override
public long size() throws IOException {
if (state == STATE_WRITE) {
sink.emit();
}
return store.size();
}
// Common
@Override
public Timeout timeout() {
return store.timeout();
}
@Override
public void close() throws IOException {
try {
if (state == STATE_READ) {
try {
source.close();
} finally {
sink.close();
}
} else {
try {
sink.close();
} finally {
source.close();
}
}
} finally {
store.close();
}
}
// Buffered
@Override
public Buffer buffer() {
if (state == STATE_READ) {
return source.buffer();
} else {
return sink.buffer();
}
}
}
|
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JPanel;
import api.gui.ApplicationWindow;
import api.gui.HealthGrid;
import api.util.EventHandler;
import api.util.Support;
public class HealthGridDemo
{
public final static void main(final String[] args)
{
new HealthGridDemo(args);
}
private HealthGrid grid = null;
private boolean isDebugging = false;
private int iterations = 1;
private ApplicationWindow window = null;
public HealthGridDemo(final String[] args)
{
this.setDebugging(Support.promptDebugMode(this.getWindow()));
// Define a self-contained ActionListener event handler.
EventHandler<HealthGridDemo> myActionPerformed = new EventHandler<HealthGridDemo>(this)
{
private final static long serialVersionUID = 1L;
@Override
public final void run(final AWTEvent event)
{
ActionEvent actionEvent = (ActionEvent)event;
HealthGridDemo parent = this.getParent();
ApplicationWindow window = parent.getWindow();
switch (actionEvent.getActionCommand())
{
case "Initialize":
parent.setIterations(1);
parent.getGrid().initializeConfiguration();
window.setTitle("Health Grid Application - Iteration: " + parent.getIterations());
break;
case "Iterate A":
case "Iterate B":
case "Iterate C":
final int NUM_ITERATIONS = Support.getIntegerInputString(window,
"How many iterations?", "Number of Iterations");
for (int i = 0; i < NUM_ITERATIONS; i++)
{
parent.getGrid().iterateConfiguration(actionEvent.getActionCommand());
if ((parent.getIterations() % 1000) == 0)
{
if (parent.isDebugging())
{
Support.displayDebugMessage(window,
"Infection (" + (parent.getIterations() / 1000) + ")\n");
}
parent.getGrid().injectInfection();
}
parent.setIterations(parent.getIterations() + 1);
window.setTitle("Health Grid Application - Iteration: " + parent.getIterations());
}
break;
case "Randomize":
parent.setIterations(1);
parent.getGrid().randomizeConfiguration();
window.setTitle("Health Grid Application - Iteration: " + parent.getIterations());
break;
default:
break;
}
}
};
// Define a self-contained interface construction event handler.
EventHandler<HealthGridDemo> myDrawGUI = new EventHandler<HealthGridDemo>(this)
{
private final static long serialVersionUID = 1L;
@Override
public final void run(final ApplicationWindow window)
{
HealthGridDemo parent = this.getParent();
JPanel buttonPanel = new JPanel();
Container contentPane = window.getContentPane();
JPanel gridPanel = new JPanel();
JButton initialize = new JButton("Initialize");
JButton iterateA = new JButton("Iterate A");
JButton iterateB = new JButton("Iterate B");
JButton iterateC = new JButton("Iterate C");
JButton randomize = new JButton("Randomize");
final int rows = Support.getIntegerInputString(window, "How many rows?", "Number of Rows");
final int cols = Support.getIntegerInputString(window, "How many columns?", "Number of Columns");
parent.setGrid(new HealthGrid(rows, cols));
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(initialize);
buttonPanel.add(randomize);
buttonPanel.add(iterateA);
buttonPanel.add(iterateB);
buttonPanel.add(iterateC);
gridPanel.setLayout(new FlowLayout());
gridPanel.add(parent.getGrid());
contentPane.setLayout(new BorderLayout());
contentPane.add(buttonPanel, BorderLayout.NORTH);
contentPane.add(gridPanel, BorderLayout.CENTER);
initialize.addActionListener(window);
initialize.setFont(Support.DEFAULT_TEXT_FONT);
iterateA.addActionListener(window);
iterateA.setFont(Support.DEFAULT_TEXT_FONT);
iterateB.addActionListener(window);
iterateB.setFont(Support.DEFAULT_TEXT_FONT);
iterateC.addActionListener(window);
iterateC.setFont(Support.DEFAULT_TEXT_FONT);
randomize.addActionListener(window);
randomize.setFont(Support.DEFAULT_TEXT_FONT);
}
};
this.setWindow(new ApplicationWindow(null, "Health Grid Application - Iteration: " + this.getIterations(), new Dimension(800, 600),
this.isDebugging(), false, myActionPerformed, myDrawGUI));
this.getWindow().pack();
}
public final HealthGrid getGrid()
{
return this.grid;
}
public final int getIterations()
{
return this.iterations;
}
public final ApplicationWindow getWindow()
{
return this.window;
}
public final boolean isDebugging()
{
return this.isDebugging;
}
public final void setDebugging(final boolean isDebugging)
{
this.isDebugging = isDebugging;
}
public final void setGrid(final HealthGrid grid)
{
this.grid = grid;
}
public final void setIterations(final int iterations)
{
this.iterations = iterations;
}
public final void setWindow(final ApplicationWindow window)
{
this.window = window;
}
}
|
// HttpMonitor.java
package ed.net.httpserver;
import java.util.*;
import javax.servlet.http.*;
import ed.js.*;
import ed.net.*;
import ed.lang.*;
import ed.util.*;
public abstract class HttpMonitor implements HttpHandler {
public HttpMonitor( String name ){
this( name , false );
}
public HttpMonitor( String name , boolean plainText ){
_name = name;
_plainText = plainText;
_uri = "/~" + name;
if ( _plainText )
_header = null;
else {
StringBuilder buf = new StringBuilder();
buf.append( "<html>" );
buf.append( "<head>" );
buf.append( "<title>" ).append( DNSUtil.getLocalHost() ).append( " " ).append( _name ).append( "</title>" );
buf.append( "<style>\n" );
buf.append( " body { font-size: .65em; font-family: Monaco; }\n" );
buf.append( " table { font-size: 10px; }\n" );
buf.append( " th { backgroud: #dddddd; text-align:left; }\n" );
buf.append( " .floatingList li { float: left; list-style-type:none; }\n" );
buf.append( " bottomLine { border-bottom: 1px solid black; }\n" );
buf.append( " .warn { color: orange; }\n" );
buf.append( " .error { color: red; font-decoration: bold; }\n" );
addStyle( buf );
buf.append( "</style>\n" );
buf.append( "</head>" );
buf.append( "<body>" );
_header = buf.toString();
}
_addAll( name );
}
protected boolean allowed( HttpRequest request ){
String h = request.getHost();
if ( h == null )
return false;
if ( h.equals( "127.0.0.1" ) )
return true;
if ( ! h.endsWith( "." + Config.getInternalDomain() ) )
return false;
if ( AUTH_COOKIE == null ){
System.err.println( "WARNING: no cookie info, letting everyone in" );
return true;
}
if ( AUTH_COOKIE.equalsIgnoreCase( request.getCookie( "auth" ) ) )
return true;
if ( AUTH_COOKIE.equalsIgnoreCase( request.getParameter( "auth" ) ) )
return true;
return false;
}
protected void addStyle( StringBuilder buf ){}
public abstract void handle( MonitorRequest request );
public boolean handles( HttpRequest request , Info info ){
if ( ! request.getURI().equalsIgnoreCase( _uri ) )
return false;
if ( ! allowed( request ) )
return false;
info.fork = false;
info.admin = true;
return true;
}
public void handle( HttpRequest request , HttpResponse response ){
if ( AUTH_COOKIE != null && AUTH_COOKIE.equalsIgnoreCase( request.getParameter( "auth" ) ) ){
Cookie c = new Cookie( "auth" , AUTH_COOKIE );
c.setDomain( "10gen.cc" );
c.setPath( "/" );
c.setMaxAge( 86400 * 30 );
response.addCookie( c );
}
final JxpWriter out = response.getJxpWriter();
final MonitorRequest mr = new MonitorRequest( out , request , response );
boolean html = mr.html() && ! _plainText;
if ( _plainText )
response.setHeader( "Content-Type" , "text/plain" );
else if ( html ) {
out.print( _header );
out.print( _allContent );
String section = _section();
if ( section != null ){
String sc = _subContent.get( section );
if ( sc != null )
out.print( sc );
}
}
try {
handle( mr );
if ( mr.json() ){
out.print( JSON.serialize( mr._data ) );
}
}
catch ( Exception e ){
e.printStackTrace();
out.print( e.toString() ).print( "<br>\n" );
for ( StackTraceElement element : e.getStackTrace() )
out.print( element + "<br>\n" );
}
if ( html )
out.print( "</body></html>" );
}
public double priority(){
return Double.MIN_VALUE;
}
String _section(){
return _section( _name );
}
private static String _section( String name ){
int idx = name.indexOf( "-" );
if ( idx < 0 )
return name.toLowerCase();
return name.substring( 0 , idx ).toLowerCase();
}
private static void _addAll( String name ){
if ( name.contains( "-" ) ){
// sub menu item
String section = _section( name );
List<String> sub = _subs.get( section );
if ( sub == null ){
sub = new ArrayList<String>();
_subs.put( section , sub );
}
sub.add( name );
Collections.sort( sub );
StringBuilder buf = new StringBuilder( section + " : " );
for ( String t : sub ){
buf.append( "<a href='/~" + t + "'>" + t.substring( section.length() + 1 ) + "</a> | " );
}
buf.append( "<hr>" );
_subContent.put( section , buf.toString() );
return;
}
_all.add( name );
Collections.sort( _all );
StringBuilder buf = new StringBuilder();
for ( String t : _all ){
buf.append( "<a href='/~" + t + "'>" + t + "</a> | " );
}
buf.append( "<hr>" );
_allContent = buf.toString();
}
public class MonitorRequest {
public MonitorRequest( JxpWriter out , HttpRequest request , HttpResponse response ){
_out = out;
_request = request;
_response = response;
_json = _request.getBoolean( "json" , false );
if ( _json ){
_data = new JSObjectBase();
_cur = new Stack<JSObject>();
_cur.push( _data );
_response.setContentType( "application/json" );
}
else {
_data = null;
_cur = null;
}
}
// DATA API
public void startData(){
startData( null );
}
public void startData( String type ){
if ( _json ){
JSObject next = _cur.peek();
if ( type != null ){
JSObject o = next;
next = (JSObject)(o.get( type ));
if ( next == null ){
next = new JSObjectBase();
o.set( type , next );
}
}
_cur.push( next );
}
else {
if ( type != null )
addHeader( type );
startTable();
}
}
public void endData(){
if ( _json ){
_cur.pop();
}
else {
endTable();
}
}
public void addData( Object name , Object value ){
addData( name , value , null );
}
public void addData( Object name , Object value , String type ){
if ( _json )
_cur.peek().set( name.toString() , value.toString() );
else
addTableRow( name , value , type );
}
// RAW HTML API
public void addHeader( String header ){
if ( html() ){
_out.print( "<h3>" );
_out.print( header );
_out.print( "</h3>" );
}
}
public void addSpacingLine(){
if ( _json )
return;
_out.print( "<br>" );
}
public void startTable(){
_assertIfJson();
_out.print( "<table border='1' >" );
}
public void endTable(){
_assertIfJson();
_out.print( "</table>" );
}
public void addTableRow( Object header , Object data ){
addTableRow( header , data , null );
_assertIfJson();
}
public void addTableCell( Object data ){
_assertIfJson();
_out.print( "<td>" );
if ( data == null )
_out.print( "null" );
else
_out.print( data.toString() );
_out.print( "</td>" );
}
public void addTableRow( Object header , Object data , String valueClass ){
_assertIfJson();
_out.print( "<tr><th>" );
_out.print( header == null ? "null" : header.toString() );
_out.print( "</th><td " );
if ( valueClass != null )
_out.print( "class=\"" + valueClass + "\" " );
_out.print( ">" );
_out.print( data == null ? "null" : data.toString() );
_out.print( "</td></tr>" );
}
// BASICS
public boolean json(){
return _json;
}
public boolean html(){
return ! _json;
}
public JxpWriter getWriter(){
_assertIfJson();
return _out;
}
public HttpRequest getRequest(){
return _request;
}
public HttpResponse getResponse(){
return _response;
}
private void _assertIfJson(){
if ( _json )
throw new RuntimeException( "this is a json request, and you're trying to do a non-json thing" );
}
private final JxpWriter _out;
private final HttpRequest _request;
private final HttpResponse _response;
protected final boolean _json;
private final JSObject _data;
private final Stack<JSObject> _cur;
}
final boolean _plainText;
final String _name;
final String _uri;
final String _header;
static final List<String> _all = new ArrayList<String>();
static String _allContent = "";
static final Map<String,List<String>> _subs = new HashMap<String,List<String>>();
static final Map<String,String> _subContent = new HashMap<String,String>();
static final String AUTH_COOKIE = Config.get().getProperty( "authCookie" , null );
// Some Basic Monitors
public static final class MemMonitor extends HttpMonitor {
MemMonitor(){
super( "mem" , false );
_r = Runtime.getRuntime();
}
public void handle( MonitorRequest request ){
print( request , "before" );
if ( request.getRequest().getBoolean( "gc" , false ) ){
System.gc();
print( request , "after" );
}
}
void print( MonitorRequest request , String name ){
request.startData( name );
request.addData( "max" , MemUtil.bytesToMB( _r.maxMemory() ) );
request.addData( "total" , MemUtil.bytesToMB( _r.totalMemory() ) );
request.addData( "free" , MemUtil.bytesToMB( _r.freeMemory() ) );
request.addData( "used" , MemUtil.bytesToMB( _r.totalMemory() - _r.freeMemory() ) );
request.endData();
}
final Runtime _r;
}
public static class ThreadMonitor extends HttpMonitor {
ThreadMonitor(){
super( "threads" , false );
}
protected void addStyle( StringBuilder buf ){
buf.append( ".js { color: red; }\n" );
buf.append( ".ed { color: blue; }\n" );
}
public void handle( MonitorRequest mr ){
mr.addHeader( "Threads" );
final JxpWriter out = mr.getWriter();
final Map<Thread,StackTraceElement[]> all = Thread.getAllStackTraces();
final Thread cur = Thread.currentThread();
final String filter = getFilter( mr.getRequest() );
if ( filter != null )
out.print( "filter : <b>" ).print( filter ).print( "</b><br>" );
final StackTraceHolder holder = StackTraceHolder.getInstance();
for ( final Map.Entry<Thread,StackTraceElement[]> t : all.entrySet() ){
final Thread it = t.getKey();
if ( it == cur )
continue;
if ( filter != null && ! _match( t , filter ) )
continue;
out.print( it.getName() ).print( " " ).print( it.getId() ).print( " " ).print( it.getState().toString() ).print( "<br>" );
out.print( "<ul>" );
final StackTraceElement[] es = t.getValue();
for ( int i=0; i<es.length; i++){
es[i] = holder.fix( es[i] );
if ( es[i] == null )
continue;
final String str = es[i].toString();
String cls = "";
if ( str.startsWith( "ed.js.gen" ) )
cls = "js";
else if ( str.startsWith( "ed." ) )
cls = "ed";
out.print( "<li" );
out.print( " class='" ).print( cls ).print( "' " );
out.print(" >" ).print( str ).print( "</li>" );
}
out.print( "</ul>" );
out.print( "<hr>" );
}
}
boolean _match( Map.Entry<Thread,StackTraceElement[]> t , String filter ){
if ( t.getKey().getName().contains( filter ) )
return true;
final StackTraceElement[] es = t.getValue();
for ( int i=0; i<es.length; i++ ){
final StackTraceElement e = es[i];
if ( e == null )
continue;
if ( ( e.getClassName() != null && e.getClassName().contains( filter ) )
|| ( e.getFileName() != null && e.getFileName().contains( filter ) )
|| ( e.getMethodName() != null && e.getMethodName().contains( filter ) )
)
return true;
}
return false;
}
public static String getFilter( HttpRequest request ){
return request.getParameter( "f" );
}
}
public static class FavIconHack implements HttpHandler {
public boolean handles( HttpRequest request , Info info ){
if ( ! request.getURI().equals( "/favicon.ico" ) )
return false;
String host = request.getHost();
if ( host == null )
return false;
if ( ! host.contains( "10gen" ) )
return false;
String ref = request.getHeader( "Referer" );
if ( ref == null )
return false;
int idx = ref.indexOf( "/~" );
if ( idx < 0 || idx + 3 >= ref.length() )
return false;
return Character.isLetter( ref.charAt( idx + 2 ) );
}
public void handle( HttpRequest request , HttpResponse response ){
response.setResponseCode( 404 );
response.setCacheTime( 86400 );
}
public double priority(){
return Double.MIN_VALUE;
}
}
}
|
package act.aaa;
import act.Act;
import act.ActComponent;
import act.app.App;
import act.app.event.AppEventId;
import act.util.SubClassFinder;
import act.util.SubTypeFinder;
import org.osgl.aaa.*;
import javax.inject.Inject;
@SuppressWarnings("unused")
public class AAAServiceFinder<T> {
private App app;
@Inject
public AAAServiceFinder(App app) {
this.app = app;
}
@SubClassFinder
public void foundActAAAService(Class<ActAAAService> serviceType) {
ActAAAService service = app.getInstance(serviceType);
plugin().buildService(app, service);
}
@SubClassFinder
public void foundAuditorService(Class<Auditor> auditorClass) {
Auditor auditor = app.getInstance(auditorClass);
plugin().buildService(app, auditor);
}
@SubClassFinder
public void foundAuthenticationService(Class<AuthenticationService> serviceType) {
if (ActAAAService.class.isAssignableFrom(serviceType)) {
return;
}
AuthenticationService service = app.getInstance(serviceType);
plugin().buildService(app, service);
}
@SubClassFinder
public void foundAuthorizationService(Class<AuthorizationService> serviceType) {
AuthorizationService service = app.getInstance(serviceType);
plugin().buildService(app, service);
}
@SubClassFinder(callOn = AppEventId.PRE_START)
public void foundDynamicPermissionCheckHelper(final Class<DynamicPermissionCheckHelperBase> target) {
DynamicPermissionCheckHelperBase helper = app.getInstance(target);
AAA.registerDynamicPermissionChecker(helper, helper.getTargetClass());
}
@SubClassFinder
public void handleFound(Class<AAAPersistentService> serviceType) {
if (DefaultPersistenceService.class.equals(serviceType)) {
// DefaultPersistentService is not aimed to be used for dependency injection
// however subclass of it might be implemented by app developer
return;
}
AAAPersistentService service = app.getInstance(serviceType);
plugin().buildService(app, service);
}
private AAAPlugin plugin() {
return Act.sessionManager().findListener(AAAPlugin.class);
}
}
|
package base.grid.page;
import java.util.List;
import base.grid.BaseCell;
import base.grid.Grid;
import base.grid.header.CellHeader;
import base.grid.header.TableCellHeader;
import base.grid.header.TableHeader;
import base.grid.Cell;
public class BaseTable implements Table {
private Class<? extends TableCellHeader> header;
private TableHeader gridHeader;
private Grid grid;
private String gridSelector;
public BaseTable(Class<? extends TableCellHeader> header, String headerSelector, String gridSelector) {
this.header = header;
this.gridSelector = gridSelector;
gridHeader = new TableHeader(getHeaderClass(), headerSelector);
grid = new Grid(this.header, this.gridSelector);
}
public Grid reloadGrid() {
grid = new Grid(this.header, this.gridSelector);
return grid;
}
public Grid getGrid() {
return grid;
}
public List<BaseCell> getColumn(TableCellHeader header) {
return grid.getColumn(header);
}
public List<BaseCell> getRow(Cell cell) {
return grid.getRow(cell);
}
public TableCellHeader getHeader(String labelName) {
TableCellHeader[] headerColumns = header.getEnumConstants();
for (TableCellHeader headerColumn : headerColumns)
if (headerColumn.getLabel().equalsIgnoreCase(labelName))
return headerColumn;
throw new RuntimeException("Coluna '" + labelName + "' não encontrada");
}
public CellHeader getHeader(TableCellHeader columnEnum) {
return gridHeader.getCellHeader(columnEnum);
}
public Class<? extends TableCellHeader> getHeaderClass() {
return this.header;
}
public List<BaseCell> getRowWithInfo(TableCellHeader columnEnum, String filter) {
List<BaseCell> columns = grid.getColumn(columnEnum);
return isTextDisplayed(columns, filter);
}
public boolean isInfoDisplayedOnColumn(TableCellHeader columnEnum, String filter) {
if (getRowWithInfo(columnEnum, filter) != null)
return true;
return false;
}
public List<BaseCell> isTextDisplayed(List<BaseCell> column, String textExpected) {
int rowInterator = 1;
for (BaseCell cell : column) {
String actualText = cell.getText();
if (actualText != null) {
if (actualText.equalsIgnoreCase(textExpected)) {
return grid.getRow(rowInterator);
}
}
rowInterator++;
}
return null;
}
public void setGridRowModifier(int rowModifier) {
grid.setRowModifier(rowModifier);
}
public void setHeaderRowModifier(int rowModifier) {
gridHeader.setRowModifier(rowModifier);
}
}
|
/**
* CSSMin takes in well-formed, human-readable CSS and reduces its size substantially.
* It removes unnecessary whitespace and comments, and orders the contents of CSS
* selectors alphabetically to enhance GZIP compression.
*
* Originally by Barry van Oudtshoorn, with bug reports, fixes, and contributions by
* <ul>
* <li>Kevin de Groote</li>
* <li>Pedro Pinheiro</li>
* </ul>
* Some code is based on the YUI CssCompressor code, by Julien Lecomte.
*
* @author Barry van Oudtshoorn
*/
import java.util.*;
import java.util.regex.*;
import java.io.*;
import java.lang.*;
public class CSSMin {
protected static boolean bDebug = false;
/**
* Main entry point for CSSMin from the command-line.
* <b>Usage:</b> CSSMin <i>[Input file]</i>, <i>[Output file]</i>, <i>[DEBUG]</i>
* @param args The command-line arguments
*/
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: ");
System.out.println("CSSMin [Input file] [Output file] [DEBUG]");
System.out.println("If no output file is specified, stdout will be used.");
return;
}
bDebug = (args.length > 2);
PrintStream out;
if (args.length > 1) {
try {
out = new PrintStream(args[1]);
} catch (Exception e) {
System.err.println("Error outputting to " + args[1] + "; redirecting to stdout");
out = System.out;
}
} else {
out = System.out;
}
formatFile(args[0], out);
}
/**
* Process a file from a filename.
* @param filename The file name of the CSS file to process.
* @param out Where to send the result
*/
public static void formatFile(String filename, OutputStream out) {
try {
formatFile(new FileReader(filename), out);
} catch (java.io.FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
/**
* Process input from a reader.
* @param input Where to read the CSS from
* @param output Where to send the result
*/
public static void formatFile(Reader input, OutputStream out) {
formatFile(input, new PrintStream(out));
}
/**
* Minify CSS from a reader to a printstream.
* @param input Where to read the CSS from
* @param out Where to write the result to
*/
public static void formatFile(Reader input, PrintStream out) {
try {
int k, n;
BufferedReader br = new BufferedReader(input);
StringBuffer sb = new StringBuffer();
if (bDebug) {
System.err.println("Reading file into StringBuffer...");
}
String s;
while ((s = br.readLine()) != null) {
if (s.trim().equals("")) continue;
sb.append(s);
}
if (bDebug) {
System.err.println("Removing comments...");
}
// Find the start of the comment
while ((n = sb.indexOf("/*")) != -1) {
if (sb.charAt(n + 2) == '*') { // Retain special comments
n += 2;
continue;
}
k = sb.indexOf("*/", n + 2);
if (k == -1) {
throw new Exception("Unterminated comment. Aborting.");
}
sb.delete(n, k + 2);
}
if (bDebug) {
System.err.println(sb.toString());
System.err.println("\n\n");
}
if (bDebug) {
System.err.println("Parsing and processing selectors...");
}
Vector<Selector> selectors = new Vector<Selector>();
n = 0;
while ((k = sb.indexOf("}", n)) != -1) {
try {
selectors.addElement(new Selector(sb.substring(n, k + 1)));
} catch (Exception e) {
System.out.println(e.getMessage());
}
n = k + 1;
}
for (Selector selector : selectors) {
out.print(selector.toString());
}
out.print("\r\n");
out.close();
if (bDebug) {
System.err.println("Process completed successfully.");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
class Selector {
private Property[] properties;
private String selector;
/**
* Creates a new Selector using the supplied strings.
* @param selector The selector; for example, "div { border: solid 1px red; color: blue; }"
* @throws Exception If the selector is incomplete and cannot be parsed.
*/
public Selector(String selector) throws Exception {
String[] parts = selector.split("\\{"); // We have to escape the { with a \ for the regex, which itself requires escaping for the string. Sigh.
if (parts.length < 2) {
throw new Exception("Warning: Incomplete selector: " + selector);
}
this.selector = parts[0].trim().replaceAll(", ", ",");
String contents = parts[1].trim();
if (CSSMin.bDebug) {
System.err.println("Parsing selector: " + this.selector);
System.err.println("\t" + contents);
}
if (contents.charAt(contents.length() - 1) != '}') { // Ensure that we have a leading and trailing brace.
throw new Exception("\tUnterminated selector: " + selector);
}
if (contents.length() == 1) {
throw new Exception("\tEmpty selector body: " + selector);
}
contents = contents.substring(0, contents.length() - 2);
this.properties = parseProperties(contents);
sortProperties(this.properties);
}
/**
* Prints out this selector and its contents nicely, with the contents sorted alphabetically.
* @returns A string representing this selector, minified.
*/
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(this.selector).append("{");
for (Property p : this.properties) {
sb.append(p.toString());
}
sb.append("}");
return sb.toString();
}
/**
* Parses out the properties of a selector's body.
* @param contents The body; for example, "border: solid 1px red; color: blue;"
* @returns An array of properties parsed from this selector.
*/
private Property[] parseProperties(String contents) {
ArrayList<String> parts = new ArrayList<String>();
boolean bCanSplit = true;
int j = 0;
String substr;
for (int i = 0; i < contents.length(); i++) {
if (!bCanSplit) { // If we're inside a string
bCanSplit = (contents.charAt(i) == '"');
} else if (contents.charAt(i) == '"') {
bCanSplit = false;
} else if (contents.charAt(i) == ';') {
substr = contents.substring(j, i);
if (!(substr.trim().equals("") || (substr == null))) parts.add(substr);
j = i + 1;
}
}
substr = contents.substring(j, contents.length());
if (!(substr.trim().equals("") || (substr == null))) parts.add(substr);
Property[] results = new Property[parts.size()];
for (int i = 0; i < parts.size(); i++) {
try {
results[i] = new Property(parts.get(i));
} catch (Exception e) {
System.out.println(e.getMessage());
results[i] = null;
}
}
return results;
}
/**
* Sorts the properties array to enhance gzipping.
* @param properties The array to be sorted.
*/
private void sortProperties(Property[] properties) {
Arrays.sort(properties);
}
}
class Property implements Comparable<Property> {
protected String property;
protected Part[] parts;
/**
* Creates a new Property using the supplied strings. Parses out the values of the property selector.
* @param property The property; for example, "border: solid 1px red;" or "-moz-box-shadow: 3px 3px 3px rgba(255, 255, 0, 0.5);".
* @throws Exception If the property is incomplete and cannot be parsed.
*/
public Property(String property) throws Exception {
try {
// Parse the property.
ArrayList<String> parts = new ArrayList<String>();
boolean bCanSplit = true;
int j = 0;
String substr;
if (CSSMin.bDebug) {
System.err.println("\t\tExamining property: " + property);
}
for (int i = 0; i < property.length(); i++) {
if (!bCanSplit) { // If we're inside a string
bCanSplit = (property.charAt(i) == '"');
} else if (property.charAt(i) == '"') {
bCanSplit = false;
} else if (property.charAt(i) == ':') {
substr = property.substring(j, i);
if (!(substr.trim().equals("") || (substr == null))) parts.add(substr);
j = i + 1;
}
}
substr = property.substring(j, property.length());
if (!(substr.trim().equals("") || (substr == null))) parts.add(substr);
if (parts.size() < 2) {
throw new Exception("\t\tWarning: Incomplete property: " + property);
}
this.property = parts.get(0).trim().toLowerCase();
this.parts = parseValues(simplifyRGBColours(parts.get(1).trim().replaceAll(", ", ",")));
} catch (PatternSyntaxException e) {
// Invalid regular expression used.
}
}
/**
* Prints out this property nicely.
* @returns A string representing this property, minified.
*/
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(this.property).append(":");
for (Part p : this.parts) {
sb.append(p.toString()).append(",");
}
sb.deleteCharAt(sb.length() - 1); // Delete the trailing comma.
sb.append(";");
if (CSSMin.bDebug) {
System.err.println(sb.toString());
}
return sb.toString();
}
/**
* Compare this property with another.
*/
public int compareTo(Property other) {
// We can't just use String.compareTo(), because we need to sort properties that have hack prefixes last -- eg, *display should come after display.
String thisProp = (this.property.charAt(0) < 65) ? this.property.substring(1) : this.property;
String thatProp = (other.property.charAt(0) < 65) ? other.property.substring(1) : other.property;
return thisProp.compareTo(thatProp);
}
/**
* Parse the values out of a property.
* @param contents The property to parse
* @returns An array of Parts
*/
private Part[] parseValues(String contents) {
String[] parts = contents.split(",");
Part[] results = new Part[parts.length];
for (int i = 0; i < parts.length; i++) {
try {
results[i] = new Part(parts[i]);
} catch (Exception e) {
System.out.println(e.getMessage());
results[i] = null;
}
}
return results;
}
// Convert rgb(51,102,153) to #336699 (this code largely based on YUI code)
private String simplifyRGBColours(String contents) {
StringBuffer newContents = new StringBuffer();
StringBuffer hexColour;
String[] rgbColours;
int colourValue;
Pattern pattern = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
Matcher matcher = pattern.matcher(contents);
while (matcher.find()) {
hexColour = new StringBuffer("
rgbColours = matcher.group(1).split(",");
for (int i = 0; i < rgbColours.length; i++) {
colourValue = Integer.parseInt(rgbColours[i]);
if (colourValue < 16) {
hexColour.append("0");
}
hexColour.append(Integer.toHexString(colourValue));
}
matcher.appendReplacement(newContents, hexColour.toString());
}
matcher.appendTail(newContents);
return newContents.toString();
}
}
class Part {
String contents;
/**
* Create a new property by parsing the given string.
* @param contents The string to parse.
* @throws Exception If the part cannot be parsed.
*/
public Part(String contents) throws Exception {
// Many of these regular expressions are adapted from those used in the YUI CSS Compressor.
// For simpler regexes.
this.contents = " " + contents;
simplify();
}
private void simplify() {
// Replace 0in, 0cm, etc. with just 0
this.contents = this.contents.replaceAll("(\\s)(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0.6 with .6
this.contents = this.contents.replaceAll("(\\s)0+\\.(\\d+)", "$1.$2");
this.contents = this.contents.trim();
// Simplify multiple zeroes
if (this.contents.equals("0 0 0 0")) this.contents = "0";
if (this.contents.equals("0 0 0")) this.contents = "0";
if (this.contents.equals("0 0")) this.contents = "0";
simplifyHexColours();
}
private void simplifyHexColours() {
StringBuffer newContents = new StringBuffer();
Pattern pattern = Pattern.compile("#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
Matcher matcher = pattern.matcher(this.contents);
while (matcher.find()) {
if (matcher.group(1).equalsIgnoreCase(matcher.group(2)) && matcher.group(3).equalsIgnoreCase(matcher.group(4)) && matcher.group(5).equalsIgnoreCase(matcher.group(6))) {
matcher.appendReplacement(newContents, "#" + matcher.group(1).toLowerCase() + matcher.group(3).toLowerCase() + matcher.group(5).toLowerCase());
} else {
matcher.appendReplacement(newContents, matcher.group().toLowerCase());
}
}
matcher.appendTail(newContents);
this.contents = newContents.toString();
}
/**
* Returns itself.
* @returns this part's string representation.
*/
public String toString() {
return this.contents;
}
}
|
package com.j256.ormlite.dao;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.FieldType;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.GenericRowMapper;
import com.j256.ormlite.stmt.PreparedDelete;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.PreparedUpdate;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.SelectArg;
import com.j256.ormlite.stmt.UpdateBuilder;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.support.DatabaseConnection;
import com.j256.ormlite.support.DatabaseResults;
import com.j256.ormlite.table.ObjectFactory;
/**
* The definition of the Database Access Objects that handle the reading and writing a class from the database. Kudos to
* Robert A. for the general concept of this hierarchy.
*
* @param <T>
* The class that the code will be operating on.
* @param <ID>
* The class of the ID column associated with the class. The T class does not require an ID field. The class
* needs an ID parameter however so you can use Void or Object to satisfy the compiler.
* @author graywatson
*/
public interface Dao<T, ID> extends CloseableIterable<T> {
/**
* Retrieves an object associated with a specific ID.
*
* @param id
* Identifier that matches a specific row in the database to find and return.
* @return The object that has the ID field which equals id or null if no matches.
* @throws SQLException
* on any SQL problems or if more than 1 item with the id are found in the database.
*/
public T queryForId(ID id) throws SQLException;
/**
* Query for and return the first item in the object table which matches the PreparedQuery. See
* {@link #queryBuilder()} for more information. This can be used to return the object that matches a single unique
* column. You should use {@link #queryForId(Object)} if you want to query for the id column.
*
* @param preparedQuery
* Query used to match the objects in the database.
* @return The first object that matches the query.
* @throws SQLException
* on any SQL problems.
*/
public T queryForFirst(PreparedQuery<T> preparedQuery) throws SQLException;
/**
* Query for all of the items in the object table. For medium sized or large tables, this may load a lot of objects
* into memory so you should consider using the {@link #iterator()} method instead.
*
* @return A list of all of the objects in the table.
* @throws SQLException
* on any SQL problems.
*/
public List<T> queryForAll() throws SQLException;
/**
* Query for the items in the object table that match a simple where with a single field = value type of WHERE
* clause. This is a convenience method for calling queryBuilder().where().eq(fieldName, value).query().
*
* @return A list of the objects in the table that match the fieldName = value;
* @throws SQLException
* on any SQL problems.
*/
public List<T> queryForEq(String fieldName, Object value) throws SQLException;
/**
* Query for the rows in the database that match the object passed in as a parameter. Any fields in the matching
* object that are not the default value (null, false, 0, 0.0, etc.) are used as the matching parameters with AND.
* If you are worried about SQL quote escaping, you should use {@link #queryForMatchingArgs(Object)}.
*/
public List<T> queryForMatching(T matchObj) throws SQLException;
/**
* Same as {@link #queryForMatching(Object)} but this uses {@link SelectArg} and SQL ? arguments. This is slightly
* more expensive but you don't have to worry about SQL quote escaping.
*/
public List<T> queryForMatchingArgs(T matchObj) throws SQLException;
/**
* Query for the rows in the database that matches all of the field to value entries from the map passed in. If you
* are worried about SQL quote escaping, you should use {@link #queryForFieldValuesArgs(Map)}.
*/
public List<T> queryForFieldValues(Map<String, Object> fieldValues) throws SQLException;
/**
* Same as {@link #queryForFieldValues(Map)} but this uses {@link SelectArg} and SQL ? arguments. This is slightly
* more expensive but you don't have to worry about SQL quote escaping.
*/
public List<T> queryForFieldValuesArgs(Map<String, Object> fieldValues) throws SQLException;
/**
* Query for a data item in the table that has the same id as the data parameter.
*/
public T queryForSameId(T data) throws SQLException;
/**
* Create and return a new query builder object which allows you to build a custom SELECT statement. You call
* methods on the builder to construct your statement and then call {@link QueryBuilder#prepare()} once you are
* ready to build. This returns a {@link PreparedQuery} object which gets passed to {@link #query(PreparedQuery)} or
* {@link #iterator(PreparedQuery)}.
*/
public QueryBuilder<T, ID> queryBuilder();
/**
* Like {@link #queryBuilder()} but allows you to build an UPDATE statement. You can then call call
* {@link UpdateBuilder#prepare()} and pass the returned {@link PreparedUpdate} to {@link #update(PreparedUpdate)}.
*/
public UpdateBuilder<T, ID> updateBuilder();
/**
* Like {@link #queryBuilder()} but allows you to build an DELETE statement. You can then call call
* {@link DeleteBuilder#prepare()} and pass the returned {@link PreparedDelete} to {@link #delete(PreparedDelete)}.
*/
public DeleteBuilder<T, ID> deleteBuilder();
/**
* Query for the items in the object table which match the prepared query. See {@link #queryBuilder} for more
* information.
*
* <p>
* <b>NOTE:</b> For medium sized or large tables, this may load a lot of objects into memory so you should consider
* using the {@link #iterator(PreparedQuery)} method instead.
* </p>
*
* @param preparedQuery
* Query used to match the objects in the database.
* @return A list of all of the objects in the table that match the query.
* @throws SQLException
* on any SQL problems.
*/
public List<T> query(PreparedQuery<T> preparedQuery) throws SQLException;
/**
* Create a new row in the database from an object. If the object being created uses
* {@link DatabaseField#generatedId()} then the data parameter will be modified and set with the corresponding id
* from the database.
*
* @param data
* The data item that we are creating in the database.
* @return The number of rows updated in the database. This should be 1.
*/
public int create(T data) throws SQLException;
/**
* This is a convenience method to creating a data item but only if the ID does not already exist in the table. This
* extracts the id from the data parameter, does a {@link #queryForId(Object)} on it, returning the data if it
* exists. If it does not exist {@link #create(Object)} will be called with the parameter.
*
* @return Either the data parameter if it was inserted (now with the ID field set via the create method) or the
* data element that existed already in the database.
*/
public T createIfNotExists(T data) throws SQLException;
/**
* This is a convenience method for creating an item in the database if it does not exist. The id is extracted from
* the data parameter and a query-by-id is made on the database. If a row in the database with the same id exists
* then all of the columns in the database will be updated from the fields in the data parameter. If the id is null
* (or 0 or some other default value) or doesn't exist in the database then the object will be created in the
* database. This also means that your data item <i>must</i> have an id field defined.
*
* @return Status object with the number of rows changed and whether an insert or update was performed.
*/
public CreateOrUpdateStatus createOrUpdate(T data) throws SQLException;
public int update(T data) throws SQLException;
/**
* Update the data parameter in the database to change its id to the newId parameter. The data <i>must</i> have its
* current (old) id set. If the id field has already changed then it cannot be updated. After the id has been
* updated in the database, the id field of the data parameter will also be changed.
*
* <p>
* <b>NOTE:</b> Depending on the database type and the id type, you may be unable to change the id of the field.
* </p>
*
* @param data
* The data item that we are updating in the database with the current id.
* @param newId
* The <i>new</i> id that you want to update the data with.
* @return The number of rows updated in the database. This should be 1.
* @throws SQLException
* on any SQL problems.
*/
public int updateId(T data, ID newId) throws SQLException;
public int update(PreparedUpdate<T> preparedUpdate) throws SQLException;
/**
* Does a query for the data parameter's id and copies in each of the field values from the database to refresh the
* data parameter. Any local object changes to persisted fields will be overwritten. If the database has been
* updated this brings your local object up to date.
*
* @param data
* The data item that we are refreshing with fields from the database.
* @return The number of rows found in the database that correspond to the data id. This should be 1.
* @throws SQLException
* on any SQL problems or if the data item is not found in the table or if more than 1 item is found
* with data's id.
*/
public int refresh(T data) throws SQLException;
/**
* Delete the database row corresponding to the id from the data parameter.
*
* @param data
* The data item that we are deleting from the database.
* @return The number of rows updated in the database. This should be 1.
* @throws SQLException
* on any SQL problems.
*/
public int delete(T data) throws SQLException;
/**
* Delete an object from the database that has an id.
*
* @param id
* The id of the item that we are deleting from the database.
* @return The number of rows updated in the database. This should be 1.
* @throws SQLException
* on any SQL problems.
*/
public int deleteById(ID id) throws SQLException;
/**
* Delete a collection of objects from the database using an IN SQL clause. The ids are extracted from the datas
* parameter and used to remove the corresponding rows in the database with those ids.
*
* @param datas
* A collection of data items to be deleted.
* @return The number of rows updated in the database. This should be the size() of the collection.
* @throws SQLException
* on any SQL problems.
*/
public int delete(Collection<T> datas) throws SQLException;
/**
* Delete the objects that match the collection of ids from the database using an IN SQL clause.
*
* @param ids
* A collection of data ids to be deleted.
* @return The number of rows updated in the database. This should be the size() of the collection.
* @throws SQLException
* on any SQL problems.
*/
public int deleteIds(Collection<ID> ids) throws SQLException;
/**
* Delete the objects that match the prepared statement parameter.
*
* @param preparedDelete
* A prepared statement to match database rows to be deleted.
* @return The number of rows updated in the database.
* @throws SQLException
* on any SQL problems.
*/
public int delete(PreparedDelete<T> preparedDelete) throws SQLException;
public CloseableIterator<T> iterator();
/**
* Same as {@link #iterator()} but while specifying flags for the results. This is necessary with certain database
* types. The resultFlags could be something like ResultSet.TYPE_SCROLL_INSENSITIVE or other values.
*
* <p>
* <b>WARNING:</b> Depending on the database type the underlying connection may never be freed -- even if you go all
* of the way through the results. It is <i>strongly</i> recommended that you call the
* {@link CloseableIterator#close()} method when you are done with the iterator.
* </p>
*/
public CloseableIterator<T> iterator(int resultFlags);
/**
* Same as {@link #iterator()} but with a prepared query parameter. See {@link #queryBuilder} for more information.
* You use it like the following:
*
* <p>
* <blockquote>
*
* <pre>
* QueryBuilder<Account, String> qb = accountDao.queryBuilder();
* ... custom query builder methods
* CloseableIterator<Account> iterator = partialDao.iterator(qb.prepare());
* try {
* while (iterator.hasNext()) {
* Account account = iterator.next();
* ...
* }
* } finish {
* iterator.close();
* }
* </pre>
*
* </blockquote>
* </p>
*
* @param preparedQuery
* Query used to iterate across a sub-set of the items in the database.
* @return An iterator for T.
* @throws SQLException
* on any SQL problems.
*/
public CloseableIterator<T> iterator(PreparedQuery<T> preparedQuery) throws SQLException;
/**
* Same as {@link #iterator(PreparedQuery)} but while specifying flags for the results. This is necessary with
* certain database types.
*/
public CloseableIterator<T> iterator(PreparedQuery<T> preparedQuery, int resultFlags) throws SQLException;
/**
* This makes a one time use iterable class that can be closed afterwards. The DAO itself is
* {@link CloseableWrappedIterable} but multiple threads can each call this to get their own closeable iterable.
* This allows you to do something like:
*
* <blockquote>
*
* <pre>
* CloseableWrappedIterable<Foo> wrappedIterable = fooDao.getWrappedIterable();
* try {
* for (Foo foo : wrappedIterable) {
* ...
* }
* } finally {
* wrappedIterable.close();
* }
* </pre>
*
* </blockquote>
*/
public CloseableWrappedIterable<T> getWrappedIterable();
/**
* Same as {@link #getWrappedIterable()} but with a prepared query parameter. See {@link #queryBuilder} or
* {@link #iterator(PreparedQuery)} for more information.
*/
public CloseableWrappedIterable<T> getWrappedIterable(PreparedQuery<T> preparedQuery);
/**
* This closes the last iterator returned by the {@link #iterator()} method.
*
* <p>
* <b>NOTE:</b> This is not reentrant. If multiple threads are getting iterators from this DAO then you should use
* the {@link #getWrappedIterable()} method to get a wrapped iterable for each thread instead.
* </p>
*/
public void closeLastIterator() throws SQLException;
/**
* Similar to the {@link #iterator(PreparedQuery)} except it returns a GenericRawResults object associated with the
* SQL select query argument. Although you should use the {@link #iterator()} for most queries, this method allows
* you to do special queries that aren't supported otherwise. Like the above iterator methods, you must call close
* on the returned RawResults object once you are done with it. The arguments are optional but can be set with
* strings to expand ? type of SQL.
*
* <p>
* You can use the {@link QueryBuilder#prepareStatementString()} method here if you want to build the query using
* the structure of the QueryBuilder.
* </p>
*
* <p>
*
* <pre>
* QueryBuilder<Account, Integer> qb = accountDao.queryBuilder();
* qb.where().ge("orderCount", 10);
* results = accountDao.queryRaw(qb.prepareStatementString());
* </pre>
*
* </p>
*
* If you want to use the QueryBuilder with arguments to the raw query then you should do something like:
*
* <p>
*
* <pre>
* QueryBuilder<Account, Integer> qb = accountDao.queryBuilder();
* // we specify a SelectArg here to generate a ? in the statement string below
* qb.where().ge("orderCount", new SelectArg());
* // the 10 at the end is an optional argument to fulfill the SelectArg above
* results = accountDao.queryRaw(qb.prepareStatementString(), rawRowMapper, 10);
* </pre>
*
* </p>
*
* <p>
* <b>NOTE:</b> If you are using the {@link QueryBuilder#prepareStatementString()} to build your query, it may have
* added the id column to the selected column list if the Dao object has an id you did not include it in the columns
* you selected. So the results might have one more column than you are expecting.
* </p>
*/
public GenericRawResults<String[]> queryRaw(String query, String... arguments) throws SQLException;
/**
* Similar to the {@link #queryRaw(String, String...)} but this iterator returns rows that you can map yourself. For
* every result that is returned by the database, the {@link RawRowMapper#mapRow(String[], String[])} method is
* called so you can convert the result columns into an object to be returned by the iterator. The arguments are
* optional but can be set with strings to expand ? type of SQL. For a simple implementation of a raw row mapper,
* see {@link #getRawRowMapper()}.
*/
public <UO> GenericRawResults<UO> queryRaw(String query, RawRowMapper<UO> mapper, String... arguments)
throws SQLException;
/**
* Similar to the {@link #queryRaw(String, RawRowMapper, String...)} but uses the column-types array to present an
* array of object results to the mapper instead of strings. The arguments are optional but can be set with strings
* to expand ? type of SQL.
*/
public <UO> GenericRawResults<UO> queryRaw(String query, DataType[] columnTypes, RawRowObjectMapper<UO> mapper,
String... arguments) throws SQLException;
/**
* Similar to the {@link #queryRaw(String, String...)} but instead of an array of String results being returned by
* the iterator, this uses the column-types parameter to return an array of Objects instead. The arguments are
* optional but can be set with strings to expand ? type of SQL.
*/
public GenericRawResults<Object[]> queryRaw(String query, DataType[] columnTypes, String... arguments)
throws SQLException;
/**
* Perform a raw query that returns a single value (usually an aggregate function like MAX or COUNT). If the query
* does not return a single long value then it will throw a SQLException.
*/
public long queryRawValue(String query, String... arguments) throws SQLException;
/**
* Run a raw execute SQL statement to the database. The arguments are optional but can be set with strings to expand
* ? type of SQL. If you have no arguments, you may want to call {@link #executeRawNoArgs(String)}.
*
* @return number of rows affected.
*/
public int executeRaw(String statement, String... arguments) throws SQLException;
/**
* Run a raw execute SQL statement on the database without any arguments. This may use a different mechanism to
* execute the query depending on the database backend.
*
* @return number of rows affected.
*/
public int executeRawNoArgs(String statement) throws SQLException;
/**
* Run a raw update SQL statement to the database. The statement must be an SQL INSERT, UPDATE or DELETE
* statement.The arguments are optional but can be set with strings to expand ? type of SQL.
*
* @return number of rows affected.
*/
public int updateRaw(String statement, String... arguments) throws SQLException;
/**
* Call the call-able that will perform a number of batch tasks. This is for performance when you want to run a
* number of database operations at once -- maybe loading data from a file. This will turn off what databases call
* "auto-commit" mode, run the call-able, and then re-enable "auto-commit". If auto-commit is not supported then a
* transaction will be used instead.
*
* <p>
* <b>NOTE:</b> If neither auto-commit nor transactions are supported by the database type then this may just call
* the callable. Also, "commit()" is <i>not</i> called on the connection at all. If "auto-commit" is disabled then
* this will leave it off and nothing will have been persisted.
* </p>
*/
public <CT> CT callBatchTasks(Callable<CT> callable) throws Exception;
/**
* Return the string version of the object with each of the known field values shown. Useful for testing and
* debugging.
*
* @param data
* The data item for which we are returning the toString information.
*/
public String objectToString(T data);
/**
* Return true if the two parameters are equal. This checks each of the fields defined in the database to see if
* they are equal. Useful for testing and debugging.
*
* @param data1
* One of the data items that we are checking for equality.
* @param data2
* The other data item that we are checking for equality.
*/
public boolean objectsEqual(T data1, T data2) throws SQLException;
/**
* Returns the ID from the data parameter passed in. This is used by some of the internal queries to be able to
* search by id.
*/
public ID extractId(T data) throws SQLException;
/**
* Returns the class of the DAO. This is used by internal query operators.
*/
public Class<T> getDataClass();
/**
* Returns the class of the DAO. This is used by internal query operators.
*/
public FieldType findForeignFieldType(Class<?> clazz);
/**
* Returns true if we can call update on this class. This is used most likely by folks who are extending the base
* dao classes.
*/
public boolean isUpdatable();
/**
* Returns true if the table already exists otherwise false.
*/
public boolean isTableExists() throws SQLException;
/**
* Returns the number of rows in the table associated with the data class. Depending on the size of the table and
* the database type, this may be expensive and take a while.
*/
public long countOf() throws SQLException;
/**
* Returns the number of rows in the table associated with the prepared query passed in. Depending on the size of
* the table and the database type, this may be expensive and take a while.
*/
public long countOf(PreparedQuery<T> preparedQuery) throws SQLException;
/**
* Creates an empty collection and assigns it to the appropriate field in the parent object. This allows you to add
* things to the collection from the start.
*
* For example let's say you have an Account which has the field:
*
* <pre>
* @ForeignCollectionField(columnName = "orders")
* Collection<Order> orders;
* </pre>
*
* You would then call:
*
* <pre>
* accoundDao.assignEmptyForeignCollection(account, "orders");
* // this would add it the collection and the internal DAO
* account.orders.add(order1);
* </pre>
*
* @param parent
* Parent object that will be associated with all items added to this collection if not already assigned.
* @param fieldName
* parameter is the field name of the foreign collection field -- you might consider using the
* {@link ForeignCollectionField#columnName()} to set the name to a static name.
*/
public void assignEmptyForeignCollection(T parent, String fieldName) throws SQLException;
/**
* Like {@link #assignEmptyForeignCollection(Object, String)} but it returns the empty collection that you assign to
* the appropriate field.
*
* <p>
* <b>NOTE:</b> May be deprecated in the future.
* </p>
*/
public <FT> ForeignCollection<FT> getEmptyForeignCollection(String fieldName) throws SQLException;
/**
* Call this with true to enable an object cache for the DAO. Set to false to disable any caching. It is (as of
* 9/2011) one of the newer features of ORMLite. It keeps a {@link ReferenceObjectCache} of the objects (using
* {@link WeakReference}) referenced by the DAO. No support for objects returned by the {@link #queryRaw} methods.
*
* @throws SQLException
* If the DAO's class does not have an id field which is required by the {@link ObjectCache}.
*/
public void setObjectCache(boolean enabled) throws SQLException;
/**
* Same as {@link #setObjectCache(boolean)} except you specify the actual cache instance to use for the DAO. This
* allows you to use a {@link ReferenceObjectCache} with {@link SoftReference} setting, the {@link LruObjectCache},
* or inject your own cache implementation. Call it with null to disable the cache.
*
* @throws SQLException
* If the DAO's class does not have an id field which is required by the {@link ObjectCache}.
*/
public void setObjectCache(ObjectCache objectCache) throws SQLException;
/**
* Returns the current object-cache being used by the DAO or null if none.
*/
public ObjectCache getObjectCache();
/**
* Flush the object cache if it has been enabled. This will remove an objects that are in the cache to reclaim
* memory. Any future queries will re-request them from the database.
*/
public void clearObjectCache();
/**
* Return the latest row from the database results from a query to select * (star).
*/
public T mapSelectStarRow(DatabaseResults results) throws SQLException;
/**
* Return a row mapper that is suitable for mapping results from a query to select * (star).
*/
public GenericRowMapper<T> getSelectStarRowMapper() throws SQLException;
/**
* Return a row mapper that is suitable for use with {@link #queryRaw(String, RawRowMapper, String...)}. This is a
* bit experimental at this time. It most likely will _not_ work with all databases since the string output for each
* data type is hard to forecast. Please provide feedback.
*/
public RawRowMapper<T> getRawRowMapper();
/**
* Returns true if an object exists that matches this ID otherwise false.
*/
public boolean idExists(ID id) throws SQLException;
/**
* <p>
* <b>WARNING:</b> This method is for advanced users only. It is only to support the
* {@link #setAutoCommit(DatabaseConnection, boolean)} and other methods below. Chances are you should be using the
* {@link #callBatchTasks(Callable)} instead of this method unless you know what you are doing.
* </p>
*
* <p>
* This allocates a connection for this specific thread that will be used in all other DAO operations. The thread
* <i>must</i> call {@link #endThreadConnection(DatabaseConnection)} once it is done with the connection. It is
* highly recommended that a
* <code>try { conn = dao.startThreadConnection(); ... } finally { dao.endThreadConnection(conn); }</code> type of
* pattern be used here to ensure you do not leak connections.
* </p>
*/
public DatabaseConnection startThreadConnection() throws SQLException;
/**
* <p>
* <b>WARNING:</b> This method is for advanced users only. It is only to support the
* {@link #setAutoCommit(DatabaseConnection, boolean)} and other methods below. Chances are you should be using the
* {@link #callBatchTasks(Callable)} instead of this method unless you know what you are doing.
* </p>
*
* <p>
* This method is used to free the connection returned by the {@link #startThreadConnection()} above.
* </p>
*
* @param connection
* Connection to be freed. If null then it will be a no-op.
*/
public void endThreadConnection(DatabaseConnection connection) throws SQLException;
/**
* @deprecated You should use the {@link #setAutoCommit(DatabaseConnection, boolean)} method instead.
*/
@Deprecated
public void setAutoCommit(boolean autoCommit) throws SQLException;
/**
* Set auto-commit mode to be true or false on the connection returned by the {@link #startThreadConnection()}. This
* may not be supported by all database types.
*
* <p>
* <b>WARNING:</b> Chances are you should be using the {@link #callBatchTasks(Callable)} instead of this method
* unless you know what you are doing.
* </p>
*/
public void setAutoCommit(DatabaseConnection connection, boolean autoCommit) throws SQLException;
/**
* @deprecated You should use the {@link #isAutoCommit(DatabaseConnection)} method instead.
*/
@Deprecated
public boolean isAutoCommit() throws SQLException;
/**
* Return true if the database connection returned by the {@link #startThreadConnection()} is in auto-commit mode
* otherwise false. This may not be supported by all database types.
*/
public boolean isAutoCommit(DatabaseConnection connection) throws SQLException;
/**
* If you have previously set auto-commit to false using {@link #setAutoCommit(DatabaseConnection, boolean)} then
* this will commit all changes to the database made from that point up to now on the connection returned by the
* {@link #startThreadConnection()}. The changes will be written to the database and discarded. The connection will
* continue to stay in the current auto-commit mode.
*
* <p>
* <b>WARNING:</b> Chances are you should be using the {@link #callBatchTasks(Callable)} instead of this method
* unless you know what you are doing.
* </p>
*/
public void commit(DatabaseConnection connection) throws SQLException;
/**
* If you have previously set auto-commit to false using {@link #setAutoCommit(DatabaseConnection, boolean)} then
* this will roll-back and flush all changes to the database made from that point up to now on the connection
* returned by the {@link #startThreadConnection()} . None of those changes will be written to the database and are
* discarded. The connection will continue to stay in the current auto-commit mode.
*
* <p>
* <b>WARNING:</b> Chances are you should be using the {@link #callBatchTasks(Callable)} instead of this method
* unless you know what you are doing.
* </p>
*/
public void rollBack(DatabaseConnection connection) throws SQLException;
/**
* Return the associated ConnectionSource or null if none set on the DAO yet.
*/
public ConnectionSource getConnectionSource();
/**
* Set an object factory so we can wire in controls over an object when it is constructed. Set to null to disable
* the factory.
*/
public void setObjectFactory(ObjectFactory<T> objectFactory);
/**
* Return class for the {@link Dao#createOrUpdate(Object)} method.
*/
public static class CreateOrUpdateStatus {
private boolean created;
private boolean updated;
private int numLinesChanged;
public CreateOrUpdateStatus(boolean created, boolean updated, int numberLinesChanged) {
this.created = created;
this.updated = updated;
this.numLinesChanged = numberLinesChanged;
}
public boolean isCreated() {
return created;
}
public boolean isUpdated() {
return updated;
}
public int getNumLinesChanged() {
return numLinesChanged;
}
}
}
|
package com.watcher;
import java.util.Scanner;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class ProcessWatch extends Thread {
private Process process = null;
private boolean running = true;
private boolean over;
private Lock lock;
private Condition condition;
ProcessWatch(){
super();
over = false;
lock = new ReentrantLock();
condition = lock.newCondition();
}
boolean isRunning(){
return running;
}
@Override
public void run() {
try{
while (isRunning()){
refresh();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
private void refresh() throws InterruptedException{
lock.lockInterruptibly();
try{
if(process == null)
condition.await();
Scanner scanner = new Scanner(process.getInputStream());
while(true){
if(over)
break;
String before = null;
while(scanner.hasNext()){
String temp = scanner.nextLine();
if(before == null || !temp.equals(before)){
System.out.println(temp);
before = temp;
}
}
}
} finally {
lock.unlock();
}
}
void close(){
running = false;
interrupt();
}
void setOver(boolean over) {
this.over = over;
this.process = null;
}
void setProcess(Process process) throws InterruptedException {
lock.lockInterruptibly();
try {
this.process = process;
this.over = false;
condition.signal();
} finally {
lock.unlock();
}
}
}
|
package coyote.loader.cfg;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import coyote.commons.StringUtil;
import coyote.commons.UriUtil;
import coyote.dataframe.DataField;
import coyote.dataframe.DataFrame;
import coyote.dataframe.marshal.JSONMarshaler;
/**
* The Config class models a component that is used to make file-based
* configuration of components easier than using property files.
*
* <p>The primary goal of this class is to allow hierarchical configurations to
* be specified using different notations (such as JSON) as a formatting
* strategy. Basic File and network protocol I/O is supported in a simple
* interface.</p>
*/
public class Config extends DataFrame implements Cloneable, Serializable {
public static final String CLASS = "Config";
// Common configuration tags
public static final String CLASS_TAG = "Class";
public static final String NAME_TAG = "Name";
public static final String ID_TAG = "ID";
/** Serialization identifier */
private static final long serialVersionUID = -6020161245846637528L;
/**
* A collection of ConfigSlots we use to optionally validate the completeness
* of the Config object or to provide default configurations.
*/
private HashMap<String, ConfigSlot> slots = null;
public Config() {}
/**
*
* @param file
*
* @return TODO Complete Documentation
*
* @throws IOException
* @throws ConfigurationException
*/
public static Config read( final File file ) throws IOException, ConfigurationException {
return Config.read( new FileInputStream( file ) );
}
/**
* Read the data from the given input stream and create an object from the
* data read.
*
* <p>This assumes a UTF-8 JSON formatted stream of bytes.</p>
*
* @param configStream the input stream from which to read
*
* @return a configuration filled with the
*
* @throws ConfigurationException if there were issues creating a configuration object from the data read in from the stream.
*/
public static Config read( final InputStream configStream ) throws ConfigurationException {
final Config retval = new Config();
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ( ( bytesRead = configStream.read( buffer ) ) != -1 ) {
output.write( buffer, 0, bytesRead );
}
} catch ( IOException e ) {
throw new ConfigurationException( "Could not read configuration stream", e );
}
String data = null;
try {
data = new String( output.toByteArray(), "UTF-8" );
} catch ( UnsupportedEncodingException e ) {
throw new ConfigurationException( "Could not read UTF-8", e );
}
if ( data != null ) {
List<DataFrame> config = JSONMarshaler.marshal( data );
if ( config.get( 0 ) != null ) {
retval.populate( config.get( 0 ) );
}
}
return retval;
}
/**
*
* @param filename
*
* @return TODO Complete Documentation
*
* @throws IOException
* @throws ConfigurationException
*/
public static Config read( final String filename ) throws IOException, ConfigurationException {
return Config.read( new FileInputStream( filename ) );
}
/**
*
* @param uri
*
* @return TODO Complete Documentation
*
* @throws IOException
* @throws ConfigurationException
*/
public static Config read( final URI uri ) throws IOException, ConfigurationException {
if ( StringUtil.isNotBlank( uri.getScheme() ) ) {
if ( uri.getScheme().toLowerCase().startsWith( "file" ) ) {
return Config.read( new FileInputStream( UriUtil.getFile( uri ) ) );
} else {
return Config.read( uri.toURL().openStream() );
}
} else {
// Assume this is a file path
return Config.read( new FileInputStream( uri.toString() ) );
}
}
/**
* Add the referenced ConfigSlot.
*
* @param slot the reference to the ConfigSlot to add.
*/
public void addConfigSlot( final ConfigSlot slot ) {
if ( slots == null ) {
slots = new HashMap();
}
if ( slot != null ) {
slots.put( slot.getName(), slot );
}
}
/**
* Return an Iterator over all the ConfigSlots
*
* @return an Iterator over all the ConfigSlot, never returns null;
*/
public Iterator<ConfigSlot> configSlotIterator() {
if ( slots != null ) {
return slots.values().iterator();
} else {
return new Vector().iterator();
}
}
/**
* Retrieve a named ConfigSlot from the configuration
*
* @param name String which represents the name of the slot to retrieve
*
* @return value ConfigSlot object with the given name or null if it does
* not exist
*/
public ConfigSlot getConfigSlot( final String name ) {
if ( slots != null ) {
synchronized( slots ) {
return (ConfigSlot)slots.get( name );
}
} else {
return null;
}
}
/**
* Access the current number of elements set in this configuration.
*
* @return number of named values in this configuration
*/
public int getElementCount() {
return fields.size();
}
/**
* @return the id
*/
public String getId() {
return getAsString( ID_TAG );
}
/**
* @param id the id to set
*/
public void setId( final String id ) {
this.put( ID_TAG, id );
}
/**
* @return the name
*/
public String getName() {
return getAsString( NAME_TAG );
}
/**
* @param name the name to set
*/
public void setName( final String name ) {
this.put( NAME_TAG, name );
}
/**
* @return the class
*/
public String getClassName() {
return getAsString( CLASS_TAG );
}
/**
* @param name the class name to set
*/
public void setClassName( final String name ) {
put( Config.CLASS_TAG, name );
}
/**
* Remove the referenced ConfigSlot
*
* @param slot The reference to the ConfigSlot to remove.
*/
public void removeConfigSlot( final ConfigSlot slot ) {
if ( slots == null ) {
return;
} else {
synchronized( slots ) {
slots.remove( slot );
}
}
}
/**
* Use the set configuration slots and prime the configuration with those
* defaults.
*
* <p>This allows the caller to set a configuration object to the defaults.
* This is useful a a starting point for configurable components when a
* configuration has not been provided.</p>
*/
public void setDefaults() {
final Iterator<ConfigSlot> it = configSlotIterator();
while ( it.hasNext() ) {
final ConfigSlot slot = (ConfigSlot)it.next();
if ( slot != null ) {
final String defaultValue = slot.getDefaultValue();
if ( defaultValue != null ) {
put( slot.getName(), defaultValue );
}
}
}
}
/**
* Return all the configuration sections with the given name.
*
* <p>This performs a case-insensitive search for the sections.</p>
*
* @param tag The name of the section for which to search
*
* @return The list of sections with a matching name. May be empty, but never null;
*/
public List<Config> getSections( String tag ) {
List<Config> retval = new ArrayList<Config>();
// If we have a tag for which to search...
if ( StringUtil.isNotBlank( tag ) ) {
// Look for the class to load
for ( DataField field : getFields() ) {
if ( tag.equalsIgnoreCase( field.getName() ) && field.isFrame() ) {
Config cfg = new Config();
cfg.populate( (DataFrame)field.getObjectValue() );
retval.add( cfg );
} // name match && a frame
} // for
} // tag != null
// return what we have found
return retval;
}
/**
* Return all the configuration sections within this section
*
* <p>This will not return scalar attributes, just the embedded sections.</p>
*
* @return The list of sections. May be empty, but never null;
*/
public List<Config> getSections() {
List<Config> retval = new ArrayList<Config>();
// Look for the class to load
for ( DataField field : getFields() ) {
if ( field.isFrame() ) {
Config cfg = new Config();
cfg.populate( (DataFrame)field.getObjectValue() );
retval.add( cfg );
} // name match && a frame
} // for
// return what we have found
return retval;
}
/**
* Perform a case insensitive search for the first value with the given name.
*
* @param tag the name of the configuration attribute for which to search
*
* @return the first value with the given name as a string or null if not
* configuration field with that name was found, or if the found
* field contained a null value.
*/
public String getString( String tag ) {
// If we have a tag for which to search...
if ( StringUtil.isNotBlank( tag ) ) {
// Look for the class to load
for ( DataField field : getFields() ) {
if ( tag.equalsIgnoreCase( field.getName() ) ) {
return field.getStringValue();
} // name match && a frame
} // for
} // tag != null
// If we got here, there was nothing which matched the given tag
return null;
}
}
|
package de.craften.util;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import de.craften.craftenlauncher.logic.Logger;
/**
* Simple OS Helper determines the current OS and cpu architecture.
*
* @author evidence
* @author redbeard
*/
public final class OSHelper {
private static String operatingSystem;
private static OSHelper instance;
private static String pS = File.separator;
private static String[] mOsArch32 = {"x86", "i386", "i686"}, //32-bit
mOsArch64 = {"x64", "ia64", "amd64"}; //64-bit
/**
* Returns a new OSHelper instance.
* @return
*/
public synchronized static OSHelper getInstance() {
if (instance == null) {
instance = new OSHelper();
}
return instance;
}
/**
* Returns a new OSHelper instance for testing purposes.
* @return
*/
public static OSHelper TEST_CreateInstance() {
return new OSHelper();
}
private OSHelper() {
operatingSystem = System.getProperty("os.name");
if (operatingSystem.contains("Win")) {
operatingSystem = "windows";
} else if (operatingSystem.contains("Linux")) {
operatingSystem = "linux";
} else if (operatingSystem.contains("Mac")) {
operatingSystem = "osx";
}
}
/**
* Returns true if Java is running in x86 (32 bit) version.
* @return
*/
public boolean isJava32bit(){
String archInfo = System.getProperty("os.arch");
if (archInfo != null && !archInfo.equals("")) {
for (String aMOsArch32 : mOsArch32) {
if (archInfo.equals(aMOsArch32)) {
return true;
}
}
}
return false;
}
/**
* Returns true if Java is running in x64 (64 bit) version.
* @return
*/
public boolean isJava64bit(){
String archInfo = System.getProperty("os.arch");
if (archInfo != null && !archInfo.equals("")) {
for (String aMOsArch64 : mOsArch64) {
if (archInfo.equals(aMOsArch64)) {
return true;
}
}
}
return false;
}
/**
* Returns the OS processor architecture.
* @return 32 or 64
*/
public String getOSArch(){
String arch = System.getenv("PROCESSOR_ARCHITECTURE");
String wow64Arch = System.getenv("PROCESSOR_ARCHITEW6432");
String realArch = null;
if(arch != null) {
if(arch.endsWith("64") || wow64Arch != null && wow64Arch.endsWith("64")) {
realArch = "64";
} else {
realArch = "32";
}
} else {
if(wow64Arch != null && wow64Arch.endsWith("64")) {
realArch = "64";
} else {
realArch = "32";
}
}
return realArch;
}
/**
* Returns the minecraft path for the current os system and creates the
* path if it does not exist.
* @return
*/
public String getMinecraftPath() {
String path = "";
if (operatingSystem.equals("windows")) {
path = System.getenv("APPDATA") + pS + ".minecraft" + pS;
if (new File(path).exists()) {
return path;
}
} else if (operatingSystem.equals("linux")) {
path = System.getProperty("user.home") + pS + ".minecraft"
+ pS;
if (new File(path).exists()) {
return path;
}
} else if (operatingSystem.equals("mac")) {
path = System.getProperty("user.home") + pS + "Library" + pS
+ "Application Support" + pS + "minecraft" + pS;
if (new File(path).exists()) {
return path;
}
}
new File(path).mkdirs();
return path;
}
/**
* Returns the current operating system.
* @return
*/
public String getOS() {
return operatingSystem;
}
/**
* Returns the operatins system as a String in lower case letters.
* @return
*/
public String getOSasString(){
return operatingSystem.toString().toLowerCase();
}
/**
* Returns the current java path. The java programm for the current os
* is added.
* e.g. (path).javaw.exe in windows.
* @return
*/
public String getJavaPath() {
String fs = File.separator;
String path = System.getProperty("java.home") + fs + "bin" + fs;
if (operatingSystem.equals(OS.WINDOWS) &&
(new File(path + "javaw.exe").isFile())) {
return path + "javaw.exe";
}
return path + "java";
}
}
|
package dk.es.br.dibs;
import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.SecureRandom;
import java.security.Security;
import com.sun.net.ssl.internal.ssl.Provider;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Currency;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
public class DibsClient
{
private final static Logger LOG = LoggerFactory.getLogger(DibsClient.class);
private final static SSLContext sslContext = initSSL();
private final static Pattern EXPECTED_FEE_PATTERN = Pattern.compile(".*\"fee\"\\s*:\\s*(\\d+)\\.?\\d*.*");
private final static Pattern SURCHARGEABILITY_REASON_PATTERN = Pattern.compile(".*\"reason\"\\s*:\\s*\"(\\w+)\".*");
static
{
try
{
System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
Provider provider = new Provider();
Security.addProvider(provider);
LOG.info("Added com.sun.net.ssl.internal.www.protocol security provider");
}
catch (Exception e)
{
LOG.error("Error setting protocol handlers needed by DIBS: " + e);
}
}
private final DibsConfig cfg;
public DibsClient(DibsConfig cfg)
{
this.cfg = cfg;
}
/**
* Deletes the specified account from the DIBS system. The account template
* MUST define the merchant and the account id properties
*
* @param accountId the account to delete
* @throws DibsException if the account does not exist or for some reason cannot be deleted
*/
public void deleteAccount(String accountId)
throws DibsException
{
// First fill out the message to dibs
Map msg = new HashMap();
msg.put("merchant", getMerchantId());
msg.put("ticket", accountId);
// Query the DIBS server
Map result = post("/cgi-adm/delticket.cgi", msg, true);
String status = (String) result.get("status");
if (status == null || !status.equalsIgnoreCase("ACCEPTED"))
throw new DibsException("'" + accountId + "': failed to delete account: " + result.get("message") + " (" + result.get("reason") + ")");
}
private enum Iso4217 {
DKK("208"), EUR("978"), USD("840"), GBP("826"),
SEK("752"), AUD("036"), CAD("124"), ISK("352"),
JPY("392"), NZD("554"), NOK("578"), CHF("756"),
TRL("792");
private final String code;
Iso4217(String code) {
this.code = code;
}
}
public static String codeOf(Currency currency) {
/* replace with currency.getNumericCode() (as of java 1.7) sometime... */
Iso4217 dc = Iso4217.valueOf(currency.getCurrencyCode());
return dc.code;
}
/**
* Checks the validity of the specified account in the DIBS system. This is
* done by attempting to authorize a small transaction, and then immediately cancel
* the authorization.
*
* @param accountId the account to check
* @param cents the amount to test authorization against
* @param currency the currency to test authorization against
* @return "ok" if there are no problems. Or the response
*/
public DibsResponse validateCardSubscription(String accountId, int cents, Currency currency)
throws DibsException
{
// First fill out the message to dibs - authorize a 1kr transfer
Map params = new HashMap();
params.put("merchant", getMerchantId());
params.put("ticket", accountId);
params.put("orderid", "checking-account");
params.put("amount", String.valueOf(cents));
params.put("currency", codeOf(currency));
// Query the DIBS server
Map result = post("/cgi-ssl/ticket_auth.cgi", params, false);
String status = (String)result.get("status");
if ("ACCEPTED".equalsIgnoreCase(status))
{
// Checked out fine. Now cancel the authorization:
String transact = (String)result.get("transact");
// Change the status to be canceled
params = new HashMap();
params.put("merchant", getMerchantId());
params.put("transact", transact);
try
{
post("/cgi-adm/cancel.cgi", params, true);
}
catch (Exception ex)
{
LOG.error("Validate Account: Exception trying to cancel authorization " + transact, ex);
}
LOG.info(accountId + " checked positive");
return new CheckAccountResponse(true, result);
}
String reason = (String)result.get("reason");
String message = (String)result.get("message");
// Presume auth failed. Need to see if the cardholder is to blame
switch (new Integer(reason))
{
case 1: // Communication problems
case 2: // Error in the parameters sent to the DIBS server
case 3: // Error at the acquirer
throw new RuntimeException("Account validation failed, " + result);
}
LOG.info(accountId + " checked negative (" + reason + ": " + message + ")");
return new CheckAccountResponse(false, result);
}
private Map post(String path, Map params, boolean auth)
throws DibsException
{
long t1 = System.currentTimeMillis();
String query = prepareAndFormatQuery(params);
URL url = dibsUrl(path);
try {
String response = _post(url, query, auth);
Map res = parseResponse(response);
LOG.info(path + "["+params+"] : " + res);
return res;
}
finally {
long t2 = System.currentTimeMillis();
LOG.info("DIBS call:" + path + " " + query + ": " + (t2-t1) + "ms");
}
}
private static URL dibsUrl(String path) {
try {
return new URL(null, "https:
} catch (MalformedURLException ex) {
throw new IllegalArgumentException(path, ex);
}
}
/**
* This method will authorize and deduct the specified amount of money from
* the specified account
*
* @param accountId the account to check
* @param orderId the unique order id
* @param amount the amount of money to deduct
* @param chargeCardFee whether to charge card fee to the given card account
* @return the transaction id
*/
public DibsResponse<Payment> withdraw(String accountId,
String orderId,
BigDecimal amount,
Currency currency,
boolean chargeCardFee)
throws DibsException
{
long cents = Math.round(amount.doubleValue() * 100.0);
// Sanity checks
if (StringUtils.isEmpty(accountId))
throw new IllegalArgumentException("Account id missing");
if (StringUtils.isEmpty(orderId))
throw new IllegalArgumentException("Order id missing");
if (cents < 0)
throw new DibsException("Cannot withdraw kr: " + amount);
long t1 = System.currentTimeMillis();
LOG.info("Withdraw " + amount + " from card account " + accountId + ", orderId " + orderId);
DibsResponse<Payment> response = withdrawCents(accountId, orderId, cents, currency, chargeCardFee);
Payment payment = response.result();
Long transactionId = payment.transactionId();
BigDecimal feeAmount = payment.feeAmount();
long t2 = System.currentTimeMillis();
LOG.info("Withdrew " + amount + " from card account " + accountId + ", orderId " + orderId + ": transaction " + transactionId + ", fee reported by Dibs: " + feeAmount + " (" + (t2-t1) + "ms)");
return response;
}
private DibsResponse<Payment> withdrawCents(String accountId,
String orderId,
long cents,
Currency currency,
boolean chargeCardFee)
throws DibsException
{
// First fill out the message to dibs
Map msg = new HashMap();
msg.put("merchant", getMerchantId());
msg.put("ticket", accountId);
msg.put("orderid", orderId);
msg.put("amount", cents);
msg.put("currency", codeOf(currency));
msg.put("capturenow", "yes");
msg.put("uniqueoid", "yes");
msg.put("fullreply", "yes");
String md5key = md5of("merchant=" + getMerchantId() + "&orderid=" + orderId + "&ticket=" + accountId + "¤cy=" + codeOf(currency) + "&amount=" + cents);
msg.put("md5key", md5key);
if (isTesting())
msg.put("test", "yes");
if (chargeCardFee)
msg.put("calcfee", "yes");
// Query the DIBS server
Map result = post("/cgi-ssl/ticket_auth.cgi", msg, false);
LOG.info("DIBS response: " + (result != null ? result.toString() : "null"));
String status = (String)result.get("status");
String message = (String)result.get("message");
if (!"ACCEPTED".equals(status))
throw new DibsException("Withdrawal " + status + ": " + message, (String)result.get("reason"), (String)result.get("actioncode"));
String transact = (String)result.get("transact");
if (StringUtils.isEmpty(transact))
throw new DibsException("Withdrawal " + status + " without transaction: " + message, (String)result.get("reason"), (String)result.get("actioncode"));
String reportedFee = (String)result.get("fee");
Long feeCents = reportedFee != null
? Long.valueOf(reportedFee)
: new Long(0);
final BigDecimal feeAmount = new BigDecimal(feeCents).scaleByPowerOfTen(-2);
final Long transactionId = Long.valueOf(transact);
// TODO: From DIBS, does severity != null => suspect is true ?
String suspect = (String)result.get("suspect");
final Boolean isSuspect = suspect != null
? Boolean.valueOf(suspect)
: false;
String severity = (String)result.get("severity");
final Integer suspectSeverity = suspect != null
? Integer.valueOf(severity)
: null;
final String orderNumber = (String)result.get("orderid");
final String cardType = (String)result.get("cardtypeCD");
final String cardGroup = (String)result.get("privatebusiness");
final String cardRegion = (String)result.get("surchargeregion");
return new DibsResponse<Payment>() {
@Override
public Long transactionId() {
return transactionId;
}
@Override
public boolean success() {
return true;
}
@Override
public String reason() {
return null;
}
@Override
public String actionCode() {
return null;
}
@Override
public Payment result() {
return new Payment()
.transactionId(transactionId)
.feeAmount(feeAmount)
.suspect(isSuspect)
.suspectSeverity(suspectSeverity)
.orderId(orderNumber)
.cardType(cardType)
.cardGroup(cardGroup)
.cardRegion(cardRegion);
}
};
}
public String getCardType(Long transactionId)
throws DibsException
{
// First fill out the message to dibs
Map msg = new HashMap();
msg.put("merchant", getMerchantId());
msg.put("transact", transactionId);
// Query the DIBS server
Map res = post("/cardtype.pml", msg, true);
// Check that the transaction was executed properly.
// If the card type is not recognized, "0" is returned
String arg1 = (String)res.get("1");
if ("0".equals(arg1)) {
LOG.info(transactionId + ": card type not recognized");
return null;
}
// The reply is the card type
return arg1;
}
private String getMerchantId()
{
return cfg.getMerchantId();
}
private String basicAuth()
{
String dibsUser = cfg.getDibsUser();
String dibsPass = cfg.getDibsPassword();
String userpass = dibsUser + ":" + dibsPass;
return "Basic " + new String(Base64.encodeBase64(userpass.getBytes()));
}
public String surchargeabilityReason(String ticket)
throws DibsException
{
String path = "/api/card/v1/tickets/" + ticket;
String response = _get(dibsUrl(path), false);
return parseSurchargeabilityResponse(response);
}
public static String parseSurchargeabilityResponse(String response)
{
Matcher matcher = SURCHARGEABILITY_REASON_PATTERN.matcher(response);
if (!matcher.matches())
throw new IllegalArgumentException("Unknown response format. Response was: " + response);
return matcher.group(1);
}
public int expectedFeeCents(String ticket, int amountCents, Currency currency)
throws DibsException
{
String path = "/api/fee/v1/subscribers/" + getMerchantId() + "/best";
Map<String, String> params = new HashMap<>();
params.put("amount", Integer.toString(amountCents));
params.put("currency", codeOf(currency));
params.put("test", Boolean.toString(isTesting()));
params.put("ticket", ticket);
String response = _get(dibsUrl(path + "?" + formatQuery(params)), false);
return parseFeeResponse(response);
}
public static int parseFeeResponse(String response)
{
Matcher matcher = EXPECTED_FEE_PATTERN.matcher(response);
if (!matcher.matches())
throw new IllegalArgumentException("Unrecognised response format. Response was: " + response);
return Integer.parseInt(matcher.group(1));
}
private String _get(URL url, boolean auth)
throws DibsException
{
try {
return response(connect(url, auth));
} catch (IOException ioe)
{
throw new DibsException("failed", ioe);
}
}
/**
* Posts a request to the DIBS server. Solemnly stolen from DIBS' sample
* DeltapayHTTP class. Small changes implemented.
*
* @param url the server
* @param message the parameters
* @param auth should we use basic authentication
* @return the result
*/
private String _post(URL url, String message, boolean auth)
throws DibsException
{
HttpsURLConnection conn;
OutputStream os;
try {
conn = connect(url, auth);
os = conn.getOutputStream();
}
catch (IOException ex) {
LOG.error(url + ": failed to connect", ex);
throw new DibsException("failed to connect", ex);
}
try(PrintWriter wrt = new PrintWriter(os)) {
wrt.println(message);
}
try {
return response(conn);
}
catch (IOException ex) {
LOG.error(url + "[" + message + "]: failed to get response", ex);
throw new DibsException("failed to get response", ex);
}
}
private HttpsURLConnection connect(URL url, boolean auth)
throws DibsException {
HttpsURLConnection conn;
try {
conn = (HttpsURLConnection) url.openConnection();
} catch (IOException ioe)
{
throw new DibsException("failed to connect ", ioe);
}
conn.setSSLSocketFactory(sslContext.getSocketFactory());
conn.setDoOutput(true);
conn.setUseCaches(false);
// conn.setConnectTimeout(...);
// conn.setReadTimeout(....);
if (auth)
conn.setRequestProperty("Authorization", basicAuth());
return conn;
}
private static String response(HttpsURLConnection conn)
throws IOException
{ StringBuilder res = new StringBuilder();
try (BufferedReader rdr = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String line;
while ((line = rdr.readLine()) != null)
res.append(line);
}
return res.toString();
}
/**
* Parses the response sent from the DIBS server and converts it into a param
* name value map.
*
* @param s the response received from the server
* @return the result map
*/
public static Map parseResponse(String s)
{
LOG.info("To parse response {}", s);
Map res = new HashMap();
StringTokenizer st = new StringTokenizer(s, "&");
while (st.hasMoreTokens())
{
String s1 = st.nextToken();
StringTokenizer st2 = new StringTokenizer(s1, "=");
if (st2.countTokens() == 0)
continue;
String key = st2.countTokens() == 2 ? st2.nextToken().toLowerCase() : String.valueOf(res.size() + 1);
String val = urlDecodeUTF8(st2.nextToken());
res.put(key, val);
}
return res;
}
private static String prepareAndFormatQuery(Map params)
{
params.put("textreply", "yes");
return formatQuery(params);
}
private static String formatQuery(Map params)
{
StringBuilder msg = new StringBuilder();
Iterator es = params.entrySet().iterator();
while (es.hasNext())
{
Map.Entry e = (Map.Entry)es.next();
Object k = e.getKey();
Object v = e.getValue();
if (k == null || v == null)
continue;
if (msg.length() > 0)
msg.append("&");
msg.append(k.toString()).append("=").append(urlEncodeUTF8(v.toString()));
}
return msg.toString();
}
private static class CheckAccountResponse implements DibsResponse<Boolean> {
private final boolean m_valid;
private final String m_reason;
private final String m_actionCode;
private final Long m_transactionId;
private CheckAccountResponse(boolean success, Map resultMap) {
m_valid = success;
m_reason = (String)resultMap.get("reason");
m_actionCode = (String)resultMap.get("actioncode");
String transact = (String)resultMap.get("transact");
m_transactionId = transact == null ? null : Long.valueOf(transact);
}
@Override
public Long transactionId() {
return m_transactionId;
}
@Override
public boolean success() {
return m_valid;
}
@Override
public Boolean result()
{
return m_valid;
}
@Override
public String reason()
{
return m_reason;
}
@Override
public String actionCode()
{
return m_actionCode;
}
}
public static class Payment extends DibsTransaction
{
private Long transactionId;
private String orderId;
private BigDecimal amount;
private BigDecimal feeAmount;
private BigDecimal totalAmount;
private Boolean suspect;
private Integer suspectSeverity;
private String cardBrand;
private String cardType;
private String cardGroup;
private String cardRegion;
private Payment() {}
Payment transactionId(Long transactionId)
{
this.transactionId = transactionId;
return this;
}
Payment orderId(String orderId)
{
this.orderId = orderId;
return this;
}
Payment amount(BigDecimal amount)
{
this.amount = amount;
return this;
}
Payment feeAmount(BigDecimal feeAmount)
{
this.feeAmount = feeAmount;
return this;
}
Payment totalAmount(BigDecimal totalAmount)
{
this.totalAmount = amount;
return this;
}
Payment suspect(Boolean suspect)
{
this.suspect = suspect;
return this;
}
Payment suspectSeverity(Integer suspectSeverity)
{
this.suspectSeverity = suspectSeverity;
return this;
}
Payment cardBrand(String cardBrand)
{
this.cardBrand = cardBrand;
return this;
}
Payment cardType(String cardType)
{
this.cardType = cardType;
return this;
}
Payment cardGroup(String cardGroup)
{
this.cardGroup = cardGroup;
return this;
}
Payment cardRegion(String cardRegion)
{
this.cardRegion = cardRegion;
return this;
}
@Override
public Long transactionId()
{
return transactionId;
}
@Override
public String orderId()
{
return orderId;
}
@Override
public BigDecimal amount()
{
return amount;
}
@Override
public BigDecimal feeAmount()
{
return feeAmount;
}
@Override
public BigDecimal totalAmount()
{
return totalAmount;
}
@Override
public Boolean suspect()
{
return suspect;
}
@Override
public Integer suspectSeverity()
{
return suspectSeverity;
}
@Override
public String cardBrand()
{
return cardBrand;
}
@Override
public String cardType()
{
return cardType;
}
@Override
public String cardGroup()
{
return cardGroup;
}
@Override
public String cardRegion()
{
return cardRegion;
}
}
private static String urlEncodeUTF8(String s)
{
try
{
return URLEncoder.encode(s, "UTF-8");
}
catch (UnsupportedEncodingException ex)
{
// Can't happen
throw new RuntimeException(ex);
}
}
private static String urlDecodeUTF8(String nn)
{
try
{
return URLDecoder.decode(nn, "UTF-8");
}
catch (UnsupportedEncodingException ex)
{
// Can't happen
throw new RuntimeException(ex);
}
}
private boolean isTesting() {
return cfg.isTesting();
}
public String md5of(String src) {
return MD5(cfg.getMd5K1(), cfg.getMd5K2(), src);
}
public static String MD5(String src) {
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
md.update(src.getBytes());
BigInteger hash = new BigInteger(1, md.digest());
String res = "0000000000000000000000000000000" + hash.toString(16);
res = res.substring(res.length() - 32);
return res;
}
public static String MD5(String k1, String k2, String src) {
return MD5(k2 + MD5(k1 + src));
}
private static SSLContext initSSL()
{
SSLContext sslContext;
try
{
sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, new SecureRandom());
}
catch (NoSuchAlgorithmException | KeyManagementException ex)
{
throw new RuntimeException("Could not setup ssl context", ex);
}
return sslContext;
}
}
|
package gherkin.pickles;
import gherkin.SymbolCounter;
import gherkin.GherkinDialect;
import gherkin.GherkinDialectProvider;
import gherkin.ast.Background;
import gherkin.ast.DataTable;
import gherkin.ast.DocString;
import gherkin.ast.Examples;
import gherkin.ast.Feature;
import gherkin.ast.Location;
import gherkin.ast.Node;
import gherkin.ast.Scenario;
import gherkin.ast.ScenarioDefinition;
import gherkin.ast.ScenarioOutline;
import gherkin.ast.Step;
import gherkin.ast.TableCell;
import gherkin.ast.TableRow;
import gherkin.ast.Tag;
import java.util.ArrayList;
import java.util.List;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.Collections.unmodifiableList;
public class Compiler {
public List<Pickle> compile(Feature feature, String path) {
List<Pickle> pickles = new ArrayList<>();
GherkinDialect dialect = new GherkinDialectProvider().getDialect(feature.getLanguage(), null);
List<Tag> featureTags = feature.getTags();
List<PickleStep> backgroundSteps = getBackgroundSteps(feature.getBackground(), path);
for (ScenarioDefinition scenarioDefinition : feature.getScenarioDefinitions()) {
if (scenarioDefinition instanceof Scenario) {
compileScenario(pickles, backgroundSteps, (Scenario) scenarioDefinition, featureTags, path);
} else {
compileScenarioOutline(pickles, backgroundSteps, (ScenarioOutline) scenarioDefinition, featureTags, path, dialect);
}
}
return pickles;
}
private void compileScenario(List<Pickle> pickles, List<PickleStep> backgroundSteps, Scenario scenario, List<Tag> featureTags, String path) {
if (scenario.getSteps().isEmpty())
return;
List<PickleStep> steps = new ArrayList<>();
steps.addAll(backgroundSteps);
List<Tag> scenarioTags = new ArrayList<>();
scenarioTags.addAll(featureTags);
scenarioTags.addAll(scenario.getTags());
for (Step step : scenario.getSteps()) {
steps.add(pickleStep(step, path));
}
Pickle pickle = new Pickle(
scenario.getKeyword() + ": " + scenario.getName(),
steps,
pickleTags(scenarioTags, path),
singletonList(pickleLocation(scenario.getLocation(), path))
);
pickles.add(pickle);
}
private void compileScenarioOutline(List<Pickle> pickles, List<PickleStep> backgroundSteps, ScenarioOutline scenarioOutline, List<Tag> featureTags, String path, GherkinDialect dialect) {
if (scenarioOutline.getSteps().isEmpty())
return;
String keyword = dialect.getScenarioKeywords().get(0);
for (final Examples examples : scenarioOutline.getExamples()) {
if (examples.getTableHeader() == null) continue;
List<TableCell> variableCells = examples.getTableHeader().getCells();
for (final TableRow values : examples.getTableBody()) {
List<TableCell> valueCells = values.getCells();
List<PickleStep> steps = new ArrayList<>();
steps.addAll(backgroundSteps);
List<Tag> tags = new ArrayList<>();
tags.addAll(featureTags);
tags.addAll(scenarioOutline.getTags());
tags.addAll(examples.getTags());
for (Step scenarioOutlineStep : scenarioOutline.getSteps()) {
String stepText = interpolate(scenarioOutlineStep.getText(), variableCells, valueCells);
// TODO: Use an Array of location in DataTable/DocString as well.
// If the Gherkin AST classes supported
// a list of locations, we could just reuse the same classes
PickleStep pickleStep = new PickleStep(
stepText,
createPickleArguments(scenarioOutlineStep.getArgument(), variableCells, valueCells, path),
asList(
pickleLocation(values.getLocation(), path),
pickleStepLocation(scenarioOutlineStep, path)
)
);
steps.add(pickleStep);
}
Pickle pickle = new Pickle(
keyword + ": " + interpolate(scenarioOutline.getName(), variableCells, valueCells),
steps,
pickleTags(tags, path),
asList(
pickleLocation(values.getLocation(), path),
pickleLocation(scenarioOutline.getLocation(), path)
)
);
pickles.add(pickle);
}
}
}
private List<Argument> createPickleArguments(Node argument, String path) {
List<TableCell> noCells = emptyList();
return createPickleArguments(argument, noCells, noCells, path);
}
private List<Argument> createPickleArguments(Node argument, List<TableCell> variableCells, List<TableCell> valueCells, String path) {
List<Argument> result = new ArrayList<>();
if (argument == null) return result;
if (argument instanceof DataTable) {
DataTable t = (DataTable) argument;
List<TableRow> rows = t.getRows();
List<PickleRow> newRows = new ArrayList<>(rows.size());
for (TableRow row : rows) {
List<TableCell> cells = row.getCells();
List<PickleCell> newCells = new ArrayList<>();
for (TableCell cell : cells) {
newCells.add(
new PickleCell(
pickleLocation(cell.getLocation(), path),
interpolate(cell.getValue(), variableCells, valueCells)
)
);
}
newRows.add(new PickleRow(newCells));
}
result.add(new PickleTable(newRows));
} else if (argument instanceof DocString) {
DocString ds = (DocString) argument;
result.add(
new PickleString(
pickleLocation(ds.getLocation(), path),
interpolate(ds.getContent(), variableCells, valueCells)
)
);
} else {
throw new RuntimeException("Unexpected argument type: " + argument);
}
return result;
}
private List<PickleStep> getBackgroundSteps(Background background, String path) {
List<PickleStep> result = new ArrayList<>();
if (background != null) {
for (Step step : background.getSteps()) {
result.add(pickleStep(step, path));
}
}
return unmodifiableList(result);
}
private PickleStep pickleStep(Step step, String path) {
return new PickleStep(
step.getText(),
createPickleArguments(step.getArgument(), path),
singletonList(pickleStepLocation(step, path))
);
}
private String interpolate(String name, List<TableCell> variableCells, List<TableCell> valueCells) {
int col = 0;
for (TableCell variableCell : variableCells) {
TableCell valueCell = valueCells.get(col++);
String header = variableCell.getValue();
String value = valueCell.getValue();
name = name.replace("<" + header + ">", value);
}
return name;
}
private PickleLocation pickleStepLocation(Step step, String path) {
return new PickleLocation(
path,
step.getLocation().getLine(),
step.getLocation().getColumn() + (step.getKeyword() != null ? SymbolCounter.countSymbols(step.getKeyword()) : 0)
);
}
private PickleLocation pickleLocation(Location location, String path) {
return new PickleLocation(path, location.getLine(), location.getColumn());
}
private List<PickleTag> pickleTags(List<Tag> tags, String path) {
List<PickleTag> result = new ArrayList<>();
for (Tag tag : tags) {
result.add(pickleTag(tag, path));
}
return result;
}
private PickleTag pickleTag(Tag tag, String path) {
return new PickleTag(pickleLocation(tag.getLocation(), path), tag.getName());
}
}
|
package hudson.remoting;
import hudson.remoting.Channel.Mode;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.CmdLineException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.TrustManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.File;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLConnection;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLClassLoader;
import java.net.InetSocketAddress;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
import java.security.NoSuchAlgorithmException;
import java.security.KeyManagementException;
/**
* Entry point for running a {@link Channel}. This is the main method of the slave JVM.
*
* <p>
* This class also defines several methods for
* starting a channel on a fresh JVM.
*
* @author Kohsuke Kawaguchi
*/
public class Launcher {
public Mode mode = Mode.BINARY;
// no-op, but left for backward compatibility
@Option(name="-ping")
public boolean ping = true;
@Option(name="-text",usage="encode communication with the master with base64. " +
"Useful for running slave over 8-bit unsafe protocol like telnet")
public void setTextMode(boolean b) {
mode = b?Mode.TEXT:Mode.BINARY;
System.out.println("Running in "+mode.name().toLowerCase()+" mode");
}
@Option(name="-jnlpUrl",usage="instead of talking to the master via stdin/stdout, " +
"emulate a JNLP client by making a TCP connection to the master. " +
"Connection parameters are obtained by parsing the JNLP file.")
public URL slaveJnlpURL = null;
@Option(name="-cp",aliases="-classpath",metaVar="PATH",
usage="add the given classpath elements to the system classloader.")
public void addClasspath(String pathList) throws Exception {
Method $addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
$addURL.setAccessible(true);
for(String token : pathList.split(File.pathSeparator))
$addURL.invoke(ClassLoader.getSystemClassLoader(),new File(token).toURI().toURL());
// fix up the system.class.path to pretend that those jar files
// are given through CLASSPATH or something.
// some tools like JAX-WS RI and Hadoop relies on this.
System.setProperty("java.class.path",System.getProperty("java.class.path")+File.pathSeparatorChar+pathList);
}
@Option(name="-tcp",usage="instead of talking to the master via stdin/stdout, " +
"listens to a random local port, write that port number to the given file, " +
"then wait for the master to connect to that port.")
public File tcpPortFile=null;
public InetSocketAddress connectionTarget = null;
@Option(name="-connectTo",usage="make a TCP connection to the given host and port, then start communication.",metaVar="HOST:PORT")
public void setConnectTo(String target) {
String[] tokens = target.split(":");
if(tokens.length!=2) {
System.err.println("Illegal parameter: "+target);
System.exit(1);
}
connectionTarget = new InetSocketAddress(tokens[0],Integer.valueOf(tokens[1]));
}
/**
* Bypass HTTPS security check by using free-for-all trust manager.
*
* @param _
* This is ignored.
*/
@Option(name="-noCertificateCheck")
public void setNoCertificateCheck(boolean _) throws NoSuchAlgorithmException, KeyManagementException {
System.out.println("Skipping HTTPS certificate checks altoghether. Note that this is not secure at all.");
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[]{new NoCheckTrustManager()}, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
// bypass host name check, too.
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
}
public static void main(String... args) throws Exception {
Launcher launcher = new Launcher();
CmdLineParser parser = new CmdLineParser(launcher);
try {
parser.parseArgument(args);
launcher.run();
} catch (CmdLineException e) {
System.err.println(e.getMessage());
System.err.println("java -jar slave.jar [options...]");
parser.printUsage(System.err);
System.err.println();
}
}
public void run() throws Exception {
if(connectionTarget!=null) {
runAsTcpClient();
System.exit(0);
} else
if(slaveJnlpURL!=null) {
List<String> jnlpArgs = parseJnlpArguments();
hudson.remoting.jnlp.Main.main(jnlpArgs.toArray(new String[jnlpArgs.size()]));
} else
if(tcpPortFile!=null) {
runAsTcpServer();
System.exit(0);
} else {
runWithStdinStdout();
System.exit(0);
}
}
/**
* Parses the connection arguments from JNLP file given in the URL.
*/
private List<String> parseJnlpArguments() throws ParserConfigurationException, SAXException, IOException, InterruptedException {
while (true) {
try {
URLConnection con = slaveJnlpURL.openConnection();
con.connect();
if (con instanceof HttpURLConnection) {
HttpURLConnection http = (HttpURLConnection) con;
if(http.getResponseCode()>=400)
// got the error code. report that (such as 401)
throw new IOException("Failed to load "+slaveJnlpURL+": "+http.getResponseCode()+" "+http.getResponseMessage());
}
Document dom;
// check if this URL points to a .jnlp file
String contentType = con.getHeaderField("Content-Type");
if(contentType==null || !contentType.startsWith("application/x-java-jnlp-file")) {
// load DOM anyway, but if it fails to parse, that's probably because this is not an XML file to begin with.
try {
dom = loadDom(slaveJnlpURL, con);
} catch (SAXException e) {
throw new IOException(slaveJnlpURL+" doesn't look like a JNLP file; content type was "+contentType);
} catch (IOException e) {
throw new IOException(slaveJnlpURL+" doesn't look like a JNLP file; content type was "+contentType);
}
} else {
dom = loadDom(slaveJnlpURL, con);
}
// exec into the JNLP launcher, to fetch the connection parameter through JNLP.
NodeList argElements = dom.getElementsByTagName("argument");
List<String> jnlpArgs = new ArrayList<String>();
for( int i=0; i<argElements.getLength(); i++ )
jnlpArgs.add(argElements.item(i).getTextContent());
// force a headless mode
jnlpArgs.add("-headless");
return jnlpArgs;
} catch (SSLHandshakeException e) {
if(e.getMessage().contains("PKIX path building failed")) {
// invalid SSL certificate. One reason this happens is when the certificate is self-signed
IOException x = new IOException("Failed to validate a server certificate. If you are using a self-signed certificate, you can use the -noCertificateCheck option to bypass this check.");
x.initCause(e);
throw x;
} else
throw e;
} catch (IOException e) {
System.err.println("Failing to obtain "+slaveJnlpURL);
e.printStackTrace(System.err);
System.err.println("Waiting 10 seconds before retry");
Thread.sleep(10*1000);
// retry
}
}
}
private static Document loadDom(URL slaveJnlpURL, URLConnection con) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
return db.parse(con.getInputStream(),slaveJnlpURL.toExternalForm());
}
/**
* Listens on an ephemeral port, record that port number in a port file,
* then accepts one TCP connection.
*/
private void runAsTcpServer() throws IOException, InterruptedException {
// if no one connects for too long, assume something went wrong
// and avoid hanging foreever
ServerSocket ss = new ServerSocket(0,1);
ss.setSoTimeout(30*1000);
// write a port file to report the port number
FileWriter w = new FileWriter(tcpPortFile);
w.write(String.valueOf(ss.getLocalPort()));
w.close();
// accept just one connection and that's it.
// when we are done, remove the port file to avoid stale port file
Socket s;
try {
s = ss.accept();
ss.close();
} finally {
tcpPortFile.delete();
}
runOnSocket(s);
}
private void runOnSocket(Socket s) throws IOException, InterruptedException {
main(new BufferedInputStream(new SocketInputStream(s)),
new BufferedOutputStream(new SocketOutputStream(s)), mode,ping);
}
/**
* Connects to the given TCP port and then start running
*/
private void runAsTcpClient() throws IOException, InterruptedException {
// if no one connects for too long, assume something went wrong
// and avoid hanging foreever
Socket s = new Socket(connectionTarget.getAddress(),connectionTarget.getPort());
runOnSocket(s);
}
private void runWithStdinStdout() throws IOException, InterruptedException {
// use stdin/stdout for channel communication
ttyCheck();
// this will prevent programs from accidentally writing to System.out
// and messing up the stream.
OutputStream os = System.out;
System.setOut(System.err);
main(System.in,os, mode,ping);
}
private static void ttyCheck() {
try {
Method m = System.class.getMethod("console");
Object console = m.invoke(null);
if(console!=null) {
// we seem to be running from interactive console. issue a warning.
// but since this diagnosis could be wrong, go on and do what we normally do anyway. Don't exit.
System.out.println(
"WARNING: Are you running slave agent from an interactive console?\n" +
"If so, you are probably using it incorrectly.\n" +
"See http://hudson.gotdns.com/wiki/display/HUDSON/Launching+slave.jar+from+from+console");
}
} catch (LinkageError e) {
// we are probably running on JDK5 that doesn't have System.console()
// we can't check
} catch (InvocationTargetException e) {
// this is impossible
throw new AssertionError(e);
} catch (NoSuchMethodException e) {
// must be running on JDK5
} catch (IllegalAccessException e) {
// this is impossible
throw new AssertionError(e);
}
}
public static void main(InputStream is, OutputStream os) throws IOException, InterruptedException {
main(is,os,Mode.BINARY);
}
public static void main(InputStream is, OutputStream os, Mode mode) throws IOException, InterruptedException {
main(is,os,mode,false);
}
public static void main(InputStream is, OutputStream os, Mode mode, boolean performPing) throws IOException, InterruptedException {
ExecutorService executor = Executors.newCachedThreadPool();
Channel channel = new Channel("channel", executor, mode, is, os);
System.err.println("channel started");
if(performPing) {
// System.err.println("Starting periodic ping thread");
new PingThread(channel) {
@Override
protected void onDead() {
System.err.println("Ping failed. Terminating");
System.exit(-1);
}
}.start();
}
channel.join();
System.err.println("channel stopped");
}
/**
* {@link X509TrustManager} that performs no check at all.
*/
private static class NoCheckTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
}
|
package invtweaks;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.oredict.OreDictionary;
import org.apache.logging.log4j.Level;
import java.io.File;
public class InvTweaksConst {
// Mod version
public static final String MOD_VERSION = "@VERSION@";
// Mod tree version
// Change only when the tree evolves significantly enough to need to override all configs
public static final String TREE_VERSION = "1.12.0";
public static final String INVTWEAKS_CHANNEL = "InventoryTweaks";
// Network Protocol version
public static final byte PROTOCOL_VERSION = 2;
public static final byte PACKET_LOGIN = 0x00;
public static final byte PACKET_CLICK = 0x01;
public static final byte PACKET_SORTCOMPLETE = 0x02;
// Timing constants
public static final int RULESET_SWAP_DELAY = 1000;
public static final int POLLING_DELAY = 3;
public static final int CHEST_ALGORITHM_SWAP_MAX_INTERVAL = 2000;
public static final int TOOLTIP_DELAY = 800;
// File constants
public static final File MINECRAFT_DIR = Minecraft.getMinecraft().mcDataDir;
public static final File MINECRAFT_CONFIG_DIR = new File(MINECRAFT_DIR, "config/");
public static final File CONFIG_PROPS_FILE = new File(MINECRAFT_CONFIG_DIR, "InvTweaks.cfg");
public static final File CONFIG_RULES_FILE = new File(MINECRAFT_CONFIG_DIR, "InvTweaksRules.txt");
public static final File CONFIG_TREE_FILE = new File(MINECRAFT_CONFIG_DIR, "InvTweaksTree.txt");
public static final File OLD_CONFIG_TREE_FILE = new File(MINECRAFT_CONFIG_DIR, "InvTweaksTree.xml");
public static final File OLDER_CONFIG_RULES_FILE = new File(MINECRAFT_DIR, "InvTweaksRules.txt");
public static final String INVTWEAKS_RESOURCE_DOMAIN = "inventorytweaks";
public static final ResourceLocation DEFAULT_CONFIG_FILE = new ResourceLocation(INVTWEAKS_RESOURCE_DOMAIN,
"defaultconfig.dat");
public static final ResourceLocation DEFAULT_CONFIG_TREE_FILE = new ResourceLocation(INVTWEAKS_RESOURCE_DOMAIN,
"itemtree.xml");
public static final String HELP_URL = "http://inventory-tweaks.readthedocs.org";
// Global mod constants
public static final String INGAME_LOG_PREFIX = "InvTweaks: ";
public static final Level DEBUG = Level.INFO;
public static final int JIMEOWAN_ID = 54696386; // Used in GUIs
// Minecraft constants
public static final int INVENTORY_SIZE = 36;
public static final int INVENTORY_ROW_SIZE = 9;
public static final int HOTBAR_SIZE = 9;
public static final int INVENTORY_HOTBAR_SIZE = INVENTORY_ROW_SIZE;
public static final int DAMAGE_WILDCARD = OreDictionary.WILDCARD_VALUE;
}
|
package io.druid.data.input;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Maps;
import com.metamx.common.ISE;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class Rows
{
public static InputRow toCaseInsensitiveInputRow(final Row row, final List<String> dimensions)
{
if (row instanceof MapBasedRow) {
MapBasedRow mapBasedRow = (MapBasedRow) row;
TreeMap<String, Object> caseInsensitiveMap = Maps.newTreeMap(String.CASE_INSENSITIVE_ORDER);
caseInsensitiveMap.putAll(mapBasedRow.getEvent());
return new MapBasedInputRow(
mapBasedRow.getTimestampFromEpoch(),
dimensions,
caseInsensitiveMap
);
}
throw new ISE("Can only convert MapBasedRow objects because we are ghetto like that.");
}
/**
* @param timeStamp rollup up timestamp to be used to create group key
* @param inputRow input row
* @return groupKey for the given input row
*/
public static List<Object> toGroupKey(long timeStamp, InputRow inputRow)
{
final Map<String, Set<String>> dims = Maps.newTreeMap();
for (final String dim : inputRow.getDimensions()) {
final Set<String> dimValues = ImmutableSortedSet.copyOf(inputRow.getDimension(dim.toLowerCase()));
if (dimValues.size() > 0) {
dims.put(dim, dimValues);
}
}
return ImmutableList.of(
timeStamp,
dims
);
}
}
|
package net.imagej.app;
import org.scijava.Priority;
import org.scijava.app.AbstractApp;
import org.scijava.app.App;
import org.scijava.plugin.Plugin;
/**
* Application metadata about ImageJ.
*
* @author Curtis Rueden
* @see org.scijava.app.AppService
*/
@Plugin(type = App.class, name = ImageJApp.NAME,
priority = Priority.HIGH_PRIORITY)
public class ImageJApp extends AbstractApp {
public static final String NAME = "ImageJ";
@Override
public String getGroupId() {
return "net.imagej";
}
@Override
public String getArtifactId() {
return "ij-core";
}
}
|
package org.basex.test.w3c;
import static org.basex.core.Text.*;
import static org.basex.util.Token.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.regex.Pattern;
import org.basex.core.Context;
import org.basex.core.Prop;
import org.basex.core.cmd.Check;
import org.basex.core.cmd.Close;
import org.basex.core.cmd.CreateDB;
import org.basex.data.Data;
import org.basex.data.DataText;
import org.basex.data.Nodes;
import org.basex.data.SerializerProp;
import org.basex.data.XMLSerializer;
import org.basex.io.ArrayOutput;
import org.basex.io.IO;
import org.basex.io.TextInput;
import org.basex.query.QueryException;
import org.basex.query.QueryProcessor;
import org.basex.query.expr.Expr;
import org.basex.query.func.FNSimple;
import org.basex.query.func.FunDef;
import org.basex.query.item.DBNode;
import org.basex.query.item.Item;
import org.basex.query.item.Str;
import org.basex.query.item.Type;
import org.basex.query.item.Uri;
import org.basex.query.item.Value;
import org.basex.query.iter.NodIter;
import org.basex.query.iter.ItemIter;
import org.basex.util.Args;
import org.basex.util.Performance;
import org.basex.util.TokenBuilder;
import org.basex.util.TokenList;
import org.basex.util.Util;
public abstract class W3CTS {
// Try "ulimit -n 65536" if Linux tells you "Too many open files."
/** Inspect flag. */
private static final byte[] INSPECT = token("Inspect");
/** Fragment flag. */
private static final byte[] FRAGMENT = token("Fragment");
/** XML flag. */
private static final byte[] XML = token("XML");
/** Replacement pattern. */
private static final Pattern SLASH = Pattern.compile("/", Pattern.LITERAL);
/** Database context. */
protected final Context context = new Context();
/** Path to the XQuery Test Suite. */
protected String path = "";
/** Data reference. */
protected Data data;
/** History path. */
private final String pathhis;
/** Log file. */
private final String pathlog;
/** Test suite input. */
private final String input;
/** Test suite id. */
private final String testid;
/** Query path. */
private String queries;
/** Expected results. */
private String expected;
/** Reported results. */
private String results;
/** Reports. */
private String report;
/** Test sources. */
private String sources;
/** Maximum length of result output. */
private static int maxout = 500;
/** Query filter string. */
private String single;
/** Flag for printing current time functions into log file. */
private boolean currTime;
/** Flag for creating report files. */
private boolean reporting;
/** Verbose flag. */
private boolean verbose;
/** Debug flag. */
private boolean debug;
/** Minimum conformance. */
private boolean minimum;
/** Print compilation steps. */
private boolean compile;
/** Cached source files. */
private final HashMap<String, String> srcs = new HashMap<String, String>();
/** Cached module files. */
private final HashMap<String, String> mods = new HashMap<String, String>();
/** Cached collections. */
private final HashMap<String, byte[][]> colls =
new HashMap<String, byte[][]>();
/** OK log. */
private final StringBuilder logOK = new StringBuilder();
/** OK log. */
private final StringBuilder logOK2 = new StringBuilder();
/** Error log. */
private final StringBuilder logErr = new StringBuilder();
/** Error log. */
private final StringBuilder logErr2 = new StringBuilder();
/** File log. */
private final StringBuilder logReport = new StringBuilder();
/** Error counter. */
private int err;
/** Error2 counter. */
private int err2;
/** OK counter. */
private int ok;
/** OK2 counter. */
private int ok2;
/**
* Constructor.
* @param nm name of test
*/
public W3CTS(final String nm) {
input = nm + "Catalog" + IO.XMLSUFFIX;
testid = nm.substring(0, 4);
pathhis = testid.toLowerCase() + ".hist";
pathlog = testid.toLowerCase() + ".log";
}
/**
* Runs the test suite.
* @param args command-line arguments
* @throws Exception exception
*/
void run(final String[] args) throws Exception {
final Args arg = new Args(args, this,
" Test Suite [options] [pat]" + NL +
" [pat] perform only tests with the specified pattern" + NL +
" -c print compilation steps" + NL +
" -d show debugging info" + NL +
" -h show this help" + NL +
" -m minimum conformance" + NL +
" -p change path" + NL +
" -r create report" + NL +
" -v verbose output");
while(arg.more()) {
if(arg.dash()) {
final char c = arg.next();
if(c == 'r') {
reporting = true;
currTime = true;
} else if(c == 'c') {
compile = true;
} else if(c == 'd') {
debug = true;
} else if(c == 'm') {
minimum = true;
} else if(c == 'p') {
path = arg.string() + "/";
} else if(c == 'v') {
verbose = true;
} else {
arg.check(false);
}
} else {
single = arg.string();
maxout = Integer.MAX_VALUE;
}
}
if(!arg.finish()) return;
queries = path + "Queries/XQuery/";
expected = path + "ExpectedTestResults/";
results = path + "ReportingResults/Results/";
report = path + "ReportingResults/";
sources = path + "TestSources/";
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final String dat = sdf.format(Calendar.getInstance().getTime());
final Performance perf = new Performance();
context.prop.set(Prop.CHOP, false);
new Check(path + input).execute(context);
data = context.data;
final Nodes root = new Nodes(0, data);
Util.outln(NL + Util.name(this) + " Test Suite " +
/**
* Calculates the percentage of correct queries.
* @param v value
* @param t total value
* @return percentage
*/
private String pc(final int v, final long t) {
return (t == 0 ? 100 : v * 10000 / t / 100d) + "%";
}
/**
* Parses the specified test case.
* @param root root node
* @throws Exception exception
* @return true if the query, specified by {@link #single}, was evaluated
*/
private boolean parse(final Nodes root) throws Exception {
final String pth = text("@FilePath", root);
final String outname = text("@name", root);
if(single != null && !outname.startsWith(single)) return true;
Performance perf = new Performance();
if(verbose) Util.out("- " + outname);
boolean inspect = false;
boolean correct = true;
final Nodes nodes = states(root);
for(int n = 0; n < nodes.size(); ++n) {
final Nodes state = new Nodes(nodes.nodes[n], nodes.data);
final String inname = text("*:query/@name", state);
context.query = IO.get(queries + pth + inname + IO.XQSUFFIX);
final String in = read(context.query);
String er = null;
ItemIter iter = null;
boolean doc = true;
final Nodes cont = nodes("*:contextItem", state);
Nodes curr = null;
if(cont.size() != 0) {
final Data d = Check.check(context,
srcs.get(string(data.atom(cont.nodes[0]))));
curr = new Nodes(d.doc(), d);
curr.doc = true;
}
context.prop.set(Prop.QUERYINFO, compile);
final QueryProcessor xq = new QueryProcessor(in, curr, context);
context.prop.set(Prop.QUERYINFO, false);
// limit result sizes to 1MB
final ArrayOutput ao = new ArrayOutput();
final TokenBuilder files = new TokenBuilder();
try {
files.add(file(nodes("*:input-file", state),
nodes("*:input-file/@variable", state), xq, n == 0));
files.add(file(nodes("*:defaultCollection", state),
null, xq, n == 0));
var(nodes("*:input-URI", state),
nodes("*:input-URI/@variable", state), xq);
eval(nodes("*:input-query/@name", state),
nodes("*:input-query/@variable", state), pth, xq);
parse(xq, state);
for(final int p : nodes("*:module", root).nodes) {
final String ns = text("@namespace", new Nodes(p, data));
final String f = mods.get(string(data.atom(p))) + IO.XQSUFFIX;
xq.module(ns, f);
}
// evaluate and serialize query
final SerializerProp sp = new SerializerProp();
sp.set(SerializerProp.S_INDENT, context.prop.is(Prop.CHOP) ?
DataText.YES : DataText.NO);
final XMLSerializer xml = new XMLSerializer(ao, sp);
iter = ItemIter.get(xq.iter());
Item it;
while((it = iter.next()) != null) {
doc &= it.type == Type.DOC;
it.serialize(xml);
}
xml.close();
} catch(final Exception ex) {
if(!(ex instanceof QueryException || ex instanceof IOException)) {
System.err.println("\n*** " + outname + " ***");
System.err.println(in + "\n");
ex.printStackTrace();
}
er = ex.getMessage();
if(er.startsWith(STOPPED)) er = er.substring(er.indexOf('\n') + 1);
if(er.startsWith("[")) er = er.replaceAll("\\[(.*?)\\] (.*)", "$1 $2");
// unexpected error - dump stack trace
}
// print compilation steps
if(compile) {
Util.errln("
Util.err(xq.info());
Util.errln(in);
}
final Nodes outFiles = nodes("*:output-file/text()", state);
final Nodes cmpFiles = nodes("*:output-file/@compare", state);
boolean xml = false;
boolean frag = false;
final TokenList result = new TokenList();
for(int o = 0; o < outFiles.size(); ++o) {
final String resFile = string(data.atom(outFiles.nodes[o]));
final IO exp = IO.get(expected + pth + resFile);
result.add(read(exp));
final byte[] type = data.atom(cmpFiles.nodes[o]);
xml |= eq(type, XML);
frag |= eq(type, FRAGMENT);
}
String expError = text("*:expected-error/text()", state);
final StringBuilder log = new StringBuilder(pth + inname + IO.XQSUFFIX);
if(files.size() != 0) {
log.append(" [");
log.append(files);
log.append("]");
}
log.append(NL);
/** Remove comments. */
log.append(norm(in));
log.append(NL);
final String logStr = log.toString();
// skip queries with variable results
final boolean print = currTime || !logStr.contains("current-");
boolean correctError = false;
if(er != null && (outFiles.size() == 0 || !expError.isEmpty())) {
expError = error(pth + outname, expError);
final String code = er.substring(0, Math.min(8, er.length()));
for(final String e : SLASH.split(expError)) {
if(code.equals(e)) {
correctError = true;
break;
}
}
}
if(correctError) {
if(print) {
logOK.append(logStr);
logOK.append("[Right] ");
logOK.append(norm(er));
logOK.append(NL);
logOK.append(NL);
addLog(pth, outname + ".log", er);
}
++ok;
} else if(er == null) {
int s = -1;
final int rs = result.size();
while(++s < rs) {
inspect |= s < cmpFiles.nodes.length &&
eq(data.atom(cmpFiles.nodes[s]), INSPECT);
final byte[] res = result.get(s);
if(res.length == ao.size() && eq(res, ao.toArray())) break;
if(xml || frag) {
iter.reset();
String ri = string(res).trim();
if(!doc) {
if(ri.startsWith("<?xml")) ri = ri.replaceAll("^<.*?>\\s*", "");
ri = "<X>" + ri + "</X>";
}
try {
final Data rdata = CreateDB.xml(IO.get(ri), context);
final ItemIter ir = new ItemIter();
for(int pre = doc ? 0 : 2; pre < rdata.meta.size;) {
ir.add(new DBNode(rdata, pre));
pre += rdata.size(pre, rdata.kind(pre));
}
final boolean eq = FNSimple.deep(null, iter, ir);
if(!eq && debug) {
iter.reset();
ir.reset();
final XMLSerializer ser = new XMLSerializer(System.out);
Item it;
Util.outln(NL + "=== " + testid + " ===");
while((it = ir.next()) != null) it.serialize(ser);
Util.outln(NL + "=== " + NAME + " ===");
while((it = iter.next()) != null) it.serialize(ser);
Util.outln();
}
rdata.close();
if(eq) break;
} catch(final IOException ex) {
} catch(final Throwable ex) {
ex.printStackTrace();
}
}
}
if((rs > 0 || !expError.isEmpty()) && s == rs && !inspect) {
if(print) {
if(outFiles.size() == 0) result.add(error(pth + outname, expError));
logErr.append(logStr);
logErr.append("[" + testid + " ] ");
logErr.append(norm(string(result.get(0))));
logErr.append(NL);
logErr.append("[Wrong] ");
logErr.append(norm(ao.toString()));
logErr.append(NL);
logErr.append(NL);
addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"),
ao.toString());
}
correct = false;
++err;
} else {
if(print) {
logOK.append(logStr);
logOK.append("[Right] ");
logOK.append(norm(ao.toString()));
logOK.append(NL);
logOK.append(NL);
addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"),
ao.toString());
}
++ok;
}
} else {
if(outFiles.size() == 0 || !expError.isEmpty()) {
if(print) {
logOK2.append(logStr);
logOK2.append("[" + testid + " ] ");
logOK2.append(norm(expError));
logOK2.append(NL);
logOK2.append("[Rght?] ");
logOK2.append(norm(er));
logOK2.append(NL);
logOK2.append(NL);
addLog(pth, outname + ".log", er);
}
++ok2;
} else {
if(print) {
logErr2.append(logStr);
logErr2.append("[" + testid + " ] ");
logErr2.append(norm(string(result.get(0))));
logErr2.append(NL);
logErr2.append("[Wrong] ");
logErr2.append(norm(er));
logErr2.append(NL);
logErr2.append(NL);
addLog(pth, outname + ".log", er);
}
correct = false;
++err2;
}
}
if(curr != null) Close.close(context, curr.data);
xq.close();
}
if(reporting) {
logReport.append(" <test-case name=\"");
logReport.append(outname);
logReport.append("\" result='");
logReport.append(correct ? "pass" : "fail");
if(inspect) logReport.append("' todo='inspect");
logReport.append("'/>");
logReport.append(NL);
}
if(verbose) {
final long t = perf.getTime();
if(t > 100000000) Util.out(": " + Performance.getTimer(t, 1));
Util.outln();
}
return single == null || !outname.equals(single);
}
/**
* Normalizes the specified string.
* @param in input string
* @return result
*/
private String norm(final String in) {
final StringBuilder sb = new StringBuilder();
int m = 0;
boolean s = false;
final int cl = in.length();
for(int c = 0; c < cl && sb.length() < maxout; ++c) {
final char ch = in.charAt(c);
if(ch == '(' && c + 1 < cl && in.charAt(c + 1) == ':') {
if(m == 0 && !s) {
sb.append(' ');
s = true;
}
++m;
++c;
} else if(m != 0 && ch == ':' && c + 1 < cl && in.charAt(c + 1) == ')') {
--m;
++c;
} else if(m == 0) {
if(!s || ch > ' ') sb.append(ch);
s = ch <= ' ';
}
}
if(sb.length() >= maxout) sb.append("...");
return sb.toString().replaceAll("(\r|\n)+", " ").trim();
}
/**
* Initializes the input files, specified by the context nodes.
* @param nod variables
* @param var documents
* @param qp query processor
* @param first call
* @return string with input files
* @throws QueryException query exception
*/
private byte[] file(final Nodes nod, final Nodes var,
final QueryProcessor qp, final boolean first) throws QueryException {
final TokenBuilder tb = new TokenBuilder();
for(int c = 0; c < nod.size(); ++c) {
final byte[] nm = data.atom(nod.nodes[c]);
String src = srcs.get(string(nm));
if(tb.size() != 0) tb.add(", ");
tb.add(nm);
Expr expr = null;
if(src == null) {
expr = coll(nm, qp);
} else {
// assign document
FunDef def = FunDef.DOC;
if(!first) {
def = FunDef.DB;
src = IO.get(src).dbname();
}
// [CG] XQuery/Query Info
expr = def.newInstance(null, Str.get(src));
}
if(var != null) qp.bind(string(data.atom(var.nodes[c])), expr);
}
return tb.finish();
}
/**
* Assigns the nodes to the specified variables.
* @param nod nodes
* @param var variables
* @param qp query processor
* @throws QueryException query exception
*/
private void var(final Nodes nod, final Nodes var, final QueryProcessor qp)
throws QueryException {
for(int c = 0; c < nod.size(); ++c) {
final byte[] nm = data.atom(nod.nodes[c]);
final String src = srcs.get(string(nm));
final Item it = src == null ? coll(nm, qp) : Str.get(src);
qp.bind(string(data.atom(var.nodes[c])), it);
}
}
/**
* Assigns a collection.
* @param name collection name
* @param qp query processor
* @return expression
* @throws QueryException query exception
*/
private Uri coll(final byte[] name, final QueryProcessor qp)
throws QueryException {
// assign collection
final NodIter col = new NodIter();
for(final byte[] cl : colls.get(string(name))) {
if(new File(string(cl)).exists()) {
col.add(qp.ctx.doc(cl, true, false, null));
} else {
Util.errln("Warning: \"%\" not found.", cl);
}
}
qp.ctx.addColl(col, name);
return Uri.uri(name);
}
/**
* Evaluates the the input files and assigns the result to the specified
* variables.
* @param nod variables
* @param var documents
* @param pth file path
* @param qp query processor
* @throws Exception exception
*/
private void eval(final Nodes nod, final Nodes var, final String pth,
final QueryProcessor qp) throws Exception {
for(int c = 0; c < nod.size(); ++c) {
final String file = pth + string(data.atom(nod.nodes[c])) + IO.XQSUFFIX;
final String in = read(IO.get(queries + file));
final QueryProcessor xq = new QueryProcessor(in, context);
final Value val = xq.iter().finish();
qp.bind(string(data.atom(var.nodes[c])), val);
xq.close();
}
}
/**
* Adds a log file.
* @param pth file path
* @param nm file name
* @param msg message
* @throws Exception exception
*/
private void addLog(final String pth, final String nm, final String msg)
throws Exception {
if(reporting) {
final File file = new File(results + pth);
if(!file.exists()) file.mkdirs();
final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(results + pth + nm), UTF8));
bw.write(msg);
bw.close();
}
}
/**
* Returns an error message.
* @param nm test name
* @param error XQTS error
* @return error message
*/
private String error(final String nm, final String error) {
final String error2 = expected + nm + ".log";
final IO file = IO.get(error2);
return file.exists() ? error + "/" + read(file) : error;
}
/**
* Returns the resulting query text (text node or attribute value).
* @param qu query
* @param root root node
* @return attribute value
* @throws Exception exception
*/
protected String text(final String qu, final Nodes root) throws Exception {
final Nodes n = nodes(qu, root);
final TokenBuilder tb = new TokenBuilder();
for(int i = 0; i < n.size(); ++i) {
if(i != 0) tb.add('/');
tb.add(data.atom(n.nodes[i]));
}
return tb.toString();
}
/**
* Returns the resulting auxiliary uri in multiple strings.
* @param role role
* @param root root node
* @return attribute value
* @throws Exception exception
*/
protected String[] aux(final String role, final Nodes root) throws Exception {
return text("*:aux-URI[@role = '" + role + "']", root).split("/");
}
/**
* Returns the resulting query nodes.
* @param qu query
* @param root root node
* @return attribute value
* @throws Exception exception
*/
protected Nodes nodes(final String qu, final Nodes root) throws Exception {
return new QueryProcessor(qu, root, context).queryNodes();
}
/**
* Recursively deletes a directory.
* @param pth deletion path
*/
void delete(final File[] pth) {
for(final File f : pth) {
if(f.isDirectory()) delete(f.listFiles());
f.delete();
}
}
/**
* Adds the specified file to the writer.
* @param bw writer
* @param f file path
* @throws Exception exception
*/
private void write(final BufferedWriter bw, final String f) throws Exception {
final BufferedReader br = new BufferedReader(new
InputStreamReader(new FileInputStream(f), UTF8));
String line;
while((line = br.readLine()) != null) {
bw.write(line);
bw.write(NL);
}
br.close();
}
/**
* Returns the contents of the specified file.
* @param f file to be read
* @return content
*/
private String read(final IO f) {
try {
return TextInput.content(f).toString().replaceAll("\r\n?", "\n");
} catch(final IOException ex) {
ex.printStackTrace();
return "";
}
}
/**
* Initializes the test.
* @param root root nodes reference
* @throws Exception exception
*/
@SuppressWarnings("unused")
void init(final Nodes root) throws Exception { }
/**
* Performs test specific parsings.
* @param qp query processor
* @param root root nodes reference
* @throws Exception exception
*/
@SuppressWarnings("unused")
void parse(final QueryProcessor qp, final Nodes root) throws Exception { }
/**
* Returns all query states.
* @param root root node
* @return states
* @throws Exception exception
*/
@SuppressWarnings("unused")
Nodes states(final Nodes root) throws Exception {
return root;
}
}
|
package org.gitlab4j.api;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;
import org.gitlab4j.api.GitLabApi.ApiVersion;
import org.gitlab4j.api.models.CustomAttribute;
import org.gitlab4j.api.models.Email;
import org.gitlab4j.api.models.ImpersonationToken;
import org.gitlab4j.api.models.ImpersonationToken.Scope;
import org.gitlab4j.api.utils.EmailChecker;
import org.gitlab4j.api.models.SshKey;
import org.gitlab4j.api.models.User;
public class UserApi extends AbstractApi {
private boolean customAttributesEnabled = false;
public UserApi(GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Enables custom attributes to be returned when fetching User instances.
*/
public void enableCustomAttributes() {
customAttributesEnabled = true;
}
/**
* Disables custom attributes to be returned when fetching User instances.
*/
public void disableCustomAttributes() {
customAttributesEnabled = false;
}
public List<User> getUsers() throws GitLabApiException {
String url = this.gitLabApi.getGitLabServerUrl();
if (url.startsWith("https://gitlab.com")) {
GitLabApi.getLogger().warning("Fetching all users from " + url +
" may take many minutes to complete, use Pager<User> getUsers(int) instead.");
}
return (getUsers(getDefaultPerPage()).all());
}
/**
* Get a list of users using the specified page and per page settings.
*
* <pre><code>GitLab Endpoint: GET /users</code></pre>
*
* @param page the page to get
* @param perPage the number of users per page
* @return the list of Users in the specified range
* @throws GitLabApiException if any exception occurs
*/
public List<User> getUsers(int page, int perPage) throws GitLabApiException {
Response response = get(Response.Status.OK, getPageQueryParams(page, perPage, customAttributesEnabled), "users");
return (response.readEntity(new GenericType<List<User>>() {}));
}
/**
* Get a Pager of users.
*
* <pre><code>GitLab Endpoint: GET /users</code></pre>
*
* @param itemsPerPage the number of User instances that will be fetched per page
* @return a Pager of User
* @throws GitLabApiException if any exception occurs
*/
public Pager<User> getUsers(int itemsPerPage) throws GitLabApiException {
return (new Pager<User>(this, User.class, itemsPerPage, createGitLabApiForm().asMap(), "users"));
}
/**
* Get a Stream of users.
*
* <pre><code>GitLab Endpoint: GET /users</code></pre>
*
* @return a Stream of Users.
* @throws GitLabApiException if any exception occurs
*/
public Stream<User> getUsersStream() throws GitLabApiException {
return (getUsers(getDefaultPerPage()).stream());
}
/**
* Get a list of active users
*
* <pre><code>GitLab Endpoint: GET /users?active=true</code></pre>
*
* @return a list of active Users
* @throws GitLabApiException if any exception occurs
*/
public List<User> getActiveUsers() throws GitLabApiException {
return (getActiveUsers(getDefaultPerPage()).all());
}
/**
* Get a list of active users using the specified page and per page settings.
*
* <pre><code>GitLab Endpoint: GET /users?active=true</code></pre>
*
* @param page the page to get
* @param perPage the number of users per page
* @return the list of active Users in the specified range
* @throws GitLabApiException if any exception occurs
*/
public List<User> getActiveUsers(int page, int perPage) throws GitLabApiException {
GitLabApiForm formData = createGitLabApiForm()
.withParam("active", true)
.withParam(PAGE_PARAM, page)
.withParam(PER_PAGE_PARAM, perPage);
Response response = get(Response.Status.OK, formData.asMap(), "users");
return (response.readEntity(new GenericType<List<User>>() {}));
}
/**
* Get a Pager of active users.
*
* <pre><code>GitLab Endpoint: GET /users?active=true</code></pre>
*
* @param itemsPerPage the number of active User instances that will be fetched per page
* @return a Pager of active User
* @throws GitLabApiException if any exception occurs
*/
public Pager<User> getActiveUsers(int itemsPerPage) throws GitLabApiException {
GitLabApiForm formData = createGitLabApiForm().withParam("active", true);
return (new Pager<User>(this, User.class, itemsPerPage, formData.asMap(), "users"));
}
/**
* Get a Stream of active users
*
* <pre><code>GitLab Endpoint: GET /users?active=true</code></pre>
*
* @return a Stream of active Users
* @throws GitLabApiException if any exception occurs
*/
public Stream<User> getActiveUsersStream() throws GitLabApiException {
return (getActiveUsers(getDefaultPerPage()).stream());
}
/**
* Blocks the specified user. Available only for admin.
*
* <pre><code>GitLab Endpoint: POST /users/:id/block</code></pre>
*
* @param userId the ID of the user to block
* @throws GitLabApiException if any exception occurs
*/
public void blockUser(Integer userId) throws GitLabApiException {
if (userId == null) {
throw new RuntimeException("userId cannot be null");
}
if (isApiVersion(ApiVersion.V3)) {
put(Response.Status.CREATED, null, "users", userId, "block");
} else {
post(Response.Status.CREATED, (Form) null, "users", userId, "block");
}
}
/**
* Unblocks the specified user. Available only for admin.
*
* <pre><code>GitLab Endpoint: POST /users/:id/unblock</code></pre>
*
* @param userId the ID of the user to unblock
* @throws GitLabApiException if any exception occurs
*/
public void unblockUser(Integer userId) throws GitLabApiException {
if (userId == null) {
throw new RuntimeException("userId cannot be null");
}
if (isApiVersion(ApiVersion.V3)) {
put(Response.Status.CREATED, null, "users", userId, "unblock");
} else {
post(Response.Status.CREATED, (Form) null, "users", userId, "unblock");
}
}
/**
* Get a list of blocked users.
*
* <pre><code>GitLab Endpoint: GET /users?blocked=true</code></pre>
*
* @return a list of blocked Users
* @throws GitLabApiException if any exception occurs
*/
public List<User> getBlockedUsers() throws GitLabApiException {
return (getBlockedUsers(getDefaultPerPage()).all());
}
/**
* Get a list of blocked users using the specified page and per page settings.
*
* <pre><code>GitLab Endpoint: GET /users?blocked=true</code></pre>
*
* @param page the page to get
* @param perPage the number of users per page
* @return the list of blocked Users in the specified range
* @throws GitLabApiException if any exception occurs
*/
public List<User> getblockedUsers(int page, int perPage) throws GitLabApiException {
GitLabApiForm formData = createGitLabApiForm()
.withParam("blocked", true)
.withParam(PAGE_PARAM, page)
.withParam(PER_PAGE_PARAM, perPage);
Response response = get(Response.Status.OK, formData.asMap(), "users");
return (response.readEntity(new GenericType<List<User>>() {}));
}
/**
* Get a Pager of blocked users.
*
* <pre><code>GitLab Endpoint: GET /users?blocked=true</code></pre>
*
* @param itemsPerPage the number of blocked User instances that will be fetched per page
* @return a Pager of blocked User
* @throws GitLabApiException if any exception occurs
*/
public Pager<User> getBlockedUsers(int itemsPerPage) throws GitLabApiException {
GitLabApiForm formData = createGitLabApiForm().withParam("blocked", true);
return (new Pager<User>(this, User.class, itemsPerPage, formData.asMap(), "users"));
}
/**
* Get a Stream of blocked users.
*
* <pre><code>GitLab Endpoint: GET /users?blocked=true</code></pre>
*
* @return a Stream of blocked Users
* @throws GitLabApiException if any exception occurs
*/
public Stream<User> getBlockedUsersStream() throws GitLabApiException {
return (getBlockedUsers(getDefaultPerPage()).stream());
}
/**
* Get a single user.
*
* <pre><code>GitLab Endpoint: GET /users/:id</code></pre>
*
* @param userId the ID of the user to get
* @return the User instance for the specified user ID
* @throws GitLabApiException if any exception occurs
*/
public User getUser(Integer userId) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm().withParam("with_custom_attributes", customAttributesEnabled);
Response response = get(Response.Status.OK, formData.asMap(), "users", userId);
return (response.readEntity(User.class));
}
/**
* Get a single user as an Optional instance.
*
* <pre><code>GitLab Endpoint: GET /users/:id</code></pre>
*
* @param userId the ID of the user to get
* @return the User for the specified user ID as an Optional instance
*/
public Optional<User> getOptionalUser(Integer userId) {
try {
return (Optional.ofNullable(getUser(userId)));
} catch (GitLabApiException glae) {
return (GitLabApi.createOptionalFromException(glae));
}
}
/**
* Lookup a user by username. Returns null if not found.
*
* <p>NOTE: This is for admin users only.</p>
*
* <pre><code>GitLab Endpoint: GET /users?username=:username</code></pre>
*
* @param username the username of the user to get
* @return the User instance for the specified username, or null if not found
* @throws GitLabApiException if any exception occurs
*/
public User getUser(String username) throws GitLabApiException {
GitLabApiForm formData = createGitLabApiForm()
.withParam("username", username, true)
.withParam(PAGE_PARAM, 1)
.withParam(PER_PAGE_PARAM, 1);
Response response = get(Response.Status.OK, formData.asMap(), "users");
List<User> users = response.readEntity(new GenericType<List<User>>() {});
return (users.isEmpty() ? null : users.get(0));
}
/**
* Lookup a user by username and return an Optional instance.
*
* <p>NOTE: This is for admin users only.</p>
*
* <pre><code>GitLab Endpoint: GET /users?username=:username</code></pre>
*
* @param username the username of the user to get
* @return the User for the specified username as an Optional instance
*/
public Optional<User> getOptionalUser(String username) {
try {
return (Optional.ofNullable(getUser(username)));
} catch (GitLabApiException glae) {
return (GitLabApi.createOptionalFromException(glae));
}
}
public User getUserByEmail(String email) throws GitLabApiException {
if (!EmailChecker.isValidEmail(email)) {
throw new IllegalArgumentException("email is not valid");
}
List<User> users = findUsers(email, 1, 1);
return (users.isEmpty() ? null : users.get(0));
}
/**
* Lookup a user by email address and returns an Optional with the User instance as the value.
*
* <pre><code>GitLab Endpoint: GET /users?search=:email_or_username</code></pre>
*
* @param email the email of the user to get
* @return the User for the specified email as an Optional instance
*/
public Optional<User> getOptionalUserByEmail(String email) {
try {
return (Optional.ofNullable(getUserByEmail(email)));
} catch (GitLabApiException glae) {
return (GitLabApi.createOptionalFromException(glae));
}
}
/**
* Lookup a user by external UID. Returns null if not found.
*
* <p>NOTE: This is for admin users only.</p>
*
* <pre><code>GitLab Endpoint: GET /users?extern_uid=:externalUid&provider=:provider</code></pre>
*
* @param provider the provider of the external uid
* @param externalUid the external UID of the user
* @return the User instance for the specified external UID, or null if not found
* @throws GitLabApiException if any exception occurs
*/
public User getUserByExternalUid(String provider, String externalUid) throws GitLabApiException {
GitLabApiForm formData = createGitLabApiForm()
.withParam("provider", provider, true)
.withParam("extern_uid", externalUid, true)
.withParam(PAGE_PARAM, 1)
.withParam(PER_PAGE_PARAM, 1);
Response response = get(Response.Status.OK, formData.asMap(), "users");
List<User> users = response.readEntity(new GenericType<List<User>>() {});
return (users.isEmpty() ? null : users.get(0));
}
/**
* Lookup a user by external UID and return an Optional instance.
*
* <p>NOTE: This is for admin users only.</p>
*
* <pre><code>GitLab Endpoint: GET /users?extern_uid=:externUid&provider=:provider</code></pre>
*
* @param provider the provider of the external uid
* @param externalUid the external UID of the user
* @return the User for the specified external UID as an Optional instance
*/
public Optional<User> getOptionalUserByExternalUid(String provider, String externalUid) {
try {
return (Optional.ofNullable(getUserByExternalUid(provider, externalUid)));
} catch (GitLabApiException glae) {
return (GitLabApi.createOptionalFromException(glae));
}
}
/**
* Search users by Email or username
*
* <pre><code>GitLab Endpoint: GET /users?search=:email_or_username</code></pre>
*
* @param emailOrUsername the email or username to search for
* @return the User List with the email or username like emailOrUsername
* @throws GitLabApiException if any exception occurs
*/
public List<User> findUsers(String emailOrUsername) throws GitLabApiException {
return (findUsers(emailOrUsername, getDefaultPerPage()).all());
}
/**
* Search users by Email or username in the specified page range.
*
* <pre><code>GitLab Endpoint: GET /users?search=:email_or_username</code></pre>
*
* @param emailOrUsername the email or username to search for
* @param page the page to get
* @param perPage the number of users per page
* @return the User List with the email or username like emailOrUsername in the specified page range
* @throws GitLabApiException if any exception occurs
*/
public List<User> findUsers(String emailOrUsername, int page, int perPage) throws GitLabApiException {
GitLabApiForm formData = createGitLabApiForm()
.withParam("search", emailOrUsername, true)
.withParam(PAGE_PARAM, page)
.withParam(PER_PAGE_PARAM, perPage);
Response response = get(Response.Status.OK, formData.asMap(), "users");
return (response.readEntity(new GenericType<List<User>>() {
}));
}
/**
* Search users by Email or username and return a Pager
*
* <pre><code>GitLab Endpoint: GET /users?search=:email_or_username</code></pre>
*
* @param emailOrUsername the email or username to search for
* @param itemsPerPage the number of Project instances that will be fetched per page
* @return the User Pager with the email or username like emailOrUsername
* @throws GitLabApiException if any exception occurs
*/
public Pager<User> findUsers(String emailOrUsername, int itemsPerPage) throws GitLabApiException {
GitLabApiForm formData = createGitLabApiForm().withParam("search", emailOrUsername, true);
return (new Pager<User>(this, User.class, itemsPerPage, formData.asMap(), "users"));
}
/**
* Search users by Email or username.
*
* <pre><code>GitLab Endpoint: GET /users?search=:email_or_username</code></pre>
*
* @param emailOrUsername the email or username to search for
* @return a Stream of User instances with the email or username like emailOrUsername
* @throws GitLabApiException if any exception occurs
*/
public Stream<User> findUsersStream(String emailOrUsername) throws GitLabApiException {
return (findUsers(emailOrUsername, getDefaultPerPage()).stream());
}
/**
* <p>Creates a new user. Note only administrators can create new users.
* Either password or reset_password should be specified (reset_password takes priority).</p>
*
* <p>If both the User object's projectsLimit and the parameter projectsLimit is specified
* the parameter will take precedence.</p>
*
* <pre><code>GitLab Endpoint: POST /users</code></pre>
*
* <p>The following properties of the provided User instance can be set during creation:<pre><code> email (required) - Email
* username (required) - Username
* name (required) - Name
* skype (optional) - Skype ID
* linkedin (optional) - LinkedIn
* twitter (optional) - Twitter account
* websiteUrl (optional) - Website URL
* organization (optional) - Organization name
* projectsLimit (optional) - Number of projects user can create
* externUid (optional) - External UID
* provider (optional) - External provider name
* bio (optional) - User's biography
* location (optional) - User's location
* admin (optional) - User is admin - true or false (default)
* canCreateGroup (optional) - User can create groups - true or false
* skipConfirmation (optional) - Skip confirmation - true or false (default)
* external (optional) - Flags the user as external - true or false(default)
* sharedRunnersMinutesLimit (optional) - Pipeline minutes quota for this user
* </code></pre>
*
* @param user the User instance with the user info to create
* @param password the password for the new user
* @param projectsLimit the maximum number of project
* @return created User instance
* @throws GitLabApiException if any exception occurs
* @deprecated Will be removed in version 5.0, replaced by {@link #createUser(User, CharSequence, boolean)}
*/
public User createUser(User user, CharSequence password, Integer projectsLimit) throws GitLabApiException {
Form formData = userToForm(user, projectsLimit, password, null, true);
Response response = post(Response.Status.CREATED, formData, "users");
return (response.readEntity(User.class));
}
/**
* <p>Creates a new user. Note only administrators can create new users.
* Either password or resetPassword should be specified (resetPassword takes priority).</p>
*
* <pre><code>GitLab Endpoint: POST /users</code></pre>
*
* <p>The following properties of the provided User instance can be set during creation:<pre><code> email (required) - Email
* username (required) - Username
* name (required) - Name
* skype (optional) - Skype ID
* linkedin (optional) - LinkedIn
* twitter (optional) - Twitter account
* websiteUrl (optional) - Website URL
* organization (optional) - Organization name
* projectsLimit (optional) - Number of projects user can create
* externUid (optional) - External UID
* provider (optional) - External provider name
* bio (optional) - User's biography
* location (optional) - User's location
* admin (optional) - User is admin - true or false (default)
* canCreateGroup (optional) - User can create groups - true or false
* skipConfirmation (optional) - Skip confirmation - true or false (default)
* external (optional) - Flags the user as external - true or false(default)
* sharedRunnersMinutesLimit (optional) - Pipeline minutes quota for this user
* </code></pre>
*
* @param user the User instance with the user info to create
* @param password the password for the new user
* @param resetPassword whether to send a password reset link
* @return created User instance
* @throws GitLabApiException if any exception occurs
*/
public User createUser(User user, CharSequence password, boolean resetPassword) throws GitLabApiException {
Form formData = userToForm(user, null, password, resetPassword, true);
Response response = post(Response.Status.CREATED, formData, "users");
return (response.readEntity(User.class));
}
public User updateUser(User user, CharSequence password) throws GitLabApiException {
Form form = userToForm(user, null, password, false, false);
Response response = put(Response.Status.OK, form.asMap(), "users", user.getId());
return (response.readEntity(User.class));
}
@Deprecated
public User modifyUser(User user, CharSequence password, Integer projectsLimit) throws GitLabApiException {
Form form = userToForm(user, projectsLimit, password, false, false);
Response response = put(Response.Status.OK, form.asMap(), "users", user.getId());
return (response.readEntity(User.class));
}
/**
* Deletes a user. Available only for administrators.
*
* <pre><code>GitLab Endpoint: DELETE /users/:id</code></pre>
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @throws GitLabApiException if any exception occurs
*/
public void deleteUser(Object userIdOrUsername) throws GitLabApiException {
deleteUser(userIdOrUsername, null);
}
/**
* Deletes a user. Available only for administrators.
*
* <pre><code>GitLab Endpoint: DELETE /users/:id</code></pre>
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @param hardDelete If true, contributions that would usually be moved to the
* ghost user will be deleted instead, as well as groups owned solely by this user
* @throws GitLabApiException if any exception occurs
*/
public void deleteUser(Object userIdOrUsername, Boolean hardDelete) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm().withParam("hard_delete ", hardDelete);
Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT);
delete(expectedStatus, formData.asMap(), "users", getUserIdOrUsername(userIdOrUsername));
}
/**
* Get currently authenticated user.
*
* <pre><code>GitLab Endpoint: GET /user</code></pre>
*
* @return the User instance for the currently authenticated user
* @throws GitLabApiException if any exception occurs
*/
public User getCurrentUser() throws GitLabApiException {
Response response = get(Response.Status.OK, null, "user");
return (response.readEntity(User.class));
}
/**
* Get a list of currently authenticated user's SSH keys.
*
* <pre><code>GitLab Endpoint: GET /user/keys</code></pre>
*
* @return a list of currently authenticated user's SSH keys
* @throws GitLabApiException if any exception occurs
*/
public List<SshKey> getSshKeys() throws GitLabApiException {
Response response = get(Response.Status.OK, getDefaultPerPageParam(), "user", "keys");
return (response.readEntity(new GenericType<List<SshKey>>() {}));
}
/**
* Get a list of a specified user's SSH keys. Available only for admin users.
*
* <pre><code>GitLab Endpoint: GET /users/:id/keys</code></pre>
*
* @param userId the user ID to get the SSH keys for
* @return a list of a specified user's SSH keys
* @throws GitLabApiException if any exception occurs
*/
public List<SshKey> getSshKeys(Integer userId) throws GitLabApiException {
if (userId == null) {
throw new RuntimeException("userId cannot be null");
}
Response response = get(Response.Status.OK, getDefaultPerPageParam(), "users", userId, "keys");
List<SshKey> keys = response.readEntity(new GenericType<List<SshKey>>() {});
if (keys != null) {
keys.forEach(key -> key.setUserId(userId));
}
return (keys);
}
/**
* Get a single SSH Key.
*
* <pre><code>GitLab Endpoint: GET /user/keys/:key_id</code></pre>
*
* @param keyId the ID of the SSH key.
* @return an SshKey instance holding the info on the SSH key specified by keyId
* @throws GitLabApiException if any exception occurs
*/
public SshKey getSshKey(Integer keyId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "user", "keys", keyId);
return (response.readEntity(SshKey.class));
}
/**
* Get a single SSH Key as an Optional instance.
*
* <pre><code>GitLab Endpoint: GET /user/keys/:key_id</code></pre>
*
* @param keyId the ID of the SSH key
* @return an SshKey as an Optional instance holding the info on the SSH key specified by keyId
*/
public Optional<SshKey> getOptionalSshKey(Integer keyId) {
try {
return (Optional.ofNullable(getSshKey(keyId)));
} catch (GitLabApiException glae) {
return (GitLabApi.createOptionalFromException(glae));
}
}
/**
* Creates a new key owned by the currently authenticated user.
*
* <pre><code>GitLab Endpoint: POST /user/keys</code></pre>
*
* @param title the new SSH Key's title
* @param key the new SSH key
* @return an SshKey instance with info on the added SSH key
* @throws GitLabApiException if any exception occurs
*/
public SshKey addSshKey(String title, String key) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm().withParam("title", title).withParam("key", key);
Response response = post(Response.Status.CREATED, formData, "user", "keys");
return (response.readEntity(SshKey.class));
}
/**
* Create new key owned by specified user. Available only for admin users.
*
* <pre><code>GitLab Endpoint: POST /users/:id/keys</code></pre>
*
* @param userId the ID of the user to add the SSH key for
* @param title the new SSH Key's title
* @param key the new SSH key
* @return an SshKey instance with info on the added SSH key
* @throws GitLabApiException if any exception occurs
*/
public SshKey addSshKey(Integer userId, String title, String key) throws GitLabApiException {
if (userId == null) {
throw new RuntimeException("userId cannot be null");
}
GitLabApiForm formData = new GitLabApiForm().withParam("title", title).withParam("key", key);
Response response = post(Response.Status.CREATED, formData, "users", userId, "keys");
SshKey sshKey = response.readEntity(SshKey.class);
if (sshKey != null) {
sshKey.setUserId(userId);
}
return (sshKey);
}
/**
* Deletes key owned by currently authenticated user. This is an idempotent function and calling it
* on a key that is already deleted or not available results in success.
*
* <pre><code>GitLab Endpoint: DELETE /user/keys/:key_id</code></pre>
*
* @param keyId the key ID to delete
* @throws GitLabApiException if any exception occurs
*/
public void deleteSshKey(Integer keyId) throws GitLabApiException {
if (keyId == null) {
throw new RuntimeException("keyId cannot be null");
}
Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT);
delete(expectedStatus, null, "user", "keys", keyId);
}
/**
* Deletes key owned by a specified user. Available only for admin users.
*
* <pre><code>GitLab Endpoint: DELETE /users/:id/keys/:key_id</code></pre>
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @param keyId the key ID to delete
* @throws GitLabApiException if any exception occurs
*/
public void deleteSshKey(Object userIdOrUsername, Integer keyId) throws GitLabApiException {
if (keyId == null) {
throw new RuntimeException("keyId cannot be null");
}
Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT);
delete(expectedStatus, null, "users", getUserIdOrUsername(userIdOrUsername), "keys", keyId);
}
/**
* Get a list of a specified user's impersonation tokens. Available only for admin users.
*
* <pre><code>GitLab Endpoint: GET /users/:id/impersonation_tokens</code></pre>
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @return a list of a specified user's impersonation tokens
* @throws GitLabApiException if any exception occurs
*/
public List<ImpersonationToken> getImpersonationTokens(Object userIdOrUsername) throws GitLabApiException {
return (getImpersonationTokens(userIdOrUsername, null));
}
/**
* Get a list of a specified user's impersonation tokens. Available only for admin users.
*
* <pre><code>GitLab Endpoint: GET /users/:id/impersonation_tokens</code></pre>
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @param state the state of impersonation tokens to list (ALL, ACTIVE, INACTIVE)
* @return a list of a specified user's impersonation tokens
* @throws GitLabApiException if any exception occurs
*/
public List<ImpersonationToken> getImpersonationTokens(Object userIdOrUsername, ImpersonationState state) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("state", state)
.withParam(PER_PAGE_PARAM, getDefaultPerPage());
Response response = get(Response.Status.OK, formData.asMap(), "users", getUserIdOrUsername(userIdOrUsername), "impersonation_tokens");
return (response.readEntity(new GenericType<List<ImpersonationToken>>() {}));
}
/**
* Get an impersonation token of a user. Available only for admin users.
*
* <pre><code>GitLab Endpoint: GET /users/:user_id/impersonation_tokens/:impersonation_token_id</code></pre>
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @param tokenId the impersonation token ID to get
* @return the specified impersonation token
* @throws GitLabApiException if any exception occurs
*/
public ImpersonationToken getImpersonationToken(Object userIdOrUsername, Integer tokenId) throws GitLabApiException {
if (tokenId == null) {
throw new RuntimeException("tokenId cannot be null");
}
Response response = get(Response.Status.OK, null, "users", getUserIdOrUsername(userIdOrUsername), "impersonation_tokens", tokenId);
return (response.readEntity(ImpersonationToken.class));
}
/**
* Get an impersonation token of a user as an Optional instance. Available only for admin users.
*
* <pre><code>GitLab Endpoint: GET /users/:user_id/impersonation_tokens/:impersonation_token_id</code></pre>
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @param tokenId the impersonation token ID to get
* @return the specified impersonation token as an Optional instance
*/
public Optional<ImpersonationToken> getOptionalImpersonationToken(Object userIdOrUsername, Integer tokenId) {
try {
return (Optional.ofNullable(getImpersonationToken(userIdOrUsername, tokenId)));
} catch (GitLabApiException glae) {
return (GitLabApi.createOptionalFromException(glae));
}
}
/**
* Create an impersonation token. Available only for admin users.
*
* <pre><code>GitLab Endpoint: POST /users/:user_id/impersonation_tokens</code></pre>
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @param name the name of the impersonation token, required
* @param expiresAt the expiration date of the impersonation token, optional
* @param scopes an array of scopes of the impersonation token
* @return the created ImpersonationToken instance
* @throws GitLabApiException if any exception occurs
*/
public ImpersonationToken createImpersonationToken(Object userIdOrUsername, String name, Date expiresAt, Scope[] scopes) throws GitLabApiException {
if (scopes == null || scopes.length == 0) {
throw new RuntimeException("scopes cannot be null or empty");
}
GitLabApiForm formData = new GitLabApiForm()
.withParam("name", name, true)
.withParam("expires_at", expiresAt);
for (Scope scope : scopes) {
formData.withParam("scopes[]", scope.toString());
}
Response response = post(Response.Status.CREATED, formData, "users", getUserIdOrUsername(userIdOrUsername), "impersonation_tokens");
return (response.readEntity(ImpersonationToken.class));
}
/**
* Revokes an impersonation token. Available only for admin users.
*
* <pre><code>GitLab Endpoint: DELETE /users/:user_id/impersonation_tokens/:impersonation_token_id</code></pre>
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @param tokenId the impersonation token ID to revoke
* @throws GitLabApiException if any exception occurs
*/
public void revokeImpersonationToken(Object userIdOrUsername, Integer tokenId) throws GitLabApiException {
if (tokenId == null) {
throw new RuntimeException("tokenId cannot be null");
}
Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT);
delete(expectedStatus, null, "users", getUserIdOrUsername(userIdOrUsername), "impersonation_tokens", tokenId);
}
/**
* Populate the REST form with data from the User instance.
*
* @param user the User instance to populate the Form instance with
* @param projectsLimit the maximum number of projects the user is allowed (optional)
* @param password the password, required when creating a new user
* @param create whether the form is being populated to create a new user
* @return the populated Form instance
*/
Form userToForm(User user, Integer projectsLimit, CharSequence password, Boolean resetPassword, boolean create) {
if (create) {
if ((password == null || password.toString().trim().isEmpty()) && !resetPassword) {
throw new IllegalArgumentException("either password or reset_password must be set");
}
}
projectsLimit = (projectsLimit == null) ? user.getProjectsLimit() : projectsLimit;
String skipConfirmationFeildName = create ? "skip_confirmation" : "skip_reconfirmation";
return (new GitLabApiForm()
.withParam("email", user.getEmail(), create)
.withParam("password", password, false)
.withParam("reset_password", resetPassword, false)
.withParam("username", user.getUsername(), create)
.withParam("name", user.getName(), create)
.withParam("skype", user.getSkype(), false)
.withParam("linkedin", user.getLinkedin(), false)
.withParam("twitter", user.getTwitter(), false)
.withParam("website_url", user.getWebsiteUrl(), false)
.withParam("organization", user.getOrganization(), false)
.withParam("projects_limit", projectsLimit, false)
.withParam("extern_uid", user.getExternUid(), false)
.withParam("provider", user.getProvider(), false)
.withParam("bio", user.getBio(), false)
.withParam("location", user.getLocation(), false)
.withParam("admin", user.getIsAdmin(), false)
.withParam("can_create_group", user.getCanCreateGroup(), false)
.withParam(skipConfirmationFeildName, user.getSkipConfirmation(), false)
.withParam("external", user.getExternal(), false)
.withParam("shared_runners_minutes_limit", user.getSharedRunnersMinutesLimit(), false));
}
/**
* Creates custom attribute for the given user
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @param customAttribute the custom attribute to set
* @return the created CustomAttribute
* @throws GitLabApiException on failure while setting customAttributes
*/
public CustomAttribute createCustomAttribute(final Object userIdOrUsername, final CustomAttribute customAttribute) throws GitLabApiException {
if (Objects.isNull(customAttribute)) {
throw new IllegalArgumentException("CustomAttributes can't be null");
}
return createCustomAttribute(userIdOrUsername, customAttribute.getKey(), customAttribute.getValue());
}
/**
* Creates custom attribute for the given user
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @param key for the customAttribute
* @param value or the customAttribute
* @return the created CustomAttribute
* @throws GitLabApiException on failure while setting customAttributes
*/
public CustomAttribute createCustomAttribute(final Object userIdOrUsername, final String key, final String value) throws GitLabApiException {
if (Objects.isNull(key) || key.trim().isEmpty()) {
throw new IllegalArgumentException("Key can't be null or empty");
}
if (Objects.isNull(value) || value.trim().isEmpty()) {
throw new IllegalArgumentException("Value can't be null or empty");
}
GitLabApiForm formData = new GitLabApiForm().withParam("value", value);
Response response = put(Response.Status.OK, formData.asMap(),
"users", getUserIdOrUsername(userIdOrUsername), "custom_attributes", key);
return (response.readEntity(CustomAttribute.class));
}
/**
* Change custom attribute for the given user
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @param customAttribute the custome attribute to change
* @return the changed CustomAttribute
* @throws GitLabApiException on failure while changing customAttributes
*/
public CustomAttribute changeCustomAttribute(final Object userIdOrUsername, final CustomAttribute customAttribute) throws GitLabApiException {
if (Objects.isNull(customAttribute)) {
throw new IllegalArgumentException("CustomAttributes can't be null");
}
//changing & creating custom attributes is the same call in gitlab api
// -> https://docs.gitlab.com/ce/api/custom_attributes.html#set-custom-attribute
return createCustomAttribute(userIdOrUsername, customAttribute.getKey(), customAttribute.getValue());
}
/**
* Changes custom attribute for the given user
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @param key for the customAttribute
* @param value for the customAttribute
* @return changedCustomAttribute
* @throws GitLabApiException on failure while changing customAttributes
*/
public CustomAttribute changeCustomAttribute(final Object userIdOrUsername, final String key, final String value) throws GitLabApiException {
return createCustomAttribute(userIdOrUsername, key, value);
}
/**
* Delete a custom attribute for the given user
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @param customAttribute to remove
* @throws GitLabApiException on failure while deleting customAttributes
*/
public void deleteCustomAttribute(final Object userIdOrUsername, final CustomAttribute customAttribute) throws GitLabApiException {
if (Objects.isNull(customAttribute)) {
throw new IllegalArgumentException("customAttributes can't be null");
}
deleteCustomAttribute(userIdOrUsername, customAttribute.getKey());
}
/**
* Delete a custom attribute for the given user
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @param key of the customAttribute to remove
* @throws GitLabApiException on failure while deleting customAttributes
*/
public void deleteCustomAttribute(final Object userIdOrUsername, final String key) throws GitLabApiException {
if (Objects.isNull(key) || key.trim().isEmpty()) {
throw new IllegalArgumentException("Key can't be null or empty");
}
delete(Response.Status.OK, null, "users", getUserIdOrUsername(userIdOrUsername), "custom_attributes", key);
}
/**
* Creates a GitLabApiForm instance that will optionally include the
* with_custom_attributes query param if enabled.
*
* @return a GitLabApiForm instance that will optionally include the
* with_custom_attributes query param if enabled
*/
private GitLabApiForm createGitLabApiForm() {
GitLabApiForm formData = new GitLabApiForm();
return (customAttributesEnabled ? formData.withParam("with_custom_attributes", true) : formData);
}
/**
* Uploads and sets the user's avatar for the specified user.
*
* <pre><code>PUT /users/:id</code></pre>
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @param avatarFile the File instance of the avatar file to upload
* @return the updated User instance
* @throws GitLabApiException if any exception occurs
*/
public User setUserAvatar(final Object userIdOrUsername, File avatarFile) throws GitLabApiException {
Response response = putUpload(Response.Status.OK, "avatar", avatarFile, "users", getUserIdOrUsername(userIdOrUsername));
return (response.readEntity(User.class));
}
/**
* Get a list of emails for the current user.
*
* <pre><code>GitLab Endpoint: GET /users/emails</code></pre>
*
* @return a List of Email instances for the current user
* @throws GitLabApiException if any exception occurs
*/
public List<Email> getEmails() throws GitLabApiException {
Response response = get(Response.Status.OK, null, "user", "emails");
return (response.readEntity(new GenericType<List<Email>>() {}));
}
public List<Email> getEmails(final Object userIdOrUsername) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "users", getUserIdOrUsername(userIdOrUsername), "emails");
return (response.readEntity(new GenericType<List<Email>>() {}));
}
/**
* Add an email to the current user's emails.
*
* <pre><code>GitLab Endpoint: POST /user/:id/emails</code></pre>
*
* @param email the email address to add
* @return the Email instance for the added email
* @throws GitLabApiException if any exception occurs
*/
public Email addEmail(String email) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm().withParam("email", email, true);
Response response = post(Response.Status.CREATED, formData, "user", "emails");
return (response.readEntity(Email.class));
}
/**
* Get a single Email instance specified by he email ID
*
* <pre><code>GitLab Endpoint: GET /user/emails/:emailId</code></pre>
*
* @param emailId the email ID to get
* @return the Email instance for the provided email ID
* @throws GitLabApiException if any exception occurs
*/
public Email getEmail(final Long emailId) throws GitLabApiException {
Response response = get(Response.Status.CREATED, null, "user", "emails", emailId);
return (response.readEntity(Email.class));
}
/**
* Add an email to the user's emails.
*
* <pre><code>GitLab Endpoint: POST /user/:id/emails</code></pre>
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @param email the email address to add
* @param skipConfirmation skip confirmation and assume e-mail is verified - true or false (default)
* @return the Email instance for the added email
* @throws GitLabApiException if any exception occurs
*/
public Email addEmail(final Object userIdOrUsername, String email, Boolean skipConfirmation) throws GitLabApiException {
GitLabApiForm formData = new GitLabApiForm()
.withParam("email", email, true)
.withParam("skip_confirmation ", skipConfirmation);
Response response = post(Response.Status.CREATED, formData, "users", getUserIdOrUsername(userIdOrUsername), "emails");
return (response.readEntity(Email.class));
}
/**
* Deletes an email belonging to the current user.
*
* <pre><code>GitLab Endpoint: DELETE /user/emails/:emailId</code></pre>
*
* @param emailId the email ID to delete
* @throws GitLabApiException if any exception occurs
*/
public void deleteEmail(final Long emailId) throws GitLabApiException {
delete(Response.Status.NO_CONTENT, null, "user", "emails", emailId);
}
/**
* Deletes a user's email
*
* <pre><code>GitLab Endpoint: DELETE /user/:id/emails/:emailId</code></pre>
*
* @param userIdOrUsername the user in the form of an Integer(ID), String(username), or User instance
* @param emailId the email ID to delete
* @throws GitLabApiException if any exception occurs
*/
public void deleteEmail(final Object userIdOrUsername, final Long emailId) throws GitLabApiException {
delete(Response.Status.NO_CONTENT, null, "users", getUserIdOrUsername(userIdOrUsername), "emails", emailId);
}
}
|
package org.graylog2;
import org.json.simple.JSONValue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.zip.GZIPOutputStream;
public class GelfMessage {
private static final String ID_NAME = "id";
private static final String GELF_VERSION = "1.0";
private static final byte[] GELF_CHUNKED_ID = new byte[]{0x1e, 0x0f};
private static final int MAXIMUM_CHUNK_SIZE = 1420;
private String version = GELF_VERSION;
private String host;
private byte[] hostBytes = lastFourAsciiBytes("none");
private String shortMessage;
private String fullMessage;
private Long timestamp;
private long javaTimestamp;
private String level;
private String facility = "gelf-java";
private String line;
private String file;
private Map<String, Object> additonalFields = new HashMap<String, Object>();
public GelfMessage() {
}
// todo: merge these constructors.
public GelfMessage(String shortMessage, String fullMessage, Date timestamp, String level) {
this.shortMessage = shortMessage;
this.fullMessage = fullMessage;
this.javaTimestamp = timestamp.getTime();
this.timestamp = javaTimestamp / 1000L;
this.level = level;
}
public GelfMessage(String shortMessage, String fullMessage, Long timestamp, String level, String line, String file) {
this.shortMessage = shortMessage;
this.fullMessage = fullMessage;
this.javaTimestamp = timestamp;
this.timestamp = javaTimestamp / 1000L;
this.level = level;
this.line = line;
this.file = file;
}
public String toJson() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("version", getVersion());
map.put("host", getHost());
map.put("short_message", getShortMessage());
map.put("full_message", getFullMessage());
map.put("timestamp", getTimestamp().intValue());
map.put("level", getLevel());
map.put("facility", getFacility());
map.put("file", getFile());
map.put("line", getLine());
for (Map.Entry<String, Object> additionalField : additonalFields.entrySet()) {
if (!ID_NAME.equals(additionalField.getKey())) {
map.put("_" + additionalField.getKey(), additionalField.getValue());
}
}
return JSONValue.toJSONString(map);
}
public List<byte[]> toDatagrams() {
byte[] messageBytes = gzipMessage(toJson());
List<byte[]> datagrams = new ArrayList<byte[]>();
if (messageBytes.length > MAXIMUM_CHUNK_SIZE) {
sliceDatagrams(messageBytes, datagrams);
} else {
datagrams.add(messageBytes);
}
return datagrams;
}
private void sliceDatagrams(byte[] messageBytes, List<byte[]> datagrams) {
int messageLength = messageBytes.length;
byte[] messageId = ByteBuffer.allocate(8)
.putInt((int) System.currentTimeMillis()) // 4 least-significant-bytes of the time in millis
.put(hostBytes) // 4 least-significant-bytes of the host
.array();
int num = ((Double) Math.ceil((double) messageLength / MAXIMUM_CHUNK_SIZE)).intValue();
for (int idx = 0; idx < num; idx++) {
byte[] header = concatByteArray(GELF_CHUNKED_ID, concatByteArray(messageId, new byte[]{(byte) idx, (byte) num}));
int from = idx * MAXIMUM_CHUNK_SIZE;
int to = from + MAXIMUM_CHUNK_SIZE;
if (to >= messageLength) {
to = messageLength;
}
byte[] datagram = concatByteArray(header, Arrays.copyOfRange(messageBytes, from, to));
datagrams.add(datagram);
}
}
private byte[] gzipMessage(String message) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
OutputStream stream = new GZIPOutputStream(bos);
stream.write(message.getBytes());
stream.close();
byte[] zipped = bos.toByteArray();
bos.close();
return zipped;
} catch (IOException e) {
return null;
}
}
private byte[] lastFourAsciiBytes(String host) {
final String shortHost = host.length() >= 4 ? host.substring(host.length() - 4) : host;
try {
return shortHost.getBytes("ASCII");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("JVM without ascii support?", e);
}
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
this.hostBytes = lastFourAsciiBytes(host);
}
public String getShortMessage() {
return shortMessage;
}
public void setShortMessage(String shortMessage) {
this.shortMessage = shortMessage;
}
public String getFullMessage() {
return fullMessage;
}
public void setFullMessage(String fullMessage) {
this.fullMessage = fullMessage;
}
public Long getTimestamp() {
return timestamp;
}
public Long getJavaTimestamp() {
return javaTimestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getFacility() {
return facility;
}
public void setFacility(String facility) {
this.facility = facility;
}
public String getLine() {
return line;
}
public void setLine(String line) {
this.line = line;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public GelfMessage addField(String key, String value) {
getAdditonalFields().put(key, value);
return this;
}
public GelfMessage addField(String key, Object value) {
getAdditonalFields().put(key, value);
return this;
}
public Map<String, Object> getAdditonalFields() {
return additonalFields;
}
public void setAdditonalFields(Map<String, Object> additonalFields) {
this.additonalFields = additonalFields;
}
public boolean isValid() {
return !isEmpty(version) && !isEmpty(host) && !isEmpty(shortMessage) && !isEmpty(facility);
}
public boolean isEmpty(String str) {
return str == null || "".equals(str.trim());
}
private byte[] concatByteArray(byte[] first, byte[] second) {
byte[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
}
|
package org.lantern;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.io.Console;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;
import javax.crypto.Cipher;
import javax.net.ssl.SSLSocket;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOExceptionWithCause;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpMessage;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Packet;
import org.lantern.state.StaticSettings;
import org.lastbamboo.common.offer.answer.NoAnswerException;
import org.lastbamboo.common.p2p.P2PClient;
import org.lastbamboo.common.stun.client.PublicIpAddress;
import org.littleshoot.commom.xmpp.XmppUtils;
import org.littleshoot.util.ByteBufferUtils;
import org.littleshoot.util.FiveTuple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.io.Files;
/**
* Utility methods for use with Lantern.
*/
public class LanternUtils {
private static final Logger LOG =
LoggerFactory.getLogger(LanternUtils.class);
private static final SecureRandom secureRandom = new SecureRandom();
private static String MAC_ADDRESS;
private static boolean amFallbackProxy = false;
private static String keystorePath = "<UNSET>";
private static String fallbackServerHost;
private static int fallbackServerPort;
public static boolean isDevMode() {
return LanternClientConstants.isDevMode();
}
/*
public static Socket openRawOutgoingPeerSocket(
final URI uri, final P2PClient p2pClient,
final Map<URI, AtomicInteger> peerFailureCount) throws IOException {
return openOutgoingPeerSocket(uri, p2pClient, peerFailureCount, true);
}
*/
static {
addFallbackProxy();
}
private static void addFallbackProxy() {
final File file =
new File(LanternClientConstants.CONFIG_DIR, "fallback.json");
if (!file.isFile()) {
try {
copyFallback();
} catch (final IOException e) {
LOG.error("Could not copy fallback?", e);
}
}
if (!file.isFile()) {
LOG.error("No fallback proxy to load!");
return;
}
final ObjectMapper om = new ObjectMapper();
InputStream is = null;
try {
is = new FileInputStream(file);
final String proxy = IOUtils.toString(is);
final FallbackProxy fp = om.readValue(proxy, FallbackProxy.class);
fallbackServerHost = fp.getIp();
fallbackServerPort = fp.getPort();
LOG.debug("Set fallback proxy to {}", fallbackServerHost);
} catch (final IOException e) {
LOG.error("Could not load fallback", e);
} finally {
IOUtils.closeQuietly(is);
}
}
private static void copyFallback() throws IOException {
LOG.debug("Copying fallback file");
final File from;
final File home =
new File(new File(SystemUtils.USER_HOME), "fallback.json");
if (home.isFile()) {
from = home;
} else {
LOG.debug("No fallback proxy found in home - checking cur...");
final File curDir = new File("fallback.json");
if (curDir.isFile()) {
from = curDir;
} else {
LOG.warn("Still could not find fallback proxy!");
return;
}
}
final File par = LanternClientConstants.CONFIG_DIR;
final File to = new File(par, from.getName());
if (!par.isDirectory() && !par.mkdirs()) {
throw new IOException("Could not make config dir?");
}
Files.copy(from, to);
}
public static FiveTuple openOutgoingPeer(
final URI uri, final P2PClient<FiveTuple> p2pClient,
final Map<URI, AtomicInteger> peerFailureCount) throws IOException {
if (p2pClient == null) {
LOG.info("P2P client is null. Testing?");
throw new IOException("P2P client not connected");
}
// Start the connection attempt.
try {
LOG.debug("Creating a new socket to {}", uri);
return p2pClient.newSocket(uri);
} catch (final NoAnswerException nae) {
// This is tricky, as it can mean two things. First, it can mean
// the XMPP message was somehow lost. Second, it can also mean
// the other side is actually not there and didn't respond as a
// result.
LOG.info("Did not get answer!! Closing channel from browser", nae);
final AtomicInteger count = peerFailureCount.get(uri);
if (count == null) {
LOG.debug("Incrementing failure count");
peerFailureCount.put(uri, new AtomicInteger(0));
}
else if (count.incrementAndGet() > 5) {
LOG.info("Got a bunch of failures in a row to this peer. " +
"Removing it.");
// We still reset it back to zero. Note this all should
// ideally never happen, and we should be able to use the
// XMPP presence alerts to determine if peers are still valid
// or not.
peerFailureCount.put(uri, new AtomicInteger(0));
//proxyStatusListener.onCouldNotConnectToPeer(uri);
}
throw new IOExceptionWithCause(nae);
} catch (final IOException ioe) {
//proxyStatusListener.onCouldNotConnectToPeer(uri);
LOG.debug("Could not connect to peer", ioe);
throw ioe;
}
}
public static Socket openOutgoingPeerSocket(final URI uri,
final P2PClient<Socket> p2pClient,
final Map<URI, AtomicInteger> peerFailureCount) throws IOException {
return openOutgoingPeerSocket(uri, p2pClient, peerFailureCount, false);
}
private static Socket openOutgoingPeerSocket(
final URI uri, final P2PClient<Socket> p2pClient,
final Map<URI, AtomicInteger> peerFailureCount,
final boolean raw) throws IOException {
if (p2pClient == null) {
LOG.info("P2P client is null. Testing?");
throw new IOException("P2P client not connected");
}
// Start the connection attempt.
try {
LOG.info("Creating a new socket to {}", uri);
final Socket sock;
if (raw) {
sock = p2pClient.newRawSocket(uri);
} else {
sock = p2pClient.newSocket(uri);
}
// Note that it's OK that this prints SSL_NULL_WITH_NULL_NULL --
// the handshake doesn't actually happen until the first IO, so
// the SSL ciphers and such should be all null at this point.
LOG.debug("Got outgoing peer socket {}", sock);
if (sock instanceof SSLSocket) {
LOG.debug("Socket has ciphers {}",
((SSLSocket)sock).getEnabledCipherSuites());
} else {
LOG.warn("Not an SSL socket...");
}
//startReading(sock, browserToProxyChannel, recordStats);
return sock;
} catch (final NoAnswerException nae) {
// This is tricky, as it can mean two things. First, it can mean
// the XMPP message was somehow lost. Second, it can also mean
// the other side is actually not there and didn't respond as a
// result.
LOG.info("Did not get answer!! Closing channel from browser", nae);
final AtomicInteger count = peerFailureCount.get(uri);
if (count == null) {
LOG.info("Incrementing failure count");
peerFailureCount.put(uri, new AtomicInteger(0));
}
else if (count.incrementAndGet() > 5) {
LOG.info("Got a bunch of failures in a row to this peer. " +
"Removing it.");
// We still reset it back to zero. Note this all should
// ideally never happen, and we should be able to use the
// XMPP presence alerts to determine if peers are still valid
// or not.
peerFailureCount.put(uri, new AtomicInteger(0));
//proxyStatusListener.onCouldNotConnectToPeer(uri);
}
throw new IOExceptionWithCause(nae);
} catch (final IOException ioe) {
//proxyStatusListener.onCouldNotConnectToPeer(uri);
LOG.info("Could not connect to peer", ioe);
throw ioe;
}
}
public static byte[] utf8Bytes(final String str) {
try {
return str.getBytes("UTF-8");
} catch (final UnsupportedEncodingException e) {
LOG.error("No UTF-8?", e);
throw new RuntimeException("No UTF-8?", e);
}
}
/**
* This is the local proxy port data is relayed to on the "server" side
* of P2P connections.
*
* NOT IN CONSTANTS BECAUSE LanternUtils INITIALIZES THE LOGGER, WHICH
* CAN'T HAPPEN IN CONSTANTS DUE TO THE CONFIGURATION SEQUENCE IN
* PRODUCTION.
*/
public static final int PLAINTEXT_LOCALHOST_PROXY_PORT =
LanternUtils.randomPort();
public static boolean isTransferEncodingChunked(final HttpMessage m) {
final List<String> chunked =
m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING);
if (chunked.isEmpty()) {
return false;
}
for (String v: chunked) {
if (v.equalsIgnoreCase(HttpHeaders.Values.CHUNKED)) {
return true;
}
}
return false;
}
/**
* We subclass here purely to expose the encoding method of the built-in
* request encoder.
*/
private static final class RequestEncoder extends HttpRequestEncoder {
private ChannelBuffer encode(final HttpRequest request,
final Channel ch) throws Exception {
return (ChannelBuffer) super.encode(null, ch, request);
}
}
public static byte[] toByteBuffer(final HttpRequest request,
final ChannelHandlerContext ctx) throws Exception {
// We need to convert the Netty message to raw bytes for sending over
// the socket.
final RequestEncoder encoder = new RequestEncoder();
final ChannelBuffer cb = encoder.encode(request, ctx.getChannel());
return toRawBytes(cb);
}
public static byte[] toRawBytes(final ChannelBuffer cb) {
final ByteBuffer buf = cb.toByteBuffer();
return ByteBufferUtils.toRawBytes(buf);
}
public static Collection<String> toHttpsCandidates(final String uriStr) {
final Collection<String> segments = new LinkedHashSet<String>();
try {
final org.apache.commons.httpclient.URI uri =
new org.apache.commons.httpclient.URI(uriStr, false);
final String host = uri.getHost();
//LOG.info("Using host: {}", host);
segments.add(host);
final String[] segmented = host.split("\\.");
//LOG.info("Testing segments: {}", Arrays.asList(segmented));
for (int i = 0; i < segmented.length; i++) {
final String tmp = segmented[i];
segmented[i] = "*";
final String segment = StringUtils.join(segmented, '.');
//LOG.info("Adding segment: {}", segment);
segments.add(segment);
segmented[i] = tmp;
}
for (int i = 1; i < segmented.length - 1; i++) {
final String segment =
"*." + StringUtils.join(segmented, '.', i, segmented.length);//segmented.slice(i,segmented.length).join(".");
//LOG.info("Checking segment: {}", segment);
segments.add(segment);
}
} catch (final URIException e) {
LOG.error("Could not create URI?", e);
}
return segments;
}
public static void waitForInternet() {
while (true) {
if (hasNetworkConnection()) {
return;
}
try {
Thread.sleep(50);
} catch (final InterruptedException e) {
LOG.error("Interrupted?", e);
}
}
}
public static boolean hasNetworkConnection() {
LOG.debug("Checking for network connection by looking up public IP");
final InetAddress ip =
new PublicIpAddress().getPublicIpAddress();
LOG.debug("Returning result: "+ip);
return ip != null;
}
public static int randomPort() {
if (LanternConstants.ON_APP_ENGINE) {
// Can't create server sockets on app engine.
return -1;
}
for (int i = 0; i < 20; i++) {
int randomInt = secureRandom.nextInt();
if (randomInt == Integer.MIN_VALUE) {
// Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE -- caught
// by FindBugs.
randomInt = 0;
}
final int randomPort = 1024 + (Math.abs(randomInt) % 60000);
ServerSocket sock = null;
try {
sock = new ServerSocket();
sock.bind(new InetSocketAddress("127.0.0.1", randomPort));
final int port = sock.getLocalPort();
return port;
} catch (final IOException e) {
LOG.info("Could not bind to port: {}", randomPort);
} finally {
if (sock != null) {
try {
sock.close();
} catch (IOException e) {
}
}
}
}
// If we can't grab one of our securely chosen random ports, use
// whatever port the OS assigns.
ServerSocket sock = null;
try {
sock = new ServerSocket();
sock.bind(null);
final int port = sock.getLocalPort();
return port;
} catch (final IOException e) {
LOG.info("Still could not bind?");
int randomInt = secureRandom.nextInt();
if (randomInt == Integer.MIN_VALUE) {
// see above
randomInt = 0;
}
return 1024 + (Math.abs(randomInt) % 60000);
} finally {
if (sock != null) {
try {
sock.close();
} catch (IOException e) {
}
}
}
}
/**
* Execute keytool, returning the output.
*
* @throws IOException If the executable cannot be found.
*/
public static String runKeytool(final String... args) {
try {
final CommandLine command = new CommandLine(findKeytoolPath(), args);
command.execute();
final String output = command.getStdOut();
if (!command.isSuccessful()) {
LOG.info("Command failed!! -- {}", Arrays.asList(args));
}
return output;
} catch (IOException e) {
LOG.warn("Could not run key tool?", e);
}
return "";
}
private static String findKeytoolPath() {
if (SystemUtils.IS_OS_MAC_OSX) {
// try to explicitly select the 1.6 keytool --
// The user may have 1.5 selected as the default
// javavm (default in os x 10.5.8)
// in this case, the default location below will
// point to the 1.5 keytool instead.
final File keytool16 = new File(
"/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Commands/keytool");
if (keytool16.exists()) {
return keytool16.getAbsolutePath();
}
}
final File jh = new File(System.getProperty("java.home"), "bin");
if (jh.isDirectory()) {
final String name;
if (SystemUtils.IS_OS_WINDOWS) {
name = "keytool.exe";
} else {
name = "keytool";
}
try {
return new File(jh, name).getCanonicalPath();
} catch (final IOException e) {
LOG.warn("Error getting canonical path: " + jh);
}
} else {
LOG.warn("java.home/bin not a directory? "+jh);
}
final File defaultLocation = new File("/usr/bin/keytool");
if (defaultLocation.exists()) {
return defaultLocation.getAbsolutePath();
}
final String networkSetupBin = CommandLine.findExecutable("keytool");
if (networkSetupBin != null) {
return networkSetupBin;
}
LOG.error("Could not find keytool?!?!?!?");
return null;
}
public static boolean isLanternHub(final String jabberid) {
final String userid = LanternXmppUtils.jidToUserId(jabberid);
return LanternClientConstants.LANTERN_JID.equals(userid);
}
public static Packet activateOtr(final XMPPConnection conn) {
return XmppUtils.goOffTheRecord(LanternClientConstants.LANTERN_JID,
conn);
}
public static Packet deactivateOtr(final XMPPConnection conn) {
return XmppUtils.goOnTheRecord(LanternClientConstants.LANTERN_JID,
conn);
}
public static void browseUrl(final String uri) {
if( !Desktop.isDesktopSupported() ) {
LOG.error("Desktop not supported?");
LinuxBrowserLaunch.openURL(uri);
return;
}
final Desktop desktop = Desktop.getDesktop();
if( !desktop.isSupported(Desktop.Action.BROWSE )) {
LOG.error("Browse not supported?");
}
try {
desktop.browse(new URI(uri));
} catch (final IOException e) {
LOG.warn("Error opening browser", e);
} catch (final URISyntaxException e) {
LOG.warn("Could not load URI", e);
}
}
public static char[] readPasswordCLI() throws IOException {
Console console = System.console();
if (console == null) {
LOG.debug("No console -- using System.in...");
final Scanner sc = new Scanner(System.in, "UTF-8");
final char[] line = sc.nextLine().toCharArray();
sc.close();
return line;
}
try {
return console.readPassword();
} catch (final IOError e) {
throw new IOException("Could not read pass from console", e);
}
}
public static String readLineCLI() throws IOException {
Console console = System.console();
if (console == null) {
return readLineCliNoConsole();
}
try {
return console.readLine();
} catch (final IOError e) {
throw new IOException("Could not read line from console", e);
}
}
public static String readLineCliNoConsole() {
LOG.debug("No console -- using System.in...");
final Scanner sc = new Scanner(System.in, "UTF-8");
//sc.useDelimiter("\n");
//return sc.next();
final String line = sc.nextLine();
sc.close();
return line;
}
/**
* Returns <code>true</code> if the specified string is either "true" or
* "on" ignoring case.
*
* @param val The string in question.
* @return <code>true</code> if the specified string is either "true" or
* "on" ignoring case, otherwise <code>false</code>.
*/
public static boolean isTrue(final String val) {
return checkTrueOrFalse(val, "true", "on");
}
/**
* Returns <code>true</code> if the specified string is either "false" or
* "off" ignoring case.
*
* @param val The string in question.
* @return <code>true</code> if the specified string is either "false" or
* "off" ignoring case, otherwise <code>false</code>.
*/
public static boolean isFalse(final String val) {
return checkTrueOrFalse(val, "false", "off");
}
private static boolean checkTrueOrFalse(final String val,
final String str1, final String str2) {
final String str = val.trim();
return StringUtils.isNotBlank(str) &&
(str.equalsIgnoreCase(str1) || str.equalsIgnoreCase(str2));
}
/**
* Replaces the first instance of the specified regex in the given file
* with the replacement string and writes out the new complete file.
*
* @param file The file to modify.
* @param regex The regular expression to search for.
* @param replacement The replacement string.
*/
public static void replaceInFile(final File file,
final String regex, final String replacement) {
LOG.debug("Replacing "+regex+" with "+replacement+" in "+file);
try {
final String cur = FileUtils.readFileToString(file, "UTF-8");
final String noStart = cur.replaceFirst(regex, replacement);
FileUtils.writeStringToFile(file, noStart, "UTF-8");
} catch (final IOException e) {
LOG.warn("Could not replace string in file", e);
}
}
public static void loadJarLibrary(final Class<?> jarRepresentative,
final String fileName) throws IOException {
File tempDir = null;
InputStream is = null;
try {
tempDir = Files.createTempDir();
final File tempLib = new File(tempDir, fileName);
is = jarRepresentative.getResourceAsStream("/" + fileName);
if (is == null) {
final String msg = "No file in jar named: "+fileName;
LOG.warn(msg);
throw new IOException(msg);
}
FileUtils.copyInputStreamToFile(is, tempLib);
System.load(tempLib.getAbsolutePath());
} finally {
FileUtils.deleteQuietly(tempDir);
IOUtils.closeQuietly(is);
}
}
public static String fileInJarToString(final String fileName)
throws IOException {
InputStream is = null;
try {
is = LanternUtils.class.getResourceAsStream("/" + fileName);
return IOUtils.toString(is);
} finally {
IOUtils.closeQuietly(is);
}
}
/**
* Creates a typed object from the specified string. If the string is a
* boolean, this returns a boolean, if an int, an int, etc.
*
* @param val The string.
* @return A typed object.
*/
public static Object toTyped(final String val) {
if (LanternUtils.isTrue(val)) {
return true;
} else if (LanternUtils.isFalse(val)) {
return false;
} else if (NumberUtils.isNumber(val)) {
return Integer.parseInt(val);
}
return val;
}
/**
* Prints request headers.
*
* @param request The request.
*/
public static void printRequestHeaders(final HttpServletRequest request) {
LOG.info(getRequestHeaders(request).toString());
}
/**
* Gets request headers as a string.
*
* @param request The request.
* @return The request headers as a string.
*/
public static String getRequestHeaders(final HttpServletRequest request) {
final Enumeration<String> headers = request.getHeaderNames();
final StringBuilder sb = new StringBuilder();
sb.append("\n");
sb.append(request.getRequestURL().toString());
sb.append("\n");
while (headers.hasMoreElements()) {
final String headerName = headers.nextElement();
sb.append(headerName);
sb.append(": ");
sb.append(request.getHeader(headerName));
sb.append("\n");
}
return sb.toString();
}
public static void zeroFill(char[] array) {
if (array != null) {
Arrays.fill(array, '\0');
}
}
public static void zeroFill(byte[] array) {
if (array != null) {
Arrays.fill(array, (byte) 0);
}
}
public static boolean isUnlimitedKeyStrength() {
try {
return Cipher.getMaxAllowedKeyLength("AES") == Integer.MAX_VALUE;
} catch (final NoSuchAlgorithmException e) {
LOG.error("No AES?", e);
return false;
}
}
public static String toEmail(final XMPPConnection conn) {
final String jid = conn.getUser().trim();
return XmppUtils.jidToUser(jid);
}
public static boolean isNotJid(final String email) {
final boolean isEmail = !email.contains(".talk.google.com");
/*
if (isEmail) {
LOG.debug("Allowing email {}", email);
} else {
LOG.debug("Is a JID {}", email);
}
*/
return isEmail;
}
public static Point getScreenCenter(final int width, final int height) {
final Toolkit toolkit = Toolkit.getDefaultToolkit();
final Dimension screenSize = toolkit.getScreenSize();
final int x = (screenSize.width - width) / 2;
final int y = (screenSize.height - height) / 2;
return new Point(x, y);
}
public static boolean waitForServer(final int port) {
return waitForServer(port, 60 * 1000);
}
public static boolean waitForServer(final int port, final int millis) {
final long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < millis) {
final Socket sock = new Socket();
try {
final SocketAddress isa =
new InetSocketAddress("127.0.0.1", port);
sock.connect(isa, 2000);
sock.close();
return true;
} catch (final IOException e) {
}
try {
Thread.sleep(100);
} catch (final InterruptedException e) {
LOG.info("Interrupted?");
}
}
LOG.error("Never able to connect with local server! " +
"Maybe couldn't bind?");
return false;
}
/*
public static boolean isLanternMessage(final Presence pres) {
final Object prop = pres.getProperty(XmppMessageConstants.PROFILE);
return prop != null;
}
*/
/**
* Determines whether or not oauth data should be persisted to disk. It is
* only persisted if we can do so safely and securely but also cleanly.
*
* Fixme: this should actually be a user preference refs #586
*
* @return <code>true</code> if credentials should be persisted to disk,
* otherwise <code>false</code>.
*/
public static boolean persistCredentials() {
return true;
}
/**
* Accesses the object to set a property on with a trivial json-pointer
* syntax as in /object1/object2.
*
* Public for testing. Note this is actually not use in favor of
* ModelMutables that consolidates all accessible methods.
*/
public static Object getTargetForPath(final Object root, final String path)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
if (!path.contains("/")) {
return root;
}
final String curProp = StringUtils.substringBefore(path, "/");
final Object propObject;
if (curProp.isEmpty()) {
propObject = root;
} else {
propObject = PropertyUtils.getProperty(root, curProp);
}
final String nextProp = StringUtils.substringAfter(path, "/");
if (nextProp.contains("/")) {
return getTargetForPath(propObject, nextProp);
}
return propObject;
}
public static void setFromPath(final Object root, final String path, final Object value)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
if (!path.contains("/")) {
PropertyUtils.setProperty(root, path, value);
return;
}
final String curProp = StringUtils.substringBefore(path, "/");
final Object propObject;
if (curProp.isEmpty()) {
propObject = root;
} else {
propObject = PropertyUtils.getProperty(root, curProp);
}
final String nextProp = StringUtils.substringAfter(path, "/");
if (nextProp.contains("/")) {
setFromPath(propObject, nextProp, value);
return;
}
PropertyUtils.setProperty(propObject, nextProp, value);
}
public static boolean isLocalHost(final Channel channel) {
final InetSocketAddress remote =
(InetSocketAddress) channel.getRemoteAddress();
return remote.getAddress().isLoopbackAddress();
}
public static boolean isLocalHost(final Socket sock) {
final InetSocketAddress remote =
(InetSocketAddress) sock.getRemoteSocketAddress();
return remote.getAddress().isLoopbackAddress();
}
/**
* Returns whether or not the string is either true of false. If it's some
* other random string, this returns false.
*
* @param str The string to test.
* @return <code>true</code> if the string is either true or false
* (or on or off), otherwise false.
*/
public static boolean isTrueOrFalse(final String str) {
if (LanternUtils.isTrue(str)) {
return true;
} else if (LanternUtils.isFalse(str)) {
return true;
}
return false;
}
/**
* The completion of the native calls is dependent on OS process
* scheduling, so we need to wait until files actually exist.
*
* @param file The file to wait for.
*/
public static void waitForFile(final File file) {
int i = 0;
while (!file.isFile() && i < 100) {
try {
Thread.sleep(80);
i++;
} catch (final InterruptedException e) {
LOG.error("Interrupted?", e);
}
}
if (!file.isFile()) {
LOG.error("Still could not create file at: {}", file);
} else {
LOG.info("Successfully created file at: {}", file);
}
}
public static void fullDelete(final File file) {
file.deleteOnExit();
if (file.isFile() && !file.delete()) {
LOG.error("Could not delete file {}!!", file);
}
}
public static void addCert(final String alias, final File cert,
final File trustStore, final String storePass) {
if (!cert.isFile()) {
LOG.error("No cert at "+cert);
return;
}
LOG.debug("Importing cert");
// Quick not on '-import' versus '-importcert' from the oracle docs:
// "This command was named -import in previous releases. This old name
// is still supported in this release and will be supported in future
// releases, but for clarify the new name, -importcert, is preferred
// going forward."
// We use import for backwards compatibility.
final String result = LanternUtils.runKeytool("-import",
"-noprompt", "-file", cert.getAbsolutePath(),
"-alias", alias, "-keystore",
trustStore.getAbsolutePath(), "-storepass", storePass);
LOG.debug("Result of running keytool: {}", result);
}
public static boolean isConnect(final HttpRequest request) {
return request.getMethod() == HttpMethod.CONNECT;
}
public static InetSocketAddress isa(final String host, final int port) {
final InetAddress ia;
try {
ia = InetAddress.getByName(host);
} catch (final UnknownHostException e) {
LOG.error("Could not lookup host address at "+host, e);
throw new Error("Bad host", e);
}
return new InetSocketAddress(ia, port);
}
public static URI newURI(final String userId) {
try {
return new URI(userId);
} catch (URISyntaxException e) {
LOG.error("Could not create URI from "+userId);
throw new Error("Bad URI: "+userId);
}
}
/**
* We call this dynamically instead of using a constant because the API
* PORT is set at startup, and we don't want to create a race condition
* for retrieving it.
*
* @return The base URL for photos.
*/
public static String photoUrlBase() {
return StaticSettings.getLocalEndpoint()+"/photo/";
}
public static String defaultPhotoUrl() {
return LanternUtils.photoUrlBase() + "?email=default";
}
public static boolean fileContains(final File file, final String str) {
InputStream fis = null;
try {
fis = new FileInputStream(file);
final String text = IOUtils.toString(fis);
return text.contains(str);
} catch (final IOException e) {
LOG.warn("Could not read file?", e);
} finally {
IOUtils.closeQuietly(fis);
}
return false;
}
/**
* Modifies .desktop files on Ubuntu with out hack to set our icon.
*
* @param path The path to the file.
*/
public static void addStartupWMClass(final String path) {
final File desktopFile = new File(path);
if (!desktopFile.isFile()) {
LOG.warn("No lantern desktop file at: {}", desktopFile);
return;
}
final Collection<?> lines =
Arrays.asList("StartupWMClass=127.0.0.1__"+
// We use the substring here to get rid of the leading "/"
StaticSettings.getPrefix().substring(1)+"_index.html");
try {
FileUtils.writeLines(desktopFile, "UTF-8", lines, true);
} catch (final IOException e) {
LOG.warn("Error writing to: "+desktopFile, e);
}
}
public static String photoUrl(final String email) {
try {
return LanternUtils.photoUrlBase() + "?email=" +
URLEncoder.encode(email, "UTF-8");
} catch (final UnsupportedEncodingException e) {
LOG.error("Unsupported encoding?", e);
throw new RuntimeException(e);
}
}
public static String runCommand(final String cmd, final String... args)
throws IOException {
LOG.debug("Command: {}\nargs: {}", cmd, Arrays.asList(args));
final CommandLine command;
if (SystemUtils.IS_OS_WINDOWS) {
String[] cmdline = new String[args.length + 3];
cmdline[0] = "cmd.exe";
cmdline[1] = "/C";
cmdline[2] = cmd;
for (int i=0; i<args.length; ++i) {
cmdline[3+i] = args[i];
}
command = new CommandLine(cmdline);
} else {
command = new CommandLine(cmd, args);
}
command.execute();
final String output = command.getStdOut();
if (!command.isSuccessful()) {
final String msg = "Command failed!! Args: " + Arrays.asList(args)
+ " Result: " + output;
LOG.error(msg);
throw new IOException(msg);
}
return output;
}
public static void addCSPHeader(HttpServletResponse resp) {
String[] paths = {"ws://127.0.0.1",
"http://127.0.0.1",
"ws://localhost",
"http://localhost"
};
List<String> policies = new ArrayList<String>();
for (String path : paths) {
policies.add(path + ":" + StaticSettings.getApiPort());
}
String localhost = StringUtils.join(policies, " ");
resp.addHeader("Content-Security-Policy", "default-src " + localhost + " 'unsafe-inline' 'unsafe-eval'; img-src data:// " + localhost);
}
/**
* Returns whether or not this Lantern is running as a fallback proxy.
*
* @return <code>true</code> if it's a fallback proxy, otherwise
* <code>false</code>.
*/
public static boolean isFallbackProxy() {
return amFallbackProxy;
}
public static void setFallbackProxy() {
// To check whether this is set in time for it to be picked up.
LOG.info("I am a fallback proxy");
amFallbackProxy = true;
}
public static String getKeystorePath() {
return keystorePath;
}
public static void setKeystorePath(final String path) {
LOG.info("Setting keystorePath to '" + path + "'");
keystorePath = path;
}
public static boolean isTesting() {
final String prop = System.getProperty("testing");
return "true".equalsIgnoreCase(prop);
}
}
|
package org.lantern;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.URI;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.UnresolvedAddressException;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Queue;
import java.util.Random;
import java.util.TreeSet;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.io.IOExceptionWithCause;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpMessage;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Packet;
import org.json.simple.JSONArray;
import org.lastbamboo.common.offer.answer.NoAnswerException;
import org.lastbamboo.common.p2p.P2PClient;
import org.littleshoot.commom.xmpp.XmppUtils;
import org.littleshoot.proxy.ProxyUtils;
import org.littleshoot.util.ByteBufferUtils;
import org.littleshoot.util.Sha1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility methods for use with Lantern.
*/
public class LanternUtils {
private static final Logger LOG =
LoggerFactory.getLogger(LanternUtils.class);
private static String MAC_ADDRESS;
private static final File CONFIG_DIR =
new File(System.getProperty("user.home"), ".lantern");
private static final File DATA_DIR;
private static final File LOG_DIR;
private static final File PROPS_FILE =
new File(CONFIG_DIR, "lantern.properties");
private static final Properties PROPS = new Properties();
static {
if (SystemUtils.IS_OS_WINDOWS) {
//logDirParent = CommonUtils.getDataDir();
DATA_DIR = new File(System.getenv("APPDATA"), "Lantern");
LOG_DIR = new File(DATA_DIR, "logs");
} else if (SystemUtils.IS_OS_MAC_OSX) {
final File homeLibrary =
new File(System.getProperty("user.home"), "Library");
DATA_DIR = new File(homeLibrary, "Logs");
LOG_DIR = new File(DATA_DIR, "Lantern");
} else {
DATA_DIR = new File(SystemUtils.getUserHome(), ".lantern");
LOG_DIR = new File(DATA_DIR, "logs");
}
if (!DATA_DIR.isDirectory()) {
if (!DATA_DIR.mkdirs()) {
System.err.println("Could not create parent at: "
+ DATA_DIR);
}
}
if (!LOG_DIR.isDirectory()) {
if (!LOG_DIR.mkdirs()) {
System.err.println("Could not create dir at: " + LOG_DIR);
}
}
if (!CONFIG_DIR.isDirectory()) {
if (!CONFIG_DIR.mkdirs()) {
LOG.error("Could not make config directory at: "+CONFIG_DIR);
}
}
if (!PROPS_FILE.isFile()) {
try {
if (!PROPS_FILE.createNewFile()) {
LOG.error("Could not create props file!!");
}
} catch (final IOException e) {
LOG.error("Could not create props file!!", e);
}
}
InputStream is = null;
try {
is = new FileInputStream(PROPS_FILE);
PROPS.load(is);
} catch (final IOException e) {
LOG.error("Error loading props file: "+PROPS_FILE, e);
} finally {
IOUtils.closeQuietly(is);
}
}
public static final ClientSocketChannelFactory clientSocketChannelFactory =
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
/**
* Helper method that ensures all written requests are properly recorded.
*
* @param request The request.
*/
public static void writeRequest(final Queue<HttpRequest> httpRequests,
final HttpRequest request, final ChannelFuture cf) {
httpRequests.add(request);
LOG.info("Writing request: {}", request);
LanternUtils.genericWrite(request, cf);
}
public static void genericWrite(final Object message,
final ChannelFuture future) {
final Channel ch = future.getChannel();
if (ch.isConnected()) {
ch.write(message);
} else {
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(final ChannelFuture cf)
throws Exception {
if (cf.isSuccess()) {
ch.write(message);
}
}
});
}
}
public static Socket openRawOutgoingPeerSocket(
final Channel browserToProxyChannel,
final URI uri, final ProxyStatusListener proxyStatusListener,
final P2PClient p2pClient,
final Map<URI, AtomicInteger> peerFailureCount,
final boolean recordStats) throws IOException {
return openOutgoingPeerSocket(browserToProxyChannel, uri,
proxyStatusListener, p2pClient, peerFailureCount, true,
recordStats);
}
public static Socket openOutgoingPeerSocket(
final Channel browserToProxyChannel,
final URI uri, final ProxyStatusListener proxyStatusListener,
final P2PClient p2pClient,
final Map<URI, AtomicInteger> peerFailureCount,
final boolean recordStats) throws IOException {
return openOutgoingPeerSocket(browserToProxyChannel, uri,
proxyStatusListener, p2pClient, peerFailureCount, false,
recordStats);
}
private static Socket openOutgoingPeerSocket(
final Channel browserToProxyChannel,
final URI uri, final ProxyStatusListener proxyStatusListener,
final P2PClient p2pClient,
final Map<URI, AtomicInteger> peerFailureCount,
final boolean raw, final boolean recordStats) throws IOException {
// Start the connection attempt.
try {
LOG.info("Creating a new socket to {}", uri);
final Socket sock;
if (raw) {
sock = p2pClient.newRawSocket(uri);
} else {
sock = p2pClient.newSocket(uri);
}
LOG.info("Got outgoing peer socket: {}", sock);
startReading(sock, browserToProxyChannel, recordStats);
return sock;
} catch (final NoAnswerException nae) {
// This is tricky, as it can mean two things. First, it can mean
// the XMPP message was somehow lost. Second, it can also mean
// the other side is actually not there and didn't respond as a
// result.
LOG.info("Did not get answer!! Closing channel from browser", nae);
final AtomicInteger count = peerFailureCount.get(uri);
if (count == null) {
LOG.info("Incrementing failure count");
peerFailureCount.put(uri, new AtomicInteger(0));
}
else if (count.incrementAndGet() > 5) {
LOG.info("Got a bunch of failures in a row to this peer. " +
"Removing it.");
// We still reset it back to zero. Note this all should
// ideally never happen, and we should be able to use the
// XMPP presence alerts to determine if peers are still valid
// or not.
peerFailureCount.put(uri, new AtomicInteger(0));
proxyStatusListener.onCouldNotConnectToPeer(uri);
}
throw new IOExceptionWithCause(nae);
} catch (final IOException ioe) {
proxyStatusListener.onCouldNotConnectToPeer(uri);
LOG.warn("Could not connect to peer", ioe);
throw ioe;
}
}
private static void startReading(final Socket sock, final Channel channel,
final boolean recordStats) {
final Runnable runner = new Runnable() {
@Override
public void run() {
final byte[] buffer = new byte[4096];
long count = 0;
int n = 0;
try {
final InputStream is = sock.getInputStream();
while (-1 != (n = is.read(buffer))) {
//LOG.info("Writing response data: {}", new String(buffer, 0, n));
// We need to make a copy of the buffer here because
// the writes are asynchronous, so the bytes can
// otherwise get scrambled.
final ChannelBuffer buf =
ChannelBuffers.copiedBuffer(buffer, 0, n);
channel.write(buf);
if (recordStats) {
LanternHub.statsTracker().addBytesProxied(n);
}
count += n;
}
ProxyUtils.closeOnFlush(channel);
} catch (final IOException e) {
LOG.info("Exception relaying peer data back to browser",e);
ProxyUtils.closeOnFlush(channel);
// The other side probably just closed the connection!!
//channel.close();
//proxyStatusListener.onError(peerUri);
}
}
};
final Thread peerReadingThread =
new Thread(runner, "Peer-Data-Reading-Thread");
peerReadingThread.setDaemon(true);
peerReadingThread.start();
}
public static String getMacAddress() {
if (MAC_ADDRESS != null) {
LOG.info("Returning MAC: "+MAC_ADDRESS);
return MAC_ADDRESS;
}
final Enumeration<NetworkInterface> nis;
try {
nis = NetworkInterface.getNetworkInterfaces();
} catch (final SocketException e1) {
throw new Error("Could not read network interfaces?");
}
while (nis.hasMoreElements()) {
final NetworkInterface ni = nis.nextElement();
try {
if (!ni.isUp()) {
LOG.info("Ignoring interface that's not up: {}",
ni.getDisplayName());
continue;
}
final byte[] mac = ni.getHardwareAddress();
if (mac != null && mac.length > 0) {
LOG.info("Returning 'normal' MAC address");
return macMe(mac);
}
} catch (final SocketException e) {
LOG.warn("Could not get MAC address?");
}
}
try {
LOG.warn("Returning custom MAC address");
return macMe(InetAddress.getLocalHost().getHostAddress() +
System.currentTimeMillis());
} catch (final UnknownHostException e) {
final byte[] bytes = new byte[24];
new Random().nextBytes(bytes);
return macMe(bytes);
}
}
private static String macMe(final String mac) {
return macMe(utf8Bytes(mac));
}
public static byte[] utf8Bytes(final String str) {
try {
return str.getBytes("UTF-8");
} catch (final UnsupportedEncodingException e) {
LOG.error("No UTF-8?", e);
throw new RuntimeException("No UTF-8?", e);
}
}
private static String macMe(final byte[] mac) {
final MessageDigest md = new Sha1();
md.update(mac);
final byte[] raw = md.digest();
MAC_ADDRESS = Base64.encodeBase64URLSafeString(raw);
return MAC_ADDRESS;
}
public static File configDir() {
return CONFIG_DIR;
}
public static File dataDir() {
return DATA_DIR;
}
public static File logDir() {
return LOG_DIR;
}
public static File propsFile() {
return PROPS_FILE;
}
public static boolean isTransferEncodingChunked(final HttpMessage m) {
final List<String> chunked =
m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING);
if (chunked.isEmpty()) {
return false;
}
for (String v: chunked) {
if (v.equalsIgnoreCase(HttpHeaders.Values.CHUNKED)) {
return true;
}
}
return false;
}
public static JSONArray toJsonArray(final Collection<String> strs) {
final JSONArray json = new JSONArray();
synchronized (strs) {
json.addAll(strs);
}
return json;
}
public static boolean isConfigured() {
if (!PROPS_FILE.isFile()) {
return false;
}
final Properties props = new Properties();
InputStream is = null;
try {
is = new FileInputStream(PROPS_FILE);
props.load(is);
final String un = props.getProperty("google.user");
final String pwd = props.getProperty("google.pwd");
return (StringUtils.isNotBlank(un) && StringUtils.isNotBlank(pwd));
} catch (final IOException e) {
LOG.error("Error loading props file: "+PROPS_FILE, e);
} finally {
IOUtils.closeQuietly(is);
}
return false;
}
public static Collection<RosterEntry> getRosterEntries(final String email,
final String pwd, final int attempts) throws IOException {
final XMPPConnection conn =
XmppUtils.persistentXmppConnection(email, pwd, "lantern", attempts);
final Roster roster = conn.getRoster();
final Collection<RosterEntry> unordered = roster.getEntries();
final Comparator<RosterEntry> comparator = new Comparator<RosterEntry>() {
@Override
public int compare(final RosterEntry re1, final RosterEntry re2) {
final String name1 = re1.getName();
final String name2 = re2.getName();
if (name1 == null) {
return 1;
} else if (name2 == null) {
return -1;
}
return name1.compareToIgnoreCase(name2);
}
};
final Collection<RosterEntry> entries =
new TreeSet<RosterEntry>(comparator);
for (final RosterEntry entry : unordered) {
entries.add(entry);
}
return entries;
}
public static Collection<String> getProxies() {
final String proxies = getStringProperty("proxies");
if (StringUtils.isBlank(proxies)) {
return Collections.emptySet();
} else {
final String[] all = proxies.split(",");
return Arrays.asList(all);
}
}
public static void addProxy(final String server) {
String proxies = getStringProperty("proxies");
if (proxies == null) {
proxies = server;
} else {
proxies += ",";
proxies += server;
}
setStringProperty("proxies", proxies);
}
public static void writeCredentials(final String email, final String pwd) {
LOG.info("Writing credentials...");
PROPS.setProperty("google.user", email);
PROPS.setProperty("google.pwd", pwd);
persistProps();
}
public static void clearCredentials() {
LOG.info("Clearing credentials...");
PROPS.remove("google.user");
PROPS.remove("google.pwd");
persistProps();
}
public static boolean newInstall() {
return getBooleanProperty("newInstall");
}
public static void installed() {
setBooleanProperty("newInstall", false);
}
public static void setBooleanProperty(final String key,
final boolean value) {
PROPS.setProperty(key, String.valueOf(value));
persistProps();
}
public static boolean getBooleanProperty(final String key) {
final String val = PROPS.getProperty(key);
if (StringUtils.isBlank(val)) {
return false;
}
LOG.info("Checking property: {}", val);
return "true".equalsIgnoreCase(val.trim());
}
public static void setStringProperty(final String key, final String value) {
PROPS.setProperty(key, value);
persistProps();
}
public static String getStringProperty(final String key) {
return PROPS.getProperty(key);
}
public static void clear(final String key) {
PROPS.remove(key);
persistProps();
}
private static void persistProps() {
FileWriter fw = null;
try {
fw = new FileWriter(PROPS_FILE);
PROPS.store(fw, "");
} catch (final IOException e) {
LOG.error("Could not store props?");
} finally {
IOUtils.closeQuietly(fw);
}
}
/**
* We subclass here purely to expose the encoding method of the built-in
* request encoder.
*/
private static final class RequestEncoder extends HttpRequestEncoder {
private ChannelBuffer encode(final HttpRequest request,
final Channel ch) throws Exception {
return (ChannelBuffer) super.encode(null, ch, request);
}
}
public static byte[] toByteBuffer(final HttpRequest request,
final ChannelHandlerContext ctx) throws Exception {
// We need to convert the Netty message to raw bytes for sending over
// the socket.
final RequestEncoder encoder = new RequestEncoder();
final ChannelBuffer cb = encoder.encode(request, ctx.getChannel());
return toRawBytes(cb);
}
public static byte[] toRawBytes(final ChannelBuffer cb) {
final ByteBuffer buf = cb.toByteBuffer();
return ByteBufferUtils.toRawBytes(buf);
}
public static Collection<String> toHttpsCandidates(final String uriStr) {
final Collection<String> segments = new LinkedHashSet<String>();
try {
final org.apache.commons.httpclient.URI uri =
new org.apache.commons.httpclient.URI(uriStr, false);
final String host = uri.getHost();
LOG.info("Using host: {}", host);
segments.add(host);
final String[] segmented = host.split("\\.");
LOG.info("Testing segments: {}", Arrays.asList(segmented));
for (int i = 0; i < segmented.length; i++) {
final String tmp = segmented[i];
segmented[i] = "*";
final String segment = StringUtils.join(segmented, '.');
LOG.info("Adding segment: {}", segment);
segments.add(segment);
segmented[i] = tmp;
}
for (int i = 1; i < segmented.length - 1; i++) {
final String segment =
"*." + StringUtils.join(segmented, '.', i, segmented.length);//segmented.slice(i,segmented.length).join(".");
LOG.info("Checking segment: {}", segment);
segments.add(segment);
}
} catch (final URIException e) {
LOG.error("Could not create URI?", e);
}
return segments;
}
public static void waitForInternet() {
while (true) {
try {
final DatagramChannel channel = DatagramChannel.open();
final SocketAddress server =
new InetSocketAddress("time-a.nist.gov", 37);
channel.connect(server);
return;
} catch (final IOException e) {
LOG.error("Could not create channel!", e);
} catch (final UnresolvedAddressException e) {
LOG.error("Could not resolve address", e);
}
try {
Thread.sleep(250);
} catch (final InterruptedException e) {
LOG.error("Interrupted?", e);
}
}
}
public static int randomPort() {
try {
final ServerSocket sock = new ServerSocket();
sock.bind(null);
final int port = sock.getLocalPort();
sock.close();
return port;
} catch (final IOException e) {
return 1024 + (RandomUtils.nextInt() % 60000);
}
}
/**
* Execute keytool, returning the output.
*/
public static String runKeytool(final String... args) {
final CommandLine command = new CommandLine(findKeytoolPath(), args);
command.execute();
final String output = command.getStdOut();
if (!command.isSuccessful()) {
LOG.warn("Command failed!! -- {}", args);
}
return output;
}
private static String findKeytoolPath() {
final File defaultLocation = new File("/usr/bin/keytool");
if (defaultLocation.exists()) {
return defaultLocation.getAbsolutePath();
}
final String networkSetupBin = CommandLine.findExecutable("keytool");
if (networkSetupBin != null) {
return networkSetupBin;
}
LOG.error("Could not fine keytool?!?!?!?");
return null;
}
private static final boolean RUN_WITH_UI =
LanternUtils.getBooleanProperty("linuxui");
public static boolean runWithUi() {
if (!settingExists("linuxui")) {
return true;
}
return RUN_WITH_UI;
}
private static boolean settingExists(final String key) {
return PROPS.containsKey(key);
}
public static Packet activateOtr(final XMPPConnection conn) {
return XmppUtils.goOffTheRecord(LanternConstants.LANTERN_JID, conn);
}
public static Packet deactivateOtr(final XMPPConnection conn) {
return XmppUtils.goOnTheRecord(LanternConstants.LANTERN_JID, conn);
}
public static boolean shouldProxy() {
return CensoredUtils.isCensored() || CensoredUtils.isForceCensored();
}
}
|
package org.oakgp;
import static org.oakgp.Arguments.createArguments;
import static org.oakgp.util.Utils.assertEvaluateToSameResult;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import org.oakgp.node.ConstantNode;
import org.oakgp.node.FunctionNode;
import org.oakgp.node.Node;
import org.oakgp.serialize.NodeWriter;
/**
* Simplifies tree structures by replacing expressions with their values.
* <p>
* e.g. The expression:
*
* <pre>
* (+ 7 (* 3 6))
* </pre>
*
* can be simplified to the value:
*
* <pre>
* 25
* </pre>
*
* </p>
* <b>Note:</b> relies on {@code Operator} implementations being referentially transparent.
*/
public final class NodeSimplifier {
public Node simplify(Node input) {
int ctr = 0;
Set<String> s = new HashSet<>();
Node previous;
Node output = input;
do {
previous = output;
output = _simplify(output);
if (!output.equals(previous) && !s.add(new NodeWriter().writeNode(output))) { // TODO
return output;
}
if (ctr++ > 10000) { // TODO
throw new IllegalArgumentException(new NodeWriter().writeNode(input));
}
} while (output instanceof FunctionNode && !output.equals(previous));
return output;
}
private Node _simplify(Node input) {
if (input instanceof FunctionNode) {
Node output = simplifyFunctionNode((FunctionNode) input);
assertEvaluateToSameResult(input, output);
return output;
} else {
return input;
}
}
private Node simplifyFunctionNode(final FunctionNode input) {
// try to simplify each of the arguments
Arguments inputArgs = input.getArguments();
Node[] simplifiedArgs = new Node[inputArgs.length()];
boolean modified = false;
boolean constants = true;
for (int i = 0; i < simplifiedArgs.length; i++) {
Node originalArg = inputArgs.get(i);
simplifiedArgs[i] = _simplify(originalArg);
if (originalArg != simplifiedArgs[i]) {
modified = true;
}
if (!(simplifiedArgs[i] instanceof ConstantNode)) {
constants = false;
}
}
// if could simplify arguments then use simplified version to create new FunctionNode
Arguments arguments;
FunctionNode output;
if (modified) {
arguments = createArguments(simplifiedArgs);
output = new FunctionNode(input.getOperator(), arguments);
} else {
arguments = inputArgs;
output = input;
}
// if all arguments are constants then return result of evaluating them
if (constants) {
return new ConstantNode(output.evaluate(null), output.getType());
}
// try to simplify using operator
// return input.getOperator().simplify(arguments).orElse(output);
Optional<Node> o = input.getOperator().simplify(arguments);
if (o.isPresent()) {
assertEvaluateToSameResult(input, o.get());
return o.get();
} else {
return output;
}
}
}
|
package org.takes.rq;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.EqualsAndHashCode;
import org.takes.HttpException;
import org.takes.Request;
import org.takes.misc.Sprintf;
import org.takes.misc.VerboseIterable;
/**
* HTTP multipart FORM data decoding.
*
* <p>All implementations of this interface must be immutable and thread-safe.
*
* @author Yegor Bugayenko (yegor@teamed.io)
* @version $Id$
* @since 0.9
*/
@SuppressWarnings("PMD.TooManyMethods")
public interface RqMultipart extends Request {
/**
* Get single part.
* @param name Name of the part to get
* @return List of parts (can be empty)
*/
Iterable<Request> part(CharSequence name);
/**
* Get all part names.
* @return All names
*/
Iterable<String> names();
@EqualsAndHashCode(callSuper = true)
final class Base extends RqWrap implements RqMultipart {
/**
* Pattern to get boundary from header.
*/
private static final Pattern BOUNDARY = Pattern.compile(
".*[^a-z]boundary=([^;]+).*"
);
/**
* Pattern to get name from header.
*/
private static final Pattern NAME = Pattern.compile(
".*[^a-z]name=\"([^\"]+)\".*"
);
/**
* Map of params and values.
*/
private final transient Map<String, List<Request>> map;
/**
* Internal buffer.
*/
private final transient ByteBuffer buffer;
/**
* Origin request body.
*/
private final transient ReadableByteChannel body;
/**
* Ctor.
* @param req Original request
* @throws IOException If fails
* @checkstyle ExecutableStatementCountCheck (2 lines)
*/
public Base(final Request req) throws IOException {
super(req);
this.body = Base.body(req);
this.buffer = Base.buffer(req);
this.map = this.requests(req);
}
@Override
public Iterable<Request> part(final CharSequence name) {
final List<Request> values = this.map
.get(name.toString().toLowerCase(Locale.ENGLISH));
final Iterable<Request> iter;
if (values == null) {
iter = new VerboseIterable<>(
Collections.<Request>emptyList(),
new Sprintf(
"there are no parts by name \"%s\" among %d others: %s",
name, this.map.size(), this.map.keySet()
)
);
} else {
iter = new VerboseIterable<>(
values,
new Sprintf(
"there are just %d parts by name \"%s\"",
values.size(), name
)
);
}
return iter;
}
@Override
public Iterable<String> names() {
return this.map.keySet();
}
/**
* Returns the ReadableByteChannel based on request body.
* @param req Original request
* @return The ReadableByteChannel based on request body.
* @throws IOException If fails
*/
private static ReadableByteChannel body(final Request req)
throws IOException {
return Channels.newChannel(new RqLengthAware(req).body());
}
/**
* Returns the ByteBuffer for the request body.
* @param req Original request
* @return The ByteBuffer for the request body.
* @throws IOException If fails
*/
private static ByteBuffer buffer(final Request req)
throws IOException {
return ByteBuffer.allocate(
// @checkstyle MagicNumberCheck (1 line)
Math.min(8192, new RqLengthAware(req).body().available())
);
}
/**
* Build a request for each part of the origin request.
* @param req Origin request
* @return The requests map that use the part name as a map key
* @throws IOException If fails
*/
private Map<String, List<Request>> requests(
final Request req) throws IOException {
final String header = new RqHeaders.Smart(
new RqHeaders.Base(req)
// @checkstyle MultipleStringLiteralsCheck (1 line)
).single("Content-Type");
if (!header.toLowerCase(Locale.ENGLISH)
.startsWith("multipart/form-data")) {
throw new HttpException(
HttpURLConnection.HTTP_BAD_REQUEST,
String.format(
// @checkstyle LineLength (1 line)
"RqMultipart.Base can only parse multipart/form-data, while Content-Type specifies a different type: \"%s\"",
header
)
);
}
final Matcher matcher = RqMultipart.Base.BOUNDARY.matcher(header);
if (!matcher.matches()) {
throw new HttpException(
HttpURLConnection.HTTP_BAD_REQUEST,
String.format(
// @checkstyle LineLength (1 line)
"boundary is not specified in Content-Type header: \"%s\"",
header
)
);
}
if (this.body.read(this.buffer) < 0) {
throw new HttpException(
HttpURLConnection.HTTP_BAD_REQUEST,
"failed to read the request body"
);
}
final byte[] boundary = String.format(
"\r\n--%s", matcher.group(1)
).getBytes(StandardCharsets.UTF_8);
this.buffer.flip();
this.buffer.position(boundary.length - 2);
final Collection<Request> requests = new LinkedList<>();
while (this.buffer.hasRemaining()) {
final byte data = this.buffer.get();
if (data == '-') {
break;
}
this.buffer.position(this.buffer.position() + 1);
requests.add(this.make(boundary));
}
return RqMultipart.Base.asMap(requests);
}
/**
* Make a request.
* Scans the origin request until the boundary reached. Caches
* the content into a temporary file and returns it as a new request.
* @param boundary Boundary
* @return Request
* @throws IOException If fails
* @todo #254:30min in order to delete temporary files InputStream
* instance on Request.body should be closed. In context of multipart
* requests that means that body of all parts should be closed once
* they are not needed anymore.
*/
private Request make(final byte[] boundary) throws IOException {
final File file = File.createTempFile(
RqMultipart.class.getName(), ".tmp"
);
final FileChannel channel = new RandomAccessFile(
file, "rw"
).getChannel();
try {
channel.write(
ByteBuffer.wrap(
this.head().iterator().next().getBytes(
StandardCharsets.UTF_8
)
)
);
// @checkstyle MultipleStringLiteralsCheck (1 line)
channel.write(
ByteBuffer.wrap(
RqMultipart.Fake.CRLF.getBytes(StandardCharsets.UTF_8)
)
);
this.copy(channel, boundary);
} finally {
channel.close();
}
return new RqWithHeader(
new RqLive(
new TempInputStream(
new FileInputStream(file),
file
)
),
"Content-Length",
String.valueOf(file.length())
);
}
/**
* Copy until boundary reached.
* @param target Output file channel
* @param boundary Boundary
* @throws IOException If fails
* @checkstyle ExecutableStatementCountCheck (2 lines)
*/
private void copy(final WritableByteChannel target,
final byte[] boundary) throws IOException {
int match = 0;
boolean cont = true;
while (cont) {
if (!this.buffer.hasRemaining()) {
this.buffer.clear();
for (int idx = 0; idx < match; ++idx) {
this.buffer.put(boundary[idx]);
}
match = 0;
if (this.body.read(this.buffer) == -1) {
break;
}
this.buffer.flip();
}
final ByteBuffer btarget = this.buffer.slice();
final int offset = this.buffer.position();
btarget.limit(0);
while (this.buffer.hasRemaining()) {
final byte data = this.buffer.get();
if (data == boundary[match]) {
++match;
if (match == boundary.length) {
cont = false;
break;
}
} else {
match = 0;
btarget.limit(this.buffer.position() - offset);
}
}
target.write(btarget);
}
}
/**
* Convert a list of requests to a map.
* @param reqs Requests
* @return Map of them
* @throws IOException If fails
*/
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
private static Map<String, List<Request>> asMap(
final Collection<Request> reqs) throws IOException {
final Map<String, List<Request>> map = new HashMap<>(reqs.size());
for (final Request req : reqs) {
final String header = new RqHeaders.Smart(
new RqHeaders.Base(req)
// @checkstyle MultipleStringLiteralsCheck (1 line)
).single("Content-Disposition");
final Matcher matcher = RqMultipart.Base.NAME.matcher(header);
if (!matcher.matches()) {
throw new HttpException(
HttpURLConnection.HTTP_BAD_REQUEST,
String.format(
// @checkstyle LineLength (1 line)
"\"name\" not found in Content-Disposition header: %s",
header
)
);
}
final String name = matcher.group(1);
if (!map.containsKey(name)) {
map.put(name, new LinkedList<Request>());
}
map.get(name).add(req);
}
return map;
}
}
/**
* Smart decorator.
* @since 0.15
*/
final class Smart implements RqMultipart {
/**
* Original request.
*/
private final transient RqMultipart origin;
/**
* Ctor.
* @param req Original
*/
public Smart(final RqMultipart req) {
this.origin = req;
}
/**
* Get single part.
* @param name Name of the part to get
* @return Part
* @throws HttpException If fails
*/
public Request single(final CharSequence name) throws HttpException {
final Iterator<Request> parts = this.part(name).iterator();
if (!parts.hasNext()) {
throw new HttpException(
HttpURLConnection.HTTP_BAD_REQUEST,
String.format(
"form param \"%s\" is mandatory", name
)
);
}
return parts.next();
}
@Override
public Iterable<Request> part(final CharSequence name) {
return this.origin.part(name);
}
@Override
public Iterable<String> names() {
return this.origin.names();
}
@Override
public Iterable<String> head() throws IOException {
return this.origin.head();
}
@Override
public InputStream body() throws IOException {
return this.origin.body();
}
}
/**
* Fake decorator.
* @since 0.16
*/
final class Fake implements RqMultipart {
/**
* Fake boundary constant.
*/
private static final String BOUNDARY = "AaB02x";
/**
* Carriage return constant.
*/
private static final String CRLF = "\r\n";
/**
* Fake multipart request.
*/
private final RqMultipart fake;
/**
* Fake ctor.
* @param req Fake request header holder
* @param dispositions Fake request body parts
* @throws IOException If fails
*/
public Fake(final Request req, final Request... dispositions)
throws IOException {
this.fake = new RqMultipart.Base(
new RqMultipart.Fake.FakeMultipartRequest(
req, dispositions
)
);
}
@Override
public Iterable<Request> part(final CharSequence name) {
return this.fake.part(name);
}
@Override
public Iterable<String> names() {
return this.fake.names();
}
@Override
public Iterable<String> head() throws IOException {
return this.fake.head();
}
@Override
public InputStream body() throws IOException {
return this.fake.body();
}
/**
* Fake body stream creator.
* @param parts Fake request body parts
* @return InputStream of given dispositions
* @throws IOException If fails
*/
private static InputStream fakeStream(final Request... parts)
throws IOException {
return new ByteArrayInputStream(
RqMultipart.Fake.fakeBody(parts).toString().getBytes(
StandardCharsets.UTF_8
)
);
}
/**
* Fake body creator.
* @param parts Fake request body parts
* @return StringBuilder of given dispositions
* @throws IOException If fails
*/
@SuppressWarnings("PMD.InsufficientStringBufferDeclaration")
private static StringBuilder fakeBody(final Request... parts)
throws IOException {
final StringBuilder builder = new StringBuilder();
for (final Request part : parts) {
builder.append(String.format("--%s", RqMultipart.Fake.BOUNDARY))
.append(RqMultipart.Fake.CRLF)
// @checkstyle MultipleStringLiteralsCheck (1 line)
.append("Content-Disposition: ")
.append(
new RqHeaders.Smart(
new RqHeaders.Base(part)
// @checkstyle MultipleStringLiteralsCheck (1 line)
).single("Content-Disposition")
).append(RqMultipart.Fake.CRLF);
final String body = new RqPrint(part).printBody();
if (!(RqMultipart.Fake.CRLF.equals(body) || body.isEmpty())) {
builder.append(RqMultipart.Fake.CRLF)
.append(body)
.append(RqMultipart.Fake.CRLF);
}
}
builder.append("Content-Transfer-Encoding: utf-8")
.append(RqMultipart.Fake.CRLF)
.append(String.format("--%s--", RqMultipart.Fake.BOUNDARY));
return builder;
}
/**
* This class is using a decorator pattern for representing
* a fake HTTP multipart request.
*/
private static final class FakeMultipartRequest implements Request {
/**
* Request object. Holds a value for the header.
*/
private final Request req;
/**
* Holding multiple request body parts.
*/
private final Request[] parts;
/**
* The Constructor for the class.
* @param rqst The Request object
* @param list The sequence of dispositions
*/
FakeMultipartRequest(final Request rqst, final Request... list) {
this.req = rqst;
this.parts = list;
}
@Override
public Iterable<String> head() throws IOException {
return new RqWithHeaders(
this.req,
String.format(
"Content-Type: multipart/form-data; boundary=%s",
RqMultipart.Fake.BOUNDARY
),
String.format(
"Content-Length: %s",
RqMultipart.Fake.fakeBody(this.parts).length()
)
).head();
}
@Override
public InputStream body() throws IOException {
return RqMultipart.Fake.fakeStream(this.parts);
}
}
}
}
|
package ru.r2cloud.web;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;
import com.eclipsesource.json.ParseException;
import fi.iki.elonen.NanoHTTPD;
import ru.r2cloud.util.Configuration;
import ru.r2cloud.util.SignedURL;
import ru.r2cloud.web.api.StaticController;
public class WebServer extends NanoHTTPD {
private static final Logger LOG = LoggerFactory.getLogger(WebServer.class);
private static final String ALLOW_HEADERS = "Authorization, Content-Type";
private final GsonRenderer jsonRenderer;
private final Map<String, HttpContoller> controllers;
private final Authenticator auth;
private final StaticController staticController;
public WebServer(Configuration props, Map<String, HttpContoller> controllers, Authenticator auth, SignedURL signed) {
super(props.getProperty("server.hostname"), props.getInteger("server.port"));
jsonRenderer = new GsonRenderer();
this.auth = auth;
this.controllers = controllers;
staticController = new StaticController(props, signed);
}
@Override
public void start() {
try {
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
LOG.info("webserver is listening on {}:{}", getHostname(), getListeningPort());
} catch (IOException e) {
throw new RuntimeException("unable to start", e);
}
}
@Override
public Response serve(IHTTPSession session) {
if (session.getMethod().equals(Method.OPTIONS)) {
Response result = NanoHTTPD.newFixedLengthResponse(Response.Status.OK, "text/plain; charset=utf-8", null);
setupCorsHeaders(result);
return result;
}
if (session.getUri().startsWith(staticController.getRequestMappingURL())) {
return staticController.doGet(session);
}
if (isAuthenticationRequired(session) && !auth.isAuthenticated(session)) {
Response result = NanoHTTPD.newFixedLengthResponse(Response.Status.UNAUTHORIZED, MimeType.JSON.getType(), "{}");
setupCorsHeaders(result);
return result;
}
HttpContoller controller = controllers.get(session.getUri());
ModelAndView model = null;
if (controller == null) {
model = new ModelAndView();
model.setStatus(Response.Status.NOT_FOUND);
} else {
try {
switch (session.getMethod()) {
case GET:
model = controller.doGet(session);
break;
case POST:
model = processPost(session, controller);
break;
default:
break;
}
} catch (Exception e) {
LOG.error("unable to handle request", e);
model = new InternalServerError();
}
}
if (model == null) {
model = new ModelAndView();
model.setStatus(Response.Status.INTERNAL_ERROR);
}
Response result = jsonRenderer.render(model);
if (model.getStatus() != null) {
result.setStatus(model.getStatus());
}
if (model.getHeaders() != null) {
for (Entry<String, String> cur : model.getHeaders().entrySet()) {
result.addHeader(cur.getKey(), cur.getValue());
}
}
setupCorsHeaders(result);
return result;
}
private static ModelAndView processPost(IHTTPSession session, HttpContoller controller) {
ModelAndView model;
JsonValue request;
try {
request = Json.parse(WebServer.getRequestBody(session));
if (!request.isObject()) {
model = new BadRequest("expected object");
} else {
model = controller.doPost(request.asObject());
}
} catch (ParseException e) {
model = new BadRequest("expected json object");
}
return model;
}
private static void setupCorsHeaders(Response result) {
result.addHeader("Access-Control-Allow-Origin", "*");
result.addHeader("Access-Control-Max-Age", "1728000");
result.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
result.addHeader("Access-Control-Allow-Headers", ALLOW_HEADERS);
result.addHeader("Access-Control-Expose-Headers", ALLOW_HEADERS);
}
public boolean isAuthenticationRequired(IHTTPSession session) {
return session.getUri().startsWith("/api/v1/admin/");
}
public static String getParameter(IHTTPSession session, String name) {
Map<String, List<String>> parameters = getParameters(session);
List<String> values = parameters.get(name);
if (values == null || values.isEmpty()) {
return null;
}
return values.get(0);
}
public static Map<String, List<String>> getParameters(IHTTPSession session) {
Map<String, List<String>> parameters = session.getParameters();
if (parameters.isEmpty()) {
try {
session.parseBody(new HashMap<>());
parameters = session.getParameters();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ResponseException e) {
throw new RuntimeException(e);
}
}
return parameters;
}
public static String getRequestBody(IHTTPSession session) {
final HashMap<String, String> map = new HashMap<>();
try {
session.parseBody(map);
} catch (Exception e) {
throw new RuntimeException(e);
}
return map.get("postData");
}
public static String getString(JsonValue value, String name) {
JsonValue field = ((JsonObject) value).get(name);
if (field == null || field.isNull()) {
return null;
}
if (!field.isString()) {
return null;
}
return field.asString();
}
public static Double getDouble(JsonValue value, String name) {
JsonValue result = ((JsonObject) value).get(name);
if (result == null || result.isNull()) {
return null;
}
return result.asDouble();
}
public static Integer getInteger(IHTTPSession session, String name) {
String param = getParameter(session, name);
if (param == null || param.trim().length() == 0) {
return null;
}
return Integer.valueOf(param);
}
public static boolean getBoolean(IHTTPSession session, String name) {
String param = getParameter(session, name);
if (param == null || param.trim().length() == 0) {
return false;
}
return Boolean.valueOf(param);
}
public static Integer getInteger(JsonValue value, String name) {
JsonValue result = ((JsonObject) value).get(name);
if (result == null || result.isNull()) {
return null;
}
if (result.isString()) {
return Integer.parseInt(result.asString());
}
if (!result.isNumber()) {
throw new NumberFormatException();
}
return result.asInt();
}
public static boolean getBoolean(JsonValue value, String name) {
JsonValue result = ((JsonObject) value).get(name);
if (result == null || result.isNull()) {
return false;
}
return result.asBoolean();
}
}
|
package seedu.ezdo.ui;
import java.util.logging.Logger;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.layout.Region;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import seedu.ezdo.commons.core.LogsCenter;
import seedu.ezdo.commons.util.FxViewUtil;
/**
* Controller for a help page
*/
public class HelpWindow extends UiPart<Region> {
private static final Logger logger = LogsCenter.getLogger(HelpWindow.class);
private static final String ICON = "/images/help_icon.png";
private static final String FXML = "HelpWindow.fxml";
private static final String TITLE = "Help";
private static final String USERGUIDE_URL =
"https://cs2103jan2017-w14-b4.github.io/main/docs/UserGuide.html";
@FXML
private WebView browser;
private final Stage dialogStage;
public HelpWindow() {
super(FXML);
Scene scene = new Scene(getRoot());
//Null passed as the parent stage to make it non-modal.
dialogStage = createDialogStage(TITLE, null, scene);
dialogStage.setMaximized(true); //TODO: set a more appropriate initial size
FxViewUtil.setStageIcon(dialogStage, ICON);
browser.getEngine().load(USERGUIDE_URL);
FxViewUtil.applyAnchorBoundaryParameters(browser, 0.0, 0.0, 0.0, 0.0);
}
public void show() {
logger.fine("Showing help page about the application.");
dialogStage.showAndWait();
}
}
|
package tars.logic.parser;
import static tars.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static tars.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.time.DateTimeException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import tars.commons.core.Messages;
import tars.commons.exceptions.IllegalValueException;
import tars.commons.exceptions.InvalidRangeException;
import tars.commons.flags.Flag;
import tars.commons.util.DateTimeUtil;
import tars.commons.util.ExtractorUtil;
import tars.commons.util.StringUtil;
import tars.logic.commands.AddCommand;
import tars.logic.commands.CdCommand;
import tars.logic.commands.ClearCommand;
import tars.logic.commands.Command;
import tars.logic.commands.DeleteCommand;
import tars.logic.commands.EditCommand;
import tars.logic.commands.ExitCommand;
import tars.logic.commands.FindCommand;
import tars.logic.commands.HelpCommand;
import tars.logic.commands.IncorrectCommand;
import tars.logic.commands.ListCommand;
import tars.logic.commands.MarkCommand;
import tars.logic.commands.RedoCommand;
import tars.logic.commands.SelectCommand;
import tars.logic.commands.UndoCommand;
import tars.model.task.TaskQuery;
/**
* Parses user input.
*/
public class Parser {
/**
* Used for initial separation of command word and args.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
private static final Pattern TASK_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)");
private static final Pattern FILEPATH_ARGS_FORMAT = Pattern.compile("(?<filepath>\\S+)");
private static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one
// more
// whitespace
public Parser() {
}
/**
* Parses user input into command for execution.
*
* @param userInput
* full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
switch (commandWord) {
case AddCommand.COMMAND_WORD:
return prepareAdd(arguments);
case SelectCommand.COMMAND_WORD:
return prepareSelect(arguments);
case EditCommand.COMMAND_WORD:
return prepareEdit(arguments);
case DeleteCommand.COMMAND_WORD:
return prepareDelete(arguments);
case ClearCommand.COMMAND_WORD:
return new ClearCommand();
case FindCommand.COMMAND_WORD:
return prepareFind(arguments);
case ListCommand.COMMAND_WORD:
if (arguments != null && !arguments.isEmpty()) {
return prepareList(arguments);
} else {
return new ListCommand();
}
case UndoCommand.COMMAND_WORD:
return new UndoCommand();
case RedoCommand.COMMAND_WORD:
return new RedoCommand();
case MarkCommand.COMMAND_WORD:
return prepareMark(arguments);
case CdCommand.COMMAND_WORD:
return prepareCd(arguments);
case ExitCommand.COMMAND_WORD:
return new ExitCommand();
case HelpCommand.COMMAND_WORD:
return new HelpCommand();
default:
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
/**
* Parses arguments in the context of the add task command.
*
* @@author A0139924W
* @param args
* full command args string
* @return the prepared command
*/
private Command prepareAdd(String args) {
// there is no arguments
if (args.trim().length() == 0) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
String name = "";
Flag priorityFlag = new Flag(Flag.PRIORITY, false);
Flag dateTimeFlag = new Flag(Flag.DATETIME, false);
Flag tagFlag = new Flag(Flag.TAG, true);
Flag[] flags = { priorityFlag, dateTimeFlag, tagFlag };
TreeMap<Integer, Flag> flagsPosMap = ExtractorUtil.getFlagPositon(args, flags);
HashMap<Flag, String> argumentMap = ExtractorUtil.getArguments(args, flags, flagsPosMap);
if (flagsPosMap.size() == 0) {
name = args;
} else if (flagsPosMap.firstKey() == 0) {
// there are arguments but name should be the first argument
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
} else {
name = args.substring(0, flagsPosMap.firstKey()).trim();
}
try {
return new AddCommand(name,
DateTimeUtil.getDateTimeFromArgs(argumentMap.get(dateTimeFlag).replace(Flag.DATETIME + " ", "")),
argumentMap.get(priorityFlag).replace(Flag.PRIORITY + " ", ""),
ExtractorUtil.getTagsFromArgs(argumentMap.get(tagFlag), tagFlag));
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
} catch (DateTimeException dte) {
return new IncorrectCommand(Messages.MESSAGE_INVALID_DATE);
}
}
/**
* Parses arguments in the context of the edit task command.
*
* @@author A0121533W
* @param args
* full command args string
* @return the prepared command
*/
private Command prepareEdit(String args) {
args = args.trim();
int targetIndex = 0;
if (args.indexOf(" ") != -1) {
targetIndex = args.indexOf(" ");
}
Optional<Integer> index = parseIndex(args.substring(0, targetIndex));
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
Flag[] flags = generateFlagArrayForEditCommand();
TreeMap<Integer, Flag> flagsPosMap = ExtractorUtil.getFlagPositon(args, flags);
HashMap<Flag, String> argumentMap = ExtractorUtil.getArguments(args, flags, flagsPosMap);
if (flagsPosMap.size() == 0) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE));
}
return new EditCommand(index.get(), argumentMap);
}
private Flag[] generateFlagArrayForEditCommand() {
Flag nameFlag = new Flag(Flag.NAME, false);
Flag priorityFlag = new Flag(Flag.PRIORITY, false);
Flag dateTimeFlag = new Flag(Flag.DATETIME, false);
Flag addTagFlag = new Flag(Flag.ADDTAG, true);
Flag removeTagFlag = new Flag(Flag.REMOVETAG, true);
Flag[] flags = { nameFlag, priorityFlag, dateTimeFlag, addTagFlag, removeTagFlag };
return flags;
}
/**
* Parses arguments in the context of the delete task command.
*
* @param args
* full command args string
* @return the prepared command
*/
private Command prepareDelete(String args) {
args = args.trim();
if (args.equals("")) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
try {
String rangeIndex = StringUtil.indexString(args);
args = rangeIndex;
} catch (InvalidRangeException ire) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
} catch (IllegalValueException ive) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
return new DeleteCommand(args);
}
/**
* Parses arguments in the context of the mark task command.
*
* @@author A0121533W
* @param args
* full command args string
* @return the prepared command
*/
private Command prepareMark(String args) {
Flag doneFlag = new Flag(Flag.DONE, false);
Flag undoneFlag = new Flag(Flag.UNDONE, false);
Flag[] flags = { doneFlag, undoneFlag };
TreeMap<Integer, Flag> flagsPosMap = ExtractorUtil.getFlagPositon(args, flags);
HashMap<Flag, String> argumentMap = ExtractorUtil.getArguments(args, flags, flagsPosMap);
if (flagsPosMap.size() == 0) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkCommand.MESSAGE_USAGE));
}
String markDone = argumentMap.get(doneFlag).replace(Flag.DONE + " ", "").trim();
String markUndone = argumentMap.get(undoneFlag).replace(Flag.UNDONE + " ", "").trim();
try {
String indexesToMarkDone = StringUtil.indexString(markDone);
String indexesToMarkUndone = StringUtil.indexString(markUndone);
markDone = indexesToMarkDone;
markUndone = indexesToMarkUndone;
} catch (InvalidRangeException | IllegalValueException e) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkCommand.MESSAGE_USAGE));
}
return new MarkCommand(markDone, markUndone);
}
/**
* Parses arguments in the context of the select task command.
*
* @param args
* full command args string
* @return the prepared command
*/
private Command prepareSelect(String args) {
Optional<Integer> index = parseIndex(args);
if (!index.isPresent()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE));
}
return new SelectCommand(index.get());
}
/**
* Returns the specified index in the {@code command} IF a positive unsigned
* integer is given as the index. Returns an {@code Optional.empty()}
* otherwise.
*/
private Optional<Integer> parseIndex(String command) {
final Matcher matcher = TASK_INDEX_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String index = matcher.group("targetIndex");
if (!StringUtil.isUnsignedInteger(index)) {
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
/**
* Parses arguments in the context of the find task command.
*
* @param args
* full command args string
* @return the prepared command
*/
private Command prepareFind(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE));
}
Flag[] flags = generateFlagArrayForFindCommand();
TreeMap<Integer, Flag> flagsPosMap = ExtractorUtil.getFlagPositon(args.trim(), flags);
HashMap<Flag, String> argumentMap = ExtractorUtil.getArguments(args.trim(), flags, flagsPosMap);
if (flagsPosMap.size() == 0) {
return new FindCommand(generateKeywordSetFromArgs(args.trim()));
}
TaskQuery taskQuery;
try {
taskQuery = createTaskQuery(argumentMap, flags);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
} catch (DateTimeException dte) {
return new IncorrectCommand(Messages.MESSAGE_INVALID_DATE);
}
return new FindCommand(taskQuery);
}
private TaskQuery createTaskQuery(HashMap<Flag, String> argumentMap, Flag[] flags)
throws DateTimeException, IllegalValueException {
TaskQuery taskQuery = new TaskQuery();
Boolean statusDone = true;
Boolean statusUndone = false;
taskQuery.createNameQuery(argumentMap.get(flags[0]).replace(Flag.NAME, "").trim().replaceAll("( )+", " "));
taskQuery.createDateTimeQuery(
DateTimeUtil.getDateTimeFromArgs(argumentMap.get(flags[1]).replace(Flag.DATETIME, "").trim()));
taskQuery.createPriorityQuery(argumentMap.get(flags[2]).replace(Flag.PRIORITY, "").trim());
if (!argumentMap.get(flags[3]).isEmpty() && !argumentMap.get(flags[4]).isEmpty()) {
throw new IllegalValueException(TaskQuery.MESSAGE_BOTH_STATUS_SEARCHED_ERROR);
} else {
if (!argumentMap.get(flags[3]).isEmpty()) {
taskQuery.createStatusQuery(statusDone);
}
if (!argumentMap.get(flags[4]).isEmpty()) {
taskQuery.createStatusQuery(statusUndone);
}
}
taskQuery.createTagsQuery(argumentMap.get(flags[5]).replace(Flag.TAG, "").trim().replaceAll("( )+", " "));
return taskQuery;
}
private ArrayList<String> generateKeywordSetFromArgs(String keywordsArgs) {
String[] keywordsArray = keywordsArgs.split("\\s+");
return new ArrayList<String>(Arrays.asList(keywordsArray));
}
private Flag[] generateFlagArrayForFindCommand() {
Flag nameFlag = new Flag(Flag.NAME, false);
Flag priorityFlag = new Flag(Flag.PRIORITY, false);
Flag dateTimeFlag = new Flag(Flag.DATETIME, false);
Flag doneFlag = new Flag(Flag.DONE, false);
Flag undoneFlag = new Flag(Flag.UNDONE, false);
Flag tagFlag = new Flag(Flag.TAG, false);
Flag[] flags = { nameFlag, dateTimeFlag, priorityFlag, doneFlag, undoneFlag, tagFlag };
return flags;
}
/**
* Parses arguments in the context of the list task command.
*
* @@author @A0140022H
* @param args
* full command args string
* @return the prepared command
*/
private Command prepareList(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_USAGE));
}
// keywords delimited by whitespace
final String[] keywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords));
return new ListCommand(keywordSet);
}
/**
* Parses arguments in the context of the change storage file directory (cd)
* command.
*
* @@author A0124333U
* @param args
* full command args string
* @return the prepared command
*/
private Command prepareCd(String args) {
final Matcher matcher = FILEPATH_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(CdCommand.MESSAGE_INVALID_FILEPATH));
}
if (!isFileTypeValid(args.trim())) {
return new IncorrectCommand(String.format(CdCommand.MESSAGE_INVALID_FILEPATH));
}
return new CdCommand(args.trim());
}
/**
* Checks if new file type is a valid file type
*
* @@author A0124333U
* @param args
* @return Boolean variable of whether the file type is valid
**/
private Boolean isFileTypeValid(String args) {
String filePath = args.trim();
String extension = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length());
if (extension.equals(CdCommand.getXmlFileExt())) {
return true;
}
return false;
}
}
|
package tars.logic.parser;
import tars.commons.core.Messages;
import tars.commons.exceptions.IllegalValueException;
import tars.commons.util.StringUtil;
import tars.logic.commands.AddCommand;
import tars.logic.commands.ClearCommand;
import tars.logic.commands.Command;
import tars.logic.commands.DeleteCommand;
import tars.logic.commands.ExitCommand;
import tars.logic.commands.FindCommand;
import tars.logic.commands.HelpCommand;
import tars.logic.commands.IncorrectCommand;
import tars.logic.commands.ListCommand;
import tars.logic.commands.SelectCommand;
import static tars.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static tars.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.time.DateTimeException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Parses user input.
*/
public class Parser {
/**
* Used for initial separation of command word and args.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
private static final Pattern PERSON_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)");
private static final Pattern KEYWORDS_ARGS_FORMAT =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
public Parser() {}
/**
* Parses user input into command for execution.
*
* @param userInput full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
switch (commandWord) {
case AddCommand.COMMAND_WORD:
return prepareAdd(arguments);
case SelectCommand.COMMAND_WORD:
return prepareSelect(arguments);
case DeleteCommand.COMMAND_WORD:
return prepareDelete(arguments);
case ClearCommand.COMMAND_WORD:
return new ClearCommand();
case FindCommand.COMMAND_WORD:
return prepareFind(arguments);
case ListCommand.COMMAND_WORD:
return new ListCommand();
case ExitCommand.COMMAND_WORD:
return new ExitCommand();
case HelpCommand.COMMAND_WORD:
return new HelpCommand();
default:
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
/**
* Parses arguments in the context of the add task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareAdd(String args) {
Option nameOpt = new Option("-n", true);
Option priorityOpt = new Option("-p", true);
Option dateTimeOpt = new Option("-dt", true);
Option tagOpt = new Option("-t", false);
Option[] options = {
nameOpt,
priorityOpt,
dateTimeOpt,
tagOpt
};
HashMap<Option, String> optionFlagNArgMap = getOptionFlagNArg(args, options);
if (optionFlagNArgMap.get(nameOpt) == null || optionFlagNArgMap.get(nameOpt).equals("")) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
try {
return new AddCommand(
optionFlagNArgMap.get(nameOpt).replace(" -n ", ""),
getDateTimeFromArgs(optionFlagNArgMap.get(dateTimeOpt).replace(" -dt ", "")),
optionFlagNArgMap.get(priorityOpt).replace(" -p ", ""),
getTagsFromArgs(optionFlagNArgMap.get(tagOpt)));
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
} catch (DateTimeException dte) {
return new IncorrectCommand(Messages.MESSAGE_INVALID_DATE);
}
}
/**
* Extracts the new task's datetime from the add command's task arguments string.
*/
private static String[] getDateTimeFromArgs(String taskArguments) {
if (taskArguments.equals("")) {
return new String[] {"", ""};
} else if (taskArguments.contains("to")) {
int toIndex = taskArguments.indexOf("to");
String startDateTime = taskArguments.substring(0, toIndex).trim();
String endDateTime = taskArguments.substring(toIndex + 2).trim();
return new String[] {startDateTime, endDateTime};
} else {
return new String[] {"", taskArguments};
}
}
/**
* Extracts the new task's tags from the add command's tag arguments string.
* Merges duplicate tag strings.
*/
private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException {
// no tags
if (tagArguments.equals("")) {
return Collections.emptySet();
}
// replace first delimiter prefix, then split
final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" -t ", "").split(" -t "));
return new HashSet<>(tagStrings);
}
/**
* Extracts the option's flag and arg from arguments string.
*/
private static HashMap<Option, String> getOptionFlagNArg(String args, Option[] options) {
TreeMap<Integer, Option> flagsPosMap = new TreeMap<Integer, Option>();
HashMap<Option, String> flagsValueMap = new HashMap<Option, String>();
if (args != null && args.length() > 0 && options.length > 0) {
for (int i = 0; i < options.length; i++) {
int indexOf = -1;
flagsValueMap.put(options[i], "");
do {
indexOf = args.indexOf(options[i].flag, indexOf + 1);
if (indexOf >= 0) {
flagsPosMap.put(indexOf, options[i]);
}
if (options[i].hasMultiple) {
break;
}
} while (indexOf >= 0);
}
int endPos = args.length();
for (Map.Entry<Integer, Option> entry : flagsPosMap.descendingMap().entrySet()) {
Option option = entry.getValue();
Integer pos = entry.getKey();
String arg = args.substring(pos, endPos);
endPos = pos;
if (flagsValueMap.containsKey(option)) {
flagsValueMap.put(option, flagsValueMap.get(option).concat(arg));
} else {
flagsValueMap.put(option, arg);
}
}
}
return flagsValueMap;
}
/**
* Parses arguments in the context of the delete task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareDelete(String args) {
Optional<Integer> index = parseIndex(args);
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
return new DeleteCommand(index.get());
}
/**
* Parses arguments in the context of the select task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareSelect(String args) {
Optional<Integer> index = parseIndex(args);
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE));
}
return new SelectCommand(index.get());
}
/**
* Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index.
* Returns an {@code Optional.empty()} otherwise.
*/
private Optional<Integer> parseIndex(String command) {
final Matcher matcher = PERSON_INDEX_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String index = matcher.group("targetIndex");
if(!StringUtil.isUnsignedInteger(index)){
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
/**
* Parses arguments in the context of the find task command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareFind(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
FindCommand.MESSAGE_USAGE));
}
// keywords delimited by whitespace
final String[] keywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords));
return new FindCommand(keywordSet);
}
}
class Option {
public String flag;
public boolean hasMultiple;
public Option(String flag, boolean hasMultiple) {
this.flag = " " + flag + " ";
this.hasMultiple = hasMultiple;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Option // instanceof handles nulls
&& this.flag.equals(((Option) other).flag)); // state check
}
@Override
public int hashCode() {
return flag.hashCode();
}
}
|
package web;
import csp.Sudoku;
import org.json.*;
import java.util.HashSet;
import java.util.Set;
public class SudokuJSONSerializer {
static Sudoku fromJSON(String string) {
JSONObject root = new JSONObject(new JSONTokener(string));
return new Sudoku(parseGivens(root), root.getInt("boxesPerRow"), root.getInt("boxesPerColumn"));
}
static String toJSON(Sudoku sudoku) {
JSONArray arr = new JSONArray();
if (!sudoku.isSolved()) {
sudoku.getGivens().forEach((given) -> arr.put(stringifyCandidate(given)));
return new JSONStringer()
.object()
.key("givens")
.value(arr)
.endObject()
.toString();
}
else {
sudoku.getSolution().forEach((candidate) -> arr.put(stringifyCandidate(candidate)));
return new JSONStringer()
.object()
.key("solution")
.value(arr)
.endObject()
.toString();
}
}
private static Set<Sudoku.Candidate> parseGivens(JSONObject root) {
JSONArray givens = root.getJSONArray("givens");
Set<Sudoku.Candidate> candidates = new HashSet<>();
for (int i = 0; i < givens.length(); ++i) {
candidates.add(parseCandidate(givens.getJSONObject(i)));
}
return candidates;
}
private static Sudoku.Candidate parseCandidate(JSONObject candidate) {
return new Sudoku.Candidate(candidate.getInt("row"), candidate.getInt("column"), candidate.getInt("digit"));
}
private static JSONObject stringifyCandidate(Sudoku.Candidate candidate) {
JSONObject blob = new JSONObject();
blob.put("row", candidate.row);
blob.put("column", candidate.column);
blob.put("digit", candidate.digit);
return blob;
};
}
|
package com.mygdx.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.sun.javafx.scene.paint.GradientUtils;
import java.awt.Point;
public class PantallaJuego implements Screen, InputProcessor {
private final Juego juego;
private OrthographicCamera camara;
private Viewport vista;
private Texture texturaFondo;
private Texture texturaHeroe1;
private Texture texturaHeroe2;
private Texture texturaHeroe3;
private float[] posicion = new float[2];
private Texture texturaTorre;
private Texture texturaPerdiste;
private SpriteBatch batch;
private Texto texto; //texto para mostrar el cd de las habilidades
private Fondo fondo;
private Estado estado = Estado.JUGANDO;
private Nivel nivel;
private Heroe hero1;
private Heroe hero2;
private Heroe hero3;
private String[] heroesId = new String[3];
private Enemigo[] enemigos;
float xInicial,yInicial;
public PantallaJuego(Juego juego) {
this.juego = juego;
heroesId[0]="1";
heroesId[1]="2";
heroesId[2]="3";
this.nivel = new Nivel("1",heroesId);
this.enemigos = new Enemigo[this.nivel.getCantEnemigos()];
int range = (nivel.getEnemigos().length-1) + 1;
for (int i = 0; i< this.nivel.getCantEnemigos();i++){
int ran = (int)(Math.random() * range);
this.enemigos[i] = new Enemigo(nivel.getEnemigos()[ran],100,100,"Cristal");
}
}
@Override
public void show() {
inicializarCamara();
cargarTexturas();
crearEscena();
Gdx.input.setInputProcessor(this);
texto =new Texto();
}
private void inicializarCamara() {
camara = new OrthographicCamera(1280,720);
camara.position.set(1280/2,720/2,0);
camara.update();
vista = new StretchViewport(1280,800,camara);
}
private void cargarTexturas() {
texturaFondo = this.nivel.getTextura();
texturaHeroe1 = this.nivel.getHeroes()[0].getTextura();
texturaHeroe2 = this.nivel.getHeroes()[1].getTextura();
texturaHeroe3 = this.nivel.getHeroes()[2].getTextura();
}
private void crearEscena() {
batch = new SpriteBatch();
fondo = new Fondo(texturaFondo);
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(1,1,1,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camara.combined);
batch.begin();
fondo.draw(batch);
nivel.getHeroes()[0].draw(batch);//guerrero
nivel.getHeroes()[1].draw(batch);//mago
nivel.getHeroes()[2].draw(batch);//arquera
nivel.getCristal().draw(batch);
if(estado == Estado.PERDER){
batch.draw(texturaPerdiste,200,200);
}
batch.end();
}
public float[] getPosicion1() {
return posicion;
}
@Override
public void resize(int width, int height) {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
}
@Override
public void dispose() {
}
@Override
public boolean keyDown(int keycode) {
return false;
}
@Override
public boolean keyUp(int keycode) {
return false;
}
@Override
public boolean keyTyped(char character) {
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
//si toco alguna habilidad
Vector3 v = new Vector3(screenX,screenY,0);
camara.unproject(v);
float x =v.x;
float y = v.y;
if (estado == Estado.JUGANDO) {
if(nivel.getHeroes()[0].contiene(x,y)){
xInicial = x ;
yInicial = y;
//h.setPosicion(x,y);
//nivel.getHeroes()[0].setEstado(Heroe.Estado.CAMINANDO);
nivel.getHeroes()[0].setEstado(Heroe.Estado.SELECCIONADO);
System.out.println(nivel.getHeroes()[0].getEstado().toString());
}
if(nivel.getHeroes()[1].contiene(x,y)){
xInicial = x ;
yInicial = y;
nivel.getHeroes()[1].setEstado(Heroe.Estado.SELECCIONADO);
//h.setPosicion(x,y);
//nivel.getHeroes()[0].setEstado(Heroe.Estado.CAMINANDO);
}
if(nivel.getHeroes()[2].contiene(x,y)){
xInicial = x ;
yInicial = y;
nivel.getHeroes()[2].setEstado(Heroe.Estado.SELECCIONADO);
//h.setPosicion(x,y);
//nivel.getHeroes()[0].setEstado(Heroe.Estado.CAMINANDO);
}
}
return true;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
Vector3 v = new Vector3(screenX,screenY,0);
camara.unproject(v);
float x =v.x;
float y = v.y;
//posicion[0] = x;
//posicion[1] = y;
System.out.println(nivel.getHeroes()[0].getEstado().toString());
if (nivel.getHeroes()[0].getEstado() == Heroe.Estado.SELECCIONADO) {
if (xInicial > x + 20 || y > yInicial + 20) {
nivel.getHeroes()[0].setEstado(Heroe.Estado.CAMINANDO);
System.out.println("entre1");
nivel.getHeroes()[0].xFinal = x;
nivel.getHeroes()[0].yFinal = y;
}
}
if (nivel.getHeroes()[1].getEstado() == Heroe.Estado.SELECCIONADO) {
if (xInicial > x + 20 || y > yInicial + 20) {
nivel.getHeroes()[1].setEstado(Heroe.Estado.CAMINANDO);
System.out.println("entre2");
nivel.getHeroes()[1].xFinal = x;
nivel.getHeroes()[1].yFinal = y;
}
}
if (nivel.getHeroes()[2].getEstado() == Heroe.Estado.SELECCIONADO) {
if (xInicial > x + 20 || y > yInicial + 20) {
nivel.getHeroes()[2].setEstado(Heroe.Estado.CAMINANDO);
System.out.println("entre3");
nivel.getHeroes()[2].xFinal = x;
nivel.getHeroes()[2].yFinal = y;
//nivel.getHeroes()[0].setPosicion();
}
}
return true;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return true;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
@Override
public boolean scrolled(int amount) {
return false;
}
public enum Estado{
JUGANDO,
GANAR,
PERDER,
SELECCIONADO
}
}
|
package com.quexten.ravtech.ui;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.kotcrab.vis.ui.VisUI;
import com.quexten.ravtech.RavTech;
import com.quexten.ravtech.util.Debug;
public class RavUI {
Stage screenStage = new Stage(new ScreenViewport());
public DebugConsole debugConsole;
public RavUI () {
if (!VisUI.isLoaded())
VisUI.load(Gdx.files.internal("mdpi/uiskin.json"));
debugConsole = new DebugConsole();
RavTech.input.addInputProcessor(screenStage);
screenStage.addListener(new InputListener() {
@Override
public boolean keyDown (InputEvent event, int key) {
if (key == Keys.F1)
debugConsole.toggleVisible();
return true;
}
});
screenStage.addActor(debugConsole);
}
public void render () {
screenStage.act();
screenStage.draw();
}
public Stage getStage () {
return screenStage;
}
}
|
package jpaoletti.jpm2.core.model;
import jpaoletti.jpm2.core.dao.DAOListConfiguration;
import org.hibernate.criterion.Criterion;
/**
* An interface that filters the data shown by an entity.
*
* @author jpaoletti
*
*/
public interface ListFilter {
/**
* Returns a unique id for the filter;
*
* @return
*/
public String getId();
/**
* @param dlc Dao configuration list being configured
* @param entity
* @param sessionData
* @param ownerId
* @return the filter object
*/
public Criterion getListFilter(final DAOListConfiguration dlc, Entity entity, SessionEntityData sessionData, String ownerId);
}
|
package org.motechproject.util;
import org.joda.time.*;
import org.motechproject.model.DayOfWeek;
import org.motechproject.model.Time;
import java.util.Date;
import java.util.List;
import static org.motechproject.model.DayOfWeek.getDayOfWeek;
public class DateUtil {
public static DateTime now() {
return DateTimeSourceUtil.now();
}
public static LocalDate today() {
return DateTimeSourceUtil.today();
}
public static LocalDate tomorrow() {
return today().plusDays(1);
}
public static LocalDate newDate(int year, int month, int day) {
return new LocalDate(DateTimeSourceUtil.SourceInstance.timeZone()).withYear(year).withMonthOfYear(month).withDayOfMonth(day);
}
public static DateTime newDateTime(LocalDate localDate, int hour, int minute, int second) {
return new DateTime(DateTimeSourceUtil.SourceInstance.timeZone()).
withYear(localDate.getYear()).withMonthOfYear(localDate.getMonthOfYear()).withDayOfMonth(localDate.getDayOfMonth())
.withHourOfDay(hour).withMinuteOfHour(minute).withSecondOfMinute(second).withMillisOfSecond(0);
}
public static DateTime setTimeZone(DateTime dateTime) {
return dateTime == null ? dateTime : dateTime.toDateTime(DateTimeSourceUtil.SourceInstance.timeZone());
}
public static DateTime newDateTime(Date date) {
return new DateTime(date.getTime(), DateTimeSourceUtil.SourceInstance.timeZone()).withMillisOfSecond(0);
}
public static DateTime newDateTime(LocalDate date) {
return newDateTime(date, 0, 0, 0);
}
public static LocalDate newDate(Date date) {
if (date == null) return null;
return new LocalDate(date.getTime(), DateTimeSourceUtil.SourceInstance.timeZone());
}
public static LocalDate newDate(DateTime dateTime) {
if (dateTime == null) return null;
return newDate(dateTime.getYear(), dateTime.getMonthOfYear(), dateTime.getDayOfMonth());
}
public static int daysPast(LocalDate date, DayOfWeek dayOfWeek) {
int count = 0;
while (date.getDayOfWeek() != dayOfWeek.getValue()) {
date = date.minusDays(1);
count++;
}
return count;
}
public static boolean isOnOrBefore(LocalDate firstDate, LocalDate secondDate) {
return firstDate.equals(secondDate) || firstDate.isBefore(secondDate);
}
public static boolean isOnOrAfter(LocalDate firstDate, LocalDate secondDate) {
return firstDate.equals(secondDate) || firstDate.isAfter(secondDate);
}
public static int daysToCalendarWeekEnd(LocalDate date, int calendarWeekStartDay) {
int currentDayOfWeek = date.get(DateTimeFieldType.dayOfWeek());
int calendarWeekEndDay = (calendarWeekStartDay + 6) % 7;
int intervalBetweenWeekEndAndCurrentDay = calendarWeekEndDay - currentDayOfWeek;
return intervalBetweenWeekEndAndCurrentDay >= 0 ? intervalBetweenWeekEndAndCurrentDay :
intervalBetweenWeekEndAndCurrentDay + 7;
}
public static DateTime newDateTime(LocalDate localDate, Time time) {
return newDateTime(localDate, time.getHour(), time.getMinute(), 0);
}
public static DateTime newDateTime(int year, int month, int day, Time time) {
return newDateTime(newDate(year, month, day), time.getHour(), time.getMinute(), 0);
}
public static DateTime newDateTime(int year, int month, int day, int hour, int minute, int second) {
return newDateTime(newDate(year, month, day), hour, minute, second);
}
public static int getDifferenceOfDatesInYears(Date startDate) {
Period period = new Period(newDate(startDate), today(), PeriodType.yearMonthDay());
return period.getYears();
}
public static DateTime endOfDay(Date dateTime) {
return new DateTime(dateTime).withTime(23, 59, 59, 999);
}
public static DateTime nextApplicableWeekDay(DateTime fromDate, List<DayOfWeek> applicableDays) {
return nextApplicableWeekDayIncludingFromDate(fromDate.dayOfMonth().addToCopy(1), applicableDays);
}
public static DateTime nextApplicableWeekDayIncludingFromDate(DateTime fromDate, List<DayOfWeek> applicableDays) {
int dayOfWeek = fromDate.getDayOfWeek();
int noOfDaysToNearestCycleDate = 0;
int WEEK_MAX_DAY = DayOfWeek.Sunday.getValue();
for (int currentDayOfWeek = dayOfWeek, dayCount = 0; dayCount <= WEEK_MAX_DAY; dayCount++) {
if (applicableDays.contains(getDayOfWeek(currentDayOfWeek))) {
noOfDaysToNearestCycleDate = dayCount;
break;
}
if (currentDayOfWeek == WEEK_MAX_DAY) currentDayOfWeek = 1;
else currentDayOfWeek++;
}
return fromDate.dayOfMonth().addToCopy(noOfDaysToNearestCycleDate);
}
}
|
package org.motechproject.util;
import org.joda.time.DateTime;
import org.joda.time.DateTimeFieldType;
import org.joda.time.LocalDate;
import org.motechproject.model.DayOfWeek;
import org.motechproject.model.Time;
import java.util.Date;
public class DateUtil {
public static DateTime now() {
return DateTimeSourceUtil.now();
}
public static LocalDate today() {
return DateTimeSourceUtil.today();
}
public static LocalDate tomorrow() {
return today().plusDays(1);
}
public static LocalDate newDate(int year, int month, int day) {
return new LocalDate(DateTimeSourceUtil.SourceInstance.timeZone()).withYear(year).withMonthOfYear(month).withDayOfMonth(day);
}
public static DateTime newDateTime(LocalDate localDate, int hour, int minute, int second) {
return new DateTime(DateTimeSourceUtil.SourceInstance.timeZone()).
withYear(localDate.getYear()).withMonthOfYear(localDate.getMonthOfYear()).withDayOfMonth(localDate.getDayOfMonth())
.withHourOfDay(hour).withMinuteOfHour(minute).withSecondOfMinute(second).withMillisOfSecond(0);
}
public static DateTime setTimeZone(DateTime dateTime) {
return dateTime.toDateTime(DateTimeSourceUtil.SourceInstance.timeZone());
}
public static DateTime newDateTime(Date date) {
return new DateTime(date.getTime(), DateTimeSourceUtil.SourceInstance.timeZone()).withMillisOfSecond(0);
}
public static LocalDate newDate(Date date) {
if (date == null) return null;
return new LocalDate(date.getTime(), DateTimeSourceUtil.SourceInstance.timeZone());
}
public static int daysPast(LocalDate date, DayOfWeek dayOfWeek) {
int count = 0;
while (date.getDayOfWeek() != dayOfWeek.getValue()) {
date = date.minusDays(1);
count++;
}
return count;
}
public static boolean isOnOrBefore(LocalDate firstDate, LocalDate secondDate) {
return firstDate.equals(secondDate) || firstDate.isBefore(secondDate);
}
public static int daysToCalendarWeekEnd(LocalDate date, int calendarWeekStartDay) {
int currentDayOfWeek = date.get(DateTimeFieldType.dayOfWeek());
int calendarWeekEndDay = (calendarWeekStartDay + 6) % 7;
int intervalBetweenWeekEndAndCurrentDay = calendarWeekEndDay - currentDayOfWeek;
return intervalBetweenWeekEndAndCurrentDay >= 0 ? intervalBetweenWeekEndAndCurrentDay :
intervalBetweenWeekEndAndCurrentDay + 7;
}
public static DateTime newDateTime(LocalDate localDate, Time time) {
return newDateTime(localDate, time.getHour(), time.getMinute(), 0);
}
}
|
package com.baomidou.mybatisplus.test;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.handlers.EnumTypeHandler;
import com.baomidou.mybatisplus.test.h2.entity.enums.AgeEnum;
import com.baomidou.mybatisplus.test.h2.entity.mapper.H2UserMapper;
import com.baomidou.mybatisplus.test.h2.entity.persistent.H2User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.h2.Driver;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.SQLException;
/**
* Mybatis
*
* @author nieqiurong 2019/2/27.
*/
@ExtendWith(MockitoExtension.class)
class MybatisTest {
@Test
void test() throws IOException, SQLException {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDbType(DbType.H2.getDb());
dataSource.setDriver(new Driver());
dataSource.setUsername("sa");
dataSource.setPassword("");
dataSource.setValidationQuery("select 1");
dataSource.setUrl("jdbc:h2:mem:test;MODE=mysql;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE");
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory factory = new MybatisSqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = factory.openSession(dataSource.getConnection());
Configuration configuration = factory.getConfiguration();
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
/*
* defaultEnumTypeHandlerMP,
* MP
*/
typeHandlerRegistry.register(AgeEnum.class, EnumTypeHandler.class);
Connection connection = dataSource.getConnection();
ScriptRunner scriptRunner = new ScriptRunner(connection);
scriptRunner.runScript(Resources.getResourceAsReader("h2/user.ddl.sql"));
H2UserMapper mapper = sqlSession.getMapper(H2UserMapper.class);
mapper.delete(new QueryWrapper<>());
Assertions.assertEquals(mapper.myInsertWithNameVersion("test", 2), 1);
Assertions.assertEquals(mapper.mySelectMaps().size(), 1);
Assertions.assertEquals(mapper.insert(new H2User("test")), 1);
Assertions.assertEquals(mapper.selectCount(new QueryWrapper<H2User>().lambda().eq(H2User::getName, "test")), 2);
Assertions.assertEquals(mapper.delete(new QueryWrapper<H2User>().lambda().eq(H2User::getName, "test")), 2);
H2User h2User = new H2User(66L, "66666", AgeEnum.THREE, 666);
Assertions.assertEquals(mapper.insert(h2User), 1);
h2User.setName("7777777777");
H2User user = mapper.selectById(66L);
Assertions.assertNotNull(user);
Assertions.assertEquals(user.getAge(), AgeEnum.THREE);
Assertions.assertNotNull(user.getTestType());
Assertions.assertEquals(mapper.updateById(new H2User(66L, "777777")), 1);
Assertions.assertEquals(mapper.deleteById(66L), 1);
Assertions.assertEquals(mapper.insert(h2User), 1);
Assertions.assertEquals(mapper.delete(new QueryWrapper<>()), 1);
}
}
|
package hudson.tasks;
import hudson.CopyOnWrite;
import hudson.FilePath.FileCallable;
import hudson.Functions;
import hudson.Launcher;
import hudson.Util;
import hudson.model.Build;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.model.Project;
import hudson.remoting.VirtualChannel;
import hudson.util.ArgumentListBuilder;
import hudson.util.FormFieldValidator;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.StringTokenizer;
/**
* Build by using Maven.
*
* @author Kohsuke Kawaguchi
*/
public class Maven extends Builder {
/**
* The targets and other maven options.
* Can be separated by SP or NL.
*/
private final String targets;
/**
* Identifies {@link MavenInstallation} to be used.
*/
private final String mavenName;
public Maven(String targets,String mavenName) {
this.targets = targets;
this.mavenName = mavenName;
}
public String getTargets() {
return targets;
}
/**
* Gets the Maven to invoke,
* or null to invoke the default one.
*/
public MavenInstallation getMaven() {
for( MavenInstallation i : DESCRIPTOR.getInstallations() ) {
if(mavenName !=null && i.getName().equals(mavenName))
return i;
}
return null;
}
/**
* Looks for <tt>pom.xlm</tt> or <tt>project.xml</tt> to determine the maven executable
* name.
*/
private static final class DecideDefaultMavenCommand implements FileCallable<String> {
// command line arguments.
private final String arguments;
public DecideDefaultMavenCommand(String arguments) {
this.arguments = arguments;
}
public String invoke(File ws, VirtualChannel channel) throws IOException {
String seed=null;
// check for the -f option
StringTokenizer tokens = new StringTokenizer(arguments);
while(tokens.hasMoreTokens()) {
String t = tokens.nextToken();
if(t.equals("-f") && tokens.hasMoreTokens()) {
File file = new File(ws,tokens.nextToken());
if(!file.exists())
continue; // looks like an error, but let the execution fail later
if(file.isDirectory())
// in M1, you specify a directory in -f
seed = "maven";
else
// in M2, you specify a POM file name.
seed = "mvn";
break;
}
}
if(seed==null) {
if(new File(ws,"pom.xml").exists())
seed = "mvn";
else
// err on Maven 1 to be closer to the behavior in < 1.81
seed = "maven";
}
if(Functions.isWindows())
seed += ".bat";
return seed;
}
}
public boolean perform(Build build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
Project proj = build.getProject();
String normalizedTarget = targets.replaceAll("[\t\r\n]+"," ");
ArgumentListBuilder args = new ArgumentListBuilder();
MavenInstallation ai = getMaven();
if(ai==null) {
String execName = proj.getWorkspace().act(new DecideDefaultMavenCommand(normalizedTarget));
args.add(execName).addTokenized(normalizedTarget);
} else {
File exec = ai.getExecutable();
if(exec==null) {
listener.fatalError("Couldn't find any executable in "+ai.getMavenHome());
return false;
}
if(!exec.exists()) {
listener.fatalError(exec+" doesn't exist");
return false;
}
args.add(exec.getPath()).addTokenized(normalizedTarget);
}
Map<String,String> env = build.getEnvVars();
if(ai!=null)
env.put("MAVEN_HOME",ai.getMavenHome());
// just as a precaution
// see http://maven.apache.org/continuum/faqs.html#how-does-continuum-detect-a-successful-build
env.put("MAVEN_TERMINATE_CMD","on");
try {
int r = launcher.launch(args.toCommandArray(),env,listener.getLogger(),proj.getModuleRoot()).join();
return r==0;
} catch (IOException e) {
Util.displayIOException(e,listener);
e.printStackTrace( listener.fatalError("command execution failed") );
return false;
}
}
public Descriptor<Builder> getDescriptor() {
return DESCRIPTOR;
}
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
public static final class DescriptorImpl extends Descriptor<Builder> {
@CopyOnWrite
private volatile MavenInstallation[] installations = new MavenInstallation[0];
private DescriptorImpl() {
super(Maven.class);
load();
}
protected void convert(Map<String, Object> oldPropertyBag) {
if(oldPropertyBag.containsKey("installations"))
installations = (MavenInstallation[]) oldPropertyBag.get("installations");
}
public String getHelpFile() {
return "/help/project-config/maven.html";
}
public String getDisplayName() {
return "Invoke top-level Maven targets";
}
public MavenInstallation[] getInstallations() {
return installations;
}
public boolean configure(StaplerRequest req) {
boolean r = true;
int i;
String[] names = req.getParameterValues("maven_name");
String[] homes = req.getParameterValues("maven_home");
int len;
if(names!=null && homes!=null)
len = Math.min(names.length,homes.length);
else
len = 0;
MavenInstallation[] insts = new MavenInstallation[len];
for( i=0; i<len; i++ ) {
if(Util.nullify(names[i])==null) continue;
if(Util.nullify(homes[i])==null) continue;
insts[i] = new MavenInstallation(names[i],homes[i]);
}
this.installations = insts;
save();
return r;
}
public Builder newInstance(StaplerRequest req) {
return new Maven(req.getParameter("maven_targets"),req.getParameter("maven_version"));
}
// web methods
/**
* Checks if the MAVEN_HOME is valid.
*/
public void doCheckMavenHome( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// this can be used to check the existence of a file on the server, so needs to be protected
new FormFieldValidator(req,rsp,true) {
public void check() throws IOException, ServletException {
File f = getFileParameter("value");
if(f.getPath().equals("")) {
error("MAVEN_HOME is required");
return;
}
if(!f.isDirectory()) {
error(f+" is not a directory");
return;
}
// I couldn't come up with a simple logic to test for a maven installation
// there seems to be just too much difference between m1 and m2.
ok();
}
}.process();
}
}
public static final class MavenInstallation {
private final String name;
private final String mavenHome;
public MavenInstallation(String name, String mavenHome) {
this.name = name;
this.mavenHome = mavenHome;
}
/**
* install directory.
*/
public String getMavenHome() {
return mavenHome;
}
public File getHomeDir() {
return new File(mavenHome);
}
/**
* Human readable display name.
*/
public String getName() {
return name;
}
public File getExecutable() {
File exe = getExeFile("maven");
if(exe.exists())
return exe;
exe = getExeFile("mvn");
if(exe.exists())
return exe;
return null;
}
private File getExeFile(String execName) {
if(File.separatorChar=='\\')
execName += ".bat";
return new File(getMavenHome(), "bin/" + execName);
}
/**
* Returns true if the executable exists.
*/
public boolean getExists() {
return getExecutable()!=null;
}
}
}
|
package edu.northwestern.bioinformatics.studycalendar.utils.accesscontrol;
import static java.util.Arrays.asList;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarError;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarSystemException;
import edu.northwestern.bioinformatics.studycalendar.dao.StudyCalendarDao;
import edu.northwestern.bioinformatics.studycalendar.dao.SiteDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.StudySite;
import edu.northwestern.bioinformatics.studycalendar.domain.UserRole;
import edu.northwestern.bioinformatics.studycalendar.domain.Site;
import edu.northwestern.bioinformatics.studycalendar.utils.DomainObjectTools;
import gov.nih.nci.security.UserProvisioningManager;
import gov.nih.nci.security.authorization.domainobjects.Group;
import gov.nih.nci.security.authorization.domainobjects.ProtectionElement;
import gov.nih.nci.security.authorization.domainobjects.ProtectionGroup;
import gov.nih.nci.security.authorization.domainobjects.ProtectionGroupRoleContext;
import gov.nih.nci.security.authorization.domainobjects.Role;
import gov.nih.nci.security.authorization.domainobjects.User;
import gov.nih.nci.security.dao.*;
import gov.nih.nci.security.exceptions.CSObjectNotFoundException;
import gov.nih.nci.security.exceptions.CSTransactionException;
import gov.nih.nci.security.util.ObjectSetUtil;
import gov.nih.nci.cabig.ctms.domain.DomainObject;
import java.util.*;
//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Padmaja Vedula
* @author Rhett Sutphin
*/
// TODO: None of these methods should throw checked exceptions
public class StudyCalendarAuthorizationManager {
public static final String APPLICATION_CONTEXT_NAME = "study_calendar";
public static final String ASSIGNED_USERS = "ASSIGNED_USERS";
public static final String AVAILABLE_USERS = "AVAILABLE_USERS";
public static final String ASSIGNED_PGS = "ASSIGNED_PGS";
public static final String AVAILABLE_PGS = "AVAILABLE_PGS";
public static final String ASSIGNED_PES = "ASSIGNED_PES";
public static final String AVAILABLE_PES = "AVAILABLE_PES";
public static final String PARTICIPANT_COORDINATOR_GROUP = "PARTICIPANT_COORDINATOR";
public static final String SITE_COORDINATOR_GROUP = "SITE_COORDINATOR";
private static Logger log = LoggerFactory.getLogger(StudyCalendarAuthorizationManager.class);
private UserProvisioningManager userProvisioningManager;
private SiteDao siteDao;
public User getUserObject(String id) throws Exception {
User user = null;
user = userProvisioningManager.getUserById(id);
return user;
}
public void createProtectionGroup(String newProtectionGroup) throws Exception {
ProtectionGroup requiredProtectionGroup = new ProtectionGroup();
requiredProtectionGroup.setProtectionGroupName(newProtectionGroup);
userProvisioningManager.createProtectionGroup(requiredProtectionGroup);
if (log.isDebugEnabled()) {
log.debug("new protection group created " + newProtectionGroup);
}
}
/**
* Method to retrieve all site protection groups
*
*/
public List getSites() throws Exception {
List<ProtectionGroup> siteList = new ArrayList<ProtectionGroup>() ;
ProtectionGroup protectionGroup = new ProtectionGroup();
SearchCriteria pgSearchCriteria = new ProtectionGroupSearchCriteria(protectionGroup);
List<ProtectionGroup> pgList = userProvisioningManager.getObjects(pgSearchCriteria);
if (pgList.size() > 0) {
for (ProtectionGroup requiredProtectionGroup : pgList) {
if (isSitePG(requiredProtectionGroup)) {
siteList.add(requiredProtectionGroup);
}
}
}
return siteList;
}
/**
* Method to retrieve a site protection group
* @param name
* @return null or site Protection Group
*
*/
public ProtectionGroup getPGByName(String name) throws Exception {
ProtectionGroup requiredProtectionGroup = null;
ProtectionGroup protectionGroupSearch = new ProtectionGroup();
protectionGroupSearch.setProtectionGroupName(name);
SearchCriteria protectionGroupSearchCriteria = new ProtectionGroupSearchCriteria(protectionGroupSearch);
List<ProtectionGroup> protectionGroupList = userProvisioningManager.getObjects(protectionGroupSearchCriteria);
if (protectionGroupList.size() > 0) {
requiredProtectionGroup = protectionGroupList.get(0);
}
return requiredProtectionGroup;
}
public List<User> getUsersForGroup(String groupName) {
List<User> usersForRequiredGroup = new ArrayList<User>();
User user = new User();
SearchCriteria userSearchCriteria = new UserSearchCriteria(user);
List<User> userList = userProvisioningManager.getObjects(userSearchCriteria);
for (User requiredUser : userList) {
Set<Group> userGroups = getGroups(requiredUser);
for (Group userGroup : userGroups) {
if (userGroup.getGroupName().equals(groupName)) {
usersForRequiredGroup.add(requiredUser);
break;
}
}
}
return usersForRequiredGroup;
}
public void assignProtectionGroupsToUsers(String userId, ProtectionGroup protectionGroup, String roleName) throws Exception {
assignProtectionGroupsToUsers(asList(userId), protectionGroup, roleName);
}
public void assignProtectionGroupsToUsers(List<String> userIds, ProtectionGroup protectionGroup, String roleName) throws Exception
{
if (protectionGroup == null) return;
Role role = new Role();
role.setName(roleName);
SearchCriteria roleSearchCriteria = new RoleSearchCriteria(role);
List roleList = userProvisioningManager.getObjects(roleSearchCriteria);
if (roleList.size() > 0) {
Role accessRole = (Role) roleList.get(0);
String[] roleIds = new String[] {accessRole.getId().toString()};
for (String userId : userIds)
{
userProvisioningManager.assignUserRoleToProtectionGroup(userId, roleIds, protectionGroup.getProtectionGroupId().toString());
}
}
}
public void assignProtectionGroupsToUsers(List<String> userIds, ProtectionGroup protectionGroup, String[] roleNames) throws Exception
{
if (protectionGroup == null) return;
List<Role> roleList = new ArrayList<Role>();
for (String roleStr : roleNames ) {
Role searchRole = new Role();
searchRole.setName(roleStr);
SearchCriteria roleSearchCriteria = new RoleSearchCriteria(searchRole);
roleList.addAll(userProvisioningManager.getObjects(roleSearchCriteria));
}
if (roleList.size() > 0) {
String[] roleIds = new String[roleList.size()];
Iterator<Role> role = roleList.iterator();
for (int i = 0; i < roleIds.length; i++) {
roleIds[i] = role.next().getId().toString();
}
for (String userId : userIds)
{
userProvisioningManager.assignUserRoleToProtectionGroup(userId, roleIds, protectionGroup.getProtectionGroupId().toString());
}
}
}
public void removeProtectionGroupUsers(List<String> userIds, ProtectionGroup protectionGroup) throws Exception
{
if (protectionGroup == null) return;
if (!((userIds.size() == 1) && (userIds.get(0).equals("")))) {
for (String userId : userIds)
{
userProvisioningManager.removeUserFromProtectionGroup(protectionGroup.getProtectionGroupId().toString(), userId);
}
}
}
public void registerUrl(String url, List<String> protectionGroups) {
if (log.isDebugEnabled()) log.debug("Attempting to register PE for " + url + " in " + protectionGroups);
ProtectionElement element = getOrCreateProtectionElement(url);
syncProtectionGroups(element, protectionGroups);
}
private ProtectionElement getOrCreateProtectionElement(String objectId) {
ProtectionElement element = null;
try {
element = userProvisioningManager.getProtectionElement(objectId);
log.debug("PE for " + objectId + " found");
} catch (CSObjectNotFoundException e) {
log.debug("PE for " + objectId + " not found");
// continue
}
if (element == null) {
element = new ProtectionElement();
element.setObjectId(objectId);
element.setProtectionElementName(objectId);
element.setProtectionElementDescription("Autogenerated PE for " + objectId);
try {
userProvisioningManager.createProtectionElement(element);
} catch (CSTransactionException e) {
throw new StudyCalendarSystemException("Creating PE for " + objectId + " failed", e);
}
try {
element = userProvisioningManager.getProtectionElement(element.getObjectId());
} catch (CSObjectNotFoundException e) {
throw new StudyCalendarSystemException("Reloading just-created PE for " + element.getObjectId() + " failed", e);
}
}
return element;
}
private void syncProtectionGroups(ProtectionElement element, List<String> desiredProtectionGroups) {
Set<ProtectionGroup> existingGroups;
try {
existingGroups = userProvisioningManager.getProtectionGroups(element.getProtectionElementId().toString());
} catch (CSObjectNotFoundException e) {
throw new StudyCalendarError("Could not find groups for just-created/loaded PE", e);
}
// if they're all the same, we don't need to do anything
if (existingGroups.size() == desiredProtectionGroups.size()) {
List<String> existingNames = new ArrayList<String>(existingGroups.size());
for (ProtectionGroup existingGroup : existingGroups) existingNames.add(existingGroup.getProtectionGroupName());
if (log.isDebugEnabled()) log.debug(element.getObjectId() + " currently in " + desiredProtectionGroups);
if (existingNames.containsAll(desiredProtectionGroups)) {
log.debug("Sync requires no changes");
return;
}
}
if (log.isDebugEnabled()) log.debug("Setting groups for " + element.getObjectId() + " to " + desiredProtectionGroups);
// accumulate IDs from names
// Seriously -- there's no way to look them up by name
List<ProtectionGroup> allGroups = userProvisioningManager.getProtectionGroups();
List<String> desiredGroupIds = new ArrayList<String>(desiredProtectionGroups.size());
for (ProtectionGroup group : allGroups) {
if (desiredProtectionGroups.contains(group.getProtectionGroupName())) {
desiredGroupIds.add(group.getProtectionGroupId().toString());
}
}
// warn about missing groups, if any
if (desiredGroupIds.size() != desiredProtectionGroups.size()) {
List<String> missingGroups = new LinkedList<String>(desiredProtectionGroups);
for (ProtectionGroup group : allGroups) {
String name = group.getProtectionGroupName();
if (missingGroups.contains(name)) missingGroups.remove(name);
}
log.warn("Requested protection groups included one or more that don't exist: " + missingGroups + ". These groups were skipped.");
}
try {
userProvisioningManager.assignToProtectionGroups(
element.getProtectionElementId().toString(), desiredGroupIds.toArray(new String[0]));
} catch (CSTransactionException e) {
throw new StudyCalendarSystemException("Assigning PE " + element.getProtectionElementName() + " to groups " + desiredProtectionGroups + " failed", e);
}
}
public List<ProtectionGroup> getSitePGsForUser(String userName) {
return getSitePGs(userProvisioningManager.getUser(userName));
}
public List<ProtectionGroup> getStudySitePGsForUser(String userName) {
User user = userProvisioningManager.getUser(userName);
List<ProtectionGroup> studySitePGs = new ArrayList<ProtectionGroup>();
for (Group group : getGroups(user)) {
if (group.getGroupName().equals(PARTICIPANT_COORDINATOR_GROUP)) {
Set<ProtectionGroupRoleContext> pgRoleContexts = getProtectionGroupRoleContexts(user);
for (ProtectionGroupRoleContext pgrc : pgRoleContexts) {
if (isStudySitePG(pgrc.getProtectionGroup())) {
studySitePGs.add(pgrc.getProtectionGroup());
}
}
}
}
return studySitePGs;
}
public List<Study> checkOwnership(String userName, List<Study> studies) {
Set<Study> assignedStudies = new LinkedHashSet<Study>();
User userTemplate = new User();
userTemplate.setLoginName(userName);
SearchCriteria userSearchCriteria = new UserSearchCriteria(userTemplate);
List<User> userList = userProvisioningManager.getObjects(userSearchCriteria);
if (userList.size() > 0) {
User user = userList.get(0);
Set<Group> userGroups = getGroups(user);
if (userGroups.size() > 0) {
Group requiredGroup = userGroups.iterator().next();
if (requiredGroup.getGroupName().equals(PARTICIPANT_COORDINATOR_GROUP)) {
for (Study study : studies) {
if (checkParticipantCoordinatorOwnership(user, study)) {
assignedStudies.add(study);
}
}
} else if (requiredGroup.getGroupName().equals(SITE_COORDINATOR_GROUP)) {
List<ProtectionGroup> sites = getSitePGs(user);
for (Study study : studies) {
if (checkSiteCoordinatorOwnership(study, sites)) {
assignedStudies.add(study);
}
}
} else {
assignedStudies.addAll(studies);
}
}
}
return new ArrayList<Study>(assignedStudies);
}
public void removeProtectionGroup(String protectionGroupName) throws Exception {
ProtectionGroup pg = new ProtectionGroup();
pg.setProtectionGroupName(protectionGroupName);
SearchCriteria pgSearchCriteria = new ProtectionGroupSearchCriteria(pg);
List<ProtectionGroup> pgList = userProvisioningManager.getObjects(pgSearchCriteria);
if (pgList.size() > 0) {
userProvisioningManager.removeProtectionGroup(pgList.get(0).getProtectionGroupId().toString());
}
}
public void createAndAssignPGToUser(List<String> userIds, String protectionGroupName, String roleName) throws Exception {
ProtectionGroup pg = new ProtectionGroup();
pg.setProtectionGroupName(protectionGroupName);
SearchCriteria pgSearchCriteria = new ProtectionGroupSearchCriteria(pg);
List<ProtectionGroup> pgList = userProvisioningManager.getObjects(pgSearchCriteria);
if (pgList.size() <= 0) {
ProtectionGroup requiredProtectionGroup = new ProtectionGroup();
requiredProtectionGroup.setProtectionGroupName(protectionGroupName);
userProvisioningManager.createProtectionGroup(requiredProtectionGroup);
}
Role role = new Role();
role.setName(roleName);
SearchCriteria roleSearchCriteria = new RoleSearchCriteria(role);
List roleList = userProvisioningManager.getObjects(roleSearchCriteria);
if (roleList.size() > 0) {
Role accessRole = (Role) roleList.get(0);
String[] roleIds = new String[] {accessRole.getId().toString()};
if (!((userIds.size() == 1) && (userIds.get(0).equals("")))) {
for (String userId : userIds)
{
userProvisioningManager.assignUserRoleToProtectionGroup(userId, roleIds, getPGByName(protectionGroupName).getProtectionGroupId().toString());
}
}
}
}
public boolean isUserPGAssigned(String pgName, String userId) throws Exception {
Set<ProtectionGroupRoleContext> pgRoleContext = userProvisioningManager.getProtectionGroupRoleContextForUser(userId);
List<ProtectionGroupRoleContext> pgRoleContextList = new ArrayList<ProtectionGroupRoleContext> (pgRoleContext);
if (pgRoleContextList.size() != 0) {
for (ProtectionGroupRoleContext pgrc : pgRoleContextList) {
if (pgrc.getProtectionGroup().getProtectionGroupName().equals(pgName)) {
return true;
}
}
}
return false;
}
public void assignCsmGroups(edu.northwestern.bioinformatics.studycalendar.domain.User user, Set<UserRole> userRoles) throws Exception {
List<String> csmRoles = rolesToCsmGroups(userRoles);
String[] strCsmRoles = csmRoles.toArray(new String[csmRoles.size()]);
userProvisioningManager.assignGroupsToUser(user.getCsmUserId().toString(), strCsmRoles);
}
private List<String> rolesToCsmGroups(Set<UserRole> userRoles) throws Exception{
List csmGroupsForUser = new ArrayList<String>();
if(userRoles != null) {
List<Group> allCsmGroups = getAllCsmGroups();
for(UserRole userRole: userRoles) {
for(Group group: allCsmGroups) {
if(isGroupEqualToRole(group, userRole.getRole())) {
csmGroupsForUser.add(group.getGroupId().toString());
}
}
}
}
return csmGroupsForUser;
}
////// INTERNAL HELPERS
protected boolean isGroupEqualToRole(Group group, edu.northwestern.bioinformatics.studycalendar.domain.Role role) {
return group.getGroupName().equals(role.getCode());
}
@SuppressWarnings("unchecked")
private List<Group> getAllCsmGroups() throws Exception {
SearchCriteria searchCriteria = new GroupSearchCriteria(new Group());
List<Group> groups = userProvisioningManager.getObjects(searchCriteria);
if(groups == null) {
throw new StudyCalendarSystemException("Get Csm Groups is null");
}
return groups;
}
private List<ProtectionGroup> getSitePGs(User user) {
List<ProtectionGroup> sites = new ArrayList<ProtectionGroup>();
Set<ProtectionGroupRoleContext> pgRoleContext = getProtectionGroupRoleContexts(user);
if (pgRoleContext.size() != 0) {
for (ProtectionGroupRoleContext pgrc : pgRoleContext) {
if (isSitePG(pgrc.getProtectionGroup())) {
sites.add(pgrc.getProtectionGroup());
}
}
}
return sites;
}
private boolean checkSiteCoordinatorOwnership(Study study, List<ProtectionGroup> sites) {
List<StudySite> studySites = study.getStudySites();
for (StudySite studySite : studySites) {
for (ProtectionGroup site : sites) {
if (studySite.getSite().equals(DomainObjectTools.loadFromExternalObjectId(site.getProtectionGroupName(), siteDao))) {
return true;
}
}
}
return false;
}
private boolean checkParticipantCoordinatorOwnership(User user, Study study) {
String userName = user.getLoginName();
List<StudySite> studySites = study.getStudySites();
for (StudySite studySite : studySites) {
String protectionGroupName = DomainObjectTools.createExternalObjectId(studySite);
Set<ProtectionGroupRoleContext> pgRoleContext = getProtectionGroupRoleContexts(user);
if (pgRoleContext.size() != 0) {
for (ProtectionGroupRoleContext pgrc : pgRoleContext) {
if (pgrc.getProtectionGroup().getProtectionGroupName().equals(protectionGroupName)) {
return true;
}
}
}
}
return userProvisioningManager.checkOwnership(userName, DomainObjectTools.createExternalObjectId(study));
}
private Set<Group> getGroups(User user) {
try {
return userProvisioningManager.getGroups(user.getUserId().toString());
} catch (CSObjectNotFoundException e) {
throw new StudyCalendarSystemException("Could not get groups for " + user.getLoginName(), e);
}
}
private Set<ProtectionGroupRoleContext> getProtectionGroupRoleContexts(User user) {
try {
return userProvisioningManager.getProtectionGroupRoleContextForUser(user.getUserId().toString());
} catch (CSObjectNotFoundException e) {
throw new StudyCalendarSystemException("Could not find PGRCs for " + user.getLoginName(), e);
}
}
private boolean isSitePG(ProtectionGroup protectionGroup) {
return protectionGroup.getProtectionGroupName().startsWith(Site.class.getName());
}
private boolean isStudySitePG(ProtectionGroup protectionGroup) {
return protectionGroup.getProtectionGroupName().startsWith(StudySite.class.getName());
}
////// CONFIGURATION
public void setUserProvisioningManager(UserProvisioningManager userProvisioningManager) {
this.userProvisioningManager = userProvisioningManager;
}
public void setSiteDao(SiteDao siteDao) {
this.siteDao = siteDao;
}
}
|
package main.xml.pubmed.model;
public class MedlineCitationDate {
private String year;
private String month;
private String day;
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
}
|
package org.apereo.cas.adaptors.u2f.storage;
import com.yubico.u2f.data.DeviceRegistration;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apereo.cas.util.crypto.CertUtils;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import java.security.cert.X509Certificate;
import java.util.Collection;
import static org.junit.Assert.*;
/**
* This is {@link AbstractU2FDeviceRepositoryTests}.
*
* @author Misagh Moayyed
* @since 5.2.0
*/
@Slf4j
public abstract class AbstractU2FDeviceRepositoryTests {
@Test
public void verifyDeviceSaved() {
try {
final X509Certificate cert = CertUtils.readCertificate(new ClassPathResource("cert.crt"));
final DeviceRegistration r1 = new DeviceRegistration("keyhandle11", "publickey1", cert, 1);
final DeviceRegistration r2 = new DeviceRegistration("keyhandle22", "publickey1", cert, 2);
getDeviceRepository().registerDevice("casuser", r1);
getDeviceRepository().registerDevice("casuser", r2);
final Collection<DeviceRegistration> devs = getDeviceRepository().getRegisteredDevices("casuser");
assertEquals(2, devs.size());
} catch (final Exception e) {
throw new AssertionError(e.getMessage(), e);
}
}
protected abstract U2FDeviceRepository getDeviceRepository();
}
|
package com.systematic.trading.maths.indicator.rsi;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.List;
import com.systematic.trading.collection.NonNullableArrayList;
import com.systematic.trading.data.TradingDayPrices;
import com.systematic.trading.data.price.ClosingPrice;
import com.systematic.trading.maths.indicator.Validator;
/**
* Relative Strength Index - RSI
*
* A technical momentum indicator that compares the magnitude of recent gains to recent losses in an
* attempt to determine over bought and over sold conditions of an asset.
*
* RSI = 100 - 100/(1 + RS*)
*
* Where RS = Average of x days' up closes / Average of x days' down closes.
*
* Uses the EMA in calculation of the relative strength (J. Welles Wilder approach), not the SMA.
*
* Taking the prior value plus the current value is a smoothing technique similar to that used in
* exponential moving average calculation. This also means that RSI values become more accurate as
* the calculation period extends.
*
* @author CJ Hare
*/
public class RelativeStrengthIndexCalculator implements RelativeStrengthIndex {
/** Constant for the value of 100. */
private static final BigDecimal ONE_HUNDRED = BigDecimal.valueOf(50);
/** Scale, precision and rounding to apply to mathematical operations. */
private final MathContext mathContext;
/** The number of trading days to look back for calculation. */
private final int lookback;
/** Provides the array to store the result in. */
private final List<BigDecimal> relativeStrengthValues;
/** Provides the array to store the result in. */
private final List<BigDecimal> relativeStrengthIndexValues;
/** Required number of data points required for ATR calculation. */
private final int minimumNumberOfPrices;
/** Constant used for smoothing the moving average. */
private final BigDecimal smoothingConstant;
/** Responsible for parsing and validating the input. */
private final Validator validator;
/**
* @param lookback the number of days to use when calculating the RSI.
* @param daysOfRsiValues the number of trading days to calculate the RSI value.
* @param validator validates and parses input.
* @param mathContext the scale, precision and rounding to apply to mathematical operations.
*/
public RelativeStrengthIndexCalculator(final int lookback, final int daysOfRsiValues, final Validator validator,
final MathContext mathContext) {
this.relativeStrengthIndexValues = new NonNullableArrayList<>();
this.relativeStrengthValues = new NonNullableArrayList<>();
this.minimumNumberOfPrices = lookback + daysOfRsiValues;
this.smoothingConstant = calculateSmoothingConstant(lookback);
this.mathContext = mathContext;
this.validator = validator;
this.lookback = lookback;
}
@Override
public List<BigDecimal> rsi( final TradingDayPrices[] data ) {
validator.verifyZeroNullEntries(data);
validator.verifyEnoughValues(data, minimumNumberOfPrices);
relativeStrengthIndexValues.clear();
relativeStrengthValues.clear();
/* For the first zero - time period entries calculate the SMA based on up to down movement
* Upwards movement upward = closeToday - closeYesterday downward = 0 Downwards movement
* upward = closeYesterday - closeToday */
final int startRsiIndex = 0;
ClosingPrice closeToday;
ClosingPrice closeYesterday = data[startRsiIndex].getClosingPrice();
BigDecimal upward = BigDecimal.ZERO;
BigDecimal downward = BigDecimal.ZERO;
final int endInitialLookback = startRsiIndex + lookback;
for (int i = startRsiIndex; i < endInitialLookback; i++) {
closeToday = data[i].getClosingPrice();
switch (closeToday.compareTo(closeYesterday)) {
// Today's price is higher then yesterdays
case 1:
upward = upward.add(closeToday.subtract(closeYesterday, mathContext));
break;
// Today's price is lower then yesterdays
case -1:
downward = downward.add(closeYesterday.subtract(closeToday, mathContext));
break;
// When equal there's no movement, both are zero
case 0:
default:
break;
}
closeYesterday = closeToday;
}
// Dividing by the number of time periods for a SMA
// Reduce lookup by one, as the initial value is neither up or down
upward = upward.divide(BigDecimal.valueOf(lookback - 1L), mathContext);
downward = downward.divide(BigDecimal.valueOf(lookback - 1L), mathContext);
/* RS = EMA(U,n) / EMA(D,n) (smoothing constant) multiplier: (2 / (Time periods + 1) ) EMA:
* {Close - EMA(previous day)} x multiplier + EMA(previous day). */
for (int i = endInitialLookback; i < data.length; i++) {
closeToday = data[i].getClosingPrice();
closeYesterday = data[i - 1].getClosingPrice();
switch (closeToday.compareTo(closeYesterday)) {
case 1: // Today's price is higher then yesterdays
upward = (closeToday.subtract(closeYesterday, mathContext).subtract(upward, mathContext))
.multiply(smoothingConstant, mathContext).add(upward, mathContext);
downward = downward.negate().multiply(smoothingConstant, mathContext).add(downward, mathContext);
break;
case -1: // Today's price is lower then yesterdays
upward = upward.negate().multiply(smoothingConstant, mathContext).add(upward, mathContext);
downward = (closeYesterday.subtract(closeToday, mathContext).subtract(downward, mathContext))
.multiply(smoothingConstant, mathContext).add(downward, mathContext);
break;
case 0: // When equal there's no movement, both are zero
default:
break;
}
// When downward approaches zero, RSI approaches 100
if (downward.compareTo(BigDecimal.ZERO) <= 0) {
relativeStrengthValues.add(ONE_HUNDRED);
} else {
relativeStrengthValues.add(upward.divide(downward, mathContext));
}
}
/* RSI = 100 / 1 + RS */
for (final BigDecimal rs : relativeStrengthValues) {
relativeStrengthIndexValues
.add(ONE_HUNDRED.subtract(ONE_HUNDRED.divide(BigDecimal.ONE.add(rs), mathContext)));
}
return relativeStrengthIndexValues;
}
private BigDecimal calculateSmoothingConstant( final int lookback ) {
return BigDecimal.valueOf(2d / (lookback + 1));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.