answer
stringlengths 17
10.2M
|
|---|
package com.wiccanarts.common.item;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.EnumAction;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.PotionEffect;
import net.minecraft.potion.PotionUtils;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.world.World;
public class ItemBrewPhial extends ItemMod {
public ItemBrewPhial(String id) {
super(id);
}
@Override
public ItemStack onItemUseFinish(ItemStack stack, World world, EntityLivingBase entity) {
EntityPlayer player = entity instanceof EntityPlayer ? (EntityPlayer) entity : null;
assert player != null;
--stack.stackSize;
if (!world.isRemote) {
for (PotionEffect effect : PotionUtils.getEffectsFromStack(stack)) {
System.out.println(effect);
entity.addPotionEffect(effect);
}
}
if (!player.capabilities.isCreativeMode) {
if (stack.stackSize <= 0) {
return new ItemStack(Items.GLASS_BOTTLE);
}
player.inventory.addItemStackToInventory(new ItemStack(Items.GLASS_BOTTLE));
}
return stack;
}
@Override
public int getMaxItemUseDuration(ItemStack stack) {
return 32;
}
@Override
public EnumAction getItemUseAction(ItemStack stack) {
return EnumAction.DRINK;
}
public ActionResult<ItemStack> onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand) {
playerIn.setActiveHand(hand);
return new ActionResult<>(EnumActionResult.SUCCESS, itemStackIn);
}
}
|
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import junit.framework.Assert;
import org.junit.Test;
import edu.cornell.mannlib.vitro.testing.AbstractTestClass;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder.ParamMap;
public class UrlBuilderTest extends AbstractTestClass {
@Test
public void testGetUrl() {
UrlBuilder.contextPath = "/vivo";
String path1 = "/individual";
Assert.assertEquals("/vivo/individual", UrlBuilder.getUrl(path1));
int portalId = 1;
String path2 = "/individual?home=" + portalId;
Assert.assertEquals("/vivo/individual?home=1", UrlBuilder.getUrl(path2));
}
@Test
public void testGetUrlWithEmptyContext() {
UrlBuilder.contextPath = "";
String path = "/individual";
Assert.assertEquals(path, UrlBuilder.getUrl(path));
}
@Test
public void testGetUrlWithParams() {
UrlBuilder.contextPath = "/vivo";
String path = "/individual";
ParamMap params = new ParamMap();
int portalId = 1;
params.put("home", "" + portalId);
params.put("name", "Tom");
Assert.assertEquals("/vivo/individual?home=1&name=Tom", UrlBuilder.getUrl(path, params));
}
@Test
public void testEncodeUrl() {
UrlBuilder.contextPath = "/vivo";
String path = "/individuallist";
ParamMap params = new ParamMap();
String vClassUri = "http://vivoweb.org/ontology/core#FacultyMember";
params.put("vclassId", vClassUri);
Assert.assertEquals("/vivo/individuallist?vclassId=http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23FacultyMember", UrlBuilder.getUrl(path, params));
}
@Test
public void testDecodeUrl() {
String vClassUri = "http://vivoweb.org/ontology/core#FacultyMember";
String vClassUriEncoded = "http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23FacultyMember";
Assert.assertEquals(vClassUri, UrlBuilder.urlDecode(vClassUriEncoded));
}
@Test
public void testUtf8Encode(){
UrlBuilder.contextPath = "/vivo";
String path = "/individual";
ParamMap params = new ParamMap();
params.put("name", "Tom");
Assert.assertEquals("/vivo/individual?name=%E2%98%85Tom%E2%98%85", UrlBuilder.getUrl(path, params));
}
@Test
public void testDecodeUtf8Url() {
String vClassUri = "http://vivoweb.org/ontology/core#FacultyMember";
String vClassUriEncoded = "http%3A%2F%2Fvivoweb.org%2Fontology%2Fcore%23FacultyMember%E2%98%85";
Assert.assertEquals(vClassUri, UrlBuilder.urlDecode(vClassUriEncoded));
}
}
|
// TiffWriter.java
package loci.formats.out;
import java.io.IOException;
import loci.common.RandomAccessInputStream;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.FormatWriter;
import loci.formats.ImageTools;
import loci.formats.codec.CompressionType;
import loci.formats.gui.AWTImageTools;
import loci.formats.meta.MetadataRetrieve;
import loci.formats.tiff.IFD;
import loci.formats.tiff.TiffCompression;
import loci.formats.tiff.TiffParser;
import loci.formats.tiff.TiffRational;
import loci.formats.tiff.TiffSaver;
public class TiffWriter extends FormatWriter {
// -- Constants --
public static final String COMPRESSION_UNCOMPRESSED =
CompressionType.UNCOMPRESSED.getCompression();
public static final String COMPRESSION_LZW =
CompressionType.LZW.getCompression();
public static final String COMPRESSION_J2K =
CompressionType.J2K.getCompression();
public static final String COMPRESSION_J2K_LOSSY =
CompressionType.J2K_LOSSY.getCompression();
public static final String COMPRESSION_JPEG =
CompressionType.JPEG.getCompression();
// -- Fields --
/** Whether or not the output file is a BigTIFF file. */
protected boolean isBigTiff;
/** The TiffSaver that will do most of the writing. */
protected TiffSaver tiffSaver;
/** Whether or not to check the parameters passed to saveBytes. */
private boolean checkParams = true;
/**
* Sets the compression code for the specified IFD.
*
* @param ifd The IFD table to handle.
*/
private void formatCompression(IFD ifd)
throws FormatException
{
if (compression == null) compression = "";
TiffCompression compressType = TiffCompression.UNCOMPRESSED;
if (compression.equals(COMPRESSION_LZW)) {
compressType = TiffCompression.LZW;
}
else if (compression.equals(COMPRESSION_J2K)) {
compressType = TiffCompression.JPEG_2000;
}
else if (compression.equals(COMPRESSION_J2K_LOSSY)) {
compressType = TiffCompression.JPEG_2000_LOSSY;
}
else if (compression.equals(COMPRESSION_JPEG)) {
compressType = TiffCompression.JPEG;
}
Object v = ifd.get(new Integer(IFD.COMPRESSION));
if (v == null)
ifd.put(new Integer(IFD.COMPRESSION), compressType.getCode());
}
// -- Constructors --
public TiffWriter() {
this("Tagged Image File Format", new String[] {"tif", "tiff"});
}
public TiffWriter(String format, String[] exts) {
super(format, exts);
compressionTypes = new String[] {
COMPRESSION_UNCOMPRESSED,
COMPRESSION_LZW,
COMPRESSION_J2K,
COMPRESSION_J2K_LOSSY,
COMPRESSION_JPEG
};
isBigTiff = false;
}
// -- TiffWriter API methods --
/**
* Saves the given image to the specified (possibly already open) file.
* The IFD hashtable allows specification of TIFF parameters such as bit
* depth, compression and units. If this image is the last one in the file,
* the last flag must be set.
*/
public void saveBytes(int no, byte[] buf, IFD ifd)
throws IOException, FormatException
{
MetadataRetrieve r = getMetadataRetrieve();
int w = r.getPixelsSizeX(series).getValue().intValue();
int h = r.getPixelsSizeY(series).getValue().intValue();
saveBytes(no, buf, ifd, 0, 0, w, h);
}
/**
* Saves the given image to the specified series in the current file.
* The IFD hashtable allows specification of TIFF parameters such as bit
* depth, compression and units. If this image is the last one in the series,
* the lastInSeries flag must be set. If this image is the last one in the
* file, the last flag must be set.
*/
public void saveBytes(int no, byte[] buf, IFD ifd, int x, int y, int w, int h)
throws IOException, FormatException
{
if (checkParams) checkParams(no, buf, x, y, w, h);
MetadataRetrieve retrieve = getMetadataRetrieve();
Boolean bigEndian = retrieve.getPixelsBinDataBigEndian(series, 0);
boolean littleEndian = bigEndian == null ?
false : !bigEndian.booleanValue();
//if (tiffSaver == null)
tiffSaver = new TiffSaver(out);
tiffSaver.setWritingSequentially(sequential);
tiffSaver.setLittleEndian(littleEndian);
tiffSaver.setBigTiff(isBigTiff);
if (no < initialized[series].length && !initialized[series][no]) {
initialized[series][no] = true;
RandomAccessInputStream tmp = new RandomAccessInputStream(currentId);
if (tmp.length() == 0) {
// write TIFF header
tiffSaver.writeHeader();
}
tmp.close();
}
int width = retrieve.getPixelsSizeX(series).getValue().intValue();
int height = retrieve.getPixelsSizeY(series).getValue().intValue();
int c = getSamplesPerPixel();
int type = FormatTools.pixelTypeFromString(
retrieve.getPixelsType(series).toString());
int bytesPerPixel = FormatTools.getBytesPerPixel(type);
int plane = width * height * c * bytesPerPixel;
if (plane > buf.length) {
c = buf.length / (width * height * bytesPerPixel);
plane = width * height * c * bytesPerPixel;
}
if (bytesPerPixel > 1 && c != 1 && c != 3) {
// split channels
checkParams = false;
if (no == 0) {
initialized[series] = new boolean[initialized[series].length * c];
}
for (int i=0; i<c; i++) {
byte[] b = ImageTools.splitChannels(buf, i, c, bytesPerPixel,
false, interleaved);
saveBytes(no + i, b, ifd, x, y, w, h);
}
checkParams = true;
return;
}
if (ifd == null) ifd = new IFD();
formatCompression(ifd);
byte[][] lut = AWTImageTools.get8BitLookupTable(cm);
if (lut != null) {
int[] colorMap = new int[lut.length * lut[0].length];
for (int i=0; i<lut.length; i++) {
for (int j=0; j<lut[0].length; j++) {
colorMap[i * lut[0].length + j] = (int) ((lut[i][j] & 0xff) << 8);
}
}
ifd.putIFDValue(IFD.COLOR_MAP, colorMap);
}
ifd.put(new Integer(IFD.IMAGE_WIDTH), new Integer(width));
ifd.put(new Integer(IFD.IMAGE_LENGTH), new Integer(height));
Double physicalSizeX = retrieve.getPixelsPhysicalSizeX(series);
if (physicalSizeX == null) physicalSizeX = 0d;
else physicalSizeX = 1d / physicalSizeX;
Double physicalSizeY = retrieve.getPixelsPhysicalSizeY(series);
if (physicalSizeY == null) physicalSizeY = 0d;
else physicalSizeY = 1d / physicalSizeY;
ifd.put(IFD.RESOLUTION_UNIT, 3);
ifd.put(IFD.X_RESOLUTION,
new TiffRational((long) (physicalSizeX * 1000 * 10000), 1000));
ifd.put(IFD.Y_RESOLUTION,
new TiffRational((long) (physicalSizeY * 1000 * 10000), 1000));
if (!isBigTiff) {
isBigTiff = (out.length() + 2 * plane) >= 4294967296L;
if (isBigTiff) {
throw new FormatException("File is too large; call setBigTiff(true)");
}
}
// write the image
ifd.put(new Integer(IFD.LITTLE_ENDIAN), new Boolean(littleEndian));
out.seek(out.length());
ifd.putIFDValue(IFD.PLANAR_CONFIGURATION, interleaved ? 1 : 2);
int sampleFormat = 1;
if (FormatTools.isSigned(type)) sampleFormat = 2;
if (FormatTools.isFloatingPoint(type)) sampleFormat = 3;
ifd.putIFDValue(IFD.SAMPLE_FORMAT, sampleFormat);
RandomAccessInputStream in = new RandomAccessInputStream(currentId);
in.order(littleEndian);
tiffSaver.setInputStream(in);
int index = no;
int realSeries = getSeries();
for (int i=0; i<realSeries; i++) {
setSeries(i);
index += getPlaneCount();
}
setSeries(realSeries);
tiffSaver.writeImage(buf, ifd, index, type, x, y, w, h,
no == getPlaneCount() - 1 && getSeries() == retrieve.getImageCount() - 1);
tiffSaver.setInputStream(null);
in.close();
}
// -- FormatWriter API methods --
protected int getPlaneCount() {
int c = getSamplesPerPixel();
if (c == 1 || c == 3) return super.getPlaneCount();
return c * super.getPlaneCount();
}
// -- IFormatWriter API methods --
/**
* @see loci.formats.IFormatWriter#saveBytes(int, byte[], int, int, int, int)
*/
public void saveBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
IFD ifd = new IFD();
if (!sequential) {
TiffParser parser = new TiffParser(currentId);
try {
long[] ifdOffsets = parser.getIFDOffsets();
if (no < ifdOffsets.length) {
ifd = parser.getIFD(ifdOffsets[no]);
}
}
finally {
RandomAccessInputStream tiffParserStream = parser.getStream();
if (tiffParserStream != null) {
tiffParserStream.close();
}
}
}
formatCompression(ifd);
saveBytes(no, buf, ifd, x, y, w, h);
}
/* @see loci.formats.IFormatWriter#canDoStacks(String) */
public boolean canDoStacks() { return true; }
/* @see loci.formats.IFormatWriter#getPixelTypes(String) */
public int[] getPixelTypes(String codec) {
if (codec != null && (codec.startsWith(COMPRESSION_J2K) ||
codec.equals(COMPRESSION_JPEG)))
{
return new int[] {FormatTools.INT8, FormatTools.UINT8, FormatTools.INT16, FormatTools.UINT16};//Question to ask
}
return new int[] {FormatTools.INT8, FormatTools.UINT8, FormatTools.INT16,
FormatTools.UINT16, FormatTools.INT32, FormatTools.UINT32,
FormatTools.FLOAT, FormatTools.DOUBLE};
}
// -- TiffWriter API methods --
/**
* Sets whether or not BigTIFF files should be written.
* This flag is not reset when close() is called.
*/
public void setBigTiff(boolean bigTiff) {
FormatTools.assertId(currentId, false, 1);
isBigTiff = bigTiff;
}
}
|
// LocationTest.java
package loci.common.utests;
import static org.testng.AssertJUnit.assertEquals;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import loci.common.Location;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class LocationTest {
// -- Fields --
private Location[] files;
private boolean[] exists;
private boolean[] isDirectory;
private boolean[] isHidden;
private String[] mode;
// -- Setup methods --
@BeforeMethod
public void setup() throws IOException {
File tmpDirectory = new File(System.getProperty("java.io.tmpdir"),
System.currentTimeMillis() + "-location-test");
boolean success = tmpDirectory.mkdirs();
tmpDirectory.deleteOnExit();
File hiddenFile = File.createTempFile(".hiddenTest", null, tmpDirectory);
hiddenFile.deleteOnExit();
File invalidFile = File.createTempFile("invalidTest", null, tmpDirectory);
String invalidPath = invalidFile.getAbsolutePath();
invalidFile.delete();
File validFile = File.createTempFile("validTest", null, tmpDirectory);
validFile.deleteOnExit();
files = new Location[] {
new Location(validFile.getAbsolutePath()),
new Location(invalidPath),
new Location(tmpDirectory),
new Location("http://loci.wisc.edu/software/bio-formats"),
new Location("http://openmicroscopy.org/software/bio-formats"),
new Location(hiddenFile)
};
exists = new boolean[] {
true, false, true, true, false, true
};
isDirectory = new boolean[] {
false, false, true, false, false, false
};
isHidden = new boolean[] {
false, false, false, false, false, true
};
mode = new String[] {
"rw", "", "rw", "r", "", "rw"
};
}
// -- Tests --
@Test
public void testReadWriteMode() {
for (int i=0; i<files.length; i++) {
String msg = files[i].getName();
assertEquals(msg, files[i].canRead(), mode[i].indexOf("r") != -1);
assertEquals(msg, files[i].canWrite(), mode[i].indexOf("w") != -1);
}
}
@Test
public void testAbsolute() {
for (Location file : files) {
assertEquals(file.getName(), file.getAbsolutePath(),
file.getAbsoluteFile().getAbsolutePath());
}
}
@Test
public void testExists() {
for (int i=0; i<files.length; i++) {
assertEquals(files[i].getName(), files[i].exists(), exists[i]);
}
}
@Test
public void testCanonical() throws IOException {
for (Location file : files) {
assertEquals(file.getName(), file.getCanonicalPath(),
file.getCanonicalFile().getAbsolutePath());
}
}
@Test
public void testParent() {
for (Location file : files) {
assertEquals(file.getName(), file.getParent(),
file.getParentFile().getAbsolutePath());
}
}
@Test
public void testIsDirectory() {
for (int i=0; i<files.length; i++) {
assertEquals(files[i].getName(), files[i].isDirectory(), isDirectory[i]);
}
}
@Test
public void testIsFile() {
for (int i=0; i<files.length; i++) {
assertEquals(files[i].getName(), files[i].isFile(),
!isDirectory[i] && exists[i]);
}
}
@Test
public void testIsHidden() {
for (int i=0; i<files.length; i++) {
assertEquals(files[i].getName(), files[i].isHidden(), isHidden[i]);
}
}
@Test
public void testListFiles() {
for (int i=0; i<files.length; i++) {
String[] completeList = files[i].list();
String[] unhiddenList = files[i].list(true);
Location[] fileList = files[i].listFiles();
if (!files[i].isDirectory()) {
assertEquals(files[i].getName(), completeList, null);
assertEquals(files[i].getName(), unhiddenList, null);
assertEquals(files[i].getName(), fileList, null);
continue;
}
assertEquals(files[i].getName(), completeList.length, fileList.length);
List<String> complete = Arrays.asList(completeList);
for (String child : unhiddenList) {
assertEquals(files[i].getName(), complete.contains(child), true);
assertEquals(files[i].getName(),
new Location(files[i], child).isHidden(), false);
}
for (int f=0; f<fileList.length; f++) {
assertEquals(files[i].getName(),
fileList[f].getName(), completeList[f]);
}
}
}
@Test
public void testToURL() throws IOException {
for (Location file : files) {
String path = file.getAbsolutePath();
if (path.indexOf(":
path = "file://" + path;
}
if (file.isDirectory() && !path.endsWith(File.separator)) {
path += File.separator;
}
assertEquals(file.getName(), file.toURL(), new URL(path));
}
}
@Test
public void testToString() {
for (Location file : files) {
assertEquals(file.getName(), file.toString(), file.getAbsolutePath());
}
}
}
|
package com.sapienter.jbilling.server.user;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import javax.naming.NamingException;
import com.sapienter.jbilling.server.util.audit.EventLogger;
import org.apache.log4j.Logger;
import com.sapienter.jbilling.common.SessionInternalError;
import com.sapienter.jbilling.server.invoice.InvoiceBL;
import com.sapienter.jbilling.server.system.event.EventManager;
import com.sapienter.jbilling.server.user.contact.db.ContactDAS;
import com.sapienter.jbilling.server.user.contact.db.ContactDTO;
import com.sapienter.jbilling.server.user.contact.db.ContactFieldDAS;
import com.sapienter.jbilling.server.user.contact.db.ContactFieldDTO;
import com.sapienter.jbilling.server.user.contact.db.ContactFieldTypeDAS;
import com.sapienter.jbilling.server.user.contact.db.ContactFieldTypeDTO;
import com.sapienter.jbilling.server.user.contact.db.ContactMapDAS;
import com.sapienter.jbilling.server.user.contact.db.ContactMapDTO;
import com.sapienter.jbilling.server.user.contact.db.ContactTypeDAS;
import com.sapienter.jbilling.server.user.contact.db.ContactTypeDTO;
import com.sapienter.jbilling.server.user.event.NewContactEvent;
import com.sapienter.jbilling.server.util.Constants;
import com.sapienter.jbilling.server.util.Context;
import com.sapienter.jbilling.server.util.db.JbillingTableDAS;
import java.util.ArrayList;
public class ContactBL {
private static final Logger LOG = Logger.getLogger(ContactBL.class);
// contact types in synch with the table contact_type
static public final Integer ENTITY = new Integer(1);
// private methods
private ContactDAS contactDas = null;
private ContactFieldDAS contactFieldDas = null;
private ContactDTO contact = null;
private Integer entityId = null;
private JbillingTableDAS jbDAS = null;
private EventLogger eLogger = null;
public ContactBL(Integer contactId)
throws NamingException {
init();
contact = contactDas.find(contactId);
}
public ContactBL() {
init();
}
public void set(Integer userId) {
contact = contactDas.findPrimaryContact(userId);
//LOG.debug("Found " + contact + " for " + userId);
setEntityFromUser(userId);
}
private void setEntityFromUser(Integer userId) {
// id the entity
UserBL user;
try {
user = new UserBL();
entityId = user.getEntityId(userId);
} catch (Exception e) {
LOG.error("Finding the entity", e);
}
}
public void set(Integer userId, Integer contactTypeId) {
contact = contactDas.findContact(userId, contactTypeId);
setEntityFromUser(userId);
}
public void setEntity(Integer entityId) {
this.entityId = entityId;
contact = contactDas.findEntityContact(entityId);
}
public boolean setInvoice(Integer invoiceId) {
boolean retValue = false;
contact = contactDas.findInvoiceContact(invoiceId);
InvoiceBL invoice = new InvoiceBL(invoiceId);
if (contact == null) {
set(invoice.getEntity().getBaseUser().getUserId());
} else {
entityId = invoice.getEntity().getBaseUser().getCompany().getId();
retValue = true;
}
return retValue;
}
public Integer getPrimaryType(Integer entityId) {
return new ContactTypeDAS().findPrimary(entityId).getId();
}
/**
* Rather confusing considering the previous method, but necessary
* to follow the convention
* @return
*/
public ContactDTO getEntity() {
return contact;
}
public ContactDTOEx getVoidDTO(Integer myEntityId) {
entityId = myEntityId;
ContactDTOEx retValue = new ContactDTOEx();
retValue.setFieldsTable(initializeFields());
return retValue;
}
public ContactDTOEx getDTO() {
ContactDTOEx retValue = new ContactDTOEx(
contact.getId(),
contact.getOrganizationName(),
contact.getAddress1(),
contact.getAddress2(),
contact.getCity(),
contact.getStateProvince(),
contact.getPostalCode(),
contact.getCountryCode(),
contact.getLastName(),
contact.getFirstName(),
contact.getInitial(),
contact.getTitle(),
contact.getPhoneCountryCode(),
contact.getPhoneAreaCode(),
contact.getPhoneNumber(),
contact.getFaxCountryCode(),
contact.getFaxAreaCode(),
contact.getFaxNumber(),
contact.getEmail(),
contact.getCreateDate(),
contact.getDeleted(),
contact.getInclude());
LOG.debug("ContactDTO: getting custom fields");
try {
retValue.setFieldsTable(initializeFields());
for (ContactFieldDTO field: contact.getFields()) {
// now find the field of this type
ContactFieldDTO dto = (ContactFieldDTO) retValue
.getFieldsTable().get(String.valueOf(field.getType().getId()));
if (field != null && dto != null) {
dto.setContent(field.getContent() == null ? "" : field.getContent());
dto.setId(field.getId());
}
}
} catch (Exception e) {
LOG.error("Error initializing fields", e);
}
LOG.debug("Returning dto with " + retValue.getFieldsTable().size() +
" fields");
return retValue;
}
public List<ContactDTOEx> getAll(Integer userId) {
List<ContactDTOEx> retValue = new ArrayList<ContactDTOEx>();
UserBL user = new UserBL(userId);
entityId = user.getEntityId(userId);
for (ContactTypeDTO type: user.getEntity().getEntity().getContactTypes()) {
contact = contactDas.findContact(userId, type.getId());
if (contact != null) {
ContactDTOEx dto = getDTO();
dto.setType(type.getId());
retValue.add(dto);
}
}
return retValue;
}
/**
* Create a Hashtable with the key beign the field type for the
* entity
* @return
*/
private Hashtable<String, ContactFieldDTO> initializeFields() {
// now go over the entity specific fields
Hashtable<String, ContactFieldDTO> fields = new Hashtable<String, ContactFieldDTO>();
EntityBL entity = new EntityBL(entityId);
for (ContactFieldTypeDTO field: entity.getEntity().getContactFieldTypes()) {
ContactFieldDTO fieldDto = new ContactFieldDTO();
fieldDto.setType(field);
fieldDto.setContent(new String()); // can't be null
// the key HAS to be a String if we want struts to be able to
// read the Hashtabe
fields.put(String.valueOf(field.getId()), fieldDto);
}
return fields;
}
private void init() {
contactDas = new ContactDAS();
contactFieldDas = new ContactFieldDAS();
jbDAS = (JbillingTableDAS) Context.getBean(Context.Name.JBILLING_TABLE_DAS);
eLogger = EventLogger.getInstance();
}
public Integer createPrimaryForUser(ContactDTOEx dto, Integer userId, Integer entityId)
throws SessionInternalError {
// find which type id is the primary for this entity
try {
Integer retValue;
ContactTypeDTO type = new ContactTypeDAS().findPrimary(entityId);
retValue = createForUser(dto, userId, type.getId());
// this is the primary contact, the only one with a user_id
// denormilized for performance
contact.setUserId(userId);
return retValue;
} catch (Exception e) {
throw new SessionInternalError(e);
}
}
/**
* Finds what is the next contact type and creates a new
* contact with it
* @param dto
*/
public boolean append(ContactDTOEx dto, Integer userId)
throws SessionInternalError {
UserBL user = new UserBL(userId);
for (ContactTypeDTO type: user.getEntity().getEntity().getContactTypes()) {
set(userId, type.getId());
if (contact == null) {
// this one is available
createForUser(dto, userId, type.getId());
return true;
}
}
return false; // no type was avaiable
}
public Integer createForUser(ContactDTOEx dto, Integer userId,
Integer typeId) throws SessionInternalError {
try {
return create(dto, Constants.TABLE_BASE_USER, userId, typeId);
} catch (Exception e) {
LOG.debug("Error creating contact for " +
"user " + userId);
throw new SessionInternalError(e);
}
}
public Integer createForInvoice(ContactDTOEx dto, Integer invoiceId) {
return create(dto, Constants.TABLE_INVOICE, invoiceId, new Integer(1));
}
/**
*
* @param dto
* @param table
* @param foreignId
* @param typeId Use 1 if it is not for a user (like and entity or invoice)
* @return
* @throws NamingException
*/
public Integer create(ContactDTOEx dto, String table,
Integer foreignId, Integer typeId) {
// first thing is to create the map to the user
ContactMapDTO map = new ContactMapDTO();
map.setJbillingTable(jbDAS.findByName(table));
map.setContactType(new ContactTypeDAS().find(typeId));
map.setForeignId(foreignId);
map = new ContactMapDAS().save(map);
// now the contact itself
dto.setCreateDate(new Date());
dto.setDeleted(0);
dto.setVersionNum(0);
dto.setId(0);
contact = contactDas.save(new ContactDTO(dto)); // it won't take the Ex
contact.setContactMap(map);
map.setContact(contact);
updateCreateFields(dto.getFieldsTable(), false);
LOG.debug("created " + contact);
// do an event if this is a user contact (invoices, companies, have
// contacts too)
if (table.equals(Constants.TABLE_BASE_USER)) {
NewContactEvent event = new NewContactEvent(contact, entityId);
EventManager.process(event);
eLogger.auditBySystem(entityId,
contact.getUserId(),
Constants.TABLE_CONTACT,
contact.getId(),
EventLogger.MODULE_USER_MAINTENANCE,
EventLogger.ROW_CREATED, null, null, null);
}
return contact.getId();
}
public void updatePrimaryForUser(ContactDTOEx dto, Integer userId) {
contact = contactDas.findPrimaryContact(userId);
update(dto);
}
public void updateForUser(ContactDTOEx dto, Integer userId,
Integer contactTypeId) throws SessionInternalError {
contact = contactDas.findContact(userId, contactTypeId);
if (contact != null) {
update(dto);
} else {
try {
createForUser(dto, userId, contactTypeId);
} catch (Exception e1) {
throw new SessionInternalError(e1);
}
}
}
private void update(ContactDTOEx dto) {
contact.setAddress1(dto.getAddress1());
contact.setAddress2(dto.getAddress2());
contact.setCity(dto.getCity());
contact.setCountryCode(dto.getCountryCode());
contact.setEmail(dto.getEmail());
contact.setFaxAreaCode(dto.getFaxAreaCode());
contact.setFaxCountryCode(dto.getFaxCountryCode());
contact.setFaxNumber(dto.getFaxNumber());
contact.setFirstName(dto.getFirstName());
contact.setInitial(dto.getInitial());
contact.setLastName(dto.getLastName());
contact.setOrganizationName(dto.getOrganizationName());
contact.setPhoneAreaCode(dto.getPhoneAreaCode());
contact.setPhoneCountryCode(dto.getPhoneCountryCode());
contact.setPhoneNumber(dto.getPhoneNumber());
contact.setPostalCode(dto.getPostalCode());
contact.setStateProvince(dto.getStateProvince());
contact.setTitle(dto.getTitle());
contact.setInclude(dto.getInclude());
if (entityId == null) {
setEntityFromUser(contact.getUserId());
}
NewContactEvent event = new NewContactEvent(contact, entityId);
EventManager.process(event);
eLogger.auditBySystem(entityId,
contact.getUserId(),
Constants.TABLE_CONTACT,
contact.getId(),
EventLogger.MODULE_USER_MAINTENANCE,
EventLogger.ROW_UPDATED, null, null, null);
updateCreateFields(dto.getFieldsTable(), true);
}
private void updateCreateFields(Hashtable fields, boolean isUpdate) {
if (fields == null) {
// if the fields are not there, do nothing
return;
}
// now the per-entity fields
for (Iterator it = fields.keySet().iterator(); it.hasNext();) {
String type = (String) it.next();
ContactFieldDTO field = (ContactFieldDTO) fields.get(type);
// we can't create or update custom fields with null value
if (field.getContent() == null) {
continue;
}
if (isUpdate) {
if (field.getId() != 0) {
contactFieldDas.find(field.getId()).setContent(field.getContent());
} else {
// it is un update, but don't know the field id
ContactFieldDTO aField = contactFieldDas.findByType(Integer.valueOf(type),
contact.getId());
if (aField != null) {
aField.setContent(field.getContent());
} else {
// not there yet. It's ok
createContactField(Integer.valueOf(type), field.getContent());
}
}
} else {
// create the new field
createContactField(Integer.valueOf(type), field.getContent());
}
}
}
private void createContactField(Integer type, String content) {
ContactFieldDTO newField = new ContactFieldDTO();
newField.setType(new ContactFieldTypeDAS().find(type));
newField.setContent(content);
newField.setContact(contact);
newField = new ContactFieldDAS().save(newField);
contact.getFields().add(newField);
}
public void delete() {
if (contact == null) return;
LOG.debug("Deleting contact " + contact.getId());
// delete the map first
new ContactMapDAS().delete(contact.getContactMap());
// now the fields
for(ContactFieldDTO field: contact.getFields()) {
new ContactFieldDAS().delete(field);
}
contact.getFields().clear();
// for the logger
Integer entityId = this.entityId;
Integer userId = contact.getUserId();
Integer contactId = contact.getId();
// the contact goes last
contactDas.delete(contact);
contact = null;
// log event
eLogger.auditBySystem(entityId,
userId,
Constants.TABLE_CONTACT,
contactId,
EventLogger.MODULE_USER_MAINTENANCE,
EventLogger.ROW_DELETED, null, null, null);
}
/**
* Sets this contact object to that on the parent, taking the children id
* as a parameter.
* @param customerId
*/
public void setFromChild(Integer userId) {
UserBL customer = new UserBL(userId);
set(customer.getEntity().getCustomer().getParent().getBaseUser().getUserId());
}
}
|
package kg.apc.jmeter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import kg.apc.charting.GraphPanelChart;
import kg.apc.cmd.UniversalRunner;
import kg.apc.jmeter.graphs.AbstractGraphPanelVisualizer;
import org.apache.jmeter.JMeter;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
/**
*
* @author undera
*/
public class PluginsCMDWorker {
private int graphWidth = 800;
private int graphHeight = 600;
public static final int EXPORT_PNG = 1;
public static final int EXPORT_CSV = 2;
private int exportMode = 0;
private String inputFile;
private String outputCSV;
private String outputPNG;
private String pluginType;
private static final Logger log = LoggingManager.getLoggerForClass();
private int aggregate = -1;
private int zeroing = -1;
private int preventOutliers = -1;
private int rowsLimit = -1;
private int forceY = -1;
private int lowCounts = -1;
private int granulation = -1;
private int relativeTimes = -1;
private int gradient = -1;
public PluginsCMDWorker() {
prepareJMeterEnv();
}
private void prepareJMeterEnv() {
if (JMeterUtils.getJMeterHome() != null) {
log.warn("JMeter env exists. No one should see this normally.");
return;
}
String homeDir = UniversalRunner.getJARLocation();
File dir = new File(homeDir);
while (dir != null && dir.exists()
&& dir.getName().equals("ext")
&& dir.getParentFile().getName().equals("lib")) {
dir = dir.getParentFile();
}
if (dir == null || !dir.exists()) {
throw new IllegalArgumentException("CMDRunner.jar must be placed in <jmeter>/lib/ext directory");
}
homeDir = dir.getParent();
log.debug("Creating jmeter env using JMeter home: " + homeDir);
JMeterUtils.setJMeterHome(homeDir);
initializeProperties();
}
/**
* Had to copy this method from JMeter class 'cause they provide no ways to
* re-use this code
*
* @see JMeter
*/
private void initializeProperties() {
JMeterUtils.loadJMeterProperties(JMeterUtils.getJMeterHome() + File.separator
+ "bin" + File.separator
+ "jmeter.properties");
JMeterUtils.initLogging();
JMeterUtils.initLocale();
Properties jmeterProps = JMeterUtils.getJMeterProperties();
// Add local JMeter properties, if the file is found
String userProp = JMeterUtils.getPropDefault("user.properties", "");
if (userProp.length() > 0) {
FileInputStream fis = null;
try {
File file = JMeterUtils.findFile(userProp);
if (file.canRead()) {
log.info("Loading user properties from: " + file.getCanonicalPath());
fis = new FileInputStream(file);
Properties tmp = new Properties();
tmp.load(fis);
jmeterProps.putAll(tmp);
LoggingManager.setLoggingLevels(tmp);//Do what would be done earlier
}
} catch (IOException e) {
log.warn("Error loading user property file: " + userProp, e);
} finally {
try {
fis.close();
} catch (IOException ex) {
log.warn("There was problem closing file stream", ex);
}
}
}
// Add local system properties, if the file is found
String sysProp = JMeterUtils.getPropDefault("system.properties", "");
if (sysProp.length() > 0) {
FileInputStream fis = null;
try {
File file = JMeterUtils.findFile(sysProp);
if (file.canRead()) {
log.info("Loading system properties from: " + file.getCanonicalPath());
fis = new FileInputStream(file);
System.getProperties().load(fis);
}
} catch (IOException e) {
log.warn("Error loading system property file: " + sysProp, e);
} finally {
try {
fis.close();
} catch (IOException ex) {
log.warn("There was problem closing file stream", ex);
}
}
}
}
public void addExportMode(int mode) {
exportMode |= mode;
}
public void setInputFile(String string) {
inputFile = string;
}
public void setOutputCSVFile(String string) {
outputCSV = string;
}
public void setOutputPNGFile(String string) {
outputPNG = string;
}
public void setPluginType(String string) {
pluginType = string;
}
private void checkParams() {
if (pluginType == null) {
throw new IllegalArgumentException("Missing plugin type specification");
}
if (exportMode == 0) {
throw new IllegalArgumentException("Missing any export specification");
}
if (inputFile == null) {
throw new IllegalArgumentException("Missing input JTL file specification");
}
if (!(new File(inputFile).exists())) {
throw new IllegalArgumentException("Cannot find specified JTL file: " + inputFile);
}
}
public void setGraphWidth(int i) {
graphWidth = i;
}
public void setGraphHeight(int i) {
graphHeight = i;
}
public int doJob() {
checkParams();
AbstractGraphPanelVisualizer gui = getGUIObject(pluginType);
setOptions(gui);
ResultCollector rc = new ResultCollector();
log.debug("Using JTL file: " + inputFile);
rc.setFilename(inputFile);
rc.setListener(gui);
rc.loadExistingFile();
// to handle issue 64 and since it must be cheap - set options again
setOptions(gui);
if ((exportMode & EXPORT_PNG) == EXPORT_PNG) {
try {
gui.getGraphPanelChart().saveGraphToPNG(new File(outputPNG), graphWidth, graphHeight);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
if ((exportMode & EXPORT_CSV) == EXPORT_CSV) {
try {
gui.getGraphPanelChart().saveGraphToCSV(new File(outputCSV));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
return 0;
}
private AbstractGraphPanelVisualizer getGUIObject(String pluginType) {
Class a;
try {
a = Class.forName(pluginType);
} catch (ClassNotFoundException ex) {
if (!pluginType.endsWith("Gui")) {
return getGUIObject(pluginType + "Gui");
}
if (!pluginType.startsWith("kg.apc.jmeter.vizualizers.")) {
return getGUIObject("kg.apc.jmeter.vizualizers." + pluginType);
}
throw new RuntimeException(ex);
}
try {
return (AbstractGraphPanelVisualizer) a.newInstance();
} catch (InstantiationException ex) {
throw new RuntimeException(ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
}
}
private void setOptions(AbstractGraphPanelVisualizer gui) {
GraphPanelChart graph = gui.getGraphPanelChart();
if (aggregate >= 0) {
gui.switchModel(aggregate > 0);
}
if (granulation >= 0) {
gui.setGranulation(granulation);
}
if (relativeTimes >= 0) {
graph.setUseRelativeTime(relativeTimes > 0);
}
if (gradient >= 0) {
graph.getChartSettings().setDrawGradient(gradient > 0);
}
if (zeroing >= 0) {
graph.getChartSettings().setDrawFinalZeroingLines(zeroing > 0);
}
if (rowsLimit >= 0) {
graph.getChartSettings().setMaxPointPerRow(rowsLimit);
}
if (preventOutliers >= 0) {
graph.getChartSettings().setPreventXAxisOverScaling(preventOutliers > 0);
}
if (lowCounts >= 0) {
graph.getChartSettings().setHideNonRepValLimit(lowCounts);
}
if (forceY >= 0) {
graph.getChartSettings().setForcedMaxY(forceY);
}
}
public void setAggregate(int logicValue) {
aggregate = logicValue;
}
public void setZeroing(int logicValue) {
zeroing = logicValue;
}
public void setPreventOutliers(int logicValue) {
preventOutliers = logicValue;
}
public void setRowsLimit(int parseInt) {
rowsLimit = parseInt;
}
public void setForceY(int parseInt) {
forceY = parseInt;
}
public void setHideLowCounts(int parseInt) {
lowCounts = parseInt;
}
public void setGranulation(int parseInt) {
granulation = parseInt;
}
public void setRelativeTimes(int logicValue) {
relativeTimes = logicValue;
}
public void setGradient(int logicValue) {
gradient = logicValue;
}
}
|
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.javaee.ExternalResourceManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.WatchedRootsProvider;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.PsiReference;
import com.intellij.psi.impl.source.xml.XmlEntityCache;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.*;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.io.HttpRequests;
import com.intellij.util.net.HttpConfigurable;
import com.intellij.util.net.IOExceptionDialog;
import com.intellij.xml.XmlBundle;
import com.intellij.xml.util.XmlUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
/**
* @author mike
*/
public class FetchExtResourceAction extends BaseExtResourceAction implements WatchedRootsProvider {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.intention.FetchDtdAction");
@NonNls private static final String HTML_MIME = "text/html";
@NonNls private static final String HTTP_PROTOCOL = "http:
@NonNls private static final String HTTPS_PROTOCOL = "https:
@NonNls private static final String FTP_PROTOCOL = "ftp:
@NonNls private static final String EXT_RESOURCES_FOLDER = "extResources";
private final boolean myForceResultIsValid;
public FetchExtResourceAction() {
myForceResultIsValid = false;
}
public FetchExtResourceAction(boolean forceResultIsValid) {
myForceResultIsValid = forceResultIsValid;
}
@Override
protected String getQuickFixKeyId() {
return "fetch.external.resource";
}
@Override
protected boolean isAcceptableUri(final String uri) {
return uri.startsWith(HTTP_PROTOCOL) || uri.startsWith(FTP_PROTOCOL) || uri.startsWith(HTTPS_PROTOCOL);
}
public static String findUrl(PsiFile file, int offset, String uri) {
final PsiElement currentElement = file.findElementAt(offset);
final XmlAttribute attribute = PsiTreeUtil.getParentOfType(currentElement, XmlAttribute.class);
if (attribute != null) {
final XmlTag tag = PsiTreeUtil.getParentOfType(currentElement, XmlTag.class);
if (tag != null) {
final String prefix = tag.getPrefixByNamespace(XmlUtil.XML_SCHEMA_INSTANCE_URI);
if (prefix != null) {
final String attrValue = tag.getAttributeValue(XmlUtil.SCHEMA_LOCATION_ATT, XmlUtil.XML_SCHEMA_INSTANCE_URI);
if (attrValue != null) {
final StringTokenizer tokenizer = new StringTokenizer(attrValue);
while (tokenizer.hasMoreElements()) {
if (uri.equals(tokenizer.nextToken())) {
if (!tokenizer.hasMoreElements()) return uri;
final String url = tokenizer.nextToken();
return url.startsWith(HTTP_PROTOCOL) ? url : uri;
}
if (!tokenizer.hasMoreElements()) return uri;
tokenizer.nextToken(); // skip file location
}
}
}
}
}
return uri;
}
@Override
@NotNull
public Set<String> getRootsToWatch() {
String path = getExternalResourcesPath();
Path file = checkExists(path);
return Collections.singleton(file.toAbsolutePath().toString());
}
@NotNull
private static Path checkExists(String dir) {
Path path = Paths.get(dir);
if (!path.toFile().isDirectory()) {
try {
Files.createDirectories(path);
}
catch (IOException e) {
LOG.warn("Unable to create: " + path, e);
}
}
return path;
}
static class FetchingResourceIOException extends IOException {
private final String url;
FetchingResourceIOException(Throwable cause, String url) {
initCause(cause);
this.url = url;
}
}
@Override
public boolean startInWriteAction() {
return false;
}
@Override
protected void doInvoke(@NotNull final PsiFile file, final int offset, @NotNull final String uri, final Editor editor)
throws IncorrectOperationException {
final String url = findUrl(file, offset, uri);
final Project project = file.getProject();
ProgressManager.getInstance().run(new Task.Backgroundable(project, XmlBundle.message("fetching.resource.title")) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
while (true) {
try {
HttpConfigurable.getInstance().prepareURL(url);
fetchDtd(project, uri, url, indicator);
ApplicationManager.getApplication().invokeLater(() -> DaemonCodeAnalyzer.getInstance(project).restart(file));
return;
}
catch (IOException ex) {
LOG.info(ex);
@SuppressWarnings("InstanceofCatchParameter")
String problemUrl = ex instanceof FetchingResourceIOException ? ((FetchingResourceIOException)ex).url : url;
String message = XmlBundle.message("error.fetching.title");
if (!url.equals(problemUrl)) {
message = XmlBundle.message("error.fetching.dependent.resource.title");
}
if (!IOExceptionDialog.showErrorDialog(message, XmlBundle.message("error.fetching.resource", problemUrl))) {
break; // cancel fetching
}
}
}
}
});
}
private void fetchDtd(final Project project, final String dtdUrl, final String url, final ProgressIndicator indicator) throws IOException {
final String extResourcesPath = getExternalResourcesPath();
final File extResources = new File(extResourcesPath);
LOG.assertTrue(extResources.mkdirs() || extResources.exists(), extResources);
final PsiManager psiManager = PsiManager.getInstance(project);
ApplicationManager.getApplication().invokeAndWait(() -> WriteAction.run(() -> {
final String path = FileUtil.toSystemIndependentName(extResources.getAbsolutePath());
final VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path);
LOG.assertTrue(vFile != null, path);
}));
final List<String> downloadedResources = new LinkedList<>();
final List<String> resourceUrls = new LinkedList<>();
final IOException[] nestedException = new IOException[1];
try {
final String resPath = fetchOneFile(indicator, url, project, extResourcesPath, null);
if (resPath == null) return;
resourceUrls.add(dtdUrl);
downloadedResources.add(resPath);
VirtualFile virtualFile = findFileByPath(resPath, dtdUrl);
Set<String> processedLinks = new HashSet<>();
Map<String, String> baseUrls = new HashMap<>();
VirtualFile contextFile = virtualFile;
Set<String> linksToProcess = new HashSet<>(extractEmbeddedFileReferences(virtualFile, null, psiManager, url));
while (!linksToProcess.isEmpty()) {
String s = linksToProcess.iterator().next();
linksToProcess.remove(s);
processedLinks.add(s);
final boolean absoluteUrl = s.startsWith(HTTP_PROTOCOL) || s.startsWith(HTTPS_PROTOCOL);
String resourceUrl;
if (absoluteUrl) {
resourceUrl = s;
}
else {
String baseUrl = baseUrls.get(s);
if (baseUrl == null) baseUrl = url;
resourceUrl = baseUrl.substring(0, baseUrl.lastIndexOf('/') + 1) + s;
}
String refName = s;
if (absoluteUrl) {
refName = Integer.toHexString(s.hashCode()) + "_" + refName.substring(refName.lastIndexOf('/') + 1);
}
String resourcePath;
try {
resourcePath = fetchOneFile(indicator, resourceUrl, project, extResourcesPath, refName);
}
catch (IOException e) {
nestedException[0] = new FetchingResourceIOException(e, resourceUrl);
break;
}
if (resourcePath == null) break;
virtualFile = findFileByPath(resourcePath, absoluteUrl ? s : null);
downloadedResources.add(resourcePath);
if (absoluteUrl) {
resourceUrls.add(s);
}
final Set<String> newLinks = extractEmbeddedFileReferences(virtualFile, contextFile, psiManager, resourceUrl);
for (String u : newLinks) {
baseUrls.put(u, resourceUrl);
if (!processedLinks.contains(u)) linksToProcess.add(u);
}
}
}
catch (IOException ex) {
nestedException[0] = ex;
}
if (nestedException[0] != null) {
cleanup(resourceUrls, downloadedResources);
throw nestedException[0];
}
}
private static VirtualFile findFileByPath(final String resPath, @Nullable final String dtdUrl) {
final Ref<VirtualFile> ref = new Ref<>();
ApplicationManager.getApplication().invokeAndWait(() -> ApplicationManager.getApplication().runWriteAction(() -> {
ref.set(LocalFileSystem.getInstance().refreshAndFindFileByPath(resPath.replace(File.separatorChar, '/')));
if (dtdUrl != null) {
ExternalResourceManager.getInstance().addResource(dtdUrl, resPath);
}
}));
return ref.get();
}
public static String getExternalResourcesPath() {
return PathManager.getSystemPath() + File.separator + EXT_RESOURCES_FOLDER;
}
private void cleanup(final List<String> resourceUrls, final List<String> downloadedResources) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
for (String resourcesUrl : resourceUrls) {
ExternalResourceManager.getInstance().removeResource(resourcesUrl);
}
for (String downloadedResource : downloadedResources) {
VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByIoFile(new File(downloadedResource));
if (virtualFile != null) {
try {
virtualFile.delete(this);
}
catch (IOException ignore) {
}
}
}
}
});
}
});
}
@Nullable
private String fetchOneFile(final ProgressIndicator indicator,
final String resourceUrl,
final Project project,
String extResourcesPath,
@Nullable String refname) throws IOException {
SwingUtilities.invokeLater(
() -> indicator.setText(XmlBundle.message("fetching.progress.indicator", resourceUrl))
);
FetchResult result = fetchData(project, resourceUrl, indicator);
if (result == null) return null;
if(!resultIsValid(project, indicator, resourceUrl, result)) {
return null;
}
String resPath = extResourcesPath + File.separatorChar;
if (refname != null) { // resource is known under ref.name so need to save it
resPath += refname;
int refNameSlashIndex = resPath.lastIndexOf('/');
if (refNameSlashIndex != -1) {
checkExists(resPath.substring(0, refNameSlashIndex));
}
}
else {
int slashIndex = resourceUrl.lastIndexOf('/');
resPath += Integer.toHexString(resourceUrl.hashCode()) + "_" + resourceUrl.substring(slashIndex + 1);
}
int lastDoPosInResourceUrl = resourceUrl.lastIndexOf('.');
if (lastDoPosInResourceUrl == -1 ||
FileTypeManager.getInstance().getFileTypeByExtension(resourceUrl.substring(lastDoPosInResourceUrl + 1)) == FileTypes.UNKNOWN) {
// remote url does not contain file with extension
final String extension =
result.contentType != null &&
result.contentType.contains(HTML_MIME) ? StdFileTypes.HTML.getDefaultExtension() : StdFileTypes.XML.getDefaultExtension();
resPath += "." + extension;
}
File res = new File(resPath);
FileUtil.writeToFile(res, result.bytes);
return resPath;
}
private boolean resultIsValid(final Project project, ProgressIndicator indicator, final String resourceUrl, FetchResult result) {
if (myForceResultIsValid) {
return true;
}
if (!ApplicationManager.getApplication().isUnitTestMode() &&
result.contentType != null &&
result.contentType.contains(HTML_MIME) &&
new String(result.bytes, StandardCharsets.UTF_8).contains("<html")) {
ApplicationManager.getApplication().invokeLater(() -> Messages.showMessageDialog(project,
XmlBundle.message("invalid.url.no.xml.file.at.location", resourceUrl),
XmlBundle.message("invalid.url.title"),
Messages.getErrorIcon()), indicator.getModalityState());
return false;
}
return true;
}
private static Set<String> extractEmbeddedFileReferences(XmlFile file, XmlFile context, final String url) {
if (context != null) {
XmlEntityCache.copyEntityCaches(file, context);
}
Set<String> result = new LinkedHashSet<>();
XmlUtil.processXmlElements(
file,
element -> {
if (element instanceof XmlEntityDecl) {
String candidateName = null;
for (PsiElement e = element.getLastChild(); e != null; e = e.getPrevSibling()) {
if (e instanceof XmlAttributeValue && candidateName == null) {
candidateName = e.getText().substring(1, e.getTextLength() - 1);
}
else if (e instanceof XmlToken &&
candidateName != null &&
(((XmlToken)e).getTokenType() == XmlTokenType.XML_DOCTYPE_PUBLIC ||
((XmlToken)e).getTokenType() == XmlTokenType.XML_DOCTYPE_SYSTEM
)
) {
result.add(candidateName);
break;
}
}
}
else if (element instanceof XmlTag) {
final XmlTag tag = (XmlTag)element;
String schemaLocation = tag.getAttributeValue(XmlUtil.SCHEMA_LOCATION_ATT);
if (schemaLocation != null) {
// processing xsd:import && xsd:include
final PsiReference[] references = tag.getAttribute(XmlUtil.SCHEMA_LOCATION_ATT).getValueElement().getReferences();
if (references.length > 0) {
String extension = FileUtilRt.getExtension(new File(url).getName());
final String namespace = tag.getAttributeValue("namespace");
if (namespace != null &&
schemaLocation.indexOf('/') == -1 &&
!extension.equals(FileUtilRt.getExtension(schemaLocation))) {
result.add(namespace.substring(0, namespace.lastIndexOf('/') + 1) + schemaLocation);
}
else {
result.add(schemaLocation);
}
}
}
else {
schemaLocation = tag.getAttributeValue(XmlUtil.SCHEMA_LOCATION_ATT, XmlUtil.XML_SCHEMA_INSTANCE_URI);
if (schemaLocation != null) {
final StringTokenizer tokenizer = new StringTokenizer(schemaLocation);
while (tokenizer.hasMoreTokens()) {
tokenizer.nextToken();
if (!tokenizer.hasMoreTokens()) break;
String location = tokenizer.nextToken();
result.add(location);
}
}
}
}
return true;
},
true,
true
);
return result;
}
public static Set<String> extractEmbeddedFileReferences(final VirtualFile vFile,
@Nullable final VirtualFile contextVFile,
final PsiManager psiManager,
final String url) {
return ReadAction.compute(() -> {
PsiFile file = psiManager.findFile(vFile);
if (file instanceof XmlFile) {
PsiFile contextFile = contextVFile != null ? psiManager.findFile(contextVFile) : null;
return extractEmbeddedFileReferences((XmlFile)file, contextFile instanceof XmlFile ? (XmlFile)contextFile : null, url);
}
return Collections.emptySet();
});
}
protected static class FetchResult {
byte[] bytes;
String contentType;
}
@Nullable
private static FetchResult fetchData(final Project project, final String dtdUrl, final ProgressIndicator indicator) throws IOException {
try {
return HttpRequests.request(dtdUrl).accept("text/xml,application/xml,text/html,*/*").connect(request -> {
FetchResult result = new FetchResult();
result.bytes = request.readBytes(indicator);
result.contentType = request.getConnection().getContentType();
return result;
});
}
catch (MalformedURLException e) {
if (!ApplicationManager.getApplication().isUnitTestMode()) {
ApplicationManager.getApplication().invokeLater(() -> Messages.showMessageDialog(project,
XmlBundle.message("invalid.url.message", dtdUrl),
XmlBundle.message("invalid.url.title"),
Messages.getErrorIcon()), indicator.getModalityState());
}
}
return null;
}
}
|
package javaslang.collection;
import javaslang.Lazy;
import javaslang.Tuple;
import javaslang.Tuple2;
import javaslang.control.None;
import javaslang.control.Option;
import javaslang.control.Some;
import java.io.Serializable;
import java.util.Objects;
public interface HashArrayMappedTrie<K, V> extends java.lang.Iterable<Tuple2<K, V>> {
static <K, V> HashArrayMappedTrie<K, V> empty() {
return EmptyNode.instance();
}
default boolean isEmpty() {
return this == EmptyNode.INSTANCE;
}
int size();
default Option<V> get(K key) {
return ((AbstractNode<K, V>) this).lookup(0, key);
}
default boolean containsKey(K key) {
return get(key).isDefined();
}
default HashArrayMappedTrie<K, V> put(K key, V value) {
return ((AbstractNode<K, V>) this).modify(0, key, new Some<>(value));
}
default HashArrayMappedTrie<K, V> remove(K key) {
return ((AbstractNode<K, V>) this).modify(0, key, None.instance());
}
// this is a javaslang.collection.Iterator!
@Override
Iterator<Tuple2<K, V>> iterator();
/**
* TODO: javadoc
*
* @param <K> Key type
* @param <V> Value type
*/
abstract class AbstractNode<K, V> implements HashArrayMappedTrie<K, V> {
static final int SIZE = 5;
static final int BUCKET_SIZE = 1 << SIZE;
static final int MAX_INDEX_NODE = BUCKET_SIZE / 2;
static final int MIN_ARRAY_NODE = BUCKET_SIZE / 4;
private static final int M1 = 0x55555555;
private static final int M2 = 0x33333333;
private static final int M4 = 0x0f0f0f0f;
private final transient Lazy<Integer> hashCode = Lazy.of(() -> Traversable.hash(this));
int bitCount(int x) {
x = x - ((x >> 1) & M1);
x = (x & M2) + ((x >> 2) & M2);
x = (x + (x >> 4)) & M4;
x = x + (x >> 8);
x = x + (x >> 16);
return x & 0x7f;
}
int hashFragment(int shift, int hash) {
return (hash >>> shift) & (BUCKET_SIZE - 1);
}
int toBitmap(int hash) {
return 1 << hash;
}
int fromBitmap(int bitmap, int bit) {
return bitCount(bitmap & (bit - 1));
}
static <K, V> int size(Iterable<AbstractNode<K, V>> subNodes) {
int size = 0;
for (AbstractNode<?, ?> subNode : subNodes) {
size += subNode.size();
}
return size;
}
abstract boolean isLeaf();
abstract Option<V> lookup(int shift, K key);
abstract AbstractNode<K, V> modify(int shift, K key, Option<V> value);
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof HashArrayMappedTrie) {
final Iterator<?> iter1 = this.iterator();
final Iterator<?> iter2 = ((HashArrayMappedTrie<?, ?>) o).iterator();
while (iter1.hasNext() && iter2.hasNext()) {
if (!Objects.equals(iter1.next(), iter2.next())) {
return false;
}
}
return !iter1.hasNext() && !iter2.hasNext();
} else {
return false;
}
}
@Override
public int hashCode() {
return hashCode.get();
}
@Override
public String toString() {
return List.ofAll(this).mkString(", ", "HashMap(", ")");
}
}
/**
* TODO: javadoc
*
* @param <K> Key type
* @param <V> Value type
*/
class EmptyNode<K, V> extends AbstractNode<K, V> implements Serializable {
private static final long serialVersionUID = 1L;
private static final EmptyNode<?, ?> INSTANCE = new EmptyNode<>();
private EmptyNode() {
}
@SuppressWarnings("unchecked")
static <K, V> EmptyNode<K, V> instance() {
return (EmptyNode<K, V>) INSTANCE;
}
@Override
Option<V> lookup(int shift, K key) {
return None.instance();
}
@Override
AbstractNode<K, V> modify(int shift, K key, Option<V> value) {
return value.isEmpty() ? this : new LeafNode<>(key.hashCode(), key, value.get());
}
@Override
boolean isLeaf() {
return true;
}
@Override
public int size() {
return 0;
}
@Override
public Iterator<Tuple2<K, V>> iterator() {
return Iterator.empty();
}
/**
* Instance control for object serialization.
*
* @return The singleton instance of EmptyNode.
* @see java.io.Serializable
*/
private Object readResolve() {
return INSTANCE;
}
}
/**
* TODO: javadoc
*
* @param <K> Key type
* @param <V> Value type
*/
class LeafNode<K, V> extends AbstractNode<K, V> implements Serializable {
private static final long serialVersionUID = 1L;
private final int hash;
private final List<Tuple2<K, V>> entries;
private LeafNode(int hash, K key, V value) {
this(hash, List.of(Tuple.of(key, value)));
}
private LeafNode(int hash, List<Tuple2<K, V>> entries) {
this.hash = hash;
this.entries = entries;
}
private AbstractNode<K, V> update(K key, Option<V> value) {
List<Tuple2<K, V>> filtered = entries.removeFirst(t -> t._1.equals(key));
if (value.isEmpty()) {
return filtered.isEmpty() ? EmptyNode.instance() : new LeafNode<>(hash, filtered);
} else {
return new LeafNode<>(hash, filtered.prepend(Tuple.of(key, value.get())));
}
}
@Override
Option<V> lookup(int shift, K key) {
if (hash != key.hashCode()) {
return None.instance();
}
return entries.findFirst(t -> t._1.equals(key)).map(t -> t._2);
}
@Override
AbstractNode<K, V> modify(int shift, K key, Option<V> value) {
if (key.hashCode() == hash) {
return update(key, value);
} else {
return value.isEmpty() ? this : mergeLeaves(shift, new LeafNode<>(key.hashCode(), key, value.get()));
}
}
AbstractNode<K, V> mergeLeaves(int shift, LeafNode<K, V> other) {
int h1 = this.hash;
int h2 = other.hash;
if (h1 == h2) {
return new LeafNode<>(h1, other.entries.foldLeft(entries, List::prepend));
}
int subH1 = hashFragment(shift, h1);
int subH2 = hashFragment(shift, h2);
return new IndexedNode<>(toBitmap(subH1) | toBitmap(subH2),
subH1 == subH2 ?
List.of(mergeLeaves(shift + SIZE, other))
: subH1 < subH2 ? List.of(this, other) : List.of(other, this));
}
@Override
boolean isLeaf() {
return true;
}
@Override
public int size() {
return entries.length();
}
@Override
public Iterator<Tuple2<K, V>> iterator() {
return entries.iterator();
}
}
/**
* TODO: javadoc
*
* @param <K> Key type
* @param <V> Value type
*/
class IndexedNode<K, V> extends AbstractNode<K, V> implements Serializable {
private static final long serialVersionUID = 1L;
private final int bitmap;
private final List<AbstractNode<K, V>> subNodes;
private IndexedNode(int bitmap, List<AbstractNode<K, V>> subNodes) {
this.bitmap = bitmap;
this.subNodes = subNodes;
}
@Override
Option<V> lookup(int shift, K key) {
int h = key.hashCode();
int frag = hashFragment(shift, h);
int bit = toBitmap(frag);
return ((bitmap & bit) != 0) ? subNodes.get(fromBitmap(bitmap, bit)).lookup(shift + SIZE, key) : None.instance();
}
@Override
AbstractNode<K, V> modify(int shift, K key, Option<V> value) {
int frag = hashFragment(shift, key.hashCode());
int bit = toBitmap(frag);
int indx = fromBitmap(bitmap, bit);
int mask = bitmap;
boolean exists = (mask & bit) != 0;
AbstractNode<K, V> child = exists ? subNodes.get(indx).modify(shift + SIZE, key, value)
: EmptyNode.<K, V> instance().modify(shift + SIZE, key, value);
boolean removed = exists && child.isEmpty();
boolean added = !exists && !child.isEmpty();
int newBitmap = removed ? mask & ~bit : added ? mask | bit : mask;
if (newBitmap == 0) {
return EmptyNode.instance();
} else if (removed) {
if (subNodes.length() <= 2 && subNodes.get(indx ^ 1).isLeaf()) {
return subNodes.get(indx ^ 1); // collapse
} else {
return new IndexedNode<>(newBitmap, subNodes.removeAt(indx));
}
} else if (added) {
if (subNodes.length() >= MAX_INDEX_NODE) {
return expand(frag, child, mask, subNodes);
} else {
return new IndexedNode<>(newBitmap, subNodes.insert(indx, child));
}
} else {
if (!exists) {
return this;
} else {
return new IndexedNode<>(newBitmap, subNodes.update(indx, child));
}
}
}
ArrayNode<K, V> expand(int frag, AbstractNode<K, V> child, int mask, List<AbstractNode<K, V>> subNodes) {
int bit = mask;
int count = 0;
List<AbstractNode<K, V>> sub = subNodes;
final Object[] arr = new Object[BUCKET_SIZE];
for (int i = 0; i < BUCKET_SIZE; i++) {
if ((bit & 1) != 0) {
arr[i] = sub.head();
sub = sub.tail();
count++;
} else if (i == frag) {
arr[i] = child;
count++;
} else {
arr[i] = EmptyNode.instance();
}
bit = bit >>> 1;
}
return new ArrayNode<>(count, Array.wrap(arr));
}
@Override
boolean isLeaf() {
return false;
}
@Override
public int size() {
return size(subNodes);
}
@Override
public Iterator<Tuple2<K, V>> iterator() {
return Iterator.ofIterables(subNodes);
}
}
/**
* TODO: javadoc
*
* @param <K> Key type
* @param <V> Value type
*/
class ArrayNode<K, V> extends AbstractNode<K, V> implements Serializable {
private static final long serialVersionUID = 1L;
private final Array<AbstractNode<K, V>> subNodes;
private final int count;
private ArrayNode(int count, Array<AbstractNode<K, V>> subNodes) {
this.subNodes = subNodes;
this.count = count;
}
@Override
Option<V> lookup(int shift, K key) {
int frag = hashFragment(shift, key.hashCode());
AbstractNode<K, V> child = subNodes.get(frag);
return child.lookup(shift + SIZE, key);
}
@Override
AbstractNode<K, V> modify(int shift, K key, Option<V> value) {
int frag = hashFragment(shift, key.hashCode());
AbstractNode<K, V> child = subNodes.get(frag);
AbstractNode<K, V> newChild = child.modify(shift + SIZE, key, value);
if (child.isEmpty() && !newChild.isEmpty()) {
return new ArrayNode<>(count + 1, subNodes.update(frag, newChild));
} else if (!child.isEmpty() && newChild.isEmpty()) {
if (count - 1 <= MIN_ARRAY_NODE) {
return pack(frag, subNodes);
} else {
return new ArrayNode<>(count - 1, subNodes.update(frag, EmptyNode.instance()));
}
} else {
return new ArrayNode<>(count, subNodes.update(frag, newChild));
}
}
IndexedNode<K, V> pack(int idx, Array<AbstractNode<K, V>> elements) {
List<AbstractNode<K, V>> arr = List.empty();
int bitmap = 0;
for (int i = BUCKET_SIZE - 1; i >= 0; i
AbstractNode<K, V> elem = elements.get(i);
if (i != idx && elem != empty()) {
arr = arr.prepend(elem);
bitmap = bitmap | (1 << i);
}
}
return new IndexedNode<>(bitmap, arr);
}
@Override
boolean isLeaf() {
return false;
}
@Override
public int size() {
return size(subNodes);
}
@Override
public Iterator<Tuple2<K, V>> iterator() {
return Iterator.ofIterables(subNodes);
}
}
}
|
package loci.common;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.joran.util.ConfigurationWatchListUtil;
/**
* A utility class with convenience methods for logback.
*/
public final class LogbackTools {
// -- Constructor --
private LogbackTools() { }
/**
* Checks whether logback has been enabled.
*
* This method will check if the root logger has been initialized via either
* a configuration file or a previous call to {@link #enableLogging()}. The
* logger context property will be used to discriminate the latter case from
* other initializations.
*
* @return {@code true} if logging was successfully enabled
*/
public static synchronized boolean isEnabled() {
Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
LoggerContext loggerContext = root.getLoggerContext();
return (ConfigurationWatchListUtil.getMainWatchURL(loggerContext) != null
|| (loggerContext.getProperty("caller") == "Bio-Formats"));
}
/**
* Sets the level of the root logger
*
* @param level A string indicating the desired level
* (i.e.: ALL, DEBUG, ERROR, FATAL, INFO, OFF, WARN).
*/
public static synchronized void setRootLevel(String level) {
Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.toLevel(level));
}
/**
* Initializes logback without an external configuration file.
*
* The logging initialization also sets a logger context property to record
* the initalization provenance.
*
* @return {@code true} if logging was successfully enabled
*/
public static synchronized boolean enableLogging() {
Logger root = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
LoggerContext context = root.getLoggerContext();
if (!root.iteratorForAppenders().hasNext()) {
context.reset();
context.putProperty("caller", "Bio-Formats");
PatternLayoutEncoder layout = new PatternLayoutEncoder();
layout.setContext(context);
layout.setPattern("%m%n");
layout.start();
ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<ILoggingEvent>();
appender.setContext(context);
appender.setEncoder(layout);
appender.start();
root.addAppender(appender);
}
else {
Appender defaultAppender = root.iteratorForAppenders().next();
if (defaultAppender instanceof ConsoleAppender) {
context.reset();
context.putProperty("caller", "Bio-Formats");
PatternLayoutEncoder layout = new PatternLayoutEncoder();
layout.setContext(context);
layout.setPattern("%m%n");
layout.start();
defaultAppender.setContext(context);
((ConsoleAppender) defaultAppender).setEncoder(layout);
defaultAppender.start();
root.addAppender(defaultAppender);
}
}
return true;
}
public static synchronized void enableIJLogging(boolean debug,
Appender<ILoggingEvent> appender) {
try {
Object logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
if (!(logger instanceof Logger)) return;
Logger root = (Logger) logger;
if (debug) {
root.setLevel(Level.DEBUG);
}
appender.setContext(root.getLoggerContext());
root.addAppender(appender);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package ucar.nc2.iosp.gini;
import ucar.nc2.*;
import ucar.nc2.constants.*;
import ucar.nc2.units.DateFormatter;
import ucar.unidata.geoloc.*;
import ucar.unidata.geoloc.projection.LambertConformal;
import ucar.unidata.geoloc.projection.Stereographic;
import ucar.unidata.geoloc.projection.Mercator;
import ucar.ma2.Array;
import ucar.ma2.DataType;
import ucar.unidata.util.Parameter;
import java.io.*;
import java.util.*;
import java.util.zip.Inflater;
import java.util.zip.DataFormatException;
import java.text.*;
import java.nio.*;
/**
* Netcdf header reading and writing for version 3 file format.
* This is used by Giniiosp.
*/
class Giniheader {
static private final int GINI_PIB_LEN = 21; // gini product identification block
static private final int GINI_PDB_LEN = 512; // gini product description block
static private final int GINI_HED_LEN = GINI_PDB_LEN + GINI_PIB_LEN; // gini product header
static private final double DEG_TO_RAD = 0.017453292;
private boolean debug = false;
private ucar.nc2.NetcdfFile ncfile;
static private org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Giniheader.class);
int dataStart = 0; // where the data starts
protected int Z_type = 0;
static public boolean isValidFile(ucar.unidata.io.RandomAccessFile raf) {
try {
return validatePIB(raf);
} catch (IOException e) {
return false;
}
}
static private int findWMOHeader(String pib) {
int pos = pib.indexOf("KNES");
if (pos == -1) pos = pib.indexOf("CHIZ");
if (pos != -1) { /* 'KNES' or 'CHIZ' found */
pos = pib.indexOf("\r\r\n"); /* <<<<< UPC mod 20030710 >>>>> */
if (pos != -1) { /* CR CR NL found */
pos = pos + 3;
}
} else {
pos = 0;
}
return pos;
}
static boolean validatePIB(ucar.unidata.io.RandomAccessFile raf) throws IOException {
int pos = 0;
raf.seek(pos);
// gini header process
String pib = raf.readString(GINI_PIB_LEN + GINI_HED_LEN);
return findWMOHeader(pib) != 0;
}
byte[] readPIB(ucar.unidata.io.RandomAccessFile raf) throws IOException {
int pos = 0;
raf.seek(pos);
// gini header process
byte[] b = new byte[GINI_PIB_LEN + GINI_HED_LEN];
byte[] buf = new byte[GINI_HED_LEN];
byte[] head = new byte[GINI_PDB_LEN];
raf.readFully(b);
String pib = new String(b, CDM.utf8Charset);
pos = findWMOHeader(pib);
dataStart = pos + GINI_PDB_LEN;
// Test the next two bytes to see if the image portion looks like
// it is zlib-compressed
byte[] b2 = new byte[] {b[pos], b[pos + 1]};
int pos1 = 0;
if (Giniiosp.isZlibHed(b2)) {
Z_type = 1;
Inflater inflater = new Inflater(false);
inflater.setInput(b, pos, GINI_HED_LEN);
try {
int resultLength = inflater.inflate(buf, 0, GINI_HED_LEN);
if (resultLength != GINI_HED_LEN) log.warn("GINI: Zlib inflated image header size error");
} catch (DataFormatException ex) {
log.error("ERROR on inflation " + ex.getMessage());
ex.printStackTrace();
throw new IOException(ex.getMessage());
}
int inflatedLen = GINI_HED_LEN - inflater.getRemaining();
String inf = new String(buf, CDM.utf8Charset);
pos1 = findWMOHeader(inf);
System.arraycopy(buf, pos1, head, 0, GINI_PDB_LEN);
dataStart = pos + inflatedLen;
} else {
System.arraycopy(b, pos, head, 0, GINI_PDB_LEN);
}
if (pos == 0 && pos1 == 0) {
throw new IOException("Error on Gini File");
}
return head;
}
void read(ucar.unidata.io.RandomAccessFile raf, ucar.nc2.NetcdfFile ncfile) throws IOException {
this.ncfile = ncfile;
int proj; /* projection type indicator */
/* 1 - Mercator */
/* 3 - Lambert Conf./Tangent Cone*/
/* 5 - Polar Stereographic */
int ent_id; /* GINI creation entity */
int sec_id; /* GINI sector ID */
int phys_elem; /* 1 - Visible, 2- 3.9IR, 3 - 6.7IR ..*/
int nx;
int ny;
int pole;
int gyear;
int gmonth;
int gday;
int ghour;
int gminute;
int gsecond;
double lonv; /* meridian parallel to y-axis */
double lon1 = 0.0, lon2 = 0.0;
double lat1 = 0.0, lat2 = 0.0;
double latt;
double imageScale = 0.0;
byte[] head = readPIB(raf);
ByteBuffer bos = ByteBuffer.wrap(head);
Attribute att = new Attribute(CDM.CONVENTIONS, "GRIB");
this.ncfile.addAttribute(null, att);
bos.position(0);
//sat_id = (int )( raf.readByte());
Byte nv = bos.get();
att = new Attribute("source_id", nv);
this.ncfile.addAttribute(null, att);
nv = bos.get();
ent_id = nv.intValue();
att = new Attribute("entity_id", nv);
this.ncfile.addAttribute(null, att);
nv = bos.get();
sec_id = nv.intValue();
att = new Attribute("sector_id", nv);
this.ncfile.addAttribute(null, att);
nv = bos.get();
phys_elem = nv.intValue();
att = new Attribute("phys_elem", nv);
this.ncfile.addAttribute(null, att);
bos.position(bos.position() + 4);
gyear = (int) (bos.get());
gyear += (gyear < 50) ? 2000 : 1900; //TODO: Find example where this hack is necessary
gmonth = (int) (bos.get());
gday = (int) (bos.get());
ghour = (int) (bos.get());
gminute = (int) (bos.get());
gsecond = (int) (bos.get());
DateFormat dformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
dformat.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MILLISECOND, 0);
cal.set(gyear, gmonth - 1, gday, ghour, gminute, gsecond);
cal.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
String dstring = dformat.format(cal.getTime());
Dimension dimT = new Dimension("time", 1, true, false, false);
ncfile.addDimension(null, dimT);
String timeCoordName = "time";
Variable taxis = new Variable(ncfile, null, null, timeCoordName);
taxis.setDataType(DataType.DOUBLE);
taxis.setDimensions("time");
taxis.addAttribute(new Attribute(CDM.LONG_NAME, "time since base date"));
taxis.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.Time.toString()));
double[] tdata = new double[1];
tdata[0] = cal.getTimeInMillis();
Array dataA = Array.factory(DataType.DOUBLE, new int[]{1}, tdata);
taxis.setCachedData(dataA, false);
DateFormatter formatter = new DateFormatter();
taxis.addAttribute(new Attribute(CDM.UNITS, "msecs since " + formatter.toDateTimeStringISO(new Date(0))));
ncfile.addVariable(null, taxis);
//att = new Attribute( "Time", dstring);
//this.ncfile.addAttribute(null, att);
this.ncfile.addAttribute(null, new Attribute("time_coverage_start", dstring));
this.ncfile.addAttribute(null, new Attribute("time_coverage_end", dstring));
bos.get(); /* skip a byte for hundreds of seconds */
nv = bos.get();
att = new Attribute("ProjIndex", nv);
this.ncfile.addAttribute(null, att);
proj = nv.intValue();
if (proj == 1) {
att = new Attribute("ProjName", "MERCATOR");
} else if (proj == 3) {
att = new Attribute("ProjName", "LAMBERT_CONFORNAL");
} else if (proj == 5) {
att = new Attribute("ProjName", "POLARSTEREOGRAPHIC");
}
this.ncfile.addAttribute(null, att);
/*
** Get grid dimensions
*/
nx = bos.getShort();
att = new Attribute("NX", nx);
this.ncfile.addAttribute(null, att);
ny = bos.getShort();
att = new Attribute("NY", ny);
this.ncfile.addAttribute(null, att);
ProjectionImpl projection = null;
double dxKm = 0.0, dyKm = 0.0, latin, lonProjectionOrigin;
switch (proj) {
case 1: /* Mercator */
/*
** Get the latitude and longitude of first and last "grid" points
*/
/* Latitude of first grid point */
lat1 = readScaledInt(bos);
att = new Attribute("Latitude0", lat1);
this.ncfile.addAttribute(null, att);
lon1 = readScaledInt(bos);
att = new Attribute("Longitude0", lon1);
this.ncfile.addAttribute(null, att);
/* Longitude of last grid point */
bos.get(); /* skip one byte */
lat2 = readScaledInt(bos);
att = new Attribute("LatitudeN", lat2);
this.ncfile.addAttribute(null, att);
lon2 = readScaledInt(bos);
att = new Attribute("LongitudeN", lon2);
this.ncfile.addAttribute(null, att);
/*
** Hack to catch incorrect sign of lon2 in header.
*/
// if ( lon1 > 0.0 && lon2 < 0.0 ) lon2 *= -1;
double lon_1 = lon1;
double lon_2 = lon2;
if (lon1 < 0) lon_1 += 360.0;
if (lon2 < 0) lon_2 += 360.0;
lonv = (lon_1 + lon_2) / 2.0;
if (lonv > 180.0) lonv -= 360.0;
if (lonv < -180.0) lonv += 360.0;
/*
** Get the "Latin" parameter. The ICD describes this value as:
** "Latin - The latitude(s) at which the Mercator projection cylinder
** intersects the earth." It should read that this is the latitude
** at which the image resolution is that defined by octet 41.
*/
bos.getInt(); /* skip 4 bytes */
bos.get(); /* skip 1 byte */
/* Latitude of proj cylinder intersects */
latin = readScaledInt(bos);
att = new Attribute("LatitudeX", latin);
this.ncfile.addAttribute(null, att);
projection = new Mercator(lonv, latin);
break;
case 3: /* Lambert Conformal */
case 5: /* Polar Stereographic */
/*
** Get lat/lon of first grid point
*/
lat1 = readScaledInt(bos);
lon1 = readScaledInt(bos);
/*
** Get Lov - the orientation of the grid; i.e. the east longitude of
** the meridian which is parallel to the y-aixs
*/
bos.get(); /* skip one byte */
lonv = readScaledInt(bos);
lonProjectionOrigin = lonv;
att = new Attribute("Lov", lonv);
this.ncfile.addAttribute(null, att);
/*
** Get distance increment of grid
*/
dxKm = readScaledInt(bos);
att = new Attribute("DxKm", dxKm);
this.ncfile.addAttribute(null, att);
dyKm = readScaledInt(bos);
att = new Attribute("DyKm", dyKm);
this.ncfile.addAttribute(null, att);
/* calculate the lat2 and lon2 */
if (proj == 5) {
latt = 60.0; /* Fixed for polar stereographic */
imageScale = (1. + Math.sin(DEG_TO_RAD * latt)) / 2.;
}
lat2 = lat1 + dyKm * (ny - 1) / 111.26;
/* Convert to east longitude */
if (lonv < 0.) lonv += 360.;
if (lon1 < 0.) lon1 += 360.;
lon2 = lon1 + dxKm * (nx - 1) / 111.26 * Math.cos(DEG_TO_RAD * lat1);
/*
** Convert to normal longitude to McIDAS convention
*/
lonv = (lonv > 180.) ? -(360. - lonv) : lonv;
lon1 = (lon1 > 180.) ? -(360. - lon1) : lon1;
lon2 = (lon2 > 180.) ? -(360. - lon2) : lon2;
/*
** Check high bit of octet for North or South projection center
*/
nv = bos.get();
pole = nv.intValue();
pole = (pole > 127) ? -1 : 1;
att = new Attribute("ProjCenter", pole);
this.ncfile.addAttribute(null, att);
bos.get(); /* skip one byte for Scanning mode */
latin = readScaledInt(bos);
att = new Attribute("Latin", latin);
this.ncfile.addAttribute(null, att);
if (proj == 3)
projection = new LambertConformal(latin, lonProjectionOrigin, latin, latin);
else // (proj == 5)
projection = new Stereographic(90.0, lonv, imageScale);
break;
default: {
System.out.println();
throw new IllegalStateException("unimplemented projection " + proj);
}
}
this.ncfile.addAttribute(null, new Attribute("title", gini_GetEntityID(ent_id)));
this.ncfile.addAttribute(null, new Attribute("summary", getPhysElemSummary(phys_elem, ent_id)));
this.ncfile.addAttribute(null, new Attribute("id", gini_GetSectorID(sec_id)));
this.ncfile.addAttribute(null, new Attribute("keywords_vocabulary", gini_GetPhysElemID(phys_elem, ent_id)));
this.ncfile.addAttribute(null, new Attribute("cdm_data_type", FeatureType.GRID.toString()));
this.ncfile.addAttribute(null, new Attribute(CF.FEATURE_TYPE, FeatureType.GRID.toString()));
this.ncfile.addAttribute(null, new Attribute("standard_name_vocabulary", getPhysElemLongName(phys_elem, ent_id)));
this.ncfile.addAttribute(null, new Attribute("creator_name", "UNIDATA"));
this.ncfile.addAttribute(null, new Attribute("creator_url", "http:
this.ncfile.addAttribute(null, new Attribute("naming_authority", "UCAR/UOP"));
this.ncfile.addAttribute(null, new Attribute("geospatial_lat_min", lat1));
this.ncfile.addAttribute(null, new Attribute("geospatial_lat_max", lat2));
this.ncfile.addAttribute(null, new Attribute("geospatial_lon_min", lon1));
this.ncfile.addAttribute(null, new Attribute("geospatial_lon_max", lon2));
//this.ncfile.addAttribute(null, new Attribute("geospatial_vertical_min", new Float(0.0)));
//this.ncfile.addAttribute(null, new Attribute("geospatial_vertical_max", new Float(0.0)));
/** Get the image resolution.
*/
bos.position(41); /* jump to 42 bytes of PDB */
nv = bos.get(); /* Res [km] */
att = new Attribute("imageResolution", nv);
this.ncfile.addAttribute(null, att);
// if(proj == 1)
// dyKm = nv.doubleValue()/dyKm;
/* compression flag 43 byte */
nv = bos.get(); /* Res [km] */
att = new Attribute("compressionFlag", nv);
this.ncfile.addAttribute(null, att);
if (DataType.unsignedByteToShort(nv) == 128) {
Z_type = 2;
//out.println( "ReadNexrInfo:: This is a Z file ");
}
/* new 47 - 60 */
bos.position(46);
nv = bos.get(); /* Cal indicator */
int navcal = DataType.unsignedByteToShort(nv);
int[] calcods = null;
if (navcal == 128)
calcods = getCalibrationInfo(bos, phys_elem, ent_id);
// only one data variable per gini file
String vname = gini_GetPhysElemID(phys_elem, ent_id);
Variable var = new Variable(ncfile, ncfile.getRootGroup(), null, vname);
var.addAttribute(new Attribute(CDM.LONG_NAME, getPhysElemLongName(phys_elem, ent_id)));
var.addAttribute(new Attribute(CDM.UNITS, getPhysElemUnits(phys_elem, ent_id)));
// var.addAttribute( new Attribute(CDM.MISSING_VALUE, new Byte((byte) 0))); // ??
// get dimensions
List<Dimension> dims = new ArrayList<>();
Dimension dimX = new Dimension("x", nx, true, false, false);
Dimension dimY = new Dimension("y", ny, true, false, false);
ncfile.addDimension(null, dimY);
ncfile.addDimension(null, dimX);
dims.add(dimT);
dims.add(dimY);
dims.add(dimX);
var.setDimensions(dims);
// size and beginning data position in file
long begin = dataStart;
if (debug) log.warn(" name= " + vname + " velems=" + var.getSize() + " begin= " + begin + "\n");
if (navcal == 128) {
var.setDataType(DataType.FLOAT);
var.setSPobject(new Vinfo(begin, nx, ny, calcods));
/* var.addAttribute(new Attribute("_Unsigned", "true"));
int numer = calcods[0] - calcods[1];
int denom = calcods[2] - calcods[3];
float a = (numer*1.f) / (1.f*denom);
float b = calcods[0] - a * calcods[2];
var.addAttribute( new Attribute("scale_factor", new Float(a)));
var.addAttribute( new Attribute("add_offset", new Float(b)));
*/
} else {
var.setDataType(DataType.UBYTE);
//var.addAttribute(new Attribute(CDM.UNSIGNED, "true"));
// var.addAttribute(new Attribute("_missing_value", new Short((short)255)));
var.addAttribute(new Attribute(CDM.SCALE_FACTOR, (short) (1)));
var.addAttribute(new Attribute(CDM.ADD_OFFSET, (short) (0)));
var.setSPobject(new Vinfo(begin, nx, ny));
}
String coordinates = "x y time";
var.addAttribute(new Attribute(_Coordinate.Axes, coordinates));
ncfile.addVariable(null, var);
// add coordinate information. we need:
// nx, ny, dx, dy,
// latin, lov, la1, lo1
// we have to project in order to find the origin
ProjectionPoint start = projection.latLonToProj(new LatLonPointImpl(lat1, lon1));
if (debug) log.warn("start at proj coord " + start);
double startx = start.getX();
double starty = start.getY();
// create coordinate variables
Variable xaxis = new Variable(ncfile, null, null, "x");
xaxis.setDataType(DataType.DOUBLE);
xaxis.setDimensions("x");
xaxis.addAttribute(new Attribute(CDM.LONG_NAME, "projection x coordinate"));
xaxis.addAttribute(new Attribute(CDM.UNITS, "km"));
xaxis.addAttribute(new Attribute(_Coordinate.AxisType, "GeoX"));
double[] data = new double[nx];
if (proj == 1) {
double lon_1 = lon1;
double lon_2 = lon2;
if (lon1 < 0) lon_1 += 360.0;
if (lon2 < 0) lon_2 += 360.0;
double dx = (lon_2 - lon_1) / (nx - 1);
for (int i = 0; i < data.length; i++) {
double ln = lon1 + i * dx;
ProjectionPoint pt = projection.latLonToProj(new LatLonPointImpl(lat1, ln));
data[i] = pt.getX(); // startx + i*dx;
}
} else {
for (int i = 0; i < data.length; i++)
data[i] = startx + i * dxKm;
}
dataA = Array.factory(DataType.DOUBLE, new int[]{nx}, data);
xaxis.setCachedData(dataA, false);
ncfile.addVariable(null, xaxis);
Variable yaxis = new Variable(ncfile, null, null, "y");
yaxis.setDataType(DataType.DOUBLE);
yaxis.setDimensions("y");
yaxis.addAttribute(new Attribute(CDM.LONG_NAME, "projection y coordinate"));
yaxis.addAttribute(new Attribute(CDM.UNITS, "km"));
yaxis.addAttribute(new Attribute(_Coordinate.AxisType, "GeoY"));
data = new double[ny];
double endy = starty + dyKm * (data.length - 1); // apparently lat1,lon1 is always the lower ledt, but data is upper left
if (proj == 1) {
double dy = (lat2 - lat1) / (ny - 1);
for (int i = 0; i < data.length; i++) {
double la = lat2 - i * dy;
ProjectionPoint pt = projection.latLonToProj(new LatLonPointImpl(la, lon1));
data[i] = pt.getY(); //endyy - i*dy;
}
} else {
for (int i = 0; i < data.length; i++)
data[i] = endy - i * dyKm;
}
dataA = Array.factory(DataType.DOUBLE, new int[]{ny}, data);
yaxis.setCachedData(dataA, false);
ncfile.addVariable(null, yaxis);
// coordinate transform variable
Variable ct = new Variable(ncfile, null, null, projection.getClassName());
ct.setDataType(DataType.CHAR);
ct.setDimensions("");
for (Parameter p : projection.getProjectionParameters()) {
ct.addAttribute(new Attribute(p));
}
ct.addAttribute(new Attribute(_Coordinate.TransformType, "Projection"));
ct.addAttribute(new Attribute(_Coordinate.Axes, "x y "));
// fake data
dataA = Array.factory(DataType.CHAR, new int[]{});
dataA.setChar(dataA.getIndex(), ' ');
ct.setCachedData(dataA, false);
ncfile.addVariable(null, ct);
ncfile.addAttribute(null, new Attribute(CDM.CONVENTIONS, _Coordinate.Convention));
// finish
ncfile.finish();
}
int[] getCalibrationInfo(ByteBuffer bos, int phys_elem, int ent_id) {
bos.position(46);
byte nv = bos.get(); /* Cal indicator */
int navcal = DataType.unsignedByteToShort(nv);
int[] calcods = null;
if (navcal == 128) { /* Unidata Cal block found; unpack values */
int scale = 10000;
int jscale = 100000000;
byte[] unsb = new byte[8];
bos.get(unsb);
String unitStr = new String(unsb, CDM.utf8Charset).toUpperCase();
String iname;
String iunit;
bos.position(55);
nv = bos.get();
int calcod = DataType.unsignedByteToShort(nv);
if (unitStr.contains("INCH")) {
iname = "RAIN";
iunit = "IN ";
} else if (unitStr.contains("dBz")) {
iname = "ECHO";
iunit = "dBz ";
} else if (unitStr.contains("KFT")) {
iname = "TOPS";
iunit = "KFT ";
} else if (unitStr.contains("KG/M")) {
iname = "VIL ";
iunit = "mm ";
} else {
iname = " ";
iunit = " ";
}
if (calcod > 0) {
calcods = new int[5 * calcod + 1];
calcods[0] = calcod;
for (int i = 0; i < calcod; i++) {
bos.position(56 + i * 16);
int minb = bos.getInt() / 10000; /* min brightness values */
int maxb = bos.getInt() / 10000; /* max brightness values */
int mind = bos.getInt(); /* min data values */
int maxd = bos.getInt(); /* max data values */
int idscal = 1;
while (mind % idscal == 0 && maxd % idscal == 0) {
idscal *= 10;
}
idscal /= 10;
if (idscal < jscale) jscale = idscal;
calcods[1 + i * 5] = mind;
calcods[2 + i * 5] = maxd;
calcods[3 + i * 5] = minb;
calcods[4 + i * 5] = maxb;
calcods[5 + i * 5] = 0;
}
if (jscale > scale) jscale = scale;
scale /= jscale;
if (gini_GetPhysElemID(phys_elem, ent_id).contains("Precipitation")) {
if (scale < 100) {
jscale /= (100 / scale);
scale = 100;
}
}
for (int i = 0; i < calcod; i++) {
calcods[1 + i * 5] /= jscale;
calcods[2 + i * 5] /= jscale;
calcods[5 + i * 5] = scale;
}
}
}
return calcods;
}
int gini_GetCompressType() {
return Z_type;
}
// Return the string of entity ID for the GINI image file
String gini_GetSectorID(int ent_id) {
String name;
/* GINI channel ID */
switch (ent_id) {
case 0:
name = "Northern Hemisphere Composite";
break;
case 1:
name = "East CONUS";
break;
case 2:
name = "West CONUS";
break;
case 3:
name = "Alaska Regional";
break;
case 4:
name = "Alaska National";
break;
case 5:
name = "Hawaii Regional";
break;
case 6:
name = "Hawaii National";
break;
case 7:
name = "Puerto Rico Regional";
break;
case 8:
name = "Puerto Rico National";
break;
case 9:
name = "Supernational";
break;
case 10:
name = "NH Composite - Meteosat/GOES E/ GOES W/GMS";
break;
default:
name = "Unknown-ID";
}
return name;
}
// Return the channel ID for the GINI image file
String gini_GetEntityID(int ent_id) {
String name;
switch (ent_id) {
case 99:
name = "RADAR-MOSIAC Composite Image";
break;
case 6:
name = "Composite";
break;
case 7:
name = "DMSP satellite Image";
break;
case 8:
name = "GMS satellite Image";
break;
case 9: /* METEOSAT (using 6) */
name = "METEOSAT satellite Image";
break;
case 10: /* GOES-7 */
name = "GOES-7 satellite Image";
break;
case 11: /* GOES-8 */
name = "GOES-8 satellite Image";
break;
case 12: /* GOES-9 */
name = "GOES-9 satellite Image";
break;
case 13: /* GOES-10 */
name = "GOES-10 satellite Image";
break;
case 14: /* GOES-11 */
name = "GOES-11 satellite Image";
break;
case 15: /* GOES-12 */
name = "GOES-12 satellite Image";
break;
case 16: /* GOES-13 */
name = "GOES-13 satellite Image";
break;
default:
name = "Unknown";
}
return name;
}
// Return the channel ID for the GINI image file
String gini_GetPhysElemID(int phys_elem, int ent_id) {
String name;
switch (phys_elem) {
case 1:
name = "VIS";
break;
case 3:
name = "IR_WV";
break;
case 2:
case 4:
case 5:
case 6:
case 7:
name = "IR";
break;
case 13:
name = "LI";
break;
case 14:
name = "PW";
break;
case 15:
name = "SFC_T";
break;
case 16:
name = "LI";
break;
case 17:
name = "PW";
break;
case 18:
name = "SFC_T";
break;
case 19:
name = "CAPE";
break;
case 20:
name = "T";
break;
case 21:
name = "WINDEX";
break;
case 22:
name = "DMPI";
break;
case 23:
name = "MDPI";
break;
case 25:
if (ent_id == 99)
name = "Reflectivity";
else
name = "Volcano_imagery";
break;
case 27:
if (ent_id == 99)
name = "Reflectivity";
else
name = "CTP";
break;
case 28:
if (ent_id == 99)
name = "Reflectivity";
else
name = "Cloud_Amount";
break;
case 26:
name = "EchoTops";
break;
case 29:
name = "VIL";
break;
case 30:
case 31:
name = "Precipitation";
break;
case 40:
case 41:
case 42:
case 43:
case 44:
case 45:
case 46:
case 47:
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
case 58:
name = "sounder_imagery";
break;
case 59:
name = "VIS_sounder";
break;
default:
name = "Unknown";
}
return name;
}
String getPhysElemUnits(int phys_elem, int ent_id) {
switch (phys_elem) {
case 1:
case 3:
case 2:
case 4:
case 5:
case 6:
case 7:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 20:
case 21:
case 22:
case 23:
case 29:
case 43:
case 48:
case 50:
case 51:
case 52:
case 55:
case 57:
case 59:
return "N/A";
case 26:
return "K FT";
case 25:
if (ent_id == 99)
return "dBz";
else
return "N/A";
case 27:
if (ent_id == 99)
return "dBz";
else
return "N/A";
case 28:
if (ent_id == 99)
return "dBz";
else
return "N/A";
case 30:
return "IN";
case 31:
return "IN";
default:
return "Unknown";
}
}
// Return the channel ID for the GINI image file
String getPhysElemLongName(int phys_elem, int ent_id) {
switch (phys_elem) {
case 1:
return "Imager Visible";
case 2:
return "Imager 3.9 micron IR";
case 3:
return "Imager 6.7/6.5 micron IR (WV)";
case 4:
return "Imager 11 micron IR";
case 5:
return "Imager 12 micron IR";
case 6:
return "Imager 13 micron IR";
case 7:
return "Imager 1.3 micron IR";
case 13:
return "Lifted Index LI";
case 14:
return "Precipitable Water PW";
case 15:
return "Surface Skin Temperature";
case 16:
return "Lifted Index LI";
case 17:
return "Precipitable Water PW";
case 18:
return "Surface Skin Temperature";
case 19:
return "Convective Available Potential Energy";
case 20:
return "land-sea Temperature";
case 21:
return "Wind Index";
case 22:
return "Dry Microburst Potential Index";
case 23:
return "Microburst Potential Index";
case 25:
if (ent_id == 99)
return "2 km National 248 nm Base Composite Reflectivity";
else
return "Volcano_imagery";
case 26:
return "4 km National Echo Tops";
case 27:
if (ent_id == 99)
return "1 km National Base Reflectivity Composite (Unidata)";
else
return "Cloud Top Pressure or Height";
case 28:
if (ent_id == 99)
return "1 km National Composite Reflectivity (Unidata)";
else
return "Cloud Amount";
case 29:
return "4 km National Vertically Integrated Liquid Water";
case 30:
return "2 km National 1-hour Precipitation (Unidata)";
case 31:
return "4 km National Storm Total Precipitation (Unidata)";
case 43:
return "14.06 micron sounder image";
case 48:
return "11.03 micron sounder image";
case 50:
return "7.43 micron sounder image";
case 51:
return "7.02 micron sounder image";
case 52:
return "6.51 micron sounder image";
case 55:
return "4.45 micron sounder image";
case 57:
return "3.98 micron sounder image";
case 59:
return "VIS sounder image ";
default:
return "unknown physical element " + phys_elem;
}
}
String getPhysElemSummary(int phys_elem, int ent_id) {
switch (phys_elem) {
case 1:
return "Satellite Product Imager Visible";
case 2:
return "Satellite Product Imager 3.9 micron IR";
case 3:
return "Satellite Product Imager 6.7/6.5 micron IR (WV)";
case 4:
return "Satellite Product Imager 11 micron IR";
case 5:
return "Satellite Product Imager 12 micron IR";
case 6:
return "Satellite Product Imager 13 micron IR";
case 7:
return "Satellite Product Imager 1.3 micron IR";
case 13:
return "Imager Based Derived Lifted Index LI";
case 14:
return "Imager Based Derived Precipitable Water PW";
case 15:
return "Imager Based Derived Surface Skin Temperature";
case 16:
return "Sounder Based Derived Lifted Index LI";
case 17:
return "Sounder Based Derived Precipitable Water PW";
case 18:
return "Sounder Based Derived Surface Skin Temperature";
case 19:
return "Derived Convective Available Potential Energy CAPE";
case 20:
return "Derived land-sea Temperature";
case 21:
return "Derived Wind Index WINDEX";
case 22:
return "Derived Dry Microburst Potential Index DMPI";
case 23:
return "Derived Microburst Day Potential Index MDPI";
case 43:
return "Satellite Product 14.06 micron sounder image";
case 48:
return "Satellite Product 11.03 micron sounder image";
case 50:
return "Satellite Product 7.43 micron sounder image";
case 51:
return "Satellite Product 7.02 micron sounder image";
case 52:
return "Satellite Product 6.51 micron sounder image";
case 55:
return "Satellite Product 4.45 micron sounder image";
case 57:
return "Satellite Product 3.98 micron sounder image";
case 59:
return "Satellite Product VIS sounder visible image ";
case 25:
if (ent_id == 99)
return "Nexrad Level 3 National 248 nm Base Composite Reflectivity at Resolution 2 km";
else
return "Satellite Derived Volcano_imagery";
case 26:
return "Nexrad Level 3 National Echo Tops at Resolution 4 km";
case 29:
return "Nexrad Level 3 National Vertically Integrated Liquid Water at Resolution 4 km";
case 28:
if (ent_id == 99)
return "Nexrad Level 3 National 248 nm Base Composite Reflectivity at Resolution 2 km";
else
return "Gridded Cloud Amount";
case 27:
if (ent_id == 99)
return "Nexrad Level 3 Base Reflectivity National Composition at Resolution 1 km";
else
return "Gridded Cloud Top Pressure or Height";
case 30:
return "Nexrad Level 3 1 hour precipitation National Composition at Resolution 2 km";
case 31:
return "Nexrad Level 3 total precipitation National Composition at Resolution 4 km";
default:
return "unknown";
}
}
// Read a scaled, 3-byte integer from file and convert to double
private double readScaledInt(ByteBuffer buf) {
// Get the first two bytes
short s1 = buf.getShort();
// And the last one as unsigned
short s2 = DataType.unsignedByteToShort(buf.get());
// Get the sign bit, converting from 0 or 2 to +/- 1.
int posneg = 1 - ((s1 & 0x8000) >> 14);
// Combine the first two bytes (without sign bit) with the last byte.
// Multiply by proper factor for +/-
int nn = (((s1 & 0x7FFF) << 8) | s2) * posneg;
return (double) nn / 10000.0;
}
// variable info for reading/writing
static class Vinfo {
long begin; // offset of start of data from start of file
int nx;
int ny;
int[] levels;
Vinfo(long begin, int x, int y) {
this.begin = begin;
this.nx = x;
this.ny = y;
}
Vinfo(long begin, int x, int y, int[] levels) {
this.begin = begin;
this.nx = x;
this.ny = y;
this.levels = levels;
}
}
}
|
package org.xwiki.test.ui;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriBuilder;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.EntityReferenceResolver;
import org.xwiki.model.reference.EntityReferenceSerializer;
import org.xwiki.rest.model.jaxb.ObjectFactory;
import org.xwiki.rest.model.jaxb.Xwiki;
import org.xwiki.test.integration.XWikiExecutor;
import org.xwiki.test.ui.po.ViewPage;
import org.xwiki.test.ui.po.editor.ClassEditPage;
import org.xwiki.test.ui.po.editor.ObjectEditPage;
/**
* Helper methods for testing, not related to a specific Page Object. Also made available to tests classes.
*
* @version $Id$
* @since 3.2M3
*/
public class TestUtils
{
/**
* @since 5.0M2
*/
public static final UsernamePasswordCredentials ADMIN_CREDENTIALS = new UsernamePasswordCredentials("Admin",
"admin");
/**
* @since 5.1M1
*/
public static final UsernamePasswordCredentials SUPER_ADMIN_CREDENTIALS = new UsernamePasswordCredentials(
"superadmin", "pass");
/**
* @since 5.0M2
*/
public static final String BASE_URL = XWikiExecutor.URL + ":" + XWikiExecutor.DEFAULT_PORT + "/xwiki/";
/**
* @since 5.0M2
*/
public static final String BASE_BIN_URL = BASE_URL + "bin/";
/**
* @since 5.0M2
*/
public static final String BASE_REST_URL = BASE_URL + "rest/";
private static PersistentTestContext context;
private static ComponentManager componentManager;
private static EntityReferenceResolver<String> referenceResolver;
private static EntityReferenceSerializer<String> referenceSerializer;
/**
* Used to convert Java object into its REST XML representation.
*/
private static Marshaller marshaller;
/**
* Used to convert REST request XML result into its Java representation.
*/
private static Unmarshaller unmarshaller;
/**
* Used to create REST Java resources.
*/
private static ObjectFactory objectFactory;
{
{
try {
// Initialize REST related tools
JAXBContext context =
JAXBContext.newInstance("org.xwiki.rest.model.jaxb"
+ ":org.xwiki.extension.repository.xwiki.model.jaxb");
marshaller = context.createMarshaller();
unmarshaller = context.createUnmarshaller();
objectFactory = new ObjectFactory();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
}
/** Cached secret token. TODO cache for each user. */
private String secretToken = null;
private HttpClient adminHTTPClient;
public TestUtils()
{
this.adminHTTPClient = new HttpClient();
this.adminHTTPClient.getState().setCredentials(AuthScope.ANY, SUPER_ADMIN_CREDENTIALS);
this.adminHTTPClient.getParams().setAuthenticationPreemptive(true);
}
/** Used so that AllTests can set the persistent test context. */
public static void setContext(PersistentTestContext context)
{
TestUtils.context = context;
}
public static void initializeComponent(ComponentManager componentManager) throws Exception
{
TestUtils.componentManager = componentManager;
TestUtils.referenceResolver = TestUtils.componentManager.getInstance(EntityReferenceResolver.TYPE_STRING);
TestUtils.referenceSerializer = TestUtils.componentManager.getInstance(EntityReferenceSerializer.TYPE_STRING);
}
protected XWikiWebDriver getDriver()
{
return context.getDriver();
}
public Session getSession()
{
return this.new Session(getDriver().manage().getCookies(), getSecretToken());
}
public void setSession(Session session)
{
WebDriver.Options options = getDriver().manage();
options.deleteAllCookies();
if (session != null) {
for (Cookie cookie : session.getCookies()) {
options.addCookie(cookie);
}
}
if (session != null && !StringUtils.isEmpty(session.getSecretToken())) {
this.secretToken = session.getSecretToken();
} else {
recacheSecretToken();
}
}
/**
* @since 7.0RC1
*/
public void setDefaultCredentials(String username, String password)
{
this.adminHTTPClient.getState().setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username, password));
}
/**
* @since 7.0RC1
*/
public void setDefaultCredentials(UsernamePasswordCredentials defaultCredentials)
{
this.adminHTTPClient.getState().setCredentials(AuthScope.ANY, defaultCredentials);
}
public UsernamePasswordCredentials getDefaultCredentials()
{
return (UsernamePasswordCredentials) this.adminHTTPClient.getState().getCredentials(AuthScope.ANY);
}
public void loginAsSuperAdmin()
{
login(SUPER_ADMIN_CREDENTIALS.getUserName(), SUPER_ADMIN_CREDENTIALS.getPassword());
}
public void loginAsSuperAdminAndGotoPage(String pageURL)
{
loginAndGotoPage(SUPER_ADMIN_CREDENTIALS.getUserName(), SUPER_ADMIN_CREDENTIALS.getPassword(), pageURL);
}
public void loginAsAdmin()
{
login(ADMIN_CREDENTIALS.getUserName(), ADMIN_CREDENTIALS.getPassword());
}
public void loginAsAdminAndGotoPage(String pageURL)
{
loginAndGotoPage(ADMIN_CREDENTIALS.getUserName(), ADMIN_CREDENTIALS.getPassword(), pageURL);
}
public void login(String username, String password)
{
loginAndGotoPage(username, password, null);
}
public void loginAndGotoPage(String username, String password, String pageURL)
{
if (!username.equals(getLoggedInUserName())) {
// Log in and direct to a non existent page so that it loads very fast and we don't incur the time cost of
// going to the home page for example.
// Also recache the CSRF token
getDriver().get(getURLToLoginAndGotoPage(username, password, getURL("XWiki", "Register", "register")));
recacheSecretTokenWhenOnRegisterPage();
if (pageURL != null) {
// Go to the page asked
getDriver().get(pageURL);
} else {
getDriver().get(getURLToNonExistentPage());
}
setDefaultCredentials(username, password);
}
}
/**
* Consider using setSession(null) because it will drop the cookies which is faster than invoking a logout action.
*/
public String getURLToLogout()
{
return getURL("XWiki", "XWikiLogin", "logout");
}
public String getURLToLoginAsAdmin()
{
return getURLToLoginAs(ADMIN_CREDENTIALS.getUserName(), ADMIN_CREDENTIALS.getPassword());
}
public String getURLToLoginAsSuperAdmin()
{
return getURLToLoginAs(SUPER_ADMIN_CREDENTIALS.getUserName(), SUPER_ADMIN_CREDENTIALS.getPassword());
}
public String getURLToLoginAs(final String username, final String password)
{
return getURLToLoginAndGotoPage(username, password, null);
}
/**
* @param pageURL the URL of the page to go to after logging in.
* @return URL to accomplish login and goto.
*/
public String getURLToLoginAsAdminAndGotoPage(final String pageURL)
{
return getURLToLoginAndGotoPage(ADMIN_CREDENTIALS.getUserName(), ADMIN_CREDENTIALS.getPassword(), pageURL);
}
/**
* @param pageURL the URL of the page to go to after logging in.
* @return URL to accomplish login and goto.
*/
public String getURLToLoginAsSuperAdminAndGotoPage(final String pageURL)
{
return getURLToLoginAndGotoPage(SUPER_ADMIN_CREDENTIALS.getUserName(), SUPER_ADMIN_CREDENTIALS.getPassword(),
pageURL);
}
/**
* @param username the name of the user to log in as.
* @param password the password for the user to log in.
* @param pageURL the URL of the page to go to after logging in.
* @return URL to accomplish login and goto.
*/
public String getURLToLoginAndGotoPage(final String username, final String password, final String pageURL)
{
Map<String, String> parameters = new HashMap<String, String>()
{
{
put("j_username", username);
put("j_password", password);
if (pageURL != null && pageURL.length() > 0) {
put("xredirect", pageURL);
}
}
};
return getURL("XWiki", "XWikiLogin", "loginsubmit", parameters);
}
/**
* @return URL to a non existent page that loads very fast (we are using plain mode so that we don't even have to
* display the skin ;))
*/
public String getURLToNonExistentPage()
{
return getURL("NonExistentSpace", "NonExistentPage", "view", "xpage=plain");
}
/**
* After successful completion of this function, you are guaranteed to be logged in as the given user and on the
* page passed in pageURL.
*/
public void assertOnPage(final String pageURL)
{
final String pageURI = pageURL.replaceAll("\\?.*", "");
getDriver().waitUntilCondition(new ExpectedCondition<Boolean>()
{
@Override
public Boolean apply(WebDriver driver)
{
return getDriver().getCurrentUrl().contains(pageURI);
}
});
}
public String getLoggedInUserName()
{
By userAvatar = By.xpath("//div[@id='xwikimainmenu']//li[contains(@class, 'navbar-avatar')]/a");
if (!getDriver().hasElementWithoutWaiting(userAvatar)) {
// Guest
return null;
}
WebElement element = getDriver().findElementWithoutWaiting(userAvatar);
String href = element.getAttribute("href");
String loggedInUserName = href.substring(href.lastIndexOf("/") + 1);
// Return
return loggedInUserName;
}
public void createUserAndLogin(final String username, final String password, Object... properties)
{
createUserAndLoginWithRedirect(username, password, getURLToNonExistentPage(), properties);
}
public void createUserAndLoginWithRedirect(final String username, final String password, String url,
Object... properties)
{
createUser(username, password, getURLToLoginAndGotoPage(username, password, url), properties);
setDefaultCredentials(username, password);
}
public void createUser(final String username, final String password, String redirectURL, Object... properties)
{
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("register", "1");
parameters.put("xwikiname", username);
parameters.put("register_password", password);
parameters.put("register2_password", password);
parameters.put("register_email", "");
parameters.put("xredirect", redirectURL);
parameters.put("form_token", getSecretToken());
getDriver().get(getURL("XWiki", "Register", "register", parameters));
recacheSecretToken();
if (properties.length > 0) {
updateObject("XWiki", username, "XWiki.XWikiUsers", 0, properties);
}
}
public ViewPage gotoPage(String space, String page)
{
gotoPage(space, page, "view");
return new ViewPage();
}
/**
* @since 7.2M2
*/
public ViewPage gotoPage(EntityReference reference)
{
gotoPage(reference, "view");
return new ViewPage();
}
public void gotoPage(String space, String page, String action)
{
gotoPage(space, page, action, "");
}
/**
* @since 7.2M2
*/
public void gotoPage(EntityReference reference, String action)
{
gotoPage(reference, action, "");
}
/**
* @since 3.5M1
*/
public void gotoPage(String space, String page, String action, Object... queryParameters)
{
gotoPage(space, page, action, toQueryString(queryParameters));
}
public void gotoPage(String space, String page, String action, Map<String, ?> queryParameters)
{
gotoPage(Collections.singletonList(space), page, action, queryParameters);
}
/**
* @since 7.2M2
*/
public void gotoPage(List<String> spaces, String page, String action, Map<String, ?> queryParameters)
{
gotoPage(spaces, page, action, toQueryString(queryParameters));
}
/**
* @since 7.2M2
*/
public void gotoPage(EntityReference reference, String action, Map<String, ?> queryParameters)
{
gotoPage(reference, action, toQueryString(queryParameters));
}
public void gotoPage(String space, String page, String action, String queryString)
{
gotoPage(Collections.singletonList(space), page, action, queryString);
}
/**
* @since 7.2M2
*/
public void gotoPage(List<String> spaces, String page, String action, String queryString)
{
gotoPage(getURL(spaces, page, action, queryString));
}
/**
* @since 7.2M2
*/
public void gotoPage(EntityReference reference, String action, String queryString)
{
gotoPage(getURL(reference, action, queryString));
}
public void gotoPage(String url)
{
// Only navigate if the current URL is different from the one to go to, in order to improve performances.
if (!getDriver().getCurrentUrl().equals(url)) {
getDriver().get(url);
}
}
public String getURLToDeletePage(String space, String page)
{
return getURL(space, page, "delete", "confirm=1");
}
/**
* @since 7.2M2
*/
public String getURLToDeletePage(EntityReference reference)
{
return getURL(reference, "delete", "confirm=1");
}
/**
* @param space the name of the space to delete
* @return the URL that can be used to delete the specified pace
* @since 4.5
*/
public String getURLToDeleteSpace(String space)
{
return getURL(space, "WebHome", "deletespace", "confirm=1");
}
public ViewPage createPage(String space, String page, String content, String title)
{
return createPage(Collections.singletonList(space), page, content, title);
}
/**
* @since 7.2M2
*/
public ViewPage createPage(EntityReference reference, String content, String title)
{
return createPage(reference, content, title, null);
}
/**
* @since 7.2M2
*/
public ViewPage createPage(List<String> spaces, String page, String content, String title)
{
return createPage(spaces, page, content, title, null);
}
public ViewPage createPage(String space, String page, String content, String title, String syntaxId)
{
return createPage(Collections.singletonList(space), page, content, title, syntaxId);
}
/**
* @since 7.2M2
*/
public ViewPage createPage(EntityReference reference, String content, String title, String syntaxId)
{
return createPage(reference, content, title, syntaxId, null);
}
/**
* @since 7.2M2
*/
public ViewPage createPage(List<String> spaces, String page, String content, String title, String syntaxId)
{
return createPage(spaces, page, content, title, syntaxId, null);
}
public ViewPage createPage(String space, String page, String content, String title, String syntaxId,
String parentFullPageName)
{
return createPage(Collections.singletonList(space), page, content, title, syntaxId, parentFullPageName);
}
/**
* @since 7.2M2
*/
public ViewPage createPage(List<String> spaces, String page, String content, String title, String syntaxId,
String parentFullPageName)
{
Map<String, String> queryMap = new HashMap<String, String>();
if (content != null) {
queryMap.put("content", content);
}
if (title != null) {
queryMap.put("title", title);
}
if (syntaxId != null) {
queryMap.put("syntaxId", syntaxId);
}
if (parentFullPageName != null) {
queryMap.put("parent", parentFullPageName);
}
gotoPage(spaces, page, "save", queryMap);
return new ViewPage();
}
/**
* @since 7.2M2
*/
public ViewPage createPage(EntityReference reference, String content, String title, String syntaxId,
String parentFullPageName)
{
Map<String, String> queryMap = new HashMap<>();
if (content != null) {
queryMap.put("content", content);
}
if (title != null) {
queryMap.put("title", title);
}
if (syntaxId != null) {
queryMap.put("syntaxId", syntaxId);
}
if (parentFullPageName != null) {
queryMap.put("parent", parentFullPageName);
}
gotoPage(reference, "save", queryMap);
return new ViewPage();
}
/**
* @since 5.1M2
*/
public ViewPage createPageWithAttachment(String space, String page, String content, String title, String syntaxId,
String parentFullPageName, String attachmentName, InputStream attachmentData) throws Exception
{
return createPageWithAttachment(space, page, content, title, syntaxId, parentFullPageName, attachmentName,
attachmentData, null);
}
/**
* @since 5.1M2
*/
public ViewPage createPageWithAttachment(String space, String page, String content, String title, String syntaxId,
String parentFullPageName, String attachmentName, InputStream attachmentData,
UsernamePasswordCredentials credentials) throws Exception
{
return createPageWithAttachment(Collections.singletonList(space), page, content, title, syntaxId,
parentFullPageName, attachmentName, attachmentData, credentials);
}
/**
* @since 7.2M2
*/
public ViewPage createPageWithAttachment(List<String> spaces, String page, String content, String title,
String syntaxId, String parentFullPageName, String attachmentName, InputStream attachmentData,
UsernamePasswordCredentials credentials) throws Exception
{
ViewPage vp = createPage(spaces, page, content, title, syntaxId, parentFullPageName);
attachFile(spaces, page, attachmentName, attachmentData, false, credentials);
return vp;
}
/**
* @since 5.1M2
*/
public ViewPage createPageWithAttachment(String space, String page, String content, String title,
String attachmentName, InputStream attachmentData) throws Exception
{
return createPageWithAttachment(space, page, content, title, null, null, attachmentName, attachmentData);
}
/**
* @since 5.1M2
*/
public ViewPage createPageWithAttachment(String space, String page, String content, String title,
String attachmentName, InputStream attachmentData, UsernamePasswordCredentials credentials) throws Exception
{
ViewPage vp = createPage(space, page, content, title);
attachFile(space, page, attachmentName, attachmentData, false, credentials);
return vp;
}
public void deletePage(String space, String page)
{
getDriver().get(getURLToDeletePage(space, page));
}
/**
* @since 7.2M2
*/
public void deletePage(EntityReference reference)
{
getDriver().get(getURLToDeletePage(reference));
}
/**
* @since 7.2M2
*/
public EntityReference resolveDocumentReference(String referenceAsString)
{
return referenceResolver.resolve(referenceAsString, EntityType.DOCUMENT);
}
/**
* @since 7.2M3
*/
public EntityReference resolveSpaceReference(String referenceAsString)
{
return referenceResolver.resolve(referenceAsString, EntityType.SPACE);
}
/**
* @since 7.2RC1
*/
public String serializeReference(EntityReference reference)
{
return referenceSerializer.serialize(reference);
}
/**
* Accesses the URL to delete the specified space.
*
* @param space the name of the space to delete
* @since 4.5
*/
public void deleteSpace(String space)
{
getDriver().get(getURLToDeleteSpace(space));
}
public boolean pageExists(String space, String page)
{
return pageExists(Collections.singletonList(space), page);
}
/**
* @since 7.2M2
*/
public boolean pageExists(List<String> spaces, String page)
{
boolean exists;
try {
executeGet(getURL(spaces, page, "view", null), Status.OK.getStatusCode());
exists = true;
} catch (Exception e) {
exists = false;
}
return exists;
}
/**
* Get the URL to view a page.
*
* @param space the space in which the page resides.
* @param page the name of the page.
*/
public String getURL(String space, String page)
{
return getURL(space, page, "view");
}
/**
* Get the URL of an action on a page.
*
* @param space the space in which the page resides.
* @param page the name of the page.
* @param action the action to do on the page.
*/
public String getURL(String space, String page, String action)
{
return getURL(space, page, action, "");
}
/**
* Get the URL of an action on a page with a specified query string.
*
* @param space the space in which the page resides.
* @param page the name of the page.
* @param action the action to do on the page.
* @param queryString the query string to pass in the URL.
*/
public String getURL(String space, String page, String action, String queryString)
{
return getURL(action, new String[]{ space, page }, queryString);
}
/**
* @since 7.2M2
*/
public String getURL(List<String> spaces, String page, String action, String queryString)
{
List<String> path = new ArrayList<>(spaces);
path.add(page);
return getURL(action, path.toArray(new String[] {}), queryString);
}
/**
* @since 7.2M2
*/
public String getURL(EntityReference reference, String action, String queryString)
{
return getURL(action, extractListFromReference(reference).toArray(new String[]{}), queryString);
}
/**
* @since 7.2M2
*/
public String getURLFragment(EntityReference reference)
{
return StringUtils.join(extractListFromReference(reference), "/");
}
private List<String> extractListFromReference(EntityReference reference)
{
List<String> path = new ArrayList<>();
// Add the spaces
EntityReference spaceReference = reference.extractReference(EntityType.SPACE);
EntityReference wikiReference = reference.extractReference(EntityType.WIKI);
for (EntityReference singleReference : spaceReference.removeParent(wikiReference).getReversedReferenceChain())
{
path.add(singleReference.getName());
}
if (reference.getType() == EntityType.DOCUMENT) {
path.add(reference.getName());
}
return path;
}
/**
* @since 7.2M1
*/
public String getURL(String action, String[] path, String queryString)
{
StringBuilder builder = new StringBuilder(TestUtils.BASE_BIN_URL);
if (!StringUtils.isEmpty(action)) {
builder.append(action).append('/');
}
List<String> escapedPath = new ArrayList<>();
for (String element : path) {
escapedPath.add(escapeURL(element));
}
builder.append(StringUtils.join(escapedPath, '/'));
boolean needToAddSecretToken = !Arrays.asList("view", "register", "download").contains(action);
if (needToAddSecretToken || !StringUtils.isEmpty(queryString)) {
builder.append('?');
}
if (needToAddSecretToken) {
addQueryStringEntry(builder, "form_token", getSecretToken());
builder.append('&');
}
if (!StringUtils.isEmpty(queryString)) {
builder.append(queryString);
}
return builder.toString();
}
/**
* Get the URL of an action on a page with specified parameters. If you need to pass multiple parameters with the
* same key, this function will not work.
*
* @param space the space in which the page resides.
* @param page the name of the page.
* @param action the action to do on the page.
* @param queryParameters the parameters to pass in the URL, these will be automatically URL encoded.
*/
public String getURL(String space, String page, String action, Map<String, ?> queryParameters)
{
return getURL(space, page, action, toQueryString(queryParameters));
}
/**
* @param space the name of the space that contains the page with the specified attachment
* @param page the name of the page that holds the attachment
* @param attachment the attachment name
* @param action the action to perform on the attachment
* @param queryString the URL query string
* @return the URL that performs the specified action on the specified attachment
*/
public String getAttachmentURL(String space, String page, String attachment, String action, String queryString)
{
return getURL(action, new String[] {space, page, attachment}, queryString);
}
/**
* @param space the name of the space that contains the page with the specified attachment
* @param page the name of the page that holds the attachment
* @param attachment the attachment name
* @param action the action to perform on the attachment
* @return the URL that performs the specified action on the specified attachment
*/
public String getAttachmentURL(String space, String page, String attachment, String action)
{
return getAttachmentURL(space, page, attachment, action, "");
}
/**
* @param space the name of the space that contains the page with the specified attachment
* @param page the name of the page that holds the attachment
* @param attachment the attachment name
* @return the URL to download the specified attachment
*/
public String getAttachmentURL(String space, String page, String attachment)
{
return getAttachmentURL(space, page, attachment, "download");
}
/**
* (Re)-cache the secret token used for CSRF protection. A user with edit rights on Main.WebHome must be logged in.
* This method must be called before {@link #getSecretToken()} is called and after each re-login.
*
* @see #getSecretToken()
*/
public void recacheSecretToken()
{
// Save the current URL to be able to get back after we cache the secret token. We're not using the browser's
// Back button because if the current page is the result of a POST request then by going back we are re-sending
// the POST data which can have unexpected results. Moreover, some browsers pop up a modal confirmation box
// which blocks the test.
String previousURL = getDriver().getCurrentUrl();
// Go to the registration page because the registration form uses secret token.
gotoPage("XWiki", "Register", "register");
recacheSecretTokenWhenOnRegisterPage();
// Return to the previous page.
getDriver().get(previousURL);
}
private void recacheSecretTokenWhenOnRegisterPage()
{
try {
WebElement tokenInput = getDriver().findElement(By.xpath("//input[@name='form_token']"));
this.secretToken = tokenInput.getAttribute("value");
} catch (NoSuchElementException exception) {
// Something is really wrong if this happens.
System.out.println("Warning: Failed to cache anti-CSRF secret token, some tests might fail!");
exception.printStackTrace();
}
}
/**
* Get the secret token used for CSRF protection. Remember to call {@link #recacheSecretToken()} first.
*
* @return anti-CSRF secret token, or empty string if the token was not cached
* @see #recacheSecretToken()
*/
public String getSecretToken()
{
if (this.secretToken == null) {
System.out.println("Warning: No cached anti-CSRF token found. "
+ "Make sure to call recacheSecretToken() before getSecretToken(), otherwise this test might fail.");
return "";
}
return this.secretToken;
}
/**
* Encodes a given string so that it may be used as a URL component. Compatable with javascript decodeURIComponent,
* though more strict than encodeURIComponent: all characters except [a-zA-Z0-9], '.', '-', '*', '_' are converted
* to hexadecimal, and spaces are substituted by '+'.
*
* @param s
*/
public String escapeURL(String s)
{
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
// should not happen
throw new RuntimeException(e);
}
}
/**
* This class represents all cookies stored in the browser. Use with getSession() and setSession()
*/
public class Session
{
private final Set<Cookie> cookies;
private final String secretToken;
private Session(final Set<Cookie> cookies, final String secretToken)
{
this.cookies = Collections.unmodifiableSet(new HashSet<Cookie>()
{
{
addAll(cookies);
}
});
this.secretToken = secretToken;
}
private Set<Cookie> getCookies()
{
return this.cookies;
}
private String getSecretToken()
{
return this.secretToken;
}
}
public boolean isInWYSIWYGEditMode()
{
return getDriver().findElements(By.xpath("//div[@id='editcolumn' and contains(@class, 'editor-wysiwyg')]"))
.size() > 0;
}
public boolean isInWikiEditMode()
{
return getDriver().findElements(By.xpath("//div[@id='editcolumn' and contains(@class, 'editor-wiki')]")).size() > 0;
}
public boolean isInViewMode()
{
return !getDriver().hasElementWithoutWaiting(By.id("editMeta"));
}
public boolean isInSourceViewMode()
{
return getDriver().findElements(By.xpath("//textarea[@class = 'wiki-code']")).size() > 0;
}
public boolean isInInlineEditMode()
{
String currentURL = getDriver().getCurrentUrl();
// Keep checking the deprecated inline action for backward compatibility.
return currentURL.contains("editor=inline") || currentURL.contains("/inline/");
}
public boolean isInRightsEditMode()
{
return getDriver().getCurrentUrl().contains("editor=rights");
}
public boolean isInObjectEditMode()
{
return getDriver().getCurrentUrl().contains("editor=object");
}
public boolean isInClassEditMode()
{
return getDriver().getCurrentUrl().contains("editor=class");
}
public boolean isInDeleteMode()
{
return getDriver().getCurrentUrl().contains("/delete/");
}
public boolean isInRenameMode()
{
return getDriver().getCurrentUrl().contains("xpage=rename");
}
public boolean isInCreateMode()
{
return getDriver().getCurrentUrl().contains("/create/");
}
/**
* Forces the current user to be the Guest user by clearing all coookies.
*/
public void forceGuestUser()
{
setSession(null);
}
public void addObject(String space, String page, String className, Object... properties)
{
gotoPage(space, page, "objectadd", toQueryParameters(className, null, properties));
}
public void addObject(String space, String page, String className, Map<String, ?> properties)
{
gotoPage(space, page, "objectadd", toQueryParameters(className, null, properties));
}
public void deleteObject(String space, String page, String className, int objectNumber)
{
StringBuilder queryString = new StringBuilder();
queryString.append("classname=");
queryString.append(escapeURL(className));
queryString.append('&');
queryString.append("classid=");
queryString.append(objectNumber);
gotoPage(space, page, "objectremove", queryString.toString());
}
public void updateObject(String space, String page, String className, int objectNumber, Map<String, ?> properties)
{
gotoPage(space, page, "save", toQueryParameters(className, objectNumber, properties));
}
public void updateObject(String space, String page, String className, int objectNumber, Object... properties)
{
// TODO: would be even quicker using REST
Map<String, Object> queryParameters =
(Map<String, Object>) toQueryParameters(className, objectNumber, properties);
// Append the updateOrCreate objectPolicy since we always want this in our tests.
queryParameters.put("objectPolicy", "updateOrCreate");
gotoPage(space, page, "save", queryParameters);
}
public ClassEditPage addClassProperty(String space, String page, String propertyName, String propertyType)
{
gotoPage(space, page, "propadd", "propname", propertyName, "proptype", propertyType);
return new ClassEditPage();
}
/**
* @since 3.5M1
*/
public String toQueryString(Object... queryParameters)
{
return toQueryString(toQueryParameters(queryParameters));
}
/**
* @since 3.5M1
*/
public String toQueryString(Map<String, ?> queryParameters)
{
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, ?> entry : queryParameters.entrySet()) {
addQueryStringEntry(builder, entry.getKey(), entry.getValue());
builder.append('&');
}
return builder.toString();
}
/**
* @sice 3.2M1
*/
public void addQueryStringEntry(StringBuilder builder, String key, Object value)
{
if (value != null) {
if (value instanceof Iterable) {
for (Object element : (Iterable<?>) value) {
addQueryStringEntry(builder, key, element.toString());
builder.append('&');
}
} else {
addQueryStringEntry(builder, key, value.toString());
}
} else {
addQueryStringEntry(builder, key, (String) null);
}
}
/**
* @sice 3.2M1
*/
public void addQueryStringEntry(StringBuilder builder, String key, String value)
{
builder.append(escapeURL(key));
if (value != null) {
builder.append('=');
builder.append(escapeURL(value));
}
}
/**
* @since 3.5M1
*/
public Map<String, ?> toQueryParameters(Object... properties)
{
return toQueryParameters(null, null, properties);
}
public Map<String, ?> toQueryParameters(String className, Integer objectNumber, Object... properties)
{
Map<String, Object> queryParameters = new HashMap<String, Object>();
queryParameters.put("classname", className);
for (int i = 0; i < properties.length; i += 2) {
int nextIndex = i + 1;
queryParameters.put(toQueryParameterKey(className, objectNumber, (String) properties[i]),
nextIndex < properties.length ? properties[nextIndex] : null);
}
return queryParameters;
}
public Map<String, ?> toQueryParameters(String className, Integer objectNumber, Map<String, ?> properties)
{
Map<String, Object> queryParameters = new HashMap<String, Object>();
if (className != null) {
queryParameters.put("classname", className);
}
for (Map.Entry<String, ?> entry : properties.entrySet()) {
queryParameters.put(toQueryParameterKey(className, objectNumber, entry.getKey()), entry.getValue());
}
return queryParameters;
}
public String toQueryParameterKey(String className, Integer objectNumber, String key)
{
if (className == null) {
return key;
} else {
StringBuilder keyBuilder = new StringBuilder(className);
keyBuilder.append('_');
if (objectNumber != null) {
keyBuilder.append(objectNumber);
keyBuilder.append('_');
}
keyBuilder.append(key);
return keyBuilder.toString();
}
}
public ObjectEditPage editObjects(String space, String page)
{
gotoPage(space, page, "edit", "editor=object");
return new ObjectEditPage();
}
public ClassEditPage editClass(String space, String page)
{
gotoPage(space, page, "edit", "editor=class");
return new ClassEditPage();
}
public String getVersion() throws Exception
{
Xwiki xwiki = getRESTResource("", null);
return xwiki.getVersion();
}
public String getMavenVersion() throws Exception
{
String version = getVersion();
int index = version.indexOf('-');
if (index > 0) {
version = version.substring(0, index) + "-SNAPSHOT";
}
return version;
}
public void attachFile(String space, String page, String name, File file, boolean failIfExists) throws Exception
{
InputStream is = new FileInputStream(file);
try {
attachFile(space, page, name, is, failIfExists);
} finally {
is.close();
}
}
/**
* @since 5.1M2
*/
public void attachFile(String space, String page, String name, InputStream is, boolean failIfExists,
UsernamePasswordCredentials credentials) throws Exception
{
attachFile(Collections.singletonList(space), page, name, is, failIfExists, credentials);
}
/**
* @since 7.2M2
*/
public void attachFile(List<String> spaces, String page, String name, InputStream is, boolean failIfExists,
UsernamePasswordCredentials credentials) throws Exception
{
UsernamePasswordCredentials currentCredentials = getDefaultCredentials();
try {
if (credentials != null) {
setDefaultCredentials(credentials);
}
attachFile(spaces, page, name, is, failIfExists);
} finally {
setDefaultCredentials(currentCredentials);
}
}
public void attachFile(String space, String page, String name, InputStream is, boolean failIfExists)
throws Exception
{
attachFile(Collections.singletonList(space), page, name, is, failIfExists);
}
/**
* @since 7.2M2
*/
public void attachFile(List<String> spaces, String page, String name, InputStream is, boolean failIfExists)
throws Exception
{
// make sure xwiki.Import exists
if (!pageExists(spaces, page)) {
createPage(spaces, page, null, null);
}
StringBuilder url = new StringBuilder(BASE_REST_URL);
url.append("wikis/xwiki");
for (String space : spaces) {
url.append("/spaces/").append(escapeURL(space));
}
url.append("/pages/");
url.append(escapeURL(page));
url.append("/attachments/");
url.append(escapeURL(name));
if (failIfExists) {
executePut(url.toString(), is, MediaType.APPLICATION_OCTET_STREAM, Status.CREATED.getStatusCode());
} else {
executePut(url.toString(), is, MediaType.APPLICATION_OCTET_STREAM, Status.CREATED.getStatusCode(),
Status.ACCEPTED.getStatusCode());
}
}
// FIXME: improve that with a REST API to directly import a XAR
public void importXar(File file) throws Exception
{
// attach file
attachFile("XWiki", "Import", file.getName(), file, false);
// import file
executeGet(
BASE_BIN_URL + "import/XWiki/Import?historyStrategy=add&importAsBackup=true&ajax&action=import&name="
+ escapeURL(file.getName()), Status.OK.getStatusCode());
}
public InputStream getRESTInputStream(String resourceUri, Map<String, ?> queryParams, Object... elements)
throws Exception
{
return getInputStream(BASE_REST_URL, resourceUri, queryParams, elements);
}
public InputStream getInputStream(String path, Map<String, ?> queryParams) throws Exception
{
return getInputStream(BASE_URL, path, queryParams);
}
public String getString(String path, Map<String, ?> queryParams) throws Exception
{
try (InputStream inputStream = getInputStream(BASE_URL, path, queryParams)) {
return IOUtils.toString(inputStream);
}
}
public InputStream getInputStream(String prefix, String path, Map<String, ?> queryParams, Object... elements)
throws Exception
{
String cleanPrefix = prefix.endsWith("/") ? prefix.substring(0, prefix.length() - 1) : prefix;
if (path.startsWith(cleanPrefix)) {
cleanPrefix = "";
}
UriBuilder builder = UriBuilder.fromUri(cleanPrefix).path(path.startsWith("/") ? path.substring(1) : path);
if (queryParams != null) {
for (Map.Entry<String, ?> entry : queryParams.entrySet()) {
if (entry.getValue() instanceof Object[]) {
builder.queryParam(entry.getKey(), (Object[]) entry.getValue());
} else {
builder.queryParam(entry.getKey(), entry.getValue());
}
}
}
String url = builder.build(elements).toString();
return executeGet(url, Status.OK.getStatusCode()).getResponseBodyAsStream();
}
public InputStream postRESTInputStream(String resourceUri, Object restObject, Map<String, Object[]> queryParams,
Object... elements) throws Exception
{
UriBuilder builder =
UriBuilder.fromUri(BASE_REST_URL.substring(0, BASE_REST_URL.length() - 1)).path(
!resourceUri.isEmpty() && resourceUri.charAt(0) == '/' ? resourceUri.substring(1) : resourceUri);
if (queryParams != null) {
for (Map.Entry<String, Object[]> entry : queryParams.entrySet()) {
builder.queryParam(entry.getKey(), entry.getValue());
}
}
String url = builder.build(elements).toString();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
marshaller.marshal(restObject, stream);
return executePost(url, new ByteArrayInputStream(stream.toByteArray()), MediaType.APPLICATION_XML,
Status.OK.getStatusCode()).getResponseBodyAsStream();
}
public byte[] getRESTBuffer(String resourceUri, Map<String, Object[]> queryParams, Object... elements)
throws Exception
{
InputStream is = getRESTInputStream(resourceUri, queryParams, elements);
byte[] buffer;
try {
buffer = IOUtils.toByteArray(is);
} finally {
is.close();
}
return buffer;
}
public <T> T getRESTResource(String resourceUri, Map<String, Object[]> queryParams, Object... elements)
throws Exception
{
T resource;
try (InputStream is = getRESTInputStream(resourceUri, queryParams, elements)) {
resource = (T) unmarshaller.unmarshal(is);
}
return resource;
}
public <T> T postRESTResource(String resourceUri, Object entity, Object... elements) throws Exception
{
return postRESTResource(resourceUri, entity, Collections.<String, Object[]>emptyMap(), elements);
}
public <T> T postRESTResource(String resourceUri, Object entity, Map<String, Object[]> queryParams,
Object... elements) throws Exception
{
T resource;
try (InputStream is = postRESTInputStream(resourceUri, entity, queryParams, elements)) {
resource = (T) unmarshaller.unmarshal(is);
}
return resource;
}
protected GetMethod executeGet(String uri, int expectedCode) throws Exception
{
GetMethod getMethod = new GetMethod(uri);
int code = this.adminHTTPClient.executeMethod(getMethod);
if (code != expectedCode) {
throw new Exception("Failed to execute get [" + uri + "] with code [" + code + "]");
}
return getMethod;
}
protected PostMethod executePost(String uri, InputStream content, String mediaType, int... expectedCodes)
throws Exception
{
PostMethod putMethod = new PostMethod(uri);
RequestEntity entity = new InputStreamRequestEntity(content, mediaType);
putMethod.setRequestEntity(entity);
int code = this.adminHTTPClient.executeMethod(putMethod);
if (!ArrayUtils.contains(expectedCodes, code)) {
throw new Exception("Failed to execute post [" + uri + "] with code [" + code + "]");
}
return putMethod;
}
protected PutMethod executePut(String uri, InputStream content, String mediaType, int... expectedCodes)
throws Exception
{
PutMethod putMethod = new PutMethod(uri);
RequestEntity entity = new InputStreamRequestEntity(content, mediaType);
putMethod.setRequestEntity(entity);
int code = this.adminHTTPClient.executeMethod(putMethod);
if (!ArrayUtils.contains(expectedCodes, code)) {
throw new Exception("Failed to execute put [" + uri + "] with code [" + code + "]");
}
return putMethod;
}
/**
* Delete the latest version from the history of a page, using the {@code /deleteversions/} action.
*
* @param space the space name of the page
* @param page the name of the page
* @since 7.0M2
*/
public void deleteLatestVersion(String space, String page)
{
deleteVersion(space, page, "latest");
}
/**
* Delete a specific version from the history of a page, using the {@code /deleteversions/} action.
*
* @param space the space name of the page
* @param page the name of the page
* @param version the version to delete
* @since 7.0M2
*/
public void deleteVersion(String space, String page, String version)
{
deleteVersions(space, page, version, version);
}
/**
* Delete an interval of versions from the history of a page, using the {@code /deleteversions/} action.
*
* @param space the space name of the page
* @param page the name of the page
* @param v1 the starting version to delete
* @param v2 the ending version to delete
* @since 7.0M2
*/
public void deleteVersions(String space, String page, String v1, String v2)
{
gotoPage(space, page, "deleteversions", "rev1", v1, "rev2", v2, "confirm", "1");
}
/**
* Roll back a page to the previous version, using the {@code /rollback/} action.
*
* @param space the space name of the page
* @param page the name of the page
* @since 7.0M2
*/
public void rollbackToPreviousVersion(String space, String page)
{
rollBackTo(space, page, "previous");
}
/**
* Roll back a page to the specified version, using the {@code /rollback/} action.
*
* @param space the space name of the page
* @param page the name of the page
* @param version the version to rollback to
* @since 7.0M2
*/
public void rollBackTo(String space, String page, String version)
{
gotoPage(space, page, "rollback", "rev", version, "confirm", "1");
}
/**
* Set the hierarchy mode used in the wiki
* @param mode the mode to use ("reference" or "parentchild")
* @since 7.2M2
*/
public void setHierarchyMode(String mode) {
setPropertyInXWikiPreferences("core.hierarchyMode", "String", mode);
}
/**
* Add and set a property into XWiki.XWikiPreferences. Create XWiki.XWikiPreferences if it does not exist.
* @param propertyName name of the property to set
* @param propertyType the type of the property to add
* @param value value to set to the property
* @since 7.2M2
*/
public void setPropertyInXWikiPreferences(String propertyName, String propertyType, Object value)
{
addClassProperty("XWiki", "XWikiPreferences", propertyName, propertyType);
gotoPage("XWiki", "XWikiPreferences", "edit", "editor", "object");
ObjectEditPage objectEditPage = new ObjectEditPage();
if (objectEditPage.hasObject("XWiki.XWikiPreferences")) {
updateObject("XWiki", "XWikiPreferences", "XWiki.XWikiPreferences", 0, propertyName, value);
} else {
addObject("XWiki", "XWikiPreferences", "XWiki.XWikiPreferences", propertyName, value);
}
}
}
|
package test.hystrix;
import java.util.concurrent.Future;
import org.apache.log4j.PropertyConfigurator;
import rx.Observable;
public class ClientTest {
public static void main(String[] args) {
try {
PropertyConfigurator.configure("conf/log4j.properties");
final HelloCommand command = new HelloCommand();
// System.out.println("result: " + command.execute());
// System.out.println("");
Future<String> future = command.queue();
System.out.println("result: " + future.get());
System.out.println("");
Observable<String> observe = command.observe();
observe.asObservable().subscribe((result) -> {
System.out.println(result);
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.nflabs.zeppelin.interpreter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.nflabs.zeppelin.conf.ZeppelinConfiguration;
import com.nflabs.zeppelin.conf.ZeppelinConfiguration.ConfVars;
import com.nflabs.zeppelin.interpreter.Interpreter.RegisteredInterpreter;
import com.nflabs.zeppelin.interpreter.remote.RemoteInterpreter;
/**
* Manage interpreters.
*
*/
public class InterpreterFactory {
Logger logger = LoggerFactory.getLogger(InterpreterFactory.class);
private Map<String, URLClassLoader> cleanCl = Collections
.synchronizedMap(new HashMap<String, URLClassLoader>());
private ZeppelinConfiguration conf;
String[] interpreterClassList;
private Map<String, InterpreterSetting> interpreterSettings =
new HashMap<String, InterpreterSetting>();
private Map<String, List<String>> interpreterBindings = new HashMap<String, List<String>>();
private Gson gson;
public InterpreterFactory(ZeppelinConfiguration conf) throws InterpreterException, IOException {
this.conf = conf;
String replsConf = conf.getString(ConfVars.ZEPPELIN_INTERPRETERS);
interpreterClassList = replsConf.split(",");
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
builder.registerTypeAdapter(Interpreter.class, new InterpreterSerializer());
gson = builder.create();
init();
}
private void init() throws InterpreterException, IOException {
ClassLoader oldcl = Thread.currentThread().getContextClassLoader();
// Load classes
File[] interpreterDirs = new File(conf.getInterpreterDir()).listFiles();
if (interpreterDirs != null) {
for (File path : interpreterDirs) {
logger.info("Reading " + path.getAbsolutePath());
URL[] urls = null;
try {
urls = recursiveBuildLibList(path);
} catch (MalformedURLException e1) {
logger.error("Can't load jars ", e1);
}
URLClassLoader ccl = new URLClassLoader(urls, oldcl);
for (String className : interpreterClassList) {
try {
Class.forName(className, true, ccl);
Set<String> keys = Interpreter.registeredInterpreters.keySet();
for (String intName : keys) {
if (className.equals(
Interpreter.registeredInterpreters.get(intName).getClassName())) {
Interpreter.registeredInterpreters.get(intName).setPath(path.getAbsolutePath());
logger.info("Interpreter " + intName + " found. class=" + className);
cleanCl.put(path.getAbsolutePath(), ccl);
}
}
} catch (ClassNotFoundException e) {
// nothing to do
}
}
}
}
loadFromFile();
// if no interpreter settings are loaded, create default set
synchronized (interpreterSettings) {
if (interpreterSettings.size() == 0) {
HashMap<String, List<RegisteredInterpreter>> groupClassNameMap =
new HashMap<String, List<RegisteredInterpreter>>();
for (String k : Interpreter.registeredInterpreters.keySet()) {
RegisteredInterpreter info = Interpreter.registeredInterpreters.get(k);
if (!groupClassNameMap.containsKey(info.getGroup())) {
groupClassNameMap.put(info.getGroup(), new LinkedList<RegisteredInterpreter>());
}
groupClassNameMap.get(info.getGroup()).add(info);
}
for (String className : interpreterClassList) {
for (String groupName : groupClassNameMap.keySet()) {
List<RegisteredInterpreter> infos = groupClassNameMap.get(groupName);
boolean found = false;
Properties p = new Properties();
for (RegisteredInterpreter info : infos) {
if (found == false && info.getClassName().equals(className)) {
found = true;
}
for (String k : info.getProperties().keySet()) {
p.put(k, info.getProperties().get(k).getDefaultValue());
}
}
if (found) {
// add all interpreters in group
add(groupName, groupName, false, p);
groupClassNameMap.remove(groupName);
break;
}
}
}
}
}
for (String settingId : interpreterSettings.keySet()) {
InterpreterSetting setting = interpreterSettings.get(settingId);
logger.info("Interpreter setting group {} : id={}, name={}",
setting.getGroup(), settingId, setting.getName());
for (Interpreter interpreter : setting.getInterpreterGroup()) {
logger.info(" className = {}", interpreter.getClassName());
}
}
}
private void loadFromFile() throws IOException {
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
builder.registerTypeAdapter(Interpreter.class, new InterpreterSerializer());
Gson gson = builder.create();
File settingFile = new File(conf.getInterpreterSettingPath());
if (!settingFile.exists()) {
// nothing to read
return;
}
FileInputStream fis = new FileInputStream(settingFile);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
isr.close();
fis.close();
String json = sb.toString();
Map<String, Object> savedObject = gson.fromJson(json,
new TypeToken<Map<String, Object>>() {}.getType());
Map<String, Map<String, Object>> settings = (Map<String, Map<String, Object>>) savedObject
.get("interpreterSettings");
Map<String, List<String>> bindings = (Map<String, List<String>>) savedObject
.get("interpreterBindings");
for (String k : settings.keySet()) {
Map<String, Object> set = settings.get(k);
String id = (String) set.get("id");
String name = (String) set.get("name");
String group = (String) set.get("group");
Boolean remote = (Boolean) set.get("remote");
if (remote == null) {
remote = false;
}
Properties properties = new Properties();
properties.putAll((Map<String, String>) set.get("properties"));
InterpreterGroup interpreterGroup = createInterpreterGroup(group, remote, properties);
InterpreterSetting intpSetting = new InterpreterSetting(
id,
name,
group,
remote,
interpreterGroup);
interpreterSettings.put(k, intpSetting);
}
this.interpreterBindings = bindings;
}
private void saveToFile() throws IOException {
String jsonString;
synchronized (interpreterSettings) {
Map<String, Object> saveObject = new HashMap<String, Object>();
saveObject.put("interpreterSettings", interpreterSettings);
saveObject.put("interpreterBindings", interpreterBindings);
jsonString = gson.toJson(saveObject);
}
File settingFile = new File(conf.getInterpreterSettingPath());
if (!settingFile.exists()) {
settingFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(settingFile, false);
OutputStreamWriter out = new OutputStreamWriter(fos);
out.append(jsonString);
out.close();
fos.close();
}
private RegisteredInterpreter getRegisteredReplInfoFromClassName(String clsName) {
Set<String> keys = Interpreter.registeredInterpreters.keySet();
for (String intName : keys) {
RegisteredInterpreter info = Interpreter.registeredInterpreters.get(intName);
if (clsName.equals(info.getClassName())) {
return info;
}
}
return null;
}
/**
* Return ordered interpreter setting list.
* The list does not contain more than one setting from the same interpreter class.
* Order by InterpreterClass (order defined by ZEPPELIN_INTERPRETERS), Interpreter setting name
* @return
*/
public List<String> getDefaultInterpreterSettingList() {
// this list will contain default interpreter setting list
List<String> defaultSettings = new LinkedList<String>();
// to ignore the same interpreter group
Map<String, Boolean> interpreterGroupCheck = new HashMap<String, Boolean>();
List<InterpreterSetting> sortedSettings = get();
for (InterpreterSetting setting : sortedSettings) {
if (defaultSettings.contains(setting.id())) {
continue;
}
if (!interpreterGroupCheck.containsKey(setting.getGroup())) {
defaultSettings.add(setting.id());
interpreterGroupCheck.put(setting.getGroup(), true);
}
}
return defaultSettings;
}
public List<RegisteredInterpreter> getRegisteredInterpreterList() {
List<RegisteredInterpreter> registeredInterpreters = new LinkedList<RegisteredInterpreter>();
for (String className : interpreterClassList) {
registeredInterpreters.add(Interpreter.findRegisteredInterpreterByClassName(className));
}
return registeredInterpreters;
}
/**
* @param name user defined name
* @param groupName interpreter group name to instantiate
* @param properties
* @return
* @throws InterpreterException
* @throws IOException
*/
public InterpreterGroup add(String name, String groupName, boolean remote, Properties properties)
throws InterpreterException, IOException {
synchronized (interpreterSettings) {
InterpreterGroup interpreterGroup = createInterpreterGroup(groupName, remote, properties);
InterpreterSetting intpSetting = new InterpreterSetting(
name,
groupName,
remote,
interpreterGroup);
interpreterSettings.put(intpSetting.id(), intpSetting);
saveToFile();
return interpreterGroup;
}
}
private InterpreterGroup createInterpreterGroup(String groupName,
boolean remote,
Properties properties)
throws InterpreterException {
InterpreterGroup interpreterGroup = new InterpreterGroup();
for (String className : interpreterClassList) {
Set<String> keys = Interpreter.registeredInterpreters.keySet();
for (String intName : keys) {
RegisteredInterpreter info = Interpreter.registeredInterpreters
.get(intName);
if (info.getClassName().equals(className)
&& info.getGroup().equals(groupName)) {
Interpreter intp;
if (remote) {
intp = createRemoteRepl(info.getPath(),
info.getClassName(),
properties,
interpreterGroup);
} else {
intp = createRepl(info.getPath(),
info.getClassName(),
properties,
interpreterGroup);
}
interpreterGroup.add(intp);
break;
}
}
}
return interpreterGroup;
}
public void remove(String id) throws IOException {
synchronized (interpreterSettings) {
if (interpreterSettings.containsKey(id)) {
InterpreterSetting intp = interpreterSettings.get(id);
intp.getInterpreterGroup().close();
intp.getInterpreterGroup().destroy();
interpreterSettings.remove(id);
for (List<String> settings : interpreterBindings.values()) {
Iterator<String> it = settings.iterator();
while (it.hasNext()) {
String settingId = it.next();
if (settingId.equals(id)) {
it.remove();
}
}
}
saveToFile();
}
}
}
/**
* Get loaded interpreters
* @return
*/
public List<InterpreterSetting> get() {
synchronized (interpreterSettings) {
List<InterpreterSetting> orderedSettings = new LinkedList<InterpreterSetting>();
List<InterpreterSetting> settings = new LinkedList<InterpreterSetting>(
interpreterSettings.values());
Collections.sort(settings, new Comparator<InterpreterSetting>(){
@Override
public int compare(InterpreterSetting o1, InterpreterSetting o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (String className : interpreterClassList) {
for (InterpreterSetting setting : settings) {
for (InterpreterSetting orderedSetting : orderedSettings) {
if (orderedSetting.id().equals(setting.id())) {
continue;
}
}
for (Interpreter intp : setting.getInterpreterGroup()) {
if (className.equals(intp.getClassName())) {
boolean alreadyAdded = false;
for (InterpreterSetting st : orderedSettings) {
if (setting.id().equals(st.id())) {
alreadyAdded = true;
}
}
if (alreadyAdded == false) {
orderedSettings.add(setting);
}
}
}
}
}
return orderedSettings;
}
}
public InterpreterSetting get(String name) {
synchronized (interpreterSettings) {
return interpreterSettings.get(name);
}
}
public void putNoteInterpreterSettingBinding(String noteId,
List<String> settingList) throws IOException {
synchronized (interpreterSettings) {
interpreterBindings.put(noteId, settingList);
saveToFile();
}
}
public void removeNoteInterpreterSettingBinding(String noteId) {
synchronized (interpreterSettings) {
interpreterBindings.remove(noteId);
}
}
public List<String> getNoteInterpreterSettingBinding(String noteId) {
LinkedList<String> bindings = new LinkedList<String>();
synchronized (interpreterSettings) {
List<String> settingIds = interpreterBindings.get(noteId);
if (settingIds != null) {
bindings.addAll(settingIds);
}
}
return bindings;
}
/**
* Change interpreter property and restart
* @param name
* @param properties
* @throws IOException
*/
public void setPropertyAndRestart(String id, boolean remote,
Properties properties) throws IOException {
synchronized (interpreterSettings) {
InterpreterSetting intpsetting = interpreterSettings.get(id);
if (intpsetting != null) {
intpsetting.getInterpreterGroup().close();
intpsetting.getInterpreterGroup().destroy();
intpsetting.setRemote(remote);
InterpreterGroup interpreterGroup = createInterpreterGroup(
intpsetting.getGroup(), remote, properties);
intpsetting.setInterpreterGroup(interpreterGroup);
saveToFile();
} else {
throw new InterpreterException("Interpreter setting id " + id
+ " not found");
}
}
}
public void restart(String id) {
synchronized (interpreterSettings) {
synchronized (interpreterSettings) {
InterpreterSetting intpsetting = interpreterSettings.get(id);
if (intpsetting != null) {
intpsetting.getInterpreterGroup().close();
intpsetting.getInterpreterGroup().destroy();
InterpreterGroup interpreterGroup = createInterpreterGroup(
intpsetting.getGroup(), intpsetting.isRemote(), intpsetting.getProperties());
intpsetting.setInterpreterGroup(interpreterGroup);
} else {
throw new InterpreterException("Interpreter setting id " + id
+ " not found");
}
}
}
}
public void close() {
synchronized (interpreterSettings) {
synchronized (interpreterSettings) {
Collection<InterpreterSetting> intpsettings = interpreterSettings.values();
for (InterpreterSetting intpsetting : intpsettings) {
intpsetting.getInterpreterGroup().close();
intpsetting.getInterpreterGroup().destroy();
}
}
}
}
private Interpreter createRepl(String dirName, String className,
Properties property, InterpreterGroup interpreterGroup)
throws InterpreterException {
logger.info("Create repl {} from {}", className, dirName);
ClassLoader oldcl = Thread.currentThread().getContextClassLoader();
try {
URLClassLoader ccl = cleanCl.get(dirName);
if (ccl == null) {
// classloader fallback
ccl = URLClassLoader.newInstance(new URL[] {}, oldcl);
}
boolean separateCL = true;
try { // check if server's classloader has driver already.
Class cls = this.getClass().forName(className);
if (cls != null) {
separateCL = false;
}
} catch (Exception e) {
// nothing to do.
}
URLClassLoader cl;
if (separateCL == true) {
cl = URLClassLoader.newInstance(new URL[] {}, ccl);
} else {
cl = ccl;
}
Thread.currentThread().setContextClassLoader(cl);
Class<Interpreter> replClass = (Class<Interpreter>) cl.loadClass(className);
Constructor<Interpreter> constructor =
replClass.getConstructor(new Class[] {Properties.class});
Interpreter repl = constructor.newInstance(property);
repl.setClassloaderUrls(ccl.getURLs());
LazyOpenInterpreter intp = new LazyOpenInterpreter(
new ClassloaderInterpreter(repl, cl));
intp.setInterpreterGroup(interpreterGroup);
return intp;
} catch (SecurityException e) {
throw new InterpreterException(e);
} catch (NoSuchMethodException e) {
throw new InterpreterException(e);
} catch (IllegalArgumentException e) {
throw new InterpreterException(e);
} catch (InstantiationException e) {
throw new InterpreterException(e);
} catch (IllegalAccessException e) {
throw new InterpreterException(e);
} catch (InvocationTargetException e) {
throw new InterpreterException(e);
} catch (ClassNotFoundException e) {
throw new InterpreterException(e);
} finally {
Thread.currentThread().setContextClassLoader(oldcl);
}
}
private Interpreter createRemoteRepl(String interpreterPath, String className,
Properties property, InterpreterGroup interpreterGroup) {
LazyOpenInterpreter intp = new LazyOpenInterpreter(new RemoteInterpreter(
property, className, conf.getInterpreterRemoteRunnerPath(), interpreterPath));
intp.setInterpreterGroup(interpreterGroup);
return intp;
}
private URL[] recursiveBuildLibList(File path) throws MalformedURLException {
URL[] urls = new URL[0];
if (path == null || path.exists() == false) {
return urls;
} else if (path.getName().startsWith(".")) {
return urls;
} else if (path.isDirectory()) {
File[] files = path.listFiles();
if (files != null) {
for (File f : files) {
urls = (URL[]) ArrayUtils.addAll(urls, recursiveBuildLibList(f));
}
}
return urls;
} else {
return new URL[] {path.toURI().toURL()};
}
}
}
|
package com.gooddata.csv;
import com.gooddata.Constants;
import com.gooddata.exception.InvalidParameterException;
import com.gooddata.modeling.model.SourceColumn;
import com.gooddata.util.CSVReader;
import com.gooddata.util.FileUtil;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* GoodData CSV data type guessing
*
* @author zd <zd@gooddata.com>
* @version 1.0
*/
public class DataTypeGuess {
private static final String[] DATE_FORMATS = {"yyyy-MM-dd", "MM/dd/yyyy", "M/d/yyyy", "MM-dd-yyyy",
"yyyy-M-d", "M-d-yyyy"};
private static DateTimeFormatter[] KNOWN_FORMATS;
private final boolean hasHeader;
private String defaultLdmType = null;
static {
KNOWN_FORMATS = new DateTimeFormatter[DATE_FORMATS.length];
for (int i = 0; i < DATE_FORMATS.length; i++) {
KNOWN_FORMATS[i] = DateTimeFormat.forPattern(DATE_FORMATS[i]);
}
}
public DataTypeGuess(boolean hasHeader) {
this.hasHeader = hasHeader;
}
/**
* Tests if the String is integer
*
* @param t the tested String
* @return true if the String is integer, false otherwise
*/
public static boolean isInteger(String t) {
try {
Integer.parseInt(t);
return true;
} catch (NumberFormatException e) {
return false;
}
}
/**
* Tests if the String is decimal
*
* @param t the tested String
* @return true if the String is decimal, false otherwise
*/
public static boolean isDecimal(String t) {
for (String c : Constants.DISCARD_CHARS) {
t = t.replace(c, "");
}
try {
/*
if(isInteger(t))
return false;
*/
Double.parseDouble(t);
return true;
} catch (NumberFormatException e) {
return false;
}
}
/**
* Tests if the String is date
*
* @param t the tested String
* @return true if the String is date, false otherwise
*/
public static String getDateFormat(String t) {
for (int i = 0; i < KNOWN_FORMATS.length; i++) {
DateTimeFormatter d = KNOWN_FORMATS[i];
try {
DateTime dt = d.parseDateTime(t);
if (t.equals(d.print(dt)))
return DATE_FORMATS[i];
} catch (IllegalArgumentException e) {
// do nothing
}
}
return null;
}
/**
* Guesses the CSV schema
*
* @param separator field separator
* @return the String[] with the CSV column types
* @throws IOException in case of IO issue
*/
public SourceColumn[] guessCsvSchema(URL url, char separator) throws IOException {
return guessCsvSchema(url.openStream(), separator);
}
/**
* Guesses the CSV schema
*
* @param is CSV stream
* @param separator field separator
* @return the String[] with the CSV column types
* @throws IOException in case of IO issue
*/
public SourceColumn[] guessCsvSchema(InputStream is, char separator) throws IOException {
CSVReader cr = FileUtil.createUtf8CsvReader(is, separator);
return guessCsvSchema(cr);
}
/**
* Guesses the CSV schema
*
* @param cr CSV reader
* @return the String[] with the CSV column types
* @throws IOException in case of IO issue
*/
public SourceColumn[] guessCsvSchema(CSVReader cr) throws IOException {
return guessCsvSchema(cr, -1);
}
/**
* Guesses the CSV schema
*
* @param cr CSV reader
* @return the String[] with the CSV column types
* @throws IOException in case of IO issue
*/
public SourceColumn[] guessCsvSchema(CSVReader cr, int columns) throws IOException {
if (hasHeader) {
columns = cr.readNext().length;
}
if (columns == -1) {
throw new UnsupportedOperationException("You have to specify number of columns if the CSV does not have a header.");
}
List<Set<String>> excludedColumnTypes = new ArrayList<Set<String>>();
String[] dateFormats = new String[columns];
if (defaultLdmType == null) {
String[] row = cr.readNext();
if (row != null) {
for (int i = 0; i < row.length; i++) {
HashSet<String> allTypes = new HashSet<String>();
excludedColumnTypes.add(allTypes);
}
int countdown = 1000;
while (row != null && countdown
for (int i = 0; i < row.length; i++) {
if (i >= excludedColumnTypes.size())
throw new InvalidParameterException("The CSV file contains rows with different number of columns on row " + cr.getRow());
Set<String> types = excludedColumnTypes.get(i);
String value = row[i];
String dateFormat = getDateFormat(value);
if (dateFormat == null) {
types.add(SourceColumn.LDM_TYPE_DATE);
} else {
dateFormats[i] = dateFormat;
}
if (!isDecimal(value)) {
types.add(SourceColumn.LDM_TYPE_FACT);
}
}
row = cr.readNext();
}
}
}
SourceColumn[] ret = new SourceColumn[columns];
for (int i = 0; i < columns; i++) {
final String ldmType;
if (defaultLdmType != null)
ldmType = defaultLdmType;
else {
if (i >= excludedColumnTypes.size()) {
ldmType = SourceColumn.LDM_TYPE_ATTRIBUTE;
} else {
final Set<String> excludedColumnType = excludedColumnTypes.get(i);
if (!excludedColumnType.contains(SourceColumn.LDM_TYPE_DATE))
ldmType = SourceColumn.LDM_TYPE_DATE;
else if (!excludedColumnType.contains(SourceColumn.LDM_TYPE_FACT))
ldmType = SourceColumn.LDM_TYPE_FACT;
else
ldmType = SourceColumn.LDM_TYPE_ATTRIBUTE;
}
}
ret[i] = new SourceColumn(null, ldmType, null);
if (SourceColumn.LDM_TYPE_DATE.equals(ldmType)) {
ret[i].setFormat(dateFormats[i]);
}
}
return ret;
}
/**
* returns default LDM type to be associated with detected fields rather
* than by guessing
*
* @return
*/
public String getDefaultLdmType() {
return defaultLdmType;
}
/**
* sets the default LDM type to be associated with detected fields rather
* than by guessing
*
* @param defaultLdmType
*/
public void setDefaultLdmType(String defaultLdmType) {
this.defaultLdmType = defaultLdmType;
}
}
|
package com.yahoo.restapi;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yahoo.container.jdisc.AclMapping;
import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.container.jdisc.RequestHandlerSpec;
import java.io.InputStream;
import java.security.Principal;
import java.util.List;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalLong;
/**
* Rest API routing and response serialization
*
* @author bjorncs
*/
public interface RestApi {
static Builder builder() { return new RestApiImpl.BuilderImpl(); }
static RouteBuilder route(String pathPattern) { return new RestApiImpl.RouteBuilderImpl(pathPattern); }
static HandlerConfigBuilder handlerConfig() { return new RestApiImpl.HandlerConfigBuilderImpl(); }
HttpResponse handleRequest(HttpRequest request);
ObjectMapper jacksonJsonMapper();
/** @see com.yahoo.container.jdisc.HttpRequestHandler#requestHandlerSpec() */
RequestHandlerSpec requestHandlerSpec();
interface Builder {
Builder setObjectMapper(ObjectMapper mapper);
Builder setDefaultRoute(RouteBuilder route);
Builder addRoute(RouteBuilder route);
Builder addFilter(Filter filter);
/** see {@link RestApiMappers#DEFAULT_EXCEPTION_MAPPERS} for default mappers */
<EXCEPTION extends RuntimeException> Builder addExceptionMapper(Class<EXCEPTION> type, ExceptionMapper<EXCEPTION> mapper);
/** see {@link RestApiMappers#DEFAULT_RESPONSE_MAPPERS} for default mappers */
<RESPONSE_ENTITY> Builder addResponseMapper(Class<RESPONSE_ENTITY> type, ResponseMapper<RESPONSE_ENTITY> mapper);
/** see {@link RestApiMappers#DEFAULT_REQUEST_MAPPERS} for default mappers */
<REQUEST_ENTITY> Builder addRequestMapper(Class<REQUEST_ENTITY> type, RequestMapper<REQUEST_ENTITY> mapper);
<RESPONSE_ENTITY> Builder registerJacksonResponseEntity(Class<RESPONSE_ENTITY> type);
<REQUEST_ENTITY> Builder registerJacksonRequestEntity(Class<REQUEST_ENTITY> type);
/** Disables mappers listed in {@link RestApiMappers#DEFAULT_EXCEPTION_MAPPERS} */
Builder disableDefaultExceptionMappers();
/** Disables mappers listed in {@link RestApiMappers#DEFAULT_RESPONSE_MAPPERS} */
Builder disableDefaultResponseMappers();
Builder disableDefaultAclMapping();
RestApi build();
}
interface RouteBuilder {
RouteBuilder name(String name);
RouteBuilder addFilter(Filter filter);
// GET
RouteBuilder get(Handler<?> handler);
RouteBuilder get(Handler<?> handler, HandlerConfigBuilder config);
// POST
RouteBuilder post(Handler<?> handler);
<REQUEST_ENTITY> RouteBuilder post(
Class<REQUEST_ENTITY> type, HandlerWithRequestEntity<REQUEST_ENTITY, ?> handler);
RouteBuilder post(Handler<?> handler, HandlerConfigBuilder config);
<REQUEST_ENTITY> RouteBuilder post(
Class<REQUEST_ENTITY> type, HandlerWithRequestEntity<REQUEST_ENTITY, ?> handler, HandlerConfigBuilder config);
// PUT
RouteBuilder put(Handler<?> handler);
<REQUEST_ENTITY> RouteBuilder put(
Class<REQUEST_ENTITY> type, HandlerWithRequestEntity<REQUEST_ENTITY, ?> handler);
RouteBuilder put(Handler<?> handler, HandlerConfigBuilder config);
<REQUEST_ENTITY> RouteBuilder put(
Class<REQUEST_ENTITY> type, HandlerWithRequestEntity<REQUEST_ENTITY, ?> handler, HandlerConfigBuilder config);
// DELETE
RouteBuilder delete(Handler<?> handler);
RouteBuilder delete(Handler<?> handler, HandlerConfigBuilder config);
// PATCH
RouteBuilder patch(Handler<?> handler);
<REQUEST_ENTITY> RouteBuilder patch(
Class<REQUEST_ENTITY> type, HandlerWithRequestEntity<REQUEST_ENTITY, ?> handler);
RouteBuilder patch(Handler<?> handler, HandlerConfigBuilder config);
<REQUEST_ENTITY> RouteBuilder patch(
Class<REQUEST_ENTITY> type, HandlerWithRequestEntity<REQUEST_ENTITY, ?> handler, HandlerConfigBuilder config);
// Default
RouteBuilder defaultHandler(Handler<?> handler);
RouteBuilder defaultHandler(Handler<?> handler, HandlerConfigBuilder config);
<REQUEST_ENTITY> RouteBuilder defaultHandler(
Class<REQUEST_ENTITY> type, HandlerWithRequestEntity<REQUEST_ENTITY, ?> handler);
<REQUEST_ENTITY> RouteBuilder defaultHandler(
Class<REQUEST_ENTITY> type, HandlerWithRequestEntity<REQUEST_ENTITY, ?> handler, HandlerConfigBuilder config);
}
@FunctionalInterface interface Handler<RESPONSE_ENTITY> {
RESPONSE_ENTITY handleRequest(RequestContext context) throws RestApiException;
}
@FunctionalInterface interface HandlerWithRequestEntity<REQUEST_ENTITY, RESPONSE_ENTITY> {
RESPONSE_ENTITY handleRequest(RequestContext context, REQUEST_ENTITY requestEntity) throws RestApiException;
}
@FunctionalInterface interface ExceptionMapper<EXCEPTION extends RuntimeException> { HttpResponse toResponse(RequestContext context, EXCEPTION exception); }
@FunctionalInterface interface ResponseMapper<RESPONSE_ENTITY> { HttpResponse toHttpResponse(RequestContext context, RESPONSE_ENTITY responseEntity) throws RestApiException; }
@FunctionalInterface interface RequestMapper<REQUEST_ENTITY> { Optional<REQUEST_ENTITY> toRequestEntity(RequestContext context) throws RestApiException; }
@FunctionalInterface interface Filter { HttpResponse filterRequest(FilterContext context); }
interface HandlerConfigBuilder {
HandlerConfigBuilder withReadAclAction();
HandlerConfigBuilder withWriteAclAction();
HandlerConfigBuilder withCustomAclAction(AclMapping.Action action);
}
interface RequestContext {
HttpRequest request();
PathParameters pathParameters();
QueryParameters queryParameters();
Headers headers();
Attributes attributes();
Optional<RequestContent> requestContent();
RequestContent requestContentOrThrow();
ObjectMapper jacksonJsonMapper();
/**
* Creates a URI builder pre-initialized with scheme, host and port.
* Intended for response generation (e.g for interactive REST APIs).
* DO NOT USE FOR CUSTOM ROUTING.
*/
UriBuilder uriBuilder();
AclMapping.Action aclAction();
Optional<Principal> userPrincipal();
Principal userPrincipalOrThrow();
interface Parameters {
Optional<String> getString(String name);
String getStringOrThrow(String name);
default Optional<Boolean> getBoolean(String name) { return getString(name).map(Boolean::valueOf);}
default boolean getBooleanOrThrow(String name) { return Boolean.parseBoolean(getStringOrThrow(name)); }
default OptionalLong getLong(String name) {
return getString(name).map(Long::parseLong).map(OptionalLong::of).orElseGet(OptionalLong::empty);
}
default long getLongOrThrow(String name) { return Long.parseLong(getStringOrThrow(name)); }
default OptionalDouble getDouble(String name) {
return getString(name).map(Double::parseDouble).map(OptionalDouble::of).orElseGet(OptionalDouble::empty);
}
default double getDoubleOrThrow(String name) { return Double.parseDouble(getStringOrThrow(name)); }
}
interface PathParameters extends Parameters {}
interface QueryParameters extends Parameters {
List<String> getStringList(String name);
}
interface Headers extends Parameters {}
interface Attributes {
Optional<Object> get(String name);
void set(String name, Object value);
}
interface RequestContent {
String contentType();
InputStream content();
}
}
interface FilterContext {
RequestContext requestContext();
String route();
HttpResponse executeNext();
}
}
|
package org.robovm.templater;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.robovm.compiler.config.Arch;
import org.robovm.compiler.config.Config;
import org.robovm.compiler.config.Config.TargetType;
import org.robovm.compiler.config.OS;
import org.robovm.compiler.config.Resource;
import org.robovm.compiler.log.ConsoleLogger;
import org.robovm.compiler.log.Logger;
/**
* The RoboVM {@code Templater} generates a new RoboVM project from a template.
*
* @author BlueRiver Interactive
*/
public class Templater {
private static final String PACKAGE_FOLDER_PLACEHOLDER = "__packageInPathFormat__";
private static final String MAIN_CLASS_FILE_PLACEHOLDER = "__mainClass__";
private static final List<String> SUBSTITUTED_PLACEHOLDER_FILES_EXTENSIONS = Arrays.asList("xml", "java");
private static final String DOLLAR_SYMBOL_PLACEHOLDER = Pattern.quote("${symbol_dollar}");
private static final String PACKAGE_PLACEHOLDER = Pattern.quote("package ${package};");
private static final String MAIN_CLASS_PLACEHOLDER = Pattern.quote("${mainClass}");
private static final String MAVEN_ARCHETYPE_SET_PLACEHOLDER = "#set\\(.*\\)\n";
private final Logger logger;
private final String template;
private final URL templateURL;
private String mainClass;
private String mainClassName;
private String packageName;
private String packageDirName;
private String appName;
private String appId;
private String executable;
public Templater(Logger logger, String template) {
if (logger == null) {
throw new NullPointerException("logger");
}
if (template == null) {
throw new NullPointerException("template");
}
this.logger = logger;
this.template = template;
templateURL = Templater.class.getResource("/templates/robovm-" + template + "-template.tar.gz");
if (templateURL == null) {
throw new IllegalArgumentException(String.format("Template with name '%s' doesn't exist!", template));
}
}
/**
* <p>
* Sets the main class for the generated project. This is the only required
* parameter. All other parameters will derive from this one if not
* explicitly specified.
* </p>
*
* Example: {@code com.company.app.MainClass}
*
* @param mainClass
* @return
*/
public Templater mainClass(String mainClass) {
this.mainClass = mainClass;
return this;
}
/**
* <p>
* Sets the package name for the generated project. Will derive from the
* main class name if not explicitly specified.
* </p>
*
* Example: {@code com.company.app}
*
* @param packageName
* @return
*/
public Templater packageName(String packageName) {
this.packageName = packageName;
return this;
}
/**
* <p>
* Sets the app name for the generated project. Will derive from the main
* class name if not explicitly specified.
* </p>
*
* Example: {@code MyApp}
*
* @param appName
* @return
*/
public Templater appName(String appName) {
this.appName = appName;
return this;
}
/**
* <p>
* Sets the app id for the generated project. Will derive from the main
* class name if not explicitly specified.
* </p>
*
* Example: {@code com.company.app}
*
* @param appId
* @return
*/
public Templater appId(String appId) {
this.appId = appId;
return this;
}
/**
* <p>
* Sets the executable name for the generated project. Will derive from the
* main class name if not explicitly specified.
* </p>
*
* Example: {@code MyApp}
*
* @param executable
* @return
*/
public Templater executable(String executable) {
this.executable = executable;
return this;
}
public void buildProject(File projectRoot) {
if (projectRoot == null) {
throw new NullPointerException("projectRoot");
}
if (mainClass == null) {
throw new IllegalArgumentException("No main class specified");
}
mainClassName = mainClass.substring(mainClass.lastIndexOf('.') + 1);
if (executable == null || executable.length() == 0) {
executable = mainClassName;
}
if (appName == null || appName.length() == 0) {
appName = mainClassName;
}
if (packageName == null || packageName.length() == 0) {
int index = mainClass.lastIndexOf('.');
if (index == -1) {
packageName = "";
} else {
packageName = mainClass.substring(0, index);
}
}
packageDirName = packageName.replaceAll("\\.", File.separator);
if (appId == null || appId.length() == 0) {
appId = packageName;
}
try {
File targetFile = new File(projectRoot, FilenameUtils.getBaseName(templateURL.getPath()));
FileUtils.copyURLToFile(templateURL, targetFile);
extractArchive(targetFile, targetFile.getParentFile());
targetFile.delete();
generateConfig(projectRoot);
} catch (IOException e) {
throw new Error(e);
}
logger.info("Project with template '%s' successfully created in: %s", template,
projectRoot.getAbsolutePath());
}
private void extractArchive(File archive, File destDir) throws IOException {
TarArchiveInputStream in = null;
try {
in = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(archive)));
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File f = new File(destDir, substitutePlaceholdersInFileName(entry.getName()));
if (entry.isDirectory()) {
f.mkdirs();
} else {
f.getParentFile().mkdirs();
OutputStream out = null;
try {
out = new FileOutputStream(f);
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(out);
}
substitutePlaceholdersInFile(f);
}
}
} finally {
IOUtils.closeQuietly(in);
}
}
private void generateConfig(File projectRoot) throws IOException {
File propsFile = new File(projectRoot, "robovm.properties");
File configFile = new File(projectRoot, "robovm.xml");
Properties props = new Properties();
Config.Builder configBuilder = new Config.Builder();
props.setProperty("app.mainclass", mainClass);
props.setProperty("app.name", appName);
props.setProperty("app.executable", mainClassName);
props.setProperty("app.id", appId);
props.setProperty("app.version", "1.0");
props.setProperty("app.build", "1");
File infoPList = new File(projectRoot, "Info.plist.xml");
File resources = new File(projectRoot, "resources");
resources.mkdirs();
configBuilder.os(OS.ios);
configBuilder.arch(Arch.thumbv7);
configBuilder.targetType(TargetType.ios);
configBuilder.mainClass("${app.mainclass}");
configBuilder.executableName("${app.executable}");
configBuilder.iosInfoPList(infoPList);
configBuilder.addResource(new Resource(resources, null));
configBuilder.write(configFile);
Writer writer = null;
try {
writer = new OutputStreamWriter(new FileOutputStream(propsFile));
props.store(writer, "");
} finally {
IOUtils.closeQuietly(writer);
}
}
private String substitutePlaceholdersInFileName(String fileName) {
fileName = fileName.replaceAll(PACKAGE_FOLDER_PLACEHOLDER, packageDirName);
fileName = fileName.replaceAll(MAIN_CLASS_FILE_PLACEHOLDER, mainClassName);
return fileName;
}
private void substitutePlaceholdersInFile(File file) throws IOException {
String extension = FilenameUtils.getExtension(file.getName());
if (SUBSTITUTED_PLACEHOLDER_FILES_EXTENSIONS.contains(extension)) {
String content = FileUtils.readFileToString(file, "UTF-8");
content = content.replaceAll(MAVEN_ARCHETYPE_SET_PLACEHOLDER, "");
content = content.replaceAll(DOLLAR_SYMBOL_PLACEHOLDER, Matcher.quoteReplacement("$"));
content = content.replaceAll(PACKAGE_PLACEHOLDER, getPackageNameReplacement(packageName));
content = content.replaceAll(MAIN_CLASS_PLACEHOLDER, mainClassName);
FileUtils.writeStringToFile(file, content, "UTF-8");
}
}
private static String getPackageNameReplacement(String packageName) {
if (packageName == null || packageName.length() == 0) {
return "";
}
return String.format("package %s;", packageName);
}
public static void main(String[] args) {
if (args.length <= 1) {
printHelpText();
return;
}
String template = null;
String mainClass = null;
String packageName = null;
String appName = null;
String appId = null;
String executable = null;
File projectRoot = null;
for (int i = 0; i < args.length; i += 2) {
if (isOption(args[i])) {
if (args[i].length() <= 1) {
throw new IllegalArgumentException("invalid option: " + args[i]);
}
char option = args[i].charAt(1);
switch (option) {
case 't': // template
template = getOptionValue(args, i);
break;
case 'c': // main class
mainClass = getOptionValue(args, i);
break;
case 'p': // package name
packageName = getOptionValue(args, i);
break;
case 'n': // app name
appName = getOptionValue(args, i);
break;
case 'i': // app id
appId = getOptionValue(args, i);
break;
case 'e': // executable name
executable = getOptionValue(args, i);
break;
case 'g': // generate
projectRoot = new File(getOptionValue(args, i));
break;
default:
// ignore
break;
}
} else {
printHelpText();
}
}
new Templater(new ConsoleLogger(true), template).mainClass(mainClass).packageName(packageName).appName(appName)
.appId(appId)
.executable(executable).buildProject(projectRoot);
}
private static boolean isOption(String arg) {
return arg.startsWith("-");
}
private static String getOptionValue(String[] args, int option) {
if (args.length < option + 1) {
throw new IllegalArgumentException("value missing for option: " + args[option]);
}
String value = args[option + 1];
if (isOption(value)) {
throw new IllegalArgumentException("illegal value for option: " + args[option]);
}
return value;
}
private static void printHelpText() {
System.out.println("RoboVM Templater\n"
+ "Generates a new RoboVM project from a template\n"
+ "Usage: templater\n"
+ "-t <TEMPLATE> template (required)\n"
+ "-c <CLASS> main class (required)\n"
+ "-p <PACKAGE> package name\n"
+ "-n <NAME> app name\n"
+ "-i <ID> app id\n"
+ "-e <EXECUTABLE> executable name\n"
+ "-g <PROJECT_ROOT> generates project to project root (required)");
}
}
|
package net.ripe.db.whois.common.rpsl;
import com.google.common.base.Charsets;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import net.ripe.db.whois.common.domain.CIString;
import org.apache.commons.lang3.Validate;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Immutable
public class RpslObject {
private final ObjectType type;
private final RpslAttribute typeAttribute;
private final CIString key;
private List<RpslAttribute> attributes;
private Map<AttributeType, List<RpslAttribute>> typeCache;
private int hash;
public RpslObject(final RpslObject oldObject, final List<RpslAttribute> attributes) {
this(attributes);
}
public RpslObject(final List<RpslAttribute> attributes) {
Validate.notEmpty(attributes);
this.typeAttribute = attributes.get(0);
this.type = ObjectType.getByName(typeAttribute.getKey());
this.attributes = Collections.unmodifiableList(attributes);
final Set<AttributeType> keyAttributes = ObjectTemplate.getTemplate(type).getKeyAttributes();
if (keyAttributes.size() == 1) {
this.key = getValueForAttribute(keyAttributes.iterator().next());
Validate.notEmpty(this.key.toString(), "key attributes must have value");
} else {
final StringBuilder keyBuilder = new StringBuilder(32);
for (AttributeType keyAttribute : keyAttributes) {
String key = getValueForAttribute(keyAttribute).toString();
Validate.notEmpty(key, "key attributes must have value");
keyBuilder.append(key);
}
this.key = CIString.ciString(keyBuilder.toString());
}
}
public static RpslObject parse(final String input) {
return new RpslObject(RpslObjectBuilder.getAttributes(input));
}
public static RpslObject parse(final byte[] input) {
return new RpslObject(RpslObjectBuilder.getAttributes(input));
}
public ObjectType getType() {
return type;
}
public List<RpslAttribute> getAttributes() {
return attributes;
}
public int size() {
return attributes.size();
}
public final CIString getKey() {
return key;
}
public String getFormattedKey() {
switch (type) {
case PERSON:
case ROLE:
return String.format("[%s] %s %s", type.getName(), getKey(), getAttributes().get(0).getCleanValue());
default:
return String.format("[%s] %s", type.getName(), getKey());
}
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof RpslObject)) {
return false;
}
final RpslObject other = (RpslObject) obj;
return Iterables.elementsEqual(getAttributes(), other.getAttributes());
}
@Override
public int hashCode() {
if (hash == 0) {
int result = getAttributes().hashCode();
if (result == 0) {
result
}
hash = result;
}
return hash;
}
public RpslAttribute getTypeAttribute() {
return getAttributes().get(0);
}
Map<AttributeType, List<RpslAttribute>> getOrCreateCache() {
if (typeCache == null) {
final EnumMap<AttributeType, List<RpslAttribute>> map = Maps.newEnumMap(AttributeType.class);
for (final RpslAttribute attribute : getAttributes()) {
final AttributeType attributeType = attribute.getType();
if (attributeType == null) {
continue;
}
List<RpslAttribute> list = map.get(attributeType);
if (list == null) {
list = Lists.newArrayList();
map.put(attributeType, list);
}
list.add(attribute);
}
typeCache = map;
}
return typeCache;
}
public RpslAttribute findAttribute(final AttributeType attributeType) {
final List<RpslAttribute> foundAttributes = findAttributes(attributeType);
switch (foundAttributes.size()) {
case 0:
throw new IllegalArgumentException("No " + attributeType + ": found in " + key);
case 1:
return foundAttributes.get(0);
default:
throw new IllegalArgumentException("Multiple " + attributeType + ": found in " + key);
}
}
public List<RpslAttribute> findAttributes(final AttributeType attributeType) {
final List<RpslAttribute> list = getOrCreateCache().get(attributeType);
return list == null ? Collections.<RpslAttribute>emptyList() : Collections.unmodifiableList(list);
}
public List<RpslAttribute> findAttributes(final Iterable<AttributeType> attributeTypes) {
final List<RpslAttribute> result = Lists.newArrayList();
for (final AttributeType attributeType : attributeTypes) {
findCachedAttributes(result, attributeType);
}
return result;
}
public List<RpslAttribute> findAttributes(final AttributeType... attributeTypes) {
return findAttributes(Arrays.asList(attributeTypes));
}
private void findCachedAttributes(final List<RpslAttribute> result, final AttributeType attributeType) {
final List<RpslAttribute> list = getOrCreateCache().get(attributeType);
if (list != null) {
result.addAll(list);
}
}
public boolean containsAttributes(final Collection<AttributeType> attributeTypes) {
for (AttributeType attributeType : attributeTypes) {
if (containsAttribute(attributeType)) {
return true;
}
}
return false;
}
public boolean containsAttribute(final AttributeType attributeType) {
return getOrCreateCache().containsKey(attributeType);
}
public void writeTo(final Writer writer) throws IOException {
for (final RpslAttribute attribute : getAttributes()) {
attribute.writeTo(writer);
}
writer.flush();
}
@Override
public String toString() {
try {
final StringWriter writer = new StringWriter();
for (final RpslAttribute attribute : getAttributes()) {
attribute.writeTo(writer);
}
return writer.toString();
} catch (IOException e) {
throw new IllegalStateException("Should never occur", e);
}
}
public CIString getValueForAttribute(final AttributeType attributeType) {
return findAttribute(attributeType).getCleanValue();
}
@Nullable
public CIString getValueOrNullForAttribute(final AttributeType attributeType) {
List<RpslAttribute> attributes = findAttributes(attributeType);
if (attributes.isEmpty()) {
return null;
}
return attributes.get(0).getCleanValue();
}
public Set<CIString> getValuesForAttribute(final AttributeType... attributeType) {
final Set<CIString> values = Sets.newLinkedHashSet();
for (AttributeType attrType : attributeType) {
final List<RpslAttribute> rpslAttributes = getOrCreateCache().get(attrType);
if (!rpslAttributes.isEmpty()) {
for (RpslAttribute rpslAttribute : rpslAttributes) {
values.addAll(rpslAttribute.getCleanValues());
}
}
}
return values;
}
}
|
package net.snowflake.client.util;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import net.snowflake.client.log.SFLogger;
import net.snowflake.client.log.SFLoggerFactory;
/** Search for credentials in sql and/or other text */
public class SecretDetector {
// We look for long base64 encoded (and perhaps also URL encoded - hence the
// '%' character in the regex) strings.
// This will match some things that it shouldn't. The minimum number of
// characters is essentially a random choice - long enough to not mask other
// strings but not so long that it might miss things.
private static final Pattern GENERIC_CREDS_PATTERN =
Pattern.compile("([a-z0-9+/%]{18,})", Pattern.CASE_INSENSITIVE);
// "\\s*" refers to >= 0 spaces, "[^']" refers to chars other than `'`
private static final Pattern AWS_KEY_PATTERN =
Pattern.compile(
"(aws_key_id|aws_secret_key|access_key_id|secret_access_key)(\\s*=\\s*)'([^']+)'",
Pattern.CASE_INSENSITIVE);
// Used for detecting tokens in serialized JSON
private static final Pattern AWS_TOKEN_PATTERN =
Pattern.compile(
"(accessToken|tempToken|keySecret)\"\\s*:\\s*\"([a-z0-9/+]{32,}={0,2})\"",
Pattern.CASE_INSENSITIVE);
// Signature added in the query string of a URL in SAS based authentication
// for S3 or Azure Storage requests
private static final Pattern SAS_TOKEN_PATTERN =
Pattern.compile(
"(sig|signature|AWSAccessKeyId|password|passcode)=([a-z0-9%/+]{16,})",
Pattern.CASE_INSENSITIVE);
// Search for password pattern
private static final Pattern PASSWORD_PATTERN =
Pattern.compile(
"(password|passcode|pwd)"
+ "([\'\"\\s:=]+)"
+ "([a-z0-9!\"
Pattern.CASE_INSENSITIVE);
private static final Pattern PRIVATE_KEY_PATTERN =
Pattern.compile(
"
Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
// "privateKeyData": "[PRIVATE-KEY]"
private static final Pattern PRIVATE_KEY_DATA_PATTERN =
Pattern.compile(
"\"privateKeyData\": \"([a-z0-9/+=\\\\n]{10,})\"",
Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
private static final Pattern CONNECTION_TOKEN_PATTERN =
Pattern.compile(
"(token|assertion content)" + "(['\"\\s:=]+)" + "([a-z0-9=/_\\-+]{8,})",
Pattern.CASE_INSENSITIVE);
private static final int LOOK_AHEAD = 10;
// only attempt to find secrets in its leading 100Kb SNOW-30961
private static final int MAX_LENGTH = 100 * 1000;
private static final SFLogger LOGGER = SFLoggerFactory.getLogger(SecretDetector.class);
private static String[] SENSITIVE_NAMES = {
"access_key_id",
"accesstoken",
"aws_key_id",
"aws_secret_key",
"awsaccesskeyid",
"keysecret",
"passcode",
"password",
"privatekey",
"privatekeydata",
"secret_access_key",
"sig",
"signature",
"temptoken",
};
private static Set<String> SENSITIVE_NAME_SET = new HashSet<>(Arrays.asList(SENSITIVE_NAMES));
/**
* Check whether the name is sensitive
*
* @param name
*/
public static boolean isSensitive(String name) {
return SENSITIVE_NAME_SET.contains(name.toLowerCase());
}
/**
* Determine whether a connection parameter should be masked if parameter values are being
* printed. Sensitive parameters include passwords and token values. Helper function for
* maskParameterValue().
*
* @param name of the parameter
* @return true if the parameter should be masked
*/
private static boolean isSensitiveParameter(String name) {
Pattern PASSWORD_IN_NAME =
Pattern.compile(".*?(password|pwd|token|proxyuser).*?", Pattern.CASE_INSENSITIVE);
Matcher matcher = PASSWORD_IN_NAME.matcher(name);
return isSensitive(name) || matcher.matches();
}
/**
* Mask sensitive parameter values. Used currently for connection parameters whose values are to
* be recorded for each session.
*
* @param key parameter key
* @param value parameter value, which is sometimes masked
* @return the original value if the parameter key does not mark it as sensitive, or return a
* masked text if the key is determined to be sensitive.
*/
public static String maskParameterValue(String key, String value) {
if (isSensitiveParameter(key)) {
return "****";
}
return value;
}
private static String filterAWSKeys(String text) {
Matcher matcher =
AWS_KEY_PATTERN.matcher(text.length() <= MAX_LENGTH ? text : text.substring(0, MAX_LENGTH));
if (matcher.find()) {
return matcher.replaceAll("$1$2'****'");
}
return text;
}
private static String filterGenericSecret(String text) {
Matcher matcher =
GENERIC_CREDS_PATTERN.matcher(
text.length() <= MAX_LENGTH ? text : text.substring(0, MAX_LENGTH));
if (matcher.find()) {
return matcher.replaceAll("****");
}
return text;
}
private static String filterSASTokens(String text) {
Matcher matcher =
SAS_TOKEN_PATTERN.matcher(
text.length() <= MAX_LENGTH ? text : text.substring(0, MAX_LENGTH));
if (matcher.find()) {
return matcher.replaceAll("$1=****");
}
return text;
}
private static String filterPassword(String text) {
Matcher matcher =
PASSWORD_PATTERN.matcher(
text.length() <= MAX_LENGTH ? text : text.substring(0, MAX_LENGTH));
if (matcher.find()) {
return matcher.replaceAll("$1$2**** ");
}
return text;
}
private static String filterConnectionTokens(String text) {
Matcher matcher =
CONNECTION_TOKEN_PATTERN.matcher(
text.length() <= MAX_LENGTH ? text : text.substring(0, MAX_LENGTH));
if (matcher.find()) {
return matcher.replaceAll("$1$2****");
}
return text;
}
/**
* mask AWS secret in the input string
*
* @param sql The sql text to mask
* @return masked string
*/
public static String maskAWSSecret(String sql) {
return filterAWSKeys(sql);
}
/**
* Masks SAS token(s) in the input string
*
* @param text Text which may contain SAS token(s)
* @return Masked string
*/
public static String maskSASToken(String text) {
return filterSASTokens(text);
}
/**
* Masks any secrets present in the input string. This currently checks for SAS tokens ({@link
* SecretDetector#maskSASToken(String)}) and AWS keys ({@link
* SecretDetector#maskAWSSecret(String)}.
*
* @param text Text which may contain secrets
* @return Masked string
*/
public static String maskSecrets(String text) {
return filterAccessTokens(
filterConnectionTokens(filterPassword(filterSASTokens(filterAWSKeys(text)))));
}
/**
* Filter access tokens that might be buried in JSON. Currently only used to filter the
* scopedCreds passed for XP binary downloads
*
* @param message the message text which may contain secrets
* @return Return filtered message
*/
public static String filterAccessTokens(String message) {
Matcher awsMatcher = AWS_TOKEN_PATTERN.matcher(message);
// aws
if (awsMatcher.find()) {
message = awsMatcher.replaceAll("$1\":\"XXXX\"");
}
// azure
Matcher azureMatcher = SAS_TOKEN_PATTERN.matcher(message);
if (azureMatcher.find()) {
message = azureMatcher.replaceAll("$1=XXXX");
}
// GCS
Matcher gcsMatcher = PRIVATE_KEY_PATTERN.matcher(message);
if (gcsMatcher.find()) {
message =
gcsMatcher.replaceAll(
"
}
gcsMatcher = PRIVATE_KEY_DATA_PATTERN.matcher(message);
if (gcsMatcher.find()) {
message = gcsMatcher.replaceAll("\"privateKeyData\": \"XXXX\"");
}
return message;
}
public static JSONObject maskJsonObject(JSONObject json) {
for (Map.Entry<String, Object> entry : json.entrySet()) {
if (entry.getValue() instanceof String) {
entry.setValue(maskSecrets((String) entry.getValue()));
} else if (entry.getValue() instanceof JSONArray) {
maskJsonArray((JSONArray) entry.getValue());
} else if (entry.getValue() instanceof JSONObject) {
maskJsonObject((JSONObject) entry.getValue());
}
}
return json;
}
public static JSONArray maskJsonArray(JSONArray array) {
for (int i = 0; i < array.size(); i++) {
Object node = array.get(i);
if (node instanceof JSONObject) {
maskJsonObject((JSONObject) node);
} else if (node instanceof JSONArray) {
maskJsonArray((JSONArray) node);
} else if (node instanceof String) {
array.set(i, SecretDetector.maskSecrets((String) node));
}
// for other types, we can just leave it untouched
}
return array;
}
public static JsonNode maskJacksonNode(JsonNode node) {
if (node.isTextual()) {
String maskedText = SecretDetector.maskSecrets(node.textValue());
if (!maskedText.equals(node.textValue())) {
return new TextNode(maskedText);
}
} else if (node.isObject()) {
ObjectNode objNode = (ObjectNode) node;
Iterator<String> fieldNames = objNode.fieldNames();
while (fieldNames.hasNext()) {
String fieldName = fieldNames.next();
JsonNode tmpNode = maskJacksonNode(objNode.get(fieldName));
if (objNode.get(fieldName).isTextual()) {
objNode.set(fieldName, tmpNode);
}
}
} else if (node.isArray()) {
ArrayNode arrayNode = (ArrayNode) node;
for (int i = 0; i < arrayNode.size(); i++) {
JsonNode tmpNode = maskJacksonNode(arrayNode.get(i));
if (arrayNode.get(i).isTextual()) {
arrayNode.set(i, tmpNode);
}
}
}
return node;
}
}
|
package nl.hsac.fitnesse.fixture.util;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.util.Map;
/**
* Helper to make Http calls and get response.
*/
public class HttpClient {
private final static org.apache.http.client.HttpClient HTTP_CLIENT;
static {
HTTP_CLIENT = HttpClients.custom()
.useSystemProperties()
.disableContentCompression()
.setUserAgent(HttpClient.class.getName())
.build();
}
/**
* @param url URL of service
* @param response response pre-populated with request to send. Response content and
* statusCode will be filled.
* @param headers http headers to add
* @param type contentType for request.
*/
public void post(String url, HttpResponse response, Map<String, Object> headers, String type) {
HttpPost methodPost = new HttpPost(url);
ContentType contentType = ContentType.parse(type);
HttpEntity ent = new StringEntity(response.getRequest(), contentType);
methodPost.setEntity(ent);
getResponse(url, response, methodPost, headers);
}
/**
* Posts file as 'application/octet-stream'.
* @param url URL of service
* @param response response pre-populated with request to send. Response content and
* statusCode will be filled.
* @param headers http headers to add
* @param file file containing binary data to post.
*/
public void post(String url, HttpResponse response, Map<String, Object> headers, File file) {
HttpPost methodPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody(file.getName(), file,
ContentType.APPLICATION_OCTET_STREAM, file.getName());
HttpEntity multipart = builder.build();
methodPost.setEntity(multipart);
getResponse(url, response, methodPost, headers);
}
/**
* @param url URL of service
* @param response response pre-populated with request to send. Response content and
* statusCode will be filled.
* @param headers http headers to add
* @param type contentType for request.
*/
public void put(String url, HttpResponse response, Map<String, Object> headers, String type) {
HttpPut methodPut = new HttpPut(url);
ContentType contentType = ContentType.parse(type);
HttpEntity ent = new StringEntity(response.getRequest(), contentType);
methodPut.setEntity(ent);
getResponse(url, response, methodPut, headers);
}
/**
* @param url URL of service
* @param response response to be filled.
* @param headers http headers to add
*/
public void get(String url, HttpResponse response, Map<String, Object> headers, boolean followRedirect) {
HttpGet method = new HttpGet(url);
if (!followRedirect) {
RequestConfig r = RequestConfig.copy(RequestConfig.DEFAULT)
.setRedirectsEnabled(false)
.build();
method.setConfig(r);
}
getResponse(url, response, method, headers);
}
/**
* @param url URL to send to DELETE to
* @param response response to be filled.
* @param headers headers to add.
*/
public void delete(String url, HttpResponse response, Map<String, Object> headers) {
HttpDelete method = new HttpDelete(url);
getResponse(url, response, method, headers);
}
protected void getResponse(String url, HttpResponse response, HttpRequestBase method, Map<String, Object> headers) {
long startTime = 0;
long endTime = -1;
try {
if (headers != null) {
for (String key : headers.keySet()) {
Object value = headers.get(key);
if (value != null) {
method.setHeader(key, value.toString());
}
}
}
org.apache.http.HttpResponse resp;
CookieStore store = response.getCookieStore();
startTime = currentTimeMillis();
if (store == null) {
resp = getHttpResponse(url, method);
} else {
resp = getHttpResponse(store, url, method);
}
endTime = currentTimeMillis();
int returnCode = resp.getStatusLine().getStatusCode();
response.setStatusCode(returnCode);
HttpEntity entity = resp.getEntity();
copyHeaders(response.getResponseHeaders(), resp.getAllHeaders());
if (entity == null) {
response.setResponse(null);
} else {
if (response instanceof BinaryHttpResponse) {
BinaryHttpResponse binaryHttpResponse = (BinaryHttpResponse) response;
byte[] content = EntityUtils.toByteArray(entity);
binaryHttpResponse.setResponseContent(content);
String fileName = getAttachmentFileName(resp);
binaryHttpResponse.setFileName(fileName);
} else {
String result = EntityUtils.toString(entity);
response.setResponse(result);
}
}
} catch (Exception e) {
throw new RuntimeException("Unable to get response from: " + url, e);
} finally {
if (startTime > 0) {
if (endTime < 0) {
endTime = currentTimeMillis();
}
}
response.setResponseTime(endTime - startTime);
method.reset();
}
}
protected void copyHeaders(Map<String, Object> responseHeaders, Header[] respHeaders) {
for (Header h : respHeaders) {
String headerName = h.getName();
String headerValue = h.getValue();
responseHeaders.put(headerName, headerValue);
}
}
private String getAttachmentFileName(org.apache.http.HttpResponse resp) {
String fileName = null;
Header[] contentDisp = resp.getHeaders("content-disposition");
if (contentDisp != null && contentDisp.length > 0) {
HeaderElement[] headerElements = contentDisp[0].getElements();
if (headerElements != null) {
for (HeaderElement headerElement : headerElements) {
if ("attachment".equals(headerElement.getName())) {
NameValuePair param = headerElement.getParameterByName("filename");
if (param != null) {
fileName = param.getValue();
break;
}
}
}
}
}
return fileName;
}
protected org.apache.http.HttpResponse getHttpResponse(CookieStore store, String url, HttpRequestBase method) throws IOException {
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, store);
return HTTP_CLIENT.execute(method, localContext);
}
protected org.apache.http.HttpResponse getHttpResponse(String url, HttpRequestBase method) throws IOException {
return HTTP_CLIENT.execute(method);
}
protected long currentTimeMillis() {
return System.currentTimeMillis();
}
}
|
package io.hawt;
import io.hawt.jmx.JmxTreeWatcher;
import io.hawt.jmx.PluginRegistry;
import io.hawt.jmx.UploadManager;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* A {@link javax.servlet.ServletContextListener} which initialises key hawtio services in the webapp
*/
public class HawtioContextListener implements ServletContextListener {
private JmxTreeWatcher treeWatcher = new JmxTreeWatcher();
private PluginRegistry registry = new PluginRegistry();
private UploadManager uploadManager = new UploadManager();
public void contextInitialized(ServletContextEvent servletContextEvent) {
String realm = System.getProperty("hawtio.realm", "karaf");
String role = System.getProperty("hawtio.role", "admin");
//String rolePrincipalClasses = System.getProperty("hawtio.rolePrincipalClasses", "org.apache.karaf.jaas.boot.principal.RolePrincipal,org.apache.karaf.jaas.modules.RolePrincipal");
String rolePrincipalClasses = System.getProperty("hawtio.rolePrincipalClasses", "");
Boolean authEnabled = Boolean.valueOf(System.getProperty("hawtio.authenticationEnabled", "true"));
servletContextEvent.getServletContext().setAttribute("realm", realm);
servletContextEvent.getServletContext().setAttribute("role", role);
servletContextEvent.getServletContext().setAttribute("rolePrincipalClasses", rolePrincipalClasses);
servletContextEvent.getServletContext().setAttribute("authEnabled", authEnabled);
try {
treeWatcher.init();
registry.init();
uploadManager.init();
} catch (Exception e) {
throw createServletException(e);
}
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
try {
treeWatcher.destroy();
registry.destroy();
uploadManager.destroy();
} catch (Exception e) {
throw createServletException(e);
}
}
protected RuntimeException createServletException(Exception e) {
return new RuntimeException(e);
}
}
|
package org.usfirst.frc.team997.robot.commands;
import org.usfirst.frc.team997.robot.Robot;
import edu.wpi.first.wpilibj.command.Command;
public class ArcadeDrive extends Command {
public ArcadeDrive() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
requires(Robot.driveTrain);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
//leftstick moves up than motors dance on forward
//leftstick moves down than motors fall and die backwards
//rightstick moves to the left left motor tapdances back and right motor dies forward
//rightstick moves to the right leftmotor spazzes forward and right motor sings backwords
//leftstick and right are falling all the way forward and left - left motor will be full speed and rightmotor at slowish speed
//leftstick and right are falling all the way forward and right - leftmotor will be slowish and right motor at full speed
double getArcadeleftspeed
= deadBand(Robot.oi.lefty() + Robot.oi.rightx());
double getArcaderightspeed
= deadBand(Robot.oi.lefty() - Robot.oi.rightx());
Robot.driveTrain.driveVoltage(getArcadeleftspeed,getArcaderightspeed);
}
private double deadBand(double a) {
if(Math.abs(a)>0.15) {
return a;
} else {
return 0;
}
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
Robot.drivetrain.driveVoltage(0,0);
}
}
|
package org.jooq.example.runner;
import org.jooq.example.app.BookLookup;
import org.jooq.example.common.DbInfo;
import org.jooq.example.migrator.Migrator;
public class Runner {
private final DbInfo dbInfo;
public Runner(DbInfo dbInfo) {
this.dbInfo = dbInfo;
}
public static void main(String[] args) {
new Runner(new DbInfo("jdbc:h2:~/h2testDb", "sa", "")).start();
}
public void start() {
new Migrator(dbInfo).migrate();
int nbOfResults = 10;
System.out.println("The first " + nbOfResults + " titles are:");
new BookLookup(dbInfo).getBooksNames(0, nbOfResults).forEach(System.out::println);
}
}
|
package com.exedio.cope;
public class TypeInConditionTest extends AbstractLibTest
{
public TypeInConditionTest()
{
super(Main.typeInConditionModel);
}
TypeInConditionAItem itema;
TypeInConditionB1Item itemb1;
TypeInConditionB2Item itemb2;
TypeInConditionC1Item itemc1;
TypeInConditionRefItem reffa;
TypeInConditionRefItem reffb1;
TypeInConditionRefItem reffb2;
TypeInConditionRefItem reffc1;
@Override
public void setUp() throws Exception
{
super.setUp();
deleteOnTearDown(itema = new TypeInConditionAItem("itema"));
deleteOnTearDown(itemb1 = new TypeInConditionB1Item("itemb1"));
deleteOnTearDown(itemb2 = new TypeInConditionB2Item("itemb2"));
deleteOnTearDown(itemc1 = new TypeInConditionC1Item("itemc1"));
deleteOnTearDown(reffa = new TypeInConditionRefItem(itema));
deleteOnTearDown(reffb1 = new TypeInConditionRefItem(itemb1));
deleteOnTearDown(reffb2 = new TypeInConditionRefItem(itemb2));
deleteOnTearDown(reffc1 = new TypeInConditionRefItem(itemc1));
}
public void testIt()
{
assertContains(itema, itemb1, itemb2, itemc1, itema.TYPE.search(null));
assertContains(reffa, reffb1, reffb2, reffc1, reffa.TYPE.search(null));
assertContains(itema, itemb1, itemb2, itema.TYPE.search(itema.TYPE.getThis().typeNotIn(itemc1.TYPE)));
assertContains(itema, itemb2, itema.TYPE.search(itema.TYPE.getThis().typeNotIn(itemb1.TYPE)));
assertContains(itema, itemb2, itema.TYPE.search(itema.TYPE.getThis().typeNotIn(itemb1.TYPE, itemc1.TYPE)));
assertContains(itema, itemb1, itemc1, itema.TYPE.search(itema.TYPE.getThis().typeNotIn(itemb2.TYPE)));
assertContains(itema, itemb1, itema.TYPE.search(itema.TYPE.getThis().typeNotIn(itemb2.TYPE, itemc1.TYPE)));
assertContains(itema.TYPE.search(itema.TYPE.getThis().typeNotIn(itema.TYPE)));
assertContains(itema.TYPE.search(itema.TYPE.getThis().typeNotIn(new Type[]{itema.TYPE, itemb1.TYPE, itemb2.TYPE, itemc1.TYPE})));
assertContains(itemc1, itema.TYPE.search(itema.TYPE.getThis().typeIn(itemc1.TYPE)));
assertContains(reffa, reffb1, reffb2, reffa.TYPE.search(reffa.ref.typeNotIn(itemc1.TYPE)));
assertContains(reffa, reffb2, reffa.TYPE.search(reffa.ref.typeNotIn(itemb1.TYPE)));
assertContains(reffa, reffb2, reffa.TYPE.search(reffa.ref.typeNotIn(itemb1.TYPE, itemc1.TYPE)));
assertContains(reffa, reffb1, reffc1, reffa.TYPE.search(reffa.ref.typeNotIn(itemb2.TYPE)));
assertContains(reffa, reffb1, reffa.TYPE.search(reffa.ref.typeNotIn(itemb2.TYPE, itemc1.TYPE)));
assertContains(reffa.TYPE.search(reffa.ref.typeNotIn(itema.TYPE)));
assertContains(reffa.TYPE.search(reffa.ref.typeNotIn(new Type[]{itema.TYPE, itemb1.TYPE, itemb2.TYPE, itemc1.TYPE})));
assertContains(reffc1, reffa.TYPE.search(reffa.ref.typeIn(itemc1.TYPE)));
model.checkTypeColumns();
System.out.println("
// test self joins and inheritance
{
itemc1.setTextc1("textC1");
final Query<TypeInConditionC1Item> q = itemc1.TYPE.newQuery(itemc1.code.equal("itemc1"));
final Join j = q.join(itemc1.TYPE);
j.setCondition(new JoinedFunction<String>(itemc1.textc1, j).equal(itemc1.textc1));
assertContains(itemc1, q.search());
}
if(!hsqldb&&!oracle&&!((String)model.getDatabaseInfo().get("database.version")).endsWith("(5.0)")) // TODO dont know why
{
final Query<TypeInConditionC1Item> q = itemc1.TYPE.newQuery(itemc1.code.equal("itemc1"));
final Join j = q.join(itemb2.TYPE);
j.setCondition(new JoinedFunction<String>(itemc1.code, j).equal(itemb2.code));
assertContains(q.search());
}
if(!hsqldb&&!oracle) // TODO dont know why
{
final Query<TypeInConditionC1Item> q = itemc1.TYPE.newQuery(itemc1.code.equal("itemc1").and(itemb1.TYPE.getThis().typeNotIn(itemc1.TYPE)));
q.join(itemb2.TYPE);
assertContains(q.search());
}
{
final Query<TypeInConditionC1Item> q = itemc1.TYPE.newQuery(itemc1.code.equal("itemc1"));
final Join j = q.join(itemb2.TYPE);
j.setCondition(itemb1.TYPE.getThis().typeNotIn(itemc1.TYPE));
assertContains(q.search());
}
if(!hsqldb&&!oracle) // TODO dont know why
{
final Query<TypeInConditionC1Item> q = itemc1.TYPE.newQuery(itemc1.code.equal("itemc1").and(itema.TYPE.getThis().typeNotIn(itemc1.TYPE)));
q.join(itemb2.TYPE);
assertContains(q.search());
}
{
final Query<TypeInConditionC1Item> q = itemc1.TYPE.newQuery(itemc1.code.equal("itemc1"));
final Join j = q.join(itemb2.TYPE);
j.setCondition(itema.TYPE.getThis().typeNotIn(itemc1.TYPE));
assertContains(q.search());
}
}
@SuppressWarnings("unchecked") // OK: test bad API usage
public void testUnchecked()
{
try
{
itemb2.TYPE.search(itemb2.TYPE.getThis().typeNotIn((Type)itemb1.TYPE));
fail();
}
catch(RuntimeException e)
{
assertEquals("type TypeInConditionB2Item has no subtypes, therefore a TypeInCondition makes no sense", e.getMessage());
}
try
{
itemb1.TYPE.search(itemb1.TYPE.getThis().typeNotIn((Type)itema.TYPE));
fail();
}
catch(RuntimeException e)
{
assertEquals("type TypeInConditionB1Item is not assignable from type TypeInConditionAItem", e.getMessage());
}
}
}
|
package org.jetel.component;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.DataRecord;
import org.jetel.data.Defaults;
import org.jetel.data.HashKey;
import org.jetel.data.RecordKey;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.graph.InputPort;
import org.jetel.graph.Node;
import org.jetel.graph.OutputPort;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.ComponentXMLAttributes;
import org.jetel.util.DuplicateKeyMap;
import org.jetel.util.SynchronizeUtils;
import org.w3c.dom.Element;
/**
* <h3>HashJoin Component</h3> <!-- Joins two records from two different
* input flows based on specified key. The flow on port 0 is the driver, the flow
* on port 1 is the slave. First, all records from slave flow are read and stored in
* hash table. Then for every record from driver flow, corresponding record from
* slave flow is looked up (if it exists) -->
*
*<table border="1">
*
* <th>
* Component:
* </th>
* <tr><td>
* <h4><i>Name:</i> </h4></td><td>HashJoin</td>
* </tr>
* <tr><td><h4><i>Category:</i> </h4></td><td></td>
* </tr>
* <tr><td><h4><i>Description:</i> </h4></td>
* <td>
* Joins records on input ports. It expects that on port [0], there is a
* driver and on port [1] is a slave<br>
* For each driver record, slave record is looked up in Hashtable which is created
* from all records on slave port.
* Pair of driver and slave records is sent to transformation class.<br>
* The method <i>transform</i> is called for every pair of driver&s;slave.<br>
* It skips driver records for which there is no corresponding slave - unless outer
* join is specified, when only driver record is passed to <i>transform</i> method.<br>
* In this case be sure, that your transform code is prepared processe null input records.
* Hash join does not require input data be sorted. But it spends some time at the beginning
* initializing hashtable of slave records.
* It is generally good idea to specify how many records are expected to be stored in hashtable, especially
* when you expect the number to be really great. It is better to specify slightly greater number to ensure
* that rehashing won't occure. For small record sets - up to 512 records, there is no need to specify the
* size.
* </td>
* </tr>
* <tr><td><h4><i>Inputs:</i> </h4></td>
* <td>
* [0] - driver records<br>
* [1] - slave records<br>
* </td></tr>
* <tr><td> <h4><i>Outputs:</i> </h4>
* </td>
* <td>
* [0] - one output port
* </td></tr>
* <tr><td><h4><i>Comment:</i> </h4>
* </td>
* <td></td>
* </tr>
* </table>
* <br>
* <table border="1">
* <th>XML attributes:</th>
* <tr><td><b>type</b></td><td>"HASH_JOIN"</td></tr>
* <tr><td><b>id</b></td><td>component identification</td></tr>
* <tr><td><b>joinKey</b></td><td>field names separated by :;| {colon, semicolon, pipe}</td></tr>
* <tr><td><b>slaveOverrideKey</b><br><i>optional</i></td><td>field names separated by :;| {colon, semicolon, pipe}</td></tr>
* <tr><td><b>libraryPath</b><br><i>optional</i></td><td>name of Java library file (.jar,.zip,...) where
* to search for class to be used for transforming joined data specified in <tt>transformClass<tt> parameter.</td></tr>
* <tr><td><b>transform</b></td><td>contains definition of transformation in internal clover format </td>
* <tr><td><b>transformClass</b><br><i>optional</i></td><td>name of the class to be used for transforming joined data<br>
* If no class name is specified then it is expected that the transformation Java source code is embedded in XML - <i>see example
* below</i></td></tr>
* <tr><td><b>leftOuterJoin</b><br><i>optional</i></td><td>true/false See description of the HashJoin component.</td></tr>
* <tr><td><b>hashTableSize</b><br><i>optional</i></td><td>how many records are expected (roughly) to be in hashtable.</td></tr>
* <tr><td><b>slaveDuplicates</b><br><i>optional</i></td><td>true/false - allow records on slave port with duplicate keys. Default is false - multiple
* duplicate records are discarded - only the last one read from port stays.</td></tr>
* </table>
* <h4>Example:</h4> <pre><Node id="JOIN" type="HASH_JOIN" joinKey="CustomerID" transformClass="org.jetel.test.reformatOrders"/></pre>
*
*<pre><Node id="JOIN" type="HASH_JOIN" joinKey="EmployeeID" leftOuterJoin="false">
*import org.jetel.component.DataRecordTransform;
*import org.jetel.data.*;
*
*public class reformatJoinTest extends DataRecordTransform{
*
* public boolean transform(DataRecord[] source, DataRecord[] target){
*
* target[0].getField(0).setValue(source[0].getField(0).getValue());
* target[0].getField(1).setValue(source[0].getField(1).getValue());
* target[0].getField(2).setValue(source[0].getField(2).getValue());
* if (source[1]!=null){
* target[0].getField(3).setValue(source[1].getField(0).getValue());
* target[0].getField(4).setValue(source[1].getField(1).getValue());
* }
* return true;
* }
*}
*
*</Node></pre>
*
* @author dpavlis
* @since March 09, 2004
* @revision $Revision$
* @created 09. March 2004
*/
public class HashJoin extends Node {
private static final String XML_HASHTABLESIZE_ATTRIBUTE = "hashTableSize";
private static final String XML_LEFTOUTERJOIN_ATTRIBUTE = "leftOuterJoin";
private static final String XML_SLAVEOVERRIDEKEY_ATTRIBUTE = "slaveOverrideKey";
private static final String XML_JOINKEY_ATTRIBUTE = "joinKey";
private static final String XML_TRANSFORMCLASS_ATTRIBUTE = "transformClass";
private static final String XML_TRANSFORM_ATTRIBUTE = "transform";
private static final String XML_ALLOW_SLAVE_DUPLICATES_ATTRIBUTE ="slaveDuplicates";
/** Description of the Field */
public final static String COMPONENT_TYPE = "HASH_JOIN";
private final static int DEFAULT_HASH_TABLE_INITIAL_CAPACITY = 512;
private final static int WRITE_TO_PORT = 0;
private final static int DRIVER_ON_PORT = 0;
private final static int SLAVE_ON_PORT = 1;
private String transformClassName;
private RecordTransform transformation = null;
private String transformSource = null;
private boolean leftOuterJoin;
private boolean slaveDuplicates=false;
private String[] joinKeys;
private String[] slaveOverrideKeys = null;
private RecordKey driverKey;
private RecordKey slaveKey;
private Map hashMap;
private int hashTableInitialCapacity;
private Properties transformationParameters;
static Log logger = LogFactory.getLog(HashJoin.class);
/**
*Constructor for the HashJoin object
*
* @param id Description of the Parameter
* @param joinKeys Description of the Parameter
* @param transformClass Description of the Parameter
* @param leftOuterJoin Description of the Parameter
*/
public HashJoin(String id, String[] joinKeys, String transform,
String transformClass, boolean leftOuterJoin) {
super(id);
this.joinKeys = joinKeys;
this.transformSource =transform;
this.transformClassName = transformClass;
this.leftOuterJoin = leftOuterJoin;
this.hashTableInitialCapacity = DEFAULT_HASH_TABLE_INITIAL_CAPACITY;
}
// /**
// * Sets the leftOuterJoin attribute of the HashJoin object
// *
// * @param outerJoin The new leftOuterJoin value
// */
// public void setLeftOuterJoin(boolean outerJoin) {
// leftOuterJoin = outerJoin;
/**
* Sets the slaveOverrideKey attribute of the HashJoin object
*
* @param slaveKeys The new slaveOverrideKey value
*/
public void setSlaveOverrideKey(String[] slaveKeys) {
this.slaveOverrideKeys = slaveKeys;
}
/**
* Sets the hashTableInitialCapacity attribute of the HashJoin object
*
* @param capacity The new hashTableInitialCapacity value
*/
public void setHashTableInitialCapacity(int capacity) {
if (capacity > DEFAULT_HASH_TABLE_INITIAL_CAPACITY) {
hashTableInitialCapacity = capacity;
}
}
/**
* Description of the Method
*
* @exception ComponentNotReadyException
* Description of the Exception
*/
public void init() throws ComponentNotReadyException {
// test that we have at least one input port and one output
if (inPorts.size() < 2) {
throw new ComponentNotReadyException(
"At least two input ports have to be defined!");
} else if (outPorts.size() < 1) {
throw new ComponentNotReadyException(
"At least one output port has to be defined!");
}
if (slaveOverrideKeys == null) {
slaveOverrideKeys = joinKeys;
}
(driverKey = new RecordKey(joinKeys, getInputPort(DRIVER_ON_PORT)
.getMetadata())).init();
(slaveKey = new RecordKey(slaveOverrideKeys,
getInputPort(SLAVE_ON_PORT).getMetadata())).init();
// allocate HashMap
try {
hashMap = new HashMap(hashTableInitialCapacity);
if (slaveDuplicates)
hashMap = new DuplicateKeyMap(hashMap);
} catch (OutOfMemoryError ex) {
logger.fatal(ex);
} finally {
if (hashMap == null) {
throw new ComponentNotReadyException(
"Can't allocate HashMap of size: "
+ hashTableInitialCapacity);
}
}
// init transformation
DataRecordMetadata[] inMetadata = (DataRecordMetadata[]) getInMetadata()
.toArray(new DataRecordMetadata[0]);
DataRecordMetadata[] outMetadata = new DataRecordMetadata[] { getOutputPort(
WRITE_TO_PORT).getMetadata() };
try {
transformation = RecordTransformFactory.createTransform(
transformSource, transformClassName, this, inMetadata, outMetadata, transformationParameters);
} catch(Exception e) {
throw new ComponentNotReadyException(this, e);
}
}
/**
* @param transformationParameters
* The transformationParameters to set.
*/
public void setTransformationParameters(Properties transformationParameters) {
this.transformationParameters = transformationParameters;
}
/**
* Main processing method for the SimpleCopy object
*
* @since April 4, 2002
*/
public void run() {
InputPort inDriverPort = getInputPort(DRIVER_ON_PORT);
InputPort inSlavePort = getInputPort(SLAVE_ON_PORT);
OutputPort outPort = getOutputPort(WRITE_TO_PORT);
DataRecordMetadata slaveRecordMetadata = inSlavePort.getMetadata();
DataRecord driverRecord;
DataRecord slaveRecord;
DataRecord storeRecord;
DataRecord outRecord[]= {new DataRecord(outPort.getMetadata())};
DataRecord[] inRecords = new DataRecord[2];
slaveRecord=new DataRecord(inSlavePort.getMetadata());
slaveRecord.init();
// first read all records from SLAVE port
while (slaveRecord!=null && runIt) {
try {
if ((slaveRecord=inSlavePort.readRecord(slaveRecord)) != null) {
storeRecord=slaveRecord.duplicate();
hashMap.put(new HashKey(slaveKey, storeRecord),
storeRecord);
}
SynchronizeUtils.cloverYield();
} catch (IOException ex) {
resultMsg = ex.getMessage();
resultCode = Node.RESULT_ERROR;
closeAllOutputPorts();
return;
} catch (Exception ex) {
resultMsg = ex.getClass().getName()+" : "+ ex.getMessage();
resultCode = Node.RESULT_FATAL_ERROR;
return;
}
}
//XDEBUG START
// if (logger.isDebugEnabled()) {
// for (Iterator i = hashMap.values().iterator(); i.hasNext();) {
// logger.debug("> " + i.next());
// for (Iterator i = hashMap.keySet().iterator(); i.hasNext();) {
// logger.debug("> " + i.next());
//XDEBUG END
// now read all records from DRIVER port and try to look up corresponding
// record from SLAVE records set.
driverRecord = new DataRecord(inDriverPort.getMetadata());
driverRecord.init();
outRecord[0].init();
HashKey driverHashKey = new HashKey(driverKey, driverRecord);
inRecords[0] = driverRecord;
while (runIt && driverRecord != null) {
try {
driverRecord = inDriverPort.readRecord(driverRecord);
if (driverRecord != null) {
// let's find slave record
slaveRecord = (DataRecord) hashMap.get(driverHashKey);
// do we have it or is OuterJoin enabled ?
if ((slaveRecord != null) || (leftOuterJoin)) {
// call transformation function
do {
inRecords[1] = slaveRecord;
try{
if (!transformation.transform(inRecords, outRecord)) {
resultCode = Node.RESULT_ERROR;
resultMsg = transformation.getMessage();
return;
}
}catch(NullPointerException ex){
logger.error("Null pointer exception when transforming input data",ex);
logger.info("Possibly incorrectly handled outer-join situation");
throw new RuntimeException("Null pointer exception when transforming input data",ex);
}
outPort.writeRecord(outRecord[0]);
}while(slaveDuplicates &&
(slaveRecord = (DataRecord)((DuplicateKeyMap)hashMap).getNext())!=null);
}
}
SynchronizeUtils.cloverYield();
} catch (IOException ex) {
resultMsg = ex.getMessage();
resultCode = Node.RESULT_ERROR;
closeAllOutputPorts();
return;
} catch (Exception ex) {
resultMsg = ex.getMessage();
resultCode = Node.RESULT_FATAL_ERROR;
return;
}
}
// signal end of records stream
transformation.finished();
setEOF(WRITE_TO_PORT);
if (runIt) {
resultMsg = "OK";
} else {
resultMsg = "STOPPED";
}
resultCode = Node.RESULT_OK;
}
/**
* Description of the Method
*
* @return Description of the Returned Value
* @since May 21, 2002
*/
public void toXML(Element xmlElement) {
super.toXML(xmlElement);
if (transformClassName != null) {
xmlElement.setAttribute(XML_TRANSFORMCLASS_ATTRIBUTE, transformClassName);
}
if (transformSource!=null){
xmlElement.setAttribute(XML_TRANSFORM_ATTRIBUTE,transformSource);
}
if (joinKeys != null) {
String jKeys = joinKeys[0];
for (int i=1; i< joinKeys.length; i++) {
jKeys += Defaults.Component.KEY_FIELDS_DELIMITER + joinKeys[i];
}
xmlElement.setAttribute(XML_JOINKEY_ATTRIBUTE, jKeys);
}
if (slaveOverrideKeys != null) {
String overKeys = slaveOverrideKeys[0];
for (int i=1; i< slaveOverrideKeys.length; i++) {
overKeys += Defaults.Component.KEY_FIELDS_DELIMITER + slaveOverrideKeys[i];
}
xmlElement.setAttribute(XML_SLAVEOVERRIDEKEY_ATTRIBUTE, overKeys);
}
xmlElement.setAttribute(XML_LEFTOUTERJOIN_ATTRIBUTE, String.valueOf(this.leftOuterJoin));
if (hashTableInitialCapacity > DEFAULT_HASH_TABLE_INITIAL_CAPACITY ) {
xmlElement.setAttribute(XML_HASHTABLESIZE_ATTRIBUTE, String.valueOf(hashTableInitialCapacity));
}
if (slaveDuplicates){
xmlElement.setAttribute(XML_ALLOW_SLAVE_DUPLICATES_ATTRIBUTE, String.valueOf(slaveDuplicates));
}
Enumeration propertyAtts = transformationParameters.propertyNames();
while (propertyAtts.hasMoreElements()) {
String attName = (String)propertyAtts.nextElement();
xmlElement.setAttribute(attName,transformationParameters.getProperty(attName));
}
}
/**
* Description of the Method
*
* @param nodeXML Description of Parameter
* @return Description of the Returned Value
* @since May 21, 2002
*/
@Override public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException {
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph);
HashJoin join;
try {
join = new HashJoin(
xattribs.getString(XML_ID_ATTRIBUTE),
xattribs.getString(XML_JOINKEY_ATTRIBUTE).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX),
xattribs.getString(XML_TRANSFORM_ATTRIBUTE, null),
xattribs.getString(XML_TRANSFORMCLASS_ATTRIBUTE, null),
xattribs.getBoolean(XML_LEFTOUTERJOIN_ATTRIBUTE,false));
if (xattribs.exists(XML_SLAVEOVERRIDEKEY_ATTRIBUTE)) {
join.setSlaveOverrideKey(xattribs.getString(XML_SLAVEOVERRIDEKEY_ATTRIBUTE).
split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX));
}
if (xattribs.exists(XML_HASHTABLESIZE_ATTRIBUTE)) {
join.setHashTableInitialCapacity(xattribs.getInteger(XML_HASHTABLESIZE_ATTRIBUTE));
}
if (xattribs.exists(XML_ALLOW_SLAVE_DUPLICATES_ATTRIBUTE)) {
join.setSlaveDuplicates(xattribs.getBoolean(XML_ALLOW_SLAVE_DUPLICATES_ATTRIBUTE));
}
join.setTransformationParameters(xattribs.attributes2Properties(
new String[]{XML_ID_ATTRIBUTE,XML_JOINKEY_ATTRIBUTE,
XML_TRANSFORM_ATTRIBUTE,XML_TRANSFORMCLASS_ATTRIBUTE,
XML_LEFTOUTERJOIN_ATTRIBUTE,XML_SLAVEOVERRIDEKEY_ATTRIBUTE,
XML_HASHTABLESIZE_ATTRIBUTE,XML_ALLOW_SLAVE_DUPLICATES_ATTRIBUTE}));
return join;
} catch (Exception ex) {
throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex);
}
}
/**
* Description of the Method
*
* @return Description of the Return Value
*/
public boolean checkConfig() {
return true;
}
public String getType(){
return COMPONENT_TYPE;
}
public boolean isSlaveDuplicates() {
return slaveDuplicates;
}
public void setSlaveDuplicates(boolean slaveDuplicates) {
this.slaveDuplicates = slaveDuplicates;
}
}
|
package com.rultor.base;
import com.jcabi.urn.URN;
import com.rultor.spi.Instance;
import com.rultor.spi.Work;
import com.rultor.tools.Time;
import java.net.URI;
import org.junit.Test;
import org.mockito.Mockito;
/**
* Test case for {@link Descriptive}.
* @author Gangababu Tirumalanadhuni (gangababu.t@gmail.com)
* @version $Id$
*/
public final class DescriptiveTest {
/**
* Test descriptives in Xembly Log.
* @throws Exception If some problem inside
*/
@Test
public void testDescriptiveInXemblyLog() throws Exception {
final Time scheduled = new Time();
final Instance origin = Mockito.mock(Instance.class);
final Work work = Mockito.mock(Work.class);
Mockito.doReturn(URI.create("urn:facebook:1")).when(work).stdout();
Mockito.doReturn(scheduled).when(work).scheduled();
Mockito.doReturn(URN.create("urn:facebook:2")).when(work).owner();
Mockito.doReturn("test-rule").when(work).rule();
final Descriptive descriptive = new Descriptive(
work,
origin
);
descriptive.pulse();
Mockito.verify(origin).pulse();
Mockito.verify(work).rule();
Mockito.verify(work).scheduled();
Mockito.verify(work).stdout();
Mockito.verify(work).owner();
}
}
|
package com.melnykov.fab.sample;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.melnykov.fab.FloatingActionButton;
import com.melnykov.fab.ObservableScrollView;
import com.melnykov.fab.ScrollDirectionListener;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initActionBar();
}
@SuppressWarnings("deprecation")
private void initActionBar() {
if (getSupportActionBar() != null) {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab()
.setText("ListView")
.setTabListener(new ActionBar.TabListener() {
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
fragmentTransaction.replace(android.R.id.content, new ListViewFragment());
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
}));
actionBar.addTab(actionBar.newTab()
.setText("RecyclerView")
.setTabListener(new ActionBar.TabListener() {
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
fragmentTransaction.replace(android.R.id.content, new RecyclerViewFragment());
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
}));
actionBar.addTab(actionBar.newTab()
.setText("ScrollView")
.setTabListener(new ActionBar.TabListener() {
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
fragmentTransaction.replace(android.R.id.content, new ScrollViewFragment());
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
}));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.about) {
TextView content = (TextView) getLayoutInflater().inflate(R.layout.about_view, null);
content.setMovementMethod(LinkMovementMethod.getInstance());
content.setText(Html.fromHtml(getString(R.string.about_body)));
new AlertDialog.Builder(this)
.setTitle(R.string.about)
.setView(content)
.setInverseBackgroundForced(true)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
return super.onOptionsItemSelected(item);
}
public static class ListViewFragment extends Fragment {
@SuppressLint("InflateParams")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_listview, container, false);
ListView list = (ListView) root.findViewById(android.R.id.list);
ListViewAdapter listAdapter = new ListViewAdapter(getActivity(),
getResources().getStringArray(R.array.countries));
list.setAdapter(listAdapter);
FloatingActionButton fab = (FloatingActionButton) root.findViewById(R.id.fab);
fab.attachToListView(list, new ScrollDirectionListener() {
@Override
public void onScrollDown() {
Log.d("ListViewFragment", "onScrollDown()");
}
@Override
public void onScrollUp() {
Log.d("ListViewFragment", "onScrollUp()");
}
});
return root;
}
}
public static class RecyclerViewFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_recyclerview, container, false);
RecyclerView recyclerView = (RecyclerView) root.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
RecyclerViewAdapter adapter = new RecyclerViewAdapter(getActivity(), getResources()
.getStringArray(R.array.countries));
recyclerView.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) root.findViewById(R.id.fab);
fab.attachToRecyclerView(recyclerView);
return root;
}
}
public static class ScrollViewFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_scrollview, container, false);
ObservableScrollView scrollView = (ObservableScrollView) root.findViewById(R.id.scroll_view);
LinearLayout list = (LinearLayout) root.findViewById(R.id.list);
String[] countries = getResources().getStringArray(R.array.countries);
for (String country : countries) {
TextView textView = (TextView) inflater.inflate(R.layout.list_item, container, false);
String[] values = country.split(",");
String countryName = values[0];
int flagResId = getResources().getIdentifier(values[1], "drawable", getActivity().getPackageName());
textView.setText(countryName);
textView.setCompoundDrawablesWithIntrinsicBounds(flagResId, 0, 0, 0);
list.addView(textView);
}
FloatingActionButton fab = (FloatingActionButton) root.findViewById(R.id.fab);
fab.attachToScrollView(scrollView);
return root;
}
}
}
|
package util;
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;
import net.ontopia.utils.StringTemplateUtils;
import net.ontopia.utils.OntopiaRuntimeException;
import net.ontopia.topicmaps.core.TopicIF;
import net.ontopia.topicmaps.query.utils.QueryWrapper;
/**
* A collection of utility methods used by the portlets to perform
* various tasks.
*/
public class PortletUtils {
/**
* Produces the correct link to the given topic using the URL template
* for the topic type as stored in the topic map.
*/
public static String makeLinkTo(TopicIF topic) {
// set up
QueryWrapper w = new QueryWrapper(topic.getTopicMap());
w.setDeclarations("using lr for i\"http://psi.ontopia.net/liferay/\" ");
// find the template
Map params = w.makeParams("topic", topic);
String template = w.queryForString(
"select $URL from " +
"direct-instance-of(%topic%, $TYPE), " +
"lr:url-template($TYPE, $URL)?", params);
// if there's no template we can't make a link, so just returning an
// error
if (template == null)
return "No template set"; // FIXME: throw exception?
// start setting up templates
Map templateparams = new HashMap();
templateparams.put("topicid", topic.getObjectId());
// is this Liferay web content? if so, we need two more parameters
if (w.isTrue("instance-of(%topic%, lr:webcontent)?", params)) {
String gid = w.queryForString(
"select $GID from " +
"lr:contains(%topic% : lr:containee, $GROUP : lr:container), " +
"lr:groupid($GROUP, $GID)?", params);
String aid = w.queryForString("lr:article_id(%topic%, $AID)?");
templateparams.put("groupid", gid);
templateparams.put("articleid", gid);
}
// evaluate the template
return StringTemplateUtils.replace(template, templateparams);
}
/**
* Parses the query string to extract the query parameters as a map.
*/
public static Map<String, String> parseQueryString(String str) {
if (str == null)
return Collections.EMPTY_MAP;
Map<String, String> params = new HashMap();
int prevamp = -1;
int preveq = -1;
for (int ix = 0; ix < str.length(); ix++) {
char ch = str.charAt(ix);
if (ch == '=') {
if (preveq != -1)
throw new OntopiaRuntimeException("Bad query string " + str);
preveq = ix;
} else if (ch == '&') {
if (preveq == -1)
throw new OntopiaRuntimeException("Bad query string " + str);
String name = str.substring(prevamp + 1, preveq);
String value = str.substring(preveq + 1, ix);
params.put(name, value);
prevamp = ix;
preveq = -1;
}
}
// must also do last pair
if (preveq == -1)
throw new OntopiaRuntimeException("Bad query string " + str);
String name = str.substring(prevamp + 1, preveq);
String value = str.substring(preveq + 1);
params.put(name, value);
return params;
}
}
|
package be.fedict.dcat.scrapers;
import be.fedict.dcat.helpers.Cache;
import be.fedict.dcat.helpers.Page;
import be.fedict.dcat.helpers.Storage;
import be.fedict.dcat.vocab.MDR_LANG;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTML.Attribute;
import javax.swing.text.html.HTML.Tag;
import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.vocabulary.DCAT;
import org.eclipse.rdf4j.model.vocabulary.DCTERMS;
import org.eclipse.rdf4j.model.vocabulary.RDF;
import org.eclipse.rdf4j.repository.RepositoryException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Scraper for website Brugge.
*
* @author Bart.Hanssens
*/
public class HtmlBrugge extends Html {
private final Logger logger = LoggerFactory.getLogger(HtmlBrugge.class);
private final static String LINKS_DATASETS = "div.user-content div a:eq(1)[href]";
private final static String LINK_DATASET = "div.user-content h4";
private final static String NAME_DATASET = "strong a[name]";
private final static String SIBL_DESC = "em strong:contains(Omschrijving)";
private final static String SIBL_FMTS = "em strong:contains(Bestandsformaten)";
private final static String DIST_HREF = "a";
/**
* Get the list of all the categories.
*
* @return list of category URLs
* @throws IOException
*/
private List<URL> scrapeDatasetLists() throws IOException {
List<URL> urls = new ArrayList<>();
URL base = getBase();
String front = makeRequest(base);
Elements links = Jsoup.parse(front).select(LINKS_DATASETS);
for(Element link : links) {
String href = link.attr(HTML.Attribute.HREF.toString());
urls.add(makeAbsURL(href));
}
return urls;
}
@Override
public void scrape() throws IOException {
logger.info("Start scraping");
Cache cache = getCache();
List<URL> urls = cache.retrieveURLList();
if (urls.isEmpty()) {
urls = scrapeDatasetLists();
cache.storeURLList(urls);
}
logger.info("Found {} dataset lists", String.valueOf(urls.size()));
logger.info("Start scraping (waiting between requests)");
int i = 0;
for (URL u : urls) {
Map<String, Page> page = cache.retrievePage(u);
if (page.isEmpty()) {
sleep();
if (++i % 100 == 0) {
logger.info("Download {}...", Integer.toString(i));
}
try {
String html = makeRequest(u);
cache.storePage(u, "", new Page(u, html));
} catch (IOException ex) {
logger.error("Failed to scrape {}", u);
}
}
}
logger.info("Done scraping");
}
/**
* Generate DCAT distribution.
*
* @param store RDF store
* @param dataset URI
* @param name short name
* @param access URL of the acess page
* @param link download link element
* @param lang language code
* @throws MalformedURLException
* @throws RepositoryException
*/
private void generateDist(Storage store, IRI dataset, String name, String access,
Element link, String lang) throws MalformedURLException, RepositoryException {
String href = link.attr(Attribute.HREF.toString());
String fmt = link.ownText();
URL u = makeDistURL(name + "/" + fmt.replaceAll("/", "").replaceAll(" ", ""));
IRI dist = store.getURI(u.toString());
logger.debug("Generating distribution {}", dist.toString());
store.add(dataset, DCAT.HAS_DISTRIBUTION, dist);
store.add(dist, RDF.TYPE, DCAT.DISTRIBUTION);
store.add(dist, DCTERMS.LANGUAGE, MDR_LANG.MAP.get(lang));
store.add(dist, DCTERMS.TITLE, fmt, lang);
store.add(dist, DCAT.ACCESS_URL, makeAbsURL(access));
store.add(dist, DCAT.DOWNLOAD_URL, makeAbsURL(href));
store.add(dist, DCAT.MEDIA_TYPE, fmt);
}
/**
* Generate one dataset
*
* @param store RDF store
* @param page front
* @param el HTML element
* @param name anchor name
* @param lang language
* @throws MalformedURLException
* @throws RepositoryException
*/
private void generateDataset(Storage store, String page, Element el, String anchor,
String lang) throws MalformedURLException, RepositoryException {
String title = el.text();
String name = title.toLowerCase().replaceAll(" ", "");
URL u = makeDatasetURL(name);
IRI dataset = store.getURI(u.toString());
logger.debug("Generating dataset {}", dataset);
String desc = title;
Element sib = el.nextElementSibling();
while (sib != null && sib.tagName().equals(Tag.P.toString())) {
if (! sib.select(SIBL_DESC).isEmpty()) {
desc = sib.ownText();
}
sib = sib.nextElementSibling();
}
store.add(dataset, RDF.TYPE, DCAT.DATASET);
store.add(dataset, DCTERMS.LANGUAGE, MDR_LANG.MAP.get(lang));
store.add(dataset, DCTERMS.TITLE, title, lang);
store.add(dataset, DCTERMS.DESCRIPTION, desc, lang);
store.add(dataset, DCTERMS.IDENTIFIER, makeHashId(u.toString()));
store.add(dataset, DCAT.LANDING_PAGE, store.getURI(page + "#" + anchor));
store.add(dataset, DCAT.KEYWORD, page.substring(page.lastIndexOf("/") + 1));
Elements links = null;
sib = el.nextElementSibling();
while (sib != null && sib.tagName().equals(Tag.P.toString())) {
if(!sib.select(SIBL_FMTS).isEmpty()) {
links = sib.select(DIST_HREF);
}
sib = sib.nextElementSibling();
}
if (links != null) {
for(Element link: links) {
generateDist(store, dataset, name, page + "#" + anchor, link, lang);
}
}
}
/**
* Generate DCAT Dataset
*
* @param store RDF store
* @param id dataset id
* @param page
* @throws MalformedURLException
* @throws RepositoryException
*/
@Override
protected void generateDataset(Storage store, String id, Map<String, Page> page)
throws MalformedURLException, RepositoryException {
String lang = getDefaultLang();
Page p = page.get("");
String html = p.getContent();
Elements elements = Jsoup.parse(html).select(LINK_DATASET);
for (Element element : elements) {
String anchor = element.select(NAME_DATASET).attr(Attribute.NAME.toString());
generateDataset(store, id, element, anchor, lang);
}
}
/**
* Generate DCAT.
*
* @param cache DBC cache
* @param store RDF store
* @throws RepositoryException
* @throws MalformedURLException
*/
@Override
public void generateDcat(Cache cache, Storage store)
throws RepositoryException, MalformedURLException {
logger.info("Generate DCAT");
/* Get the list of all datasets */
List<URL> urls = cache.retrieveURLList();
for(URL u : urls) {
Map<String,Page> page = cache.retrievePage(u);
generateDataset(store, u.toString(), page);
}
generateCatalog(store);
}
/**
* Constructor
*
* @param caching DB cache file
* @param storage
* @param base
*/
public HtmlBrugge(File caching, File storage, URL base) {
super(caching, storage, base);
setName("brugge");
}
}
|
package com.breakersoft.plow;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
public class PlowThreadPools {
/**
* The NodeDispatcherExecutor
*
* @return
*/
@Bean(name="nodeDispatcherExecutor")
public ThreadPoolTaskExecutor nodeDispatcherExecutor() {
ThreadPoolTaskExecutor t = new ThreadPoolTaskExecutor();
t.setCorePoolSize(16);
t.setMaxPoolSize(16);
t.setThreadNamePrefix("NodeDispatcher");
t.setDaemon(false);
t.setQueueCapacity(1000);
return t;
}
/**
* The ProcDispatcherExecutor
*
* @return
*/
@Bean(name="procDispatcherExecutor")
public ThreadPoolTaskExecutor procDispatcherExecutor() {
ThreadPoolTaskExecutor t = new ThreadPoolTaskExecutor();
t.setCorePoolSize(16);
t.setMaxPoolSize(16);
t.setThreadNamePrefix("ProcDispatcher");
t.setDaemon(false);
t.setQueueCapacity(5000);
return t;
}
/**
* Handles Async commands from the API.
*/
@Bean(name="stateChangeExecutor")
public ThreadPoolTaskExecutor stateChangeExecutor() {
ThreadPoolTaskExecutor t = new ThreadPoolTaskExecutor();
t.setCorePoolSize(16);
t.setMaxPoolSize(32);
t.setThreadNamePrefix("StateChange");
t.setDaemon(false);
t.setQueueCapacity(1000);
t.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return t;
}
}
|
package io.spine.server.route;
import com.google.protobuf.Message;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.spine.util.Exceptions.newIllegalStateException;
import static java.util.stream.Collectors.toList;
/**
* A routing schema for a kind of messages such as commands, events, rejections, or documents.
*
* <p>A routing schema consists of a default route and custom routes per message class.
*
* @param <M> the type of the message to route
* @param <C> the type of message context objects
* @param <R> the type returned by the {@linkplain Route#apply(Message, Message) routing function}
*/
abstract class MessageRouting<M extends Message, C extends Message, R> implements Route<M, C, R> {
private static final long serialVersionUID = 0L;
private final Map<Class<? extends M>, Route<M, C, R>> routes = new LinkedHashMap<>();
/** The default route to be used if there is no matching entry set in {@link #routes}. */
private Route<M, C, R> defaultRoute;
MessageRouting(Route<M, C, R> defaultRoute) {
this.defaultRoute = defaultRoute;
}
/**
* Obtains the default route used by the schema.
*/
protected Route<M, C, R> defaultRoute() {
return defaultRoute;
}
/**
* Sets new default route in the schema.
*
* @param newDefault the new route to be used as default
*/
MessageRouting<M, C, R> replaceDefault(Route<M, C, R> newDefault) {
checkNotNull(newDefault);
defaultRoute = newDefault;
return this;
}
void addRoute(Class<? extends M> messageType, Route<M, C, R> via)
throws IllegalStateException {
checkNotNull(messageType);
checkNotNull(via);
Match match = routeFor(messageType);
if (match.found()) {
String requestedClass = messageType.getName();
String entryClass = match.entryClass()
.getName();
if (match.direct()) {
throw newIllegalStateException(
"The route for the message class `%s` already set. " +
"Please remove the route (`%s`) before setting new route.",
requestedClass, entryClass);
} else {
throw newIllegalStateException(
"The route for the message class `%s` already defined via " +
"the interface `%s`. If you want to have specific routing for " +
"the class `%s`, please put it before the routing for " +
"the super-interface.",
requestedClass, entryClass, requestedClass);
}
}
routes.put(messageType, via);
}
/**
* Obtains a route for the passed message class.
*
* @param msgCls the class of the messages
* @return optionally available route
*/
Match routeFor(Class<? extends M> msgCls) {
checkNotNull(msgCls);
Match direct = findDirect(msgCls);
if (direct.found()) {
return direct;
}
Match viaInterface = findViaInterface(msgCls);
if (viaInterface.found()) {
// Store the found route for later direct use.
routes.put(msgCls, viaInterface.route());
return viaInterface;
}
return new Match(msgCls, null, null);
}
private Match findDirect(Class<? extends M> msgCls) {
Route<M, C, R> route = routes.get(msgCls);
if (route != null) {
return new Match(msgCls, msgCls, route);
}
return new Match(msgCls, null, null);
}
private Match findViaInterface(Class<? extends M> msgCls) {
List<Map.Entry<Class<? extends M>, Route<M, C, R>>> interfaceEntries =
routes.entrySet()
.stream()
.filter(e -> e.getKey()
.isInterface())
.collect(toList());
for (Map.Entry<Class<? extends M>, Route<M, C, R>> entry : interfaceEntries) {
Class<? extends M> key = entry.getKey();
if (key.isAssignableFrom(msgCls)) {
return new Match(msgCls, key, entry.getValue());
}
}
return new Match(msgCls, null, null);
}
public void remove(Class<? extends M> messageClass) {
checkNotNull(messageClass);
if (!routes.containsKey(messageClass)) {
throw newIllegalStateException(
"Cannot remove the route for the message class (`%s`): " +
"a custom route was not previously set.",
messageClass.getName());
}
routes.remove(messageClass);
}
/**
* Obtains IDs of entities to which the passed message should be delivered.
*
* <p>If there is no function for the passed message applies the default function.
*
* @param message the message
* @param context the message context
* @return the set of entity IDs to which the message should be delivered
*/
@Override
public R apply(M message, C context) {
checkNotNull(message);
checkNotNull(context);
@SuppressWarnings("unchecked") Class<? extends M>
cls = (Class<? extends M>) message.getClass();
Match match = routeFor(cls);
if (match.found()) {
Route<M, C, R> func = match.route();
R result = func.apply(message, context);
return result;
}
R result = defaultRoute().apply(message, context);
return result;
}
/**
* Provides information on routing availability.
*/
final class Match {
private final Class<? extends M> requestedClass;
private final @Nullable Route<M, C, R> route;
private final @Nullable Class<? extends M> entryClass;
/**
* Creates new instance.
*
* @param requestedClass
* the class of the message which needs to be routed
* @param entryType
* the type through which the route is found.
* Can be a class (for the {@link #direct()} match) or a super-interface
* of the requested class.
* Is {@code null} if there is no routing found for the {@code requestedClass}.
* @param route
* the routing function or {@code null} if there is no route defined neither
* for the class or a super-interface of the class
*/
private Match(Class<? extends M> requestedClass,
@Nullable Class<? extends M> entryType,
@Nullable Route<M, C, R> route) {
this.requestedClass = requestedClass;
this.route = route;
this.entryClass = entryType;
}
boolean found() {
return route != null;
}
/**
* Returns {@code true} if the routing was defined directly for the requested class,
* otherwise {@code false}.
*/
boolean direct() {
return requestedClass.equals(entryClass);
}
Class<? extends M> entryClass() {
return checkNotNull(entryClass);
}
Route<M, C, R> route() {
return checkNotNull(route);
}
}
}
|
package org.jboss.as.server.deployment;
/**
* An enumeration of the phases of a deployment unit's processing cycle.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
public enum Phase {
/* == TEMPLATE ==
* Upon entry, this phase performs the following actions:
* <ul>
* <li></li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
*/
/**
* This phase creates the initial root structure. Depending on the service for this phase will ensure that the
* deployment unit's initial root structure is available and accessible.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>The primary deployment root is mounted (during {@link #STRUCTURE_MOUNT})</li>
* <li>Other internal deployment roots are mounted (during {@link #STRUCTURE_NESTED_JAR})</li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li><i>N/A</i></li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments:
* <ul>
* <li>{@link Attachments#DEPLOYMENT_ROOT} - the mounted deployment root for this deployment unit</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* </ul>
* <p>
*/
STRUCTURE(null),
/**
* This phase assembles information from the root structure to prepare for adding and processing additional external
* structure, such as from class path entries and other similar mechanisms.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>The root content's MANIFEST is read and made available during {@link #PARSE_MANIFEST}.</li>
* <li>The annotation index for the root structure is calculated during {@link #STRUCTURE_ANNOTATION_INDEX}.</li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#MANIFEST} - the parsed manifest of the root structure</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li><i>N/A</i></li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#CLASS_PATH_ENTRIES} - class path entries found in the manifest and elsewhere.</li>
* <li>{@link Attachments#EXTENSION_LIST_ENTRIES} - extension-list entries found in the manifest and elsewhere.</li>
* </ul>
* <p>
*/
PARSE(null),
/**
* In this phase, the full structure of the deployment unit is made available and module dependencies may be assembled.
* <p>
* Upon entry, this phase performs the following actions:
* <ul>
* <li>Any additional external structure is mounted during {@link #XXX}</li>
* <li></li>
* </ul>
* <p>
* Processors in this phase have access to the following phase attachments:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* Processors in this phase have access to the following deployment unit attachments, in addition to those defined
* for the previous phase:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
* In this phase, these phase attachments may be modified:
* <ul>
* <li>{@link Attachments#BLAH} - description here</li>
* </ul>
* <p>
*/
DEPENDENCIES(null),
CONFIGURE_MODULE(null),
POST_MODULE(null),
INSTALL(null),
CLEANUP(null),
;
/**
* This is the key for the attachment to use as the phase's "value". The attachment is taken from
* the deployment unit. If a phase doesn't have a single defining "value", {@code null} is specified.
*/
private final AttachmentKey<?> phaseKey;
private Phase(final AttachmentKey<?> key) {
phaseKey = key;
}
/**
* Get the next phase, or {@code null} if none.
*
* @return the next phase, or {@code null} if there is none
*/
public Phase next() {
final int ord = ordinal() + 1;
final Phase[] phases = Phase.values();
return ord == phases.length ? null : phases[ord];
}
/**
* Get the attachment key of the {@code DeploymentUnit} attachment that represents the result value
* of this phase.
*
* @return the key
*/
public AttachmentKey<?> getPhaseKey() {
return phaseKey;
}
// STRUCTURE
public static final int STRUCTURE_EXPLODED_MOUNT = 0x0200;
public static final int STRUCTURE_MOUNT = 0x0300;
public static final int STRUCTURE_MANIFEST = 0x0400;
// must be before osgi
public static final int STRUCTURE_JDBC_DRIVER = 0x0500;
public static final int STRUCTURE_OSGI_MANIFEST = 0x0600;
public static final int STRUCTURE_RAR = 0x0700;
public static final int STRUCTURE_WAR_DEPLOYMENT_INIT = 0x0800;
public static final int STRUCTURE_WAR = 0x0900;
public static final int STRUCTURE_EAR_DEPLOYMENT_INIT = 0x0A00;
public static final int STRUCTURE_EAR_APP_XML_PARSE = 0x0B00;
public static final int STRUCTURE_JBOSS_EJB_CLIENT_XML_PARSE = 0x0C00;
public static final int STRUCTURE_EJB_EAR_APPLICATION_NAME = 0x0D00;
public static final int STRUCTURE_EAR = 0x0E00;
public static final int STRUCTURE_APP_CLIENT = 0x0F00;
public static final int STRUCTURE_SERVICE_MODULE_LOADER = 0x1000;
public static final int STRUCTURE_ANNOTATION_INDEX = 0x1100;
public static final int STRUCTURE_EJB_JAR_IN_EAR = 0x1200;
public static final int STRUCTURE_APPLICATION_CLIENT_IN_EAR = 0x1300;
public static final int STRUCTURE_MANAGED_BEAN_JAR_IN_EAR = 0x1400;
public static final int STRUCTURE_SAR_SUB_DEPLOY_CHECK = 0x1500;
public static final int STRUCTURE_ADDITIONAL_MANIFEST = 0x1600;
public static final int STRUCTURE_SUB_DEPLOYMENT = 0x1700;
public static final int STRUCTURE_JBOSS_DEPLOYMENT_STRUCTURE_DESCRIPTOR = 0x1800;
public static final int STRUCTURE_CLASS_PATH = 0x1900;
public static final int STRUCTURE_MODULE_IDENTIFIERS = 0x1A00;
public static final int STRUCTURE_EE_MODULE_INIT = 0x1B00;
public static final int STRUCTURE_EE_RESOURCE_INJECTION_REGISTRY = 0x1C00;
// PARSE
public static final int PARSE_EE_MODULE_NAME = 0x0100;
public static final int PARSE_EAR_SUBDEPLOYMENTS_ISOLATION_DEFAULT = 0x0200;
public static final int PARSE_DEPENDENCIES_MANIFEST = 0x0300;
public static final int PARSE_COMPOSITE_ANNOTATION_INDEX = 0x0301;
public static final int PARSE_EXTENSION_LIST = 0x0700;
public static final int PARSE_EXTENSION_NAME = 0x0800;
public static final int PARSE_OSGI_BUNDLE_INFO = 0x0900;
public static final int PARSE_OSGI_XSERVICE_PROPERTIES = 0x0A00;
public static final int PARSE_OSGI_DEPLOYMENT = 0x0A80;
public static final int PARSE_WEB_DEPLOYMENT = 0x0B00;
public static final int PARSE_WEB_DEPLOYMENT_FRAGMENT = 0x0C00;
public static final int PARSE_JSF_VERSION = 0x0C50;
public static final int PARSE_ANNOTATION_WAR = 0x0D00;
public static final int PARSE_ANNOTATION_EJB = 0x0D10;
public static final int PARSE_JBOSS_WEB_DEPLOYMENT = 0x0E00;
public static final int PARSE_TLD_DEPLOYMENT = 0x0F00;
public static final int PARSE_EAR_CONTEXT_ROOT = 0x1000;
// create and attach EJB metadata for EJB deployments
public static final int PARSE_EJB_DEPLOYMENT = 0x1100;
public static final int PARSE_APP_CLIENT_XML = 0x1101;
public static final int PARSE_EJB_CLIENT_METADATA = 0x1102;
public static final int PARSE_CREATE_COMPONENT_DESCRIPTIONS = 0x1150;
// described EJBs must be created after annotated EJBs
public static final int PARSE_ENTITY_BEAN_CREATE_COMPONENT_DESCRIPTIONS = 0x1152;
public static final int PARSE_CMP_ENTITY_BEAN_CREATE_COMPONENT_DESCRIPTIONS = 0x1153;
public static final int PARSE_EJB_SESSION_BEAN_DD = 0x1200;
// create and attach the component description out of EJB annotations
public static final int PARSE_EJB_APPLICATION_EXCEPTION_ANNOTATION = 0x1901;
public static final int PARSE_WEB_COMPONENTS = 0x1F00;
public static final int PARSE_WEB_MERGE_METADATA = 0x2000;
public static final int PARSE_WEBSERVICES_CONTEXT_INJECTION = 0x2040;
public static final int PARSE_WEBSERVICES_XML = 0x2050;
public static final int PARSE_JBOSS_WEBSERVICES_XML = 0x2051;
public static final int PARSE_JAXWS_EJB_INTEGRATION = 0x2052;
public static final int PARSE_JAXRPC_POJO_INTEGRATION = 0x2053;
public static final int PARSE_JAXRPC_EJB_INTEGRATION = 0x2054;
public static final int PARSE_JAXWS_HANDLER_CHAIN_ANNOTATION = 0x2055;
public static final int PARSE_WS_JMS_INTEGRATION = 0x2056;
public static final int PARSE_JAXWS_ENDPOINT_CREATE_COMPONENT_DESCRIPTIONS = 0x2057;
public static final int PARSE_JAXWS_HANDLER_CREATE_COMPONENT_DESCRIPTIONS = 0x2058;
public static final int PARSE_RA_DEPLOYMENT = 0x2100;
public static final int PARSE_SERVICE_LOADER_DEPLOYMENT = 0x2200;
public static final int PARSE_SERVICE_DEPLOYMENT = 0x2300;
public static final int PARSE_POJO_DEPLOYMENT = 0x2400;
public static final int PARSE_IRON_JACAMAR_DEPLOYMENT = 0x2500;
public static final int PARSE_MANAGED_BEAN_ANNOTATION = 0x2900;
public static final int PARSE_EE_ANNOTATIONS = 0x2901;
public static final int PARSE_JAXRS_ANNOTATIONS = 0x2A00;
public static final int PARSE_WELD_DEPLOYMENT = 0x2B00;
public static final int PARSE_WELD_WEB_INTEGRATION = 0x2B10;
public static final int PARSE_DATA_SOURCE_DEFINITION_ANNOTATION = 0x2D00;
public static final int PARSE_EJB_CONTEXT_BINDING = 0x2E00;
public static final int PARSE_EJB_TIMERSERVICE_BINDING = 0x2E01;
public static final int PARSE_PERSISTENCE_UNIT = 0x2F00;
public static final int PARSE_PERSISTENCE_ANNOTATION = 0x3000;
public static final int PARSE_LIEFCYCLE_ANNOTATION = 0x3200;
public static final int PARSE_PASSIVATION_ANNOTATION = 0x3250;
public static final int PARSE_AROUNDINVOKE_ANNOTATION = 0x3300;
public static final int PARSE_AROUNDTIMEOUT_ANNOTATION = 0x3400;
public static final int PARSE_TIMEOUT_ANNOTATION = 0x3401;
public static final int PARSE_EJB_DD_INTERCEPTORS = 0x3500;
public static final int PARSE_EJB_SECURITY_ROLE_REF_DD = 0x3501;
public static final int PARSE_EJB_ASSEMBLY_DESC_DD = 0x3600;
public static final int PARSE_DISTINCT_NAME = 0x3601;
// should be after all components are known
public static final int PARSE_EJB_INJECTION_ANNOTATION = 0x3700;
public static final int PARSE_JACORB = 0x3A00;
public static final int PARSE_TRANSACTION_ROLLBACK_ACTION = 0x3B00;
public static final int PARSE_WEB_INITIALIZE_IN_ORDER = 0x3C00;
public static final int PARSE_EAR_MESSAGE_DESTINATIONS = 0x3D00;
public static final int PARSE_DSXML_DEPLOYMENT = 0x3E00;
public static final int PARSE_MESSAGING_XML_RESOURCES = 0x3F00;
// DEPENDENCIES
public static final int DEPENDENCIES_EJB = 0x0000;
public static final int DEPENDENCIES_MODULE = 0x0100;
public static final int DEPENDENCIES_RAR_CONFIG = 0x0300;
public static final int DEPENDENCIES_MANAGED_BEAN = 0x0400;
public static final int DEPENDENCIES_SAR_MODULE = 0x0500;
public static final int DEPENDENCIES_WAR_MODULE = 0x0600;
public static final int DEPENDENCIES_CLASS_PATH = 0x0800;
public static final int DEPENDENCIES_EXTENSION_LIST = 0x0900;
public static final int DEPENDENCIES_WELD = 0x0A00;
public static final int DEPENDENCIES_SEAM = 0x0A01;
public static final int DEPENDENCIES_WS = 0x0C00;
public static final int DEPENDENCIES_SECURITY = 0x0C50;
public static final int DEPENDENCIES_JAXRS = 0x0D00;
public static final int DEPENDENCIES_SUB_DEPLOYMENTS = 0x0E00;
public static final int DEPENDENCIES_JPA = 0x1000;
public static final int DEPENDENCIES_GLOBAL_MODULES = 0x1100;
public static final int DEPENDENCIES_JDK = 0x1200;
public static final int DEPENDENCIES_JACORB = 0x1300;
public static final int DEPENDENCIES_CMP = 0x1500;
public static final int DEPENDENCIES_JAXR = 0x1600;
public static final int DEPENDENCIES_DRIVERS = 0x1700;
//these must be last, and in this specific order
public static final int DEPENDENCIES_APPLICATION_CLIENT = 0x2000;
public static final int DEPENDENCIES_VISIBLE_MODULES = 0x2100;
public static final int DEPENDENCIES_EE_CLASS_DESCRIPTIONS = 0x2200;
// CONFIGURE_MODULE
public static final int CONFIGURE_MODULE_SPEC = 0x0100;
// POST_MODULE
public static final int POST_MODULE_INJECTION_ANNOTATION = 0x0100;
public static final int POST_MODULE_REFLECTION_INDEX = 0x0200;
public static final int POST_MODULE_TRANSFORMER = 0x0201;
public static final int POST_MODULE_JSF_MANAGED_BEANS = 0x0300;
public static final int POST_MODULE_INTERCEPTOR_ANNOTATIONS = 0x0301;
public static final int POST_MODULE_EJB_BUSINESS_VIEW_ANNOTATION = 0x0400;
public static final int POST_MODULE_EJB_HOME_MERGE = 0x0401;
public static final int POST_MODULE_EJB_DD_METHOD_RESOLUTION = 0x0402;
public static final int POST_MODULE_EJB_TIMER_METADATA_MERGE = 0x0506;
public static final int POST_MODULE_EJB_SLSB_POOL_NAME_MERGE = 0x0507;
public static final int POST_MODULE_EJB_MDB_POOL_NAME_MERGE = 0x0508;
public static final int POST_MODULE_EJB_ENTITY_POOL_NAME_MERGE = 0x0509;
public static final int POST_MODULE_EJB_DD_INTERCEPTORS = 0x0600;
public static final int POST_MODULE_EJB_TIMER_SERVICE = 0x0601;
public static final int POST_MODULE_EJB_TRANSACTION_MANAGEMENT = 0x0602;
public static final int POST_MODULE_EJB_TX_ATTR_MERGE = 0x0603;
public static final int POST_MODULE_EJB_CONCURRENCY_MANAGEMENT_MERGE= 0x0604;
public static final int POST_MODULE_EJB_CONCURRENCY_MERGE = 0x0605;
public static final int POST_MODULE_EJB_RUN_AS_MERGE = 0x0606;
public static final int POST_MODULE_EJB_RESOURCE_ADAPTER_MERGE = 0x0607;
public static final int POST_MODULE_EJB_REMOVE_METHOD = 0x0608;
public static final int POST_MODULE_EJB_STARTUP_MERGE = 0x0609;
public static final int POST_MODULE_EJB_SECURITY_DOMAIN = 0x060A;
public static final int POST_MODULE_EJB_ROLES = 0x060B;
public static final int POST_MODULE_METHOD_PERMISSIONS = 0x060C;
public static final int POST_MODULE_EJB_STATEFUL_TIMEOUT = 0x060D;
public static final int POST_MODULE_EJB_ASYNCHRONOUS_MERGE = 0x060E;
public static final int POST_MODULE_EJB_SESSION_SYNCHRONIZATION = 0x060F;
public static final int POST_MODULE_EJB_INIT_METHOD = 0x0610;
public static final int POST_MODULE_EJB_SESSION_BEAN = 0x0611;
public static final int POST_MODULE_EJB_SECURITY_PRINCIPAL_ROLE_MAPPING_MERGE = 0x0612;
public static final int POST_MODULE_EJB_CACHE = 0x0614;
public static final int POST_MODULE_EJB_CLUSTERED = 0x0615;
public static final int POST_MODULE_WELD_COMPONENT_INTEGRATION = 0x0800;
public static final int POST_MODULE_INSTALL_EXTENSION = 0x0A00;
public static final int POST_MODULE_VALIDATOR_FACTORY = 0x0B00;
public static final int POST_MODULE_EAR_DEPENDENCY = 0x0C00;
public static final int POST_MODULE_WELD_BEAN_ARCHIVE = 0x0D00;
public static final int POST_MODULE_WELD_PORTABLE_EXTENSIONS = 0x0E00;
// should come before ejb jndi bindings processor
public static final int POST_MODULE_EJB_IMPLICIT_NO_INTERFACE_VIEW = 0x1000;
public static final int POST_MODULE_EJB_JNDI_BINDINGS = 0x1100;
public static final int POST_MODULE_EJB_APPLICATION_EXCEPTIONS = 0x1200;
public static final int POST_INITIALIZE_IN_ORDER = 0x1300;
public static final int POST_MODULE_ENV_ENTRY = 0x1400;
public static final int POST_MODULE_EJB_REF = 0x1500;
public static final int POST_MODULE_PERSISTENCE_REF = 0x1600;
public static final int POST_MODULE_PERSISTENCE_CLASS_FILE_TRANSFORMER = 0x1620;
public static final int POST_MODULE_DATASOURCE_REF = 0x1700;
public static final int POST_MODULE_WS_REF_DESCRIPTOR = 0x1800;
public static final int POST_MODULE_WS_REF_ANNOTATION = 0x1801;
public static final int POST_MODULE_JAXRS_SCANNING = 0x1A00;
public static final int POST_MODULE_JAXRS_COMPONENT = 0x1B00;
public static final int POST_MODULE_JAXRS_CDI_INTEGRATION = 0x1C00;
public static final int POST_MODULE_LOCAL_HOME = 0x1E00;
public static final int POST_MODULE_APPLICATION_CLIENT_MANIFEST = 0x1F00;
public static final int POST_MODULE_APPLICATION_CLIENT_ACTIVE = 0x2000;
public static final int POST_MODULE_APP_CLIENT_METHOD_RESOLUTION = 0x2020;
public static final int POST_MODULE_EJB_ORB_BIND = 0x2100;
public static final int POST_MODULE_EJB_CLIENT_CONTEXT_SETUP = 0x2200;
public static final int POST_MODULE_CMP_PARSE = 0x2300;
public static final int POST_MODULE_CMP_ENTITY_METADATA = 0x2400;
public static final int POST_MODULE_CMP_STORE_MANAGER = 0x2500;
public static final int POST_MODULE_EJB_IIOP = 0x2600;
public static final int POST_MODULE_POJO = 0x2700;
public static final int POST_MODULE_NAMING_CONTEXT = 0x2800;
public static final int POST_MODULE_APP_NAMING_CONTEXT = 0x2900;
public static final int POST_MODULE_CACHED_CONNECTION_MANAGER = 0x2A00;
// INSTALL
public static final int INSTALL_JNDI_DEPENDENCY_SETUP = 0x0100;
public static final int INSTALL_JPA_INTERCEPTORS = 0x0200;
public static final int INSTALL_JACC_POLICY = 0x0350;
public static final int INSTALL_COMPONENT_AGGREGATION = 0x0400;
public static final int INSTALL_RESOLVE_MESSAGE_DESTINATIONS = 0x0403;
public static final int INSTALL_EJB_JACC_PROCESSING = 0x0403;
public static final int INSTALL_SERVICE_ACTIVATOR = 0x0500;
public static final int INSTALL_OSGI_DEPLOYMENT = 0x0600;
public static final int INSTALL_OSGI_MODULE = 0x0650;
public static final int INSTALL_RA_NATIVE = 0x0800;
public static final int INSTALL_RA_DEPLOYMENT = 0x0801;
public static final int INSTALL_SERVICE_DEPLOYMENT = 0x0900;
public static final int INSTALL_POJO_DEPLOYMENT = 0x0A00;
public static final int INSTALL_RA_XML_DEPLOYMENT = 0x0B00;
public static final int INSTALL_EE_MODULE_CONFIG = 0x1101;
public static final int INSTALL_MODULE_JNDI_BINDINGS = 0x1200;
public static final int INSTALL_DEPENDS_ON_ANNOTATION = 0x1210;
public static final int INSTALL_PERSISTENCE_PROVIDER = 0x1215; // before INSTALL_PERSISTENTUNIT
public static final int INSTALL_PERSISTENTUNIT = 0x1220;
public static final int INSTALL_EE_COMPONENT = 0x1230;
public static final int INSTALL_SERVLET_INIT_DEPLOYMENT = 0x1300;
public static final int INSTALL_JAXRS_DEPLOYMENT = 0x1500;
public static final int INSTALL_JSF_ANNOTATIONS = 0x1600;
public static final int INSTALL_JDBC_DRIVER = 0x1800;
public static final int INSTALL_TRANSACTION_BINDINGS = 0x1900;
public static final int INSTALL_BUNDLE_CONTEXT_BINDING = 0x1A00;
public static final int INSTALL_WELD_DEPLOYMENT = 0x1B00;
public static final int INSTALL_WELD_BEAN_MANAGER = 0x1C00;
public static final int INSTALL_JNDI_DEPENDENCIES = 0x1C01;
public static final int INSTALL_WS_UNIVERSAL_META_DATA_MODEL = 0x1C10;
public static final int INSTALL_WS_DEPLOYMENT_ASPECTS = 0x1C11;
// IMPORTANT: WS integration installs deployment aspects dynamically
// so consider INSTALL 0x1C10 - 0x1CFF reserved for WS subsystem!
public static final int INSTALL_WAR_DEPLOYMENT = 0x1D00;
public static final int INSTALL_DEPLOYMENT_REPOSITORY = 0x1E00;
public static final int INSTALL_EJB_MANAGEMENT_RESOURCES = 0x1F00;
public static final int INSTALL_APPLICATION_CLIENT = 0x2000;
public static final int INSTALL_DSXML_DEPLOYMENT = 0x2010;
public static final int INSTALL_MESSAGING_XML_RESOURCES = 0x2011;
// CLEANUP
public static final int CLEANUP_REFLECTION_INDEX = 0x0100;
public static final int CLEANUP_EE = 0x0200;
public static final int CLEANUP_EJB = 0x0300;
}
|
package scenelib.annotations.el;
import org.checkerframework.checker.signature.qual.BinaryName;
import java.io.File;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import java.util.*;
import java.util.StringJoiner;
import org.checkerframework.checker.nullness.qual.Nullable;
import scenelib.annotations.el.AElement;
import scenelib.annotations.AnnotationBuilder;
import scenelib.annotations.field.*;
import scenelib.annotations.Annotation;
import scenelib.annotations.Annotations;
/**
* An annotation type definition, consisting of the annotation name,
* its meta-annotations, and its field names and
* types. <code>AnnotationDef</code>s are immutable. An AnnotationDef with
* a non-null retention policy is called a "top-level annotation definition".
*/
public final class AnnotationDef extends AElement {
/**
* The binary name of the annotation type, such as
* "foo.Bar$Baz" for inner class Baz in class Bar in package foo.
*/
public final @BinaryName String name;
/**
* A map of the names of this annotation type's fields to their types. Since
* {@link AnnotationDef}s are immutable, clients should not modify this
* map, and doing so will result in an exception.
*/
public Map<String, AnnotationFieldType> fieldTypes;
/** Where the annotation definition came from, such as a file name. */
public String source;
/**
* Constructs an annotation definition with the given name.
* You MUST call setFieldTypes afterward, even if with an empty map. (Yuck.)
*
* @param name the binary name of the annotation type
* @param source where the annotation came from, such as a filename
*/
public AnnotationDef(@BinaryName String name, String source) {
super("annotation: " + name);
assert name != null;
assert source != null;
this.name = name;
this.source = source;
}
// Problem: I am not sure how to handle circularities (annotations meta-annotated with themselves)
/**
* Returns an AnnotationDef for the given annotation type.
* It might have been looked up in adefs, or created new and inserted in adefs.
*
* @param annoType the type for which to create an AnnotationDef
* @param adefs a cache of known AnnotationDef objects
* @return an AnnotationDef for the given annotation type
*/
public static AnnotationDef fromClass(Class<? extends java.lang.annotation.Annotation> annoType, Map<String,AnnotationDef> adefs) {
@SuppressWarnings("signature:assignment.type.incompatible") // not an array, so ClassGetName => BinaryName
@BinaryName String name = annoType.getName();
assert name != null;
if (adefs.containsKey(name)) {
return adefs.get(name);
}
Map<String,AnnotationFieldType> fieldTypes = new LinkedHashMap<>();
for (Method m : annoType.getDeclaredMethods()) {
AnnotationFieldType aft = AnnotationFieldType.fromClass(m.getReturnType(), adefs);
fieldTypes.put(m.getName(), aft);
}
AnnotationDef result = new AnnotationDef(name, Annotations.noAnnotations, fieldTypes, "class " + annoType);
adefs.put(name, result);
// An annotation can be meta-annotated with itself, so add
// meta-annotations after putting the annotation in the map.
java.lang.annotation.Annotation[] jannos;
try {
jannos = annoType.getDeclaredAnnotations();
} catch (Exception e) {
printClasspath();
throw new Error("Exception in anno.getDeclaredAnnotations() for anno = " + annoType, e);
}
for (java.lang.annotation.Annotation ja : jannos) {
result.tlAnnotationsHere.add(new Annotation(ja, adefs));
}
return result;
}
/**
* Constructs an empty (so far) annotation definition.
*
* @param name the binary name of the annotation
* @param tlAnnotationsHere the meta-annotations that are directly on the annotation definition
* @param source where the annotation came from, such as a filename
*/
public AnnotationDef(@BinaryName String name, Set<Annotation> tlAnnotationsHere, String source) {
super("annotation: " + name);
assert name != null;
assert source != null;
this.name = name;
this.source = source;
if (tlAnnotationsHere != null) {
this.tlAnnotationsHere.addAll(tlAnnotationsHere);
}
}
/**
* Constructs an annotation definition with the given name and field types.
* Uses {@link #setFieldTypes} to protect the
* immutability of the annotation definition.
*
* @param name the binary name of the annotation
* @param tlAnnotationsHere the meta-annotations that are directly on the annotation definition
* @param fieldTypes the annotation's element types
* @param source where the annotation came from, such as a filename
*/
public AnnotationDef(@BinaryName String name, Set<Annotation> tlAnnotationsHere, Map<String, ? extends AnnotationFieldType> fieldTypes, String source) {
this(name, tlAnnotationsHere, source);
setFieldTypes(fieldTypes);
}
// This ovverride is necessary because AnnotationDef extends AElement, which implements Cloneable.
@Override
public AnnotationDef clone() {
throw new UnsupportedOperationException("Can't duplicate an AnnotationDef");
}
/**
* Sets the field types of this annotation.
* The field type map is copied and then wrapped in an
* {@linkplain Collections#unmodifiableMap unmodifiable map} to protect the
* immutability of the annotation definition.
*
* @param fieldTypes the annotation's element types
*/
public void setFieldTypes(Map<String, ? extends AnnotationFieldType> fieldTypes) {
this.fieldTypes = Collections.unmodifiableMap(
new LinkedHashMap<>(fieldTypes)
);
}
/**
* The retention policy for annotations of this type.
* If non-null, this is called a "top-level" annotation definition.
* It may be null for annotations that are used only as a field of other
* annotations.
*
* @return the retention policy for annotations of this type
*/
public @Nullable RetentionPolicy retention() {
if (tlAnnotationsHere.contains(Annotations.aRetentionClass)) {
return RetentionPolicy.CLASS;
} else if (tlAnnotationsHere.contains(Annotations.aRetentionRuntime)) {
return RetentionPolicy.RUNTIME;
} else if (tlAnnotationsHere.contains(Annotations.aRetentionSource)) {
return RetentionPolicy.SOURCE;
} else {
return null;
}
}
/**
* Returns the contents of the java.lang.annotation.Target meta-annotation,
* or null if there is none.
*
* @return the contents of the @Target meta-annotation, or null
*/
public List<String> targets() {
Annotation target = target();
if (target == null) {
return null;
}
@SuppressWarnings("unchecked")
List<String> fieldValue = (List<String>) target.getFieldValue("value");
return fieldValue;
}
/**
* Returns the java.lang.annotation.Target meta-annotation,
* or null if there is none.
*
* @return the @Target meta-annotation, or null
*/
public Annotation target() {
for (Annotation anno : tlAnnotationsHere) {
if (anno.def().equals(Annotations.adTarget)) {
return anno;
}
}
return null;
}
/**
* True if this is valid in type annotation locations.
* It was meta-annotated with @Target({ElementType.TYPE_USE, ...}).
*
* Returns true if this is valid in both type annotation locations and
* (some) declaration locations. To test whether this is valid only in type
* annotation locations, use {@link #isOnlyTypeAnnotation}.
*
* @return true iff this is a type annotation
*/
public boolean isTypeAnnotation() {
List<String> targets = targets();
return targets != null && targets.contains("TYPE_USE");
}
/**
* True if this is a type annotation but not a declaration annotation.
* It was meta-annotated
* with @Target(ElementType.TYPE_USE)
* or @Target({ElementType.TYPE_USE, ElementType.TYPE})
* or @Target({ElementType.TYPE, ElementType.TYPE_USE}).
*
* @return true iff this is valid only in type annotation locations
* @see #isTypeAnnotation
*/
public boolean isOnlyTypeAnnotation() {
boolean result = Annotations.onlyTypeAnnotationTargets.contains(target());
return result;
}
/**
* This {@link AnnotationDef} equals <code>o</code> if and only if
* <code>o</code> is another nonnull {@link AnnotationDef} and
* <code>this</code> and <code>o</code> define annotation types of the same
* name with the same field names and types.
*/
@Override
public boolean equals(Object o) {
return o instanceof AnnotationDef
&& ((AnnotationDef) o).equals(this);
}
/**
* Returns whether this {@link AnnotationDef} equals <code>o</code>; a
* slightly faster variant of {@link #equals(Object)} for when the argument
* is statically known to be another nonnull {@link AnnotationDef}.
*
* @param o another AnnotationDef to compare this to
* @return true if this is equal to the given value
*/
public boolean equals(AnnotationDef o) {
boolean sameName = name.equals(o.name);
boolean sameMetaAnnotations = equalsElement(o);
boolean sameFieldTypes = fieldTypes.equals(o.fieldTypes);
// Can be useful for debugging
if (false && sameName && (! (sameMetaAnnotations
&& sameFieldTypes))) {
String message = String.format("Warning: incompatible definitions of annotation %s%n %s%n %s%n",
name, this, o);
new Exception(message).printStackTrace(System.out);
}
return sameName
&& sameMetaAnnotations
&& sameFieldTypes;
}
@Override
public int hashCode() {
return name.hashCode()
// Omit tlAnnotationsHere, becase it should be unique and, more
// importantly, including it causes an infinite loop.
// + tlAnnotationsHere.hashCode()
+ fieldTypes.hashCode();
}
/**
* Returns an <code>AnnotationDef</code> containing all the information
* from both arguments, or <code>null</code> if the two arguments
* contradict each other. Currently this just
* {@linkplain AnnotationFieldType#unify unifies the field types}
* to handle arrays of unknown element type, which can arise via
* {@link AnnotationBuilder#addEmptyArrayField}.
* <p>
*
* As a special case, if one annotation has no elements, the other one's elements are used.
*
* @param def1 the first AnnotationDef to unify
* @param def2 the second AnnotationDef to unify
* @return an AnnotationDef that contains all the fields of either argument
*/
public static AnnotationDef unify(AnnotationDef def1,
AnnotationDef def2) {
// System.out.printf("unify(%s, %s)%n", def1, def2);
if (def1.equals(def2)) {
return def1;
} else if (def1.name.equals(def2.name)
&& def1.equalsElement(def2)) {
Set<String> ks1 = def1.fieldTypes.keySet();
Set<String> ks2 = def2.fieldTypes.keySet();
if (ks1.isEmpty() || ks2.isEmpty() || ks1.equals(ks2)) {
Map<String, AnnotationFieldType> newFieldTypes
= new LinkedHashMap<>();
for (String fieldName : def1.fieldTypes.keySet()) {
AnnotationFieldType aft1 = def1.fieldTypes.get(fieldName);
AnnotationFieldType aft2 = def2.fieldTypes.get(fieldName);
AnnotationFieldType uaft = aft1 == null ? aft2
: aft2 == null ? aft1
: AnnotationFieldType.unify(aft1, aft2);
if (uaft == null) {
return null;
} else {
newFieldTypes.put(fieldName, uaft);
}
}
return new AnnotationDef(def1.name, def1.tlAnnotationsHere, newFieldTypes,
String.format("unify(%s, %s)", def1.source, def2.source));
}
}
return null;
}
/** The printed representation is: "[meta-annos...] @name(args...)". */
@Override
public String toString() {
String metaAnnos;
if (tlAnnotationsHere.isEmpty()) {
metaAnnos = "";
} else {
StringJoiner metaAnnosJoiner = new StringJoiner(" ", "[", "]");
for (Annotation a : tlAnnotationsHere) {
metaAnnosJoiner.add(a.toString());
}
metaAnnos = metaAnnosJoiner.toString() + " ";
}
StringJoiner args = new StringJoiner(",", "(", ")");
for (Map.Entry<String, AnnotationFieldType> entry : fieldTypes.entrySet()) {
args. add(entry.getValue().toString() + " "+entry.getKey());
}
return metaAnnos.toString() + "@" + name + args.toString();
}
public static void printClasspath() {
System.out.println("Classpath:");
StringTokenizer tokenizer =
new StringTokenizer(System.getProperty("java.class.path"), File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
String cpelt = tokenizer.nextToken();
boolean exists = new File(cpelt).exists();
if (! exists) {
System.out.print(" non-existent:");
}
System.out.println(" " + cpelt);
}
}
}
|
package org.researchstack.skin.ui;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import org.researchstack.backbone.StorageAccess;
import org.researchstack.backbone.helpers.LogExt;
import org.researchstack.backbone.result.TaskResult;
import org.researchstack.backbone.task.Task;
import org.researchstack.backbone.ui.PinCodeActivity;
import org.researchstack.backbone.ui.ViewTaskActivity;
import org.researchstack.backbone.ui.views.IconTabLayout;
import org.researchstack.backbone.utils.ObservableUtils;
import org.researchstack.backbone.utils.UiThreadContext;
import org.researchstack.skin.ActionItem;
import org.researchstack.skin.DataProvider;
import org.researchstack.skin.R;
import org.researchstack.skin.TaskProvider;
import org.researchstack.skin.UiManager;
import org.researchstack.skin.notification.TaskAlertReceiver;
import org.researchstack.skin.ui.adapter.MainPagerAdapter;
import java.util.List;
import rx.Observable;
public class MainActivity extends PinCodeActivity
{
private static final int REQUEST_CODE_INITIAL_TASK = 1010;
private MainPagerAdapter pagerAdapter;
//TODO Quick fix for now.
private boolean failedToFinishInitialTask;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LogExt.d(getClass(), "onCreate");
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
handleNotificationIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
LogExt.d(getClass(), "onNewIntent");
handleNotificationIntent(intent);
}
private void handleNotificationIntent(Intent intent)
{
LogExt.d(getClass(), "handleNotificationIntent");
if(intent != null && intent.hasExtra(TaskAlertReceiver.KEY_NOTIFICATION_ID))
{
// Get the notif-id from the incoming intent
int notificationId = intent.getIntExtra(TaskAlertReceiver.KEY_NOTIFICATION_ID, - 1);
// Create a delete intent w/ notif-id
Intent deleteTaskIntent = TaskAlertReceiver.createDeleteIntent(notificationId);
sendBroadcast(deleteTaskIntent);
// Finally, remove extra from the incoming intent so that, if activity is recreated, we
// do not re-call this method
intent.removeExtra(TaskAlertReceiver.KEY_NOTIFICATION_ID);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == REQUEST_CODE_INITIAL_TASK)
{
if(resultCode == RESULT_OK)
{
TaskResult taskResult = (TaskResult) data.getSerializableExtra(ViewTaskActivity.EXTRA_TASK_RESULT);
StorageAccess.getInstance().getAppDatabase().saveTaskResult(taskResult);
DataProvider.getInstance().processInitialTaskResult(this, taskResult);
}
else
{
failedToFinishInitialTask = true;
}
}
else
{
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
for(ActionItem item : UiManager.getInstance().getMainActionBarItems())
{
MenuItem menuItem = menu.add(item.getGroupId(),
item.getId(),
item.getOrder(),
item.getTitle());
menuItem.setIcon(item.getIcon());
menuItem.setShowAsAction(item.getAction());
menuItem.setIntent(new Intent(this, item.getClazz()));
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
return super.onOptionsItemSelected(item);
}
@Override
public void onDataReady()
{
super.onDataReady();
// Check if we need to run initial Task
if(! failedToFinishInitialTask)
{
Observable.create(subscriber -> {
UiThreadContext.assertBackgroundThread();
if(! DataProvider.getInstance().isSignedIn(MainActivity.this))
{
LogExt.d(getClass(), "User not signed in, skipping initial survey");
subscriber.onCompleted();
return;
}
TaskResult result = StorageAccess.getInstance()
.getAppDatabase()
.loadLatestTaskResult(TaskProvider.TASK_ID_INITIAL);
subscriber.onNext(result == null);
}).compose(ObservableUtils.applyDefault()).subscribe(needsInitialSurvey -> {
if((boolean) needsInitialSurvey)
// DataProvider.getInstance().isSignedIn(MainActivity.this))
{
Task task = TaskProvider.getInstance().get(TaskProvider.TASK_ID_INITIAL);
Intent intent = ViewTaskActivity.newIntent(this, task);
startActivityForResult(intent, MainActivity.REQUEST_CODE_INITIAL_TASK);
}
});
}
if(pagerAdapter == null)
{
List<ActionItem> items = UiManager.getInstance().getMainTabBarItems();
pagerAdapter = new MainPagerAdapter(getSupportFragmentManager(), items);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(pagerAdapter);
IconTabLayout tabLayout = (IconTabLayout) findViewById(R.id.tabLayout);
tabLayout.setOnTabSelectedListener(new IconTabLayout.OnTabSelectedListenerAdapter()
{
@Override
public void onTabSelected(TabLayout.Tab tab)
{
int index = tabLayout.getSelectedTabPosition();
viewPager.setCurrentItem(index);
}
});
for(ActionItem item : items)
{
tabLayout.addIconTab(
item.getTitle(),
item.getIcon(),
items.indexOf(item) == 0,//TODO check if should show
items.indexOf(item) == 0
);
}
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
}
@Override
public void onDataFailed()
{
super.onDataFailed();
//TODO Show dialog explaing what went wrong, instead of finishing activity.
Toast.makeText(this, "Whoops", Toast.LENGTH_LONG).show();
finish();
}
}
|
package com.quickblox.snippets.modules;
import android.content.Context;
import com.quickblox.core.QBCallbackImpl;
import com.quickblox.core.QBRequestCanceler;
import com.quickblox.core.result.Result;
import com.quickblox.internal.core.helper.StringifyArrayList;
import com.quickblox.internal.core.request.QBPagedRequestBuilder;
import com.quickblox.module.auth.model.QBProvider;
import com.quickblox.module.users.QBUsers;
import com.quickblox.module.users.model.QBUser;
import com.quickblox.module.users.result.QBUserPagedResult;
import com.quickblox.module.users.result.QBUserResult;
import com.quickblox.snippets.Snippet;
import com.quickblox.snippets.Snippets;
import java.util.ArrayList;
public class SnippetsUsers extends Snippets {
public SnippetsUsers(Context context) {
super(context);
snippets.add(signInUserWithLogin);
snippets.add(signInUserWithEmail);
snippets.add(signInUsingSocialProvider);
snippets.add(signOut);
snippets.add(signUpUser);
snippets.add(getAllUsers);
snippets.add(getUsersByIds);
snippets.add(getUsersById);
snippets.add(getUserWithLogin);
snippets.add(getUsersWithFullName);
snippets.add(getUserWithTwitterId);
snippets.add(getUserWithFacebookId);
snippets.add(getUserWithEmail);
snippets.add(getUsersWithTags);
snippets.add(getUserWithExternalId);
snippets.add(updateUser);
snippets.add(deleteUserById);
snippets.add(deleteUserByExternalId);
snippets.add(resetPassword);
}
Snippet signInUserWithLogin = new Snippet("sign in user (login)") {
@Override
public void execute() {
final QBUser user = new QBUser("testuser", "testpassword");
final QBRequestCanceler canceler = QBUsers.signIn(user, new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBUserResult qbUserResult = (QBUserResult) result;
System.out.println(">>> lastRequestedAt, " + qbUserResult.getUser().getLastRequestAt());
System.out.println(">>> User was successfully signed in, " + qbUserResult.getUser().toString());
} else {
handleErrors(result);
}
}
});
}
};
Snippet signInUserWithEmail = new Snippet("sign in user (email)") {
@Override
public void execute() {
final QBUser user = new QBUser();
user.setEmail("test987@test.com");
user.setPassword("testpassword");
QBUsers.signIn(user, new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBUserResult qbUserResult = (QBUserResult) result;
System.out.println(">>> User was successfully signed in, " + qbUserResult.getUser().toString());
} else {
handleErrors(result);
}
}
});
}
};
Snippet signInUsingSocialProvider = new Snippet("sign in using social provider") {
@Override
public void execute() {
String facebookAccessToken = "AAAEra8jNdnkBABYf3ZBSAz9dgLfyK7tQNttIoaZA1cC40niR6HVS0nYuufZB0ZCn66VJcISM8DO2bcbhEahm2nW01ZAZC1YwpZB7rds37xW0wZDZD";
QBUsers.signInUsingSocialProvider(QBProvider.TWITTER, facebookAccessToken, null, new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBUserResult qbUserResult = (QBUserResult) result;
System.out.println(">>> User was successfully signed in, " + qbUserResult.getUser().toString());
} else {
handleErrors(result);
}
}
});
}
};
Snippet signOut = new Snippet("sign out") {
@Override
public void execute() {
QBUsers.signOut(new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
System.out.println(">>> User was successfully signed out");
} else {
handleErrors(result);
}
}
});
}
};
Snippet signUpUser = new Snippet("sign up user (register)") {
@Override
public void execute() {
final QBUser user = new QBUser("testuser12344443", "testpassword");
user.setEmail("test123456789w0@test.com");
user.setExternalId("02345777");
user.setFacebookId("1233453457767");
user.setTwitterId("12334635457");
user.setFullName("fullName5");
user.setPhone("+18904567812");
StringifyArrayList<String> tags = new StringifyArrayList<String>();
tags.add("firstTag");
tags.add("secondTag");
tags.add("thirdTag");
tags.add("fourthTag");
user.setTags(tags);
user.setWebsite("website.com");
QBUsers.signUp(user, new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBUserResult qbUserResult = (QBUserResult) result;
System.out.println(">>> User was successfully signed up, " + qbUserResult.getUser().toString());
} else {
handleErrors(result);
}
}
});
}
};
Snippet getAllUsers = new Snippet("get all users") {
@Override
public void execute() {
QBPagedRequestBuilder pagedRequestBuilder = new QBPagedRequestBuilder();
pagedRequestBuilder.setPage(2);
pagedRequestBuilder.setPerPage(5);
QBUsers.getUsers(pagedRequestBuilder, new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBUserPagedResult usersResult = (QBUserPagedResult) result;
ArrayList<QBUser> users = usersResult.getUsers();
System.out.println(">>> Users: " + users.toString());
System.out.println("currentPage: " + usersResult.getCurrentPage());
System.out.println("totalEntries: " + usersResult.getTotalEntries());
System.out.println("perPage: " + usersResult.getPerPage());
System.out.println("totalPages: " + usersResult.getTotalPages());
} else {
handleErrors(result);
}
}
});
}
};
Snippet getUsersByIds = new Snippet("get users by ids") {
@Override
public void execute() {
QBPagedRequestBuilder pagedRequestBuilder = new QBPagedRequestBuilder();
pagedRequestBuilder.setPage(1);
pagedRequestBuilder.setPerPage(10);
ArrayList<String> userIds = new ArrayList<String>();
userIds.add("378");
userIds.add("379");
userIds.add("380");
QBUsers.getUsersByIDs(userIds, pagedRequestBuilder, new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBUserPagedResult usersResult = (QBUserPagedResult) result;
ArrayList<QBUser> users = usersResult.getUsers();
System.out.println(">>> Users: " + users.toString());
} else {
handleErrors(result);
}
}
});
}
};
Snippet getUsersById = new Snippet("get user by id") {
@Override
public void execute() {
QBUsers.getUser(37823232, new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBUserResult qbUserResult = (QBUserResult) result;
System.out.println(">>> User: " + qbUserResult.getUser().toString());
} else {
handleErrors(result);
}
}
});
}
};
Snippet getUserWithLogin = new Snippet("get user with login") {
@Override
public void execute() {
String login = "testuser";
QBUsers.getUserByLogin(login, new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBUserResult qbUserResult = (QBUserResult) result;
System.out.println(">>> User: " + qbUserResult.getUser().toString());
} else {
handleErrors(result);
}
}
});
}
};
Snippet getUsersWithFullName = new Snippet("get user with full name") {
@Override
public void execute() {
String fullName = "fullName";
QBUsers.getUsersByFullName(fullName, new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBUserPagedResult usersResult = (QBUserPagedResult) result;
ArrayList<QBUser> users = usersResult.getUsers();
System.out.println(">>> Users: " + users.toString());
} else {
handleErrors(result);
}
}
});
}
};
Snippet getUserWithTwitterId = new Snippet("get user with twitter id") {
@Override
public void execute() {
String twitterId = "56802037340";
QBUsers.getUserByTwitterId(twitterId, new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBUserResult qbUserResult = (QBUserResult) result;
System.out.println(">>> User: " + qbUserResult.getUser().toString());
} else {
handleErrors(result);
}
}
});
}
};
Snippet getUserWithFacebookId = new Snippet("get user with facebook id") {
@Override
public void execute() {
String facebookId = "100003123141430";
QBUsers.getUserByFacebookId(facebookId, new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBUserResult qbUserResult = (QBUserResult) result;
System.out.println(">>> User: " + qbUserResult.getUser().toString());
} else {
handleErrors(result);
}
}
});
}
};
Snippet getUserWithEmail = new Snippet("get user with email") {
@Override
public void execute() {
String email = "test123@test.com";
QBUsers.getUserByEmail(email, new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBUserResult qbUserResult = (QBUserResult) result;
System.out.println(">>> User: " + qbUserResult.getUser().toString());
} else {
handleErrors(result);
}
}
});
}
};
Snippet getUsersWithTags = new Snippet("get users with tags") {
@Override
public void execute() {
ArrayList<String> userTags = new ArrayList<String>();
userTags.add("man");
userTags.add("car");
QBUsers.getUsersByTags(userTags, new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBUserPagedResult usersResult = (QBUserPagedResult) result;
ArrayList<QBUser> users = usersResult.getUsers();
System.out.println(">>> Users: " + users.toString());
} else {
handleErrors(result);
}
}
});
}
};
Snippet getUserWithExternalId = new Snippet("get user with external id") {
@Override
public void execute() {
String externalId = "123145235";
QBUsers.getUserByExternalId(externalId, new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBUserResult qbUserResult = (QBUserResult) result;
System.out.println(">>> User: " + qbUserResult.getUser().toString());
} else {
handleErrors(result);
}
}
});
}
};
Snippet updateUser = new Snippet("update user") {
@Override
public void execute() {
final QBUser user = new QBUser();
user.setId(53779);
user.setFullName("Monro");
user.setEmail("test987@test.com");
user.setExternalId("987");
user.setFacebookId("987");
user.setTwitterId("987");
user.setFullName("galog");
user.setPhone("+123123123");
StringifyArrayList<String> tags = new StringifyArrayList<String>();
tags.add("man");
user.setTags(tags);
user.setWebsite("google.com");
QBUsers.updateUser(user, new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBUserResult qbUserResult = (QBUserResult) result;
System.out.println(">>> updatedAt: " + qbUserResult.getUser().getUpdatedAt());
System.out.println(">>> createdAt: " + qbUserResult.getUser().getCreatedAt());
System.out.println(">>> User: " + qbUserResult.getUser().toString());
} else {
handleErrors(result);
}
}
});
}
};
Snippet deleteUserById = new Snippet("delete user by id") {
@Override
public void execute() {
int userId = 562;
QBUsers.deleteUser(userId, new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
System.out.println(">>> User was successfully deleted");
} else {
handleErrors(result);
}
}
});
}
};
Snippet deleteUserByExternalId = new Snippet("delete user by external id") {
@Override
public void execute() {
QBUsers.deleteByExternalId("568965444", new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
System.out.println(">>> User was successfully deleted");
} else {
handleErrors(result);
}
}
});
}
};
Snippet resetPassword = new Snippet("reset password") {
@Override
public void execute() {
QBUsers.resetPassword("test987@test.com", new QBCallbackImpl() {
@Override
public void onComplete(Result result) {
if (result.isSuccess()) {
System.out.println(">>> Email was sent");
} else {
handleErrors(result);
}
}
});
}
};
}
|
package org.intermine.web.logic;
import java.util.HashMap;
import java.util.Map;
import org.intermine.web.logic.widget.Hypergeometric;
import java.math.BigDecimal;
import junit.framework.TestCase;
public class WebUtilTest extends TestCase
{
private Double maxValue = 1000.0;
private HashMap<String, BigDecimal> resultsMap = new HashMap();
private String[] id = new String[4];
private int[] taggedSample = new int[4];
private int[] taggedPopulation = new int[4];
private BigDecimal[] expectedResults = new BigDecimal[4];
private int bagsize = 3;
private int total = 100;
HashMap<String, BigDecimal> bonferroniMap = new HashMap();
HashMap<String, BigDecimal> benjaminiMap = new HashMap();
public WebUtilTest(String arg) {
super(arg);
}
public void setUp() throws Exception {
// these numbers are generated via this website:
id[0] = "notEnriched";
taggedSample[0] = 1;
taggedPopulation[0] = 10;
expectedResults[0] = new BigDecimal(0.27346938775509510577421679045073688030242919921875);
id[1] = "underrepresented";
taggedSample[1] = 1;
taggedPopulation[1] = 50;
expectedResults[1] = new BigDecimal(0.8787878787878582);
id[2] = "overrepresented";
taggedSample[2] = 3;
taggedPopulation[2] = 20;
expectedResults[2] = new BigDecimal(0.00705009276437833);
id[3] = "one";
taggedSample[3] = 3;
taggedPopulation[3] = 100;
expectedResults[3] = new BigDecimal(1);
for (int i = 0; i < 4; i++) {
double p = Hypergeometric.calculateP(taggedSample[i], bagsize, taggedPopulation[i], total);
resultsMap.put(id[i], new BigDecimal(p));
bonferroniMap.put(id[i], new BigDecimal(p * bagsize));
benjaminiMap.put(id[i], new BigDecimal(p));
}
}
public void testHypergeometric() throws Exception {
for (int i = 0; i < 4; i++) {
assertEquals(expectedResults[i], resultsMap.get(id[i]));
}
}
public void testBonferroni() throws Exception {
Map<String, BigDecimal> adjustedMap = WebUtil.calcErrorCorrection("Bonferroni", maxValue, resultsMap);
// rounding issue
for (String label : bonferroniMap.keySet()) {
BigDecimal expected = bonferroniMap.get(label);
BigDecimal actual = adjustedMap.get(label);
assert(expected.compareTo(actual) == 0);
}
}
public void testBenjaminiHochberg() throws Exception {
// largest p-value doesn't get adjusted
// id[1] = "underrepresented";
double p = resultsMap.get(id[0]).doubleValue();
p = p * (bagsize / (bagsize -1) );
benjaminiMap.put(id[0], new BigDecimal(p));
p = resultsMap.get(id[2]).doubleValue();
p = p * (bagsize / (bagsize -2) );
benjaminiMap.put(id[2], new BigDecimal(p));
Map<String, BigDecimal> adjustedMap = WebUtil.calcErrorCorrection("BenjaminiHochberg", maxValue, resultsMap);
// rounding issue
for (String label : benjaminiMap.keySet()) {
BigDecimal expected = benjaminiMap.get(label);
BigDecimal actual = adjustedMap.get(label);
assert(expected.compareTo(actual) == 0);
}
}
}
|
package org.intermine.web.logic;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import junit.framework.TestCase;
import org.intermine.metadata.Model;
import org.intermine.pathquery.Path;
import org.intermine.pathquery.PathException;
import org.intermine.pathquery.PathQuery;
import org.intermine.web.logic.config.WebConfig;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.struts.MockServletContext;
import org.xml.sax.SAXException;
public class WebUtilTest extends TestCase {
MockServletContext context = new MockServletContext();
WebConfig config;
Model model;
public WebUtilTest(final String arg) throws FileNotFoundException,
IOException, SAXException, ClassNotFoundException {
super(arg);
final Properties p = new Properties();
p.setProperty("web.config.classname.mappings", "CLASS_NAME_MAPPINGS");
p.setProperty("web.config.fieldname.mappings", "FIELD_NAME_MAPPINGS");
SessionMethods.setWebProperties(context, p);
final InputStream is = getClass().getClassLoader().getResourceAsStream(
"WebConfigTest.xml");
final InputStream classesIS = getClass().getClassLoader()
.getResourceAsStream("testClassMappings.properties");
final InputStream fieldsIS = getClass().getClassLoader()
.getResourceAsStream("testFieldMappings.properties");
context.addInputStream("/WEB-INF/webconfig-model.xml", is);
context.addInputStream("/WEB-INF/CLASS_NAME_MAPPINGS", classesIS);
context.addInputStream("/WEB-INF/FIELD_NAME_MAPPINGS", fieldsIS);
model = Model.getInstanceByName("testmodel");
config = WebConfig.parse(context, model);
}
public void testFormatPath() throws PathException {
Path p = new Path(model, "Employee.name");
String expected = "Angestellter > Name";
// Check class name labels
assertEquals(expected, WebUtil.formatPath(p, config));
p = new Path(model, "Contractor.oldComs.vatNumber");
// Check reference and attribute labels
expected = "Contractor > Companies they used to work for > VAT Number";
assertEquals(expected, WebUtil.formatPath(p, config));
p = new Path(model, "Contractor.personalAddress.address");
// Check default munging
expected = "Contractor > Personal Address > Address";
assertEquals(expected, WebUtil.formatPath(p, config));
// Check path making
expected = "Contractor > Companies they used to work for > VAT Number";
assertEquals(expected, WebUtil.formatPath(
"Contractor.oldComs.vatNumber", model, config));
// Check path making, complete labelling
expected = "Firma > Abteilungen > Angestellter";
assertEquals(expected, WebUtil.formatPath(
"Company.departments.employees", model, config));
// Check composite attribute labelling
p = new Path(model, "Employee.department.name");
expected = "Angestellter > Abteilung";
assertEquals(expected, WebUtil.formatPath(p, config));
// Check composite attribute labelling, from a reference.
p = new Path(model, "Manager.department.employees.department.name");
expected = "Manager > Department > Angestellter > Abteilung";
assertEquals(expected, WebUtil.formatPath(p, config));
}
public void testFormatField() throws PathException {
Path p = new Path(model, "Employee.name");
String expected = "Name";
assertEquals(expected, WebUtil.formatField(p, config));
p = new Path(model, "Contractor.oldComs.vatNumber");
expected = "VAT Number";
assertEquals(expected, WebUtil.formatField(p, config));
p = new Path(model, "Contractor.personalAddress");
expected = "Personal Address";
assertEquals(expected, WebUtil.formatField(p, config));
}
public void testSubclassedPath() throws PathException {
Path p;
String expected;
p = new Path(model, "Department.employees[Manager].seniority");
expected = "Abteilung > Angestellter > Seniority";
assertEquals(expected, WebUtil.formatPath(p, config));
p = new Path(model, "Company.departments.employees[Manager].seniority");
expected = "Firma > Abteilungen > Angestellter > Seniority";
assertEquals(expected, WebUtil.formatPath(p, config));
}
public void testFormatPathDescription() {
final PathQuery pq = new PathQuery(model);
pq.setDescription("Employee.department.company", "COMPANY");
pq.setDescription("Employee.department", "DEPARTMENT");
pq.setDescription("Employee", "EMPLOYEE");
assertEquals("EMPLOYEE",
WebUtil.formatPathDescription("Employee", pq, config));
assertEquals("EMPLOYEE > Years Alive",
WebUtil.formatPathDescription("Employee.age", pq, config));
assertEquals("EMPLOYEE > Address > Address",
WebUtil.formatPathDescription("Employee.address.address", pq,
config));
assertEquals("EMPLOYEE > Full Time",
WebUtil.formatPathDescription("Employee.fullTime", pq, config));
assertEquals("DEPARTMENT", WebUtil.formatPathDescription(
"Employee.department", pq, config));
}
public void testCompositePathDescriptions() {
final PathQuery pq = new PathQuery(model);
pq.setDescription("Employee.department.company", "COMPANY");
pq.setDescription("Employee.department", "DEPARTMENT");
pq.setDescription("Employee.address", "RESIDENCE");
pq.setDescription("Employee", "EMPLOYEE");
assertEquals("RESIDENCE > Address", WebUtil.formatPathDescription(
"Employee.address.address", pq, config));
// Obeys existing composite rules for attributes.
assertEquals("DEPARTMENT", WebUtil.formatPathDescription(
"Employee.department.name", pq, config));
assertEquals("DEPARTMENT > Manager > Name",
WebUtil.formatPathDescription(
"Employee.department.manager.name", pq, config));
assertEquals("COMPANY", WebUtil.formatPathDescription(
"Employee.department.company", pq, config));
assertEquals("COMPANY > Abteilungen > Manager > Years Alive",
WebUtil.formatPathDescription(
"Employee.department.company.departments.manager.age",
pq, config));
// Paths without any configuration are handled as per formatPath
assertEquals("Contractor > Companies they used to work for > VAT Number",
WebUtil.formatPathDescription("Contractor.oldComs.vatNumber", pq, config));
}
/**
* Check that formatted pathquery views take both the pathdescriptions and the webconfig into account.
*/
public void testFormatPathQueryView() {
final PathQuery pq = new PathQuery(model);
pq.setDescription("Employee.department.company", "COMPANY");
pq.setDescription("Employee.department", "DEPARTMENT");
pq.setDescription("Employee", "EMPLOYEE");
pq.addViews("Employee.name", "Employee.fullTime", "Employee.department.name",
"Employee.department.company.contractors.oldComs.vatNumber");
final List<String> expected = Arrays.asList("EMPLOYEE > Name", "EMPLOYEE > Full Time",
"DEPARTMENT", "COMPANY > Contractors > Companies they used to work for > VAT Number");
assertEquals(expected, WebUtil.formatPathQueryView(pq, config));
}
}
|
package org.opennms.smoketest;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MenuHeaderTest extends OpenNMSSeleniumTestCase {
@Test
public void testMenuEntries() throws Exception {
clickMenuItem("Search", null, "element/index.jsp");
findElementByXpath("//h3[text()='Search for Nodes']");
clickMenuItem("Info", "Nodes", "element/nodeList.htm");
findElementByXpath("//h3//span[text()='Nodes' or text()='Availability']");
clickMenuItem("Info", "Assets", "asset/index.jsp");
findElementByXpath("//h3[text()='Search Asset Information']");
clickMenuItem("Info", "Path Outages", "pathOutage/index.jsp");
findElementByXpath("//h3[text()='All Path Outages']");
clickMenuItem("Status", "Events", "event/index");
findElementByXpath("//h3[text()='Event Queries']");
clickMenuItem("Status", "Alarms", "alarm/index.htm");
findElementByXpath("//h3[text()='Alarm Queries']");
clickMenuItem("Status", "Notifications", "notification/index.jsp");
findElementByXpath("//h3[text()='Notification queries']");
clickMenuItem("Status", "Outages", "outage/index.jsp");
findElementByXpath("//h3[text()='Outage Menu']");
clickMenuItem("Status", "Distributed Status", "distributedStatusSummary.htm");
findElementByXpath("//h3[contains(text(), 'Distributed Status Summary')]");
clickMenuItem("Status", "Surveillance", "surveillance-view.jsp");
findElementByXpath("//select[@class='v-select-select']");
clickMenuItem("Reports", "Charts", "charts/index.jsp");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("include-charts")));
clickMenuItem("Reports", "Resource Graphs", "graph/index.jsp");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h3[contains(text(), 'Standard Resource')]")));
clickMenuItem("Reports", "KSC Reports", "KSC/index.htm");
findElementByXpath("//h3[text()='Customized Reports']");
clickMenuItem("Reports", "Statistics", "statisticsReports/index.htm");
findElementByXpath("//h3[text()='Statistics Report List']");
clickMenuItem("Dashboards", "Dashboard", "dashboard.jsp");
findElementByXpath("//select[@class='v-select-select']");
clickMenuItem("Dashboards", "Ops Board", "vaadin-wallboard");
findElementByXpath("//select[@class='v-select-select']");
frontPage();
clickMenuItem("Maps", "Distributed", "RemotePollerMap/index.jsp");
m_driver.switchTo().frame("app");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("gwt-uid-1")));
frontPage();
clickMenuItem("Maps", "Topology", "topology");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(), 'Last update time')]")));
frontPage();
clickMenuItem("Maps", "Geographical", "node-maps");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[text()='Show Severity >=']")));
frontPage();
clickMenuItem("Maps", "SVG", "map/index.jsp");
findElementById("opennmsSVGMaps");
try {
final Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.dismiss();
} catch (final Exception e) {
}
frontPage();
clickMenuItem("name=nav-admin-top", "Configure OpenNMS", BASE_URL + "opennms/admin/index.jsp");
findElementByXpath("//h3[text()='OpenNMS System']");
findElementByXpath("//h3[text()='Operations']");
frontPage();
clickMenuItem("name=nav-admin-top", "Quick-Add Node", BASE_URL + "opennms/admin/node/add.htm");
findElementByXpath("//h3[text()='Node Quick-Add']");
frontPage();
clickMenuItem("name=nav-admin-top", "Help/Support", BASE_URL + "opennms/support/index.htm");
findElementByXpath("//h3[text()='Commercial Support']");
frontPage();
clickMenuItem("name=nav-admin-top", "Log Out", BASE_URL + "opennms/j_spring_security_logout");
findElementById("input_j_username");
}
}
|
package adk.sample.basic.util;
import adk.team.util.DebrisRemovalSelector;
import adk.team.util.PositionUtil;
import adk.team.util.provider.WorldProvider;
import rescuecore2.standard.entities.Blockade;
import rescuecore2.standard.entities.Road;
import rescuecore2.standard.entities.StandardEntity;
import rescuecore2.worldmodel.EntityID;
import java.util.HashSet;
import java.util.Set;
public class BasicDebrisRemovalSelector implements DebrisRemovalSelector {
public Set<Road> impassableRoadList;
public Set<EntityID> passableRoadList;
public WorldProvider<? extends StandardEntity> provider;
public BasicDebrisRemovalSelector(WorldProvider<? extends StandardEntity> user) {
this.provider = user;
this.impassableRoadList = new HashSet<>();
this.passableRoadList = new HashSet<>();
}
@Override
public void add(Road road) {
if(!this.passableRoadList.contains(road.getID()) && !road.getBlockades().isEmpty()) {
this.impassableRoadList.add(road);
}
}
@Override
public void add(Blockade blockade) {
Road road = (Road)this.provider.getWorld().getEntity(blockade.getPosition());
if(!this.passableRoadList.contains(road.getID())) {
this.impassableRoadList.add(road);
}
}
@Override
public void add(EntityID id) {
StandardEntity entity = this.provider.getWorld().getEntity(id);
if(entity instanceof Road) {
this.add((Road)entity);
}
else if(entity instanceof Blockade) {
this.add((Blockade)entity);
}
}
@Override
public void remove(Road road) {
this.impassableRoadList.remove(road);
this.passableRoadList.add(road.getID());
}
@Override
public void remove(Blockade blockade) {
Road road = (Road)this.provider.getWorld().getEntity(blockade.getPosition());
if(road.getBlockades().isEmpty()) {
this.remove(road);
}
}
@Override
public void remove(EntityID id) {
StandardEntity entity = this.provider.getWorld().getEntity(id);
if(entity instanceof Road) {
this.remove((Road) entity);
}
else if(entity instanceof Blockade) {
this.remove((Blockade) entity);
}
}
@Override
public EntityID getTarget(int time) {
StandardEntity result = PositionUtil.getNearTarget(this.provider.getWorld(), this.provider.getOwner(), this.impassableRoadList);
return result != null ? result.getID() : null;
}
}
|
package net.teamio.taam.content.piping;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTankInfo;
import net.minecraftforge.fluids.IFluidHandler;
import net.teamio.taam.content.BaseTileEntity;
import net.teamio.taam.content.IRenderable;
import net.teamio.taam.piping.IPipe;
import net.teamio.taam.piping.IPipeTE;
import net.teamio.taam.piping.PipeEndFluidHandler;
import net.teamio.taam.piping.PipeInfo;
import net.teamio.taam.piping.PipeUtil;
public class TileEntityPipe extends BaseTileEntity implements IPipe, IPipeTE, ITickable, IRenderable {
private final PipeInfo info;
private static final List<String> visibleParts = new ArrayList<String>(7);
/**
* Bitmap containing the surrounding pipes Runtime-only, required for
* rendering. This is updated in the {@link #renderUpdate()} method, called
* from
* {@link net.minecraft.block.Block#getActualState(net.minecraft.block.state.IBlockState, IBlockAccess, BlockPos)}
* just before rendering.
*/
private byte adjacentPipes;
private PipeEndFluidHandler[] adjacentFluidHandlers;
public TileEntityPipe() {
info = new PipeInfo(500);
}
@Override
public List<String> getVisibleParts() {
// Visible parts list is re-used, as it is only used once for updating
// an OBJState anyways.
visibleParts.clear();
visibleParts.add("Center_pcmdl");
if (isSideConnected(EnumFacing.EAST))
visibleParts.add("FlangeMX_pfmdl");
if (isSideConnected(EnumFacing.WEST))
visibleParts.add("FlangePX_pfmdl");
if (isSideConnected(EnumFacing.NORTH))
visibleParts.add("FlangeMY_pfmdl");
if (isSideConnected(EnumFacing.SOUTH))
visibleParts.add("FlangePY_pfmdl");
if (isSideConnected(EnumFacing.DOWN))
visibleParts.add("FlangeMZ_pfmdl");
if (isSideConnected(EnumFacing.UP))
visibleParts.add("FlangePZ_pfmdl");
return visibleParts;
}
public boolean isSideConnected(EnumFacing side) {
return (adjacentPipes & (1 << side.ordinal())) != 0;
}
private IFluidHandler getFluidHandler(TileEntity te, EnumFacing mySide) {
if(te instanceof IFluidHandler) {
IFluidHandler fh = (IFluidHandler)te;
FluidTankInfo[] info = fh.getTankInfo(mySide.getOpposite());
if(info != null && info.length > 0) {
return fh;
}
}
return null;
}
public void renderUpdate() {
adjacentPipes = 0;
for (EnumFacing side : EnumFacing.VALUES) {
IPipe[] pipesOnSide = PipeUtil.getConnectedPipes(worldObj, pos, side);
if (pipesOnSide != null && pipesOnSide.length != 0) {
adjacentPipes |= 1 << side.ordinal();
continue;
}
TileEntity te = worldObj.getTileEntity(pos.offset(side));
if(getFluidHandler(te, side) != null) {
adjacentPipes |= 1 << side.ordinal();
}
}
};
@Override
public void blockUpdate() {
// Check surrounding blocks for IFluidHandler implementations that don't use the pipe system
// and create wrappers accordingly
boolean wrappersRequired = false;
for (EnumFacing side : EnumFacing.VALUES) {
int sideIdx = side.ordinal();
IPipe[] pipesOnSide = PipeUtil.getConnectedPipes(worldObj, pos, side);
if (pipesOnSide == null || pipesOnSide.length == 0) {
TileEntity te = worldObj.getTileEntity(pos.offset(side));
IFluidHandler fh = getFluidHandler(te, side);
if(fh != null) {
wrappersRequired = true;
// Fluid handler here, we need a wrapper.
if(adjacentFluidHandlers == null) {
adjacentFluidHandlers = new PipeEndFluidHandler[6];
adjacentFluidHandlers[sideIdx] = new PipeEndFluidHandler(fh, side.getOpposite());
} else {
// Not yet known or a different TileEntity, we need a new wrapper.
if(adjacentFluidHandlers[sideIdx] == null || adjacentFluidHandlers[sideIdx].getOwner() != te) {
adjacentFluidHandlers[sideIdx] = new PipeEndFluidHandler(fh, side.getOpposite());
}
}
}
} else {
// We have a regular pipe there, no need for a wrapper
if(adjacentFluidHandlers != null) {
adjacentFluidHandlers[sideIdx] = null;
}
}
}
// No wrappers required, delete the array
if(!wrappersRequired) {
adjacentFluidHandlers = null;
}
super.blockUpdate();
}
@Override
public void update() {
// Process "this"
PipeUtil.processPipes(this, worldObj, pos);
//Process the fluid handlers for adjecent non-pipe-machines (implementing IFluidHandler)
if(adjacentFluidHandlers != null) {
for (EnumFacing side : EnumFacing.VALUES) {
PipeEndFluidHandler handler = adjacentFluidHandlers[side.ordinal()];
if(handler != null) {
PipeUtil.processPipes(handler, worldObj, pos.offset(side));
}
}
}
updateState();
}
@Override
protected void readPropertiesFromNBT(NBTTagCompound tag) {
info.readFromNBT(tag);
}
@Override
protected void writePropertiesToNBT(NBTTagCompound tag) {
info.writeToNBT(tag);
}
/*
* IPipeTE implementation
*/
@Override
public IPipe[] getPipesForSide(EnumFacing side) {
return new IPipe[] { this };
}
/*
* IPipe implementation
*/
@Override
public int getPressure() {
return info.pressure;
}
@Override
public int addFluid(FluidStack stack) {
markDirty();
return info.addFluid(stack);
}
@Override
public FluidStack[] getFluids() {
return info.getFluids();
}
@Override
public int getCapacity() {
return info.capacity;
}
@Override
public void setPressure(int pressure) {
info.pressure = pressure;
}
@Override
public void setSuction(int suction) {
info.suction = suction;
}
@Override
public int getSuction() {
return info.suction;
}
@Override
public boolean isActive() {
return false;
}
@Override
public IPipe[] getConnectedPipes(IBlockAccess world, BlockPos pos) {
List<IPipe> pipes = new ArrayList<IPipe>(6);
for (EnumFacing side : EnumFacing.values()) {
IPipe[] pipesOnSide = PipeUtil.getConnectedPipes(world, pos, side);
if (pipesOnSide != null) {
Collections.addAll(pipes, pipesOnSide);
}
int sideIdx = side.ordinal();
if(adjacentFluidHandlers != null && adjacentFluidHandlers[sideIdx] != null) {
pipes.add(adjacentFluidHandlers[sideIdx]);
}
}
return pipes.toArray(new IPipe[pipes.size()]);
}
@Override
public int removeFluid(FluidStack like) {
return info.removeFluid(like);
}
@Override
public int getFluidAmount(FluidStack like) {
return info.getFluidAmount(like);
}
}
|
package org.opennms.smoketest;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class QuickAddNodeIT extends OpenNMSSeleniumTestCase {
/** The Constant NODE_LABEL. */
private static final String NODE_LABEL = "localNode";
private static final String NODE_IPADDR = "127.0.0.1";
private static final String NODE_CATEGORY = "Test";
/**
* Sets up the test.
*
* @throws Exception the exception
*/
@Before
public void setUp() throws Exception {
deleteTestRequisition();
createTestRequisition();
provisioningPage();
}
/**
* Tears down the test.
* <p>Be 100% sure that there are no left-overs on the testing OpenNMS installation.</p>
*
* @throws Exception the exception
*/
@After
public void tearDown() throws Exception {
deleteTestRequisition();
}
@Test
public void testQuickAddNode() throws Exception {
adminPage();
clickMenuItem("name=nav-admin-top", "Quick-Add Node", "admin/ng-requisitions/app/quick-add-node.jsp");
// Basic fields
findElementByCss("input#foreignSource");
Thread.sleep(1000);
enterTextAutocomplete(By.id("foreignSource"), REQUISITION_NAME);
enterText(By.id("ipAddress"), NODE_IPADDR);
enterText(By.id("nodeLabel"), NODE_LABEL);
// Add a category to the node
findElementById("add-category").click();
findElementByCss("input[name='categoryName'");
enterTextAutocomplete(By.cssSelector("input[name='categoryName']"), NODE_CATEGORY, Keys.ENTER);
wait.until(ExpectedConditions.elementToBeClickable(By.id("provision"))).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".modal-dialog button[data-bb-handler='main']"))).click();
wait.until(new WaitForNodesInDatabase(1));
}
protected WebElement enterTextAutocomplete(final By selector, final CharSequence... text) throws InterruptedException {
final WebElement element = m_driver.findElement(selector);
element.click();
Thread.sleep(500);
element.sendKeys(text);
Thread.sleep(100);
element.sendKeys(Keys.ENTER);
Thread.sleep(100);
try {
setImplicitWait(5, TimeUnit.SECONDS);
final List<WebElement> matching = m_driver.findElements(By.cssSelector("a[title='"+text+"']"));
if (!matching.isEmpty()) {
findElementByCss("a[title='"+text+"']").click();
}
} finally {
setImplicitWait();
}
return element;
}
}
|
package org.slc.sli.api.service;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Collections;
import java.util.Collection;
import org.slc.sli.api.client.constants.EntityNames;
import org.slc.sli.api.config.EntityDefinition;
import org.slc.sli.api.representation.EntityBody;
import org.slc.sli.api.security.CallingApplicationInfoProvider;
import org.slc.sli.api.security.SLIPrincipal;
import org.slc.sli.api.security.context.ContextResolverStore;
import org.slc.sli.api.security.context.resolver.AllowAllEntityContextResolver;
import org.slc.sli.api.security.context.resolver.EntityContextResolver;
import org.slc.sli.api.security.schema.SchemaDataProvider;
import org.slc.sli.api.util.SecurityUtil;
import org.slc.sli.dal.convert.IdConverter;
import org.slc.sli.domain.Entity;
import org.slc.sli.domain.NeutralCriteria;
import org.slc.sli.domain.NeutralQuery;
import org.slc.sli.domain.QueryParseException;
import org.slc.sli.domain.Repository;
import org.slc.sli.domain.enums.Right;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
/**
* Implementation of EntityService that can be used for most entities.
*
* It is very important this bean prototype scope, since one service is needed per
* entity/association.
*/
@Scope("prototype")
@Component("basicService")
public class BasicService implements EntityService {
private static final String ADMIN_SPHERE = "Admin";
private static final String PUBLIC_SPHERE = "Public";
private static final int MAX_RESULT_SIZE = 9999;
private static final String CUSTOM_ENTITY_COLLECTION = "custom_entities";
private static final String CUSTOM_ENTITY_CLIENT_ID = "clientId";
private static final String CUSTOM_ENTITY_ENTITY_ID = "entityId";
private static final String METADATA = "metaData";
private String collectionName;
private List<Treatment> treatments;
private EntityDefinition defn;
private Right readRight;
private Right writeRight; // this is possibly the worst named variable ever
@Autowired
private Repository<Entity> repo;
@Autowired
private ContextResolverStore contextResolverStore;
@Autowired
private SchemaDataProvider provider;
@Autowired
private IdConverter idConverter;
@Autowired
private CallingApplicationInfoProvider clientInfo;
public BasicService(String collectionName, List<Treatment> treatments, Right readRight, Right writeRight) {
this.collectionName = collectionName;
this.treatments = treatments;
this.readRight = readRight;
this.writeRight = writeRight;
}
public BasicService(String collectionName, List<Treatment> treatments) {
this(collectionName, treatments, Right.READ_GENERAL, Right.WRITE_GENERAL);
}
@Override
public long count(NeutralQuery neutralQuery) {
checkRights(readRight);
checkFieldAccess(neutralQuery);
NeutralCriteria securityCriteria = findAccessible();
List<String> allowed = (List<String>) securityCriteria.getValue();
if (allowed.isEmpty() && readRight != Right.ANONYMOUS_ACCESS) {
return 0;
}
Set<String> ids = new HashSet<String>();
List<NeutralCriteria> criterias = neutralQuery.getCriteria();
for (NeutralCriteria criteria : criterias) {
if (criteria.getKey().equals("_id")) {
@SuppressWarnings("unchecked")
List<String> idList = (List<String>) criteria.getValue();
ids.addAll(idList);
}
}
NeutralQuery localNeutralQuery = new NeutralQuery(neutralQuery);
if (securityCriteria.getKey().equals("_id")) {
if (allowed.size() >= 0 && readRight != Right.ANONYMOUS_ACCESS) {
if (!ids.isEmpty()) {
ids.retainAll(new HashSet<String>(allowed)); // retain only those IDs that area
// allowed
//update the security criteria
securityCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, new ArrayList<String>(ids));
}
}
}
//add the security criteria
localNeutralQuery.addCriteria(securityCriteria);
return repo.count(collectionName, localNeutralQuery);
}
/**
* Retrieves an entity from the data store with certain fields added/removed.
*
* @param neutralQuery
* all parameters to be included in query
* @return the body of the entity
*/
@Override
public Iterable<String> listIds(NeutralQuery neutralQuery) {
checkRights(readRight);
checkFieldAccess(neutralQuery);
NeutralCriteria securityCriteria = findAccessible();
List<String> allowed = (List<String>) securityCriteria.getValue();
if (allowed.isEmpty()) {
return Collections.emptyList();
}
// super list logic --> only true when using DefaultEntityContextResolver
List<String> results = new ArrayList<String>();
//not a super list so add the criteria
//not sure if this ever happen
if (allowed.size() > 0) {
//add the security criteria
neutralQuery.addCriteria(securityCriteria);
}
Iterable<Entity> entities = repo.findAll(collectionName, neutralQuery);
for (Entity entity : entities) {
results.add(entity.getEntityId());
}
return results;
}
@Override
public String create(EntityBody content) {
// DE260 - Logging of possibly sensitive data
// LOG.debug("Creating a new entity in collection {} with content {}", new Object[] {
// collectionName, content });
// if service does not allow anonymous write access, check user rights
if (writeRight != Right.ANONYMOUS_ACCESS) {
checkRights(determineWriteAccess(content, ""));
}
return repo.create(defn.getType(), sanitizeEntityBody(content), createMetadata(), collectionName).getEntityId();
}
@Override
public void delete(String id) {
// DE260 - Logging of possibly sensitive data
// LOG.debug("Deleting {} in {}", new String[] { id, collectionName });
checkAccess(writeRight, id);
try {
cascadeDelete(id);
} catch (RuntimeException re) {
debug(re.toString());
}
if (!repo.delete(collectionName, id)) {
info("Could not find {}", id);
throw new EntityNotFoundException(id);
}
deleteAttachedCustomEntities(id);
}
@Override
public boolean update(String id, EntityBody content) {
debug("Updating {} in {}", id, collectionName);
if (writeRight != Right.ANONYMOUS_ACCESS) {
checkAccess(determineWriteAccess(content, ""), id);
}
Entity entity = repo.findById(collectionName, id);
if (entity == null) {
info("Could not find {}", id);
throw new EntityNotFoundException(id);
}
EntityBody sanitized = sanitizeEntityBody(content);
if (entity.getBody().equals(sanitized)) {
info("No change detected to {}", id);
return false;
}
info("new body is {}", sanitized);
entity.getBody().clear();
entity.getBody().putAll(sanitized);
repo.update(collectionName, entity);
return true;
}
@Override
public EntityBody get(String id) {
checkAccess(readRight, id);
Entity entity = getRepo().findById(collectionName, id);
if (entity == null) {
info("Could not find {}", id);
throw new EntityNotFoundException(id);
}
return makeEntityBody(entity);
}
@Override
public EntityBody get(String id, NeutralQuery neutralQuery) {
checkAccess(readRight, id);
checkFieldAccess(neutralQuery);
if (neutralQuery == null) {
neutralQuery = new NeutralQuery();
}
neutralQuery.addCriteria(new NeutralCriteria("_id", "=", id));
Entity entity = repo.findOne(collectionName, neutralQuery);
if (entity == null) {
throw new EntityNotFoundException(id);
}
return makeEntityBody(entity);
}
private Iterable<EntityBody> noEntitiesFound(NeutralQuery neutralQuery) {
if (makeEntityList(repo.findAll(collectionName, neutralQuery)).isEmpty()) {
return new ArrayList<EntityBody>();
} else {
throw new AccessDeniedException("Access to resource denied.");
}
}
private List<Entity> makeEntityList(Iterable<Entity> items) {
List<Entity> myList = new ArrayList<Entity>();
for (Entity item : items) {
myList.add(item);
}
return myList;
}
@Override
public Iterable<EntityBody> get(Iterable<String> ids) {
NeutralQuery neutralQuery = new NeutralQuery();
neutralQuery.setOffset(0);
neutralQuery.setLimit(MAX_RESULT_SIZE);
return get(ids, neutralQuery);
}
@Override
public Iterable<EntityBody> get(Iterable<String> ids, NeutralQuery neutralQuery) {
if (!ids.iterator().hasNext()) {
return Collections.emptyList();
}
checkRights(readRight);
checkFieldAccess(neutralQuery);
NeutralCriteria securityCriteria = findAccessible();
List<String> idList = new ArrayList<String>();
for (String id : ids) {
idList.add(id);
}
if (!idList.isEmpty()) {
if (neutralQuery == null) {
neutralQuery = new NeutralQuery();
neutralQuery.setOffset(0);
neutralQuery.setLimit(MAX_RESULT_SIZE);
}
//add the security criteria
neutralQuery.addCriteria(securityCriteria);
//add the ids requested
neutralQuery.addCriteria(new NeutralCriteria("_id", "in", idList));
Iterable<Entity> entities = repo.findAll(collectionName, neutralQuery);
List<EntityBody> results = new ArrayList<EntityBody>();
for (Entity e : entities) {
results.add(makeEntityBody(e));
}
return results;
}
return Collections.emptyList();
}
@Override
public Iterable<EntityBody> list(NeutralQuery neutralQuery) {
checkRights(readRight);
checkFieldAccess(neutralQuery);
NeutralCriteria securityCriteria = findAccessible();
List<String> allowed = (List<String>) securityCriteria.getValue();
NeutralQuery localNeutralQuery = new NeutralQuery(neutralQuery);
if (readRight == Right.ANONYMOUS_ACCESS) {
debug("super list logic --> {} service allows anonymous access", collectionName);
} else if (allowed.isEmpty()) {
return Collections.emptyList();
} else if (allowed.size() < 0) {
debug("super list logic --> only true when using DefaultEntityContextResolver");
} else {
if (securityCriteria.getKey().equals("_id")) {
Set<String> ids = new HashSet<String>();
List<NeutralCriteria> criterias = neutralQuery.getCriteria();
for (NeutralCriteria criteria : criterias) {
if (criteria.getKey().equals("_id")) {
@SuppressWarnings("unchecked")
List<String> idList = (List<String>) criteria.getValue();
ids.addAll(idList);
}
}
if (!ids.isEmpty()) {
Set<String> allowedSet = new HashSet<String>(allowed);
ids.retainAll(allowedSet);
//update the security criteria to only include the needed ids
securityCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, new ArrayList<String>(ids));
}
}
}
//add the security criteria
localNeutralQuery.addCriteria(securityCriteria);
List<EntityBody> results = new ArrayList<EntityBody>();
for (Entity entity : repo.findAll(collectionName, localNeutralQuery)) {
results.add(makeEntityBody(entity));
}
if (results.isEmpty()) {
return noEntitiesFound(neutralQuery);
}
return results;
}
@Override
public boolean exists(String id) {
checkRights(readRight);
boolean exists = false;
if (repo.findById(collectionName, id) != null) {
exists = true;
}
return exists;
}
/**
* TODO: refactor clientId, entityId out of body into root of mongo document
* TODO: entity collection should be per application
*/
@Override
public EntityBody getCustom(String id) {
checkAccess(readRight, id);
String clientId = getClientId();
debug("Reading custom entity: entity={}, entityId={}, clientId={}", new String[] {
getEntityDefinition().getType(), id, clientId });
NeutralQuery query = new NeutralQuery();
query.addCriteria(new NeutralCriteria("metaData." + CUSTOM_ENTITY_CLIENT_ID, "=", clientId, false));
query.addCriteria(new NeutralCriteria("metaData." + CUSTOM_ENTITY_ENTITY_ID, "=", id, false));
Entity entity = getRepo().findOne(CUSTOM_ENTITY_COLLECTION, query);
if (entity != null) {
EntityBody clonedBody = new EntityBody(entity.getBody());
return clonedBody;
} else {
return null;
}
}
/**
* TODO: refactor clientId, entityId out of body into root of mongo document
* TODO: entity collection should be per application
*/
@Override
public void deleteCustom(String id) {
checkAccess(writeRight, id);
String clientId = getClientId();
NeutralQuery query = new NeutralQuery();
query.addCriteria(new NeutralCriteria("metaData." + CUSTOM_ENTITY_CLIENT_ID, "=", clientId, false));
query.addCriteria(new NeutralCriteria("metaData." + CUSTOM_ENTITY_ENTITY_ID, "=", id, false));
Entity entity = getRepo().findOne(CUSTOM_ENTITY_COLLECTION, query);
if (entity == null) {
throw new EntityNotFoundException(id);
}
boolean deleted = getRepo().delete(CUSTOM_ENTITY_COLLECTION, entity.getEntityId());
debug("Deleting custom entity: entity={}, entityId={}, clientId={}, deleted?={}", new String[] {
getEntityDefinition().getType(), id, clientId, String.valueOf(deleted) });
}
/**
* TODO: refactor clientId, entityId out of body into root of mongo document
* TODO: entity collection should be per application
*/
@Override
public void createOrUpdateCustom(String id, EntityBody customEntity) {
checkAccess(writeRight, id);
String clientId = getClientId();
NeutralQuery query = new NeutralQuery();
query.addCriteria(new NeutralCriteria("metaData." + CUSTOM_ENTITY_CLIENT_ID, "=", clientId, false));
query.addCriteria(new NeutralCriteria("metaData." + CUSTOM_ENTITY_ENTITY_ID, "=", id, false));
Entity entity = getRepo().findOne(CUSTOM_ENTITY_COLLECTION, query);
if (entity != null && entity.getBody().equals(customEntity)) {
debug("No change detected to custom entity, ignoring update: entity={}, entityId={}, clientId={}",
new String[] { getEntityDefinition().getType(), id, clientId });
return;
}
EntityBody clonedEntity = new EntityBody(customEntity);
if (entity != null) {
debug("Overwriting existing custom entity: entity={}, entityId={}, clientId={}", new String[] {
getEntityDefinition().getType(), id, clientId });
entity.getBody().clear();
entity.getBody().putAll(clonedEntity);
getRepo().update(CUSTOM_ENTITY_COLLECTION, entity);
} else {
debug("Creating new custom entity: entity={}, entityId={}, clientId={}", new String[] {
getEntityDefinition().getType(), id, clientId });
EntityBody metaData = new EntityBody();
metaData.put(CUSTOM_ENTITY_CLIENT_ID, clientId);
metaData.put(CUSTOM_ENTITY_ENTITY_ID, id);
getRepo().create(CUSTOM_ENTITY_COLLECTION, clonedEntity, metaData, CUSTOM_ENTITY_COLLECTION);
}
}
private String getClientId() {
String clientId = clientInfo.getClientId();
if (clientId == null) {
throw new AccessDeniedException("No Application Id");
}
return clientId;
}
/**
* given an entity, make the entity body to expose
*
* @param entity
* @return
*/
private EntityBody makeEntityBody(Entity entity) {
EntityBody toReturn = new EntityBody(entity.getBody());
toReturn.put(METADATA, entity.getMetaData());
for (Treatment treatment : treatments) {
toReturn = treatment.toExposed(toReturn, defn, entity.getEntityId());
}
if (readRight != Right.ANONYMOUS_ACCESS) {
// Blank out fields inaccessible to the user
filterFields(toReturn, "");
}
return toReturn;
}
/**
* given an entity body that was exposed, return the version with the treatments reversed
*
* @param content
* @return
*/
private EntityBody sanitizeEntityBody(EntityBody content) {
EntityBody sanitized = new EntityBody(content);
for (Treatment treatment : treatments) {
sanitized = treatment.toStored(sanitized, defn);
}
return sanitized;
}
/**
* Deletes any object with a reference to the given sourceId. Assumes that the sourceId
* still exists so that authorization/context can be checked.
*
* @param sourceId
* ID that was deleted, where anything else with that ID should also be deleted
*/
private void cascadeDelete(String sourceId) {
// loop for every EntityDefinition that references the deleted entity's type
for (EntityDefinition referencingEntity : defn.getReferencingEntities()) {
// loop for every reference field that COULD reference the deleted ID
for (String referenceField : referencingEntity.getReferenceFieldNames(defn.getStoredCollectionName())) {
EntityService referencingEntityService = referencingEntity.getService();
NeutralQuery neutralQuery = new NeutralQuery();
neutralQuery.addCriteria(new NeutralCriteria(referenceField + "=" + sourceId));
try {
// list all entities that have the deleted entity's ID in their reference field
for (EntityBody entityBody : referencingEntityService.list(neutralQuery)) {
String idToBeDeleted = (String) entityBody.get("id");
// delete that entity as well
referencingEntityService.delete(idToBeDeleted);
// delete custom entities attached to this entity
deleteAttachedCustomEntities(idToBeDeleted);
}
} catch (AccessDeniedException ade) {
debug("No {} have {}={}", new Object[] { referencingEntity.getResourceName(), referenceField,
sourceId });
}
}
}
}
private void deleteAttachedCustomEntities(String sourceId) {
NeutralQuery query = new NeutralQuery();
query.addCriteria(new NeutralCriteria("metaData." + CUSTOM_ENTITY_ENTITY_ID, "=", sourceId, false));
Iterable<String> ids = getRepo().findAllIds(CUSTOM_ENTITY_COLLECTION, query);
for (String id : ids) {
getRepo().delete(CUSTOM_ENTITY_COLLECTION, id);
}
}
/**
* Checks that Actor has the appropriate Rights and linkage to access given entity
* Also checks for existence of the given entity
*
* @param right
* needed Right for action
* @param entityId
* id of the entity to access
* @throws EntityNotFoundException
* if requested entity doesn't exist
* @throws AccessDeniedException
* if actor doesn't have association path to given entity
*/
private void checkAccess(Right right, String entityId) {
// Check that user has the needed right
checkRights(right);
// Check that target entity actually exists
if (repo.findById(collectionName, entityId) == null) {
warn("Could not find {}", entityId);
throw new EntityNotFoundException(entityId);
}
if (right != Right.ANONYMOUS_ACCESS) {
// Check that target entity is accessible to the actor
if (entityId != null && !isEntityAllowed(entityId)) {
throw new AccessDeniedException("No association between the user and target entity");
}
}
}
/**
* Checks to see if the entity id is allowed by security
* @param entityId The id to check
* @return
*/
private boolean isEntityAllowed(String entityId) {
NeutralCriteria securityCriteria = findAccessible();
List<String> allowed = (List<String>) securityCriteria.getValue();
if (securityCriteria.getKey().equals("_id")) {
return allowed.contains(entityId);
} else {
NeutralQuery query = new NeutralQuery();
query.addCriteria(securityCriteria);
query.addCriteria(new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList(entityId)));
Entity entity = repo.findOne(collectionName, query);
return (entity != null);
}
}
private void checkRights(Right neededRight) {
// anonymous access is always granted
if (neededRight == Right.ANONYMOUS_ACCESS) {
return;
}
if (ADMIN_SPHERE.equals(provider.getDataSphere(defn.getType()))) {
neededRight = Right.ADMIN_ACCESS;
}
if (PUBLIC_SPHERE.equals(provider.getDataSphere(defn.getType()))) {
if (Right.READ_GENERAL.equals(neededRight)) {
neededRight = Right.READ_PUBLIC;
}
}
Collection<GrantedAuthority> auths = getAuths();
if (auths.contains(Right.FULL_ACCESS)) {
debug("User has full access");
} else if (auths.contains(neededRight)) {
debug("User has needed right: {}", neededRight);
} else {
throw new AccessDeniedException("Insufficient Privileges");
}
}
private Collection<GrantedAuthority> getAuths() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (readRight != Right.ANONYMOUS_ACCESS) {
SecurityUtil.ensureAuthenticated();
}
return auth.getAuthorities();
}
private NeutralCriteria findAccessible() {
String securityField = "_id";
SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal == null) {
throw new AccessDeniedException("Principal cannot be found");
}
Entity entity = principal.getEntity();
String type = entity != null ? entity.getType() : null; // null for super admins because
// they don't contain mongo
// entries
if (getAuths().contains(Right.FULL_ACCESS)) {
return new NeutralCriteria(securityField, NeutralCriteria.CRITERIA_IN, AllowAllEntityContextResolver.SUPER_LIST);
}
EntityContextResolver resolver = contextResolverStore.findResolver(type, defn.getType());
List<String> allowed = resolver.findAccessible(principal.getEntity());
if (type != null && type.equals(EntityNames.STAFF)) {
securityField = "metaData.edOrgs";
}
NeutralCriteria securityCriteria = new NeutralCriteria(securityField, NeutralCriteria.CRITERIA_IN, allowed, false);
return securityCriteria;
}
/**
* Removes fields user isn't entitled to see
*
* @param eb
*/
@SuppressWarnings("unchecked")
private void filterFields(Map<String, Object> eb, String prefix) {
Collection<GrantedAuthority> auths = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
if (!auths.contains(Right.FULL_ACCESS)) {
List<String> toRemove = new LinkedList<String>();
for (Map.Entry<String, Object> entry : eb.entrySet()) {
String fieldName = entry.getKey();
Object value = entry.getValue();
String fieldPath = prefix + fieldName;
Right neededRight = getNeededRight(fieldPath);
debug("Field {} requires {}", fieldPath, neededRight);
SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
if (!auths.contains(neededRight) && !principal.getEntity().getEntityId().equals(eb.get("id"))) {
toRemove.add(fieldName);
} else if (value instanceof Map) {
filterFields((Map<String, Object>) value, prefix + "." + fieldName + ".");
}
}
for (String fieldName : toRemove) {
eb.remove(fieldName);
}
}
}
/**
* Returns the needed right for a field by examining the schema
*
* @param fieldPath
* The field name
* @return
*/
protected Right getNeededRight(String fieldPath) {
Right neededRight = provider.getRequiredReadLevel(defn.getType(), fieldPath);
if (ADMIN_SPHERE.equals(provider.getDataSphere(defn.getType()))) {
neededRight = Right.ADMIN_ACCESS;
}
if (PUBLIC_SPHERE.equals(provider.getDataSphere(defn.getType()))) {
if (Right.READ_GENERAL.equals(neededRight)) {
neededRight = Right.READ_PUBLIC;
}
}
return neededRight;
}
/**
* Checks query params for access restrictions
*
* @param query
* The query to check
*/
protected void checkFieldAccess(NeutralQuery query) {
if (query != null) {
// get the authorities
Collection<GrantedAuthority> auths = SecurityContextHolder.getContext().getAuthentication()
.getAuthorities();
if (!auths.contains(Right.FULL_ACCESS) && !auths.contains(Right.ANONYMOUS_ACCESS)) {
for (NeutralCriteria criteria : query.getCriteria()) {
// get the needed right for the field
Right neededRight = getNeededRight(criteria.getKey());
if (!auths.contains(neededRight)) {
throw new QueryParseException("Cannot search on restricted field", criteria.getKey());
}
}
}
}
}
/**
* Figures out if writing to restricted fields
*
* @param eb
* data currently being passed in
* @return WRITE_RESTRICTED if restricted fields are being written, WRITE_GENERAL otherwise
*/
@SuppressWarnings("unchecked")
private Right determineWriteAccess(Map<String, Object> eb, String prefix) {
Right toReturn = Right.WRITE_GENERAL;
if (ADMIN_SPHERE.equals(provider.getDataSphere(defn.getType()))) {
toReturn = Right.ADMIN_ACCESS;
} else {
for (Map.Entry<String, Object> entry : eb.entrySet()) {
String fieldName = entry.getKey();
Object value = entry.getValue();
if (value instanceof Map) {
filterFields((Map<String, Object>) value, prefix + "." + fieldName + ".");
} else {
String fieldPath = prefix + fieldName;
Right neededRight = provider.getRequiredReadLevel(defn.getType(), fieldPath);
debug("Field {} requires {}", fieldPath, neededRight);
if (neededRight == Right.WRITE_RESTRICTED) {
toReturn = Right.WRITE_RESTRICTED;
break;
}
}
}
}
return toReturn;
}
/**
* Creates the metaData HashMap to be added to the entity created in mongo.
*
* @return Map containing important metadata for the created entity.
*/
private Map<String, Object> createMetadata() {
Map<String, Object> metadata = new HashMap<String, Object>();
SLIPrincipal principal = (SLIPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
metadata.put("isOrphaned", "true");
metadata.put("createdBy", principal.getEntity().getEntityId());
metadata.put("tenantId", principal.getTenantId());
return metadata;
}
/**
* Set the entity definition for this service.
* There is a circular dependency between BasicService and EntityDefinition, so they both can't
* have it be a constructor arg.
*/
public void setDefn(EntityDefinition defn) {
this.defn = defn;
}
@Override
public EntityDefinition getEntityDefinition() {
return defn;
}
protected String getCollectionName() {
return collectionName;
}
protected List<Treatment> getTreatments() {
return treatments;
}
protected Repository<Entity> getRepo() {
return repo;
}
protected void setClientInfo(CallingApplicationInfoProvider clientInfo) {
this.clientInfo = clientInfo;
}
}
|
package master.flame.danmaku.ui.widget;
import android.graphics.RectF;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import master.flame.danmaku.controller.IDanmakuView;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.IDanmakuIterator;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.Danmakus;
public class DanmakuTouchHelper {
private final GestureDetector mTouchDelegate;
private IDanmakuView danmakuView;
private RectF mDanmakuBounds;
private final android.view.GestureDetector.OnGestureListener mOnGestureListener = new GestureDetector.SimpleOnGestureListener(){
@Override
public boolean onDown(MotionEvent event) {
if(danmakuView != null) {
IDanmakuView.OnDanmakuClickListener onDanmakuClickListener = danmakuView.getOnDanmakuClickListener();
if (onDanmakuClickListener != null) {
return true;
}
}
return false;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent event) {
IDanmakus clickDanmakus = touchHitDanmaku(event.getX(), event.getY());
boolean isEventConsumed = false;
if (null != clickDanmakus && !clickDanmakus.isEmpty()) {
isEventConsumed = performDanmakuClick(clickDanmakus);
}
if (!isEventConsumed) {
isEventConsumed = performViewClick();
}
return isEventConsumed;
}
};
private DanmakuTouchHelper(IDanmakuView danmakuView) {
this.danmakuView = danmakuView;
this.mDanmakuBounds = new RectF();
this.mTouchDelegate = new GestureDetector(((View)danmakuView).getContext(), mOnGestureListener);
}
public static synchronized DanmakuTouchHelper instance(IDanmakuView danmakuView) {
return new DanmakuTouchHelper(danmakuView);
}
public boolean onTouchEvent(MotionEvent event) {
return mTouchDelegate.onTouchEvent(event);
}
private boolean performDanmakuClick(IDanmakus danmakus) {
IDanmakuView.OnDanmakuClickListener onDanmakuClickListener = danmakuView.getOnDanmakuClickListener();
if (onDanmakuClickListener != null) {
return onDanmakuClickListener.onDanmakuClick(danmakus);
}
return false;
}
private boolean performViewClick() {
IDanmakuView.OnDanmakuClickListener onDanmakuClickListener = danmakuView.getOnDanmakuClickListener();
if (onDanmakuClickListener != null) {
return onDanmakuClickListener.onViewClick(danmakuView);
}
return false;
}
private IDanmakus touchHitDanmaku(float x, float y) {
IDanmakus hitDanmakus = new Danmakus();
mDanmakuBounds.setEmpty();
IDanmakus danmakus = danmakuView.getCurrentVisibleDanmakus();
if (null != danmakus && !danmakus.isEmpty()) {
IDanmakuIterator iterator = danmakus.iterator();
while (iterator.hasNext()) {
BaseDanmaku danmaku = iterator.next();
if (null != danmaku) {
mDanmakuBounds.set(danmaku.getLeft(), danmaku.getTop(), danmaku.getRight(), danmaku.getBottom());
if (mDanmakuBounds.contains(x, y)) {
hitDanmakus.addItem(danmaku);
}
}
}
}
return hitDanmakus;
}
}
|
package nl.b3p.viewer.solr;
import java.io.File;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
/**
* This class will initialize the solr server: the setup of the index and the
* initialization of the SolrServer object. This in order to limit the number of
* connections to the index.
*
* @author Meine Toonen
*/
public class SolrInitializer implements ServletContextListener {
private static SolrServer server;
private static final Log log = LogFactory.getLog(SolrInitializer.class);
private ServletContext context;
// Defaults
private static final String SOLR_DIR = ".solr/";
private static final String SOLR_CORE_NAME = "flamingo";
// Configuration names
public static final String DATA_DIR = "flamingo.data.dir";
private final String SETUP_SOLR = "flamingo.solr.setup";
private final String SOLR_URL = "flamingo.solr.url";
// Context parameters
private boolean setupSolr = false;
private String datadirectory;
private String solrUrl;
private static final String SOLR_CONF_DIR="/WEB-INF/classes/solr/flamingo";
@Override
public void contextInitialized(ServletContextEvent sce) {
log.debug("SolrInitializer initializing");
this.context = sce.getServletContext();
init();
System.setProperty("solr.solr.home", datadirectory + File.separator + SOLR_DIR);
File dataDirectory = new File(datadirectory);
if (!isCorrectDir(dataDirectory)) {
log.error("Cannot read/write data dir " + datadirectory + ". Solr searching not possible.");
return;
}
log.info("Data dir set " + datadirectory);
File solrDir = new File(dataDirectory, SOLR_DIR);
if (setupSolr && !solrDir.exists()) {
setupSolr(solrDir);
}
inializeSolr(solrDir);
}
private void setupSolr(File solrdir) {
log.debug("Setup the solr directory");
copyConf(solrdir);
}
private void inializeSolr(File solrDir) {
log.debug("Initialize the Solr Server instance");
if(solrUrl.charAt(solrUrl.length() -1 ) != '/'){
solrUrl += "/";
}
server = new HttpSolrServer(solrUrl +SOLR_CORE_NAME);
}
public static SolrServer getServerInstance() {
return server;
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
if(server != null){
server.shutdown();
log.debug("SolrInitializer destroyed");
}
}
private boolean isCorrectDir(File f) {
return f.isDirectory() && f.canRead() && f.canWrite();
}
private void copyConf(File solrDir){
try {
File conf = new File( this.context.getRealPath("/WEB-INF/classes/solr/solr.xml"));
FileUtils.copyFile(conf, new File(solrDir, "solr.xml"));
File coreConfiguration = new File(context.getRealPath(SOLR_CONF_DIR));
File coreDir = new File(solrDir, SOLR_CORE_NAME);
FileUtils.copyDirectory(coreConfiguration, coreDir);
} catch (Exception ex) {
log.error("Setup of the solr directory failed: ",ex);
}
}
private void init(){
String setupSolrParam = context.getInitParameter(SETUP_SOLR);
if(setupSolrParam != null){
this.setupSolr = Boolean.parseBoolean(setupSolrParam);
}
datadirectory = context.getInitParameter(DATA_DIR);
solrUrl = context.getInitParameter(SOLR_URL);
}
}
|
package com.cloud.network.rules;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ejb.Local;
import javax.naming.ConfigurationException;
import org.apache.log4j.Logger;
import com.cloud.api.commands.ListPortForwardingRulesCmd;
import com.cloud.configuration.ConfigurationManager;
import com.cloud.domain.dao.DomainDao;
import com.cloud.event.ActionEvent;
import com.cloud.event.EventTypes;
import com.cloud.event.UsageEventVO;
import com.cloud.event.dao.EventDao;
import com.cloud.event.dao.UsageEventDao;
import com.cloud.exception.InsufficientAddressCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.IPAddressVO;
import com.cloud.network.IpAddress;
import com.cloud.network.Network;
import com.cloud.network.Network.Service;
import com.cloud.network.NetworkManager;
import com.cloud.network.dao.FirewallRulesCidrsDao;
import com.cloud.network.dao.FirewallRulesDao;
import com.cloud.network.dao.IPAddressDao;
import com.cloud.network.rules.FirewallRule.FirewallRuleType;
import com.cloud.network.rules.FirewallRule.Purpose;
import com.cloud.network.rules.dao.PortForwardingRulesDao;
import com.cloud.offering.NetworkOffering;
import com.cloud.projects.Project.ListProjectResourcesCriteria;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.DomainManager;
import com.cloud.user.UserContext;
import com.cloud.uservm.UserVm;
import com.cloud.utils.Ternary;
import com.cloud.utils.component.Inject;
import com.cloud.utils.component.Manager;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.JoinBuilder;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.Ip;
import com.cloud.vm.Nic;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.dao.NicDao;
import com.cloud.vm.dao.UserVmDao;
@Local(value = { RulesManager.class, RulesService.class })
public class RulesManagerImpl implements RulesManager, RulesService, Manager {
private static final Logger s_logger = Logger.getLogger(RulesManagerImpl.class);
String _name;
@Inject
PortForwardingRulesDao _portForwardingDao;
@Inject
FirewallRulesCidrsDao _firewallCidrsDao;
@Inject
FirewallRulesDao _firewallDao;
@Inject
IPAddressDao _ipAddressDao;
@Inject
UserVmDao _vmDao;
@Inject
AccountManager _accountMgr;
@Inject
NetworkManager _networkMgr;
@Inject
EventDao _eventDao;
@Inject
UsageEventDao _usageEventDao;
@Inject
DomainDao _domainDao;
@Inject
FirewallManager _firewallMgr;
@Inject
DomainManager _domainMgr;
@Inject
ConfigurationManager _configMgr;
@Inject
NicDao _nicDao;
@Override
public void checkIpAndUserVm(IpAddress ipAddress, UserVm userVm, Account caller) {
if (ipAddress == null || ipAddress.getAllocatedTime() == null || ipAddress.getAllocatedToAccountId() == null) {
throw new InvalidParameterValueException("Unable to create ip forwarding rule on address " + ipAddress + ", invalid IP address specified.");
}
if (userVm == null) {
return;
}
if (userVm.getState() == VirtualMachine.State.Destroyed || userVm.getState() == VirtualMachine.State.Expunging) {
throw new InvalidParameterValueException("Invalid user vm: " + userVm.getId());
}
_accountMgr.checkAccess(caller, null, true, ipAddress, userVm);
// validate that IP address and userVM belong to the same account
if (ipAddress.getAllocatedToAccountId().longValue() != userVm.getAccountId()) {
throw new InvalidParameterValueException("Unable to create ip forwarding rule, IP address " + ipAddress + " owner is not the same as owner of virtual machine " + userVm.toString());
}
// validate that userVM is in the same availability zone as the IP address
if (ipAddress.getDataCenterId() != userVm.getDataCenterIdToDeployIn()) {
throw new InvalidParameterValueException("Unable to create ip forwarding rule, IP address " + ipAddress + " is not in the same availability zone as virtual machine " + userVm.toString());
}
}
@Override
public void checkRuleAndUserVm(FirewallRule rule, UserVm userVm, Account caller) {
if (userVm == null || rule == null) {
return;
}
_accountMgr.checkAccess(caller, null, true, rule, userVm);
if (userVm.getState() == VirtualMachine.State.Destroyed || userVm.getState() == VirtualMachine.State.Expunging) {
throw new InvalidParameterValueException("Invalid user vm: " + userVm.getId());
}
if (rule.getAccountId() != userVm.getAccountId()) {
throw new InvalidParameterValueException("New rule " + rule + " and vm id=" + userVm.getId() + " belong to different accounts");
}
}
@Override @DB
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "creating forwarding rule", create = true)
public PortForwardingRule createPortForwardingRule(PortForwardingRule rule, Long vmId, boolean openFirewall) throws NetworkRuleConflictException {
UserContext ctx = UserContext.current();
Account caller = ctx.getCaller();
Long ipAddrId = rule.getSourceIpAddressId();
IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId);
// Validate ip address
if (ipAddress == null) {
throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " doesn't exist in the system");
} else if (ipAddress.isOneToOneNat()) {
throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " has static nat enabled");
}
_firewallMgr.validateFirewallRule(caller, ipAddress, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), Purpose.PortForwarding, FirewallRuleType.User);
Long networkId = ipAddress.getAssociatedWithNetworkId();
Long accountId = ipAddress.getAllocatedToAccountId();
Long domainId = ipAddress.getAllocatedInDomainId();
// start port can't be bigger than end port
if (rule.getDestinationPortStart() > rule.getDestinationPortEnd()) {
throw new InvalidParameterValueException("Start port can't be bigger than end port");
}
// check that the port ranges are of equal size
if ((rule.getDestinationPortEnd() - rule.getDestinationPortStart()) != (rule.getSourcePortEnd() - rule.getSourcePortStart())) {
throw new InvalidParameterValueException("Source port and destination port ranges should be of equal sizes.");
}
// validate user VM exists
UserVm vm = _vmDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("Unable to create port forwarding rule on address " + ipAddress + ", invalid virtual machine id specified (" + vmId + ").");
} else {
checkRuleAndUserVm(rule, vm, caller);
}
_networkMgr.checkIpForService(ipAddress, Service.PortForwarding);
// Verify that vm has nic in the network
Ip dstIp = rule.getDestinationIpAddress();
Nic guestNic = _networkMgr.getNicInNetwork(vmId, networkId);
if (guestNic == null || guestNic.getIp4Address() == null) {
throw new InvalidParameterValueException("Vm doesn't belong to network associated with ipAddress");
} else {
dstIp = new Ip(guestNic.getIp4Address());
}
Transaction txn = Transaction.currentTxn();
txn.start();
PortForwardingRuleVO newRule = new PortForwardingRuleVO(rule.getXid(), rule.getSourceIpAddressId(), rule.getSourcePortStart(), rule.getSourcePortEnd(), dstIp, rule.getDestinationPortStart(),
rule.getDestinationPortEnd(), rule.getProtocol().toLowerCase(), networkId, accountId, domainId, vmId);
newRule = _portForwardingDao.persist(newRule);
//create firewallRule for 0.0.0.0/0 cidr
if (openFirewall) {
_firewallMgr.createRuleForAllCidrs(ipAddrId, caller, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), null, null, newRule.getId());
}
try {
_firewallMgr.detectRulesConflict(newRule, ipAddress);
if (!_firewallDao.setStateToAdd(newRule)) {
throw new CloudRuntimeException("Unable to update the state to add for " + newRule);
}
UserContext.current().setEventDetails("Rule Id: " + newRule.getId());
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_RULE_ADD, newRule.getAccountId(), ipAddress.getDataCenterId(), newRule.getId(), null);
_usageEventDao.persist(usageEvent);
txn.commit();
return newRule;
} catch (Exception e) {
if (newRule != null) {
txn.start();
//no need to apply the rule as it wasn't programmed on the backend yet
_firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false);
_portForwardingDao.remove(newRule.getId());
txn.commit();
}
if (e instanceof NetworkRuleConflictException) {
throw (NetworkRuleConflictException) e;
}
throw new CloudRuntimeException("Unable to add rule for the ip id=" + ipAddrId, e);
}
}
@Override @DB
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "creating static nat rule", create = true)
public StaticNatRule createStaticNatRule(StaticNatRule rule, boolean openFirewall) throws NetworkRuleConflictException {
Account caller = UserContext.current().getCaller();
Long ipAddrId = rule.getSourceIpAddressId();
IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId);
// Validate ip address
if (ipAddress == null) {
throw new InvalidParameterValueException("Unable to create static nat rule; ip id=" + ipAddrId + " doesn't exist in the system");
} else if (ipAddress.isSourceNat() || !ipAddress.isOneToOneNat() || ipAddress.getAssociatedWithVmId() == null) {
throw new NetworkRuleConflictException("Can't do static nat on ip address: " + ipAddress.getAddress());
}
_firewallMgr.validateFirewallRule(caller, ipAddress, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), Purpose.StaticNat, FirewallRuleType.User);
Long networkId = ipAddress.getAssociatedWithNetworkId();
Long accountId = ipAddress.getAllocatedToAccountId();
Long domainId = ipAddress.getAllocatedInDomainId();
_networkMgr.checkIpForService(ipAddress, Service.StaticNat);
Network network = _networkMgr.getNetwork(networkId);
NetworkOffering off = _configMgr.getNetworkOffering(network.getNetworkOfferingId());
if (off.getElasticIp()) {
throw new InvalidParameterValueException("Can't create ip forwarding rules for the network where elasticIP service is enabled");
}
String dstIp = _networkMgr.getIpInNetwork(ipAddress.getAssociatedWithVmId(), networkId);
Transaction txn = Transaction.currentTxn();
txn.start();
FirewallRuleVO newRule = new FirewallRuleVO(rule.getXid(), rule.getSourceIpAddressId(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol().toLowerCase(),
networkId, accountId, domainId, rule.getPurpose(), null, null, null, null);
newRule = _firewallDao.persist(newRule);
//create firewallRule for 0.0.0.0/0 cidr
if (openFirewall) {
_firewallMgr.createRuleForAllCidrs(ipAddrId, caller, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), null, null, newRule.getId());
}
try {
_firewallMgr.detectRulesConflict(newRule, ipAddress);
if (!_firewallDao.setStateToAdd(newRule)) {
throw new CloudRuntimeException("Unable to update the state to add for " + newRule);
}
UserContext.current().setEventDetails("Rule Id: " + newRule.getId());
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_NET_RULE_ADD, newRule.getAccountId(), 0, newRule.getId(), null);
_usageEventDao.persist(usageEvent);
txn.commit();
StaticNatRule staticNatRule = new StaticNatRuleImpl(newRule, dstIp);
return staticNatRule;
} catch (Exception e) {
if (newRule != null) {
txn.start();
//no need to apply the rule as it wasn't programmed on the backend yet
_firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false);
_portForwardingDao.remove(newRule.getId());
txn.commit();
}
if (e instanceof NetworkRuleConflictException) {
throw (NetworkRuleConflictException) e;
}
throw new CloudRuntimeException("Unable to add static nat rule for the ip id=" + newRule.getSourceIpAddressId(), e);
}
}
@Override
public boolean enableStaticNat(long ipId, long vmId) throws NetworkRuleConflictException, ResourceUnavailableException {
UserContext ctx = UserContext.current();
Account caller = ctx.getCaller();
// Verify input parameters
UserVmVO vm = _vmDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("Can't enable static nat for the address id=" + ipId + ", invalid virtual machine id specified (" + vmId + ").");
}
IPAddressVO ipAddress = _ipAddressDao.findById(ipId);
if (ipAddress == null) {
throw new InvalidParameterValueException("Unable to find ip address by id " + ipId);
}
checkIpAndUserVm(ipAddress, vm, caller);
// Verify that the ip is associated with the network and static nat service is supported for the network
Long networkId = ipAddress.getAssociatedWithNetworkId();
if (networkId == null) {
throw new InvalidParameterValueException("Unable to enable static nat for the ipAddress id=" + ipId + " as ip is not associated with any network");
}
// Check that vm has a nic in the network
Nic guestNic = _networkMgr.getNicInNetwork(vmId, networkId);
if (guestNic == null) {
throw new InvalidParameterValueException("Vm doesn't belong to the network " + networkId);
}
Network network = _networkMgr.getNetwork(networkId);
if (!_networkMgr.areServicesSupportedInNetwork(network.getId(), Service.StaticNat)) {
throw new InvalidParameterValueException("Unable to create static nat rule; StaticNat service is not supported in network id=" + networkId);
}
// Verify ip address parameter
isIpReadyForStaticNat(vmId, ipAddress, caller, ctx.getCallerUserId());
_networkMgr.checkIpForService(ipAddress, Service.StaticNat);
ipAddress.setOneToOneNat(true);
ipAddress.setAssociatedWithVmId(vmId);
if (_ipAddressDao.update(ipAddress.getId(), ipAddress)) {
//enable static nat on the backend
s_logger.trace("Enabling static nat for ip address " + ipAddress + " and vm id=" + vmId + " on the backend");
if (applyStaticNatForIp(ipId, false, caller, false)) {
return true;
} else {
ipAddress.setOneToOneNat(false);
ipAddress.setAssociatedWithVmId(null);
_ipAddressDao.update(ipAddress.getId(), ipAddress);
s_logger.warn("Failed to enable static nat rule for ip address " + ipId + " on the backend");
return false;
}
} else {
s_logger.warn("Failed to update ip address " + ipAddress + " in the DB as a part of enableStaticNat");
return false;
}
}
protected void isIpReadyForStaticNat(long vmId, IPAddressVO ipAddress, Account caller, long callerUserId) throws NetworkRuleConflictException, ResourceUnavailableException {
if (ipAddress.isSourceNat()) {
throw new InvalidParameterValueException("Can't enable static, ip address " + ipAddress + " is a sourceNat ip address");
}
if (!ipAddress.isOneToOneNat()) { // Dont allow to enable static nat if PF/LB rules exist for the IP
List<FirewallRuleVO> portForwardingRules = _firewallDao.listByIpAndPurposeAndNotRevoked(ipAddress.getId(), Purpose.PortForwarding);
if (portForwardingRules != null && !portForwardingRules.isEmpty()) {
throw new NetworkRuleConflictException("Failed to enable static nat for the ip address " + ipAddress + " as it already has PortForwarding rules assigned");
}
List<FirewallRuleVO> loadBalancingRules = _firewallDao.listByIpAndPurposeAndNotRevoked(ipAddress.getId(), Purpose.LoadBalancing);
if (loadBalancingRules != null && !loadBalancingRules.isEmpty()) {
throw new NetworkRuleConflictException("Failed to enable static nat for the ip address " + ipAddress + " as it already has LoadBalancing rules assigned");
}
} else if (ipAddress.getAssociatedWithVmId() != null && ipAddress.getAssociatedWithVmId().longValue() != vmId) {
throw new NetworkRuleConflictException("Failed to enable static for the ip address " + ipAddress + " and vm id=" + vmId + " as it's already assigned to antoher vm");
}
IPAddressVO oldIP = _ipAddressDao.findByAssociatedVmId(vmId);
if (oldIP != null) {
//If elasticIP functionality is supported in the network, we always have to disable static nat on the old ip in order to re-enable it on the new one
Long networkId = oldIP.getAssociatedWithNetworkId();
boolean reassignStaticNat = false;
if (networkId != null) {
Network guestNetwork = _networkMgr.getNetwork(networkId);
NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId());
if (offering.getElasticIp()) {
reassignStaticNat = true;
}
}
// If there is public ip address already associated with the vm, throw an exception
if (!reassignStaticNat) {
throw new InvalidParameterValueException("Failed to enable static nat for the ip address id=" + ipAddress.getId() + " as vm id=" + vmId + " is already associated with ip id=" + oldIP.getId());
}
//unassign old static nat rule
s_logger.debug("Disassociating static nat for ip " + oldIP);
if (!disableStaticNat(oldIP.getId(), caller, callerUserId, true)) {
throw new CloudRuntimeException("Failed to disable old static nat rule for vm id=" + vmId + " and ip " + oldIP);
}
}
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_DELETE, eventDescription = "revoking forwarding rule", async = true)
public boolean revokePortForwardingRule(long ruleId, boolean apply) {
UserContext ctx = UserContext.current();
Account caller = ctx.getCaller();
PortForwardingRuleVO rule = _portForwardingDao.findById(ruleId);
if (rule == null) {
throw new InvalidParameterValueException("Unable to find " + ruleId);
}
_accountMgr.checkAccess(caller, null, true, rule);
if(!revokePortForwardingRuleInternal(ruleId, caller, ctx.getCallerUserId(), apply)){
throw new CloudRuntimeException("Failed to delete port forwarding rule");
}
return true;
}
private boolean revokePortForwardingRuleInternal(long ruleId, Account caller, long userId, boolean apply) {
PortForwardingRuleVO rule = _portForwardingDao.findById(ruleId);
_firewallMgr.revokeRule(rule, caller, userId, true);
boolean success = false;
if (apply) {
success = applyPortForwardingRules(rule.getSourceIpAddressId(), true, caller);
} else {
success = true;
}
return success;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_DELETE, eventDescription = "revoking forwarding rule", async = true)
public boolean revokeStaticNatRule(long ruleId, boolean apply) {
UserContext ctx = UserContext.current();
Account caller = ctx.getCaller();
FirewallRuleVO rule = _firewallDao.findById(ruleId);
if (rule == null) {
throw new InvalidParameterValueException("Unable to find " + ruleId);
}
_accountMgr.checkAccess(caller, null, true, rule);
if(!revokeStaticNatRuleInternal(ruleId, caller, ctx.getCallerUserId(), apply)){
throw new CloudRuntimeException("Failed to revoke forwarding rule");
}
return true;
}
private boolean revokeStaticNatRuleInternal(long ruleId, Account caller, long userId, boolean apply) {
FirewallRuleVO rule = _firewallDao.findById(ruleId);
_firewallMgr.revokeRule(rule, caller, userId, true);
boolean success = false;
if (apply) {
success = applyStaticNatRules(rule.getSourceIpAddressId(), true, caller);
} else {
success = true;
}
return success;
}
@Override
public boolean revokePortForwardingRulesForVm(long vmId) {
boolean success = true;
UserVmVO vm = _vmDao.findByIdIncludingRemoved(vmId);
if (vm == null) {
return false;
}
List<PortForwardingRuleVO> rules = _portForwardingDao.listByVm(vmId);
Set<Long> ipsToReprogram = new HashSet<Long>();
if (rules == null || rules.isEmpty()) {
s_logger.debug("No port forwarding rules are found for vm id=" + vmId);
return true;
}
for (PortForwardingRuleVO rule : rules) {
// Mark port forwarding rule as Revoked, but don't revoke it yet (apply=false)
revokePortForwardingRuleInternal(rule.getId(), _accountMgr.getSystemAccount(), Account.ACCOUNT_ID_SYSTEM, false);
ipsToReprogram.add(rule.getSourceIpAddressId());
}
// apply rules for all ip addresses
for (Long ipId : ipsToReprogram) {
s_logger.debug("Applying port forwarding rules for ip address id=" + ipId + " as a part of vm expunge");
if (!applyPortForwardingRules(ipId, true, _accountMgr.getSystemAccount())) {
s_logger.warn("Failed to apply port forwarding rules for ip id=" + ipId);
success = false;
}
}
return success;
}
@Override
public boolean revokeStaticNatRulesForVm(long vmId) {
boolean success = true;
UserVmVO vm = _vmDao.findByIdIncludingRemoved(vmId);
if (vm == null) {
return false;
}
List<FirewallRuleVO> rules = _firewallDao.listStaticNatByVmId(vm.getId());
Set<Long> ipsToReprogram = new HashSet<Long>();
if (rules == null || rules.isEmpty()) {
s_logger.debug("No static nat rules are found for vm id=" + vmId);
return true;
}
for (FirewallRuleVO rule : rules) {
// mark static nat as Revoked, but don't revoke it yet (apply = false)
revokeStaticNatRuleInternal(rule.getId(), _accountMgr.getSystemAccount(), Account.ACCOUNT_ID_SYSTEM, false);
ipsToReprogram.add(rule.getSourceIpAddressId());
}
// apply rules for all ip addresses
for (Long ipId : ipsToReprogram) {
s_logger.debug("Applying static nat rules for ip address id=" + ipId + " as a part of vm expunge");
if (!applyStaticNatRules(ipId, true, _accountMgr.getSystemAccount())) {
success = false;
s_logger.warn("Failed to apply static nat rules for ip id=" + ipId);
}
}
return success;
}
@Override
public List<? extends PortForwardingRule> listPortForwardingRulesForApplication(long ipId) {
return _portForwardingDao.listForApplication(ipId);
}
@Override
public List<? extends PortForwardingRule> listPortForwardingRules(ListPortForwardingRulesCmd cmd) {
Long ipId = cmd.getIpAddressId();
Long id = cmd.getId();
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
if (ipId != null) {
IPAddressVO ipAddressVO = _ipAddressDao.findById(ipId);
if (ipAddressVO == null || !ipAddressVO.readyToUse()) {
throw new InvalidParameterValueException("Ip address id=" + ipId + " not ready for port forwarding rules yet");
}
_accountMgr.checkAccess(caller, null, true, ipAddressVO);
}
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll());
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter filter = new Filter(PortForwardingRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<PortForwardingRuleVO> sb = _portForwardingDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sb.and("id", sb.entity().getId(), Op.EQ);
sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ);
sb.and("purpose", sb.entity().getPurpose(), Op.EQ);
SearchCriteria<PortForwardingRuleVO> sc = sb.create();
_accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
if (id != null) {
sc.setParameters("id", id);
}
if (ipId != null) {
sc.setParameters("ip", ipId);
}
sc.setParameters("purpose", Purpose.PortForwarding);
return _portForwardingDao.search(sc, filter);
}
@Override
public List<String> getSourceCidrs(long ruleId){
return _firewallCidrsDao.getSourceCidrs(ruleId);
}
@Override
public boolean applyPortForwardingRules(long ipId, boolean continueOnError, Account caller) {
List<PortForwardingRuleVO> rules = _portForwardingDao.listForApplication(ipId);
if (rules.size() == 0) {
s_logger.debug("There are no firwall rules to apply for ip id=" + ipId);
return true;
}
if (caller != null) {
_accountMgr.checkAccess(caller, null, true, rules.toArray(new PortForwardingRuleVO[rules.size()]));
}
try {
if (!_firewallMgr.applyRules(rules, continueOnError, true)) {
return false;
}
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to apply firewall rules due to ", ex);
return false;
}
return true;
}
@Override
public boolean applyStaticNatRules(long sourceIpId, boolean continueOnError, Account caller) {
List<? extends FirewallRule> rules = _firewallDao.listByIpAndPurpose(sourceIpId, Purpose.StaticNat);
List<StaticNatRule> staticNatRules = new ArrayList<StaticNatRule>();
if (rules.size() == 0) {
s_logger.debug("There are no firwall rules to apply for ip id=" + sourceIpId);
return true;
}
for (FirewallRule rule : rules) {
staticNatRules.add(buildStaticNatRule(rule));
}
if (caller != null) {
_accountMgr.checkAccess(caller, null, true, staticNatRules.toArray(new StaticNatRule[staticNatRules.size()]));
}
try {
if (!_firewallMgr.applyRules(staticNatRules, continueOnError, true)) {
return false;
}
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to apply static nat rules due to ", ex);
return false;
}
return true;
}
@Override
public boolean applyPortForwardingRulesForNetwork(long networkId, boolean continueOnError, Account caller) {
List<PortForwardingRuleVO> rules = listByNetworkId(networkId);
if (rules.size() == 0) {
s_logger.debug("There are no port forwarding rules to apply for network id=" + networkId);
return true;
}
if (caller != null) {
_accountMgr.checkAccess(caller, null, true, rules.toArray(new PortForwardingRuleVO[rules.size()]));
}
try {
if (!_firewallMgr.applyRules(rules, continueOnError, true)) {
return false;
}
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to apply firewall rules due to ", ex);
return false;
}
return true;
}
@Override
public boolean applyStaticNatRulesForNetwork(long networkId, boolean continueOnError, Account caller) {
List<FirewallRuleVO> rules = _firewallDao.listByNetworkAndPurpose(networkId, Purpose.StaticNat);
List<StaticNatRule> staticNatRules = new ArrayList<StaticNatRule>();
if (rules.size() == 0) {
s_logger.debug("There are no static nat rules to apply for network id=" + networkId);
return true;
}
if (caller != null) {
_accountMgr.checkAccess(caller, null, true, rules.toArray(new FirewallRule[rules.size()]));
}
for (FirewallRuleVO rule : rules) {
staticNatRules.add(buildStaticNatRule(rule));
}
try {
if (!_firewallMgr.applyRules(staticNatRules, continueOnError, true)) {
return false;
}
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to apply firewall rules due to ", ex);
return false;
}
return true;
}
@Override
public boolean applyStaticNatsForNetwork(long networkId, boolean continueOnError, Account caller) {
List<IPAddressVO> ips = _ipAddressDao.listStaticNatPublicIps(networkId);
if (ips.isEmpty()) {
s_logger.debug("There are no static nat to apply for network id=" + networkId);
return true;
}
if (caller != null) {
_accountMgr.checkAccess(caller, null, true, ips.toArray(new IPAddressVO[ips.size()]));
}
List<StaticNat> staticNats = new ArrayList<StaticNat>();
for (IPAddressVO ip : ips) {
// Get nic IP4 address
String dstIp = _networkMgr.getIpInNetwork(ip.getAssociatedWithVmId(), networkId);
StaticNatImpl staticNat = new StaticNatImpl(ip.getAllocatedToAccountId(), ip.getAllocatedInDomainId(), networkId, ip.getId(), dstIp, false);
staticNats.add(staticNat);
}
try {
if (!_networkMgr.applyStaticNats(staticNats, continueOnError)) {
return false;
}
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to create static nat rule due to ", ex);
return false;
}
return true;
}
@Override
public List<? extends FirewallRule> searchStaticNatRules(Long ipId, Long id, Long vmId, Long start, Long size, String accountName, Long domainId, Long projectId, boolean isRecursive, boolean listAll) {
Account caller = UserContext.current().getCaller();
List<Long> permittedAccounts = new ArrayList<Long>();
if (ipId != null) {
IPAddressVO ipAddressVO = _ipAddressDao.findById(ipId);
if (ipAddressVO == null || !ipAddressVO.readyToUse()) {
throw new InvalidParameterValueException("Ip address id=" + ipId + " not ready for port forwarding rules yet");
}
_accountMgr.checkAccess(caller, null, true, ipAddressVO);
}
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(domainId, isRecursive, null);
_accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, listAll);
domainId = domainIdRecursiveListProject.first();
isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter filter = new Filter(PortForwardingRuleVO.class, "id", false, start, size);
SearchBuilder<FirewallRuleVO> sb = _firewallDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ);
sb.and("purpose", sb.entity().getPurpose(), Op.EQ);
sb.and("id", sb.entity().getId(), Op.EQ);
if (vmId != null) {
SearchBuilder<IPAddressVO> ipSearch = _ipAddressDao.createSearchBuilder();
ipSearch.and("associatedWithVmId", ipSearch.entity().getAssociatedWithVmId(), Op.EQ);
sb.join("ipSearch", ipSearch, sb.entity().getSourceIpAddressId(), ipSearch.entity().getId(), JoinBuilder.JoinType.INNER);
}
SearchCriteria<FirewallRuleVO> sc = sb.create();
_accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sc.setParameters("purpose", Purpose.StaticNat);
if (id != null) {
sc.setParameters("id", id);
}
if (ipId != null) {
sc.setParameters("ip", ipId);
}
if (vmId != null) {
sc.setJoinParameters("ipSearch", "associatedWithVmId", vmId);
}
return _firewallDao.search(sc, filter);
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "applying port forwarding rule", async = true)
public boolean applyPortForwardingRules(long ipId, Account caller) throws ResourceUnavailableException {
if(!applyPortForwardingRules(ipId, false, caller)){
throw new CloudRuntimeException("Failed to apply port forwarding rule");
}
return true;
}
@Override
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "applying static nat rule", async = true)
public boolean applyStaticNatRules(long ipId, Account caller) throws ResourceUnavailableException {
if(!applyStaticNatRules(ipId, false, caller)){
throw new CloudRuntimeException("Failed to apply static nat rule");
}
return true;
}
@Override
public boolean revokeAllPFAndStaticNatRulesForIp(long ipId, long userId, Account caller) throws ResourceUnavailableException {
List<FirewallRule> rules = new ArrayList<FirewallRule>();
List<PortForwardingRuleVO> pfRules = _portForwardingDao.listByIpAndNotRevoked(ipId);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing " + pfRules.size() + " port forwarding rules for ip id=" + ipId);
}
for (PortForwardingRuleVO rule : pfRules) {
// Mark all PF rules as Revoke, but don't revoke them yet
revokePortForwardingRuleInternal(rule.getId(), caller, userId, false);
}
List<FirewallRuleVO> staticNatRules = _firewallDao.listByIpAndPurposeAndNotRevoked(ipId, Purpose.StaticNat);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing " + staticNatRules.size() + " static nat rules for ip id=" + ipId);
}
for (FirewallRuleVO rule : staticNatRules) {
// Mark all static nat rules as Revoke, but don't revoke them yet
revokeStaticNatRuleInternal(rule.getId(), caller, userId, false);
}
//revoke static nat for the ip address
boolean success = applyStaticNatForIp(ipId, false, caller, true);
// revoke all port forwarding rules
success = success && applyPortForwardingRules(ipId, true, caller);
// revoke all all static nat rules
success = success && applyStaticNatRules(ipId, true, caller);
// Now we check again in case more rules have been inserted.
rules.addAll(_portForwardingDao.listByIpAndNotRevoked(ipId));
rules.addAll(_firewallDao.listByIpAndPurposeAndNotRevoked(ipId, Purpose.StaticNat));
if (s_logger.isDebugEnabled() && success) {
s_logger.debug("Successfully released rules for ip id=" + ipId + " and # of rules now = " + rules.size());
}
return (rules.size() == 0 && success);
}
@Override
public boolean revokeAllPFStaticNatRulesForNetwork(long networkId, long userId, Account caller) throws ResourceUnavailableException {
List<FirewallRule> rules = new ArrayList<FirewallRule>();
List<PortForwardingRuleVO> pfRules = _portForwardingDao.listByNetwork(networkId);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing " + pfRules.size() + " port forwarding rules for network id=" + networkId);
}
List<FirewallRuleVO> staticNatRules = _firewallDao.listByNetworkAndPurpose(networkId, Purpose.StaticNat);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing " + staticNatRules.size() + " static nat rules for network id=" + networkId);
}
// Mark all pf rules (Active and non-Active) to be revoked, but don't revoke it yet - pass apply=false
for (PortForwardingRuleVO rule : pfRules) {
revokePortForwardingRuleInternal(rule.getId(), caller, userId, false);
}
// Mark all static nat rules (Active and non-Active) to be revoked, but don't revoke it yet - pass apply=false
for (FirewallRuleVO rule : staticNatRules) {
revokeStaticNatRuleInternal(rule.getId(), caller, userId, false);
}
boolean success = true;
// revoke all PF rules for the network
success = success && applyPortForwardingRulesForNetwork(networkId, true, caller);
// revoke all all static nat rules for the network
success = success && applyStaticNatRulesForNetwork(networkId, true, caller);
// Now we check again in case more rules have been inserted.
rules.addAll(_portForwardingDao.listByNetworkAndNotRevoked(networkId));
rules.addAll(_firewallDao.listByNetworkAndPurposeAndNotRevoked(networkId, Purpose.StaticNat));
if (s_logger.isDebugEnabled()) {
s_logger.debug("Successfully released rules for network id=" + networkId + " and # of rules now = " + rules.size());
}
return success && rules.size() == 0;
}
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
_name = name;
return true;
}
@Override
public boolean start() {
return true;
}
@Override
public boolean stop() {
return true;
}
@Override
public String getName() {
return _name;
}
@Override
public List<? extends FirewallRule> listFirewallRulesByIp(long ipId) {
return null;
}
@Override
public boolean releasePorts(long ipId, String protocol, FirewallRule.Purpose purpose, int... ports) {
return _firewallDao.releasePorts(ipId, protocol, purpose, ports);
}
@Override
@DB
public FirewallRuleVO[] reservePorts(IpAddress ip, String protocol, FirewallRule.Purpose purpose, boolean openFirewall, Account caller, int... ports) throws NetworkRuleConflictException {
FirewallRuleVO[] rules = new FirewallRuleVO[ports.length];
Transaction txn = Transaction.currentTxn();
txn.start();
for (int i = 0; i < ports.length; i++) {
rules[i] = new FirewallRuleVO(null, ip.getId(), ports[i], protocol, ip.getAssociatedWithNetworkId(), ip.getAllocatedToAccountId(), ip.getAllocatedInDomainId(), purpose, null, null, null, null);
rules[i] = _firewallDao.persist(rules[i]);
if (openFirewall) {
_firewallMgr.createRuleForAllCidrs(ip.getId(), caller, ports[i], ports[i], protocol, null, null, rules[i].getId());
}
}
txn.commit();
boolean success = false;
try {
for (FirewallRuleVO newRule : rules) {
_firewallMgr.detectRulesConflict(newRule, ip);
}
success = true;
return rules;
} finally {
if (!success) {
txn.start();
for (FirewallRuleVO newRule : rules) {
_portForwardingDao.remove(newRule.getId());
}
txn.commit();
}
}
}
@Override
public List<? extends PortForwardingRule> gatherPortForwardingRulesForApplication(List<? extends IpAddress> addrs) {
List<PortForwardingRuleVO> allRules = new ArrayList<PortForwardingRuleVO>();
for (IpAddress addr : addrs) {
if (!addr.readyToUse()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Skipping " + addr + " because it is not ready for propation yet.");
}
continue;
}
allRules.addAll(_portForwardingDao.listForApplication(addr.getId()));
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found " + allRules.size() + " rules to apply for the addresses.");
}
return allRules;
}
@Override
public List<PortForwardingRuleVO> listByNetworkId(long networkId) {
return _portForwardingDao.listByNetwork(networkId);
}
@Override
public boolean disableStaticNat(long ipId) throws ResourceUnavailableException, NetworkRuleConflictException, InsufficientAddressCapacityException{
UserContext ctx = UserContext.current();
Account caller = ctx.getCaller();
IPAddressVO ipAddress = _ipAddressDao.findById(ipId);
checkIpAndUserVm(ipAddress, null, caller);
if (ipAddress.getElastic()) {
throw new InvalidParameterValueException("Can't disable static nat for elastic IP address " + ipAddress);
}
Long vmId = ipAddress.getAssociatedWithVmId();
if (vmId == null) {
throw new InvalidParameterValueException("IP address " + ipAddress + " is not associated with any vm Id");
}
//if network has elastic IP functionality supported, we first have to disable static nat on old ip in order to re-enable it on the new one
//enable static nat takes care of that
Network guestNetwork = _networkMgr.getNetwork(ipAddress.getAssociatedWithNetworkId());
NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId());
if (offering.getElasticIp()) {
enableElasticIpAndStaticNatForVm(_vmDao.findById(vmId), true);
return true;
} else {
return disableStaticNat(ipId, caller, ctx.getCallerUserId(), false);
}
}
@Override @DB
public boolean disableStaticNat(long ipId, Account caller, long callerUserId, boolean releaseIpIfElastic) throws ResourceUnavailableException {
boolean success = true;
IPAddressVO ipAddress = _ipAddressDao.findById(ipId);
checkIpAndUserVm(ipAddress, null, caller);
if (!ipAddress.isOneToOneNat()) {
throw new InvalidParameterValueException("One to one nat is not enabled for the ip id=" + ipId);
}
//Revoke all firewall rules for the ip
try {
s_logger.debug("Revoking all " + Purpose.Firewall + "rules as a part of disabling static nat for public IP id=" + ipId);
if (!_firewallMgr.revokeFirewallRulesForIp(ipId, callerUserId, caller)) {
s_logger.warn("Unable to revoke all the firewall rules for ip id=" + ipId + " as a part of disable statis nat");
success = false;
}
} catch (ResourceUnavailableException e) {
s_logger.warn("Unable to revoke all firewall rules for ip id=" + ipId + " as a part of ip release", e);
success = false;
}
if (!revokeAllPFAndStaticNatRulesForIp(ipId, callerUserId, caller)) {
s_logger.warn("Unable to revoke all static nat rules for ip " + ipAddress);
success = false;
}
if (success) {
boolean isIpElastic = ipAddress.getElastic();
ipAddress.setOneToOneNat(false);
ipAddress.setAssociatedWithVmId(null);
if (isIpElastic && !releaseIpIfElastic) {
ipAddress.setElastic(false);
}
_ipAddressDao.update(ipAddress.getId(), ipAddress);
if (isIpElastic && releaseIpIfElastic && !_networkMgr.handleElasticIpRelease(ipAddress)) {
s_logger.warn("Failed to release elastic ip address " + ipAddress);
success = false;
}
return true;
} else {
s_logger.warn("Failed to disable one to one nat for the ip address id" + ipId);
return false;
}
}
@Override
public PortForwardingRule getPortForwardigRule(long ruleId) {
return _portForwardingDao.findById(ruleId);
}
@Override
public FirewallRule getFirewallRule(long ruleId) {
return _firewallDao.findById(ruleId);
}
@Override
public StaticNatRule buildStaticNatRule(FirewallRule rule) {
IpAddress ip = _ipAddressDao.findById(rule.getSourceIpAddressId());
FirewallRuleVO ruleVO = _firewallDao.findById(rule.getId());
if (ip == null || !ip.isOneToOneNat() || ip.getAssociatedWithVmId() == null) {
throw new InvalidParameterValueException("Source ip address of the rule id=" + rule.getId() + " is not static nat enabled");
}
String dstIp = _networkMgr.getIpInNetwork(ip.getAssociatedWithVmId(), rule.getNetworkId());
return new StaticNatRuleImpl(ruleVO, dstIp);
}
@Override
public boolean applyStaticNatForIp(long sourceIpId, boolean continueOnError, Account caller, boolean forRevoke) {
List<StaticNat> staticNats = new ArrayList<StaticNat>();
IpAddress sourceIp = _ipAddressDao.findById(sourceIpId);
if (!sourceIp.isOneToOneNat()) {
s_logger.debug("Source ip id=" + sourceIpId + " is not one to one nat");
return true;
}
Long networkId = sourceIp.getAssociatedWithNetworkId();
if (networkId == null) {
throw new CloudRuntimeException("Ip address is not associated with any network");
}
UserVmVO vm = _vmDao.findById(sourceIp.getAssociatedWithVmId());
Network network = _networkMgr.getNetwork(networkId);
if (network == null) {
throw new CloudRuntimeException("Unable to find ip address to map to in vm id=" + vm.getId());
}
if (caller != null) {
_accountMgr.checkAccess(caller, null, true, sourceIp);
}
//create new static nat rule
// Get nic IP4 address
String dstIp;
if (forRevoke) {
dstIp = _networkMgr.getIpInNetworkIncludingRemoved(sourceIp.getAssociatedWithVmId(), networkId);
} else {
dstIp = _networkMgr.getIpInNetwork(sourceIp.getAssociatedWithVmId(), networkId);
}
StaticNatImpl staticNat = new StaticNatImpl(sourceIp.getAllocatedToAccountId(), sourceIp.getAllocatedInDomainId(), networkId, sourceIpId, dstIp, forRevoke);
staticNats.add(staticNat);
try {
if (!_networkMgr.applyStaticNats(staticNats, continueOnError)) {
return false;
}
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to create static nat rule due to ", ex);
return false;
}
return true;
}
@Override
public void enableElasticIpAndStaticNatForVm(UserVm vm, boolean getNewIp) throws InsufficientAddressCapacityException{
boolean success = true;
//enable static nat if eIp capability is supported
List<? extends Nic> nics = _nicDao.listByVmId(vm.getId());
for (Nic nic : nics) {
Network guestNetwork = _networkMgr.getNetwork(nic.getNetworkId());
NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId());
if (offering.getElasticIp()) {
//check if there is already static nat enabled
if (_ipAddressDao.findByAssociatedVmId(vm.getId()) != null && !getNewIp) {
s_logger.debug("Vm " + vm + " already has elastic ip associated with it in guest network " + guestNetwork);
continue;
}
s_logger.debug("Allocating elastic ip and enabling static nat for it for the vm " + vm + " in guest network " + guestNetwork);
IpAddress ip = _networkMgr.assignElasticIp(guestNetwork.getId(), _accountMgr.getAccount(vm.getAccountId()), false, true);
if (ip == null) {
throw new CloudRuntimeException("Failed to allocate elastic ip for vm " + vm + " in guest network " + guestNetwork);
}
s_logger.debug("Allocated elastic ip " + ip + ", now enabling static nat on it for vm " + vm);
try {
success = enableStaticNat(ip.getId(), vm.getId());
} catch (NetworkRuleConflictException ex) {
s_logger.warn("Failed to enable static nat as a part of enabling elasticIp and staticNat for vm " + vm + " in guest network " + guestNetwork + " due to exception ", ex);
success = false;
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to enable static nat as a part of enabling elasticIp and staticNat for vm " + vm + " in guest network " + guestNetwork + " due to exception ", ex);
success = false;
}
if (!success) {
s_logger.warn("Failed to enable static nat on elastic ip " + ip + " for the vm " + vm + ", releasing the ip...");
_networkMgr.handleElasticIpRelease(ip);
throw new CloudRuntimeException("Failed to enable static nat on elastic ip for the vm " + vm);
} else {
s_logger.warn("Succesfully enabled static nat on elastic ip " + ip + " for the vm " + vm);
}
}
}
}
}
|
package org.dainst.idaifield.importer;
import org.dainst.idaifield.model.Geometry;
import org.dainst.idaifield.model.GeometryType;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.MultiLineString;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.io.WKTReader;
/**
* @author Thomas Kleinke
*/
class WktParser {
static Geometry getMultiPointGeometry(String wkt) throws Exception {
Geometry geometry = new Geometry();
geometry.setCoordinates(new double[][][][]{{getMultiPointOrPolylineCoordinates(
new WKTReader().read(wkt)
)}});
geometry.setType(GeometryType.MULTIPOINT);
return geometry;
}
static Geometry getMultiPolylineGeometry(String wkt) throws Exception {
Geometry geometry = new Geometry();
geometry.setCoordinates(new double[][][][]{getMultiPolylineCoordinates(
(MultiLineString) new WKTReader().read(wkt)
)});
geometry.setType(GeometryType.MULTIPOLYLINE);
return geometry;
}
static Geometry getMultiPolygonGeometry(String wkt) throws Exception {
Geometry geometry = new Geometry();
geometry.setCoordinates(getMultipolygonCoordinates((MultiPolygon) new WKTReader().read(wkt)));
geometry.setType(GeometryType.MULTIPOLYGON);
return geometry;
}
private static double[][] getMultiPointOrPolylineCoordinates(org.locationtech.jts.geom.Geometry geometry) {
double[][] coordinates = new double[geometry.getCoordinates().length][];
for (int i = 0; i < geometry.getCoordinates().length; i++) {
Coordinate coordinate = geometry.getCoordinates()[i];
coordinates[i] = new double[Double.isNaN(coordinate.getZ()) ? 2 : 3];
coordinates[i][0] = geometry.getCoordinates()[i].getX();
coordinates[i][1] = geometry.getCoordinates()[i].getY();
if (!Double.isNaN(coordinate.getZ())) coordinates[i][1] = coordinate.getZ();
}
return coordinates;
}
private static double[][][] getMultiPolylineCoordinates(MultiLineString multiPolyline) {
double[][][] coordinates = new double[multiPolyline.getNumGeometries()][][];
for (int i = 0; i < multiPolyline.getNumGeometries(); i++) {
org.locationtech.jts.geom.Geometry geometry = multiPolyline.getGeometryN(i);
coordinates[i] = getMultiPointOrPolylineCoordinates(geometry);
}
return coordinates;
}
private static double[][][] getPolygonCoordinates(Polygon polygon) {
double[][][] coordinates = new double[polygon.getNumInteriorRing() + 1][][];
coordinates[0] = getMultiPointOrPolylineCoordinates(polygon.getExteriorRing());
for (int i = 0; i < polygon.getNumInteriorRing(); i++) {
coordinates[i + 1] = getMultiPointOrPolylineCoordinates(polygon.getInteriorRingN(i));
}
return coordinates;
}
private static double[][][][] getMultipolygonCoordinates(MultiPolygon multiPolygon) {
double[][][][] coordinates = new double[multiPolygon.getNumGeometries()][][][];
for (int i = 0; i < multiPolygon.getNumGeometries(); i++) {
Polygon polygon = (Polygon) multiPolygon.getGeometryN(i);
coordinates[i] = getPolygonCoordinates(polygon);
}
return coordinates;
}
}
|
// This program aggregates by IP hits on apache access logs.
// It can get the top ten of IP's
package com.amazonaws.vivanih.hadoop.cascading;
import cascading.flow.Flow;
import cascading.flow.FlowDef;
import cascading.flow.hadoop.HadoopFlowConnector;
import cascading.operation.aggregator.Count;
import cascading.operation.filter.Sample;
import cascading.operation.filter.Limit;
import cascading.operation.regex.RegexParser;
import cascading.operation.text.DateParser;
import cascading.pipe.*;
import cascading.property.AppProps;
import cascading.scheme.hadoop.TextDelimited;
import cascading.scheme.hadoop.TextLine;
import cascading.tap.SinkMode;
import cascading.tap.Tap;
import cascading.tap.hadoop.Hfs;
import cascading.tuple.Fields;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
String inputPath = args[0]; //input will use default filesystem. HDFS or S3.
String outputPath = args[1];
String sortedTopTen = args[ 1 ] + "/top10/";
// sources and sinks
Tap inTap = new Hfs(new TextLine(), inputPath); //input
Tap outTap = new Hfs(new TextDelimited(true, ";"), outputPath, SinkMode.REPLACE); //output
Tap top10Tap = new Hfs( new TextDelimited(true, ";"), sortedTopTen, SinkMode.REPLACE);
// Parse the line of input and break them into five fields
RegexParser parser = new RegexParser(new Fields("ip", "time", "request", "response", "size"),
"^([^ ]*) \\S+ \\S+ \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(.+?)\" (\\d{3}) ([^ ]*).*$", new int[]{1, 2, 3, 4, 5});
// "Each" pipe applies a Function or Filter Operation to each Tuple that passes through it.
Pipe processPipe = new Each("processPipe", new Fields("line"), parser, Fields.RESULTS);
// Grouping by 'ip' field:
// "GroupBy" manages one input Tuple stream and, groups the stream on selected fields in the tuple stream.
processPipe = new GroupBy(processPipe, new Fields("ip"));
// Aggregate each "ip" group using Count function:
// "Every" pipe applies an Aggregator (like count, or sum) or Buffer (a sliding window) Operation to every group of Tuples that pass through it.
processPipe = new Every(processPipe, Fields.GROUP, new Count(new Fields("IPcount")), Fields.ALL);
// After aggregation counter for each "ip," sort the counts. "true" is descending order
Pipe sortedCountByIpPipe = new GroupBy(processPipe, new Fields("IPcount"), true);
// Limit them to the first 10, in the descending order
sortedCountByIpPipe = new Each(sortedCountByIpPipe, new Fields("IPcount"), new Limit(10));
// Join the pipe together in the flow, creating inputs and outputs (taps)
FlowDef flowDef = FlowDef.flowDef()
.addSource(processPipe, inTap)
.addTailSink(processPipe, outTap) // comment to use sorted top 10
.addTailSink(sortedCountByIpPipe, top10Tap) //uncomment to use sorted top 10
.setName("DataProcessing");
Properties properties = AppProps.appProps()
.setName("DataProcessing")
.buildProperties();
Flow parsedLogFlow = new HadoopFlowConnector(properties).connect(flowDef);
//Finally, execute the flow.
parsedLogFlow.complete();
}
}
|
package api.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import actions.scoringActions.ScoringSummStAction;
import api.ApiInterface;
import application.AppBean;
import beans.relation.summary.SummaryStElem;
import beans.relation.summary.SummaryStatement;
import beans.relation.summary.SummaryStatementSQ;
import beans.scoring.ScoreBean;
import beans.scripts.PatientIllnessScript;
import controller.JsonCreator;
import controller.SummaryStatementController;
import database.DBClinReason;
import net.casus.util.CasusConfiguration;
import net.casus.util.StringUtilities;
import net.casus.util.Utility;
import util.CRTLogger;
/**
* simple JSON Webservice for simple API JSON framework
*
* <base>/crt/src/html/api/api.xhtml?impl=peerSync
* should either start a new thread, or return basic running thread data!
*
* @author Gulpi (=Martin Adler)
*/
public class SummaryStatementAPI implements ApiInterface {
AppBean appBean = null;
ReScoreThread thread = null;
ReScoreThread lastThread = null;
public SummaryStatementAPI() {
}
/**
* needs to be initialized, to be available alos from Threads, which do NOT have a Faces context!!!
* @return
*/
public AppBean getAppBean(){
if (appBean == null) {
ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
appBean = (AppBean) context.getAttribute(AppBean.APP_KEY);
}
return appBean;
}
@SuppressWarnings("unchecked")
@Override
public synchronized String handle() {
String result = null;
@SuppressWarnings("rawtypes")
Map resultObj = new TreeMap();
try {
// make sure appBean is there / in internal thread we don't have contexts!!
this.getAppBean();
// make sure lists are created already!
if (SummaryStatementController.getListItemsByLang("de") == null || SummaryStatementController.getListItemsByLang("en") == null) {
ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
new JsonCreator().initJsonExport(context);
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ReScoreThread mythread = thread;
String status = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("status");
if (StringUtilities.isValidString(status) && status.equalsIgnoreCase("true")) {
if (mythread != null) {
fillStatus(resultObj, mythread);
}
else if (lastThread != null) {
fillStatus(resultObj, lastThread);
}
else {
resultObj.put("result", "no status available!");
}
}
else {
long id = StringUtilities.getLongFromString((String) ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("id"), -1);
if (id > 0) {
PatientIllnessScript userPatientIllnesScript = new DBClinReason().selectPatIllScriptById(id);
SummaryStatement st = this.handleByPatientIllnessScript(userPatientIllnesScript);
if (st != null) {
resultObj.put("status", "ok");
Map userObj = new TreeMap();
resultObj.put("User", userObj);
boolean collections = StringUtilities.getBooleanFromString((String) ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("collections"), true);
this.addSummaryStatementToResultObj(userObj, userPatientIllnesScript, st, collections);
PatientIllnessScript expScript = getAppBean().addExpertPatIllnessScriptForVpId(userPatientIllnesScript.getVpId());
if (expScript != null) {
Map expertObj = new TreeMap();
resultObj.put("Expert", expertObj);
this.addSummaryStatementToResultObj(expertObj, "ExpertPatientIllnesScript.", expScript);
this.addSummaryStatementToResultObj(expertObj, "ExpertSummaryStatement.", expScript.getSummSt(), true, collections);
}
}
else {
resultObj.put("status", "error");
resultObj.put("errorMsg", "no SummaryStatement object ?");
}
}
else {
if (mythread == null) {
thread = new ReScoreThread();
thread.setCtrl(this);
thread.setMax(StringUtilities.getIntegerFromString((String) ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("max"), 100));
thread.setType(StringUtilities.getIntegerFromString((String) ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("type"), PatientIllnessScript.TYPE_LEARNER_CREATED));
thread.setStartDate(StringUtilities.getDateFromString((String) ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("start_date"), null));
thread.setEndDate(StringUtilities.getDateFromString((String) ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("end_date"), null));
thread.setLoadNodes(StringUtilities.getBooleanFromString((String) ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("load_nodes"), false));
mythread = thread;
mythread.start();
resultObj.put("result", "started");
}
else {
fillStatus(resultObj, mythread);
}
}
}
ObjectMapper mapper = new ObjectMapper();
try {
if (CasusConfiguration.getGlobalBooleanValue("SummaryStatementAPI.prettyJSON", true)) {
result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(resultObj);
}
else {
result = mapper.writeValueAsString(resultObj);
}
} catch (JsonProcessingException e) {
result = e.getMessage();
}
return result;
}
@SuppressWarnings("unchecked")
public void fillStatus(@SuppressWarnings("rawtypes") Map resultObj, ReScoreThread mythread) {
resultObj.put("result", "running");
resultObj.put("started", mythread.getStarted().toString());
if (mythread.getFinished() != null) {
resultObj.put("finished", mythread.getFinished().toString());
}
resultObj.put("sync_max", mythread.getCount());
resultObj.put("sync_idx", mythread.getIdx());
resultObj.put("query_max", mythread.getMax());
resultObj.put("query_start_date", mythread.getStartDate());
resultObj.put("query_end_date", mythread.getEndDate());
String details = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("details");
if (details != null && details.equalsIgnoreCase("true")) {
resultObj.put("details", mythread.getResults());
}
}
public SummaryStatement handleByPatientIllnessScript(PatientIllnessScript userPatientIllnesScript) {
SummaryStatement st = null;
PatientIllnessScript expScript = getAppBean().addExpertPatIllnessScriptForVpId(userPatientIllnesScript.getVpId());
expScript.getSummStStage();
ScoreBean scoreBean = new ScoreBean(userPatientIllnesScript, userPatientIllnesScript.getSummStId(), ScoreBean.TYPE_SUMMST, userPatientIllnesScript.getCurrentStage());
if(expScript!=null && expScript.getSummSt()!=null){
ScoringSummStAction action = new ScoringSummStAction();
st = new SummaryStatementController().initSummStRating(expScript, userPatientIllnesScript, action);
action.doScoring(st, expScript.getSummSt());
}
return st;
}
void addToResultObj(Map resultObj, String key, Object value) {
resultObj.put(key, value != null ? value : "-");
}
void addSummaryStatementToResultObj(Map resultObj, String prefix, PatientIllnessScript userPatientIllnesScript) {
if (userPatientIllnesScript == null) {
this.addToResultObj(resultObj, prefix + "obj", "null");
return;
}
this.addToResultObj(resultObj, prefix + "id", userPatientIllnesScript.getId());
this.addToResultObj(resultObj, prefix + "userId", userPatientIllnesScript.getUserId());
this.addToResultObj(resultObj, prefix + "vpId", userPatientIllnesScript.getVpId());
this.addToResultObj(resultObj, prefix + "stage", userPatientIllnesScript.getCurrentStage());
}
void addSummaryStatementToResultObj(Map resultObj, String prefix, SummaryStatement st, boolean expert, boolean collections) {
if (st == null) {
this.addToResultObj(resultObj, prefix + "obj", "null");
return;
}
this.addToResultObj(resultObj, prefix + "#id", st.getId());
this.addToResultObj(resultObj, prefix + "text", st.getText());
this.addToResultObj(resultObj, prefix + "lang", st.getLang());
this.addToResultObj(resultObj, prefix + "analyzed", st.isAnalyzed());
this.addToResultObj(resultObj, prefix + "creationDate", st.getCreationDate());
//this.addToResultObj(resultObj, prefix + "sqHits", st.getSqHits() );
//this.addToResultObj(resultObj, prefix + "itemHits", st.getItemHits());
this.addToResultObj(resultObj, prefix + "sqScore", st.getSqScore());
this.addToResultObj(resultObj, prefix + "sqScoreBasic", st.getSqScoreBasic());
this.addToResultObj(resultObj, prefix + "sqScorePerc", st.getSqScorePerc());
this.addToResultObj(resultObj, prefix + "transformationScore", st.getTransformationScore());
this.addToResultObj(resultObj, prefix + "transformScorePerc", st.getTransformScorePerc());
this.addToResultObj(resultObj, prefix + "narrowingScore", st.getNarrowingScore());
this.addToResultObj(resultObj, prefix + "narr1Score", st.getNarr1Score());
this.addToResultObj(resultObj, prefix + "narr2Score", st.getNarr2Score());
this.addToResultObj(resultObj, prefix + "narrowingScoreNew", st.getNarrowingScoreNew());
this.addToResultObj(resultObj, prefix + "personScore", st.getPersonScore());
//this.addToResultObj(resultObj, "SummaryStatement.units", st.getUnits());
this.addToResultObj(resultObj, prefix + "transformNum", st.getTransformNum());
this.addToResultObj(resultObj, prefix + "accuracyScore", st.getAccuracyScore());
this.addToResultObj(resultObj, prefix + "globalScore", st.getGlobalScore());
this.addToResultObj(resultObj, prefix + "itemHits.size", st.getItemHits()!=null?st.getItemHits().size():"-");
if (collections && st.getItemHits()!=null) {
StringBuffer sb = new StringBuffer();
Iterator<SummaryStElem> it = st.getItemHits().iterator();
while (it.hasNext()) {
SummaryStElem loop = it.next();
if (loop.getListItem() != null) {
if (sb.length()>0) sb.append(", ");
sb.append(loop.getListItem().getListItemId() + ":" + loop.getListItem().getName());
if (!expert) {
sb.append(";match:" + loop.getExpertMatch() + "," + loop.getExpertScriptMatch());
}
}
else {
if (sb.length()>0) sb.append(", ");
sb.append(loop.getId() + ":" + loop.getType());
if (!expert) {
sb.append(";match:" + loop.getExpertMatch() + "," + loop.getExpertScriptMatch());
}
}
}
this.addToResultObj(resultObj, prefix + "itemHits", "[" + sb.toString() + "]");
}
this.addToResultObj(resultObj, prefix + "anatomyHitElems.size", st.getAnatomyHitElems()!=null?st.getAnatomyHitElems().size():"-");
if (collections && st.getAnatomyHitElems()!=null) {
StringBuffer sb = new StringBuffer();
Iterator<SummaryStElem> it = st.getAnatomyHitElems().iterator();
while (it.hasNext()) {
SummaryStElem loop = it.next();
if (loop.getListItem() != null) {
if (sb.length()>0) sb.append(", ");
sb.append(loop.getListItem().getListItemId() + ":" + loop.getListItem().getName());
if (!expert) {
sb.append(";match:" + loop.getExpertMatch() + "," + loop.getExpertScriptMatch());
}
}
else {
if (sb.length()>0) sb.append(", ");
sb.append(loop.getId() + ":" + loop.getType());
if (!expert) {
sb.append(";match:" + loop.getExpertMatch() + "," + loop.getExpertScriptMatch());
}
}
}
this.addToResultObj(resultObj, prefix + "anatomyHitElems", "[" + sb.toString() + "]");
}
this.addToResultObj(resultObj, prefix + "sqHits.size", st.getSqHits()!=null?st.getSqHits().size():"-");
if (collections && st.getSqHits()!=null) {
StringBuffer sb = new StringBuffer();
Iterator<SummaryStatementSQ> it = st.getSqHits().iterator();
while (it.hasNext()) {
SummaryStatementSQ loop = it.next();
if (sb.length()>0) sb.append(", ");
sb.append(loop.getSqId() + ":" + loop.getText());
}
this.addToResultObj(resultObj, prefix + "sqHits", "[" + sb.toString() + "]");
}
}
void addSummaryStatementToResultObj(Map resultObj, PatientIllnessScript userPatientIllnesScript, SummaryStatement st, boolean collection) {
this.addSummaryStatementToResultObj(resultObj, "UserPatientIllnesScript.", userPatientIllnesScript);
this.addSummaryStatementToResultObj(resultObj, "UserSummaryStatement.", st, false, collection);
}
class ReScoreThread extends Thread {
Date started = new Date();
Date finished = null;
int max = 100;
int type = PatientIllnessScript.TYPE_LEARNER_CREATED;
Date startDate = null;
Date endDate = null;
SummaryStatementAPI ctrl = null;
List<Map> results = new ArrayList<Map>();
boolean loadNodes = false;
int count = -1;
int idx = -1;
@Override
public void run() {
try{
List<PatientIllnessScript> userPatientIllnesScripts = new DBClinReason().selectLearnerPatIllScriptsByNotAnalyzedSummSt(max, startDate, endDate, type, loadNodes);
if (userPatientIllnesScripts != null) {
this.count = userPatientIllnesScripts.size();
this.idx = 0;
Iterator<PatientIllnessScript> it = userPatientIllnesScripts.iterator();
while (it.hasNext()) {
PatientIllnessScript userPatientIllnesScript = it.next();
idx++;
try {
SummaryStatement st = ctrl.handleByPatientIllnessScript(userPatientIllnesScript);
if (st != null) {
Map result1 = new HashMap();
ctrl.addSummaryStatementToResultObj(result1, userPatientIllnesScript, st,false);
results.add(result1);
}
} catch (Throwable e) {
Map result1 = new TreeMap();
Map userObj = new TreeMap();
result1.put("User", userObj);
ctrl.addSummaryStatementToResultObj(userObj, "UserPatientIllnesScript.", userPatientIllnesScript);
ctrl.addToResultObj(result1, "exception", Utility.stackTraceToString(e));
results.add(result1);
}
}
}
}
catch(Exception e){
CRTLogger.out("PeerSyncAPIThread(): " +Utility.stackTraceToString(e), CRTLogger.LEVEL_ERROR);
}
this.setFinished(new Date());
lastThread = thread;
thread = null;
}
public Date getStarted() {
return started;
}
public void setStarted(Date started) {
this.started = started;
}
public Date getFinished() {
return finished;
}
public void setFinished(Date finished) {
this.finished = finished;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public SummaryStatementAPI getCtrl() {
return ctrl;
}
public void setCtrl(SummaryStatementAPI ctrl) {
this.ctrl = ctrl;
}
public List<Map> getResults() {
return results;
}
public void setResults(List<Map> results) {
this.results = results;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getIdx() {
return idx;
}
public void setIdx(int idx) {
this.idx = idx;
}
public boolean isLoadNodes() {
return loadNodes;
}
public void setLoadNodes(boolean loadNodes) {
this.loadNodes = loadNodes;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
}
|
package com.rinworks.robotutils;
import static org.junit.jupiter.api.Assertions.*;
import java.io.File;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
import org.junit.jupiter.api.Test;
import com.rinworks.robotutils.RobotComm.Address;
import com.rinworks.robotutils.RobotComm.ChannelStatistics;
import com.rinworks.robotutils.RobotComm.ReceivedCommand;
import com.rinworks.robotutils.RobotComm.ReceivedMessage;
import com.rinworks.robotutils.RobotComm.SentCommand;
import com.rinworks.robotutils.RobotComm.SentCommand.COMMAND_STATUS;
class RobotCommTest {
private boolean assertionFailure;
private String assertionFailureString;
class TestTransport implements RobotComm.DatagramTransport {
final String ALWAYSDROP_TEXT = "TRANSPORT-MUST-DROP";
private final MyRemoteNode loopbackNode = new MyRemoteNode(new MyAddress("loopback"));
private final ConcurrentLinkedQueue<String> recvQueue = new ConcurrentLinkedQueue<>();
private final Timer transportTimer = new Timer();
private final Random rand = new Random();
private final AtomicLong numSends = new AtomicLong(0);
private final AtomicLong numRecvs = new AtomicLong(0);
private final AtomicLong numForceDrops = new AtomicLong(0);
private final AtomicLong numRandomDrops = new AtomicLong(0);
private final StructuredLogger.Log log;
private boolean closed = false;
private double failureRate = 0;
private int maxDelay = 0;
private MyListener curListener = null; // we support only one listener at a time.
private class MyAddress implements Address {
final String addr;
public MyAddress(String a) {
this.addr = a;
}
@Override
public String stringRepresentation() {
return this.addr;
}
}
TestTransport(StructuredLogger.Log log) {
this.log = log;
}
// Changes transport characteristics: sends datagrams with {failureRate} failure
// rate,
// and {maxDelay} max delay per packet.
void setTransportCharacteristics(double failureRate, int maxDelay) {
assert failureRate >= 0 && failureRate <= 1;
assert maxDelay >= 0;
this.failureRate = failureRate;
this.maxDelay = maxDelay;
}
// {failureRate} "close enough" to 0 is considered to be zero-failures.
boolean zeroFailures() {
return Math.abs(this.failureRate) < 1e-7;
}
boolean noDelays() {
return this.maxDelay == 0;
}
@Override
public Address resolveAddress(String address) {
return new MyAddress(address);
}
private class MyListener implements Listener {
final private Address addr;
final MyRemoteNode loopbackNode;
BiConsumer<String, RemoteNode> clientRecv;
boolean closed;
MyListener(Address a) {
this.addr = a;
this.loopbackNode = new MyRemoteNode(addr);
this.closed = false;
// Test transport supports only one listener at a time.
assert (TestTransport.this.curListener == null);
TestTransport.this.curListener = this;
}
@Override
public void listen(BiConsumer<String, RemoteNode> handler) {
// Listen should only be called once.
assert this.clientRecv == null;
this.clientRecv = handler;
}
@Override
public Address getAddress() {
return this.addr;
}
@Override
public void close() {
this.closed = true;
this.clientRecv = null;
}
void receiveData(String s) {
if (this.clientRecv != null) {
TestTransport.this.numRecvs.incrementAndGet();
log.trace("TRANSPORT RECV:\n[" + s + "]\n");
this.clientRecv.accept(s, loopbackNode);
} else {
TestTransport.this.numForceDrops.incrementAndGet();
}
}
}
@Override
public Listener newListener(Address localAddress) {
return new MyListener(localAddress);
}
private class MyRemoteNode implements RemoteNode {
final Address addr;
MyRemoteNode(Address a) {
this.addr = a;
}
@Override
public Address remoteAddress() {
return addr;
}
@Override
public void send(String msg) {
TestTransport.this.numSends.incrementAndGet();
if (forceDrop(msg)) {
log.trace("TRANSPORT FORCEDROP:\n[" + msg + "]\n");
TestTransport.this.numForceDrops.incrementAndGet();
return;
}
if (nonForceDrop(msg)) {
log.trace("TRANSPORT: RANDDROP\n[" + msg + "]\n");
TestTransport.this.numRandomDrops.incrementAndGet();
return;
}
handleSend(msg);
}
}
@Override
public RemoteNode newRemoteNode(Address remoteAddress) {
return new MyRemoteNode(remoteAddress);
}
public boolean forceDrop(String msg) {
return msg.indexOf(ALWAYSDROP_TEXT) >= 0;
}
public boolean nonForceDrop(String msg) {
if (!this.closed && zeroFailures()) {
return false;
} else {
return this.rand.nextDouble() < this.failureRate;
}
}
@Override
public void close() {
this.closed = true;
this.transportTimer.cancel();
}
public long getNumSends() {
return this.numSends.get();
}
public long getNumRecvs() {
return this.numRecvs.get();
}
public long getNumForceDrops() {
return this.numForceDrops.get();
}
public long getNumRandomDrops() {
return this.numRandomDrops.get();
}
public int getMaxDelay() {
return this.maxDelay;
}
public double getFailureRate() {
return this.failureRate;
}
private void handleSend(String msg) {
if (this.closed) {
TestTransport.this.numForceDrops.incrementAndGet();
return;
}
if (noDelays()) {
if (this.curListener != null) {
// Send right now!
this.curListener.receiveData(msg);
} else {
TestTransport.this.numForceDrops.incrementAndGet();
}
} else {
int delay = (int) (rand.nextDouble() * this.maxDelay);
transportTimer.schedule(new TimerTask() {
@Override
public void run() {
if (!TestTransport.this.closed && TestTransport.this.curListener != null) {
// Delayed send
TestTransport.this.curListener.receiveData(msg);
} else {
TestTransport.this.numForceDrops.incrementAndGet();
}
}
}, delay);
}
}
}
class StressTester {
private final int nThreads;
private final ExecutorService exPool;
private final TestTransport transport;
private final Random rand = new Random();
private final AtomicLong nextId = new AtomicLong(1);
private final Timer testTimer = new Timer();
private final StructuredLogger.Log log;
private final StructuredLogger.Log hfLog; // high frequency (verbose) log
RobotComm rc;
RobotComm.Channel ch;
private final ConcurrentHashMap<Long, MessageRecord> msgMap = new ConcurrentHashMap<>();
private final ConcurrentLinkedQueue<MessageRecord> droppedMsgs = new ConcurrentLinkedQueue<>();
private final ConcurrentHashMap<Long, CommandRecord> cmdMap = new ConcurrentHashMap<>();
private final ConcurrentLinkedQueue<CommandRecord> cmdCliSubmitQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedQueue<CommandRecord> cmdSvrComputeQueue = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedQueue<CommandRecord> droppedCommands = new ConcurrentLinkedQueue<>();
private final ConcurrentLinkedQueue<CommandRecord> droppedResponses = new ConcurrentLinkedQueue<>();
private class MessageRecord {
final long id;
final boolean alwaysDrop;
final String msgType;
final String msgBody;
MessageRecord(long id, boolean alwaysDrop) {
this.id = id;
this.alwaysDrop = alwaysDrop;
this.msgType = randomMsgType();
this.msgBody = alwaysDrop ? transport.ALWAYSDROP_TEXT : randomMessageBody(id);
}
// First line of message body is the internal 'id'. Remainder is random junk.
private String randomMessageBody(long id) {
String strId = Long.toHexString(id);
String body = strId;
int nExtra = rand.nextInt(10);
for (int i = 0; i < nExtra; i++) {
body += "\n" + Long.toHexString(rand.nextLong());
}
return body;
}
// Type is a little bit of random hex digits, possibly an empty string.
private String randomMsgType() {
String msgt = Long.toHexString(rand.nextLong());
assert msgt.length() > 0;
msgt = msgt.substring(rand.nextInt(msgt.length()));
return msgt;
}
}
private class CommandRecord {
final MessageRecord cmdRecord;
final MessageRecord respRecord;
protected SentCommand sentCmd;
final boolean rt; // real time.
final int timeout;
CommandRecord(MessageRecord cmdRecord, MessageRecord respRecord, boolean rt, int timeout) {
this.cmdRecord = cmdRecord;
this.respRecord = respRecord;
this.rt = rt;
this.timeout = timeout;
}
}
public StressTester(int nThreads, TestTransport transport, StructuredLogger.Log log) {
this.nThreads = nThreads;
this.transport = transport;
this.log = log;
this.hfLog = log.newLog("HFLOG");
// Init executor.
this.exPool = Executors.newFixedThreadPool(nThreads);
}
public void init() {
StructuredLogger.Log rcLog = log.newLog("RCOMM");
rcLog.pauseTracing();
this.rc = new RobotComm(transport, rcLog);
RobotComm.Address addr = rc.resolveAddress("localhost");
this.ch = rc.newChannel("testChannel");
this.ch.bindToRemoteNode(addr);
this.rc.startListening();
}
/**
* Stress test sending, receiving and processing of commands.
*
* @param nMessages
* - number of messagegs to submit
* @param submissionRate
* - rate of submission per second
* @param alwaysDropRate
* - rate at which datagrams are always dropped by the transport
*/
public void submitMessages(int nMessages, int submissionRate, double alwaysDropRate) {
final int BATCH_SPAN_MILLIS = 1000;
final int MAX_EXPECTED_TRANSPORT_FAILURES = 1000000;
// If more than LARGE_COUNT messages, there should be NO transport send failures
// else our tracked messages will start to accumulate and take up too much
// memory.
final double expectedTransportFailures = nMessages * transport.getFailureRate();
if (expectedTransportFailures > MAX_EXPECTED_TRANSPORT_FAILURES) {
log.err("Too many transport failures expected " + (int) expectedTransportFailures
+ ") - resulting in too much memory consumption. Abandoning test.");
fail("Too much expected memory consumption to run this test.");
}
this.ch.startReceivingMessages();
try {
int messagesLeft = nMessages;
while (messagesLeft >= submissionRate) {
long t0 = System.currentTimeMillis();
submitMessageBatch(submissionRate, BATCH_SPAN_MILLIS, alwaysDropRate);
messagesLeft -= submissionRate;
long t1 = System.currentTimeMillis();
int sleepTime = (int) Math.max(BATCH_SPAN_MILLIS * 0.1, BATCH_SPAN_MILLIS - (t1 - t0));
Thread.sleep(sleepTime);
pruneDroppedMessages();
}
int timeLeftMillis = (1000 * messagesLeft) / submissionRate;
submitMessageBatch(messagesLeft, timeLeftMillis, alwaysDropRate);
Thread.sleep(timeLeftMillis);
// Having initiated the process of sending all the messages, we now have to
// wait for ??? and verify that exactly those messages that are expected to be
// received are received correctly.
int maxReceiveDelay = transport.getMaxDelay();
log.trace("Waiting to receive up to " + nMessages + " messages");
Thread.sleep(maxReceiveDelay);
int retryCount = 10;
while (retryCount-- > 0 && this.msgMap.size() > transport.getNumRandomDrops()) {
Thread.sleep(250);
purgeAllDroppedMessages();
}
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
// Now we do final validation.
this.finalSendMessageValidation();
this.cleanup();
}
/**
* Stress test sending, receiving and processing of commands.
*
* @param nCommands
* - number of commands to submit
* @param submissionRate
* - rate of submission per second
* @param alwaysDropCmdRate
* - rate at which CMD datagrams are always dropped by the transporrt
* @param alwaysDropRespRate
* - rate at which CMDRESP datagrams are always dropped by the
* transport
* @param maxComputeTime
* - max time it takes to compute a response to a command.
*/
public void submitCommands(int nCommands, double rtFrac, int submissionRate, double alwaysDropCmdRate,
double alwaysDropRespRate, int maxComputeTime) {
final int BATCH_SPAN_MILLIS = 1000;
this.ch.startReceivingCommands();
// Server: the handler for incoming RT commands is right here! RT commands are
// never polled-for.
// NON-RT commands are polled for in submitCommandBatch.
this.ch.startReceivingRtCommands(rcvdCmd -> {
deferredRespond(rcvdCmd, maxComputeTime);
});
try {
int commandsLeft = nCommands;
while (commandsLeft >= submissionRate) {
long t0 = System.currentTimeMillis();
submitCommandBatch(submissionRate, rtFrac, BATCH_SPAN_MILLIS, alwaysDropCmdRate, alwaysDropRespRate,
maxComputeTime);
commandsLeft -= submissionRate;
long t1 = System.currentTimeMillis();
int sleepTime = (int) Math.max(BATCH_SPAN_MILLIS * 0.1, BATCH_SPAN_MILLIS - (t1 - t0));
Thread.sleep(sleepTime);
pruneDroppedCommands(this.droppedCommands);
pruneDroppedCommands(this.droppedResponses);
}
int timeLeftMillis = (1000 * commandsLeft) / submissionRate;
submitCommandBatch(commandsLeft, rtFrac, timeLeftMillis, alwaysDropCmdRate, alwaysDropRespRate,
maxComputeTime);
Thread.sleep(timeLeftMillis);
// Having initiated the process of submitting all the commands, we now have to
// wait for ??? and verify that exactly those commands that are expected to be
// processed were processed correctly.
int approxCompletionDelay = 10 * transport.getMaxDelay();
log.trace("Waiting to receive up to " + nCommands + " commands");
Thread.sleep(approxCompletionDelay);
int retryCount = 1000;
while (retryCount-- > 0 && this.cmdMap.size() > 0) {
rc.periodicWork();
pollServerQueue(maxComputeTime);
Thread.sleep(100);
purgeAllDroppedCommands(this.droppedCommands);
purgeAllDroppedCommands(this.droppedResponses);
pollClientQueue();
}
if (retryCount <= 0) {
log.info("TIMED OUT waiting for all the commands to complete. " + cmdMap.size()
+ " commands in progress.");
}
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
// Now we do final validation.
this.finalSubmitCommandValidation();
this.cleanup();
}
// Keep count of dropped messages by removing the older
// half of them if their number grows larger than DROP_TRIGGER
private void pruneDroppedMessages() {
final long DROP_TRIGGER = 1000;
// Remember that the message map and queue of dropped messages are concurrently
// modified so sizes are estimates.
long sizeEst = this.droppedMsgs.size(); // Warning O(n) operation.
if (sizeEst > DROP_TRIGGER) {
long dropCount = sizeEst / 2;
log.trace("Purging about " + dropCount + " force-dropped messages.");
while (dropCount > 0) {
MessageRecord mr = this.droppedMsgs.poll();
if (mr == null) {
break;
}
this.msgMap.remove(mr.id, mr); // Should be O(log(n)), so it's ok all in all.
dropCount
}
}
}
// Remove all dropped messages (at least the ones that were in the queue when we
// entered
// this method).
private void purgeAllDroppedMessages() {
MessageRecord mr;
while ((mr = this.droppedMsgs.poll()) != null) {
this.msgMap.remove(mr.id, mr); // Should be O(log(n)), so it's ok all in all.
}
}
public void submitMessageBatch(int nMessages, int submissionTimespan, double alwaysDropRate) {
assert this.rc != null;
assert this.ch != null;
assert alwaysDropRate >= 0 && alwaysDropRate <= 1;
assert submissionTimespan >= 0;
log.trace("Beginning to submit " + nMessages + " messages.");
for (int i = 0; i < nMessages; i++) {
boolean alwaysDrop = rand.nextDouble() < alwaysDropRate;
long id = nextId.getAndIncrement();
MessageRecord mr = new MessageRecord(id, alwaysDrop);
int delay = (int) (rand.nextDouble() * submissionTimespan);
this.msgMap.put(id, mr);
if (alwaysDrop) {
this.droppedMsgs.add(mr);
}
this.testTimer.schedule(new TimerTask() {
@Override
public void run() {
StressTester.this.exPool.submit(() -> {
try {
hfLog.trace("Sending message with id " + id);
StressTester.this.ch.sendMessage(mr.msgType, mr.msgBody);
} catch (Exception e) {
logException(e, "#HBdp");
}
});
}
}, delay);
}
int recvAttempts = Math.max(nMessages / 100, 10);
int maxReceiveDelay = submissionTimespan + transport.getMaxDelay();
for (int i = 0; i < recvAttempts; i++) {
int delay = (int) (rand.nextDouble() * submissionTimespan);
// Special case of i == 0 - we schedule our final receive attempt to be AFTER
// the last packet is actually sent by the transport (after a potential delay)
if (i == 0) {
delay = maxReceiveDelay + 1;
}
this.testTimer.schedule(new TimerTask() {
@Override
public void run() {
StressTester.this.exPool.submit(() -> {
try {
// Let's pick up all messages received so far and verify them...
RobotComm.ReceivedMessage rm = ch.pollReceivedMessage();
while (rm != null) {
StressTester.this.processReceivedMessage(rm);
rm = ch.pollReceivedMessage();
}
} catch (Exception e) {
logException(e, "#IEPp");
}
});
}
}, delay);
}
}
protected void logException(Exception e, String loc) {
log.err("EXCEPTION", e.toString() + " loc: " + loc);
e.printStackTrace();
}
private void processReceivedMessage(ReceivedMessage rm) {
// Extract id from message.
// Look it up - we had better find it in our map.
// Verify that we expect to get it - (not alwaysDrop)
// Verify we have not already received it.
// Verify message type and message body is what we expect.
// If all ok, remove this from the hash map.
String msgType = rm.msgType();
String msgBody = rm.message();
int nli = msgBody.indexOf('\n');
String strId = nli < 0 ? msgBody : msgBody.substring(0, nli);
try {
long id = Long.parseUnsignedLong(strId, 16);
hfLog.trace("Received message with id " + id);
MessageRecord mr = this.msgMap.get(id);
// assertNotEquals(mr, null);
log.loggedAssert(mr != null, "mr == null");
// assertEquals(mr.msgType, msgType);
log.loggedAssert(mr.msgType.equals(msgType), "mr.msgType not equal to msgType");
// assertEquals(mr.msgBody, msgBody);
log.loggedAssert(mr.msgBody.equals(msgBody), "mr.msgBody not equal to msgBody");
// assertFalse(mr.alwaysDrop);
log.loggedAssert(!mr.alwaysDrop, "mr.alwaysDrop is true");
this.msgMap.remove(id, mr);
} catch (Exception e) {
logException(e, "#C49U");
fail("Exception attempting to parse ID from received message [" + rm.message() + "]");
}
}
private void finalSendMessageValidation() {
// Verify that the count of messages that still remain in our map
// is exactly equal to the number of messages dropped by the transport - i.e.,
// they were never received.
long randomDrops = this.transport.getNumRandomDrops();
long forceDrops = this.transport.getNumForceDrops();
int mapSize = this.msgMap.size();
log.info("Final verification. ForceDrops: " + forceDrops + " RandomDrops: " + randomDrops + " Missing: "
+ (mapSize - randomDrops));
if (randomDrops != mapSize) {
// We will fail this test later, but do some logging here...
log.info("Drop queue size: " + this.droppedMsgs.size());
for (MessageRecord mr : msgMap.values()) {
String mrStr = "missing mr id=" + mr.id + " drop=" + mr.alwaysDrop;
log.info(mrStr);
}
}
log.flush();
assertEquals(randomDrops, mapSize);
}
private void submitCommandBatch(int nCommands, double rtFrac, int submissionTimespan, double alwaysDropCmdRate,
double alwaysDropRespRate, int maxComputeTime) {
assert this.rc != null;
assert this.ch != null;
assert rtFrac >= 0 && rtFrac <= 1;
assert alwaysDropCmdRate >= 0 && alwaysDropCmdRate <= 1;
assert alwaysDropRespRate >= 0 && alwaysDropRespRate <= 1;
assert submissionTimespan >= 0;
log.trace("Beginning to submit " + nCommands + " commands over " + submissionTimespan + " ms");
// Client: send command
for (int i = 0; i < nCommands; i++) {
boolean alwaysDropCMD = rand.nextDouble() < alwaysDropCmdRate;
long id = nextId.getAndIncrement();
MessageRecord mrCmd = new MessageRecord(id, alwaysDropCMD);
boolean alwaysDropRESP = rand.nextDouble() < alwaysDropRespRate;
MessageRecord mrResp = new MessageRecord(id, alwaysDropRESP);
boolean rt = rand.nextDouble() < rtFrac;
int timeout = (int) (rand.nextDouble() * 1000); // Somewhat arbitrary RT timeout
CommandRecord cr = new CommandRecord(mrCmd, mrResp, rt, timeout);
int delay = (int) (rand.nextDouble() * submissionTimespan);
this.cmdMap.put(id, cr);
this.testTimer.schedule(new TimerTask() {
@Override
public void run() {
StressTester.this.exPool.submit(() -> {
try {
hfLog.trace("Sending cmd with id " + id);
RobotComm.SentCommand sc;
if (rt) {
// Real time command: completion is notified by the calling
// the supplied callback.
sc = StressTester.this.ch.submitRtCommand(mrCmd.msgType, mrCmd.msgBody, timeout,
sc1 -> StressTester.this.processCompletedRtCommand(sc1, cr));
} else {
sc = StressTester.this.ch.submitCommand(mrCmd.msgType, mrCmd.msgBody, true);
}
cr.sentCmd = sc;
if (mrCmd.alwaysDrop && !cr.rt) {
// We *know* that this command will never make it to the server.
// If it is RT, however, it will timeout.
droppedCommands.add(cr);
}
} catch (Exception e) {
logException(e, "#NFG6");
}
});
}
}, delay);
}
// Client: poll for completed commands
int completionChecks = Math.max(nCommands / 100, 10);
final int DELAY_MULTIPLYER = 2; // because of CMD->CMDRESP protocol with potential loss
int maxCompletionTime = submissionTimespan + DELAY_MULTIPLYER * transport.getMaxDelay();
for (int i = 0; i < completionChecks; i++) {
int delay = (int) (rand.nextDouble() * maxCompletionTime);
// Special case of i == 0 - we schedule our final receive attempt to be AFTER
// the last packet is actually sent by the transport (after a potential delay)
if (i == 0) {
delay = maxCompletionTime;
}
this.testTimer.schedule(new TimerTask() {
@Override
public void run() {
pollClientQueue();
}
}, delay);
}
// Server: poll for incoming commands and respond to them
int recvAttempts = Math.max(nCommands / 100, 10);
final int ARRIVAL_DELAY_MULTIPLYER = 1; // Time for CMD message to be transmitted
int maxArrivalTime = submissionTimespan + ARRIVAL_DELAY_MULTIPLYER * transport.getMaxDelay();
for (int i = 0; i < recvAttempts; i++) {
int delay = (int) (rand.nextDouble() * maxArrivalTime);
// Special case of i == 0 - we schedule our final receive attempt to be AFTER
// the last packet is actually sent by the transport (after a potential delay)
if (i == 0) {
delay = maxArrivalTime;
}
this.testTimer.schedule(new TimerTask() {
@Override
public void run() {
pollServerQueue(maxComputeTime);
}
}, delay);
}
// Both: call periodic work "periodically". We actually call somewhat randomly,
// and at least twice,
// including one at the very end.
final int PROCESS_CALL_RATE = 100; // Approx calls to make per second
int processCalls = Math.max(PROCESS_CALL_RATE * maxCompletionTime / 1000, 2);
for (int i = 0; i < processCalls; i++) {
int delay = (int) (rand.nextDouble() * maxCompletionTime);
// Special case of i == 0 - we schedule our final receive attempt to be AFTER
// the last packet is actually sent by the transport (after a potential delay)
if (i == 0) {
delay = maxCompletionTime;
}
this.testTimer.schedule(new TimerTask() {
@Override
public void run() {
StressTester.this.exPool.submit(() -> {
try {
rc.periodicWork();
} catch (Exception e) {
logException(e, "#Olpa");
}
});
}
}, delay);
}
}
protected void pollClientQueue() {
StressTester.this.exPool.submit(() -> {
try {
// Let's pick up all messages received so far and verify them...
RobotComm.SentCommand sc = ch.pollCompletedCommand();
while (sc != null) {
StressTester.this.processCompletedCommand(sc);
sc = ch.pollCompletedCommand();
}
} catch (Exception e) {
logException(e, "#1aVV");
}
});
}
private void pollServerQueue(int maxComputeTime) {
StressTester.this.exPool.submit(() -> {
try {
// Let's pick up all incoming commands received so far and process them
RobotComm.ReceivedCommand rCmd = ch.pollReceivedCommand();
// hfLog.trace("SRV - Polling recv queue. rCmd: " + rCmd);
while (rCmd != null) {
deferredRespond(rCmd, maxComputeTime);
rCmd = ch.pollReceivedCommand();
}
} catch (Exception e) {
logException(e, "#mS6i");
}
});
}
private void deferredRespond(RobotComm.ReceivedCommand rCmd, int maxComputeTime) {
int computeDelay = (int) (rand.nextDouble() * maxComputeTime);
CommandRecord cr = StressTester.this.validateReceivedCommand(rCmd);
if (cr == null) {
return;
}
// Schedule a timer task to send the computed response.
StressTester.this.testTimer.schedule(new TimerTask() {
@Override
public void run() {
StressTester.this.exPool.submit(() -> {
try {
rCmd.respond(cr.respRecord.msgType, cr.respRecord.msgBody);
if (cr.respRecord.alwaysDrop && !cr.rt) {
// We *know* that this response will never make it back to
// the client. If it is an RT message the client will get a timeout.
StressTester.this.droppedResponses.add(cr);
}
} catch (Exception e) {
logException(e, "#t87d");
}
});
}
}, computeDelay);
}
private CommandRecord validateReceivedCommand(ReceivedCommand rCmd) {
// Extract id from message.
// Look it up - we had better find it in our map.
// Verify that we expect to get it - (not alwaysDrop)
// Verify we have not already received it - exactly once reception
// Verify message type and message body is what we expect.
// If all ok return it.
String msgType = rCmd.msgType();
String msgBody = rCmd.message();
int nli = msgBody.indexOf('\n');
String strId = nli < 0 ? msgBody : msgBody.substring(0, nli);
CommandRecord cr = null;
try {
long id = Long.parseUnsignedLong(strId, 16);
hfLog.trace("Received command with id " + id);
cr = this.cmdMap.get(id);
// We comment this out because we can hit this because a delayed command can arrive
// after the client-side has timed-out or completed the command.
// log.loggedAssert(cr != null, "Srv: Incoming UNEXPECTED/FORGOTTEN cmcdId: " +
if (cr != null) {
log.loggedAssert(cr.cmdRecord.msgType.equals(msgType), "cmd msgType mismatch #C1IH");
// assertEquals(mr.msgBody, msgBody);
log.loggedAssert(cr.cmdRecord.msgBody.equals(msgBody), "cmd msgBody mismatch #NmLj");
// assertFalse(mr.alwaysDrop);
log.loggedAssert(!cr.cmdRecord.alwaysDrop, "cmd alwaysDrop is true #2p0r");
}
} catch (Exception e) {
logException(e, "#dD6h");
fail("Exception attempting to parse ID from received message [" + msgBody + "]");
}
return cr;
}
protected void processCompletedCommand(SentCommand cCmd) {
// Extract id from message.
// Look it up - we had better find it in our map.
// Verify that we expect to get it - (not alwaysDrop)
// Verify we have not already received it - exactly once completion
// Verify message type and message body is what we expect.
// If all ok return it.
// If it has been canceled by the client (that's us!) we do nothing.
if (cCmd.status() == COMMAND_STATUS.STATUS_CLIENT_CANCELED) {
return;
}
if (cCmd.status() == COMMAND_STATUS.STATUS_REMOTE_REJECTED) {
hfLog.trace("Command REJECTED with CmdId " + cCmd.cmdId());
return;
}
String msgType = cCmd.respType();
String msgBody = cCmd.response();
if (msgBody == null) {
System.err.println("MSGBODY IS NULL!!!!");
;
}
int nli = msgBody.indexOf('\n');
String strId = nli < 0 ? msgBody : msgBody.substring(0, nli);
CommandRecord cr = null;
try {
long id = Long.parseUnsignedLong(strId, 16);
hfLog.trace("Command completed with id " + id);
cr = this.cmdMap.get(id);
// assertNotEquals(mr, null);
log.loggedAssert(cr != null, "cr == null");
// assertEquals(mr.msgType, msgType);
log.loggedAssert(cr.respRecord.msgType.equals(msgType), "resp msgType mismatch #8K45");
// assertEquals(mr.msgBody, msgBody);
log.loggedAssert(cr.respRecord.msgBody.equals(msgBody), "resp msgBody mismatch #jPH4");
// assertFalse(mr.alwaysDrop);
log.loggedAssert(!cr.respRecord.alwaysDrop, "resp alwaysDrop is true #TeA8");
hfLog.trace("removing cr with id " + id + "from cmdMap #EwQp");
this.cmdMap.remove(id, cr);
} catch (Exception e) {
logException(e, "#ptzb");
}
}
protected void processCompletedRtCommand(SentCommand cCmd, CommandRecord cr) {
if (cCmd.status() == COMMAND_STATUS.STATUS_ERROR_TIMEOUT) {
hfLog.trace("Command TIMED OUT with CmdId " + cCmd.cmdId());
log.loggedAssert(cCmd.submittedTime() + cr.timeout <= System.currentTimeMillis(), "premature timeout");
this.cmdMap.remove(cr.cmdRecord.id, cr); // Should be O(log(n)), so it's ok all in all.
return;
}
processCompletedCommand(cCmd);
}
private void pruneDroppedCommands(ConcurrentLinkedQueue<CommandRecord> queue) {
final long DROP_TRIGGER = 1000;
// Remember that the message map and queue of dropped messages are concurrently
// modified so sizes are estimates.
long sizeEst = queue.size(); // Warning O(n) operation.
if (sizeEst > DROP_TRIGGER) {
long dropCount = sizeEst / 2;
log.trace("Purging about " + dropCount + " force-dropped commands.");
while (dropCount > 0) {
CommandRecord cr = queue.poll();
if (cr == null) {
break;
}
purgeOneCommand(cr);
dropCount
}
}
}
private void purgeAllDroppedCommands(ConcurrentLinkedQueue<CommandRecord> queue) {
CommandRecord cr;
while ((cr = queue.poll()) != null) {
purgeOneCommand(cr);
}
}
private void purgeOneCommand(CommandRecord cr) {
this.cmdMap.remove(cr.cmdRecord.id, cr); // Should be O(log(n)), so it's ok all in all.
SentCommand sc = cr.sentCmd;
// WARNING - race condition.
// There is a chance that another thread could have in the mean time set this
// to a non-null value, in which case we will not cancel it.
if (sc != null) {
cr.sentCmd.cancel();
}
}
private void finalSubmitCommandValidation() {
// Verify that the count of messages that still remain in our map
// is exactly equal to the number of messages dropped by the transport - i.e.,
// they were never received.
long randomDrops = this.transport.getNumRandomDrops();
long forceDrops = this.transport.getNumForceDrops();
int mapSize = this.cmdMap.size();
log.info("Final COMMAND verification. TSForceDrops: " + forceDrops + " TSRandomDrops: " + randomDrops
+ " PendingCmds: " + mapSize);
List<ChannelStatistics> stats = rc.getChannelStatistics();
for (ChannelStatistics s : stats) {
log.info("CHANNEL_STATS", s.toString());
}
if (mapSize != 0) {
// We will fail this test later, but do some logging here...
int i = 0;
for (CommandRecord cr : cmdMap.values()) {
if (i > 10) {
log.info(".. more cr's missing (not shown)");
break;
}
String mrStr = "missing cr id=" + cr.cmdRecord.id + " cdrop=" + cr.cmdRecord.alwaysDrop;
log.info(mrStr);
i++;
}
}
log.flush();
assertEquals(0, mapSize);
}
// Cleanup our queues and maps so we can do another test
private void cleanup() {
this.msgMap.clear();
this.droppedMsgs.clear();
this.cmdMap.clear();
this.cmdCliSubmitQueue.clear();
this.cmdSvrComputeQueue.clear();
this.droppedCommands.clear();
this.ch.stopReceivingMessages();
this.ch.stopReceivingCommands();
}
public void close() {
this.exPool.shutdownNow();
cleanup();
this.testTimer.cancel();
}
}
@Test
void testBasicSendReceieveMessageTest() throws InterruptedException {
StructuredLogger baseLogger = initStructuredLogger();
RobotComm.DatagramTransport transport = new TestTransport(baseLogger.defaultLog().newLog("TRANS"));
RobotComm rc = new RobotComm(transport, baseLogger.defaultLog());
RobotComm.Address addr = rc.resolveAddress("localhost");
RobotComm.Channel ch = rc.newChannel("testChannel");
ch.bindToRemoteNode(addr);
rc.startListening();
String testMessage = "test message";
ch.startReceivingMessages();
ch.sendMessage("MYTYPE", testMessage);
baseLogger.flush();
RobotComm.ReceivedMessage rm = null;
while (rm == null) {
rm = ch.pollReceivedMessage();
Thread.sleep(0);
}
;
for (RobotComm.ChannelStatistics stats : rc.getChannelStatistics()) {
System.out.println(stats);
}
ch.stopReceivingMessages();
rc.stopListening();
rc.close();
baseLogger.endLogging();
assertTrue(rm != null);
assertEquals(testMessage, rm.message());
}
@Test
void testBasicSendReceieveCommandTest() throws InterruptedException {
StructuredLogger baseLogger = initStructuredLogger();
RobotComm.DatagramTransport transport = new TestTransport(baseLogger.defaultLog().newLog("TRANS"));
RobotComm rc = new RobotComm(transport, baseLogger.defaultLog());
RobotComm.Address addr = rc.resolveAddress("localhost");
RobotComm.Channel ch = rc.newChannel("testChannel");
ch.bindToRemoteNode(addr);
rc.startListening();
final String TEST_COMMAND = "TESTCMD1";
final String TEST_CMDTYPE = "TESTCMDTYPE1";
final String TEST_RESP = "TESTRESP1";
final String TEST_RESPTYPE = "TESTRESPTYPE";
ch.startReceivingCommands();
RobotComm.SentCommand cmd = ch.submitCommand(TEST_CMDTYPE, TEST_COMMAND, true); // true == queue completion
baseLogger.flush();
assertEquals(TEST_CMDTYPE, cmd.cmdType());
assertEquals(TEST_COMMAND, cmd.command());
RobotComm.ReceivedCommand rcom = null;
while (rcom == null) {
rc.periodicWork();
rcom = ch.pollReceivedCommand();
Thread.sleep(1000);
}
// Got a commend, let's process it and turn a response.
assertEquals(TEST_CMDTYPE, rcom.msgType());
assertEquals(TEST_COMMAND, rcom.message());
rcom.respond(TEST_RESPTYPE, TEST_RESP);
;
// Let's wait for the commend to be completed.
while (cmd.status() != SentCommand.COMMAND_STATUS.STATUS_COMPLETED) {
Thread.sleep(1000);
rc.periodicWork();
}
assertEquals(TEST_RESPTYPE, cmd.respType());
assertEquals(TEST_RESP, cmd.response());
RobotComm.SentCommand cmd1 = ch.pollCompletedCommand();
assertEquals(cmd, cmd1); // We should also pick it up from the completion queue.
for (RobotComm.ChannelStatistics stats : rc.getChannelStatistics()) {
System.out.println(stats);
}
ch.stopReceivingMessages();
rc.stopListening();
rc.close();
baseLogger.endLogging();
}
StructuredLogger initStructuredLogger() {
File logfile = new File("G:\\KUMBH\\Projects\\ihs\\robotics\\temp\\log.txt");
StructuredLogger.Filter f1 = (ln, p, cat) -> {
return ln.equals("test.TRANS") || ln.equals("test.HFLOG") ? false : true;
};
StructuredLogger.Filter f2 = (ln, p, cat) -> {
return ln.equals("test.TRANS") ? false : true;
};
StructuredLogger.Filter f = f1;
StructuredLogger.RawLogger rl = StructuredLogger.createFileRawLogger(logfile, 1000000, f);
StructuredLogger.RawLogger rl2 = StructuredLogger.createConsoleRawLogger(f);
StructuredLogger.RawLogger[] rls = { rl, rl2 };
StructuredLogger sl = new StructuredLogger(rls, "test");
sl.setAsseretionFailureHandler((s) -> {
this.assertionFailure = true;
this.assertionFailureString = s;
});
sl.beginLogging();
sl.info("INIT LOGGER");
return sl;
}
@Test
// Sends a single message with no failures or delays; single thread
void stressSendAndRecvMessagesTrivial() {
final int nThreads = 1;
final int nMessages = 1;
final int messageRate = 10000;
final double dropRate = 0;
final double transportFailureRate = 0;
final int maxTransportDelay = 0;
StructuredLogger baseLogger = initStructuredLogger();
TestTransport transport = new TestTransport(baseLogger.defaultLog().newLog("TRANS"));
StressTester stresser = new StressTester(nThreads, transport, baseLogger.defaultLog());
stresser.init();
transport.setTransportCharacteristics(transportFailureRate, maxTransportDelay);
stresser.submitMessages(nMessages, messageRate, dropRate);
stresser.close();
baseLogger.flush();
baseLogger.endLogging();
}
@Test
// Sends 1000 messages with delays and drops; 10 threads
void stressSendAndRecvMessagesShort() {
final int nThreads = 10;
final int nMessages = 1000;
final int messageRate = 10000;
final double dropRate = 0.1;
final double transportFailureRate = 0.1;
final int maxTransportDelay = 250;
StructuredLogger baseLogger = initStructuredLogger();
TestTransport transport = new TestTransport(baseLogger.defaultLog().newLog("TRANS"));
StressTester stresser = new StressTester(nThreads, transport, baseLogger.defaultLog());
stresser.init();
transport.setTransportCharacteristics(transportFailureRate, maxTransportDelay);
stresser.submitMessages(nMessages, messageRate, dropRate);
stresser.close();
baseLogger.flush();
baseLogger.endLogging();
}
@Test
// Sends 1 million messages, takes about 10 seconds to run; 10 threads
void stressSendAndRecvMessagesMedium() {
final int nThreads = 10;
final double dropRate = 0.1;
final int nMessages = 1000000;
final int messageRate = 100000;
final double transportFailureRate = 0.1;
final int maxTransportDelay = 1500;
StructuredLogger baseLogger = initStructuredLogger();
TestTransport transport = new TestTransport(baseLogger.defaultLog().newLog("TRANS"));
StressTester stresser = new StressTester(nThreads, transport, baseLogger.defaultLog());
stresser.init();
transport.setTransportCharacteristics(transportFailureRate, maxTransportDelay);
stresser.submitMessages(nMessages, messageRate, dropRate);
stresser.close();
baseLogger.flush();
baseLogger.endLogging();
}
@Test
void stressSubmitAndProcessCommandsTrivial() {
final int nThreads = 1;
final int nCommands = 1;
final double rtFrac = 0;
final int commandRate = 50000;
final double dropCommandRate = 0;
final double dropResponseRate = 0;
final int maxComputeTime = 0;
final double transportFailureRate = 0;
final int maxTransportDelay = 0;
StructuredLogger baseLogger = initStructuredLogger();
TestTransport transport = new TestTransport(baseLogger.defaultLog().newLog("TRANS"));
StressTester stresser = new StressTester(nThreads, transport, baseLogger.defaultLog());
stresser.init();
transport.setTransportCharacteristics(transportFailureRate, maxTransportDelay);
stresser.submitCommands(nCommands, rtFrac, commandRate, dropCommandRate, dropResponseRate, maxComputeTime);
stresser.close();
baseLogger.flush();
baseLogger.endLogging();
}
@Test
void stressSubmitAndProcessNonRtCommands() {
final int nThreads = 10;
final int nCommands = 100000;
final double rtFrac = 0;
final int commandRate = 50000;
final double dropCommandRate = 0.01;
final double dropResponseRate = 0.01;
final int maxComputeTime = 100;
final double transportFailureRate = 0.1;
final int maxTransportDelay = 200;
StructuredLogger baseLogger = initStructuredLogger();
TestTransport transport = new TestTransport(baseLogger.defaultLog().newLog("TRANS"));
StressTester stresser = new StressTester(nThreads, transport, baseLogger.defaultLog());
stresser.init();
transport.setTransportCharacteristics(transportFailureRate, maxTransportDelay);
stresser.submitCommands(nCommands, rtFrac, commandRate, dropCommandRate, dropResponseRate, maxComputeTime);
stresser.close();
baseLogger.flush();
baseLogger.endLogging();
}
// Sends purely RT commands.
@Test
void stressSubmitAndProcessOnlyRtCommands() {
final int nThreads = 10;
final int nCommands = 100000;
final double rtFrac = 1;
final int commandRate = 50000;
final double dropCommandRate = 0.01;
final double dropResponseRate = 0.01;
final int maxComputeTime = 100;
final double transportFailureRate = 0.1;
final int maxTransportDelay = 200;
StructuredLogger baseLogger = initStructuredLogger();
TestTransport transport = new TestTransport(baseLogger.defaultLog().newLog("TRANS"));
StressTester stresser = new StressTester(nThreads, transport, baseLogger.defaultLog());
stresser.init();
transport.setTransportCharacteristics(transportFailureRate, maxTransportDelay);
stresser.submitCommands(nCommands, rtFrac, commandRate, dropCommandRate, dropResponseRate, maxComputeTime);
stresser.close();
baseLogger.flush();
baseLogger.endLogging();
}
// Sends purely RT commands.
//@Test
void stressSubmitAndProcessAllCommands() {
final int nThreads = 10;
final int nCommands = 100000;
final double rtFrac = 0.5;
final int commandRate = 50000;
final double dropCommandRate = 0.01;
final double dropResponseRate = 0.01;
final int maxComputeTime = 100;
final double transportFailureRate = 0.1;
final int maxTransportDelay = 200;
StructuredLogger baseLogger = initStructuredLogger();
TestTransport transport = new TestTransport(baseLogger.defaultLog().newLog("TRANS"));
StressTester stresser = new StressTester(nThreads, transport, baseLogger.defaultLog());
stresser.init();
transport.setTransportCharacteristics(transportFailureRate, maxTransportDelay);
stresser.submitCommands(nCommands, rtFrac, commandRate, dropCommandRate, dropResponseRate, maxComputeTime);
stresser.close();
baseLogger.flush();
baseLogger.endLogging();
}
// This one is to mess around with parameters when debugging. Usually disabled.
//@Test
void stressSubmitAndProcessCommandsWorking() {
final int nThreads = 10;
final int nCommands = 2000000;
final double rtFrac = 1;
final int commandRate = 50000;
final double dropCommandRate = 0.01;
final double dropResponseRate = 0.01;
final int maxComputeTime = 0;
final double transportFailureRate = 0.05;
final int maxTransportDelay = 50;
StructuredLogger baseLogger = initStructuredLogger();
TestTransport transport = new TestTransport(baseLogger.defaultLog().newLog("TRANS"));
StressTester stresser = new StressTester(nThreads, transport, baseLogger.defaultLog());
stresser.init();
transport.setTransportCharacteristics(transportFailureRate, maxTransportDelay);
stresser.submitCommands(nCommands, rtFrac, commandRate, dropCommandRate, dropResponseRate, maxComputeTime);
stresser.close();
baseLogger.flush();
baseLogger.endLogging();
}
}
|
package roart.common.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TimeUtil {
private static Logger log = LoggerFactory.getLogger(TimeUtil.class);
public static final String MYDATEFORMAT = "yyyy.MM.dd";
public static Date convertDate(LocalDate date) {
if (date == null) {
log.error("Date null (break point)");
return null;
}
return Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant());
}
public static LocalDate convertDate(String aDate) throws ParseException {
SimpleDateFormat dt = new SimpleDateFormat(MYDATEFORMAT);
return convertDate(dt.parse(aDate));
}
public static LocalDate convertDate(Date date) {
if (date == null) {
log.error("Date null (break point)");
return null;
}
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
public static String convertDate2(LocalDate date) {
if (date == null) {
return null;
}
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd");
return date.format(formatter);
}
public static long daysSince(LocalDate date) {
return ChronoUnit.DAYS.between(date, LocalDate.now());
}
public static Date convertDate(LocalDateTime date) {
return Date.from(date.atZone(ZoneId.systemDefault()).toInstant());
}
public static LocalDateTime convertDate2(Date date) {
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}
public static long daysSince(LocalDateTime date) {
return ChronoUnit.DAYS.between(LocalDate.now(), date);
}
}
|
package org.spine3.server.entity;
import org.spine3.test.entity.Project;
import org.spine3.test.entity.ProjectId;
import org.spine3.test.entity.command.CreateProject;
import static org.spine3.base.Identifiers.newUuid;
class Given {
private Given() {}
static Project newProject() {
final Project.Builder project = Project.newBuilder()
.setId(AggregateId.newProjectId())
.setName("Project-" + newUuid())
.setStatus(Project.Status.CREATED);
return project.build();
}
static class AggregateId {
private AggregateId() {}
static ProjectId newProjectId() {
final String uuid = newUuid();
return ProjectId.newBuilder()
.setId(uuid)
.build();
}
}
static class CommandMessage {
private CommandMessage() {}
static CreateProject createProject() {
return CreateProject.newBuilder()
.setProjectId(AggregateId.newProjectId())
.build();
}
}
/**
* Extracted from {@link org.spine3.server.entity.EntityShould}
*
* @author Mikhail Mikhaylov
*/
static class TestEntity extends Entity<String, Project> {
private boolean isValidateMethodCalled = false;
static TestEntity newInstance(String id) {
return org.spine3.test.Given.entityOfClass(TestEntity.class)
.withId(id)
.build();
}
static TestEntity withState() {
return org.spine3.test.Given.entityOfClass(TestEntity.class)
.withId(newUuid())
.withState(newProject())
.withVersion(3)
.build();
}
static TestEntity withState(TestEntity entity) {
return org.spine3.test.Given.entityOfClass(TestEntity.class)
.withId(entity.getId())
.withState(entity.getState())
.withVersion(entity.getVersion())
.build();
}
private TestEntity(String id) {
super(id);
}
@Override
protected void validate(Project state) throws IllegalStateException {
super.validate(state);
isValidateMethodCalled = true;
}
boolean isValidateMethodCalled() {
return isValidateMethodCalled;
}
}
}
|
package cl.uchile.ing.adi.quicklooklib.items;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.webkit.MimeTypeMap;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import cl.uchile.ing.adi.quicklooklib.ItemFactory;
import cl.uchile.ing.adi.quicklooklib.R;
import cl.uchile.ing.adi.quicklooklib.fragments.QuicklookFragment;
/**
* BaseItem has most of the methods related with items in the library.
*/
public abstract class BaseItem {
public static ArrayList<String> BANNED_NAMES = new ArrayList<>();
public static String ITEM_PATH = "path";
public static String ITEM_TYPE = "type";
public static String ITEM_EXTRA = "extra";
public static String ITEM_MIME = "mime-type";
public static String DOWNLOAD_PATH;
public static String CACHE_PATH;
protected Context context;
protected String type;
protected long size;
protected String path;
protected Bundle extra;
protected QuicklookFragment fragment;
protected int image;
protected String formattedName;
private boolean openable;
protected Intent intent;
private String mime;
/**
* Constructor of the class, metadata is inserted manually.
* @param path path of file (it should exist)
* @param type type of file
* @param size size of file
* @param extra extras introduced by bundle.
*/
public BaseItem(String path, String type, long size, Bundle extra, Context context) {
this.setContext(context);
this.path = path;
this.size = size;
this.type = type;
this.extra = extra;
//Image for item.
this.image = R.drawable.document;
//Formatted name for item
this.formattedName = getContext().getString(R.string.items_default_formatted_name);
// check if openable
this.mime = extra.getString("mime-type");
if(this.mime == null) this.mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(type);
if(this.mime == null) this.mime = "text/plain";
PackageManager manager = getContext().getPackageManager();
Intent i = new Intent( Intent.ACTION_VIEW );
// workaround para apps nativas y archivos que no existen todavia
try {
i.setDataAndType(FileProvider.getUriForFile(
context,
context.getApplicationContext().getPackageName() + ".fileprovider",
new File(path)
), this.mime);
} catch( IllegalArgumentException e ) {
i.setDataAndType( Uri.parse( path ), this.mime );
}
i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
this.setItemIntent(i);
ResolveInfo r = manager.resolveActivity(i, PackageManager.MATCH_DEFAULT_ONLY);
this.openable = r != null;
}
/**
* Helper class. Obtains the id of a file using the path.
* @param path path of file
* @return id of file
*/
public static String getNameFromPath(String path) {
String[] splitPath = path.split("/");
return splitPath[splitPath.length-1];
}
/**
* Uses Java Files API and obtains size of file.
*/
public static long getSizeFromPath(String path) {
File file = new File(path);
return file.length();
}
/**
* Prepares the fragment if it's not prepared and returns it
* @return the Fragment.
*/
public QuicklookFragment getFragment() {
prepareFragment();
return fragment;
}
public void prepareFragment() {
Bundle b = new Bundle();
b.putString(ITEM_PATH,this.getPath());
b.putString(ITEM_TYPE, this.getType());
b.putBundle(ITEM_EXTRA, this.getExtra());
fragment.setArguments(b);
}
/**
* Returns the name of file.
* @return the name of file.
*/
public String getName() {
return getNameFromPath(this.path);
}
/**
* Returns the path of file.
* @return the path of file.
*/
public String getType() {
return this.type;
}
/**
* Returns the size of file.
* @return the size of file.
*/
public long getSize() {
return this.size;
}
/**
* Returns the path of file.
* @return the path of file.
*/
public String getPath() {
return this.path;
}
/**
* Each implementation defines a image for its item.
* @return the resource id of the image.
*/
public int getImage() {
return this.image;
}
/**
* Returns human-readable string with file type.
* @return String with file type.
*/
public String getFormattedType() {
return this.formattedName;
}
public Bundle getExtra() {
return this.extra;
}
/**
* Returns human-readable expression of file size
* @return Strinw with file size
*/
public String getFormattedSize() {
//Folder case
if (size==-1) return "";
String[] suffixes = {"Bytes","KiB", "MiB", "GiB", "TiB"};
long countSize = size;
int i;
for (i = 0; countSize>1024 && i<suffixes.length; i++) {
countSize/=1024;
}
return ""+countSize+" "+suffixes[i];
}
/**
* @param path path of file
* @return String representing extension of file
*/
public static String loadType(String path) {
String extension = getExtension(getNameFromPath(path.replace(" ", "_")));
if (extension == null) {
return ItemFactory.DEFAULT_MIMETYPE;
} else {
return extension;
}
}
/**
* Returns extension of a path
* @param file filepath
* @return extension
*/
public static String getExtension(String file) {
String[] parts = file.split("\\.");
int len = parts.length;
if (len == 0) {
return null;
}
return parts[len-1];
}
/**
* For debug purposes
* @return String
*/
public String toString() {
return "Item:"+
"\nName: "+getName()+
"\nType: "+getType()+
"\nPath: "+getPath()+
"\nSize: "+getFormattedSize()+"\n";
}
/**
* Sets size value
* @param size size of item
*/
public void setSize(long size) {
this.size = size;
}
/**
* Sets the title for activity when item is shown.
* @return String with title
*/
public String getTitle() {
return this.getName();
}
/** Sets the subtitle for activity when item is shown.
* @return String with subtitle
*/
public String getSubTitle() {
return this.getFormattedType();
}
/**
* Adds a banned word to banned word list.
* @param banned banned word
*/
public static void addBannedWord(String banned) {
BANNED_NAMES.add(banned);
}
/**
* Checks if a word is a banned word.
* @param banned word we want to check
* @return true if the word is a banned word
*/
public static boolean isBannedWord(String banned) {
return BANNED_NAMES.contains(banned);
}
/**
* Returns the download path of files.
* @return download path of files.
*/
public static String getDownloadPath() {
return DOWNLOAD_PATH;
}
/**
* Sets the download path.
* @param dp new download path
*/
public static void setDownloadPath(String dp) {
DOWNLOAD_PATH = dp;
}
/**
* Returns the download cache of files.
* @return cache path of files
*/
public static String getCachePath() {
return CACHE_PATH;
}
/**
* Sets the cache path.
* @param cp new cache path.
*/
public static void setCachePath(String cp) {
CACHE_PATH = cp;
}
/**
* Copies an item on internal space to download folder.
* @return Path of item on downloads folder.
*/
public String copyItem(String mime) {
try {
String itemPath = BaseItem.getDownloadPath()+getName();
File f = new File(itemPath);
int copied;
if (!f.exists()) {
FileOutputStream fos = new FileOutputStream(itemPath);
copied = IOUtils.copy(new FileInputStream(getPath()), fos);
fos.close();
if(copied<=0) {
return null;
}
}
return itemPath;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public void setContext(Context c) {
if(c==null) return;
context = c;
}
public Context getContext() {
return context;
}
public boolean isOpenable() {
return this.openable;
}
/**
* Returns the path of file.
* @return the path of file.
*/
public String getMime() {
return this.mime;
}
public void setFragment(QuicklookFragment fragment) {
this.fragment = fragment;
}
/**
* Default behaviour allows QuicklookActivity to show a generic Progress dialog between
* transitions. Override if you do not want automatic Progress dialogs or you want to
* show one of your own.
*
* @return true if you want to avoid automatic Progress dialog. false to allow Quicklook to
* show one.
*/
public boolean willShowOwnProgress(){return false;}
/**
* This allows Quicklook to show or hide options menu with "Open", "share" and "save" options.
* @return true if you want to show options menu
*/
public boolean willShowOptionsMenu(){return true;}
/**
* this allows Quicklook to open with its own logic some elements.
* Return false if you want to open with an external app instead
* @return true if you want to show the element with quicklook fragments.
*/
public boolean openAsDefault(){return false;}
// Button item functions
public Uri save() {
String mime = this.getMime();
String newPath = this.copyItem(mime);
Uri pathUri = Uri.parse("file://" + newPath);
return pathUri;
}
public Intent getItemIntent() {
return intent;
}
public void setItemIntent(Intent intent) {
this.intent = intent;
}
}
|
package com.facebook.react.uimanager;
import android.content.res.Resources;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.util.SparseIntArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.PopupMenu;
import androidx.annotation.Nullable;
import com.facebook.common.logging.FLog;
import com.facebook.react.R;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.SoftAssertions;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.config.ReactFeatureFlags;
import com.facebook.react.touch.JSResponderHandler;
import com.facebook.react.uimanager.layoutanimation.LayoutAnimationController;
import com.facebook.react.uimanager.layoutanimation.LayoutAnimationListener;
import com.facebook.systrace.Systrace;
import com.facebook.systrace.SystraceMessage;
import java.util.Arrays;
import javax.annotation.concurrent.NotThreadSafe;
/**
* Delegate of {@link UIManagerModule} that owns the native view hierarchy and mapping between
* native view names used in JS and corresponding instances of {@link ViewManager}. The {@link
* UIManagerModule} communicates with this class by it's public interface methods:
*
* <ul>
* <li>{@link #updateProperties}
* <li>{@link #updateLayout}
* <li>{@link #createView}
* <li>{@link #manageChildren}
* </ul>
*
* executing all the scheduled UI operations at the end of JS batch.
*
* <p>NB: All native view management methods listed above must be called from the UI thread.
*
* <p>The {@link ReactContext} instance that is passed to views that this manager creates differs
* from the one that we pass as a constructor. Instead we wrap the provided instance of {@link
* ReactContext} in an instance of {@link ThemedReactContext} that additionally provide a correct
* theme based on the root view for a view tree that we attach newly created view to. Therefore this
* view manager will create a copy of {@link ThemedReactContext} that wraps the instance of {@link
* ReactContext} for each root view added to the manager (see {@link #addRootView}).
*
* <p>TODO(5483031): Only dispatch updates when shadow views have changed
*/
@NotThreadSafe
public class NativeViewHierarchyManager {
private static final String TAG = NativeViewHierarchyManager.class.getSimpleName();
private final SparseArray<View> mTagsToViews;
private final SparseArray<ViewManager> mTagsToViewManagers;
private final SparseBooleanArray mRootTags;
private final ViewManagerRegistry mViewManagers;
private final JSResponderHandler mJSResponderHandler = new JSResponderHandler();
private final RootViewManager mRootViewManager;
private final LayoutAnimationController mLayoutAnimator = new LayoutAnimationController();
private final SparseArray<SparseIntArray> mTagsToPendingIndicesToDelete = new SparseArray<>();
private final int[] mDroppedViewArray = new int[100];
private final RectF mBoundingBox = new RectF();
private boolean mLayoutAnimationEnabled;
private PopupMenu mPopupMenu;
private int mDroppedViewIndex = 0;
public NativeViewHierarchyManager(ViewManagerRegistry viewManagers) {
this(viewManagers, new RootViewManager());
}
public NativeViewHierarchyManager(ViewManagerRegistry viewManagers, RootViewManager manager) {
mViewManagers = viewManagers;
mTagsToViews = new SparseArray<>();
mTagsToViewManagers = new SparseArray<>();
mRootTags = new SparseBooleanArray();
mRootViewManager = manager;
}
public final synchronized View resolveView(int tag) {
View view = mTagsToViews.get(tag);
if (view == null) {
throw new IllegalViewOperationException(
"Trying to resolve view with tag " + tag + " which doesn't exist");
}
return view;
}
public final synchronized ViewManager resolveViewManager(int tag) {
ViewManager viewManager = mTagsToViewManagers.get(tag);
if (viewManager == null) {
boolean alreadyDropped = Arrays.asList(mDroppedViewArray).contains(tag);
throw new IllegalViewOperationException(
"ViewManager for tag "
+ tag
+ " could not be found.\n View already dropped? "
+ alreadyDropped
+ ".\nLast index "
+ mDroppedViewIndex
+ " in last 100 views"
+ mDroppedViewArray.toString());
}
return viewManager;
}
public void setLayoutAnimationEnabled(boolean enabled) {
mLayoutAnimationEnabled = enabled;
}
public synchronized void updateInstanceHandle(int tag, long instanceHandle) {
UiThreadUtil.assertOnUiThread();
try {
updateInstanceHandle(resolveView(tag), instanceHandle);
} catch (IllegalViewOperationException e) {
FLog.e(TAG, "Unable to update properties for view tag " + tag, e);
}
}
public synchronized void updateProperties(int tag, ReactStylesDiffMap props) {
UiThreadUtil.assertOnUiThread();
try {
ViewManager viewManager = resolveViewManager(tag);
View viewToUpdate = resolveView(tag);
if (props != null) {
viewManager.updateProperties(viewToUpdate, props);
}
} catch (IllegalViewOperationException e) {
FLog.e(TAG, "Unable to update properties for view tag " + tag, e);
}
}
public synchronized void updateViewExtraData(int tag, Object extraData) {
UiThreadUtil.assertOnUiThread();
ViewManager viewManager = resolveViewManager(tag);
View viewToUpdate = resolveView(tag);
viewManager.updateExtraData(viewToUpdate, extraData);
}
public synchronized void updateLayout(
int parentTag, int tag, int x, int y, int width, int height) {
UiThreadUtil.assertOnUiThread();
SystraceMessage.beginSection(
Systrace.TRACE_TAG_REACT_VIEW, "NativeViewHierarchyManager_updateLayout")
.arg("parentTag", parentTag)
.arg("tag", tag)
.flush();
try {
View viewToUpdate = resolveView(tag);
// Even though we have exact dimensions, we still call measure because some platform views
// Switch) assume that method will always be called before onLayout and onDraw. They use it to
// calculate and cache information used in the draw pass. For most views, onMeasure can be
// stubbed out to only call setMeasuredDimensions. For ViewGroups, onLayout should be stubbed
// out to not recursively call layout on its children: React Native already handles doing
// that.
// Also, note measure and layout need to be called *after* all View properties have been
// updated
// because of caching and calculation that may occur in onMeasure and onLayout. Layout
// operations should also follow the native view hierarchy and go top to bottom for
// consistency
// with standard layout passes (some views may depend on this).
viewToUpdate.measure(
View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY));
// We update the layout of the ReactRootView when there is a change in the layout of its
// child.
// This is required to re-measure the size of the native View container (usually a
// FrameLayout) that is configured with layout_height = WRAP_CONTENT or layout_width =
// WRAP_CONTENT
// This code is going to be executed ONLY when there is a change in the size of the Root
// View defined in the js side. Changes in the layout of inner views will not trigger an
// update
// on the layout of the Root View.
ViewParent parent = viewToUpdate.getParent();
if (parent instanceof RootView) {
parent.requestLayout();
}
// Check if the parent of the view has to layout the view, or the child has to lay itself out.
if (!mRootTags.get(parentTag)) {
ViewManager parentViewManager = mTagsToViewManagers.get(parentTag);
IViewManagerWithChildren parentViewManagerWithChildren;
if (parentViewManager instanceof IViewManagerWithChildren) {
parentViewManagerWithChildren = (IViewManagerWithChildren) parentViewManager;
} else {
throw new IllegalViewOperationException(
"Trying to use view with tag "
+ parentTag
+ " as a parent, but its Manager doesn't implement IViewManagerWithChildren");
}
if (parentViewManagerWithChildren != null
&& !parentViewManagerWithChildren.needsCustomLayoutForChildren()) {
updateLayout(viewToUpdate, x, y, width, height);
}
} else {
updateLayout(viewToUpdate, x, y, width, height);
}
} finally {
Systrace.endSection(Systrace.TRACE_TAG_REACT_VIEW);
}
}
private void updateInstanceHandle(View viewToUpdate, long instanceHandle) {
UiThreadUtil.assertOnUiThread();
viewToUpdate.setTag(R.id.view_tag_instance_handle, instanceHandle);
}
@Nullable
public long getInstanceHandle(int reactTag) {
View view = mTagsToViews.get(reactTag);
if (view == null) {
throw new IllegalViewOperationException("Unable to find view for tag: " + reactTag);
}
Long instanceHandle = (Long) view.getTag(R.id.view_tag_instance_handle);
if (instanceHandle == null) {
throw new IllegalViewOperationException("Unable to find instanceHandle for tag: " + reactTag);
}
return instanceHandle;
}
private void updateLayout(View viewToUpdate, int x, int y, int width, int height) {
if (mLayoutAnimationEnabled && mLayoutAnimator.shouldAnimateLayout(viewToUpdate)) {
mLayoutAnimator.applyLayoutUpdate(viewToUpdate, x, y, width, height);
} else {
viewToUpdate.layout(x, y, x + width, y + height);
}
}
public synchronized void createView(
ThemedReactContext themedContext,
int tag,
String className,
@Nullable ReactStylesDiffMap initialProps) {
UiThreadUtil.assertOnUiThread();
SystraceMessage.beginSection(
Systrace.TRACE_TAG_REACT_VIEW, "NativeViewHierarchyManager_createView")
.arg("tag", tag)
.arg("className", className)
.flush();
try {
ViewManager viewManager = mViewManagers.get(className);
View view = viewManager.createView(themedContext, null, null, mJSResponderHandler);
mTagsToViews.put(tag, view);
mTagsToViewManagers.put(tag, viewManager);
// Use android View id field to store React tag. This is possible since we don't inflate
// React views from layout xmls. Thus it is easier to just reuse that field instead of
// creating another (potentially much more expensive) mapping from view to React tag
view.setId(tag);
if (initialProps != null) {
viewManager.updateProperties(view, initialProps);
}
} finally {
Systrace.endSection(Systrace.TRACE_TAG_REACT_VIEW);
}
}
private static String constructManageChildrenErrorMessage(
ViewGroup viewToManage,
ViewGroupManager viewManager,
@Nullable int[] indicesToRemove,
@Nullable ViewAtIndex[] viewsToAdd,
@Nullable int[] tagsToDelete) {
StringBuilder stringBuilder = new StringBuilder();
if (null != viewToManage) {
stringBuilder.append("View tag:" + viewToManage.getId() + "\n");
stringBuilder.append(" children(" + viewManager.getChildCount(viewToManage) + "): [\n");
for (int index = 0; index < viewManager.getChildCount(viewToManage); index += 16) {
for (int innerOffset = 0;
((index + innerOffset) < viewManager.getChildCount(viewToManage)) && innerOffset < 16;
innerOffset++) {
stringBuilder.append(
viewManager.getChildAt(viewToManage, index + innerOffset).getId() + ",");
}
stringBuilder.append("\n");
}
stringBuilder.append(" ],\n");
}
if (indicesToRemove != null) {
stringBuilder.append(" indicesToRemove(" + indicesToRemove.length + "): [\n");
for (int index = 0; index < indicesToRemove.length; index += 16) {
for (int innerOffset = 0;
((index + innerOffset) < indicesToRemove.length) && innerOffset < 16;
innerOffset++) {
stringBuilder.append(indicesToRemove[index + innerOffset] + ",");
}
stringBuilder.append("\n");
}
stringBuilder.append(" ],\n");
}
if (viewsToAdd != null) {
stringBuilder.append(" viewsToAdd(" + viewsToAdd.length + "): [\n");
for (int index = 0; index < viewsToAdd.length; index += 16) {
for (int innerOffset = 0;
((index + innerOffset) < viewsToAdd.length) && innerOffset < 16;
innerOffset++) {
stringBuilder.append(
"["
+ viewsToAdd[index + innerOffset].mIndex
+ ","
+ viewsToAdd[index + innerOffset].mTag
+ "],");
}
stringBuilder.append("\n");
}
stringBuilder.append(" ],\n");
}
if (tagsToDelete != null) {
stringBuilder.append(" tagsToDelete(" + tagsToDelete.length + "): [\n");
for (int index = 0; index < tagsToDelete.length; index += 16) {
for (int innerOffset = 0;
((index + innerOffset) < tagsToDelete.length) && innerOffset < 16;
innerOffset++) {
stringBuilder.append(tagsToDelete[index + innerOffset] + ",");
}
stringBuilder.append("\n");
}
stringBuilder.append(" ]\n");
}
return stringBuilder.toString();
}
/**
* Given an index to action on under synchronous deletes, return an updated index factoring in
* asynchronous deletes (where the async delete operations have not yet been performed)
*/
private int normalizeIndex(int index, SparseIntArray pendingIndices) {
int normalizedIndex = index;
for (int i = 0; i <= index; i++) {
normalizedIndex += pendingIndices.get(i);
}
return normalizedIndex;
}
/**
* Given React tag, return sparse array of direct child indices that are pending deletion (due to
* async view deletion)
*/
private SparseIntArray getOrCreatePendingIndicesToDelete(int tag) {
SparseIntArray pendingIndicesToDelete = mTagsToPendingIndicesToDelete.get(tag);
if (pendingIndicesToDelete == null) {
pendingIndicesToDelete = new SparseIntArray();
mTagsToPendingIndicesToDelete.put(tag, pendingIndicesToDelete);
}
return pendingIndicesToDelete;
}
/**
* @param tag react tag of the node we want to manage
* @param indicesToRemove ordered (asc) list of indicies at which view should be removed
* @param viewsToAdd ordered (asc based on mIndex property) list of tag-index pairs that represent
* a view which should be added at the specified index
* @param tagsToDelete list of tags corresponding to views that should be removed
* @param indicesToDelete parallel list to tagsToDelete, list of indices of those tags
*/
public synchronized void manageChildren(
int tag,
@Nullable int[] indicesToRemove,
@Nullable ViewAtIndex[] viewsToAdd,
@Nullable int[] tagsToDelete,
@Nullable int[] indicesToDelete) {
UiThreadUtil.assertOnUiThread();
final SparseIntArray pendingIndicesToDelete = getOrCreatePendingIndicesToDelete(tag);
final ViewGroup viewToManage = (ViewGroup) mTagsToViews.get(tag);
final ViewGroupManager viewManager = (ViewGroupManager) resolveViewManager(tag);
if (viewToManage == null) {
throw new IllegalViewOperationException(
"Trying to manageChildren view with tag "
+ tag
+ " which doesn't exist\n detail: "
+ constructManageChildrenErrorMessage(
viewToManage, viewManager, indicesToRemove, viewsToAdd, tagsToDelete));
}
int lastIndexToRemove = viewManager.getChildCount(viewToManage);
if (indicesToRemove != null) {
for (int i = indicesToRemove.length - 1; i >= 0; i
int indexToRemove = indicesToRemove[i];
if (indexToRemove < 0) {
throw new IllegalViewOperationException(
"Trying to remove a negative view index:"
+ indexToRemove
+ " view tag: "
+ tag
+ "\n detail: "
+ constructManageChildrenErrorMessage(
viewToManage, viewManager, indicesToRemove, viewsToAdd, tagsToDelete));
}
if (indexToRemove >= viewManager.getChildCount(viewToManage)) {
if (mRootTags.get(tag) && viewManager.getChildCount(viewToManage) == 0) {
// This root node has already been removed (likely due to a threading issue caused by
// async js execution). Ignore this root removal.
return;
}
throw new IllegalViewOperationException(
"Trying to remove a view index above child "
+ "count "
+ indexToRemove
+ " view tag: "
+ tag
+ "\n detail: "
+ constructManageChildrenErrorMessage(
viewToManage, viewManager, indicesToRemove, viewsToAdd, tagsToDelete));
}
if (indexToRemove >= lastIndexToRemove) {
throw new IllegalViewOperationException(
"Trying to remove an out of order view index:"
+ indexToRemove
+ " view tag: "
+ tag
+ "\n detail: "
+ constructManageChildrenErrorMessage(
viewToManage, viewManager, indicesToRemove, viewsToAdd, tagsToDelete));
}
int normalizedIndexToRemove = normalizeIndex(indexToRemove, pendingIndicesToDelete);
View viewToRemove = viewManager.getChildAt(viewToManage, normalizedIndexToRemove);
if (mLayoutAnimationEnabled
&& mLayoutAnimator.shouldAnimateLayout(viewToRemove)
&& arrayContains(tagsToDelete, viewToRemove.getId())) {
// The view will be removed and dropped by the 'delete' layout animation
// instead, so do nothing
} else {
viewManager.removeViewAt(viewToManage, normalizedIndexToRemove);
}
lastIndexToRemove = indexToRemove;
}
}
if (tagsToDelete != null) {
for (int i = 0; i < tagsToDelete.length; i++) {
int tagToDelete = tagsToDelete[i];
final int indexToDelete = indicesToDelete[i];
final View viewToDestroy = mTagsToViews.get(tagToDelete);
if (viewToDestroy == null) {
throw new IllegalViewOperationException(
"Trying to destroy unknown view tag: "
+ tagToDelete
+ "\n detail: "
+ constructManageChildrenErrorMessage(
viewToManage, viewManager, indicesToRemove, viewsToAdd, tagsToDelete));
}
if (mLayoutAnimationEnabled && mLayoutAnimator.shouldAnimateLayout(viewToDestroy)) {
int updatedCount = pendingIndicesToDelete.get(indexToDelete, 0) + 1;
pendingIndicesToDelete.put(indexToDelete, updatedCount);
mLayoutAnimator.deleteView(
viewToDestroy,
new LayoutAnimationListener() {
@Override
public void onAnimationEnd() {
viewManager.removeView(viewToManage, viewToDestroy);
dropView(viewToDestroy);
int count = pendingIndicesToDelete.get(indexToDelete, 0);
pendingIndicesToDelete.put(indexToDelete, Math.max(0, count - 1));
}
});
} else {
dropView(viewToDestroy);
}
}
}
if (viewsToAdd != null) {
for (int i = 0; i < viewsToAdd.length; i++) {
ViewAtIndex viewAtIndex = viewsToAdd[i];
View viewToAdd = mTagsToViews.get(viewAtIndex.mTag);
if (viewToAdd == null) {
throw new IllegalViewOperationException(
"Trying to add unknown view tag: "
+ viewAtIndex.mTag
+ "\n detail: "
+ constructManageChildrenErrorMessage(
viewToManage, viewManager, indicesToRemove, viewsToAdd, tagsToDelete));
}
int normalizedIndexToAdd = normalizeIndex(viewAtIndex.mIndex, pendingIndicesToDelete);
viewManager.addView(viewToManage, viewToAdd, normalizedIndexToAdd);
}
}
}
private boolean arrayContains(@Nullable int[] array, int ele) {
if (array == null) {
return false;
}
for (int curEle : array) {
if (curEle == ele) {
return true;
}
}
return false;
}
/**
* Simplified version of constructManageChildrenErrorMessage that only deals with adding children
* views
*/
private static String constructSetChildrenErrorMessage(
ViewGroup viewToManage, ViewGroupManager viewManager, ReadableArray childrenTags) {
ViewAtIndex[] viewsToAdd = new ViewAtIndex[childrenTags.size()];
for (int i = 0; i < childrenTags.size(); i++) {
viewsToAdd[i] = new ViewAtIndex(childrenTags.getInt(i), i);
}
return constructManageChildrenErrorMessage(viewToManage, viewManager, null, viewsToAdd, null);
}
/** Simplified version of manageChildren that only deals with adding children views */
public synchronized void setChildren(int tag, ReadableArray childrenTags) {
UiThreadUtil.assertOnUiThread();
ViewGroup viewToManage = (ViewGroup) mTagsToViews.get(tag);
ViewGroupManager viewManager = (ViewGroupManager) resolveViewManager(tag);
for (int i = 0; i < childrenTags.size(); i++) {
View viewToAdd = mTagsToViews.get(childrenTags.getInt(i));
if (viewToAdd == null) {
throw new IllegalViewOperationException(
"Trying to add unknown view tag: "
+ childrenTags.getInt(i)
+ "\n detail: "
+ constructSetChildrenErrorMessage(viewToManage, viewManager, childrenTags));
}
viewManager.addView(viewToManage, viewToAdd, i);
}
}
/** See {@link UIManagerModule#addRootView}. */
public synchronized void addRootView(int tag, View view) {
addRootViewGroup(tag, view);
}
protected final synchronized void addRootViewGroup(int tag, View view) {
if (view.getId() != View.NO_ID) {
FLog.e(
TAG,
"Trying to add a root view with an explicit id ("
+ view.getId()
+ ") already "
+ "set. React Native uses the id field to track react tags and will overwrite this field. "
+ "If that is fine, explicitly overwrite the id field to View.NO_ID before calling "
+ "addRootView.");
}
mTagsToViews.put(tag, view);
mTagsToViewManagers.put(tag, mRootViewManager);
mRootTags.put(tag, true);
view.setId(tag);
}
private void cacheDroppedTag(int tag) {
mDroppedViewArray[mDroppedViewIndex] = tag;
mDroppedViewIndex = (mDroppedViewIndex + 1) % 100;
}
/** Releases all references to given native View. */
protected synchronized void dropView(View view) {
UiThreadUtil.assertOnUiThread();
if (view == null) {
// Ignore this drop operation when view is null.
return;
}
if (ReactFeatureFlags.logDroppedViews) {
cacheDroppedTag(view.getId());
}
if (mTagsToViewManagers.get(view.getId()) == null) {
// This view has already been dropped (likely due to a threading issue caused by async js
// execution). Ignore this drop operation.
return;
}
if (!mRootTags.get(view.getId())) {
// For non-root views we notify viewmanager with {@link ViewManager#onDropInstance}
resolveViewManager(view.getId()).onDropViewInstance(view);
}
ViewManager viewManager = mTagsToViewManagers.get(view.getId());
if (view instanceof ViewGroup && viewManager instanceof ViewGroupManager) {
ViewGroup viewGroup = (ViewGroup) view;
ViewGroupManager viewGroupManager = (ViewGroupManager) viewManager;
for (int i = viewGroupManager.getChildCount(viewGroup) - 1; i >= 0; i
View child = viewGroupManager.getChildAt(viewGroup, i);
if (child == null) {
FLog.e(TAG, "Unable to drop null child view");
} else if (mTagsToViews.get(child.getId()) != null) {
dropView(child);
}
}
viewGroupManager.removeAllViews(viewGroup);
}
mTagsToPendingIndicesToDelete.remove(view.getId());
mTagsToViews.remove(view.getId());
mTagsToViewManagers.remove(view.getId());
}
public synchronized void removeRootView(int rootViewTag) {
UiThreadUtil.assertOnUiThread();
if (!mRootTags.get(rootViewTag)) {
SoftAssertions.assertUnreachable(
"View with tag " + rootViewTag + " is not registered as a root view");
}
View rootView = mTagsToViews.get(rootViewTag);
dropView(rootView);
mRootTags.delete(rootViewTag);
}
/**
* Returns true on success, false on failure. If successful, after calling, output buffer will be
* {x, y, width, height}.
*/
public synchronized void measure(int tag, int[] outputBuffer) {
UiThreadUtil.assertOnUiThread();
View v = mTagsToViews.get(tag);
if (v == null) {
throw new NoSuchNativeViewException("No native view for " + tag + " currently exists");
}
View rootView = (View) RootViewUtil.getRootView(v);
// It is possible that the RootView can't be found because this view is no longer on the screen
// and has been removed by clipping
if (rootView == null) {
throw new NoSuchNativeViewException("Native view " + tag + " is no longer on screen");
}
computeBoundingBox(rootView, outputBuffer);
int rootX = outputBuffer[0];
int rootY = outputBuffer[1];
computeBoundingBox(v, outputBuffer);
outputBuffer[0] -= rootX;
outputBuffer[1] -= rootY;
}
private void computeBoundingBox(View view, int[] outputBuffer) {
mBoundingBox.set(0, 0, view.getWidth(), view.getHeight());
mapRectFromViewToWindowCoords(view, mBoundingBox);
outputBuffer[0] = Math.round(mBoundingBox.left);
outputBuffer[1] = Math.round(mBoundingBox.top);
outputBuffer[2] = Math.round(mBoundingBox.right - mBoundingBox.left);
outputBuffer[3] = Math.round(mBoundingBox.bottom - mBoundingBox.top);
}
private void mapRectFromViewToWindowCoords(View view, RectF rect) {
Matrix matrix = view.getMatrix();
if (!matrix.isIdentity()) {
matrix.mapRect(rect);
}
rect.offset(view.getLeft(), view.getTop());
ViewParent parent = view.getParent();
while (parent instanceof View) {
View parentView = (View) parent;
rect.offset(-parentView.getScrollX(), -parentView.getScrollY());
matrix = parentView.getMatrix();
if (!matrix.isIdentity()) {
matrix.mapRect(rect);
}
rect.offset(parentView.getLeft(), parentView.getTop());
parent = parentView.getParent();
}
}
/**
* Returns the coordinates of a view relative to the window (not just the RootView which is what
* measure will return)
*
* @param tag - the tag for the view
* @param outputBuffer - output buffer that contains [x,y,width,height] of the view in coordinates
* relative to the device window
*/
public synchronized void measureInWindow(int tag, int[] outputBuffer) {
UiThreadUtil.assertOnUiThread();
View v = mTagsToViews.get(tag);
if (v == null) {
throw new NoSuchNativeViewException("No native view for " + tag + " currently exists");
}
v.getLocationOnScreen(outputBuffer);
// We need to remove the status bar from the height. getLocationOnScreen will include the
// status bar.
Resources resources = v.getContext().getResources();
int statusBarId = resources.getIdentifier("status_bar_height", "dimen", "android");
if (statusBarId > 0) {
int height = (int) resources.getDimension(statusBarId);
outputBuffer[1] -= height;
}
// outputBuffer[0,1] already contain what we want
outputBuffer[2] = v.getWidth();
outputBuffer[3] = v.getHeight();
}
public synchronized int findTargetTagForTouch(int reactTag, float touchX, float touchY) {
UiThreadUtil.assertOnUiThread();
View view = mTagsToViews.get(reactTag);
if (view == null) {
throw new JSApplicationIllegalArgumentException("Could not find view with tag " + reactTag);
}
return TouchTargetHelper.findTargetTagForTouch(touchX, touchY, (ViewGroup) view);
}
public synchronized void setJSResponder(
int reactTag, int initialReactTag, boolean blockNativeResponder) {
if (!blockNativeResponder) {
mJSResponderHandler.setJSResponder(initialReactTag, null);
return;
}
View view = mTagsToViews.get(reactTag);
if (initialReactTag != reactTag && view instanceof ViewParent) {
// In this case, initialReactTag corresponds to a virtual/layout-only View, and we already
// have a parent of that View in reactTag, so we can use it.
mJSResponderHandler.setJSResponder(initialReactTag, (ViewParent) view);
return;
}
if (mRootTags.get(reactTag)) {
SoftAssertions.assertUnreachable(
"Cannot block native responder on " + reactTag + " that is a root view");
}
mJSResponderHandler.setJSResponder(initialReactTag, view.getParent());
}
public void clearJSResponder() {
mJSResponderHandler.clearJSResponder();
}
void configureLayoutAnimation(final ReadableMap config, final Callback onAnimationComplete) {
mLayoutAnimator.initializeFromConfig(config, onAnimationComplete);
}
void clearLayoutAnimation() {
mLayoutAnimator.reset();
}
@Deprecated
public synchronized void dispatchCommand(
int reactTag, int commandId, @Nullable ReadableArray args) {
UiThreadUtil.assertOnUiThread();
View view = mTagsToViews.get(reactTag);
if (view == null) {
throw new IllegalViewOperationException(
"Trying to send command to a non-existing view " + "with tag " + reactTag);
}
ViewManager viewManager = resolveViewManager(reactTag);
viewManager.receiveCommand(view, commandId, args);
}
public synchronized void dispatchCommand(
int reactTag, String commandId, @Nullable ReadableArray args) {
UiThreadUtil.assertOnUiThread();
View view = mTagsToViews.get(reactTag);
if (view == null) {
throw new IllegalViewOperationException(
"Trying to send command to a non-existing view " + "with tag " + reactTag);
}
ViewManager viewManager = resolveViewManager(reactTag);
viewManager.receiveCommand(view, commandId, args);
}
/**
* Show a {@link PopupMenu}.
*
* @param reactTag the tag of the anchor view (the PopupMenu is displayed next to this view); this
* needs to be the tag of a native view (shadow views can not be anchors)
* @param items the menu items as an array of strings
* @param success will be called with the position of the selected item as the first argument, or
* no arguments if the menu is dismissed
*/
public synchronized void showPopupMenu(
int reactTag, ReadableArray items, Callback success, Callback error) {
UiThreadUtil.assertOnUiThread();
View anchor = mTagsToViews.get(reactTag);
if (anchor == null) {
error.invoke("Can't display popup. Could not find view with tag " + reactTag);
return;
}
mPopupMenu = new PopupMenu(getReactContextForView(reactTag), anchor);
Menu menu = mPopupMenu.getMenu();
for (int i = 0; i < items.size(); i++) {
menu.add(Menu.NONE, Menu.NONE, i, items.getString(i));
}
PopupMenuCallbackHandler handler = new PopupMenuCallbackHandler(success);
mPopupMenu.setOnMenuItemClickListener(handler);
mPopupMenu.setOnDismissListener(handler);
mPopupMenu.show();
}
/** Dismiss the last opened PopupMenu {@link PopupMenu}. */
public void dismissPopupMenu() {
if (mPopupMenu != null) {
mPopupMenu.dismiss();
}
}
private static class PopupMenuCallbackHandler
implements PopupMenu.OnMenuItemClickListener, PopupMenu.OnDismissListener {
final Callback mSuccess;
boolean mConsumed = false;
private PopupMenuCallbackHandler(Callback success) {
mSuccess = success;
}
@Override
public void onDismiss(PopupMenu menu) {
if (!mConsumed) {
mSuccess.invoke(UIManagerModuleConstants.ACTION_DISMISSED);
mConsumed = true;
}
}
@Override
public boolean onMenuItemClick(MenuItem item) {
if (!mConsumed) {
mSuccess.invoke(UIManagerModuleConstants.ACTION_ITEM_SELECTED, item.getOrder());
mConsumed = true;
return true;
}
return false;
}
}
/**
* @return Themed React context for view with a given {@param reactTag} - it gets the context
* directly from the view using {@link View#getContext}.
*/
private ThemedReactContext getReactContextForView(int reactTag) {
View view = mTagsToViews.get(reactTag);
if (view == null) {
throw new JSApplicationIllegalArgumentException("Could not find view with tag " + reactTag);
}
return (ThemedReactContext) view.getContext();
}
public void sendAccessibilityEvent(int tag, int eventType) {
View view = mTagsToViews.get(tag);
if (view == null) {
throw new JSApplicationIllegalArgumentException("Could not find view with tag " + tag);
}
view.sendAccessibilityEvent(eventType);
}
}
|
package org.jetbrains.plugins.scala.testingSupport.scalaTest;
import org.scalatest.Report;
import org.scalatest.Reporter;
import scala.Some;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
public class ScalaTestReporter implements Reporter {
private HashMap<String, Long> map = new HashMap<String, Long>();
public void testSucceeded(Report r) {
long duration = System.currentTimeMillis() - map.get(r.name());
System.out.println("\n##teamcity[testFinished name='" + escapeString(r.name()) + "' duration='"+ duration +"']");
map.remove(r.name());
}
public void testFailed(Report r) {
long duration = System.currentTimeMillis ()- map.get(r.name());
boolean error = true;
String detail;
if (r.throwable() instanceof Some) {
Throwable x = (Throwable)((Some) r.throwable()).get();
if (x instanceof AssertionError) error = false;
StringWriter writer = new StringWriter();
x.printStackTrace(new PrintWriter(writer));
detail = writer.getBuffer().toString();
} else {
detail = "";
}
String res = "\n##teamcity[testFailed name='" + escapeString(r.name()) + "' message='" + escapeString(r.message()) +
"' details='" + escapeString(detail) + "'";
if (error) res += "error = '" + error + "'";
res += "timestamp='" + escapeString(r.date().toString()) + "']";
System.out.println(res);
testSucceeded(r);
}
public void suiteCompleted(Report r) {
System.out.println("\n##teamcity[testSuiteFinished name='" + escapeString(r.name()) + "']");
}
public void testStarting(Report r) {
map.put(r.name(), System.currentTimeMillis());
System.out.println("\n##teamcity[testStarted name='" + escapeString(r.name()) +
"' captureStandardOutput='true']");
}
public void testIgnored(Report r) {
System.out.println("\n##teamcity[testIgnored name='" + escapeString(r.name()) + "' message='" + escapeString(r.message()) + "']");
}
public void suiteStarting(Report r) {
System.out.println("##teamcity[testSuiteStarted name='" + escapeString(r.name()) + "' locationHint='scala://" +
escapeString(r.name()) + "']");
}
public void suiteAborted(Report r) {
}
public void infoProvided(Report r) {
}
public void runStopped() {
}
public void runAborted(Report r) {
}
public void runCompleted() {
}
public void dispose() {
}
public void runStarting(int i) {
System.out.println("##teamcity[testCount count='" + i + "']");
}
private String escapeString(String s) {
return s.replaceAll("[|]", "||").replaceAll("[']", "|'").replaceAll("[\n]", "|n").replaceAll("[\r]", "|r").replaceAll("]","|]");
}
}
|
package com.battlelancer.seriesguide.service;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.app.TaskStackBuilder;
import android.support.v4.content.ContextCompat;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.style.StyleSpan;
import com.battlelancer.seriesguide.R;
import com.battlelancer.seriesguide.SgApp;
import com.battlelancer.seriesguide.provider.SeriesGuideContract.Episodes;
import com.battlelancer.seriesguide.provider.SeriesGuideContract.Shows;
import com.battlelancer.seriesguide.provider.SeriesGuideDatabase.Tables;
import com.battlelancer.seriesguide.settings.DisplaySettings;
import com.battlelancer.seriesguide.settings.NotificationSettings;
import com.battlelancer.seriesguide.thetvdbapi.TvdbImageTools;
import com.battlelancer.seriesguide.ui.EpisodesActivity;
import com.battlelancer.seriesguide.ui.QuickCheckInActivity;
import com.battlelancer.seriesguide.ui.ShowsActivity;
import com.battlelancer.seriesguide.util.ServiceUtils;
import com.battlelancer.seriesguide.util.TextTools;
import com.battlelancer.seriesguide.util.TimeTools;
import com.battlelancer.seriesguide.util.Utils;
import com.uwetrottmann.androidutils.AndroidUtils;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import org.threeten.bp.Instant;
import timber.log.Timber;
public class NotificationService extends IntentService {
public static final String ACTION_CLEARED = "seriesguide.intent.action.CLEARED";
public static final String EXTRA_EPISODE_TVDBID
= "com.battlelancer.seriesguide.EXTRA_EPISODE_TVDBID";
private static final String EXTRA_EPISODE_CLEARED_TIME
= "com.battlelancer.seriesguide.episode_cleared_time";
private static final boolean DEBUG = false;
private static final int REQUEST_CODE_DELETE_INTENT = 1;
private static final int REQUEST_CODE_SINGLE_EPISODE = 2;
private static final int REQUEST_CODE_MULTIPLE_EPISODES = 3;
private static final int REQUEST_CODE_ACTION_CHECKIN = 4;
private static final int REQUEST_CODE_ACTION_SET_WATCHED = 4;
public static final long[] VIBRATION_PATTERN = new long[] {
0, 100, 200, 100, 100, 100
};
private static final String[] PROJECTION = new String[] {
Tables.EPISODES + "." + Episodes._ID, Episodes.TITLE, Episodes.FIRSTAIREDMS,
Shows.TITLE, Shows.NETWORK, Episodes.NUMBER, Episodes.SEASON, Shows.POSTER,
Episodes.OVERVIEW
};
// by airdate, then by show, then lowest number first
private static final String SORTING = Episodes.FIRSTAIREDMS + " ASC,"
+ Shows.SORT_TITLE + ","
+ Episodes.NUMBER + " ASC";
// only if notifications are on: unwatched episodes released on or after arg
private static final String SELECTION = Shows.SELECTION_NOTIFY + " AND "
+ Episodes.SELECTION_UNWATCHED + " AND "
+ Episodes.FIRSTAIREDMS + ">=?";
interface NotificationQuery {
int _ID = 0;
int TITLE = 1;
int EPISODE_FIRST_RELEASE_MS = 2;
int SHOW_TITLE = 3;
int NETWORK = 4;
int NUMBER = 5;
int SEASON = 6;
int POSTER = 7;
int OVERVIEW = 8;
}
public NotificationService() {
super("Episode Notification Service");
setIntentRedelivery(true);
}
@Override
protected void onHandleIntent(Intent intent) {
Timber.d("Waking up...");
// remove notification service wake-up alarm if notifications are disabled or not unlocked
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!NotificationSettings.isNotificationsEnabled(this) || !Utils.hasAccessToX(this)) {
Timber.d("Notifications disabled, removing wake-up alarm");
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(this, OnAlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
if (am != null) {
am.cancel(pi);
}
resetLastEpisodeAirtime(prefs);
return;
}
long nextWakeUpTime = 0;
final long customCurrentTime = TimeTools.getCurrentTime(this);
final Cursor upcomingEpisodes = queryUpcomingEpisodes(customCurrentTime);
if (upcomingEpisodes != null) {
int notificationThreshold = NotificationSettings.getLatestToIncludeTreshold(this);
if (DEBUG) {
Timber.d("DEBUG MODE: notification threshold is 1 week");
// a week, for debugging (use only one show to get single
// episode notifications)
notificationThreshold = 10080;
// notify again for same episodes
resetLastEpisodeAirtime(prefs);
}
final long nextEpisodeReleaseTime = NotificationSettings.getNextToNotifyAbout(this);
// wake user-defined amount of time earlier than next episode release time
final long plannedWakeUpTime =
TimeTools.applyUserOffset(this, nextEpisodeReleaseTime).getTime()
- DateUtils.MINUTE_IN_MILLIS * notificationThreshold;
// note: on first run plannedWakeUpTime will be <= 0
boolean checkForNewEpisodes = true;
if (System.currentTimeMillis() < plannedWakeUpTime) {
Timber.d("Woke up earlier than planned, checking for new episodes");
checkForNewEpisodes = false;
long releaseTimeLastNotified = NotificationSettings.getLastNotifiedAbout(this);
while (upcomingEpisodes.moveToNext()) {
final long releaseTime = upcomingEpisodes.getLong(
NotificationQuery.EPISODE_FIRST_RELEASE_MS);
// any episodes added that release before the next one planned to notify about?
if (releaseTime < nextEpisodeReleaseTime) {
// limit to those released after the episode we last notified about to avoid
// notifying about an episode we already notified about
// limitation: so if added episodes release at or before that last episode
// they will not be notified about
if (releaseTime > releaseTimeLastNotified) {
checkForNewEpisodes = true;
break;
}
} else {
break;
}
}
}
if (checkForNewEpisodes) {
final long latestTimeToInclude = customCurrentTime
+ DateUtils.MINUTE_IN_MILLIS * notificationThreshold;
maybeNotify(prefs, upcomingEpisodes, latestTimeToInclude);
// plan next episode to notify about
upcomingEpisodes.moveToPosition(-1);
while (upcomingEpisodes.moveToNext()) {
final long releaseTime = upcomingEpisodes.getLong(
NotificationQuery.EPISODE_FIRST_RELEASE_MS);
if (releaseTime > latestTimeToInclude) {
prefs.edit()
.putLong(NotificationSettings.KEY_NEXT_TO_NOTIFY, releaseTime)
.apply();
Timber.d("Next notification planned for episode released at: %s",
Instant.ofEpochMilli(releaseTime));
// calc wake up time to notify about this episode
// taking into account time offset and notification threshold
nextWakeUpTime = TimeTools.applyUserOffset(this, releaseTime).getTime()
- DateUtils.MINUTE_IN_MILLIS * notificationThreshold;
break;
}
}
} else {
// Go to sleep, wake up as planned
Timber.d("No new episodes");
nextWakeUpTime = plannedWakeUpTime;
}
upcomingEpisodes.close();
}
// Set a default wake-up time if there are no future episodes for now
if (nextWakeUpTime <= 0) {
nextWakeUpTime = System.currentTimeMillis() + 6 * DateUtils.HOUR_IN_MILLIS;
Timber.d("No future episodes found, wake up in 6 hours");
}
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(this, NotificationService.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
Timber.d("Going to sleep, setting wake-up alarm to: %s",
Instant.ofEpochMilli(nextWakeUpTime));
if (am != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nextWakeUpTime, pi);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
am.setExact(AlarmManager.RTC_WAKEUP, nextWakeUpTime, pi);
} else {
am.set(AlarmManager.RTC_WAKEUP, nextWakeUpTime, pi);
}
}
}
/**
* Extracts the last cleared time and stores it in settings.
*/
public static void handleDeleteIntent(Context context, @Nullable Intent intent) {
if (intent == null) {
return;
}
long clearedTime = intent.getLongExtra(EXTRA_EPISODE_CLEARED_TIME, 0);
if (clearedTime != 0) {
// Never show the cleared episode(s) again
Timber.d("Notification cleared, setting last cleared episode time: %d", clearedTime);
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putLong(NotificationSettings.KEY_LAST_CLEARED, clearedTime)
.apply();
}
}
/**
* Resets the air time of the last notified about episode. Afterwards notifications for episodes
* may appear, which were already notified about.
*/
public static void resetLastEpisodeAirtime(final SharedPreferences prefs) {
Timber.d("Resetting last cleared and last notified");
prefs.edit()
.putLong(NotificationSettings.KEY_LAST_CLEARED, 0)
.putLong(NotificationSettings.KEY_LAST_NOTIFIED, 0)
.apply();
}
/**
* Get episodes which air from 12 hours ago until eternity, excludes some episodes based on user
* settings.
*/
private Cursor queryUpcomingEpisodes(long customCurrentTime) {
StringBuilder selection = new StringBuilder(SELECTION);
boolean isNoSpecials = DisplaySettings.isHidingSpecials(this);
Timber.d("Settings: specials: %s", isNoSpecials ? "YES" : "NO");
if (isNoSpecials) {
selection.append(" AND ").append(Episodes.SELECTION_NO_SPECIALS);
}
// always exclude hidden shows
selection.append(" AND ").append(Shows.SELECTION_NO_HIDDEN);
return getContentResolver().query(Episodes.CONTENT_URI_WITHSHOW,
PROJECTION, selection.toString(), new String[] {
String.valueOf(customCurrentTime - 12 * DateUtils.HOUR_IN_MILLIS)
}, SORTING
);
}
private void maybeNotify(SharedPreferences prefs, Cursor upcomingEpisodes,
long latestTimeToInclude) {
final List<Integer> notifyPositions = new ArrayList<>();
final long latestTimeCleared = NotificationSettings.getLastCleared(this);
int position = -1;
upcomingEpisodes.moveToPosition(position);
while (upcomingEpisodes.moveToNext()) {
position++;
// get episodes which are within the notification threshold (user set)...
final long releaseTime = upcomingEpisodes.getLong(
NotificationQuery.EPISODE_FIRST_RELEASE_MS);
if (releaseTime <= latestTimeToInclude) {
// ...and released after the last one the user cleared.
// Note: should be at most those of the last few hours (see cursor query).
if (releaseTime > latestTimeCleared) {
notifyPositions.add(position);
}
} else {
// Too far into the future, stop!
break;
}
}
// Notify if we found any episodes, store latest release time we notify about
if (notifyPositions.size() > 0) {
upcomingEpisodes.moveToPosition(notifyPositions.get(notifyPositions.size() - 1));
long latestAirtime = upcomingEpisodes.getLong(
NotificationQuery.EPISODE_FIRST_RELEASE_MS);
prefs.edit().putLong(NotificationSettings.KEY_LAST_NOTIFIED, latestAirtime).apply();
Timber.d("Notify about %d episodes, latest released at: %s",
notifyPositions.size(), Instant.ofEpochMilli(latestAirtime));
notifyAbout(upcomingEpisodes, notifyPositions, latestAirtime);
}
}
private void notifyAbout(final Cursor upcomingEpisodes, List<Integer> notifyPositions,
long latestAirtime) {
final Context context = getApplicationContext();
CharSequence tickerText;
CharSequence contentTitle;
CharSequence contentText;
PendingIntent contentIntent;
// base intent for task stack
final Intent showsIntent = new Intent(context, ShowsActivity.class);
showsIntent.putExtra(ShowsActivity.InitBundle.SELECTED_TAB,
ShowsActivity.InitBundle.INDEX_TAB_UPCOMING);
final int count = notifyPositions.size();
if (count == 1) {
// notify in detail about one episode
upcomingEpisodes.moveToPosition(notifyPositions.get(0));
final String showTitle = upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE);
// show title and number, like 'Show 1x01'
contentTitle = TextTools.getShowWithEpisodeNumber(
this,
showTitle,
upcomingEpisodes.getInt(NotificationQuery.SEASON),
upcomingEpisodes.getInt(NotificationQuery.NUMBER)
);
tickerText = getString(R.string.upcoming_show, contentTitle);
// "8:00 PM Network"
final String time = TimeTools.formatToLocalTime(this, TimeTools.applyUserOffset(this,
upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS)));
final String network = upcomingEpisodes.getString(NotificationQuery.NETWORK);
contentText = TextTools.dotSeparate(time, network); // switch on purpose
Intent episodeDetailsIntent = new Intent(context, EpisodesActivity.class);
episodeDetailsIntent.putExtra(EpisodesActivity.InitBundle.EPISODE_TVDBID,
upcomingEpisodes.getInt(NotificationQuery._ID));
episodeDetailsIntent.putExtra(EXTRA_EPISODE_CLEARED_TIME, latestAirtime);
contentIntent = TaskStackBuilder.create(context)
.addNextIntent(showsIntent)
.addNextIntent(episodeDetailsIntent)
.getPendingIntent(REQUEST_CODE_SINGLE_EPISODE,
PendingIntent.FLAG_CANCEL_CURRENT);
} else {
// notify about multiple episodes
tickerText = getString(R.string.upcoming_episodes);
contentTitle = getString(R.string.upcoming_episodes_number,
NumberFormat.getIntegerInstance().format(count));
contentText = getString(R.string.upcoming_display);
contentIntent = TaskStackBuilder.create(context)
.addNextIntent(showsIntent.putExtra(EXTRA_EPISODE_CLEARED_TIME, latestAirtime))
.getPendingIntent(REQUEST_CODE_MULTIPLE_EPISODES,
PendingIntent.FLAG_CANCEL_CURRENT);
}
final NotificationCompat.Builder nb =
new NotificationCompat.Builder(context, SgApp.NOTIFICATION_CHANNEL_EPISODES);
boolean richNotification = AndroidUtils.isJellyBeanOrHigher();
if (richNotification) {
// JELLY BEAN and above
if (count == 1) {
// single episode
upcomingEpisodes.moveToPosition(notifyPositions.get(0));
maybeSetPoster(nb, upcomingEpisodes.getString(NotificationQuery.POSTER));
if (!DisplaySettings.preventSpoilers(context)) {
final String episodeTitle = TextTools.getEpisodeTitle(context,
upcomingEpisodes.getString(NotificationQuery.TITLE),
upcomingEpisodes.getInt(NotificationQuery.NUMBER));
final String episodeSummary = upcomingEpisodes
.getString(NotificationQuery.OVERVIEW);
final SpannableStringBuilder bigText = new SpannableStringBuilder();
bigText.append(episodeTitle);
bigText.setSpan(new StyleSpan(Typeface.BOLD), 0, bigText.length(), 0);
if (!TextUtils.isEmpty(episodeSummary)) {
bigText.append("\n").append(episodeSummary);
}
nb.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText)
.setSummaryText(contentText));
}
// Action button to check in
Intent checkInActionIntent = new Intent(context, QuickCheckInActivity.class);
checkInActionIntent.putExtra(QuickCheckInActivity.InitBundle.EPISODE_TVDBID,
upcomingEpisodes.getInt(NotificationQuery._ID));
checkInActionIntent.putExtra(EXTRA_EPISODE_CLEARED_TIME, latestAirtime);
checkInActionIntent.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
PendingIntent checkInIntent = PendingIntent.getActivity(context,
REQUEST_CODE_ACTION_CHECKIN,
checkInActionIntent, PendingIntent.FLAG_CANCEL_CURRENT);
// icon only shown on Wear and 4.1 (API 16) to 6.0 (API 23)
nb.addAction(R.drawable.ic_action_checkin, getString(R.string.checkin),
checkInIntent);
// Action button to set watched
Intent setWatchedIntent = new Intent(context, NotificationActionReceiver.class);
setWatchedIntent.putExtra(EXTRA_EPISODE_TVDBID,
upcomingEpisodes.getInt(NotificationQuery._ID));
// data to handle delete
checkInActionIntent.putExtra(EXTRA_EPISODE_CLEARED_TIME, latestAirtime);
PendingIntent setWatchedPendingIntent = PendingIntent.getBroadcast(context,
REQUEST_CODE_ACTION_SET_WATCHED,
setWatchedIntent, PendingIntent.FLAG_CANCEL_CURRENT);
// icon only shown on Wear and 4.1 (API 16) to 6.0 (API 23)
nb.addAction(R.drawable.ic_action_tick, getString(R.string.action_watched),
setWatchedPendingIntent);
nb.setNumber(1);
} else {
// multiple episodes
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
// display at most the first five
for (int displayIndex = 0; displayIndex < Math.min(count, 5); displayIndex++) {
if (!upcomingEpisodes.moveToPosition(notifyPositions.get(displayIndex))) {
// could not go to the desired position (testing just in case)
break;
}
final SpannableStringBuilder lineText = new SpannableStringBuilder();
// show title and number, like 'Show 1x01'
String title = TextTools.getShowWithEpisodeNumber(
this,
upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE),
upcomingEpisodes.getInt(NotificationQuery.SEASON),
upcomingEpisodes.getInt(NotificationQuery.NUMBER)
);
lineText.append(title);
lineText.setSpan(new StyleSpan(Typeface.BOLD), 0, lineText.length(), 0);
lineText.append(" ");
// "8:00 PM Network"
String time = TimeTools.formatToLocalTime(this, TimeTools
.applyUserOffset(this, upcomingEpisodes
.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS)));
String network = upcomingEpisodes
.getString(NotificationQuery.NETWORK);
lineText.append(TextTools.dotSeparate(time, network)); // switch on purpose
inboxStyle.addLine(lineText);
}
// tell if we could not display all episodes
if (count > 5) {
inboxStyle.setSummaryText(getString(R.string.more, count - 5));
}
nb.setStyle(inboxStyle);
nb.setNumber(count);
}
} else {
// ICS and below
if (count == 1) {
// single episode
upcomingEpisodes.moveToPosition(notifyPositions.get(0));
maybeSetPoster(nb, upcomingEpisodes.getString(NotificationQuery.POSTER));
}
}
// notification sound
final String ringtoneUri = NotificationSettings.getNotificationsRingtone(context);
// If the string is empty, the user chose silent...
boolean hasSound = ringtoneUri.length() != 0;
if (hasSound) {
// ...otherwise set the specified ringtone
nb.setSound(Uri.parse(ringtoneUri));
}
// vibration
boolean vibrates = NotificationSettings.isNotificationVibrating(context);
if (vibrates) {
nb.setVibrate(VIBRATION_PATTERN);
}
nb.setDefaults(Notification.DEFAULT_LIGHTS);
nb.setWhen(System.currentTimeMillis());
nb.setAutoCancel(true);
nb.setTicker(tickerText);
nb.setContentTitle(contentTitle);
nb.setContentText(contentText);
nb.setContentIntent(contentIntent);
nb.setSmallIcon(R.drawable.ic_notification);
nb.setColor(ContextCompat.getColor(this, R.color.accent_primary));
nb.setPriority(NotificationCompat.PRIORITY_DEFAULT);
Intent i = new Intent(this, NotificationActionReceiver.class);
i.setAction(ACTION_CLEARED);
i.putExtra(EXTRA_EPISODE_CLEARED_TIME, latestAirtime);
PendingIntent deleteIntent = PendingIntent.getBroadcast(this, REQUEST_CODE_DELETE_INTENT, i,
PendingIntent.FLAG_CANCEL_CURRENT);
nb.setDeleteIntent(deleteIntent);
// build the notification
Notification notification = nb.build();
// use a unique id within the app
NotificationManagerCompat nm = NotificationManagerCompat.from(getApplicationContext());
nm.notify(SgApp.NOTIFICATION_EPISODE_ID, notification);
Timber.d("Notification: count=%d, rich(JB+)=%s, sound=%s, vibrate=%s, delete=%s",
count,
richNotification ? "YES" : "NO",
hasSound ? "YES" : "NO",
vibrates ? "YES" : "NO",
Instant.ofEpochMilli(latestAirtime));
}
private void maybeSetPoster(NotificationCompat.Builder nb, String posterPath) {
try {
Bitmap poster = ServiceUtils.loadWithPicasso(this,
TvdbImageTools.smallSizeUrl(posterPath))
.centerCrop()
.resizeDimen(R.dimen.show_poster_width, R.dimen.show_poster_height)
.get();
nb.setLargeIcon(poster);
// add special large resolution background for wearables
// https://developer.android.com/training/wearables/notifications/creating.html#AddWearableFeatures
Bitmap posterSquare = ServiceUtils.loadWithPicasso(this,
TvdbImageTools.fullSizeUrl(posterPath))
.centerCrop()
.resize(400, 400)
.get();
NotificationCompat.WearableExtender wearableExtender =
new NotificationCompat.WearableExtender()
.setBackground(posterSquare);
nb.extend(wearableExtender);
} catch (IOException e) {
Timber.e(e, "maybeSetPoster: failed.");
}
}
}
|
package com.strengthcoach.strengthcoach.helpers;
import android.util.Log;
import com.parse.ParseException;
import com.parse.SaveCallback;
import com.strengthcoach.strengthcoach.Models.Address;
import com.strengthcoach.strengthcoach.Models.Gym;
import com.strengthcoach.strengthcoach.Models.Review;
import com.strengthcoach.strengthcoach.Models.SimpleUser;
import com.strengthcoach.strengthcoach.Models.Trainer;
import java.util.ArrayList;
public class DataLoader {
Address address;
Gym gym;
Trainer trainer;
SimpleUser user;
public void populate() {
user = new SimpleUser();
user.setPhoneNumber("555-555-5555");
user.setName("Mickey Mouse");
user.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
// Saved successfully.
Log.d("DEBUG", "User update saved!");
String id = user.getObjectId();
Log.d("DEBUG", "The object id is: " + id);
instantiateAddress();
instantiateTrainer();
instantiateGym();
} else {
// The save failed.
Log.d("DEBUG", "User update error: " + e);
}
}
});
}
private void instantiateTrainer() {
String profileImageUrl = "http:
String image1 = "https://developer.cdn.mozilla.net/media/uploads/demos/d/a/daniel.moura/5518edae24034cecedeb89bf3c1db5c2/1370528531_screenshot_1.png";
String image2 = "http://imgur.com/gallery/xfzQez6";
trainer = new Trainer();
trainer.setName("Mike Chang");
trainer.setAboutMe("I am the best!!");
trainer.setPhoneNumber("222-222-2222");
ArrayList<SimpleUser> clients = new ArrayList<>();
clients.add(user);
trainer.setClients(clients);
trainer.setRating(5);
trainer.setProfileImageUrl(profileImageUrl);
ArrayList<String> images = new ArrayList<>();
images.add(image1);
images.add(image2);
trainer.setImages(images);
}
private void instantiateGym() {
gym = new Gym();
gym.setName("24 Hour Fitness");
gym.setAddress(address);
gym.setLocation(37.404324, -122.108046);
ArrayList<Trainer> trainers = new ArrayList<>();
trainers.add(trainer);
gym.setTrainers(trainers);
gym.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
if (e != null) {
e.printStackTrace();
} else {
instantiateReview();
}
}
});
}
// Creates an address object and saves in Parse cloud
private void instantiateAddress() {
address = new Address();
address.setAddressLine1("2550 W El Camino Real");
address.setAddressLine2("");
address.setCity("Mountain View");
address.setState("CA");
address.setZip("94040");
}
private void instantiateReview() {
Review review = new Review();
review.setReviewer(user.getObjectId());
review.setReviewee(trainer.getObjectId());
review.setRating(4);
review.setReviewText("I had a great time with Mike --Mickey");
review.saveInBackground();
}
}
|
package org.wwarn.surveyor.client.mvp.presenter;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.web.bindery.event.shared.binder.EventBinder;
import com.google.web.bindery.event.shared.binder.EventHandler;
import org.wwarn.surveyor.client.core.*;
import org.wwarn.surveyor.client.model.FilterConfig;
import org.wwarn.surveyor.client.mvp.ClientFactory;
import org.wwarn.surveyor.client.event.FilterChangedEvent;
import org.wwarn.surveyor.client.event.ResultChangedEvent;
import org.wwarn.surveyor.client.mvp.InitialFields;
import org.wwarn.surveyor.client.mvp.SimpleClientFactory;
import org.wwarn.surveyor.client.mvp.view.filter.FilterView;
import org.wwarn.surveyor.client.mvp.view.MainPanelView;
import org.wwarn.surveyor.client.util.AsyncCallbackWithTimeout;
import java.util.*;
public class FilterPresenter implements Presenter {
protected FilterView filterView;
private FilterChangeHandler filterChangeHandler = new FilterChangeHandler();
private ResultChangeHandler resultChangeHandler = new ResultChangeHandler(this);
protected ClientFactory clientFactory = SimpleClientFactory.getInstance();
private final ApplicationContext applicationContext = clientFactory.getApplicationContext();
public static final String DEFAULT_CATCH_ALL_OPTION = "All";
private static InitialFields initialFields;
public FilterPresenter(FilterView filterView) {
this.filterView = filterView;
bind();
}
public void go(MainPanelView container) {
// add filter view to filter panel
container.getFilterContainerPanel().add(filterView.asWidget());
// setup up surveyor
setupFilters();
}
private void setupFilters() {
// EventLogger.logEvent("org.wwarn.surveyor.client.mvp.presenter.FilterPresenter.setupFilters", "getLastQueryResult", "begin");
QueryResult queryResult = clientFactory.getLastQueryResult();
// EventLogger.logEvent("org.wwarn.surveyor.client.mvp.presenter.FilterPresenter.setupFilters", "getLastQueryResult", "end");
FacetList facetFields = queryResult.getFacetFields();
FilterConfig config = applicationContext.getConfig(FilterConfig.class);
filterView.setupFilterDisplay(facetFields, config);
}
private void updateFilters() {
// EventLogger.logEvent("org.wwarn.surveyor.client.mvp.presenter.FilterPresenter.updateFilters", "getLastQueryResult", "begin");
QueryResult queryResult = clientFactory.getLastQueryResult();
// EventLogger.logEvent("org.wwarn.surveyor.client.mvp.presenter.FilterPresenter.updateFilters", "getLastQueryResult", "end");
FacetList facetFields = queryResult.getFacetFields();
FilterConfig config = applicationContext.getConfig(FilterConfig.class);
filterView.updateFilterDisplay(facetFields, config);
}
public void bind() {
filterView.setPresenter(this);
}
public void onFilterChange(String facetField, Set<String> selectedListItems) {
clientFactory.getEventBus().fireEvent(new FilterChangedEvent(facetField, selectedListItems));
// filterView.setupFilterDisplay(clientFactory.getLastQueryResult().getFacetFields());
}
/**
* Holds responsibility for handling result changes
*/
static public class ResultChangeHandler{
private FilterPresenter presenter;
// result change handler
interface ResultChangedEventBinder extends EventBinder<ResultChangeHandler> {};
private ResultChangedEventBinder eventBinder = GWT.create(ResultChangedEventBinder.class);
private ClientFactory clientFactory = SimpleClientFactory.getInstance();
public ResultChangeHandler(FilterPresenter presenter) {
this.presenter = presenter;
eventBinder.bindEventHandlers(this, clientFactory.getEventBus());
}
@EventHandler
public void onResultChanged(ResultChangedEvent resultChangedEvent){
final QueryResult queryResult = resultChangedEvent.getQueryResult();
clientFactory.setLastQueryResult(queryResult);
// on result change reload filters..
presenter.updateFilters();
}
}
/**
* Class with sole responsibility for handling FilterChangeEvents
*/
static public class FilterChangeHandler{
public static final Date START_DATE = DateTimeFormat.getFormat("yyyy").parse("1975");
public static final int DELAY_MILLIS_BEFORE_QUERYING = 800;
private Queue<FilterChangedEvent> updateQueue = new LinkedList<FilterChangedEvent>();
/*stores all previous field selections, this must be kept for filters to work correctly*/
final HashMap<String, List<FilterChangedEvent.FilterElement>> selectedFacetFieldsAndValues = new HashMap<String, List<FilterChangedEvent.FilterElement>>();
interface FilterChangedEventBinder extends EventBinder<FilterChangeHandler> {};
private FilterChangedEventBinder eventBinder = GWT.create(FilterChangedEventBinder.class);
private ClientFactory clientFactory = SimpleClientFactory.getInstance();
public FilterChangeHandler() {
eventBinder.bindEventHandlers(this, clientFactory.getEventBus());
addInitialFilterQuery();
}
private void addInitialFilterQuery(){
FilterQuery filterQuery = clientFactory.getLastFilterQuery();
if (filterQuery != null && filterQuery.getFilterQueries() != null){
for( String key: filterQuery.getFilterQueries().keySet()){
FilterChangedEvent filterChangedEvent = new FilterChangedEvent(key);
FilterQuery.FilterQueryElement filterQueryElement = filterQuery.getFilterQueries().get(key);
if(filterQueryElement instanceof FilterQuery.FilterFieldValue){
filterChangedEvent.addFilter(((FilterQuery.FilterFieldValue) filterQueryElement).getFieldsValue());
}else if (filterQueryElement instanceof FilterQuery.FilterFieldGreaterThanInteger) {
int value = ((FilterQuery.FilterFieldGreaterThanInteger) filterQueryElement).getFieldValue();
filterChangedEvent.addFilter(value);
}else if (filterQueryElement instanceof FilterQuery.FilterFieldRangeDate) {
Date minDate = ((FilterQuery.FilterFieldRangeDate) filterQueryElement).getMinValue();
Date maxDate = ((FilterQuery.FilterFieldRangeDate) filterQueryElement).getMaxValue();
filterChangedEvent.addFilter(minDate, maxDate);
}
selectedFacetFieldsAndValues.put(key, filterChangedEvent.getSelectedListItems());
}
}
}
@EventHandler
public void onFilterChanged(FilterChangedEvent filterChangedEvent){
deferredUpdate(filterChangedEvent);
}
/**
* Queue filter changed events to reduce chatter on network
* maintain a queue of requests here, on first item entry, check wait a few ms for subsequent updates, then fire an update
* on second item entry, add to queue, repeat
* on wait complete, work through all items in the queue, merge all requests into a single batch call, empty queue once done
* @param filterChangedEvent
*/
public void deferredUpdate(FilterChangedEvent filterChangedEvent){
com.google.gwt.user.client.Timer timer = new com.google.gwt.user.client.Timer() {
@Override
public void run() {
while(!updateQueue.isEmpty()){
FilterChangedEvent changedEvent = updateQueue.remove();
selectedFacetFieldsAndValues.put(changedEvent.getFacetField(), changedEvent.getSelectedListItems());
}
updateFilter(selectedFacetFieldsAndValues);
}
};
if(updateQueue.isEmpty()) {
timer.schedule(DELAY_MILLIS_BEFORE_QUERYING);
}
updateQueue.add(filterChangedEvent);
}
private void updateFilter(Map<String, List<FilterChangedEvent.FilterElement>> selectedFacetFieldsAndValues) {
// EventLogger.logEvent("org.wwarn.surveyor.client.mvp.SurveyorAppController", "clientFactory.getDataProvider()", "begin");
DataProvider dataProvider = clientFactory.getDataProvider();
// EventLogger.logEvent("org.wwarn.surveyor.client.mvp.SurveyorAppController", "clientFactory.getDataProvider()", "end");
FilterQuery filterQuery = new FilterQuery();
filterQuery.setFields(getFilterFields());
for (String filterField : selectedFacetFieldsAndValues.keySet()) {
List<FilterChangedEvent.FilterElement> filterElements = selectedFacetFieldsAndValues.get(filterField);
if(filterElements.size() > 0){
FilterChangedEvent.FilterElement valueToFilter = filterElements.get(0);
if(valueToFilter instanceof FilterChangedEvent.SingleFilterValue){
String facetFieldValue = ((FilterChangedEvent.SingleFilterValue) valueToFilter).getFacetFieldValue();
if(!facetFieldValue.equals(DEFAULT_CATCH_ALL_OPTION)){
filterQuery.addFilter(filterField, facetFieldValue);
}
}else if(valueToFilter instanceof FilterChangedEvent.DateRange){
filterDateRange(filterQuery, valueToFilter);
}else if(valueToFilter instanceof FilterChangedEvent.DateRangeAndFields){
filterDateRangeAndFields(filterQuery, valueToFilter);
}else if(valueToFilter instanceof FilterChangedEvent.FilterGreater){
filterGreater(filterQuery, valueToFilter);
}else if(valueToFilter instanceof FilterChangedEvent.MultipleFilterValue){
final FilterChangedEvent.MultipleFilterValue multipleFilterValue = (FilterChangedEvent.MultipleFilterValue) valueToFilter;
if(!multipleFilterValue.getFacetFieldValues().contains(DEFAULT_CATCH_ALL_OPTION)){
filterMultipleValues(filterQuery, valueToFilter);
}
}
}
}
filterQuery.setFetchAllDistinctFieldValues(false);
clientFactory.setLastFilterQuery(filterQuery);
try {
dataProvider.query(filterQuery, new AsyncCallbackWithTimeout<QueryResult>() {
@Override
public void onTimeOutOrOtherFailure(Throwable caught) {
throw new IllegalStateException(caught);
}
@Override
public void onNonTimedOutSuccess(QueryResult queryResult) {
clientFactory.getEventBus().fireEvent(new ResultChangedEvent(queryResult));
}
});
} catch (SearchException e) {
throw new IllegalStateException(e);
}
}
private Set<String> getFilterFields() {
final InitialFields initialFields = getInitialFields();
if (initialFields != null) {
return initialFields.getInitialFields();
};
return null;
}
private void filterDateRange(FilterQuery filterQuery, FilterChangedEvent.FilterElement valueToFilter){
FilterChangedEvent.DateRange dateRange = (FilterChangedEvent.DateRange) valueToFilter;
filterQuery.addRangeFilter(valueToFilter.getFacetField(), dateRange.getStart(), dateRange.getEnd());
}
private void filterDateRangeAndFields(FilterQuery filterQuery, FilterChangedEvent.FilterElement valueToFilter){
FilterChangedEvent.DateRangeAndFields dateRange = (FilterChangedEvent.DateRangeAndFields) valueToFilter;
filterQuery.addRangeFilter(dateRange.getFieldTo(), dateRange.getStart(), new Date());
filterQuery.addRangeFilter(dateRange.getFieldFrom(), START_DATE, dateRange.getEnd());
}
private void filterGreater(FilterQuery filterQuery, FilterChangedEvent.FilterElement valueToFilter){
FilterChangedEvent.FilterGreater minimumSize = (FilterChangedEvent.FilterGreater) valueToFilter;
filterQuery.addFilterGreater(valueToFilter.getFacetField(), minimumSize.getFacetFieldValue());
}
private void filterMultipleValues(FilterQuery filterQuery, FilterChangedEvent.FilterElement valueToFilter){
FilterChangedEvent.MultipleFilterValue listValues = (FilterChangedEvent.MultipleFilterValue) valueToFilter;
filterQuery.addMultipleValuesFilter(valueToFilter.getFacetField(), listValues.getFacetFieldValues());
}
}
private static InitialFields getInitialFields() {
if(initialFields!=null) return initialFields;
try {
initialFields = GWT.create(InitialFields.class);
} catch (RuntimeException e) {
if (!e.getMessage().startsWith("Deferred binding")) throw e;
initialFields = new DefaultInitialFields();
GWT.log("Initial fields has not been implemented in the current application");
}
return initialFields;
}
static private class DefaultInitialFields implements InitialFields{
@Override
public Set<String> getInitialFields() {
return Collections.EMPTY_SET;
}
}
}
|
package com.intellij.codeInsight.completion;
import com.intellij.aspects.psi.PsiAspectFile;
import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.generation.OverrideImplementUtil;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.LookupItemPreferencePolicy;
import com.intellij.codeInsight.lookup.LookupItemUtil;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.lang.Language;
import com.intellij.lang.ASTNode;
import com.intellij.lang.jsp.NewJspLanguage;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.NameUtil;
import com.intellij.psi.codeStyle.SuggestedNameInfo;
import com.intellij.psi.codeStyle.VariableKind;
import com.intellij.psi.filters.ClassFilter;
import com.intellij.psi.filters.TrueFilter;
import com.intellij.psi.filters.position.SuperParentFilter;
import com.intellij.psi.impl.source.codeStyle.CodeStyleManagerEx;
import com.intellij.psi.impl.source.tree.ElementType;
import com.intellij.psi.infos.CandidateInfo;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.jsp.JspFile;
import com.intellij.psi.util.PropertyUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.xml.XmlFile;
import com.intellij.util.containers.HashMap;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.Perl5Compiler;
import java.util.*;
public class CompletionUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.CompletionUtil");
public static final Key TAIL_TYPE_ATTR = Key.create("tailType"); // one of constants defined in TailType interface
private static final Key<SmartPsiElementPointer> QUALIFIER_TYPE_ATTR = Key.create("qualifierType"); // SmartPsiElementPointer to PsiType of "qualifier"
private static final CompletionData ourJavaCompletionData = new JavaCompletionData();
private static final CompletionData ourJava15CompletionData = new Java15CompletionData();
private static final CompletionData ourJSPCompletionData = new JSPCompletionData();
private static final CompletionData ourXmlCompletionData = new XmlCompletionData();
private static final CompletionData ourGenericCompletionData = new CompletionData(){
{
final CompletionVariant variant = new CompletionVariant(PsiElement.class, TrueFilter.INSTANCE);
variant.addCompletionFilter(TrueFilter.INSTANCE, TailType.NONE);
registerVariant(variant);
}
};
private static final CompletionData ourWordCompletionData = new WordCompletionData();
private static final CompletionData ourJavaDocCompletionData = new JavaDocCompletionData();
static {
registerCompletionData(StdFileTypes.JSPX, new JspxCompletionData());
}
private static HashMap<FileType,CompletionData> completionDatas;
public static final Key<CompletionData> ENFORCE_COMPLETION_DATA_KEY = new Key<CompletionData>("Enforce completionData");
private static void initBuiltInCompletionDatas() {
completionDatas = new HashMap<FileType, CompletionData>();
registerCompletionData(StdFileTypes.HTML,new HtmlCompletionData());
registerCompletionData(StdFileTypes.XHTML,new XHtmlCompletionData());
}
public static final String DUMMY_IDENTIFIER = "IntellijIdeaRulezzz ";
public static final Key<String> COMPLETION_PREFIX = Key.create("Completion prefix");
public static final Key<PsiElement> ORIGINAL_KEY = Key.create("ORIGINAL_KEY");
public static final Key<PsiElement> COPY_KEY = Key.create("COPY_KEY");
public static PsiType getQualifierType(LookupItem item){
return (PsiType) item.getAttribute(CompletionUtil.QUALIFIER_TYPE_ATTR);
}
public static void setQualifierType(LookupItem item, PsiType type){
if (type != null){
item.setAttribute(QUALIFIER_TYPE_ATTR, type);
}
else{
item.setAttribute(QUALIFIER_TYPE_ATTR, null);
}
}
public static boolean startsWith(String text, String prefix) {
//if (text.length() <= prefix.length()) return false;
return toLowerCase(text).startsWith(toLowerCase(prefix));
}
private static String toLowerCase(String text) {
CodeInsightSettings settings = CodeInsightSettings.getInstance();
switch (settings.COMPLETION_CASE_SENSITIVE) {
case CodeInsightSettings.NONE:
return text.toLowerCase();
case CodeInsightSettings.FIRST_LETTER:
{
StringBuffer buffer = new StringBuffer();
buffer.append(text.toLowerCase());
if (buffer.length() > 0) {
buffer.setCharAt(0, text.charAt(0));
}
return buffer.toString();
}
default:
return text;
}
}
static void highlightMembersOfContainer(LinkedHashSet set) {
for (Iterator iter = set.iterator(); iter.hasNext();) {
LookupItem item = (LookupItem)iter.next();
Object o = item.getObject();
PsiType qualifierType = getQualifierType(item);
if (qualifierType == null) continue;
if (qualifierType instanceof PsiArrayType) {
if (o instanceof PsiField || o instanceof PsiMethod || o instanceof PsiClass) {
PsiElement parent = ((PsiElement)o).getParent();
if (parent instanceof PsiClass && parent.getContainingFile().getVirtualFile() == null) {
item.setAttribute(LookupItem.HIGHLIGHTED_ATTR, "");
}
}
}
else if (qualifierType instanceof PsiClassType){
PsiClass qualifierClass = ((PsiClassType) qualifierType).resolve();
if (o instanceof PsiField || o instanceof PsiMethod || o instanceof PsiClass) {
PsiElement parent = ((PsiElement)o).getParent();
if (parent != null && parent.equals(qualifierClass)) {
item.setAttribute(LookupItem.HIGHLIGHTED_ATTR, "");
}
}
}
}
}
public static final CompletionData getCompletionDataByElement(PsiElement element, CompletionContext context){
CompletionData wordCompletionData = null;
ASTNode textContainer = element != null ? element.getNode() : null;
while(textContainer != null){
final IElementType elementType = textContainer.getElementType();
final TokenSet readableTextContainerElements = elementType.getLanguage().getReadableTextContainerElements();
if(readableTextContainerElements.isInSet(elementType) || elementType == ElementType.PLAIN_TEXT) wordCompletionData = ourWordCompletionData;
textContainer = textContainer.getTreeParent();
}
final CompletionData completionDataByElementInner = getCompletionDataByElementInner(element, context);
if(wordCompletionData != null) return new CompositeCompletionData(completionDataByElementInner, wordCompletionData);
return completionDataByElementInner;
}
public static final CompletionData getCompletionDataByElementInner(PsiElement element, CompletionContext context){
final PsiFile file = context.file;
if(context.file.getUserData(ENFORCE_COMPLETION_DATA_KEY) != null) {
return context.file.getUserData(ENFORCE_COMPLETION_DATA_KEY);
}
final CompletionData completionDataByFileType = getCompletionDataByFileType(file.getFileType());
if (completionDataByFileType != null) return completionDataByFileType;
if(file instanceof PsiAspectFile){
return ourGenericCompletionData;
}
else if((file instanceof PsiJavaFile || file instanceof PsiCodeFragment) &&
! (file instanceof JspFile) // TODO: we need to check the java context of JspX
){
if (element != null && new SuperParentFilter(new ClassFilter(PsiDocComment.class)).isAcceptable(element, element.getParent())){
return ourJavaDocCompletionData;
}
else{
return element != null && element.getManager().getEffectiveLanguageLevel() == LanguageLevel.JDK_1_5 ? ourJava15CompletionData : ourJavaCompletionData;
}
}
else if (file.getLanguage() == Language.findInstance(NewJspLanguage.class)) {
return ourJSPCompletionData;
}
else if (file instanceof XmlFile && file.getFileType() == StdFileTypes.XML) {
return ourXmlCompletionData;
}
return ourGenericCompletionData;
}
public static final void registerCompletionData(FileType fileType,CompletionData completionData) {
if (completionDatas==null) initBuiltInCompletionDatas();
completionDatas.put(fileType, completionData);
}
public static final CompletionData getCompletionDataByFileType(FileType fileType) {
if (completionDatas==null) initBuiltInCompletionDatas();
return completionDatas.get(fileType);
}
public static boolean checkName(String name, String prefix){
return checkName(name, prefix, false);
}
public static boolean checkName(String name, String prefix, boolean forceCaseInsensitive){
final CodeInsightSettings settings = CodeInsightSettings.getInstance();
if (name == null) {
return false;
}
boolean ret = true;
if(prefix != null){
int variant = settings.COMPLETION_CASE_SENSITIVE;
variant = forceCaseInsensitive ? CodeInsightSettings.NONE:variant;
switch(variant){
case CodeInsightSettings.NONE:
ret = name.toLowerCase().startsWith(prefix.toLowerCase());
break;
case CodeInsightSettings.FIRST_LETTER:
if(name.length() > 0){
if(prefix.length() > 0){
ret = (name.charAt(0) == prefix.charAt(0))
&& name.toLowerCase().startsWith(prefix.substring(1).toLowerCase(), 1);
}
}
else{
if(prefix.length() > 0) ret = false;
}
break;
case CodeInsightSettings.ALL:
ret = name.startsWith(prefix, 0);
break;
default:
ret = false;
}
}
return ret;
}
public static Pattern createCampelHumpsMatcher(String pattern){
Pattern pat = null;
final CodeInsightSettings settings = CodeInsightSettings.getInstance();
int variant = settings.COMPLETION_CASE_SENSITIVE;
Perl5Compiler compiler = new Perl5Compiler();
try {
switch(variant){
case CodeInsightSettings.NONE:
pat = compiler.compile(NameUtil.buildRegexp(pattern, 0, false));
break;
case CodeInsightSettings.FIRST_LETTER:
pat = compiler.compile(NameUtil.buildRegexp(pattern, 1, false));
break;
case CodeInsightSettings.ALL:
pat = compiler.compile(NameUtil.buildRegexp(pattern, 0, true));
break;
default:
pat = compiler.compile(NameUtil.buildRegexp(pattern, 0, false));
}
}
catch(MalformedPatternException me) {
}
return pat;
}
public static LookupItemPreferencePolicy completeVariableNameForRefactoring(Project project, LinkedHashSet set, String prefix, PsiType varType,
VariableKind varKind) {
FeatureUsageTracker.getInstance().triggerFeatureUsed("editing.completion.variable.name");
CodeStyleManagerEx codeStyleManager = (CodeStyleManagerEx) CodeStyleManager.getInstance(project);
SuggestedNameInfo suggestedNameInfo = codeStyleManager.suggestVariableName(varKind, null, null, varType);
final String[] suggestedNames = suggestedNameInfo.names;
LookupItemUtil.addLookupItems(set, suggestedNames, prefix);
if (set.isEmpty() && PsiType.VOID != varType) {
// use suggested names as suffixes
final String requiredSuffix = codeStyleManager.getSuffixByVariableKind(varKind);
final boolean isMethodPrefix = prefix.startsWith("is") || prefix.startsWith("get") || prefix.startsWith("set");
if(varKind != VariableKind.STATIC_FINAL_FIELD || isMethodPrefix){
for (int i = 0; i < suggestedNames.length; i++) {
suggestedNames[i] = codeStyleManager.variableNameToPropertyName(suggestedNames[i], varKind);
}
}
suggestedNameInfo = new SuggestedNameInfo(getOverlappedNameVersions(prefix, suggestedNames, requiredSuffix)) {
public void nameChoosen(String name) {
}
};
LookupItemUtil.addLookupItems(set, suggestedNameInfo.names, prefix);
}
return new NamePreferencePolicy(suggestedNameInfo);
}
public static String[] getOverlappedNameVersions(final String prefix, final String[] suggestedNames, String suffix) {
final List newSuggestions = new ArrayList();
int longestOverlap = 0;
for (int i = 0; i < suggestedNames.length; i++) {
String suggestedName = suggestedNames[i];
if(suggestedName.toUpperCase().startsWith(prefix.toUpperCase())){
newSuggestions.add(suggestedName);
longestOverlap = prefix.length();
}
suggestedName = "" + Character.toUpperCase(suggestedName.charAt(0)) + suggestedName.substring(1);
final int overlap = getOverlap(suggestedName, prefix);
if (overlap < longestOverlap) continue;
if (overlap > longestOverlap) {
newSuggestions.clear();
longestOverlap = overlap;
}
String suggestion = prefix.substring(0, prefix.length() - overlap) + suggestedName;
final int lastIndexOfSuffix = suggestion.lastIndexOf(suffix);
if (lastIndexOfSuffix >= 0 && suffix.length() < suggestion.length() - lastIndexOfSuffix) {
suggestion = suggestion.substring(0, lastIndexOfSuffix) + suffix;
}
if (!newSuggestions.contains(suggestion)) {
newSuggestions.add(suggestion);
}
}
return (String[]) newSuggestions.toArray(new String[newSuggestions.size()]);
}
private static int getOverlap(final String propertyName, final String prefix) {
int overlap = 0;
int propertyNameLen = propertyName.length();
int prefixLen = prefix.length();
for (int j = 1; j < prefixLen && j < propertyNameLen; j++) {
if (prefix.substring(prefixLen - j).equals(propertyName.substring(0, j))) {
overlap = j;
}
}
return overlap;
}
public static PsiType eliminateWildcards (PsiType type) {
if (type instanceof PsiClassType) {
PsiClassType classType = ((PsiClassType)type);
JavaResolveResult resolveResult = classType.resolveGenerics();
PsiClass aClass = (PsiClass)resolveResult.getElement();
if (aClass != null) {
PsiManager manager = aClass.getManager();
PsiTypeParameter[] typeParams = aClass.getTypeParameters();
Map<PsiTypeParameter, PsiType> map = new HashMap<PsiTypeParameter, PsiType>();
for (int j = 0; j < typeParams.length; j++) {
PsiTypeParameter typeParam = typeParams[j];
PsiType substituted = resolveResult.getSubstitutor().substitute(typeParam);
if (substituted instanceof PsiWildcardType) {
substituted = ((PsiWildcardType)substituted).getBound();
if (substituted == null) substituted = PsiType.getJavaLangObject(manager, aClass.getResolveScope());
}
map.put(typeParam, substituted);
}
PsiElementFactory factory = manager.getElementFactory();
PsiSubstitutor substitutor = factory.createSubstitutor(map);
type = factory.createType(aClass, substitutor);
}
}
return type;
}
public static String[] getUnserolvedReferences(final PsiElement parentOfType, final boolean referenceOnMethod) {
final List<String> unresolvedRefs = new ArrayList<String>();
parentOfType.accept(new PsiRecursiveElementVisitor() {
public void visitReferenceExpression(PsiReferenceExpression reference) {
final PsiElement parent = reference.getParent();
if(parent instanceof PsiReference) return;
if(referenceOnMethod && parent instanceof PsiMethodCallExpression && reference == ((PsiMethodCallExpression)parent).getMethodExpression()) {
if (reference.resolve() == null) unresolvedRefs.add(reference.getReferenceName());
}
else if(!referenceOnMethod && reference.resolve() == null) unresolvedRefs.add(reference.getReferenceName());
}
});
return unresolvedRefs.toArray(new String[unresolvedRefs.size()]);
}
public static String[] getOverides(final PsiClass parent, final PsiType typeByPsiElement) {
final List<String> overides = new ArrayList<String>();
final CandidateInfo[] methodsToOverrideImplement = OverrideImplementUtil.getMethodsToOverrideImplement(parent, true);
for (int i = 0; i < methodsToOverrideImplement.length; i++) {
final CandidateInfo candidateInfo = methodsToOverrideImplement[i];
final PsiElement element = candidateInfo.getElement();
if(typeByPsiElement == PsiUtil.getTypeByPsiElement(element) && element instanceof PsiNamedElement) overides.add(((PsiNamedElement)element).getName());
}
return overides.toArray(new String[overides.size()]);
}
public static String[] getImplements(final PsiClass parent, final PsiType typeByPsiElement) {
final List<String> overides = new ArrayList<String>();
final CandidateInfo[] methodsToOverrideImplement = OverrideImplementUtil.getMethodsToOverrideImplement(parent, false);
for (int i = 0; i < methodsToOverrideImplement.length; i++) {
final CandidateInfo candidateInfo = methodsToOverrideImplement[i];
final PsiElement element = candidateInfo.getElement();
if(typeByPsiElement == PsiUtil.getTypeByPsiElement(element) && element instanceof PsiNamedElement) overides.add(((PsiNamedElement)element).getName());
}
return overides.toArray(new String[overides.size()]);
}
public static String[] getPropertiesHandlersNames(final PsiClass psiClass,
boolean staticContext,
PsiType varType,
final PsiElement element) {
final List<String> propertyHandlers = new ArrayList<String>();
final PsiField[] fields = psiClass.getFields();
for (int i = 0; i < fields.length; i++) {
final PsiField field = fields[i];
if(field == element) continue;
final PsiModifierList modifierList = field.getModifierList();
if(staticContext && (modifierList != null && !modifierList.hasModifierProperty("static"))) continue;
final PsiMethod getter = PropertyUtil.generateGetterPrototype(field);
if(getter.getReturnType().equals(varType) && psiClass.findMethodBySignature(getter, true) == null) {
propertyHandlers.add(getter.getName());
}
final PsiMethod setter = PropertyUtil.generateSetterPrototype(field);
if(setter.getReturnType().equals(varType) && psiClass.findMethodBySignature(setter, true) == null) {
propertyHandlers.add(setter.getName());
}
}
return propertyHandlers.toArray(new String[propertyHandlers.size()]);
}
}
|
package org.jmxdatamart.Extractor;
import java.io.FileInputStream;
import java.lang.management.ManagementFactory;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import org.jmxdatamart.JMXTestServer.CarBean;
import org.jmxdatamart.JMXTestServer.TestBean;
public class Main {
private static boolean demo = true;
public static void main(String[] args) throws Exception {
if (demo) {
demo();
}
System.out.println("extract");
if (args.length != 1) {
System.out.println("Program need only 1 argument to the setting file");
return;
}
Settings s = Settings.fromXML(
new FileInputStream(args[0]));
final Extractor extractor = new Extractor(s);
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
if (extractor.isPeriodicallyExtract()) {
extractor.stop();
}
}
}));
if (!extractor.isPeriodicallyExtract()) {
System.out.println("Extractor is set to run once only!");
return;
}
System.out.println("Ctrl-C to cancel the extracting process...");
while (true) {
Thread.sleep(10000);
}
}
private static void demo() throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException, InstanceNotFoundException {
TestBean tb1 = new TestBean();
tb1.setA(new Integer(42));
tb1.setB(new Long(-1));
final ObjectName tbName1 = new ObjectName("com.personal.JMXTestServer:name=TestBean1");
TestBean tb2 = new TestBean();
tb2.setA(new Integer(55));
tb2.setB(new Long(-99));
final ObjectName tbName2 = new ObjectName("com.personal.JMXTestServer:name=TestBean2");
CarBean cb = new CarBean();
final ObjectName cbName = new ObjectName("org.jmxdatamart:name=CarBean");
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
mbs.registerMBean(tb1, tbName1);
mbs.registerMBean(cb, cbName);
mbs.registerMBean(tb2, tbName2);
System.out.println("Registered tb1, cb, and tb2");
}
}
|
package org.springframework.asm;
/**
* The path to a type argument, wildcard bound, array element type, or static
* inner type within an enclosing type.
*
* @author Eric Bruneton
*/
public class TypePath {
/**
* A type path step that steps into the element type of an array type. See
* {@link #getStep getStep}.
*/
public final static int ARRAY_ELEMENT = 0;
/**
* A type path step that steps into the nested type of a class type. See
* {@link #getStep getStep}.
*/
public final static int INNER_TYPE = 1;
/**
* A type path step that steps into the bound of a wildcard type. See
* {@link #getStep getStep}.
*/
public final static int WILDCARD_BOUND = 2;
/**
* A type path step that steps into a type argument of a generic type. See
* {@link #getStep getStep}.
*/
public final static int TYPE_ARGUMENT = 3;
/**
* The byte array where the path is stored, in Java class file format.
*/
byte[] b;
/**
* The offset of the first byte of the type path in 'b'.
*/
int offset;
/**
* Creates a new type path.
*
* @param b
* the byte array containing the type path in Java class file
* format.
* @param offset
* the offset of the first byte of the type path in 'b'.
*/
TypePath(byte[] b, int offset) {
this.b = b;
this.offset = offset;
}
/**
* Returns the length of this path.
*
* @return the length of this path.
*/
public int getLength() {
return b[offset];
}
/**
* Returns the value of the given step of this path.
*
* @param index
* an index between 0 and {@link #getLength()}, exclusive.
* @return {@link #ARRAY_ELEMENT ARRAY_ELEMENT}, {@link #INNER_TYPE
* INNER_TYPE}, {@link #WILDCARD_BOUND WILDCARD_BOUND}, or
* {@link #TYPE_ARGUMENT TYPE_ARGUMENT}.
*/
public int getStep(int index) {
return b[offset + 2 * index + 1];
}
/**
* Returns the index of the type argument that the given step is stepping
* into. This method should only be used for steps whose value is
* {@link #TYPE_ARGUMENT TYPE_ARGUMENT}.
*
* @param index
* an index between 0 and {@link #getLength()}, exclusive.
* @return the index of the type argument that the given step is stepping
* into.
*/
public int getStepArgument(int index) {
return b[offset + 2 * index + 2];
}
/**
* Converts a type path in string form, in the format used by
* {@link #toString()}, into a TypePath object.
*
* @param typePath
* a type path in string form, in the format used by
* {@link #toString()}. May be null or empty.
* @return the corresponding TypePath object, or null if the path is empty.
*/
public static TypePath fromString(final String typePath) {
if (typePath == null || typePath.length() == 0) {
return null;
}
int n = typePath.length();
ByteVector out = new ByteVector(n);
out.putByte(0);
for (int i = 0; i < n;) {
char c = typePath.charAt(i++);
if (c == '[') {
out.put11(ARRAY_ELEMENT, 0);
} else if (c == '.') {
out.put11(INNER_TYPE, 0);
} else if (c == '*') {
out.put11(WILDCARD_BOUND, 0);
} else if (c >= '0' && c <= '9') {
int typeArg = c - '0';
while (i < n && (c = typePath.charAt(i)) >= '0' && c <= '9') {
typeArg = typeArg * 10 + c - '0';
i += 1;
}
if (i < n && typePath.charAt(i) == ';') {
i += 1;
}
out.put11(TYPE_ARGUMENT, typeArg);
}
}
out.data[0] = (byte) (out.length / 2);
return new TypePath(out.data, 0);
}
/**
* Returns a string representation of this type path. {@link #ARRAY_ELEMENT
* ARRAY_ELEMENT} steps are represented with '[', {@link #INNER_TYPE
* INNER_TYPE} steps with '.', {@link #WILDCARD_BOUND WILDCARD_BOUND} steps
* with '*' and {@link #TYPE_ARGUMENT TYPE_ARGUMENT} steps with their type
* argument index in decimal form followed by ';'.
*/
@Override
public String toString() {
int length = getLength();
StringBuilder result = new StringBuilder(length * 2);
for (int i = 0; i < length; ++i) {
switch (getStep(i)) {
case ARRAY_ELEMENT:
result.append('[');
break;
case INNER_TYPE:
result.append('.');
break;
case WILDCARD_BOUND:
result.append('*');
break;
case TYPE_ARGUMENT:
result.append(getStepArgument(i)).append(';');
break;
default:
result.append('_');
}
}
return result.toString();
}
}
|
package net.sourceforge.texlipse.viewer;
import java.io.File;
import java.text.MessageFormat;
import java.util.ArrayList;
import net.sourceforge.texlipse.TexlipsePlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/**
* Viewer configuration editor.
* This dialog can be used for editing old configs or creating new ones.
*
* @author Kimmo Karlsson
* @author Tor Arne Vestb
*/
public class ViewerConfigDialog extends Dialog {
private static final String[] inverseSearchValues = new String[] { ViewerAttributeRegistry.INVERSE_SEARCH_NO, ViewerAttributeRegistry.INVERSE_SEARCH_RUN, ViewerAttributeRegistry.INVERSE_SEARCH_STD };
protected File lastPath;
private Text fileField;
private Text nameField;
private Text argsField;
private DDEGroup ddeViewGroup;
private DDEGroup ddeCloseGroup;
private Combo formatChooser;
private Combo inverseChooser;
private Label statusField;
private ViewerAttributeRegistry registry;
private ArrayList nameList;
private boolean newConfig;
private Button forwardChoice;
/**
* Create a new config editor dialog.
* @param parentShell shell of the creating component
*/
public ViewerConfigDialog(Shell parentShell, ViewerAttributeRegistry reg) {
super(parentShell);
registry = reg;
newConfig = false;
}
/**
* Create a new config creator dialog.
* @param parentShell shell of the creating component
* @param nameList list of existing viewer configuration names
*/
public ViewerConfigDialog(Shell parentShell, ArrayList nameList) {
super(parentShell);
registry = new ViewerAttributeRegistry();
registry.setActiveViewer(ViewerAttributeRegistry.VIEWER_NONE);
this.nameList = nameList;
newConfig = true;
}
/**
* Set status field message.
* @param key message text key on resource bundle
* @param info value of the text parameter (%s)
*/
protected void setStatus(String key, String info) {
String msg = "";
if (key != null && key.length() > 0) {
msg = TexlipsePlugin.getResourceString(key);
if (msg.indexOf("%s") >= 0) {
msg = msg.replaceAll("%s", info);
}
}
statusField.setText(msg);
}
/**
* Set dialog title when the window is created.
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
if (newConfig) {
newShell.setText(TexlipsePlugin.getResourceString("preferenceViewerDialogAddTitle"));
} else {
newShell.setText(TexlipsePlugin.getResourceString("preferenceViewerDialogEditTitle"));
}
}
/**
* Should be called after dialog has been closed.
* @return the viewer registry containing the dialog contents
*/
public ViewerAttributeRegistry getRegistry() {
return registry;
}
/**
* Check that the config is valid.
* Close the dialog is the config is valid.
*/
protected void okPressed() {
String name = nameField.getText();
if (name == null || name.length() == 0) {
setStatus("preferenceViewerDialogNameEmpty", "");
return;
}
// if adding new configuration, existing name is not valid
if (nameList != null && nameList.contains(name)) {
setStatus("preferenceViewerDialogNameExists", name);
return;
}
File f = new File(fileField.getText());
if (!f.exists()) {
setStatus("preferenceViewerDialogFileNotFound", f.getAbsolutePath());
return;
}
registry.setActiveViewer(name);
registry.setCommand(fileField.getText());
registry.setArguments(argsField.getText());
registry.setDDEViewCommand(ddeViewGroup.command.getText());
registry.setDDEViewServer(ddeViewGroup.server.getText());
registry.setDDEViewTopic(ddeViewGroup.topic.getText());
registry.setDDECloseCommand(ddeCloseGroup.command.getText());
registry.setDDECloseServer(ddeCloseGroup.server.getText());
registry.setDDECloseTopic(ddeCloseGroup.topic.getText());
registry.setFormat(formatChooser.getItem(formatChooser.getSelectionIndex()));
registry.setInverse(inverseSearchValues[inverseChooser.getSelectionIndex()]);
registry.setForward(forwardChoice.getSelection());
// Ask user if launch configs should be updated
try {
ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
if (manager != null) {
ILaunchConfigurationType type = manager.getLaunchConfigurationType(
TexLaunchConfigurationDelegate.CONFIGURATION_ID);
if (type != null) {
ILaunchConfiguration[] configs = manager.getLaunchConfigurations(type);
if (configs != null) {
// Check all configurations
int returnCode = 0;
MessageDialogWithToggle md = null;
for (int i = 0; i < configs.length ; i++) {
ILaunchConfiguration c = configs[i];
if (c.getType().getIdentifier().equals(TexLaunchConfigurationDelegate.CONFIGURATION_ID)) {
if (c.getAttribute("viewerCurrent", "").equals(name)) {
// We've found a config which was based on this viewer
if (0 == returnCode) {
String message = MessageFormat.format(
TexlipsePlugin.getResourceString("preferenceViewerUpdateConfigurationQuestion"),
new Object[] { c.getName() });
md = MessageDialogWithToggle.openYesNoCancelQuestion(getShell(),
TexlipsePlugin.getResourceString("preferenceViewerUpdateConfigurationTitle"), message,
TexlipsePlugin.getResourceString("preferenceViewerUpdateConfigurationAlwaysApply"),
false, null, null);
if (md.getReturnCode() == MessageDialogWithToggle.CANCEL)
return;
returnCode = md.getReturnCode();
}
// If answer was yes, update each config with latest values from registry
if (returnCode == IDialogConstants.YES_ID) {
ILaunchConfigurationWorkingCopy workingCopy = c.getWorkingCopy();
workingCopy.setAttributes(registry.asMap());
// We need to set at least one attribute using a one-shot setter method
// because the method setAttributes does not mark the config as dirty.
// A dirty config is required for a doSave to do anything useful.
workingCopy.setAttribute("viewerCurrent", name);
workingCopy.doSave();
}
// Reset return-code if we should be asked again
if (!md.getToggleState()) {
returnCode = 0;
}
}
}
}
}
}
}
} catch (CoreException e) {
// Something wrong with the config, or could not read attributes, so swallow and skip
}
setReturnCode(OK);
close();
}
/**
* Create the contents of the dialog.
* @param parent parent component
*/
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
GridLayout gl = (GridLayout) composite.getLayout();
gl.numColumns = 2;
Label descrLabel = new Label(composite, SWT.LEFT);
descrLabel.setText(TexlipsePlugin.getResourceString("preferenceViewerDescriptionLabel"));
GridData dgd = new GridData(GridData.FILL_HORIZONTAL);
dgd.horizontalSpan = 2;
descrLabel.setLayoutData(dgd);
addConfigNameField(composite);
addFileBrowser(composite);
addArgumentsField(composite);
addDDEGroups(composite);
addFormatChooser(composite);
addInverseChooser(composite);
addForwardChooser(composite);
Group group = new Group(composite, SWT.SHADOW_IN);
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
((GridData)group.getLayoutData()).horizontalSpan = 2;
group.setLayout(new GridLayout());
statusField = new Label(group, SWT.LEFT);
statusField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
statusField.setText(resolveStatus());
statusField.setToolTipText(TexlipsePlugin.getResourceString("preferenceViewerStatusTooltip"));
return composite;
}
/**
* @return an initial status message for the status field
*/
private String resolveStatus() {
String path = fileField.getText();
if (path != null && path.length() > 0) {
File file = new File(path);
if (!file.exists()) {
Button b = getButton(IDialogConstants.OK_ID);
if (b != null) {
// set button status
b.setEnabled(false);
}
return TexlipsePlugin.getResourceString("preferenceViewerDialogFileNotFound").replaceAll("%s", path);
}
}
Button b = getButton(IDialogConstants.OK_ID);
if (b != null) {
// set button status
b.setEnabled(true);
}
return TexlipsePlugin.getResourceString("preferenceViewerDialogFileOk");
}
/**
* Creates the configuration name text field.
* @param composite parent component
*/
private void addConfigNameField(Composite composite) {
Label nameLabel = new Label(composite, SWT.LEFT);
nameLabel.setText(TexlipsePlugin.getResourceString("preferenceViewerNameLabel"));
nameLabel.setToolTipText(TexlipsePlugin.getResourceString("preferenceViewerNameTooltip"));
nameLabel.setLayoutData(new GridData());
int rw = newConfig ? 0 : SWT.READ_ONLY;
nameField = new Text(composite, SWT.SINGLE | SWT.BORDER | rw);
nameField.setText(registry.getActiveViewer());
nameField.setToolTipText(TexlipsePlugin.getResourceString("preferenceViewerNameTooltip"));
nameField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
}
/**
* Creates the executable browsing component.
* @param composite parent component
*/
private void addFileBrowser(Composite composite) {
Label fileLabel = new Label(composite, SWT.LEFT);
fileLabel.setText(TexlipsePlugin.getResourceString("preferenceViewerCommandLabel"));
fileLabel.setToolTipText(TexlipsePlugin.getResourceString("preferenceViewerCommandTooltip"));
fileLabel.setLayoutData(new GridData());
Composite browser = new Composite(composite, SWT.NONE);
browser.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridLayout bgl = new GridLayout();
bgl.numColumns = 2;
browser.setLayout(bgl);
fileField = new Text(browser, SWT.SINGLE | SWT.BORDER);
fileField.setText(registry.getCommand());
fileField.setToolTipText(TexlipsePlugin.getResourceString("preferenceViewerCommandTooltip"));
fileField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
fileField.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
statusField.setText(resolveStatus());
}});
Button browseButton = new Button(browser, SWT.PUSH);
browseButton.setText(JFaceResources.getString("openBrowse"));
browseButton.setLayoutData(new GridData());
browseButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
FileDialog dialog = new FileDialog(getShell());
if (lastPath != null) {
if (lastPath.exists()) {
dialog.setFilterPath(lastPath.getAbsolutePath());
}
} else {
lastPath = new File(fileField.getText());
while (lastPath != null && !lastPath.isDirectory()) {
lastPath = lastPath.getParentFile();
}
if (lastPath != null && lastPath.exists()) {
dialog.setFilterPath(lastPath.getAbsolutePath());
}
}
String dir = dialog.open();
if (dir != null) {
lastPath = new File(dir.trim());
if (lastPath.exists()) {
fileField.setText(lastPath.getAbsolutePath());
registry.setCommand(fileField.getText());
} else {
lastPath = null;
}
}
}});
}
/**
* Creates the command arguments field to the dialog.
* @param composite parent component
*/
private void addArgumentsField(Composite composite) {
Label argsLabel = new Label(composite, SWT.LEFT);
argsLabel.setText(TexlipsePlugin.getResourceString("preferenceViewerArgumentLabel"));
argsLabel.setToolTipText(TexlipsePlugin.getResourceString("preferenceViewerArgumentTooltip"));
argsLabel.setLayoutData(new GridData());
argsField = new Text(composite, SWT.SINGLE | SWT.BORDER);
argsField.setText(registry.getArguments());
argsField.setToolTipText(TexlipsePlugin.getResourceString("preferenceViewerArgumentTooltip"));
argsField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
}
/**
* Creates the two groups for DDE view and close
*
* @param composite
* parent component
*/
private void addDDEGroups(Composite composite) {
ddeViewGroup = new DDEGroup(composite,
TexlipsePlugin.getResourceString("preferenceViewerDDEViewLabel"),
TexlipsePlugin.getResourceString("preferenceViewerDDEViewTooltip"));
ddeViewGroup.command.setText(registry.getDDEViewCommand());
ddeViewGroup.server.setText(registry.getDDEViewServer());
ddeViewGroup.topic.setText(registry.getDDEViewTopic());
ddeCloseGroup = new DDEGroup(composite,
TexlipsePlugin.getResourceString("preferenceViewerDDECloseLabel"),
TexlipsePlugin.getResourceString("preferenceViewerDDECloseTooltip"));
ddeCloseGroup.command.setText(registry.getDDECloseCommand());
ddeCloseGroup.server.setText(registry.getDDECloseServer());
ddeCloseGroup.topic.setText(registry.getDDECloseTopic());
// Only show DDE configuration if on Win32
if (Platform.getOS().equals(Platform.OS_WIN32)) {
ddeViewGroup.setVisible(true);
ddeCloseGroup.setVisible(true);
}
}
/**
* Creates the file format chooser to the page.
* @param composite parent component
*/
private void addFormatChooser(Composite composite) {
Label formatLabel = new Label(composite, SWT.LEFT);
formatLabel.setText(TexlipsePlugin.getResourceString("preferenceViewerFormatLabel"));
formatLabel.setToolTipText(TexlipsePlugin.getResourceString("preferenceViewerFormatTooltip"));
formatLabel.setLayoutData(new GridData());
formatChooser = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY);
formatChooser.setLayoutData(new GridData());
formatChooser.setToolTipText(TexlipsePlugin.getResourceString("preferenceViewerFormatTooltip"));
formatChooser.setItems(registry.getFormatList());
formatChooser.select(formatChooser.indexOf(registry.getFormat()));
}
/**
* Creates the additional controls of the page.
* @param parent parent component
*/
private void addInverseChooser(Composite parent) {
Label label = new Label(parent, SWT.LEFT);
label.setText(TexlipsePlugin.getResourceString("preferenceViewerInverseLabel"));
label.setToolTipText(TexlipsePlugin.getResourceString("preferenceViewerInverseTooltip"));
label.setLayoutData(new GridData());
String[] list = new String[] {
TexlipsePlugin.getResourceString("preferenceViewerInverseSearchNo"),
TexlipsePlugin.getResourceString("preferenceViewerInverseSearchRun"),
TexlipsePlugin.getResourceString("preferenceViewerInverseSearchStd")
};
// find out which option to choose by default
int index = 0;
while (index < inverseSearchValues.length &&
!inverseSearchValues[index].equals(registry.getInverse())) {
index++;
}
inverseChooser = new Combo(parent, SWT.DROP_DOWN | SWT.READ_ONLY);
inverseChooser.setLayoutData(new GridData());
inverseChooser.setToolTipText(TexlipsePlugin.getResourceString("preferenceViewerInverseTooltip"));
inverseChooser.setItems(list);
inverseChooser.select(index);
}
/**
* Creates the forward search support -checkbox.
* @param parent parent component
*/
private void addForwardChooser(Composite parent) {
forwardChoice = new Button(parent, SWT.CHECK);
forwardChoice.setText(TexlipsePlugin.getResourceString("preferenceViewerForwardLabel"));
GridData gd = new GridData();
gd.horizontalSpan = 2;
forwardChoice.setLayoutData(gd);
forwardChoice.setSelection(registry.getForward());
}
private class DDEGroup extends Composite {
// Public members since the class is private to the dialog
public Text command;
public Text server;
public Text topic;
public DDEGroup(Composite parent, String name, String toolTip) {
super(parent, SWT.NONE);
setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
((GridData)getLayoutData()).horizontalSpan = 2;
setLayout( new GridLayout());
Group group = new Group(this, SWT.SHADOW_IN);
group.setText(name);
group.setToolTipText(toolTip);
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setLayout(new GridLayout(4, false));
Label ddeCommandLabel = new Label(group, SWT.LEFT);
ddeCommandLabel.setText(TexlipsePlugin.getResourceString("preferenceViewerDDECommandLabel"));
ddeCommandLabel.setToolTipText(TexlipsePlugin.getResourceString("preferenceViewerDDECommandTooltip"));
ddeCommandLabel.setLayoutData(new GridData());
command = new Text(group, SWT.SINGLE | SWT.BORDER);
command.setToolTipText(TexlipsePlugin.getResourceString("preferenceViewerDDECommandTooltip"));
command.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
((GridData) command.getLayoutData()).horizontalSpan = 3;
Label ddeServerLabel = new Label(group, SWT.LEFT);
ddeServerLabel.setText(TexlipsePlugin.getResourceString("preferenceViewerDDEServerLabel"));
ddeServerLabel.setToolTipText(TexlipsePlugin.getResourceString("preferenceViewerDDEServerTooltip"));
ddeServerLabel.setLayoutData(new GridData());
server = new Text(group, SWT.SINGLE | SWT.BORDER);
server.setToolTipText(TexlipsePlugin.getResourceString("preferenceViewerDDEServerTooltip"));
server.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label ddeTopicLabel = new Label(group, SWT.LEFT);
ddeTopicLabel.setText(TexlipsePlugin.getResourceString("preferenceViewerDDETopicLabel"));
ddeTopicLabel.setToolTipText(TexlipsePlugin.getResourceString("preferenceViewerDDETopicTooltip"));
ddeTopicLabel.setLayoutData(new GridData());
topic = new Text(group, SWT.SINGLE | SWT.BORDER);
topic.setToolTipText(TexlipsePlugin.getResourceString("preferenceViewerDDETopicTooltip"));
topic.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
setVisible(false);
}
}
}
|
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package jodd.joy.core;
import jodd.madvoc.WebApplication;
import jodd.madvoc.config.AutomagicMadvocConfigurator;
import jodd.madvoc.petite.PetiteWebApplication;
import jodd.madvoc.proxetta.ProxettaAwareActionsManager;
import jodd.petite.PetiteContainer;
/**
* Default web application.
*/
public abstract class DefaultWebApplication extends PetiteWebApplication {
protected final DefaultAppCore defaultAppCore;
protected DefaultWebApplication() {
defaultAppCore = createAppCore();
}
/**
* Creates {@link DefaultAppCore}.
*/
protected abstract DefaultAppCore createAppCore();
/**
* Starts {@link DefaultAppCore application core} before web application is initialized.
*/
@Override
public WebApplication start() {
defaultAppCore.start();
return super.start();
}
/**
* Registers default and additional {@link ProxettaAwareActionsManager}.
*/
@Override
protected final void registerMadvocComponents() {
super.registerMadvocComponents();
// todo add proxetta provider? i.e. add add AppCore provider!!!
madvocContainer.registerComponentInstance(new ProxettaAwareActionsManager(defaultAppCore.getProxetta()));
}
/**
* Defines application container for Madvoc usage. We share applications
* Petite container from the appCore, so Madvoc can use it when creating
* Madvoc actions. By sharing the application container with the Madvoc,
* Petite beans can be injected in the actions.
* <p>
* If container is not shared, PetiteWebApplication would create
* new Petite container; that is fine when e.g. there are no layers.
*/
@Override
protected PetiteContainer providePetiteContainer() {
return defaultAppCore.getPetite();
}
/**
* Configures <code>AutomagicMadvocConfigurator</code>.
* todo remove this by adding special class for configuration that takes the appCore and its AppScanner.
*/
@Deprecated
public void configure(Object configurator) {
if (configurator instanceof AutomagicMadvocConfigurator) {
AutomagicMadvocConfigurator madvocConfigurator = (AutomagicMadvocConfigurator) configurator;
defaultAppCore.getAppScanner().configure(madvocConfigurator);
}
}
/**
* Destroys application context and Madvoc.
*/
@Override
public void shutdown() {
defaultAppCore.stop();
super.shutdown();
}
}
|
// LegacyImageMap.java
package imagej.legacy;
import ij.ImagePlus;
import ij.gui.ImageWindow;
import ij.gui.Roi;
import imagej.data.Dataset;
import imagej.data.display.ImageDisplay;
import imagej.data.roi.Overlay;
import imagej.event.EventService;
import imagej.event.EventSubscriber;
import imagej.ext.display.event.DisplayDeletedEvent;
import imagej.legacy.translate.DefaultImageTranslator;
import imagej.legacy.translate.ImageTranslator;
import imagej.legacy.translate.LegacyUtils;
import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
/**
* An image map between IJ1 {@link ImagePlus} objects and IJ2
* {@link ImageDisplay}s. Because every {@link ImagePlus} has a corresponding
* {@link ImageWindow} and vice versa, it works out best to associate each
* {@link ImagePlus} with a {@link ImageDisplay} rather than with a
* {@link Dataset}.
* <p>
* Any {@link Overlay}s present in the {@link ImageDisplay} are translated to a
* {@link Roi} attached to the {@link ImagePlus}, and vice versa.
* </p>
* <p>
* In the case of one {@link Dataset} belonging to multiple {@link ImageDisplay}
* s, there is a separate {@link ImagePlus} for each {@link ImageDisplay}, with
* pixels by reference.
* </p>
* <p>
* In the case of multiple {@link Dataset}s in a single {@link ImageDisplay},
* only the first {@link Dataset} is translated to the {@link ImagePlus}.
* </p>
*
* @author Curtis Rueden
* @author Barry DeZonia
*/
public class LegacyImageMap {
// -- Fields --
/** Table of {@link ImagePlus} objects corresponding to {@link ImageDisplay}s. */
private final Map<ImageDisplay, ImagePlus> imagePlusTable;
/**
* Table of {@link ImageDisplay} objects corresponding to {@link ImagePlus}es.
*/
private final Map<ImagePlus, ImageDisplay> displayTable;
/**
* The {@link ImageTranslator} to use when creating {@link ImagePlus} and
* {@link ImageDisplay} objects corresponding to one another.
*/
private final DefaultImageTranslator imageTranslator;
/** List of event subscribers, to avoid garbage collection. */
private final ArrayList<EventSubscriber<?>> subscribers;
private final EventService eventService;
// -- Constructor --
public LegacyImageMap(final EventService eventService) {
this.eventService = eventService;
imagePlusTable = new ConcurrentHashMap<ImageDisplay, ImagePlus>();
displayTable = new ConcurrentHashMap<ImagePlus, ImageDisplay>();
imageTranslator = new DefaultImageTranslator();
subscribers = new ArrayList<EventSubscriber<?>>();
subscribeToEvents();
}
// -- LegacyImageMap methods --
/**
* Gets the {@link ImageDisplay} corresponding to the given {@link ImagePlus},
* or null if there is no existing table entry.
*/
public ImageDisplay lookupDisplay(final ImagePlus imp) {
if (imp == null) return null;
return displayTable.get(imp);
}
/**
* Gets the {@link ImagePlus} corresponding to the given {@link ImageDisplay},
* or null if there is no existing table entry.
*/
public ImagePlus lookupImagePlus(final ImageDisplay display) {
if (display == null) return null;
return imagePlusTable.get(display);
}
/**
* Ensures that the given {@link ImageDisplay} has a corresponding legacy
* image.
*
* @return the {@link ImagePlus} object shadowing the given
* {@link ImageDisplay}, creating it if necessary using the
* {@link ImageTranslator}.
*/
public ImagePlus registerDisplay(final ImageDisplay display) {
ImagePlus imp = lookupImagePlus(display);
if (imp == null) {
// mapping does not exist; mirror display to image window
imp = imageTranslator.createLegacyImage(display);
addMapping(display, imp);
// Note - we need to register ImagePlus with IJ1 also
new ImageWindow(imp);
}
return imp;
}
/**
* Ensures that the given legacy image has a corresponding
* {@link ImageDisplay}.
*
* @return the {@link ImageDisplay} object shadowing the given
* {@link ImagePlus}, creating it if necessary using the
* {@link ImageTranslator}.
*/
public ImageDisplay registerLegacyImage(final ImagePlus imp) {
ImageDisplay display = lookupDisplay(imp);
if (display == null) {
// mapping does not exist; mirror legacy image to display
display = imageTranslator.createDisplay(imp);
addMapping(display, imp);
}
return display;
}
/** Removes the mapping associated with the given {@link ImageDisplay}. */
public void unregisterDisplay(final ImageDisplay display) {
final ImagePlus imp = lookupImagePlus(display);
removeMapping(display, imp);
}
/** Removes the mapping associated with the given {@link ImagePlus}. */
public void unregisterLegacyImage(final ImagePlus imp) {
final ImageDisplay display = lookupDisplay(imp);
removeMapping(display, imp);
}
// -- Helper methods --
private void addMapping(final ImageDisplay display, final ImagePlus imp) {
// System.out.println("CREATE MAPPING "+display+" to "+imp+" isComposite()="+imp.isComposite());
// Must remove old mappings to avoid memory leaks
// Removal is tricky for the displayTable. Without removal different
// ImagePluses and CompositeImages can point to the same ImageDisplay. To
// avoid a memory leak and to stay consistent in our mappings we find
// all current mappings and remove them before inserting new ones. This
// ensures that a ImageDisplay is only linked with one ImagePlus or
// CompositeImage.
imagePlusTable.remove(display);
for (final Entry<ImagePlus, ImageDisplay> entry : displayTable.entrySet()) {
if (entry.getValue() == display) {
displayTable.remove(entry.getKey());
}
}
imagePlusTable.put(display, imp);
displayTable.put(imp, display);
}
private void removeMapping(final ImageDisplay display, final ImagePlus imp) {
// System.out.println("REMOVE MAPPING "+display+" to "+imp+" isComposite()="+imp.isComposite());
if (display != null) {
imagePlusTable.remove(display);
}
if (imp != null) {
displayTable.remove(imp);
LegacyUtils.deleteImagePlus(imp);
}
}
private void subscribeToEvents() {
/* Removing this code to fix bug #835. Rely on LegacyPlugin to create
ImagePluses as they are needed.
final EventSubscriber<DisplayCreatedEvent> creationSubscriber =
new EventSubscriber<DisplayCreatedEvent>() {
@Override
public void onEvent(final DisplayCreatedEvent event) {
if(event.getObject() instanceof ImageDisplay)
registerDisplay((ImageDisplay)event.getObject());
}
};
subscribers.add(creationSubscriber);
eventService.subscribe(DisplayCreatedEvent.class, creationSubscriber);
*/
final EventSubscriber<DisplayDeletedEvent> deletionSubscriber =
new EventSubscriber<DisplayDeletedEvent>() {
@Override
public void onEvent(final DisplayDeletedEvent event) {
// Need to make sure:
// - IJ2 Windows always close when IJ1 close expected
// Stack to Images, Split Channels, etc.
// - No ImagePlus/Display mapping becomes a zombie in the
// LegacyImageMap failing to get garbage collected.
// - That IJ2 does not think IJ1 initiated the ij1.close()
if (event.getObject() instanceof ImageDisplay) {
final ImagePlus imp =
lookupImagePlus((ImageDisplay) event.getObject());
if (imp != null) LegacyOutputTracker.closeInitiatedByIJ2(imp);
unregisterDisplay((ImageDisplay) event.getObject());
if (imp != null) LegacyOutputTracker.closeCompletedByIJ2(imp);
}
}
};
subscribers.add(deletionSubscriber);
eventService.subscribe(DisplayDeletedEvent.class, deletionSubscriber);
}
}
|
package org.jfree.chart.renderer.xy;
import java.awt.AlphaComposite;
import java.awt.Composite;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import org.jfree.chart.LegendItem;
import org.jfree.chart.LegendItemCollection;
import org.jfree.chart.annotations.XYAnnotation;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.entity.XYItemEntity;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardXYSeriesLabelGenerator;
import org.jfree.chart.labels.XYItemLabelGenerator;
import org.jfree.chart.labels.XYSeriesLabelGenerator;
import org.jfree.chart.labels.XYToolTipGenerator;
import org.jfree.chart.plot.CrosshairState;
import org.jfree.chart.plot.DrawingSupplier;
import org.jfree.chart.plot.IntervalMarker;
import org.jfree.chart.plot.Marker;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.ValueMarker;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.AbstractRenderer;
import org.jfree.chart.urls.XYURLGenerator;
import org.jfree.data.Range;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.xy.XYDataset;
import org.jfree.text.TextUtilities;
import org.jfree.ui.GradientPaintTransformer;
import org.jfree.ui.Layer;
import org.jfree.ui.LengthAdjustmentType;
import org.jfree.ui.RectangleAnchor;
import org.jfree.ui.RectangleInsets;
import org.jfree.util.ObjectList;
import org.jfree.util.ObjectUtilities;
import org.jfree.util.PublicCloneable;
/**
* A base class that can be used to create new {@link XYItemRenderer}
* implementations.
*/
public abstract class AbstractXYItemRenderer extends AbstractRenderer
implements XYItemRenderer,
Cloneable,
Serializable {
/** For serialization. */
private static final long serialVersionUID = 8019124836026607990L;
/** The plot. */
private XYPlot plot;
/**
* The item label generator for ALL series.
*
* @deprecated This field is redundant, use itemLabelGeneratorList and
* baseItemLabelGenerator instead. Deprecated as of version 1.0.6.
*/
private XYItemLabelGenerator itemLabelGenerator;
/** A list of item label generators (one per series). */
private ObjectList itemLabelGeneratorList;
/** The base item label generator. */
private XYItemLabelGenerator baseItemLabelGenerator;
/**
* The tool tip generator for ALL series.
*
* @deprecated This field is redundant, use tooltipGeneratorList and
* baseToolTipGenerator instead. Deprecated as of version 1.0.6.
*/
private XYToolTipGenerator toolTipGenerator;
/** A list of tool tip generators (one per series). */
private ObjectList toolTipGeneratorList;
/** The base tool tip generator. */
private XYToolTipGenerator baseToolTipGenerator;
/** The URL text generator. */
private XYURLGenerator urlGenerator;
/**
* Annotations to be drawn in the background layer ('underneath' the data
* items).
*/
private List backgroundAnnotations;
/**
* Annotations to be drawn in the foreground layer ('on top' of the data
* items).
*/
private List foregroundAnnotations;
/** The default radius for the entity 'hotspot' */
private int defaultEntityRadius;
/** The legend item label generator. */
private XYSeriesLabelGenerator legendItemLabelGenerator;
/** The legend item tool tip generator. */
private XYSeriesLabelGenerator legendItemToolTipGenerator;
/** The legend item URL generator. */
private XYSeriesLabelGenerator legendItemURLGenerator;
/**
* Creates a renderer where the tooltip generator and the URL generator are
* both <code>null</code>.
*/
protected AbstractXYItemRenderer() {
super();
this.itemLabelGenerator = null;
this.itemLabelGeneratorList = new ObjectList();
this.toolTipGenerator = null;
this.toolTipGeneratorList = new ObjectList();
this.urlGenerator = null;
this.backgroundAnnotations = new java.util.ArrayList();
this.foregroundAnnotations = new java.util.ArrayList();
this.defaultEntityRadius = 3;
this.legendItemLabelGenerator = new StandardXYSeriesLabelGenerator(
"{0}");
}
/**
* Returns the number of passes through the data that the renderer requires
* in order to draw the chart. Most charts will require a single pass, but
* some require two passes.
*
* @return The pass count.
*/
public int getPassCount() {
return 1;
}
/**
* Returns the plot that the renderer is assigned to.
*
* @return The plot (possibly <code>null</code>).
*/
public XYPlot getPlot() {
return this.plot;
}
/**
* Sets the plot that the renderer is assigned to.
*
* @param plot the plot (<code>null</code> permitted).
*/
public void setPlot(XYPlot plot) {
this.plot = plot;
}
/**
* Initialises the renderer and returns a state object that should be
* passed to all subsequent calls to the drawItem() method.
* <P>
* This method will be called before the first item is rendered, giving the
* renderer an opportunity to initialise any state information it wants to
* maintain. The renderer can do nothing if it chooses.
*
* @param g2 the graphics device.
* @param dataArea the area inside the axes.
* @param plot the plot.
* @param data the data.
* @param info an optional info collection object to return data back to
* the caller.
*
* @return The renderer state (never <code>null</code>).
*/
public XYItemRendererState initialise(Graphics2D g2,
Rectangle2D dataArea,
XYPlot plot,
XYDataset data,
PlotRenderingInfo info) {
XYItemRendererState state = new XYItemRendererState(info);
return state;
}
// ITEM LABEL GENERATOR
/**
* Returns the label generator for a data item. This implementation simply
* passes control to the {@link #getSeriesItemLabelGenerator(int)} method.
* If, for some reason, you want a different generator for individual
* items, you can override this method.
*
* @param series the series index (zero based).
* @param item the item index (zero based).
*
* @return The generator (possibly <code>null</code>).
*/
public XYItemLabelGenerator getItemLabelGenerator(int series, int item) {
// return the generator for ALL series, if there is one...
if (this.itemLabelGenerator != null) {
return this.itemLabelGenerator;
}
// otherwise look up the generator table
XYItemLabelGenerator generator
= (XYItemLabelGenerator) this.itemLabelGeneratorList.get(series);
if (generator == null) {
generator = this.baseItemLabelGenerator;
}
return generator;
}
/**
* Returns the item label generator for a series.
*
* @param series the series index (zero based).
*
* @return The generator (possibly <code>null</code>).
*/
public XYItemLabelGenerator getSeriesItemLabelGenerator(int series) {
return (XYItemLabelGenerator) this.itemLabelGeneratorList.get(series);
}
/**
* Returns the item label generator override.
*
* @return The generator (possibly <code>null</code>).
*
* @since 1.0.5
*
* @see #setItemLabelGenerator(XYItemLabelGenerator)
*
* @deprecated As of version 1.0.6, this override setting should not be
* used. You can use the base setting instead
* ({@link #getBaseItemLabelGenerator()}).
*/
public XYItemLabelGenerator getItemLabelGenerator() {
return this.itemLabelGenerator;
}
/**
* Sets the item label generator for ALL series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param generator the generator (<code>null</code> permitted).
*
* @see #getItemLabelGenerator()
*
* @deprecated As of version 1.0.6, this override setting should not be
* used. You can use the base setting instead
* ({@link #setBaseItemLabelGenerator(XYItemLabelGenerator)}).
*/
public void setItemLabelGenerator(XYItemLabelGenerator generator) {
this.itemLabelGenerator = generator;
notifyListeners(new RendererChangeEvent(this));
}
/**
* Sets the item label generator for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero based).
* @param generator the generator (<code>null</code> permitted).
*/
public void setSeriesItemLabelGenerator(int series,
XYItemLabelGenerator generator) {
this.itemLabelGeneratorList.set(series, generator);
notifyListeners(new RendererChangeEvent(this));
}
/**
* Returns the base item label generator.
*
* @return The generator (possibly <code>null</code>).
*/
public XYItemLabelGenerator getBaseItemLabelGenerator() {
return this.baseItemLabelGenerator;
}
/**
* Sets the base item label generator and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param generator the generator (<code>null</code> permitted).
*/
public void setBaseItemLabelGenerator(XYItemLabelGenerator generator) {
this.baseItemLabelGenerator = generator;
notifyListeners(new RendererChangeEvent(this));
}
// TOOL TIP GENERATOR
/**
* Returns the tool tip generator for a data item. If, for some reason,
* you want a different generator for individual items, you can override
* this method.
*
* @param series the series index (zero based).
* @param item the item index (zero based).
*
* @return The generator (possibly <code>null</code>).
*/
public XYToolTipGenerator getToolTipGenerator(int series, int item) {
// return the generator for ALL series, if there is one...
if (this.toolTipGenerator != null) {
return this.toolTipGenerator;
}
// otherwise look up the generator table
XYToolTipGenerator generator
= (XYToolTipGenerator) this.toolTipGeneratorList.get(series);
if (generator == null) {
generator = this.baseToolTipGenerator;
}
return generator;
}
/**
* Returns the override tool tip generator.
*
* @return The tool tip generator (possible <code>null</code>).
*
* @since 1.0.5
*
* @see #setToolTipGenerator(XYToolTipGenerator)
*
* @deprecated As of version 1.0.6, this override setting should not be
* used. You can use the base setting instead
* ({@link #getBaseToolTipGenerator()}).
*/
public XYToolTipGenerator getToolTipGenerator() {
return this.toolTipGenerator;
}
/**
* Sets the tool tip generator for ALL series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param generator the generator (<code>null</code> permitted).
*
* @see #getToolTipGenerator()
*
* @deprecated As of version 1.0.6, this override setting should not be
* used. You can use the base setting instead
* ({@link #setBaseToolTipGenerator(XYToolTipGenerator)}).
*/
public void setToolTipGenerator(XYToolTipGenerator generator) {
this.toolTipGenerator = generator;
notifyListeners(new RendererChangeEvent(this));
}
/**
* Returns the tool tip generator for a series.
*
* @param series the series index (zero based).
*
* @return The generator (possibly <code>null</code>).
*/
public XYToolTipGenerator getSeriesToolTipGenerator(int series) {
return (XYToolTipGenerator) this.toolTipGeneratorList.get(series);
}
/**
* Sets the tool tip generator for a series and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param series the series index (zero based).
* @param generator the generator (<code>null</code> permitted).
*/
public void setSeriesToolTipGenerator(int series,
XYToolTipGenerator generator) {
this.toolTipGeneratorList.set(series, generator);
notifyListeners(new RendererChangeEvent(this));
}
/**
* Returns the base tool tip generator.
*
* @return The generator (possibly <code>null</code>).
*
* @see #setBaseToolTipGenerator(XYToolTipGenerator)
*/
public XYToolTipGenerator getBaseToolTipGenerator() {
return this.baseToolTipGenerator;
}
/**
* Sets the base tool tip generator and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param generator the generator (<code>null</code> permitted).
*
* @see #getBaseToolTipGenerator()
*/
public void setBaseToolTipGenerator(XYToolTipGenerator generator) {
this.baseToolTipGenerator = generator;
notifyListeners(new RendererChangeEvent(this));
}
// URL GENERATOR
/**
* Returns the URL generator for HTML image maps.
*
* @return The URL generator (possibly <code>null</code>).
*/
public XYURLGenerator getURLGenerator() {
return this.urlGenerator;
}
/**
* Sets the URL generator for HTML image maps.
*
* @param urlGenerator the URL generator (<code>null</code> permitted).
*/
public void setURLGenerator(XYURLGenerator urlGenerator) {
this.urlGenerator = urlGenerator;
notifyListeners(new RendererChangeEvent(this));
}
/**
* Adds an annotation and sends a {@link RendererChangeEvent} to all
* registered listeners. The annotation is added to the foreground
* layer.
*
* @param annotation the annotation (<code>null</code> not permitted).
*/
public void addAnnotation(XYAnnotation annotation) {
// defer argument checking
addAnnotation(annotation, Layer.FOREGROUND);
}
/**
* Adds an annotation to the specified layer.
*
* @param annotation the annotation (<code>null</code> not permitted).
* @param layer the layer (<code>null</code> not permitted).
*/
public void addAnnotation(XYAnnotation annotation, Layer layer) {
if (annotation == null) {
throw new IllegalArgumentException("Null 'annotation' argument.");
}
if (layer.equals(Layer.FOREGROUND)) {
this.foregroundAnnotations.add(annotation);
notifyListeners(new RendererChangeEvent(this));
}
else if (layer.equals(Layer.BACKGROUND)) {
this.backgroundAnnotations.add(annotation);
notifyListeners(new RendererChangeEvent(this));
}
else {
// should never get here
throw new RuntimeException("Unknown layer.");
}
}
/**
* Removes the specified annotation and sends a {@link RendererChangeEvent}
* to all registered listeners.
*
* @param annotation the annotation to remove (<code>null</code> not
* permitted).
*
* @return A boolean to indicate whether or not the annotation was
* successfully removed.
*/
public boolean removeAnnotation(XYAnnotation annotation) {
boolean removed = this.foregroundAnnotations.remove(annotation);
removed = removed & this.backgroundAnnotations.remove(annotation);
notifyListeners(new RendererChangeEvent(this));
return removed;
}
/**
* Removes all annotations and sends a {@link RendererChangeEvent}
* to all registered listeners.
*/
public void removeAnnotations() {
this.foregroundAnnotations.clear();
this.backgroundAnnotations.clear();
notifyListeners(new RendererChangeEvent(this));
}
/**
* Returns the radius of the circle used for the default entity area
* when no area is specified.
*
* @return A radius.
*/
public int getDefaultEntityRadius() {
return this.defaultEntityRadius;
}
/**
* Sets the radius of the circle used for the default entity area
* when no area is specified.
*
* @param radius the radius.
*/
public void setDefaultEntityRadius(int radius) {
this.defaultEntityRadius = radius;
}
/**
* Returns the legend item label generator.
*
* @return The label generator (never <code>null</code>).
*
* @see #setLegendItemLabelGenerator(XYSeriesLabelGenerator)
*/
public XYSeriesLabelGenerator getLegendItemLabelGenerator() {
return this.legendItemLabelGenerator;
}
/**
* Sets the legend item label generator and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param generator the generator (<code>null</code> not permitted).
*
* @see #getLegendItemLabelGenerator()
*/
public void setLegendItemLabelGenerator(XYSeriesLabelGenerator generator) {
if (generator == null) {
throw new IllegalArgumentException("Null 'generator' argument.");
}
this.legendItemLabelGenerator = generator;
notifyListeners(new RendererChangeEvent(this));
}
/**
* Returns the legend item tool tip generator.
*
* @return The tool tip generator (possibly <code>null</code>).
*
* @see #setLegendItemToolTipGenerator(XYSeriesLabelGenerator)
*/
public XYSeriesLabelGenerator getLegendItemToolTipGenerator() {
return this.legendItemToolTipGenerator;
}
/**
* Sets the legend item tool tip generator and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param generator the generator (<code>null</code> permitted).
*
* @see #getLegendItemToolTipGenerator()
*/
public void setLegendItemToolTipGenerator(
XYSeriesLabelGenerator generator) {
this.legendItemToolTipGenerator = generator;
notifyListeners(new RendererChangeEvent(this));
}
/**
* Returns the legend item URL generator.
*
* @return The URL generator (possibly <code>null</code>).
*
* @see #setLegendItemURLGenerator(XYSeriesLabelGenerator)
*/
public XYSeriesLabelGenerator getLegendItemURLGenerator() {
return this.legendItemURLGenerator;
}
/**
* Sets the legend item URL generator and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param generator the generator (<code>null</code> permitted).
*
* @see #getLegendItemURLGenerator()
*/
public void setLegendItemURLGenerator(XYSeriesLabelGenerator generator) {
this.legendItemURLGenerator = generator;
notifyListeners(new RendererChangeEvent(this));
}
/**
* Returns the lower and upper bounds (range) of the x-values in the
* specified dataset.
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @return The range (<code>null</code> if the dataset is <code>null</code>
* or empty).
*/
public Range findDomainBounds(XYDataset dataset) {
if (dataset != null) {
return DatasetUtilities.findDomainBounds(dataset, false);
}
else {
return null;
}
}
/**
* Returns the range of values the renderer requires to display all the
* items from the specified dataset.
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @return The range (<code>null</code> if the dataset is <code>null</code>
* or empty).
*/
public Range findRangeBounds(XYDataset dataset) {
if (dataset != null) {
return DatasetUtilities.findRangeBounds(dataset, false);
}
else {
return null;
}
}
/**
* Returns a (possibly empty) collection of legend items for the series
* that this renderer is responsible for drawing.
*
* @return The legend item collection (never <code>null</code>).
*/
public LegendItemCollection getLegendItems() {
if (this.plot == null) {
return new LegendItemCollection();
}
LegendItemCollection result = new LegendItemCollection();
int index = this.plot.getIndexOf(this);
XYDataset dataset = this.plot.getDataset(index);
if (dataset != null) {
int seriesCount = dataset.getSeriesCount();
for (int i = 0; i < seriesCount; i++) {
if (isSeriesVisibleInLegend(i)) {
LegendItem item = getLegendItem(index, i);
if (item != null) {
result.add(item);
}
}
}
}
return result;
}
/**
* Returns a default legend item for the specified series. Subclasses
* should override this method to generate customised items.
*
* @param datasetIndex the dataset index (zero-based).
* @param series the series index (zero-based).
*
* @return A legend item for the series.
*/
public LegendItem getLegendItem(int datasetIndex, int series) {
LegendItem result = null;
XYPlot xyplot = getPlot();
if (xyplot != null) {
XYDataset dataset = xyplot.getDataset(datasetIndex);
if (dataset != null) {
String label = this.legendItemLabelGenerator.generateLabel(
dataset, series);
String description = label;
String toolTipText = null;
if (getLegendItemToolTipGenerator() != null) {
toolTipText = getLegendItemToolTipGenerator().generateLabel(
dataset, series);
}
String urlText = null;
if (getLegendItemURLGenerator() != null) {
urlText = getLegendItemURLGenerator().generateLabel(
dataset, series);
}
Shape shape = lookupSeriesShape(series);
Paint paint = lookupSeriesPaint(series);
Paint outlinePaint = lookupSeriesOutlinePaint(series);
Stroke outlineStroke = lookupSeriesOutlineStroke(series);
result = new LegendItem(label, description, toolTipText,
urlText, shape, paint, outlineStroke, outlinePaint);
result.setSeriesKey(dataset.getSeriesKey(series));
result.setSeriesIndex(series);
result.setDataset(dataset);
result.setDatasetIndex(datasetIndex);
}
}
return result;
}
/**
* Fills a band between two values on the axis. This can be used to color
* bands between the grid lines.
*
* @param g2 the graphics device.
* @param plot the plot.
* @param axis the domain axis.
* @param dataArea the data area.
* @param start the start value.
* @param end the end value.
*/
public void fillDomainGridBand(Graphics2D g2, XYPlot plot, ValueAxis axis,
Rectangle2D dataArea, double start, double end) {
double x1 = axis.valueToJava2D(start, dataArea,
plot.getDomainAxisEdge());
double x2 = axis.valueToJava2D(end, dataArea,
plot.getDomainAxisEdge());
Rectangle2D band;
if (plot.getOrientation() == PlotOrientation.VERTICAL) {
band = new Rectangle2D.Double(Math.min(x1, x2), dataArea.getMinY(),
Math.abs(x2 - x1), dataArea.getWidth());
}
else {
band = new Rectangle2D.Double(dataArea.getMinX(), Math.min(x1, x2),
dataArea.getWidth(), Math.abs(x2 - x1));
}
Paint paint = plot.getDomainTickBandPaint();
if (paint != null) {
g2.setPaint(paint);
g2.fill(band);
}
}
/**
* Fills a band between two values on the range axis. This can be used to
* color bands between the grid lines.
*
* @param g2 the graphics device.
* @param plot the plot.
* @param axis the range axis.
* @param dataArea the data area.
* @param start the start value.
* @param end the end value.
*/
public void fillRangeGridBand(Graphics2D g2, XYPlot plot, ValueAxis axis,
Rectangle2D dataArea, double start, double end) {
double y1 = axis.valueToJava2D(start, dataArea,
plot.getRangeAxisEdge());
double y2 = axis.valueToJava2D(end, dataArea, plot.getRangeAxisEdge());
Rectangle2D band;
if (plot.getOrientation() == PlotOrientation.VERTICAL) {
band = new Rectangle2D.Double(dataArea.getMinX(), Math.min(y1, y2),
dataArea.getWidth(), Math.abs(y2 - y1));
}
else {
band = new Rectangle2D.Double(Math.min(y1, y2), dataArea.getMinY(),
Math.abs(y2 - y1), dataArea.getHeight());
}
Paint paint = plot.getRangeTickBandPaint();
if (paint != null) {
g2.setPaint(paint);
g2.fill(band);
}
}
/**
* Draws a grid line against the range axis.
*
* @param g2 the graphics device.
* @param plot the plot.
* @param axis the value axis.
* @param dataArea the area for plotting data (not yet adjusted for any
* 3D effect).
* @param value the value at which the grid line should be drawn.
*/
public void drawDomainGridLine(Graphics2D g2,
XYPlot plot,
ValueAxis axis,
Rectangle2D dataArea,
double value) {
Range range = axis.getRange();
if (!range.contains(value)) {
return;
}
PlotOrientation orientation = plot.getOrientation();
double v = axis.valueToJava2D(value, dataArea,
plot.getDomainAxisEdge());
Line2D line = null;
if (orientation == PlotOrientation.HORIZONTAL) {
line = new Line2D.Double(dataArea.getMinX(), v,
dataArea.getMaxX(), v);
}
else if (orientation == PlotOrientation.VERTICAL) {
line = new Line2D.Double(v, dataArea.getMinY(), v,
dataArea.getMaxY());
}
Paint paint = plot.getDomainGridlinePaint();
Stroke stroke = plot.getDomainGridlineStroke();
g2.setPaint(paint != null ? paint : Plot.DEFAULT_OUTLINE_PAINT);
g2.setStroke(stroke != null ? stroke : Plot.DEFAULT_OUTLINE_STROKE);
g2.draw(line);
}
/**
* Draws a line perpendicular to the domain axis.
*
* @param g2 the graphics device.
* @param plot the plot.
* @param axis the value axis.
* @param dataArea the area for plotting data (not yet adjusted for any 3D
* effect).
* @param value the value at which the grid line should be drawn.
* @param paint the paint.
* @param stroke the stroke.
*
* @since 1.0.5
*/
public void drawDomainLine(Graphics2D g2, XYPlot plot, ValueAxis axis,
Rectangle2D dataArea, double value, Paint paint, Stroke stroke) {
Range range = axis.getRange();
if (!range.contains(value)) {
return;
}
PlotOrientation orientation = plot.getOrientation();
Line2D line = null;
double v = axis.valueToJava2D(value, dataArea,
plot.getDomainAxisEdge());
if (orientation == PlotOrientation.HORIZONTAL) {
line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(),
v);
}
else if (orientation == PlotOrientation.VERTICAL) {
line = new Line2D.Double(v, dataArea.getMinY(), v,
dataArea.getMaxY());
}
g2.setPaint(paint);
g2.setStroke(stroke);
g2.draw(line);
}
/**
* Draws a line perpendicular to the range axis.
*
* @param g2 the graphics device.
* @param plot the plot.
* @param axis the value axis.
* @param dataArea the area for plotting data (not yet adjusted for any 3D
* effect).
* @param value the value at which the grid line should be drawn.
* @param paint the paint.
* @param stroke the stroke.
*/
public void drawRangeLine(Graphics2D g2,
XYPlot plot,
ValueAxis axis,
Rectangle2D dataArea,
double value,
Paint paint,
Stroke stroke) {
Range range = axis.getRange();
if (!range.contains(value)) {
return;
}
PlotOrientation orientation = plot.getOrientation();
Line2D line = null;
double v = axis.valueToJava2D(value, dataArea, plot.getRangeAxisEdge());
if (orientation == PlotOrientation.HORIZONTAL) {
line = new Line2D.Double(v, dataArea.getMinY(), v,
dataArea.getMaxY());
}
else if (orientation == PlotOrientation.VERTICAL) {
line = new Line2D.Double(dataArea.getMinX(), v,
dataArea.getMaxX(), v);
}
g2.setPaint(paint);
g2.setStroke(stroke);
g2.draw(line);
}
/**
* Draws a vertical line on the chart to represent a 'range marker'.
*
* @param g2 the graphics device.
* @param plot the plot.
* @param domainAxis the domain axis.
* @param marker the marker line.
* @param dataArea the axis data area.
*/
public void drawDomainMarker(Graphics2D g2,
XYPlot plot,
ValueAxis domainAxis,
Marker marker,
Rectangle2D dataArea) {
if (marker instanceof ValueMarker) {
ValueMarker vm = (ValueMarker) marker;
double value = vm.getValue();
Range range = domainAxis.getRange();
if (!range.contains(value)) {
return;
}
double v = domainAxis.valueToJava2D(value, dataArea,
plot.getDomainAxisEdge());
PlotOrientation orientation = plot.getOrientation();
Line2D line = null;
if (orientation == PlotOrientation.HORIZONTAL) {
line = new Line2D.Double(dataArea.getMinX(), v,
dataArea.getMaxX(), v);
}
else if (orientation == PlotOrientation.VERTICAL) {
line = new Line2D.Double(v, dataArea.getMinY(), v,
dataArea.getMaxY());
}
final Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, marker.getAlpha()));
g2.setPaint(marker.getPaint());
g2.setStroke(marker.getStroke());
g2.draw(line);
String label = marker.getLabel();
RectangleAnchor anchor = marker.getLabelAnchor();
if (label != null) {
Font labelFont = marker.getLabelFont();
g2.setFont(labelFont);
g2.setPaint(marker.getLabelPaint());
Point2D coordinates = calculateDomainMarkerTextAnchorPoint(
g2, orientation, dataArea, line.getBounds2D(),
marker.getLabelOffset(),
LengthAdjustmentType.EXPAND, anchor);
TextUtilities.drawAlignedString(label, g2,
(float) coordinates.getX(), (float) coordinates.getY(),
marker.getLabelTextAnchor());
}
g2.setComposite(originalComposite);
}
else if (marker instanceof IntervalMarker) {
IntervalMarker im = (IntervalMarker) marker;
double start = im.getStartValue();
double end = im.getEndValue();
Range range = domainAxis.getRange();
if (!(range.intersects(start, end))) {
return;
}
double start2d = domainAxis.valueToJava2D(start, dataArea,
plot.getDomainAxisEdge());
double end2d = domainAxis.valueToJava2D(end, dataArea,
plot.getDomainAxisEdge());
double low = Math.min(start2d, end2d);
double high = Math.max(start2d, end2d);
PlotOrientation orientation = plot.getOrientation();
Rectangle2D rect = null;
if (orientation == PlotOrientation.HORIZONTAL) {
// clip top and bottom bounds to data area
low = Math.max(low, dataArea.getMinY());
high = Math.min(high, dataArea.getMaxY());
rect = new Rectangle2D.Double(dataArea.getMinX(),
low, dataArea.getWidth(),
high - low);
}
else if (orientation == PlotOrientation.VERTICAL) {
// clip left and right bounds to data area
low = Math.max(low, dataArea.getMinX());
high = Math.min(high, dataArea.getMaxX());
rect = new Rectangle2D.Double(low,
dataArea.getMinY(), high - low,
dataArea.getHeight());
}
final Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, marker.getAlpha()));
Paint p = marker.getPaint();
if (p instanceof GradientPaint) {
GradientPaint gp = (GradientPaint) p;
GradientPaintTransformer t = im.getGradientPaintTransformer();
if (t != null) {
gp = t.transform(gp, rect);
}
g2.setPaint(gp);
}
else {
g2.setPaint(p);
}
g2.fill(rect);
// now draw the outlines, if visible...
if (im.getOutlinePaint() != null && im.getOutlineStroke() != null) {
if (orientation == PlotOrientation.VERTICAL) {
Line2D line = new Line2D.Double();
double y0 = dataArea.getMinY();
double y1 = dataArea.getMaxY();
g2.setPaint(im.getOutlinePaint());
g2.setStroke(im.getOutlineStroke());
if (range.contains(start)) {
line.setLine(start2d, y0, start2d, y1);
g2.draw(line);
}
if (range.contains(end)) {
line.setLine(end2d, y0, end2d, y1);
g2.draw(line);
}
}
else { // PlotOrientation.HORIZONTAL
Line2D line = new Line2D.Double();
double x0 = dataArea.getMinX();
double x1 = dataArea.getMaxX();
g2.setPaint(im.getOutlinePaint());
g2.setStroke(im.getOutlineStroke());
if (range.contains(start)) {
line.setLine(x0, start2d, x1, start2d);
g2.draw(line);
}
if (range.contains(end)) {
line.setLine(x0, end2d, x1, end2d);
g2.draw(line);
}
}
}
String label = marker.getLabel();
RectangleAnchor anchor = marker.getLabelAnchor();
if (label != null) {
Font labelFont = marker.getLabelFont();
g2.setFont(labelFont);
g2.setPaint(marker.getLabelPaint());
Point2D coordinates = calculateDomainMarkerTextAnchorPoint(
g2, orientation, dataArea, rect,
marker.getLabelOffset(), marker.getLabelOffsetType(),
anchor);
TextUtilities.drawAlignedString(label, g2,
(float) coordinates.getX(), (float) coordinates.getY(),
marker.getLabelTextAnchor());
}
g2.setComposite(originalComposite);
}
}
/**
* Calculates the (x, y) coordinates for drawing a marker label.
*
* @param g2 the graphics device.
* @param orientation the plot orientation.
* @param dataArea the data area.
* @param markerArea the rectangle surrounding the marker area.
* @param markerOffset the marker label offset.
* @param labelOffsetType the label offset type.
* @param anchor the label anchor.
*
* @return The coordinates for drawing the marker label.
*/
protected Point2D calculateDomainMarkerTextAnchorPoint(Graphics2D g2,
PlotOrientation orientation,
Rectangle2D dataArea,
Rectangle2D markerArea,
RectangleInsets markerOffset,
LengthAdjustmentType labelOffsetType,
RectangleAnchor anchor) {
Rectangle2D anchorRect = null;
if (orientation == PlotOrientation.HORIZONTAL) {
anchorRect = markerOffset.createAdjustedRectangle(markerArea,
LengthAdjustmentType.CONTRACT, labelOffsetType);
}
else if (orientation == PlotOrientation.VERTICAL) {
anchorRect = markerOffset.createAdjustedRectangle(markerArea,
labelOffsetType, LengthAdjustmentType.CONTRACT);
}
return RectangleAnchor.coordinates(anchorRect, anchor);
}
/**
* Draws a horizontal line across the chart to represent a 'range marker'.
*
* @param g2 the graphics device.
* @param plot the plot.
* @param rangeAxis the range axis.
* @param marker the marker line.
* @param dataArea the axis data area.
*/
public void drawRangeMarker(Graphics2D g2,
XYPlot plot,
ValueAxis rangeAxis,
Marker marker,
Rectangle2D dataArea) {
if (marker instanceof ValueMarker) {
ValueMarker vm = (ValueMarker) marker;
double value = vm.getValue();
Range range = rangeAxis.getRange();
if (!range.contains(value)) {
return;
}
double v = rangeAxis.valueToJava2D(value, dataArea,
plot.getRangeAxisEdge());
PlotOrientation orientation = plot.getOrientation();
Line2D line = null;
if (orientation == PlotOrientation.HORIZONTAL) {
line = new Line2D.Double(v, dataArea.getMinY(), v,
dataArea.getMaxY());
}
else if (orientation == PlotOrientation.VERTICAL) {
line = new Line2D.Double(dataArea.getMinX(), v,
dataArea.getMaxX(), v);
}
final Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, marker.getAlpha()));
g2.setPaint(marker.getPaint());
g2.setStroke(marker.getStroke());
g2.draw(line);
String label = marker.getLabel();
RectangleAnchor anchor = marker.getLabelAnchor();
if (label != null) {
Font labelFont = marker.getLabelFont();
g2.setFont(labelFont);
g2.setPaint(marker.getLabelPaint());
Point2D coordinates = calculateRangeMarkerTextAnchorPoint(
g2, orientation, dataArea, line.getBounds2D(),
marker.getLabelOffset(),
LengthAdjustmentType.EXPAND, anchor);
TextUtilities.drawAlignedString(label, g2,
(float) coordinates.getX(), (float) coordinates.getY(),
marker.getLabelTextAnchor());
}
g2.setComposite(originalComposite);
}
else if (marker instanceof IntervalMarker) {
IntervalMarker im = (IntervalMarker) marker;
double start = im.getStartValue();
double end = im.getEndValue();
Range range = rangeAxis.getRange();
if (!(range.intersects(start, end))) {
return;
}
double start2d = rangeAxis.valueToJava2D(start, dataArea,
plot.getRangeAxisEdge());
double end2d = rangeAxis.valueToJava2D(end, dataArea,
plot.getRangeAxisEdge());
double low = Math.min(start2d, end2d);
double high = Math.max(start2d, end2d);
PlotOrientation orientation = plot.getOrientation();
Rectangle2D rect = null;
if (orientation == PlotOrientation.HORIZONTAL) {
// clip left and right bounds to data area
low = Math.max(low, dataArea.getMinX());
high = Math.min(high, dataArea.getMaxX());
rect = new Rectangle2D.Double(low,
dataArea.getMinY(), high - low,
dataArea.getHeight());
}
else if (orientation == PlotOrientation.VERTICAL) {
// clip top and bottom bounds to data area
low = Math.max(low, dataArea.getMinY());
high = Math.min(high, dataArea.getMaxY());
rect = new Rectangle2D.Double(dataArea.getMinX(),
low, dataArea.getWidth(),
high - low);
}
final Composite originalComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, marker.getAlpha()));
Paint p = marker.getPaint();
if (p instanceof GradientPaint) {
GradientPaint gp = (GradientPaint) p;
GradientPaintTransformer t = im.getGradientPaintTransformer();
if (t != null) {
gp = t.transform(gp, rect);
}
g2.setPaint(gp);
}
else {
g2.setPaint(p);
}
g2.fill(rect);
// now draw the outlines, if visible...
if (im.getOutlinePaint() != null && im.getOutlineStroke() != null) {
if (orientation == PlotOrientation.VERTICAL) {
Line2D line = new Line2D.Double();
double x0 = dataArea.getMinX();
double x1 = dataArea.getMaxX();
g2.setPaint(im.getOutlinePaint());
g2.setStroke(im.getOutlineStroke());
if (range.contains(start)) {
line.setLine(x0, start2d, x1, start2d);
g2.draw(line);
}
if (range.contains(end)) {
line.setLine(x0, end2d, x1, end2d);
g2.draw(line);
}
}
else { // PlotOrientation.HORIZONTAL
Line2D line = new Line2D.Double();
double y0 = dataArea.getMinY();
double y1 = dataArea.getMaxY();
g2.setPaint(im.getOutlinePaint());
g2.setStroke(im.getOutlineStroke());
if (range.contains(start)) {
line.setLine(start2d, y0, start2d, y1);
g2.draw(line);
}
if (range.contains(end)) {
line.setLine(end2d, y0, end2d, y1);
g2.draw(line);
}
}
}
String label = marker.getLabel();
RectangleAnchor anchor = marker.getLabelAnchor();
if (label != null) {
Font labelFont = marker.getLabelFont();
g2.setFont(labelFont);
g2.setPaint(marker.getLabelPaint());
Point2D coordinates = calculateRangeMarkerTextAnchorPoint(
g2, orientation, dataArea, rect,
marker.getLabelOffset(), marker.getLabelOffsetType(),
anchor);
TextUtilities.drawAlignedString(label, g2,
(float) coordinates.getX(), (float) coordinates.getY(),
marker.getLabelTextAnchor());
}
g2.setComposite(originalComposite);
}
}
/**
* Calculates the (x, y) coordinates for drawing a marker label.
*
* @param g2 the graphics device.
* @param orientation the plot orientation.
* @param dataArea the data area.
* @param markerArea the marker area.
* @param markerOffset the marker offset.
* @param labelOffsetForRange ??
* @param anchor the label anchor.
*
* @return The coordinates for drawing the marker label.
*/
private Point2D calculateRangeMarkerTextAnchorPoint(Graphics2D g2,
PlotOrientation orientation,
Rectangle2D dataArea,
Rectangle2D markerArea,
RectangleInsets markerOffset,
LengthAdjustmentType labelOffsetForRange,
RectangleAnchor anchor) {
Rectangle2D anchorRect = null;
if (orientation == PlotOrientation.HORIZONTAL) {
anchorRect = markerOffset.createAdjustedRectangle(markerArea,
labelOffsetForRange, LengthAdjustmentType.CONTRACT);
}
else if (orientation == PlotOrientation.VERTICAL) {
anchorRect = markerOffset.createAdjustedRectangle(markerArea,
LengthAdjustmentType.CONTRACT, labelOffsetForRange);
}
return RectangleAnchor.coordinates(anchorRect, anchor);
}
/**
* Returns a clone of the renderer.
*
* @return A clone.
*
* @throws CloneNotSupportedException if the renderer does not support
* cloning.
*/
protected Object clone() throws CloneNotSupportedException {
AbstractXYItemRenderer clone = (AbstractXYItemRenderer) super.clone();
// 'plot' : just retain reference, not a deep copy
if (this.itemLabelGenerator != null
&& this.itemLabelGenerator instanceof PublicCloneable) {
PublicCloneable pc = (PublicCloneable) this.itemLabelGenerator;
clone.itemLabelGenerator = (XYItemLabelGenerator) pc.clone();
}
clone.itemLabelGeneratorList
= (ObjectList) this.itemLabelGeneratorList.clone();
if (this.baseItemLabelGenerator != null
&& this.baseItemLabelGenerator instanceof PublicCloneable) {
PublicCloneable pc = (PublicCloneable) this.baseItemLabelGenerator;
clone.baseItemLabelGenerator = (XYItemLabelGenerator) pc.clone();
}
if (this.toolTipGenerator != null
&& this.toolTipGenerator instanceof PublicCloneable) {
PublicCloneable pc = (PublicCloneable) this.toolTipGenerator;
clone.toolTipGenerator = (XYToolTipGenerator) pc.clone();
}
clone.toolTipGeneratorList
= (ObjectList) this.toolTipGeneratorList.clone();
if (this.baseToolTipGenerator != null
&& this.baseToolTipGenerator instanceof PublicCloneable) {
PublicCloneable pc = (PublicCloneable) this.baseToolTipGenerator;
clone.baseToolTipGenerator = (XYToolTipGenerator) pc.clone();
}
if (clone.legendItemLabelGenerator instanceof PublicCloneable) {
clone.legendItemLabelGenerator = (XYSeriesLabelGenerator)
ObjectUtilities.clone(this.legendItemLabelGenerator);
}
if (clone.legendItemToolTipGenerator instanceof PublicCloneable) {
clone.legendItemToolTipGenerator = (XYSeriesLabelGenerator)
ObjectUtilities.clone(this.legendItemToolTipGenerator);
}
if (clone.legendItemURLGenerator instanceof PublicCloneable) {
clone.legendItemURLGenerator = (XYSeriesLabelGenerator)
ObjectUtilities.clone(this.legendItemURLGenerator);
}
clone.foregroundAnnotations = (List) ObjectUtilities.deepClone(
this.foregroundAnnotations);
clone.backgroundAnnotations = (List) ObjectUtilities.deepClone(
this.backgroundAnnotations);
if (clone.legendItemLabelGenerator instanceof PublicCloneable) {
clone.legendItemLabelGenerator = (XYSeriesLabelGenerator)
ObjectUtilities.clone(this.legendItemLabelGenerator);
}
if (clone.legendItemToolTipGenerator instanceof PublicCloneable) {
clone.legendItemToolTipGenerator = (XYSeriesLabelGenerator)
ObjectUtilities.clone(this.legendItemToolTipGenerator);
}
if (clone.legendItemURLGenerator instanceof PublicCloneable) {
clone.legendItemURLGenerator = (XYSeriesLabelGenerator)
ObjectUtilities.clone(this.legendItemURLGenerator);
}
return clone;
}
/**
* Tests this renderer for equality with another object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return <code>true</code> or <code>false</code>.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof AbstractXYItemRenderer)) {
return false;
}
AbstractXYItemRenderer that = (AbstractXYItemRenderer) obj;
if (!ObjectUtilities.equal(this.itemLabelGenerator,
that.itemLabelGenerator)) {
return false;
}
if (!this.itemLabelGeneratorList.equals(that.itemLabelGeneratorList)) {
return false;
}
if (!ObjectUtilities.equal(this.baseItemLabelGenerator,
that.baseItemLabelGenerator)) {
return false;
}
if (!ObjectUtilities.equal(this.toolTipGenerator,
that.toolTipGenerator)) {
return false;
}
if (!this.toolTipGeneratorList.equals(that.toolTipGeneratorList)) {
return false;
}
if (!ObjectUtilities.equal(this.baseToolTipGenerator,
that.baseToolTipGenerator)) {
return false;
}
if (!ObjectUtilities.equal(this.urlGenerator, that.urlGenerator)) {
return false;
}
if (!this.foregroundAnnotations.equals(that.foregroundAnnotations)) {
return false;
}
if (!this.backgroundAnnotations.equals(that.backgroundAnnotations)) {
return false;
}
if (this.defaultEntityRadius != that.defaultEntityRadius) {
return false;
}
if (!ObjectUtilities.equal(this.legendItemLabelGenerator,
that.legendItemLabelGenerator)) {
return false;
}
if (!ObjectUtilities.equal(this.legendItemToolTipGenerator,
that.legendItemToolTipGenerator)) {
return false;
}
if (!ObjectUtilities.equal(this.legendItemURLGenerator,
that.legendItemURLGenerator)) {
return false;
}
return super.equals(obj);
}
/**
* Returns the drawing supplier from the plot.
*
* @return The drawing supplier (possibly <code>null</code>).
*/
public DrawingSupplier getDrawingSupplier() {
DrawingSupplier result = null;
XYPlot p = getPlot();
if (p != null) {
result = p.getDrawingSupplier();
}
return result;
}
/**
* Considers the current (x, y) coordinate and updates the crosshair point
* if it meets the criteria (usually means the (x, y) coordinate is the
* closest to the anchor point so far).
*
* @param crosshairState the crosshair state (<code>null</code> permitted,
* but the method does nothing in that case).
* @param x the x-value (in data space).
* @param y the y-value (in data space).
* @param transX the x-value translated to Java2D space.
* @param transY the y-value translated to Java2D space.
* @param orientation the plot orientation (<code>null</code> not
* permitted).
*
* @deprecated Use {@link #updateCrosshairValues(CrosshairState, double,
* double, int, int, double, double, PlotOrientation)} -- see bug
* report 1086307.
*/
protected void updateCrosshairValues(CrosshairState crosshairState,
double x, double y, double transX, double transY,
PlotOrientation orientation) {
updateCrosshairValues(crosshairState, x, y, 0, 0, transX, transY,
orientation);
}
/**
* Considers the current (x, y) coordinate and updates the crosshair point
* if it meets the criteria (usually means the (x, y) coordinate is the
* closest to the anchor point so far).
*
* @param crosshairState the crosshair state (<code>null</code> permitted,
* but the method does nothing in that case).
* @param x the x-value (in data space).
* @param y the y-value (in data space).
* @param domainAxisIndex the index of the domain axis for the point.
* @param rangeAxisIndex the index of the range axis for the point.
* @param transX the x-value translated to Java2D space.
* @param transY the y-value translated to Java2D space.
* @param orientation the plot orientation (<code>null</code> not
* permitted).
*
* @since 1.0.4
*/
protected void updateCrosshairValues(CrosshairState crosshairState,
double x, double y, int domainAxisIndex, int rangeAxisIndex,
double transX, double transY, PlotOrientation orientation) {
if (orientation == null) {
throw new IllegalArgumentException("Null 'orientation' argument.");
}
if (crosshairState != null) {
// do we need to update the crosshair values?
if (this.plot.isDomainCrosshairLockedOnData()) {
if (this.plot.isRangeCrosshairLockedOnData()) {
// both axes
crosshairState.updateCrosshairPoint(x, y, domainAxisIndex,
rangeAxisIndex, transX, transY, orientation);
}
else {
// just the domain axis...
crosshairState.updateCrosshairX(x, domainAxisIndex);
}
}
else {
if (this.plot.isRangeCrosshairLockedOnData()) {
// just the range axis...
crosshairState.updateCrosshairY(y, rangeAxisIndex);
}
}
}
}
/**
* Draws an item label.
*
* @param g2 the graphics device.
* @param orientation the orientation.
* @param dataset the dataset.
* @param series the series index (zero-based).
* @param item the item index (zero-based).
* @param x the x coordinate (in Java2D space).
* @param y the y coordinate (in Java2D space).
* @param negative indicates a negative value (which affects the item
* label position).
*/
protected void drawItemLabel(Graphics2D g2, PlotOrientation orientation,
XYDataset dataset, int series, int item, double x, double y,
boolean negative) {
XYItemLabelGenerator generator = getItemLabelGenerator(series, item);
if (generator != null) {
Font labelFont = getItemLabelFont(series, item);
Paint paint = getItemLabelPaint(series, item);
g2.setFont(labelFont);
g2.setPaint(paint);
String label = generator.generateLabel(dataset, series, item);
// get the label position..
ItemLabelPosition position = null;
if (!negative) {
position = getPositiveItemLabelPosition(series, item);
}
else {
position = getNegativeItemLabelPosition(series, item);
}
// work out the label anchor point...
Point2D anchorPoint = calculateLabelAnchorPoint(
position.getItemLabelAnchor(), x, y, orientation);
TextUtilities.drawRotatedString(label, g2,
(float) anchorPoint.getX(), (float) anchorPoint.getY(),
position.getTextAnchor(), position.getAngle(),
position.getRotationAnchor());
}
}
/**
* Draws all the annotations for the specified layer.
*
* @param g2 the graphics device.
* @param dataArea the data area.
* @param domainAxis the domain axis.
* @param rangeAxis the range axis.
* @param layer the layer.
* @param info the plot rendering info.
*/
public void drawAnnotations(Graphics2D g2,
Rectangle2D dataArea,
ValueAxis domainAxis,
ValueAxis rangeAxis,
Layer layer,
PlotRenderingInfo info) {
Iterator iterator = null;
if (layer.equals(Layer.FOREGROUND)) {
iterator = this.foregroundAnnotations.iterator();
}
else if (layer.equals(Layer.BACKGROUND)) {
iterator = this.backgroundAnnotations.iterator();
}
else {
// should not get here
throw new RuntimeException("Unknown layer.");
}
while (iterator.hasNext()) {
XYAnnotation annotation = (XYAnnotation) iterator.next();
annotation.draw(g2, this.plot, dataArea, domainAxis, rangeAxis,
0, info);
}
}
/**
* Adds an entity to the collection.
*
* @param entities the entity collection being populated.
* @param area the entity area (if <code>null</code> a default will be
* used).
* @param dataset the dataset.
* @param series the series.
* @param item the item.
* @param entityX the entity's center x-coordinate in user space.
* @param entityY the entity's center y-coordinate in user space.
*/
protected void addEntity(EntityCollection entities, Shape area,
XYDataset dataset, int series, int item,
double entityX, double entityY) {
if (!getItemCreateEntity(series, item)) {
return;
}
if (area == null) {
area = new Ellipse2D.Double(entityX - this.defaultEntityRadius,
entityY - this.defaultEntityRadius,
this.defaultEntityRadius * 2, this.defaultEntityRadius * 2);
}
String tip = null;
XYToolTipGenerator generator = getToolTipGenerator(series, item);
if (generator != null) {
tip = generator.generateToolTip(dataset, series, item);
}
String url = null;
if (getURLGenerator() != null) {
url = getURLGenerator().generateURL(dataset, series, item);
}
XYItemEntity entity = new XYItemEntity(area, dataset, series, item,
tip, url);
entities.add(entity);
}
}
|
package jsettlers.input;
import java.util.EnumSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import jsettlers.algorithms.construction.ConstructionMarksThread;
import jsettlers.common.buildings.EBuildingType;
import jsettlers.common.buildings.IBuilding;
import jsettlers.common.map.shapes.MapCircle;
import jsettlers.common.map.shapes.MapShapeFilter;
import jsettlers.common.material.EPriority;
import jsettlers.common.menu.IMapInterfaceConnector;
import jsettlers.common.menu.IMapInterfaceListener;
import jsettlers.common.menu.UIState;
import jsettlers.common.menu.action.EActionType;
import jsettlers.common.menu.action.IAction;
import jsettlers.common.movable.EMovableType;
import jsettlers.common.movable.IIDable;
import jsettlers.common.movable.IMovable;
import jsettlers.common.position.ILocatable;
import jsettlers.common.position.ShortPoint2D;
import jsettlers.common.selectable.ESelectionType;
import jsettlers.common.selectable.ISelectable;
import jsettlers.graphics.action.BuildAction;
import jsettlers.graphics.action.ChangeTradingRequestAction;
import jsettlers.graphics.action.ConvertAction;
import jsettlers.graphics.action.PointAction;
import jsettlers.graphics.action.ScreenChangeAction;
import jsettlers.graphics.action.SelectAreaAction;
import jsettlers.graphics.action.SetBuildingPriorityAction;
import jsettlers.graphics.action.SetMaterialDistributionSettingsAction;
import jsettlers.graphics.action.SetMaterialPrioritiesAction;
import jsettlers.graphics.action.SetMaterialProductionAction;
import jsettlers.graphics.action.SetMaterialStockAcceptedAction;
import jsettlers.graphics.action.SetTradingWaypointAction;
import jsettlers.graphics.action.ShowConstructionMarksAction;
import jsettlers.graphics.action.SoldierAction;
import jsettlers.input.tasks.ChangeTradingRequestGuiTask;
import jsettlers.input.tasks.ConstructBuildingTask;
import jsettlers.input.tasks.ConvertGuiTask;
import jsettlers.input.tasks.DestroyBuildingGuiTask;
import jsettlers.input.tasks.EGuiAction;
import jsettlers.input.tasks.MovableGuiTask;
import jsettlers.input.tasks.MoveToGuiTask;
import jsettlers.input.tasks.SetBuildingPriorityGuiTask;
import jsettlers.input.tasks.SetMaterialDistributionSettingsGuiTask;
import jsettlers.input.tasks.SetMaterialPrioritiesGuiTask;
import jsettlers.input.tasks.SetMaterialProductionGuiTask;
import jsettlers.input.tasks.SetTradingWaypointGuiTask;
import jsettlers.input.tasks.SimpleGuiTask;
import jsettlers.input.tasks.UpgradeSoldiersGuiTask;
import jsettlers.input.tasks.WorkAreaGuiTask;
import jsettlers.logic.buildings.Building;
import jsettlers.logic.constants.MatchConstants;
import jsettlers.logic.movable.interfaces.IDebugable;
import jsettlers.network.client.interfaces.IGameClock;
import jsettlers.network.client.interfaces.ITaskScheduler;
/**
* Class to handle the events provided by the user through jsettlers.graphics.
*
* @author Andreas Eberle
*/
public class GuiInterface implements IMapInterfaceListener, ITaskExecutorGuiInterface {
private static final float SELECT_BY_TYPE_RADIUS = 30;
private final IMapInterfaceConnector connector;
private final IGameClock clock;
private final ITaskScheduler taskScheduler;
private final IGuiInputGrid grid;
private final IGameStoppable gameStoppable;
private final byte playerId;
private final boolean multiplayer;
private final ConstructionMarksThread constructionMarksCalculator;
private final Timer refreshSelectionTimer;
/**
* The current selection. This is updated by game logic.
*/
private SelectionSet currentSelection = new SelectionSet();
public GuiInterface(IMapInterfaceConnector connector, IGameClock clock, ITaskScheduler taskScheduler, IGuiInputGrid grid,
IGameStoppable gameStoppable, byte player, boolean multiplayer) {
this.connector = connector;
this.clock = clock;
this.taskScheduler = taskScheduler;
this.grid = grid;
this.gameStoppable = gameStoppable;
this.playerId = player;
this.multiplayer = multiplayer;
this.constructionMarksCalculator = new ConstructionMarksThread(grid.getConstructionMarksGrid(), clock, player);
this.refreshSelectionTimer = new Timer("refreshSelectionTimer");
this.refreshSelectionTimer.schedule(new TimerTask() {
@Override
public void run() {
refreshSelection();
}
}, 1000, 1000);
grid.getPlayer(player).setMessenger(connector);
clock.setTaskExecutor(new GuiTaskExecutor(grid, this, playerId));
connector.addListener(this);
}
@Override
public void action(IAction action) {
if (action.getActionType() != EActionType.SCREEN_CHANGE) {
System.out.println("action(Action): " + action.getActionType() + " at game time: " + MatchConstants.clock().getTime());
}
switch (action.getActionType()) {
case BUILD:
this.setSelection(new SelectionSet());
final BuildAction buildAction = (BuildAction) action;
EBuildingType buildingType = buildAction.getBuildingType();
final ShortPoint2D pos2 = grid.getConstructablePosition(buildAction.getPosition(), buildingType, playerId,
InputSettings.USE_NEIGHBOR_POSITIONS_FOR_CONSTRUCTION);
if (pos2 != null) {
scheduleTask(new ConstructBuildingTask(EGuiAction.BUILD, playerId, pos2, buildingType));
}
System.out.println("build: " + buildingType);
break;
case SHOW_CONSTRUCTION_MARK: {
buildingType = ((ShowConstructionMarksAction) action).getBuildingType();
constructionMarksCalculator.setBuildingType(buildingType);
break;
}
case DEBUG_ACTION:
for (final ISelectable curr : currentSelection) {
if (curr instanceof IDebugable) {
((IDebugable) curr).debug();
}
}
break;
case SPEED_TOGGLE_PAUSE:
clock.invertPausing();
break;
case SPEED_SET_PAUSE:
clock.setPausing(true);
break;
case SPEED_UNSET_PAUSE:
clock.setPausing(false);
break;
case SPEED_SLOW:
if (!multiplayer) {
clock.setGameSpeed(0.5f);
}
break;
case SPEED_FAST:
if (!multiplayer) {
clock.setGameSpeed(2.0f);
}
break;
case SPEED_FASTER:
if (!multiplayer) {
clock.multiplyGameSpeed(1.2f);
}
break;
case SPEED_SLOWER:
if (!multiplayer) {
clock.multiplyGameSpeed(1 / 1.2f);
}
break;
case SPEED_NORMAL:
if (!multiplayer) {
clock.setGameSpeed(1.0f);
}
break;
case FAST_FORWARD:
if (!multiplayer) {
clock.fastForward();
}
break;
case SELECT_POINT:
handleSelectPointAction((PointAction) action);
break;
case SELECT_AREA:
selectArea((SelectAreaAction) action);
break;
case DESELECT:
deselect();
break;
case SELECT_POINT_TYPE:
selectPointType((PointAction) action);
break;
case MOVE_TO: {
final PointAction moveToAction = (PointAction) action;
if (currentSelection.getSelectionType() == ESelectionType.BUILDING && currentSelection.getSize() == 1) {
setBuildingWorkArea(moveToAction.getPosition());
} else {
moveTo(moveToAction.getPosition());
}
break;
}
case SHOW_MESSAGE: {
break;
}
case SET_WORK_AREA:
setBuildingWorkArea(((PointAction) action).getPosition());
break;
case DESTROY:
destroySelected();
break;
case STOP_WORKING:
stopOrStartWorkingAction(true);
break;
case START_WORKING:
stopOrStartWorkingAction(false);
break;
case SHOW_SELECTION:
showSelection();
break;
case SCREEN_CHANGE:
constructionMarksCalculator.setScreen(((ScreenChangeAction) action).getScreenArea());
break;
case TOGGLE_DEBUG:
grid.resetDebugColors();
break;
case TOGGLE_FOG_OF_WAR:
if (MatchConstants.ENABLE_FOG_OF_WAR_DISABLING) {
grid.toggleFogOfWar();
}
break;
case SAVE:
taskScheduler.scheduleTask(new SimpleGuiTask(EGuiAction.QUICK_SAVE, playerId));
break;
case CONVERT:
sendConvertAction((ConvertAction) action);
break;
case SET_BUILDING_PRIORITY:
setBuildingPriority(((SetBuildingPriorityAction) action).getNewPriority());
break;
case SET_MATERIAL_DISTRIBUTION_SETTINGS: {
final SetMaterialDistributionSettingsAction a = (SetMaterialDistributionSettingsAction) action;
taskScheduler.scheduleTask(new SetMaterialDistributionSettingsGuiTask(playerId, a.getManagerPosition(), a.getMaterialType(), a
.getProbabilities()));
break;
}
case SET_MATERIAL_PRIORITIES: {
final SetMaterialPrioritiesAction a = (SetMaterialPrioritiesAction) action;
taskScheduler.scheduleTask(new SetMaterialPrioritiesGuiTask(playerId, a.getPosition(), a.getMaterialTypeForPriority()));
break;
}
case SET_MATERIAL_STOCK_ACCEPTED: {
final SetMaterialStockAcceptedAction a = (SetMaterialStockAcceptedAction) action;
// TODO @Andreas: implement this.
System.err.println("Not implemented: " + a);
break;
}
case SET_MATERIAL_PRODUCTION: {
final SetMaterialProductionAction a = (SetMaterialProductionAction) action;
taskScheduler.scheduleTask(new SetMaterialProductionGuiTask(playerId, a.getPosition(), a.getMaterialType(), a.getProductionType(), a
.getRatio()));
break;
}
case NEXT_OF_TYPE:
selectNextOfType();
break;
case UPGRADE_SOLDIERS: {
final SoldierAction a = (SoldierAction) action;
taskScheduler.scheduleTask(new UpgradeSoldiersGuiTask(playerId, a.getSoldierType()));
break;
}
case CHANGE_TRADING_REQUEST: {
final ISelectable selected = currentSelection.getSingle();
if (selected instanceof Building) {
final ChangeTradingRequestAction a = (ChangeTradingRequestAction) action;
scheduleTask(new ChangeTradingRequestGuiTask(EGuiAction.CHANGE_TRADING, playerId, ((Building) selected).getPos(), a.getMaterial(),
a.getAmount(), a.isRelative()));
}
break;
}
case SET_TRADING_WAYPOINT: {
final ISelectable selected = currentSelection.getSingle();
if (selected instanceof Building) {
final SetTradingWaypointAction a = (SetTradingWaypointAction) action;
scheduleTask(new SetTradingWaypointGuiTask(EGuiAction.SET_TRADING_WAYPOINT, playerId, ((Building) selected).getPos(),
a.getWaypointType(), a.getPosition()));
}
}
case ABORT:
break;
case EXIT:
gameStoppable.stopGame();
break;
default:
System.out.println("WARNING: GuiInterface.action() called, but event can't be handled... (" + action.getActionType() + ")");
}
}
private void selectNextOfType() {
if (currentSelection.getSize() != 1) {
return;
}
if (currentSelection.getSelectionType() == ESelectionType.BUILDING) {
final Building building = (Building) currentSelection.get(0);
final EBuildingType buildingType = building.getBuildingType();
Building first = null;
Building next = null;
boolean buildingFound = false;
for (final Building currBuilding : Building.getAllBuildings()) {
if (currBuilding == building) {
buildingFound = true;
} else {
if (currBuilding.getBuildingType() == buildingType && currBuilding.getPlayerId() == playerId) {
if (first == null) {
first = currBuilding;
}
if (buildingFound) {
next = currBuilding;
break;
}
}
}
}
if (next != null) {
setSelection(new SelectionSet(next));
} else if (first != null) {
setSelection(new SelectionSet(first));
}
}
}
private void setBuildingWorkArea(ShortPoint2D workAreaPosition) {
final ISelectable selected = currentSelection.getSingle();
if (selected instanceof Building) {
scheduleTask(new WorkAreaGuiTask(EGuiAction.SET_WORK_AREA, playerId, workAreaPosition, ((Building) selected).getPos()));
}
}
private void sendConvertAction(ConvertAction action) {
final List<ISelectable> convertables = new LinkedList<ISelectable>();
switch (action.getTargetType()) {
case BEARER:
for (final ISelectable curr : currentSelection) {
if (curr instanceof IMovable) {
final EMovableType currType = ((IMovable) curr).getMovableType();
if (currType == EMovableType.THIEF || currType == EMovableType.PIONEER || currType == EMovableType.GEOLOGIST) {
convertables.add(curr);
if (convertables.size() >= action.getAmount()) {
break;
}
}
}
}
break;
case PIONEER:
case GEOLOGIST:
case THIEF:
for (final ISelectable curr : currentSelection) {
if (curr instanceof IMovable) {
final EMovableType currType = ((IMovable) curr).getMovableType();
if (currType == EMovableType.BEARER) {
convertables.add(curr);
if (convertables.size() >= action.getAmount()) {
break;
}
}
}
}
break;
default:
System.out.println("WARNING: can't handle convert to this movable type: " + action.getTargetType());
return;
}
if (convertables.size() > 0) {
taskScheduler.scheduleTask(new ConvertGuiTask(playerId, getIDsOfIterable(convertables), action.getTargetType()));
}
}
private void destroySelected() {
if (currentSelection == null || currentSelection.getSize() == 0) {
return;
} else if (currentSelection.getSize() == 1 && currentSelection.iterator().next() instanceof Building) {
taskScheduler.scheduleTask(new DestroyBuildingGuiTask(playerId, ((Building) currentSelection.iterator().next()).getPos()));
} else {
taskScheduler.scheduleTask(new MovableGuiTask(EGuiAction.DESTROY_MOVABLES, playerId, getIDsOfSelected()));
}
setSelection(new SelectionSet());
}
private void setBuildingPriority(EPriority newPriority) {
if (currentSelection != null && currentSelection.getSize() == 1 && currentSelection.iterator().next() instanceof Building) {
taskScheduler
.scheduleTask(new SetBuildingPriorityGuiTask(playerId, ((Building) currentSelection.iterator().next()).getPos(), newPriority));
}
}
private void showSelection() {
int x = 0;
int y = 0;
int count = 0;
for (final ISelectable member : currentSelection) {
if (member instanceof ILocatable) {
x += ((ILocatable) member).getPos().x;
y += ((ILocatable) member).getPos().y;
count++;
}
}
System.out.println("locatable: " + count);
if (count > 0) {
final ShortPoint2D point = new ShortPoint2D(x / count, y / count);
connector.scrollTo(point, false);
}
}
/**
* @param stop
* if true the members of currentSelection will stop working<br>
* if false, they will start working
*/
private void stopOrStartWorkingAction(boolean stop) {
taskScheduler.scheduleTask(new MovableGuiTask(stop ? EGuiAction.STOP_WORKING : EGuiAction.START_WORKING, playerId, getIDsOfSelected()));
}
private void moveTo(ShortPoint2D pos) {
final List<Integer> selectedIds = getIDsOfSelected();
scheduleTask(new MoveToGuiTask(playerId, pos, selectedIds));
}
private final List<Integer> getIDsOfSelected() {
return getIDsOfIterable(currentSelection);
}
private final static List<Integer> getIDsOfIterable(Iterable<? extends ISelectable> iterable) {
final List<Integer> selectedIds = new LinkedList<Integer>();
for (final ISelectable curr : iterable) {
if (curr instanceof IIDable) {
selectedIds.add(((IIDable) curr).getID());
}
}
return selectedIds;
}
private void selectArea(SelectAreaAction action) {
final SelectionSet selectionSet = new SelectionSet();
for (final ShortPoint2D curr : new MapShapeFilter(action.getArea(), grid.getWidth(), grid.getHeight())) {
final IGuiMovable movable = grid.getMovable(curr.x, curr.y);
if (movable != null && canSelectPlayer(movable.getPlayerId())) {
selectionSet.add(movable);
}
final IBuilding building = grid.getBuildingAt(curr.x, curr.y);
if (building != null && canSelectPlayer(building.getPlayerId())) {
selectionSet.add(building);
}
}
setSelection(selectionSet);
}
private boolean canSelectPlayer(byte playerIdOfSelected) {
return MatchConstants.ENABLE_ALL_PLAYER_SELECTION || playerIdOfSelected == playerId;
}
private void deselect() {
setSelection(new SelectionSet());
}
private void handleSelectPointAction(PointAction action) {
final ShortPoint2D pos = action.getPosition();
// only for debugging
grid.positionClicked(pos.x, pos.y);
// check what's to do
final ISelectable selected = getSelectableAt(pos);
if (selected != null) {
setSelection(new SelectionSet(selected));
} else {
setSelection(new SelectionSet());
}
}
private void scheduleTask(SimpleGuiTask guiTask) {
taskScheduler.scheduleTask(guiTask);
}
private ISelectable getSelectableAt(ShortPoint2D pos) {
if (grid.isInBounds(pos)) {
final short x = pos.x;
final short y = pos.y;
final IGuiMovable selectableMovable = getSelectableMovable(x, y);
if (selectableMovable != null) {
return selectableMovable;
} else {
// search buildings
final IBuilding building = grid.getBuildingAt(pos.x, pos.y);
if (building != null && canSelectPlayer(building.getPlayerId())) {
return building;
} else {
return null;
}
}
} else {
return null;
}
}
private IGuiMovable getSelectableMovable(short x, short y) {
final IGuiMovable m1 = grid.getMovable(x, y);
final IGuiMovable m3 = grid.getMovable((short) (x + 1), (short) (y + 1));
final IGuiMovable m2 = grid.getMovable((x), (short) (y + 1));
final IGuiMovable m4 = grid.getMovable((short) (x + 1), (short) (y + 2));
if (m1 != null && canSelectPlayer(m1.getPlayerId())) {
return m1;
} else if (m2 != null && canSelectPlayer(m2.getPlayerId())) {
return m2;
} else if (m3 != null && canSelectPlayer(m3.getPlayerId())) {
return m3;
} else if (m4 != null && canSelectPlayer(m4.getPlayerId())) {
return m4;
} else {
return null;
}
}
private void selectPointType(PointAction action) {
final ShortPoint2D actionPosition = action.getPosition();
final IGuiMovable selectedMovable = getSelectableMovable(actionPosition.x, actionPosition.y);
if (selectedMovable == null) { // nothing found at the location
setSelection(new SelectionSet());
return;
}
EMovableType selectedType = selectedMovable.getMovableType();
byte selectedPlayerId = selectedMovable.getPlayerId();
Set<EMovableType> selectableTypes;
if (selectedType.isSwordsman()) {
selectableTypes = EMovableType.swordsmen;
} else if (selectedType.isPikeman()) {
selectableTypes = EMovableType.pikemen;
} else if (selectedType.isBowman()) {
selectableTypes = EMovableType.bowmen;
} else {
selectableTypes = EnumSet.of(selectedType);
}
final List<ISelectable> selected = new LinkedList<>();
for (final ShortPoint2D pos : new MapCircle(actionPosition, SELECT_BY_TYPE_RADIUS)) {
final IGuiMovable movable = grid.getMovable(pos.x, pos.y);
if (movable != null && selectableTypes.contains(movable.getMovableType()) && selectedPlayerId == movable.getPlayerId()) {
selected.add(movable);
}
}
setSelection(new SelectionSet(selected));
}
/**
* Sets the selection.
*
* @param selection
* The selected items. Not null!
*/
private void setSelection(SelectionSet selection) {
currentSelection.setSelected(false);
selection.setSelected(true);
connector.setSelection(selection);
currentSelection = selection;
}
@Override
public void refreshSelection() {
if (!currentSelection.isEmpty()) {
SelectionSet newSelection = new SelectionSet();
boolean somethingWasRemoved = false;
for (ISelectable selected : currentSelection) {
if (selected.isSelected()) {
newSelection.add(selected);
} else {
somethingWasRemoved = true;
}
}
if (somethingWasRemoved || currentSelection.getSelectionType() != newSelection.getSelectionType()) {
setSelection(newSelection);
}
}
}
@Override
public UIState getUIState() {
return connector.getUIState();
}
/**
* Shuts down used threads.
*/
public void stop() {
constructionMarksCalculator.cancel();
connector.removeListener(this);
refreshSelectionTimer.cancel();
}
}
|
package com.github.dreamsnatcher.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.github.dreamsnatcher.entities.GameObject;
import com.github.dreamsnatcher.entities.GameWorld;
import com.github.dreamsnatcher.entities.Planet;
import com.github.dreamsnatcher.entities.SpaceShip;
import com.github.dreamsnatcher.utils.Assets;
public class EditorScreen extends Screen {
Skin skin;
Stage stage;
SpriteBatch batch;
OrthographicCamera camera;
GameWorld world;
GameObject selected;
public enum Action {
Place,
Drag,
Pan
}
public EditorScreen(ScreenManager manager) {
super(manager);
batch = new SpriteBatch();
camera = new OrthographicCamera(5, 5);
Assets.init();
initUI();
newWorld();
}
private void initUI() {
stage = new Stage();
ScreenManager.multiplexer.addProcessor(stage);
skin = new Skin(Gdx.files.internal("uiskin.json"));
Table root = new Table();
root.setFillParent(true);
stage.addActor(root);
root.top().pad(5).defaults().space(5);
TextButton button = new TextButton("New", skin);
root.add(button);
button.addListener(new ChangeListener() {
public void changed(ChangeEvent event, Actor actor) {
}
});
button = new TextButton("Save", skin);
root.add(button);
button.addListener(new ChangeListener() {
public void changed(ChangeEvent event, Actor actor) {
}
});
button = new TextButton("Load", skin);
root.add(button);
button.addListener(new ChangeListener() {
public void changed(ChangeEvent event, Actor actor) {
}
});
button = new TextButton("Spaceship", skin);
root.add(button);
button.addListener(new ChangeListener() {
public void changed(ChangeEvent event, Actor actor) {
}
});
button = new TextButton("Planet", skin);
root.add(button);
button.addListener(new ChangeListener() {
public void changed(ChangeEvent event, Actor actor) {
}
});
}
private void newWorld() {
world = new GameWorld();
World b2World = new World(new Vector2(0, -9), true);
world.spaceShip = new SpaceShip();
world.spaceShip.init(b2World);
}
private void saveWorld() {
}
private void loadWorld() {
}
@Override
public void render () {
stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
stage.draw();
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(Assets.spaceShip, world.spaceShip.position.x, world.spaceShip.position.y, world.spaceShip.dimension.x, world.spaceShip.dimension.y);
for(GameObject object: world.objects) {
if(object instanceof Planet) {
batch.draw(Assets.planet, object.position.x, object.position.y);
}
}
batch.end();
}
public void resize (int width, int height) {
stage.getViewport().update(width, height, true);
}
@Override
public void dispose() {
}
}
|
package com.spaceproject.systems;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.systems.IteratingSystem;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
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.graphics.g3d.ModelBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.spaceproject.SpaceProject;
import com.spaceproject.components.SeedComponent;
import com.spaceproject.components.Sprite3DComponent;
import com.spaceproject.components.TextureComponent;
import com.spaceproject.components.TransformComponent;
import com.spaceproject.config.WorldConfig;
import com.spaceproject.generation.TextureFactory;
import com.spaceproject.generation.noise.NoiseBuffer;
import com.spaceproject.screens.GameScreen;
import com.spaceproject.ui.Tile;
import com.spaceproject.utility.IRequireGameContext;
import com.spaceproject.utility.Mappers;
import java.util.ArrayList;
import java.util.Comparator;
public class WorldRenderingSystem extends IteratingSystem implements IRequireGameContext {
// rendering
private OrthographicCamera cam;
private SpriteBatch spriteBatch;
private ModelBatch modelBatch;
// array of entities to render
private Array<Entity> renderQueue = new Array<Entity>();
// render order. sort by depth, z axis determines what order to draw
private Comparator<Entity> comparator = new Comparator<Entity>() {
@Override
public int compare(Entity entityA, Entity entityB) {
return (int) Math.signum(Mappers.transform.get(entityB).zOrder
- Mappers.transform.get(entityA).zOrder);
}
};
private Array<Entity> renderQueue3D = new Array<Entity>();
private ArrayList<Tile> tiles = Tile.defaultTiles;
private NoiseBuffer noise;
private int surround; //how many tiles to draw around the camera
private Texture tileTex = TextureFactory.createTile(new Color(1f, 1f, 1f, 1f));
WorldConfig worldCFG;
private boolean debugShowEdgeTile = false;
public WorldRenderingSystem() {
super(Family.all(TransformComponent.class).one(TextureComponent.class, Sprite3DComponent.class).get());
worldCFG = SpaceProject.configManager.getConfig(WorldConfig.class);
this.cam = GameScreen.cam;
this.spriteBatch = GameScreen.batch;
modelBatch = new ModelBatch();
surround = 30;//TODO: split into surrondX/Y, change to be calculated by tileSize and window height/width
}
@Override
public void initContext(GameScreen gameScreen) {
SeedComponent seedComp = gameScreen.getCurrentPlanet().getComponent(SeedComponent.class);
loadMap(seedComp.seed);
}
private void loadMap(long seed) {
//TODO: rendering system should not be responsible for loading map, create world loading system.
long time = System.currentTimeMillis();
long timeout = 10000;
do {
noise = GameScreen.noiseManager.getNoiseForSeed(seed);
if ((System.currentTimeMillis() - time) > timeout) {
Gdx.app.log(this.getClass().getSimpleName(), "could not find seed for noise: " + seed);
//TODO: if not cached and if not in process of being generated, only then generate. but this should probably never happen?
//GameScreen.noiseManager.loadOrCreateNoiseFor(seed, PlanetComponent);
}
} while (noise == null);
}
@Override
public void update(float delta) {
super.update(delta); //adds entities to render queue
//clear screen
Gdx.gl20.glClearColor(0, 0, 0, 1);
Gdx.gl.glClearDepthf(1f);
Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
spriteBatch.setProjectionMatrix(cam.combined);
spriteBatch.begin();
//render background tiles
drawTiles(worldCFG.tileSize);
//draw game objects
drawEntities();
spriteBatch.end();
modelBatch.begin(cam);
draw3DRenderables(delta);
modelBatch.end();
}
private void drawEntities() {
spriteBatch.setColor(Color.WHITE);
//sort render order of entities
renderQueue.sort(comparator);
//render all textures
for (Entity entity : renderQueue) {
TextureComponent tex = Mappers.texture.get(entity);
if (tex.texture == null) continue;
TransformComponent t = Mappers.transform.get(entity);
float width = tex.texture.getWidth();
float height = tex.texture.getHeight();
float originX = width * 0.5f; //center
float originY = height * 0.5f; //center
//draw texture
spriteBatch.draw(tex.texture, (t.pos.x - originX), (t.pos.y - originY),
originX, originY,
width, height,
tex.scale, tex.scale,
MathUtils.radiansToDegrees * t.rotation,
0, 0, (int) width, (int) height, false, false);
}
renderQueue.clear();
}
private void drawTiles(int tileSize) {
// calculate tile that the camera is in
int centerX = (int) (cam.position.x / tileSize);
int centerY = (int) (cam.position.y / tileSize);
// subtract 1 from tile position if less than zero to account for -1/n = 0
if (cam.position.x < 0) --centerX;
if (cam.position.y < 0) --centerY;
for (int tileY = centerY - surround; tileY <= centerY + surround; tileY++) {
for (int tileX = centerX - surround; tileX <= centerX + surround; tileX++) {
//wrap tiles when position is outside of map
int tX = tileX % noise.heightMap.length;
int tY = tileY % noise.heightMap.length;
if (tX < 0) tX += noise.heightMap.length;
if (tY < 0) tY += noise.heightMap.length;
//render tile
Color tileColor = tiles.get(noise.tileMap[tX][tY]).getColor();
if (debugShowEdgeTile) {
if (tX == noise.heightMap.length - 1 || tY == noise.heightMap.length - 1)
tileColor = Color.BLACK;
}
spriteBatch.setColor(tileColor);
spriteBatch.draw(tileTex,
tileX * tileSize,
tileY * tileSize,
tileSize, tileSize);
}
}
}
private void draw3DRenderables(float delta) {
for (Entity entity : renderQueue3D) {
Sprite3DComponent sprite3D = Mappers.sprite3D.get(entity);
TransformComponent t = Mappers.transform.get(entity);
/*
if (Gdx.input.isKeyPressed(Input.Keys.Q)) {
sprite3D.renderable.angle += 15*delta;
}
if (Gdx.input.isKeyPressed(Input.Keys.E)) {
sprite3D.renderable.angle -= 15*delta;
}
if (Gdx.input.isKeyPressed(Input.Keys.R)) {
sprite3D.renderable.angle += (float)Math.PI;
}
System.out.println(sprite3D.renderable.angle * MathUtils.radDeg);
*/
/*
//TODO: would prefer to use this method rather than direct world transform, problems:
// set() seems to overwrite previous rotation only applying last called set
// setEulerAnglesRad() seems to apply pitch and yaw in the opposite order we desire
sprite3D.renderable.position.set(t.pos.x, t.pos.y, -50);
//sprite3D.renderable.rotation.set(Vector3.X, MathUtils.radDeg * sprite3D.renderable.angle);//"roll"
//sprite3D.renderable.rotation.set(Vector3.Z, MathUtils.radDeg * t.rotation);//"orientation facing"
sprite3D.renderable.rotation.setEulerAnglesRad(0, sprite3D.renderable.angle, t.rotation);//this applies in the wrong order resulting in funny rotation
sprite3D.renderable.update();
*/
//TODO: the switch to renderables from textures seems to have a performance impact. currently it's a mesh and texture per entity.
//see https://xoppa.github.io/blog/a-simple-card-game/#reduce-the-number-of-render-calls
sprite3D.renderable.worldTransform.setToRotation(Vector3.Z, MathUtils.radDeg * t.rotation);
sprite3D.renderable.worldTransform.rotate(Vector3.X, MathUtils.radDeg * sprite3D.renderable.angle);
sprite3D.renderable.worldTransform.setTranslation(t.pos.x, t.pos.y, -50);
sprite3D.renderable.worldTransform.scale(sprite3D.renderable.scale.x, sprite3D.renderable.scale.y, sprite3D.renderable.scale.z);
modelBatch.render(sprite3D.renderable);
}
renderQueue3D.clear();
}
@Override
public void processEntity(Entity entity, float deltaTime) {
if (Mappers.texture.get(entity) != null) {
//Add entities to render queue
renderQueue.add(entity);
} else {
renderQueue3D.add(entity);
}
}
}
|
package com.intuit.karate.ui;
import com.intuit.karate.CallContext;
import com.intuit.karate.Logger;
import com.intuit.karate.core.ExecutionContext;
import com.intuit.karate.core.Feature;
import com.intuit.karate.core.FeatureContext;
import com.intuit.karate.core.FeatureExecutionUnit;
import com.intuit.karate.core.FeatureParser;
import com.intuit.karate.core.ScenarioExecutionUnit;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javafx.scene.layout.BorderPane;
/**
*
* @author pthomas3
*/
public class AppSession2 {
private final Logger logger = new Logger();
private final ExecutionContext exec;
private final FeatureExecutionUnit featureUnit;
private final BorderPane rootPane = new BorderPane();
private final FeatureOutlinePanel featureOutlinePanel;
private final LogPanel logPanel;
private final List<ScenarioPanel2> scenarioPanels;
public AppSession2(File featureFile, String envString) {
Feature feature = FeatureParser.parse(featureFile);
FeatureContext featureContext = new FeatureContext(envString, feature, null, logger);
CallContext callContext = new CallContext(null, true);
exec = new ExecutionContext(System.currentTimeMillis(), featureContext, callContext, null, null, null, null);
featureUnit = new FeatureExecutionUnit(exec);
featureUnit.init();
featureOutlinePanel = new FeatureOutlinePanel(this);
List<ScenarioExecutionUnit> units = featureUnit.getScenarioExecutionUnits();
scenarioPanels = new ArrayList(units.size());
units.forEach(unit -> {
unit.init();
scenarioPanels.add(new ScenarioPanel2(this, unit));
});
rootPane.setLeft(featureOutlinePanel);
logPanel = new LogPanel(logger);
rootPane.setBottom(logPanel);
}
public void resetAll() {
scenarioPanels.forEach(scenarioPanel -> scenarioPanel.reset());
}
public void runAll() {
scenarioPanels.forEach(scenarioPanel -> scenarioPanel.runAll());
}
public BorderPane getRootPane() {
return rootPane;
}
public FeatureOutlinePanel getFeatureOutlinePanel() {
return featureOutlinePanel;
}
public void setSelectedScenario(int index) {
if (index == -1 || index > scenarioPanels.size() || scenarioPanels.size() == 0) {
return;
}
rootPane.setCenter(scenarioPanels.get(index));
}
public Logger getLogger() {
return logger;
}
public FeatureExecutionUnit getFeatureExecutionUnit() {
return featureUnit;
}
public List<ScenarioExecutionUnit> getScenarioExecutionUnits() {
return featureUnit.getScenarioExecutionUnits();
}
public void logVar(Var var) {
logPanel.append(var.toString());
}
}
|
package se.citerus.cqrs.bookstore.admin.resource;
import org.joda.time.LocalDate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.citerus.cqrs.bookstore.admin.api.OrderActivationRequest;
import se.citerus.cqrs.bookstore.admin.client.order.OrderClient;
import se.citerus.cqrs.bookstore.admin.client.order.OrderDto;
import javax.validation.Valid;
import javax.ws.rs.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
@Path("admin")
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
public class AdminResource {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final OrderClient orderClient;
public AdminResource(OrderClient orderClient) {
this.orderClient = orderClient;
}
@GET
@Path("orders")
public List<OrderDto> getOrders() {
List<OrderDto> projections = orderClient.listOrders();
logger.info("Returning [{}] orders", projections.size());
return projections;
}
@GET
@Path("events")
public List<Object[]> getEvents() {
List<Map<String, Object>> allEvents = orderClient.getAllEvents();
List<Object[]> eventsToReturn = new LinkedList<>();
for (Map event : allEvents) {
eventsToReturn.add(new Object[]{event.get("type").toString(), event});
}
logger.info("Returning [{}] events", eventsToReturn.size());
return eventsToReturn;
}
@POST
@Path("order-activation-requests")
public void orderActivationRequest(@Valid OrderActivationRequest activationRequest) {
logger.info("Activating orderId: " + activationRequest.orderId);
orderClient.activate(activationRequest);
}
// TODO: Add Simple bar chart to admin gui!
@GET
@Path("orders-per-day")
public Map<LocalDate, Integer> getOrdersPerDay() {
return orderClient.getOrdersPerDay();
}
}
|
package com.xasecure.authorization.hadoop.log;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.PrivilegedExceptionAction;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.helpers.LogLog;
public class HdfsFileAppender extends FileAppender {
// Constants for checking the DatePattern
public static final String MINUTES ="Min";
public static final String HOURS ="Hr";
public static final String DAYS ="Day";
public static final String WEEKS ="Week";
public static final String MONTHS ="Month";
// The code assumes that the following constants are in a increasing sequence.
public static final int TOP_OF_TROUBLE = -1;
public static final int TOP_OF_MINUTE = 0;
public static final int TOP_OF_HOUR = 1;
public static final int HALF_DAY = 2;
public static final int TOP_OF_DAY = 3;
public static final int TOP_OF_WEEK = 4;
public static final int TOP_OF_MONTH = 5;
/**
* The date pattern. By default, the pattern is set to "1Day" meaning daily rollover.
*/
private String hdfsFileRollingInterval = "1Day";
private String fileRollingInterval = "1Day";
private String scheduledFileCache;
/**
* The next time we estimate a rollover should occur.
*/
private long nextCheck = System.currentTimeMillis() - 1;
private long prevnextCheck = nextCheck;
private long nextCheckLocal = System.currentTimeMillis() -1;
private long prevnextCheckLocal = nextCheckLocal;
private Date now = new Date();
private Date nowLocal = now;
private SimpleDateFormat sdf;
private RollingCalendar rc = new RollingCalendar();
private RollingCalendar rcLocal = new RollingCalendar();
private FileOutputStream ostream = null;
private String fileSystemName;
private Layout layout = null;
private String encoding = null;
private String hdfsfileName = null;
private String actualHdfsfileName = null;
private String scheduledHdfsFileName = null;
private String fileCache = null;
private HdfsSink hs = null;
private Writer cacheWriter = null;
private FileOutputStream cacheOstream = null;
private boolean hdfsAvailable = false;
private long hdfsNextCheck = System.currentTimeMillis() - 1;
private boolean timeCheck = false;
private int hdfsFileRollOffset = 0;
private int fileRollOffset = 0;
private boolean firstTime = true;
private boolean firstTimeLocal = true;
private String hdfsLiveUpdate = "true";
boolean hdfsUpdateAllowed = true;
private String hdfsCheckInterval=null;
private String processUser = null;
private String datePattern = "'.'yyyy-MM-dd-HH-mm";
/**
* The gmtTimeZone is used only in computeCheckPeriod() method.
*/
private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");
private static final String DEFAULT_HDFSCHECKINTERVAL = "2min";
/**
* The default constructor does nothing.
*/
public HdfsFileAppender() {
}
/**
* The <b>hdfsFileRollingInterval</b> takes a string like 1min, 5min,... 1hr, 2hrs,.. 1day, 2days... 1week, 2weeks.. 1month, 2months.. for hdfs File rollover schedule.
*/
public void setHdfsFileRollingInterval(String pattern) {
hdfsFileRollingInterval = pattern;
}
/** Returns the value of the <b>hdfsFileRollingInterval</b> option. */
public String getHdfsFileRollingInterval() {
return hdfsFileRollingInterval;
}
/**
* The <b>LocalDatePattern</b> takes a string like 1min, 5min,... 1hr, 2hrs,.. 1day, 2days... 1week, 2weeks.. 1month, 2months.. for local cache File rollover schedule.
*/
public void setFileRollingInterval(String pattern) {
fileRollingInterval = pattern;
}
/** Returns the value of the <b>FileRollingInterval</b> option. */
public String getFileRollingInterval() {
return fileRollingInterval;
}
/**
* This will set liveHdfsUpdate flag , where true will update hdfs live else false will create local cache files and copy the files to hdfs
*/
public void setHdfsLiveUpdate(String val) {
hdfsLiveUpdate=val;
}
/** Returns the value of the <b>FileRollingInterval</b> option. */
public String getHdfsLiveUpdate() {
return hdfsLiveUpdate;
}
public String getHdfsCheckInterval() {
return hdfsCheckInterval;
}
public void setHdfsCheckInterval(String val){
hdfsCheckInterval = ( hdfsCheckInterval != null) ? val : DEFAULT_HDFSCHECKINTERVAL;
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String value) {
encoding = value;
}
public void activateOptions() {
super.activateOptions();
sdf = new SimpleDateFormat(datePattern);
processUser=System.getProperties().getProperty("user.name");
if(hdfsFileRollingInterval != null && fileName != null) {
now.setTime(System.currentTimeMillis());
int type = computeCheckPeriod(hdfsFileRollingInterval);
hdfsFileRollOffset = getTimeOffset(hdfsFileRollingInterval);
printHdfsPeriodicity(type,hdfsFileRollOffset);
rc.setType(type);
LogLog.debug("File name: " + fileName);
File file = new File(fileName);
scheduledHdfsFileName = hdfsfileName+sdf.format(new Date(file.lastModified()));
firstTime = true;
LogLog.debug("Local and hdfs Files" + scheduledHdfsFileName + " " +scheduledHdfsFileName) ;
} else {
LogLog.error("Either File or hdfsFileRollingInterval options are not set for appender [" + name + "].");
}
// Local Cache File
if (fileRollingInterval != null && fileCache != null){
nowLocal.setTime(System.currentTimeMillis());
int localtype = computeCheckPeriod(fileRollingInterval);
fileRollOffset = getTimeOffset(fileRollingInterval);
printLocalPeriodicity(localtype,fileRollOffset);
rcLocal.setType(localtype);
LogLog.debug("LocalCacheFile name: " + fileCache);
File fileCachehandle = new File(fileCache);
scheduledFileCache = fileCache+sdf.format(new Date(fileCachehandle.lastModified()));
firstTimeLocal = true;
} else {
LogLog.error("Either File or LocalDatePattern options are not set for appender [" + name + "].");
}
hdfsUpdateAllowed = Boolean.parseBoolean(hdfsLiveUpdate);
actualHdfsfileName = hdfsfileName + sdf.format(System.currentTimeMillis());
}
public static int containsIgnoreCase(String str1, String str2) {
return str1.toLowerCase().indexOf(str2.toLowerCase());
}
public int computeCheckPeriod(String timePattern){
if(containsIgnoreCase(timePattern, MINUTES) > 0) {
return TOP_OF_MINUTE;
}
if(containsIgnoreCase(timePattern, HOURS) > 0) {
return TOP_OF_HOUR;
}
if(containsIgnoreCase(timePattern, DAYS) > 0) {
return TOP_OF_DAY;
}
if(containsIgnoreCase(timePattern, WEEKS) > 0) {
return TOP_OF_WEEK;
}
if(containsIgnoreCase(timePattern, MONTHS) > 0) {
return TOP_OF_MONTH;
}
return TOP_OF_TROUBLE;
}
private void printHdfsPeriodicity(int type, int offset) {
switch(type) {
case TOP_OF_MINUTE:
LogLog.debug("Appender [" + name + "] to be rolled every " + offset + " minute.");
break;
case TOP_OF_HOUR:
LogLog.debug("Appender [" + name + "] to be rolled on top of every " + offset + " hour.");
break;
case HALF_DAY:
LogLog.debug("Appender [" + name + "] to be rolled at midday and midnight.");
break;
case TOP_OF_DAY:
LogLog.debug("Appender [" + name + "] to be rolled on top of every " + offset + " day.");
break;
case TOP_OF_WEEK:
LogLog.debug("Appender [" + name + "] to be rolled on top of every " + offset + " week.");
break;
case TOP_OF_MONTH:
LogLog.debug("Appender [" + name + "] to be rolled at start of every " + offset + " month.");
break;
default:
LogLog.warn("Unknown periodicity for appender [" + name + "].");
}
}
public int getTimeOffset(String timePattern){
int index;
int offset=-1;
if ((index = containsIgnoreCase(timePattern, MINUTES)) > 0) {
offset = Integer.parseInt(timePattern.substring(0,index));
}
if ((index = containsIgnoreCase(timePattern, HOURS)) > 0) {
offset = Integer.parseInt(timePattern.substring(0,index));
}
if ((index = containsIgnoreCase(timePattern, DAYS)) > 0) {
offset = Integer.parseInt(timePattern.substring(0,index));
}
if ((index = containsIgnoreCase(timePattern, WEEKS)) > 0) {
offset = Integer.parseInt(timePattern.substring(0,index));
}
if ((index = containsIgnoreCase(timePattern, MONTHS)) > 0) {
offset = Integer.parseInt(timePattern.substring(0,index));
}
return offset;
}
private void printLocalPeriodicity(int type, int offset) {
switch(type) {
case TOP_OF_MINUTE:
LogLog.debug("Appender [" + name + "] Local File to be rolled every " + offset + " minute.");
break;
case TOP_OF_HOUR:
LogLog.debug("Appender [" + name + "] Local File to be rolled on top of every " + offset + " hour.");
break;
case HALF_DAY:
LogLog.debug("Appender [" + name + "] Local File to be rolled at midday and midnight.");
break;
case TOP_OF_DAY:
LogLog.debug("Appender [" + name + "] Local File to be rolled on top of every " + offset + " day.");
break;
case TOP_OF_WEEK:
LogLog.debug("Appender [" + name + "] Local File to be rolled on top of every " + offset + " week.");
break;
case TOP_OF_MONTH:
LogLog.debug("Appender [" + name + "] Local File to be rolled at start of every " + offset + " month.");
break;
default:
LogLog.warn("Unknown periodicity for appender [" + name + "].");
}
}
/**
* Rollover the current file to a new file.
*/
private void rollOver() throws IOException {
/* Compute filename, but only if hdfsFileRollingInterval is specified */
if(hdfsFileRollingInterval == null) {
errorHandler.error("Missing hdfsFileRollingInterval option in rollOver().");
return;
}
long epochNow = System.currentTimeMillis();
String datedhdfsFileName = hdfsfileName+sdf.format(epochNow);
LogLog.debug("In rollOver epochNow" + epochNow + " " + "nextCheck: " + prevnextCheck );
// It is too early to roll over because we are still within the bounds of the current interval. Rollover will occur once the next interval is reached.
if (epochNow < prevnextCheck) {
return;
}
// close current file, and rename it to datedFilename
this.closeFile();
LogLog.debug("Rolling Over hdfs file to " + scheduledHdfsFileName);
if ( hdfsAvailable ) {
// for hdfs file we don't rollover the fike, we rename the file.
actualHdfsfileName = hdfsfileName + sdf.format(System.currentTimeMillis());
}
try {
// This will also close the file. This is OK since multiple close operations are safe.
this.setFile(fileName, false, this.bufferedIO, this.bufferSize);
} catch(IOException e) {
errorHandler.error("setFile(" + fileName + ", false) call failed.");
}
scheduledHdfsFileName = datedhdfsFileName;
}
/**
* Rollover the current Local file to a new file.
*/
private void rollOverLocal() throws IOException {
/* Compute filename, but only if datePattern is specified */
if(fileRollingInterval == null) {
errorHandler.error("Missing LocalDatePattern option in rollOverLocal().");
return;
}
long epochNow = System.currentTimeMillis();
String datedCacheFileName = fileCache+sdf.format(epochNow);
LogLog.debug("In rollOverLocal() epochNow" + epochNow + " " + "nextCheckLocal: " + prevnextCheckLocal );
// It is too early to roll over because we are still within the bounds of the current interval. Rollover will occur once the next interval is reached.
if (epochNow < prevnextCheckLocal ) {
return;
}
if (new File(fileCache).length() != 0 ) {
LogLog.debug("Rolling Local cache to " + scheduledFileCache);
this.closeCacheWriter();
File target = new File(scheduledFileCache);
if (target.exists()) {
target.delete();
}
File file = new File(fileCache);
boolean result = file.renameTo(target);
if(result) {
LogLog.debug(fileCache +" -> "+ scheduledFileCache);
} else {
LogLog.error("Failed to rename cache file ["+fileCache+"] to ["+scheduledFileCache+"].");
}
setFileCacheWriter();
scheduledFileCache = datedCacheFileName;
}
}
/**
* <p>
* Sets and <i>opens</i> the file where the log output will go. The specified file must be writable.
* <p>
* If there was already an opened file, then the previous file is closed first.
* <p>
* <b>Do not use this method directly. To configure a FileAppender or one of its subclasses, set its properties one by one and then call
* activateOptions.</b>
*
* @param fileName The path to the log file.
* @param append If true will append to fileName. Otherwise will truncate fileName.
*/
public void setFile(String file) {
// Trim spaces from both ends. The users probably does not want
// trailing spaces in file names.
String val = file.trim();
fileName=val;
fileCache=val+".cache";
}
@Override
public synchronized void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize) throws IOException {
LogLog.debug("setFile called: "+fileName+", "+append);
// It does not make sense to have immediate flush and bufferedIO.
if(bufferedIO) {
setImmediateFlush(false);
}
reset();
try {
// attempt to create file
ostream = new FileOutputStream(fileName, append);
} catch(FileNotFoundException ex) {
// if parent directory does not exist then
// attempt to create it and try to create file
// see bug 9150
File umFile = new File(fileName);
String parentName = umFile.getParent();
if (parentName != null) {
File parentDir = new File(parentName);
if(!parentDir.exists() && parentDir.mkdirs()) {
ostream = new FileOutputStream(fileName, append);
} else {
throw ex;
}
} else {
throw ex;
}
}
Writer fw = createWriter(ostream);
if(bufferedIO) {
fw = new BufferedWriter(fw, bufferSize);
}
this.setQWForFiles(fw);
this.fileName = fileName;
this.fileAppend = append;
this.bufferedIO = bufferedIO;
this.bufferSize = bufferSize;
//set cache file
setFileCacheWriter();
writeHeader();
LogLog.debug("setFile ended");
}
public void setHdfsDestination(final String name) {
//Setting the fileSystemname
String hostName = null;
String val = name.trim();
try {
hostName = InetAddress.getLocalHost().getHostName();
val=val.replaceAll("%hostname%", hostName);
String hostStr[] = val.split(":");
if ( hostStr.length > 0 ) {
fileSystemName = hostStr[0]+":"+hostStr[1]+":"+hostStr[2];
hdfsfileName = hostStr[3];
} else {
LogLog.error("Failed to set HdfsSystem and File");
}
} catch (UnknownHostException uhe) {
LogLog.error("Setting the Hdfs Desitination Failed", uhe);
}
LogLog.debug("FileSystemName:" + fileSystemName + "fileName:"+ hdfsfileName);
}
/**
* This method differentiates HdfsFileAppender from its super class.
* <p>
* Before actually logging, this method will check whether it is time to do a rollover. If it is, it will schedule the next rollover time and then rollover.
*/
@Override
protected void subAppend(LoggingEvent event) {
LogLog.debug("Called subAppend for logging into hdfs...");
long n = System.currentTimeMillis();
if(n >= nextCheck) {
now.setTime(n);
prevnextCheck = nextCheck;
nextCheck = rc.getNextCheckMillis(now,hdfsFileRollOffset);
if ( firstTime) {
prevnextCheck = nextCheck;
firstTime = false;
}
try {
if (hdfsUpdateAllowed) {
rollOver();
}
} catch(IOException e) {
LogLog.error("rollOver() failed.", e);
}
}
long nLocal = System.currentTimeMillis();
if ( nLocal > nextCheckLocal ) {
nowLocal.setTime(nLocal);
prevnextCheckLocal = nextCheckLocal;
nextCheckLocal = rcLocal.getNextCheckMillis(nowLocal, fileRollOffset);
if ( firstTimeLocal) {
prevnextCheckLocal = nextCheckLocal;
firstTimeLocal = false;
}
try {
rollOverLocal();
} catch(IOException e) {
LogLog.error("rollOverLocal() failed.", e);
}
}
this.layout = this.getLayout();
this.encoding = this.getEncoding();
// Append HDFS
appendHDFSFileSystem(event);
//super.subAppend(event);
}
@Override
protected
void reset() {
closeWriter();
this.qw = null;
//this.
this.closeHdfsWriter();
this.closeCacheWriter();
}
@Override
public synchronized void close() {
LogLog.debug("Closing all resource..");
this.closeFile();
this.closeHdfsWriter();
this.closeHdfsOstream();
this.closeFileSystem();
}
@Override
protected void closeFile() {
try {
if(this.ostream != null) {
this.ostream.close();
this.ostream = null;
}
} catch(IOException ie) {
LogLog.error("unable to close output stream", ie);
}
this.closeHdfsWriter();
this.closeHdfsOstream();
}
@Override
protected void closeWriter() {
try {
if(this.qw != null) {
this.qw.close();
this.qw = null;
}
} catch(IOException ie) {
LogLog.error("unable to close writer", ie);
}
}
@Override
public void finalize() {
super.finalize();
close();
}
private void appendHDFSFileSystem(LoggingEvent event) {
long currentTime = System.currentTimeMillis();
try {
if ( currentTime >= hdfsNextCheck ) {
LogLog.debug("About to Open fileSystem" + fileSystemName+" "+actualHdfsfileName) ;
hs = openHdfsSink(fileSystemName,actualHdfsfileName,fileCache,fileAppend,bufferedIO,bufferSize,layout,encoding,scheduledFileCache,cacheWriter,hdfsUpdateAllowed,processUser);
if (hdfsUpdateAllowed) {
// stream into hdfs only when liveHdfsUpdate flag is true else write to cache file.
hs.setOsteam();
hs.setWriter();
hs.append(event);
} else {
writeToCache(event);
}
hdfsAvailable = true;
} else {
// Write the Log To cache file util time to check hdfs availability
hdfsAvailable = false;
LogLog.debug("Hdfs Down..Will check hdfs vailability after " + hdfsNextCheck + "Current Time :" +hdfsNextCheck ) ;
writeToCache(event);
}
}
catch(Throwable t) {
// Write the Log To cache file if hdfs connect error out.
hdfsAvailable = false;
if ( !timeCheck ) {
int hdfscheckInterval = getTimeOffset(hdfsCheckInterval);
hdfsNextCheck = System.currentTimeMillis()+(1000*60*hdfscheckInterval);
timeCheck = true;
LogLog.debug("Hdfs Down..Will check hdfs vailability after " + hdfsCheckInterval , t) ;
}
writeToCache(event);
}
}
private HdfsSink openHdfsSink(String fileSystemName,String filename, String fileCache, boolean append, boolean bufferedIO,int bufferSize,Layout layout, String encoding, String scheduledCacheFile, Writer cacheWriter,boolean hdfsUpdateAllowed,String processUser) throws Throwable {
HdfsSink hs = null;
hs = HdfsSink.getInstance();
if ( hs != null)
LogLog.debug("Hdfs Sink successfully instatiated");
try {
hs.init(fileSystemName, filename, fileCache, append, bufferedIO, bufferSize, layout, encoding,scheduledCacheFile,cacheWriter,hdfsUpdateAllowed,processUser);
} catch (Throwable t) {
throw t;
}
return hs;
}
private void closeHdfsOstream() {
if (hs != null ){
LogLog.debug("Closing hdfs outstream") ;
hs.closeHdfsOstream();
}
}
private void closeHdfsWriter() {
if (hs != null) {
LogLog.debug("Closing hdfs Writer") ;
hs.closeHdfsWriter();
}
}
private void closeFileSystem() {
hs.closeHdfsSink();
}
/****** Cache File Methods **/
public void setFileCacheWriter() {
try {
setFileCacheOstream(fileCache);
} catch(IOException ie) {
LogLog.error("Logging failed while tring to write into Cache File..", ie);
}
LogLog.debug("Setting Cache Writer..");
cacheWriter = createCacheFileWriter(cacheOstream);
if(bufferedIO) {
cacheWriter = new BufferedWriter(cacheWriter, bufferSize);
}
}
private void setFileCacheOstream(String fileCache) throws IOException {
try {
cacheOstream = new FileOutputStream(fileCache, true);
} catch(FileNotFoundException ex) {
String parentName = new File(fileCache).getParent();
if (parentName != null) {
File parentDir = new File(parentName);
if(!parentDir.exists() && parentDir.mkdirs()) {
cacheOstream = new FileOutputStream(fileName, true);
} else {
throw ex;
}
} else {
throw ex;
}
}
}
public OutputStreamWriter createCacheFileWriter(OutputStream os ) {
OutputStreamWriter retval = null;
if(encoding != null) {
try {
retval = new OutputStreamWriter(os, encoding);
} catch(IOException ie) {
LogLog.warn("Error initializing output writer.");
LogLog.warn("Unsupported encoding?");
}
}
if(retval == null) {
retval = new OutputStreamWriter(os);
}
return retval;
}
public void writeToCache(LoggingEvent event) {
try {
LogLog.debug("Writing log to Cache.." + "layout: "+ this.layout.format(event) + "ignoresThowable: "+layout.ignoresThrowable() + "Writer:" + cacheWriter.toString());
cacheWriter.write(this.layout.format(event));
cacheWriter.flush();
if(layout.ignoresThrowable()) {
String[] s = event.getThrowableStrRep();
if (s != null) {
int len = s.length;
for(int i = 0; i < len; i++) {
LogLog.debug("Log:" + s[i]);
cacheWriter.write(s[i]);
cacheWriter.write(Layout.LINE_SEP);
cacheWriter.flush();
}
}
}
} catch (IOException ie) {
LogLog.error("Unable to log event message to hdfs:", ie);
}
}
public void rollOverCacheFile() {
if (new File(fileCache).length() != 0 ) {
long epochNow = System.currentTimeMillis();
String datedCacheFileName = fileCache + "." + epochNow;
LogLog.debug("Rolling over remaining cache File to new file"+ datedCacheFileName);
closeCacheWriter();
File target = new File(datedCacheFileName);
if (target.exists()) {
target.delete();
}
File file = new File(fileCache);
boolean result = file.renameTo(target);
if(result) {
LogLog.debug(fileCache +" -> "+ datedCacheFileName);
} else {
LogLog.error("Failed to rename cache file ["+fileCache+"] to ["+datedCacheFileName+"].");
}
}
}
public void closeCacheWriter() {
try {
if(cacheWriter != null) {
cacheWriter.close();
cacheWriter = null;
}
} catch(IOException ie) {
LogLog.error("unable to close cache writer", ie);
}
}
}
/**
* RollingCalendar is a helper class to HdfsFileAppender. Given a periodicity type and the current time, it computes the start of the next interval.
*/
class RollingCalendar extends GregorianCalendar {
private static final long serialVersionUID = 1L;
private int type = HdfsFileAppender.TOP_OF_TROUBLE;
RollingCalendar() {
super();
}
RollingCalendar(TimeZone tz, Locale locale) {
super(tz, locale);
}
void setType(int type) {
this.type = type;
}
public long getNextCheckMillis(Date now, int offset) {
return getNextCheckDate(now,offset).getTime();
}
public Date getNextCheckDate(Date now,int offset) {
this.setTime(now);
switch(this.type) {
case HdfsFileAppender.TOP_OF_MINUTE:
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.MINUTE, offset);
break;
case HdfsFileAppender.TOP_OF_HOUR:
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.HOUR_OF_DAY, offset);
break;
case HdfsFileAppender.HALF_DAY:
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
int hour = get(Calendar.HOUR_OF_DAY);
if(hour < 12) {
this.set(Calendar.HOUR_OF_DAY, 12);
} else {
this.set(Calendar.HOUR_OF_DAY, 0);
this.add(Calendar.DAY_OF_MONTH, 1);
}
break;
case HdfsFileAppender.TOP_OF_DAY:
this.set(Calendar.HOUR_OF_DAY, 0);
this.set(Calendar.MINUTE, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.DATE, offset);
break;
case HdfsFileAppender.TOP_OF_WEEK:
this.set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek());
this.set(Calendar.HOUR_OF_DAY, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.WEEK_OF_YEAR, offset);
break;
case HdfsFileAppender.TOP_OF_MONTH:
this.set(Calendar.DATE, 1);
this.set(Calendar.HOUR_OF_DAY, 0);
this.set(Calendar.SECOND, 0);
this.set(Calendar.MILLISECOND, 0);
this.add(Calendar.MONTH, offset);
break;
default:
throw new IllegalStateException("Unknown periodicity type.");
}
return getTime();
}
}
class HdfsSink {
private static final String DS_REPLICATION_VAL = "1";
private static final String DS_REPLICATION_KEY = "dfs.replication";
private static final String FS_DEFAULT_NAME_KEY = "fs.default.name";
private Configuration conf = null;
private FileSystem fs= null;
private Path pt = null;
private FSDataOutputStream hdfsostream = null;
private String fsName = null;
private String fileName = null;
private String fileCache = null;
private Layout layout = null;
private String encoding = null;
private Writer hdfswriter = null;
private int bufferSize;
private boolean bufferedIO=false;
private static int fstime=0;
private CacheFileWatcher cfw = null;
private boolean hdfsUpdateAllowed=true;
private String processUser=null;
HdfsSink() {
}
private static final ThreadLocal<HdfsSink> hdfssink = new ThreadLocal<HdfsSink>() {
protected HdfsSink initialValue() {
return new HdfsSink();
}
};
public static HdfsSink getInstance() {
return hdfssink.get();
}
public void init(String fileSystemName, String fileName, String fileCache,boolean append, boolean bufferedIO, int bufferSize, Layout layout, String encoding, String scheduledCacheFile, Writer cacheWriter, boolean hdfsUpdateAllowed, String processUser) throws Exception{
this.fsName=fileSystemName;
this.fileName=fileName;
this.layout=layout;
this.encoding=encoding;
this.bufferSize=bufferSize;
this.bufferedIO=bufferedIO;
this.fileCache=fileCache;
this.hdfsUpdateAllowed=hdfsUpdateAllowed;
this.processUser=processUser;
final Configuration conf= new Configuration();
conf.set(DS_REPLICATION_KEY,DS_REPLICATION_VAL);
conf.set(FS_DEFAULT_NAME_KEY, fsName);
try {
if ( fs == null) {
LogLog.debug("Opening Connection to hdfs Sytem" + this.fsName);
UserGroupInformation ugi = UserGroupInformation.createProxyUser(this.processUser, UserGroupInformation.getLoginUser());
fs = ugi.doAs( new PrivilegedExceptionAction<FileSystem>() {
public FileSystem run() throws Exception {
FileSystem filesystem = FileSystem.get(conf);
LogLog.debug("Inside UGI.." + fsName + " " + filesystem);
return filesystem;
}
});
if ( cfw == null) {
// Start the CacheFileWatcher to move the Cache file.
LogLog.debug("About to run CacheFilWatcher...");
Path hdfsfilePath = getParent();
cfw = new CacheFileWatcher(this.fs,this.fileCache,hdfsfilePath,cacheWriter,this.hdfsUpdateAllowed,conf);
cfw.start();
}
}
} catch(Exception ie) {
LogLog.error("Unable to Create hdfs logfile:" + ie.getMessage());
throw ie;
}
LogLog.debug("HdfsSystem up: " + fsName + "FS Object:" + fs);
}
public int getfstime() {
return fstime;
}
public FileSystem getFileSystem() {
return fs;
}
public Path getPath() {
return pt;
}
public Path getParent() {
Path pt = new Path(this.fileName);
return pt.getParent();
}
public void setOsteam() throws IOException {
try {
pt = new Path(this.fileName);
// if file Exist append it
if(fs.exists(pt)) {
LogLog.debug("Appending File: "+ this.fsName+":"+this.fileName+fs);
if (hdfsostream !=null) {
hdfsostream.close();
}
hdfsostream=fs.append(pt);
} else {
LogLog.debug("Creating File directories in hdfs if not present.."+ this.fsName+":"+this.fileName + fs);
String parentName = new Path(this.fileName).getParent().toString();
if(parentName != null) {
Path parentDir = new Path(parentName);
if (!fs.exists(parentDir) ) {
LogLog.debug("Creating Parent Directory: " + parentDir );
fs.mkdirs(parentDir);
}
}
hdfsostream = fs.create(pt);
}
} catch (IOException ie) {
LogLog.debug("Error While appending hdfsd file." + ie);
throw ie;
}
}
public void setWriter() {
LogLog.debug("Setting Writer..");
hdfswriter = createhdfsWriter(hdfsostream);
if(bufferedIO) {
hdfswriter = new BufferedWriter(hdfswriter, bufferSize);
}
}
public Writer getWriter() {
return hdfswriter;
}
public void append(LoggingEvent event) throws IOException {
try {
LogLog.debug("Writing log to HDFS." + "layout: "+ this.layout.format(event) + "ignoresThowable: "+layout.ignoresThrowable() + "Writer:" + hdfswriter.toString());
hdfswriter.write(this.layout.format(event));
hdfswriter.flush();
if(layout.ignoresThrowable()) {
String[] s = event.getThrowableStrRep();
if (s != null) {
int len = s.length;
for(int i = 0; i < len; i++) {
LogLog.debug("Log:" + s[i]);
hdfswriter.write(s[i]);
hdfswriter.write(Layout.LINE_SEP);
hdfswriter.flush();
}
}
}
} catch (IOException ie) {
LogLog.error("Unable to log event message to hdfs:", ie);
throw ie;
}
}
public void writeHeader() throws IOException {
LogLog.debug("Writing log header...");
try {
if(layout != null) {
String h = layout.getHeader();
if(h != null && hdfswriter != null)
LogLog.debug("Log header:" + h);
hdfswriter.write(h);
hdfswriter.flush();
}
} catch (IOException ie) {
LogLog.error("Unable to log header message to hdfs:", ie);
throw ie;
}
}
public
void writeFooter() throws IOException{
LogLog.debug("Writing footer header...");
try {
if(layout != null) {
String f = layout.getFooter();
if(f != null && hdfswriter != null) {
LogLog.debug("Log:" + f);
hdfswriter.write(f);
hdfswriter.flush();
}
}
} catch (IOException ie) {
LogLog.debug("Unable to log header message to hdfs:", ie);
throw ie;
}
}
public void closeHdfsOstream() {
try {
if(this.hdfsostream != null) {
this.hdfsostream.close();
this.hdfsostream = null;
}
} catch(IOException ie) {
LogLog.error("unable to close output stream", ie);
}
}
public void closeHdfsWriter() {
try {
if(hdfswriter != null) {
hdfswriter.close();
hdfswriter = null;
}
} catch(IOException ie) {
LogLog.error("unable to hfds writer", ie);
}
}
public void closeHdfsSink() {
try {
if (fs !=null) {
fs.close();
}
} catch (IOException ie) {
LogLog.error("Unable to close hdfs " + fs ,ie);
}
}
public OutputStreamWriter createhdfsWriter(FSDataOutputStream os ) {
OutputStreamWriter retval = null;
if(encoding != null) {
try {
retval = new OutputStreamWriter(os, encoding);
} catch(IOException ie) {
LogLog.warn("Error initializing output writer.");
LogLog.warn("Unsupported encoding?");
}
}
if(retval == null) {
retval = new OutputStreamWriter(os);
}
return retval;
}
}
// CacheFileWatcher Thread
class CacheFileWatcher extends Thread {
long CACHEFILE_WATCHER_SLEEP_TIME = 1000*60*2;
Configuration conf = null;
private FileSystem fs = null;
private String cacheFile = null;
private File parentDir = null;
private File[] files = null;
private Path fsPath = null;
private Path hdfsfilePath = null;
private Writer cacheWriter = null;
private boolean hdfsUpdateAllowed=true;
private boolean cacheFilesCopied = false;
CacheFileWatcher(FileSystem fs, String cacheFile, Path hdfsfilePath, Writer cacheWriter, boolean hdfsUpdateAllowed, Configuration conf) {
this.fs = fs;
this.cacheFile = cacheFile;
this.conf = conf;
this.hdfsfilePath = hdfsfilePath;
this.cacheWriter = cacheWriter;
this.hdfsUpdateAllowed = hdfsUpdateAllowed;
}
public void run(){
LogLog.debug("CacheFileWatcher Started");
while (!cacheFilesCopied ){
if (hdfsUpdateAllowed) {
rollRemainingCacheFile();
}
if ( !cacheFilePresent(cacheFile) ) {
try {
Thread.sleep(CACHEFILE_WATCHER_SLEEP_TIME);
} catch (InterruptedException ie) {
LogLog.error("Unable to complete the CatchFileWatcher Sleep", ie);
}
} else {
try {
copyCacheFilesToHdfs();
if (hdfsUpdateAllowed) {
cacheFilesCopied = true;
} else {
cacheFilesCopied = false;
}
} catch (Throwable t) {
// Error While copying the file to hdfs and thread goes for sleep and check later
cacheFilesCopied = false;
LogLog. error("Error while copying Cache Files to hdfs..Sleeping for next try",t);
try {
Thread.sleep(CACHEFILE_WATCHER_SLEEP_TIME);
} catch (InterruptedException ie) {
LogLog.error("Unable to complete the CatchFileWatcher Sleep", ie);
}
}
}
}
}
public boolean cacheFilePresent(String filename) {
String parent = new File(filename).getParent();
if ( parent != null ) {
parentDir = new File(parent);
fsPath = new Path(parent);
files = parentDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File parentDir, String name) {
return name.matches(".*cache.+");
}
});
if ( files.length > 0) {
LogLog.debug("CacheFile Present..");
return true;
}
}
return false;
}
public void copyCacheFilesToHdfs() throws Throwable{
try {
if (!fs.exists(hdfsfilePath) ) {
LogLog.debug("Creating Parent Directory: " + hdfsfilePath );
fs.mkdirs(hdfsfilePath);
}
} catch ( Throwable t) {
throw t;
}
for ( File cacheFile : files) {
try {
LogLog.debug("Copying Files..." + "File Path: " + fsPath + "CacheFile: " +cacheFile + "HDFS Path:" + hdfsfilePath);
FileUtil.copy(cacheFile, this.fs, this.hdfsfilePath, true, this.conf);
} catch (Throwable t) {
throw t;
}
}
}
public void rollRemainingCacheFile() {
String datePattern = "'.'yyyy-MM-dd-HH-mm";
SimpleDateFormat sdf = new SimpleDateFormat(datePattern);
if (new File(cacheFile).length() != 0 ) {
long epochNow = System.currentTimeMillis();
String datedCacheFileName = cacheFile + sdf.format(epochNow);
LogLog.debug("Rolling over remaining cache File "+ datedCacheFileName);
closeCacheFile();
File target = new File(datedCacheFileName);
if (target.exists()) {
target.delete();
}
File file = new File(cacheFile);
boolean result = file.renameTo(target);
if(result) {
LogLog.debug(cacheFile +" -> "+ datedCacheFileName);
} else {
LogLog.error("Failed to rename cache file ["+cacheFile+"] to ["+datedCacheFileName+"].");
}
}
}
public void closeCacheFile() {
try {
if(cacheWriter != null) {
cacheWriter.close();
cacheWriter = null;
}
} catch(IOException ie) {
LogLog.error("unable to close cache writer", ie);
}
}
}
|
package com.mapzen.android.graphics;
import com.mapzen.R;
import com.mapzen.android.core.CoreDI;
import com.mapzen.android.graphics.model.MapStyle;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.Locale;
import javax.inject.Inject;
/**
* Wrapper for Tangram MapView that initializes {@link MapzenMap} for client applications.
*/
public class MapView extends RelativeLayout {
private static final String MAPZEN_RIGHTS = "https://mapzen.com/rights/";
public static final int OVERLAY_MODE_SDK = 0;
public static final int OVERLAY_MODE_CLASSIC = 1;
@Inject MapInitializer mapInitializer;
TangramMapView tangramMapView;
CompassView compass;
ImageButton findMe;
ImageButton zoomIn;
ImageButton zoomOut;
TextView attribution;
private int overlayMode = OVERLAY_MODE_SDK;
private MapzenMap mapzenMap;
/**
* Create new instance.
*/
public MapView(Context context) {
super(context);
initDI(context);
initViews(context);
}
/**
* Create new instance.
*/
public MapView(Context context, AttributeSet attrs) {
super(context, attrs);
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MapView);
try {
overlayMode = a.getInteger(R.styleable.MapView_overlayMode, OVERLAY_MODE_SDK);
} finally {
a.recycle();
}
initDI(context);
initViews(context);
}
private void initDI(Context context) {
CoreDI.init(context.getApplicationContext());
CoreDI.component().inject(this);
}
private void initViews(Context context) {
final LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (inflater != null) {
if (overlayMode == OVERLAY_MODE_SDK) {
inflater.inflate(R.layout.mz_view_map, this);
} else {
inflater.inflate(R.layout.mz_view_map_classic, this);
}
}
}
@Override protected void onFinishInflate() {
super.onFinishInflate();
tangramMapView = (TangramMapView) findViewById(R.id.mz_tangram_map);
compass = (CompassView) findViewById(R.id.mz_compass);
findMe = (ImageButton) findViewById(R.id.mz_find_me);
zoomIn = (ImageButton) findViewById(R.id.mz_zoom_in);
zoomOut = (ImageButton) findViewById(R.id.mz_zoom_out);
attribution = (TextView) findViewById(R.id.mz_attribution);
final TextView attribution = (TextView) findViewById(R.id.mz_attribution);
attribution.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
Intent intent = new Intent();
Uri uri = Uri.parse(MAPZEN_RIGHTS);
intent.setData(uri);
MapView.this.getContext().startActivity(intent);
}
});
}
/**
* Get the underlying Tangram map object.
*/
public TangramMapView getTangramMapView() {
return tangramMapView;
}
/**
* Load map asynchronously using APK key declared in XML resources. For example:
* {@code <string name="mapzen_api_key">[YOUR_API_KEY]</string>}
*
* @param callback listener to be invoked when map is initialized and ready to use.
*/
public void getMapAsync(@NonNull OnMapReadyCallback callback) {
mapInitializer.init(this, callback);
}
/**
* Load map asynchronously using APK key declared in XML resources. For example:
* {@code <string name="mapzen_api_key">[YOUR_API_KEY]</string>}
*
* @param mapStyle mapStyle that should be set.
* @param callback listener to be invoked when map is initialized and ready to use.
*/
public void getMapAsync(MapStyle mapStyle, @NonNull OnMapReadyCallback callback) {
mapInitializer.init(this, mapStyle, callback);
}
/**
* Load map asynchronously using APK key declared in XML resources. For example:
* {@code <string name="mapzen_api_key">[YOUR_API_KEY]</string>}
*
* @param mapStyle mapStyle that should be set.
* @param locale used to determine language that should be used for map labels.
* @param callback listener to be invoked when map is initialized and ready to use.
*/
public void getMapAsync(MapStyle mapStyle, Locale locale, @NonNull OnMapReadyCallback callback) {
mapInitializer.init(this, mapStyle, locale, callback);
}
/**
* Get the compass button.
*/
public CompassView getCompass() {
return compass;
}
/**
* Show compass button.
*/
public CompassView showCompass() {
compass.setVisibility(View.VISIBLE);
return compass;
}
/**
* Hide compass button.
*/
public void hideCompass() {
compass.setVisibility(View.GONE);
}
/**
* Get the find me button.
*/
public ImageButton getFindMe() {
return findMe;
}
/**
* Show button for finding user's location on map.
*/
public ImageButton showFindMe() {
findMe.setVisibility(View.VISIBLE);
return findMe;
}
/**
* Hide button for finding user's location on map.
*/
public void hideFindMe() {
findMe.setVisibility(View.GONE);
}
/**
* Get the zoom in button.
*/
public ImageButton getZoomIn() {
return zoomIn;
}
/**
* Show button for zooming in.
*/
public ImageButton showZoomIn() {
zoomIn.setVisibility(View.VISIBLE);
return zoomIn;
}
/**
* Hide button for zooming in.
*/
public void hideZoomIn() {
zoomIn.setVisibility(View.GONE);
}
/**
* Get the zoom out button.
*/
public ImageButton getZoomOut() {
return zoomOut;
}
/**
* Show button for zooming out.
*/
public ImageButton showZoomOut() {
zoomOut.setVisibility(View.VISIBLE);
return zoomOut;
}
/**
* Hide button for zooming out.
*/
public void hideZoomOut() {
zoomOut.setVisibility(View.GONE);
}
/**
* Return the attribution text view.
*/
public TextView getAttribution() {
return attribution;
}
/**
* You must call this method from the parent Activity/Fragment's corresponding method.
*/
public void onDestroy() {
if (mapzenMap != null) {
mapzenMap.onDestroy();
}
getTangramMapView().onDestroy();
}
void setMapzenMap(MapzenMap mapzenMap) {
this.mapzenMap = mapzenMap;
}
}
|
package com.mlykotom.valifi;
import android.content.Context;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
import android.databinding.BindingAdapter;
import android.databinding.Observable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.design.widget.TextInputLayout;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Base class for validation field. Holds value change listener and basic rules for validation.
*
* @param <ValueType> of the whole field (for now it's String and beta Calendar)
*/
@SuppressWarnings("unused")
public abstract class ValiFieldBase<ValueType> extends BaseObservable {
protected ValueType mValue;
protected LinkedHashMap<PropertyValidator<ValueType>, String> mPropertyValidators = new LinkedHashMap<>();
protected boolean mIsEmptyAllowed = false;
@Nullable protected List<ValiFieldBase> mBoundFields;
boolean mIsChanged = false;
private boolean mIsError = false;
private String mError;
@Nullable private ValiFiForm mParentForm;
protected ValueChangedListener mValueChangedListener = new ValueChangedListener() {
@Override
public void run(boolean isImmediate) {
// notifying bound fields about change
if(mBoundFields != null) {
for(ValiFieldBase field : mBoundFields) {
if(!field.mIsChanged) continue; // notifies only changed items
field.notifyValueChanged(true);
}
}
// checking if value can be empty
ValueType actualValue = mValue;
if(mIsEmptyAllowed && (actualValue == null || whenThisFieldIsEmpty(actualValue))) {
setIsError(false, null);
notifyErrorChanged();
return;
}
// checking all set validators
for(Map.Entry<PropertyValidator<ValueType>, String> entry : mPropertyValidators.entrySet()) {
// all of setup validators must be valid, otherwise error
if(!entry.getKey().isValid(actualValue)) {
setIsError(true, entry.getValue());
notifyErrorChanged();
return;
}
}
// set valid
setIsError(false, null);
notifyErrorChanged();
}
};
private OnPropertyChangedCallback mCallback = setupOnPropertyChangedCallback();
public interface PropertyValidator<T> {
/**
* Decides whether field will be valid based on return value
*
* @param value field's actual value
* @return validity
*/
boolean isValid(@Nullable T value);
}
public ValiFieldBase() {
addOnPropertyChangedCallback(mCallback);
}
/**
* @param defaultValue if not null, will mark that field is changed
*/
public ValiFieldBase(@Nullable ValueType defaultValue) {
this();
mValue = defaultValue;
if(defaultValue != null) {
mIsChanged = true;
}
}
/**
* Error binding for TextInputLayout
*
* @param view TextInputLayout to be set with
* @param errorMessage error message to show
*/
@BindingAdapter("error")
public static void setError(TextInputLayout view, String errorMessage) {
view.setError(errorMessage);
}
/**
* Error binding for EditText
*
* @param view EditText to be set with
* @param errorMessage error message to show
*/
@BindingAdapter("error")
public static void setError(EditText view, String errorMessage) {
view.setError(errorMessage);
}
/**
* Helper for clearing all specified validated fields
*
* @param fields to be cleansed
*/
public static void destroyAll(ValiFieldBase... fields) {
for(ValiFieldBase field : fields) {
field.destroy();
}
}
/**
* Checking for specific type if value is empty.
* Used for checking if empty is allowed.
*
* @param actualValue value when checking
* @return true when value is empty, false when values is not empty (e.g for String, use isEmpty())
* @see #mCallback
*/
protected abstract boolean whenThisFieldIsEmpty(@NonNull ValueType actualValue);
/**
* Any inherited field must be able to convert to String.
* This is so that it's possible to show it in TextView/EditText
*
* @return converted string (e.g. for Date = formatted string)
*/
protected abstract String convertValueToString();
/**
* Allows empty field to be valid.
* Useful when some field is not necessary but needs to be in proper format if filled.
*
* @param isEmptyAllowed if true, field may be empty or null to be valid
* @return this, co validators can be chained
*/
public ValiFieldBase<ValueType> setEmptyAllowed(boolean isEmptyAllowed) {
mIsEmptyAllowed = isEmptyAllowed;
return this;
}
/**
* @return the containing value of the field
*/
public ValueType get() {
return mValue;
}
/**
* Wrapper for easy setting value
*
* @param value to be set and notified about change
*/
public void set(@Nullable ValueType value) {
if((value == mValue) || (value != null && value.equals(mValue))) return;
mValue = value;
notifyValueChanged(false);
}
/**
* This may be shown in layout as actual value
*
* @return value in string displayable in TextInputLayout/EditText
*/
@Bindable
public String getValue() {
return convertValueToString();
}
/**
* Sets new value (from binding)
*
* @param value to be set, if the same as older, skips
*/
public void setValue(@Nullable String value) {
set((ValueType) value); // TODO convert value (is it possible?)
}
/**
* Removes property change callback and clears custom validators
*/
public void destroy() {
removeOnPropertyChangedCallback(mCallback);
mPropertyValidators.clear();
mPropertyValidators = null;
if(mBoundFields != null) {
mBoundFields.clear();
mBoundFields = null;
}
mParentForm = null;
mIsChanged = false;
mIsError = false;
mIsEmptyAllowed = false;
}
/**
* Bundles this field to form
*
* @param form which validates all bundled fields
*/
public void setFormValidation(@Nullable ValiFiForm form) {
mParentForm = form;
}
@Nullable
public ValiFiForm getBoundForm() {
return mParentForm;
}
@Bindable
public String getError() {
return mError;
}
/**
* Might be used for checking submit buttons because isError might be true when data not changed
*
* @return if property was changed and is valid
*/
@Bindable
public boolean getIsValid() {
return !mIsError & (mIsChanged | mIsEmptyAllowed);
}
/**
* @param errorResource to be shown (got from app's context)
* @param targetField validates with this field
* @return this, so validators can be chained
* @see #addVerifyFieldValidator(String, ValiFieldBase)
*/
public ValiFieldBase<ValueType> addVerifyFieldValidator(@StringRes int errorResource, final ValiFieldBase<ValueType> targetField) {
String errorMessage = getAppContext().getString(errorResource);
return addVerifyFieldValidator(errorMessage, targetField);
}
/**
* Validates equality of this value and specified field's value.
* If specified field changes, it notifies this field's change listener.
*
* @param errorMessage to be shown if not valid
* @param targetField validates with this field
* @return this, so validators can be chained
*/
public ValiFieldBase<ValueType> addVerifyFieldValidator(String errorMessage, final ValiFieldBase<ValueType> targetField) {
addCustomValidator(errorMessage, new PropertyValidator<ValueType>() {
@Override
public boolean isValid(@Nullable ValueType value) {
ValueType fieldVal = targetField.get();
return (value == targetField.get()) || (value != null && value.equals(fieldVal));
}
});
targetField.addBoundField(this);
return this;
}
/**
* Ability to add custom validators
*
* @param validator which has value inside
* @return this, so validators can be chained
*/
public ValiFieldBase<ValueType> addCustomValidator(PropertyValidator<ValueType> validator) {
mPropertyValidators.put(validator, null);
return this;
}
public ValiFieldBase<ValueType> addCustomValidator(@StringRes int errorResource, PropertyValidator<ValueType> validator) {
String errorMessage = getAppContext().getString(errorResource);
return addCustomValidator(errorMessage, validator);
}
public ValiFieldBase<ValueType> addCustomValidator(String errorMessage, PropertyValidator<ValueType> validator) {
mPropertyValidators.put(validator, errorMessage);
if(mIsChanged) {
notifyValueChanged(true);
}
return this;
}
/**
* Internaly fields can be binded together so that when one changes, it notifies others
*
* @param field to be notified when this field changed
*/
protected void addBoundField(ValiFieldBase field) {
if(mBoundFields == null) {
mBoundFields = new ArrayList<>();
}
mBoundFields.add(field);
}
protected int getErrorRes(@ValiFi.Builder.ValiFiErrorResource int field) {
return ValiFi.getErrorRes(field);
}
protected Pattern getPattern(@ValiFi.Builder.ValiFiPattern int field) {
return ValiFi.getPattern(field);
}
protected Context getAppContext() {
return ValiFi.getContext();
}
/**
* Sets error state to this field + optionally to binded form
*
* @param isError whether there's error or no
* @param errorMessage to be shown
*/
protected void setIsError(boolean isError, @Nullable String errorMessage) {
mIsChanged = true;
mIsError = isError;
mError = errorMessage;
notifyValidationChanged();
if(mParentForm != null) {
mParentForm.notifyValidationChanged(this);
}
// else{
// // TODO this could be here instead of few lines above and saves some method calls
// notifyPropertyChanged(com.mlykotom.valifi.BR.isValid);
}
/**
* Notifies that value changed (internally)
*
* @param isImmediate if true, does not call binding notifier
*/
protected void notifyValueChanged(boolean isImmediate) {
if(isImmediate) {
mValueChangedListener.run(true);
} else {
notifyPropertyChanged(com.mlykotom.valifi.BR.value);
}
}
private void notifyValidationChanged() {
notifyPropertyChanged(com.mlykotom.valifi.BR.isValid);
}
private void notifyErrorChanged() {
notifyPropertyChanged(com.mlykotom.valifi.BR.error);
}
private OnPropertyChangedCallback setupOnPropertyChangedCallback() {
return new OnPropertyChangedCallback() {
@Override
public void onPropertyChanged(Observable observable, int brId) {
if(brId != com.mlykotom.valifi.BR.value) return;
mValueChangedListener.run(false);
}
};
}
public static abstract class ValueChangedListener implements Runnable {
public abstract void run(boolean isImmediate);
@Override
public final void run() {
run(false);
}
}
}
|
package com.ForgeEssentials.core;
import java.io.File;
import net.minecraftforge.common.MinecraftForge;
import com.ForgeEssentials.api.data.DataStorageManager;
import com.ForgeEssentials.core.commands.CommandFECredits;
import com.ForgeEssentials.core.commands.CommandFEDebug;
import com.ForgeEssentials.core.commands.CommandFEReload;
import com.ForgeEssentials.core.commands.CommandFEVersion;
import com.ForgeEssentials.core.compat.DuplicateCommandRemoval;
import com.ForgeEssentials.core.misc.BannedItems;
import com.ForgeEssentials.core.misc.ItemList;
import com.ForgeEssentials.core.misc.LoginMessage;
import com.ForgeEssentials.core.misc.ModListFile;
import com.ForgeEssentials.core.moduleLauncher.ModuleLauncher;
import com.ForgeEssentials.core.network.PacketHandler;
import com.ForgeEssentials.data.ForgeConfigDataDriver;
import com.ForgeEssentials.data.NBTDataDriver;
import com.ForgeEssentials.data.SQLDataDriver;
import com.ForgeEssentials.data.StorageManager;
import com.ForgeEssentials.util.FunctionHelper;
import com.ForgeEssentials.util.Localization;
import com.ForgeEssentials.util.MiscEventHandler;
import com.ForgeEssentials.util.OutputHandler;
import com.ForgeEssentials.util.TeleportCenter;
import com.ForgeEssentials.util.TickTaskHandler;
import com.ForgeEssentials.util.AreaSelector.Point;
import com.ForgeEssentials.util.AreaSelector.WarpPoint;
import com.ForgeEssentials.util.AreaSelector.WorldPoint;
import com.ForgeEssentials.util.event.ForgeEssentialsEventFactory;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.Init;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.Mod.PostInit;
import cpw.mods.fml.common.Mod.PreInit;
import cpw.mods.fml.common.Mod.ServerStarted;
import cpw.mods.fml.common.Mod.ServerStarting;
import cpw.mods.fml.common.Mod.ServerStopping;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.event.FMLServerStartedEvent;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import cpw.mods.fml.common.event.FMLServerStoppingEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.network.NetworkMod.SidedPacketHandler;
import cpw.mods.fml.common.network.NetworkMod.VersionCheckHandler;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.Side;
/**
* Main mod class
*/
@NetworkMod(clientSideRequired = false, serverSideRequired = false, serverPacketHandlerSpec = @SidedPacketHandler(channels = { "ForgeEssentials" }, packetHandler = PacketHandler.class))
@Mod(modid = "ForgeEssentials", name = "Forge Essentials", version = "@VERSION@")
public class ForgeEssentials
{
@Instance(value = "ForgeEssentials")
public static ForgeEssentials instance;
public static CoreConfig config;
public ModuleLauncher mdlaunch;
public Localization localization;
public static boolean verCheck = true;
public static boolean preload;
public static String modlistLocation;
public static File FEDIR;
public BannedItems bannedItems;
private ItemList itemList;
private MiscEventHandler miscEventHandler;
@PreInit
public void preInit(FMLPreInitializationEvent e)
{
// setup fedir stuff
if (FMLCommonHandler.instance().getSide().isClient())
FEDIR = new File(FunctionHelper.getBaseDir(), "ForgeEssentials-CLIENT");
else
FEDIR = new File(FunctionHelper.getBaseDir(), "ForgeEssentials");
OutputHandler.init(e.getModLog());
config = new CoreConfig();
// Data API stuff
{
// setup
DataStorageManager.manager = new StorageManager(config.config);
// register DataDrivers
DataStorageManager.registerDriver("ForgeConfig", ForgeConfigDataDriver.class);
DataStorageManager.registerDriver("NBT", NBTDataDriver.class);
DataStorageManager.registerDriver("SQL_DB", SQLDataDriver.class);
// Register saveables..
DataStorageManager.registerSaveableClass(PlayerInfo.class);
DataStorageManager.registerSaveableClass(Point.class);
DataStorageManager.registerSaveableClass(WorldPoint.class);
DataStorageManager.registerSaveableClass(WarpPoint.class);
}
// setup modules AFTER data stuff...
miscEventHandler = new MiscEventHandler();
bannedItems = new BannedItems();
MinecraftForge.EVENT_BUS.register(bannedItems);
LoginMessage.loadFile();
mdlaunch = new ModuleLauncher();
mdlaunch.preLoad(e);
localization = new Localization();
}
@Init
public void load(FMLInitializationEvent e)
{
mdlaunch.load(e);
localization.load();
GameRegistry.registerPlayerTracker(new PlayerTracker());
TickRegistry.registerTickHandler(new TickTaskHandler(), Side.SERVER);
ForgeEssentialsEventFactory factory = new ForgeEssentialsEventFactory();
TickRegistry.registerTickHandler(factory, Side.SERVER);
GameRegistry.registerPlayerTracker(factory);
}
@PostInit
public void postLoad(FMLPostInitializationEvent e)
{
mdlaunch.postLoad(e);
bannedItems.postLoad(e);
itemList = new ItemList();
}
@ServerStarting
public void serverStarting(FMLServerStartingEvent e)
{
ModListFile.makeModList();
// Data API stuff
((StorageManager) DataStorageManager.manager).setupManager(e);
// Central TP system
TickRegistry.registerScheduledTickHandler(new TeleportCenter(), Side.SERVER);
e.registerServerCommand(new CommandFEVersion());
e.registerServerCommand(new CommandFECredits());
e.registerServerCommand(new CommandFEReload());
e.registerServerCommand(new CommandFEDebug());
// do modules last... just in case...
mdlaunch.serverStarting(e);
}
@ServerStarted
public void serverStarted(FMLServerStartedEvent e)
{
mdlaunch.serverStarted(e);
DuplicateCommandRemoval.remove();
}
@ServerStopping
public void serverStopping(FMLServerStoppingEvent e)
{
mdlaunch.serverStopping(e);
}
@VersionCheckHandler
public boolean versionCheck(String version)
{
return true;
}
}
|
package org.reldb.dbrowser.ui.html;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultCaret;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
import org.eclipse.jface.util.Util;
import org.eclipse.swt.awt.SWT_AWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.reldb.dbrowser.ui.IconLoader;
public class BrowserSwing implements HtmlBrowser {
private BrowserSwingWidget browserPanel;
private Frame frame;
private JTextPane browser;
private Style style;
private StringBuffer text;
private void setEnhancedOutputStyle(JTextPane pane) {
pane.setContentType("text/html");
pane.setEditable(false);
pane.setEnabled(true);
HTMLEditorKit editorKit = new HTMLEditorKit();
HTMLDocument defaultDocument = (HTMLDocument) editorKit.createDefaultDocument();
pane.setEditorKit(editorKit);
pane.setDocument(defaultDocument);
StyleSheet css = editorKit.getStyleSheet();
for (String entry : style.getFormattedStyle())
css.addRule(entry);
}
@Override
public boolean createWidget(Composite parent) {
browserPanel = new BrowserSwingWidget(parent);
frame = SWT_AWT.new_Frame(browserPanel);
// seize focus
browserPanel.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
EventQueue.invokeLater(new Runnable() {
public void run() {
browser.requestFocus();
}
});
}
});
if (Util.isWin32())
style = new Style(-3, (double)IconLoader.getDPIScaling() / 100.0);
else if (Util.isGtk())
style = new Style(-5, (double)IconLoader.getDPIScaling() / 100.0);
else
style = new Style(0);
Panel root = new Panel();
root.setLayout(new GridLayout());
browser = new JTextPane();
KeyListener[] listeners = browser.getKeyListeners();
for (KeyListener listener: listeners)
browser.removeKeyListener(listener);
browser.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (!(e.getKeyCode() == KeyEvent.VK_C))
return;
if (!((e.getModifiersEx() & KeyEvent.CTRL_DOWN_MASK) == KeyEvent.CTRL_DOWN_MASK))
return;
e.consume();
browserPanel.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
browserPanel.copy();
}
});
}
});
browserPanel.setJTextPane(browser);
setEnhancedOutputStyle(browser);
browser.setDoubleBuffered(true);
DefaultCaret caret = (DefaultCaret) browser.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JScrollPane jScrollPaneOutput = new JScrollPane();
jScrollPaneOutput.setAutoscrolls(true);
jScrollPaneOutput.setViewportView(browser);
root.add(jScrollPaneOutput);
frame.add(root);
clear();
return true;
}
@Override
public boolean setFocus() {
return (browserPanel.isDisposed()) ? false : browserPanel.setFocus();
}
@Override
public void clear() {
text = new StringBuffer();
browser.setText(style.getEmptyHTMLDocument());
}
@Override
public void appendHtml(String s) {
HTMLDocument doc = (HTMLDocument) browser.getDocument();
HTMLEditorKit kit = (HTMLEditorKit) browser.getEditorKit();
try {
kit.insertHTML((HTMLDocument) doc, doc.getLength(), s, 0, 0, null);
} catch (BadLocationException | IOException e) {
e.printStackTrace();
}
text.append(s);
}
@Override
public void scrollToBottom() {
}
@Override
public Control getWidget() {
return browserPanel;
}
@Override
public String getText() {
return style.getHTMLDocument(text.toString());
}
@Override
public String getSelectedText() {
return browser.getSelectedText();
}
@Override
public boolean isSelectedTextSupported() {
return true;
}
@Override
public Style getStyle() {
return style;
}
@Override
public void dispose() {
}
@Override
public void setContent(String content) {
text = new StringBuffer(content);
browser.setText(style.getHTMLDocument(content));
}
@Override
public String getContent() {
return text.toString();
}
}
|
package lucee.runtime.engine;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.instrument.Instrumentation;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.TimeZone;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.script.ScriptEngineFactory;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import lucee.Info;
import lucee.cli.servlet.HTTPServletImpl;
import lucee.commons.collection.MapFactory;
import lucee.commons.io.CharsetUtil;
import lucee.commons.io.FileUtil;
import lucee.commons.io.IOUtil;
import lucee.commons.io.SystemUtil;
import lucee.commons.io.compress.CompressUtil;
import lucee.commons.io.log.Log;
import lucee.commons.io.res.Resource;
import lucee.commons.io.res.ResourceProvider;
import lucee.commons.io.res.ResourcesImpl;
import lucee.commons.io.res.util.ResourceUtil;
import lucee.commons.io.res.util.ResourceUtilImpl;
import lucee.commons.io.retirement.RetireOutputStreamFactory;
import lucee.commons.lang.Pair;
import lucee.commons.lang.StringUtil;
import lucee.commons.lang.SystemOut;
import lucee.commons.lang.types.RefBoolean;
import lucee.commons.lang.types.RefBooleanImpl;
import lucee.commons.net.HTTPUtil;
import lucee.intergral.fusiondebug.server.FDControllerImpl;
import lucee.loader.engine.CFMLEngine;
import lucee.loader.engine.CFMLEngineFactory;
import lucee.loader.engine.CFMLEngineFactorySupport;
import lucee.loader.engine.CFMLEngineWrapper;
import lucee.loader.osgi.BundleCollection;
import lucee.loader.util.Util;
import lucee.runtime.CFMLFactory;
import lucee.runtime.CFMLFactoryImpl;
import lucee.runtime.PageContext;
import lucee.runtime.PageContextImpl;
import lucee.runtime.PageSource;
import lucee.runtime.config.Config;
import lucee.runtime.config.ConfigImpl;
import lucee.runtime.config.ConfigServer;
import lucee.runtime.config.ConfigServerImpl;
import lucee.runtime.config.ConfigWeb;
import lucee.runtime.config.ConfigWebImpl;
import lucee.runtime.config.DeployHandler;
import lucee.runtime.config.Identification;
import lucee.runtime.config.Password;
import lucee.runtime.config.XMLConfigAdmin;
import lucee.runtime.config.XMLConfigFactory;
import lucee.runtime.config.XMLConfigServerFactory;
import lucee.runtime.config.XMLConfigWebFactory;
import lucee.runtime.exp.ApplicationException;
import lucee.runtime.exp.PageException;
import lucee.runtime.exp.PageRuntimeException;
import lucee.runtime.exp.PageServletException;
import lucee.runtime.extension.ExtensionDefintion;
import lucee.runtime.extension.RHExtension;
import lucee.runtime.instrumentation.InstrumentationFactory;
import lucee.runtime.jsr223.ScriptEngineFactoryImpl;
import lucee.runtime.net.http.HTTPServletRequestWrap;
import lucee.runtime.net.http.HttpServletRequestDummy;
import lucee.runtime.net.http.HttpServletResponseDummy;
import lucee.runtime.net.http.ReqRspUtil;
import lucee.runtime.op.CastImpl;
import lucee.runtime.op.Caster;
import lucee.runtime.op.CreationImpl;
import lucee.runtime.op.DecisionImpl;
import lucee.runtime.op.ExceptonImpl;
import lucee.runtime.op.IOImpl;
import lucee.runtime.op.JavaProxyUtilImpl;
import lucee.runtime.op.OperationImpl;
import lucee.runtime.op.StringsImpl;
import lucee.runtime.type.StructImpl;
import lucee.runtime.util.Cast;
import lucee.runtime.util.ClassUtil;
import lucee.runtime.util.ClassUtilImpl;
import lucee.runtime.util.Creation;
import lucee.runtime.util.DBUtil;
import lucee.runtime.util.DBUtilImpl;
import lucee.runtime.util.Decision;
import lucee.runtime.util.Excepton;
import lucee.runtime.util.HTMLUtil;
import lucee.runtime.util.HTMLUtilImpl;
import lucee.runtime.util.HTTPUtilImpl;
import lucee.runtime.util.IO;
import lucee.runtime.util.JavaProxyUtil;
import lucee.runtime.util.ListUtil;
import lucee.runtime.util.ListUtilImpl;
import lucee.runtime.util.ORMUtil;
import lucee.runtime.util.ORMUtilImpl;
import lucee.runtime.util.Operation;
import lucee.runtime.util.PageContextUtil;
import lucee.runtime.util.Strings;
import lucee.runtime.util.SystemUtilImpl;
import lucee.runtime.util.TemplateUtil;
import lucee.runtime.util.TemplateUtilImpl;
import lucee.runtime.util.ZipUtil;
import lucee.runtime.util.ZipUtilImpl;
import lucee.runtime.video.VideoUtil;
import lucee.runtime.video.VideoUtilImpl;
import org.apache.felix.framework.Felix;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
//import com.intergral.fusiondebug.server.FDControllerFactory;
/**
* The CFMl Engine
*/
public final class CFMLEngineImpl implements CFMLEngine {
private static Map<String,CFMLFactory> initContextes=MapFactory.<String,CFMLFactory>getConcurrentMap();
private static Map<String,CFMLFactory> contextes=MapFactory.<String,CFMLFactory>getConcurrentMap();
private ConfigServerImpl configServer=null;
private static CFMLEngineImpl engine=null;
private CFMLEngineFactory factory;
private final RefBoolean controlerState=new RefBooleanImpl(true);
private boolean allowRequestTimeout=true;
private Monitor monitor;
private List<ServletConfig> servletConfigs=new ArrayList<ServletConfig>();
private long uptime;
private InfoImpl info;
private BundleCollection bundleCollection;
private ScriptEngineFactory cfmlScriptEngine;
private ScriptEngineFactory cfmlTagEngine;
private ScriptEngineFactory luceeScriptEngine;
private ScriptEngineFactory luceeTagEngine;
private Controler controler;
//private static CFMLEngineImpl engine=new CFMLEngineImpl();
private CFMLEngineImpl(CFMLEngineFactory factory, BundleCollection bc) {
this.factory=factory;
this.bundleCollection=bc;
// happen when Lucee is loaded directly
if(bundleCollection==null) {
try{
Properties prop = InfoImpl.getDefaultProperties(null);
// read the config from default.properties
Map<String,Object> config=new HashMap<String, Object>();
Iterator<Entry<Object, Object>> it = prop.entrySet().iterator();
Entry<Object, Object> e;
String k;
while(it.hasNext()){
e = it.next();
k=(String) e.getKey();
if(!k.startsWith("org.") && !k.startsWith("felix.")) continue;
config.put(k, CFMLEngineFactorySupport.removeQuotes((String)e.getValue(),true));
}
config.put(
Constants.FRAMEWORK_BOOTDELEGATION,
"lucee.*");
Felix felix = factory.getFelix(factory.getResourceRoot(),config);
bundleCollection=new BundleCollection(felix, felix, null);
//bundleContext=bundleCollection.getBundleContext();
}
catch (Throwable t) {
throw new RuntimeException(t);
}
}
this.info=new InfoImpl(bundleCollection==null?null:bundleCollection.core);
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); // MUST better location for this
int doNew;
Resource configDir=null;
try {
configDir = getSeverContextConfigDirectory(factory);
doNew=XMLConfigFactory.doNew(this,configDir, true);
}
catch (IOException e) {
throw new PageRuntimeException(e);
}
CFMLEngineFactory.registerInstance((this));// patch, not really good but it works
ConfigServerImpl cs = getConfigServerImpl();
controler = new Controler(cs,initContextes,5*1000,controlerState);
controler.setDaemon(true);
controler.setPriority(Thread.MIN_PRIORITY);
boolean disabled=Caster.toBooleanValue(SystemUtil.getSetting(SystemUtil.SETTING_CONTROLLER_DISABLED,null),false);
if (!disabled) {
// start the controller
SystemOut.printDate(SystemUtil.getPrintWriter(SystemUtil.OUT), "Start CFML Controller");
controler.start();
}
// copy bundled extension to local extension directory (if never done before)
deployBundledExtension(cs);
// required extensions
boolean isRe=configDir==null?false:XMLConfigFactory.isRequiredExtension(this, configDir);
boolean installExtensions=Caster.toBooleanValue(XMLConfigWebFactory.getSystemPropOrEnvVar("lucee.extensions.install",null),true);
boolean updateReqExt=false;
// if we have a "fresh" install
Set<ExtensionDefintion> extensions;
if(installExtensions && (doNew==XMLConfigFactory.NEW_FRESH || doNew==XMLConfigFactory.NEW_FROM4)) {
List<ExtensionDefintion> ext = info.getRequiredExtension();
extensions = toSet(null,ext);
SystemOut.print(SystemUtil.getPrintWriter(SystemUtil.OUT),
"Install Extensions ("+doNew+"):"+toList(extensions));
}
// if we have an update we update the extension that re installed and we have an older version as defined in the manifest
else if(installExtensions && (doNew==XMLConfigFactory.NEW_MINOR || !isRe)) {
updateReqExt=true;
extensions = new HashSet<ExtensionDefintion>();
Iterator<ExtensionDefintion> it = info.getRequiredExtension().iterator();
ExtensionDefintion ed;
RHExtension rhe;
while(it.hasNext()){
ed = it.next();
if(ed.getVersion()==null) continue; // no version definition no update
try{
rhe = XMLConfigAdmin.hasRHExtensions(cs, new ExtensionDefintion(ed.getId()));
if(rhe==null) continue; // not installed we do not update
// if the installed is older than the one defined in the manifest we update (if possible)
if(!rhe.getVersion().equals(ed.getVersion()))
extensions.add(ed);
}
catch(Throwable t){
t.printStackTrace(); // fails we update
extensions.add(ed);
}
}
}
else {
extensions = new HashSet<ExtensionDefintion>();
}
// XMLConfigAdmin.hasRHExtensions(ci, ed)
// install extension defined
String extensionIds=XMLConfigWebFactory.getSystemPropOrEnvVar("lucee-extensions",null); // old no longer used
if(StringUtil.isEmpty(extensionIds,true))
extensionIds=XMLConfigWebFactory.getSystemPropOrEnvVar("lucee.extensions",null);
if(!StringUtil.isEmpty(extensionIds,true)) {
List<ExtensionDefintion> _extensions = RHExtension.toExtensionDefinitions(extensionIds);
extensions=toSet(extensions,_extensions);
}
if(extensions.size()>0) {
updateReqExt=DeployHandler.deployExtensions(
cs,
extensions.toArray(new ExtensionDefintion[extensions.size()]),
cs.getLog("deploy", true)
);
}
if(updateReqExt && configDir!=null)XMLConfigFactory.updateRequiredExtension(this, configDir);
touchMonitor(cs);
this.uptime=System.currentTimeMillis();
//this.config=config;
}
public static Set<ExtensionDefintion> toSet(Set<ExtensionDefintion> set, List<ExtensionDefintion> list) {
HashMap<String, ExtensionDefintion> map=new HashMap<String, ExtensionDefintion>();
ExtensionDefintion ed;
// set > map
if(set!=null) {
Iterator<ExtensionDefintion> it = set.iterator();
while(it.hasNext()){
ed = it.next();
map.put(ed.toString(),ed);
}
}
// list > map
if(list!=null) {
Iterator<ExtensionDefintion> it = list.iterator();
while(it.hasNext()){
ed = it.next();
map.put(ed.toString(),ed);
}
}
// to Set
HashSet<ExtensionDefintion> rtn = new HashSet<ExtensionDefintion>();
Iterator<ExtensionDefintion> it = map.values().iterator();
while(it.hasNext()){
ed = it.next();
rtn.add(ed);
}
return rtn;
}
public static String toList(Set<ExtensionDefintion> set) {
StringBuilder sb=new StringBuilder();
Iterator<ExtensionDefintion> it = set.iterator();
ExtensionDefintion ed;
while(it.hasNext()){
ed = it.next();
if(sb.length()>0) sb.append(", ");
sb.append(ed.toString());
}
return sb.toString();
}
private void deployBundledExtension(ConfigServerImpl cs) {
Resource dir = cs.getLocalExtensionProviderDirectory();
List<RHExtension> existing = DeployHandler.getLocalExtensions(cs);
String sub="extensions/";
// get the index
ClassLoader cl=CFMLEngineFactory.getInstance().getCFMLEngineFactory().getClass().getClassLoader();
InputStream is = cl.getResourceAsStream("extensions/.index");
if(is==null)is = cl.getResourceAsStream("/extensions/.index");
if(is==null) return;
Log log = cs.getLog("deploy");
try {
String index=IOUtil.toString(is, CharsetUtil.UTF8);
String[] names = lucee.runtime.type.util.ListUtil.listToStringArray(index, ';');
String name;
Resource temp=null;
RHExtension rhe,exist;
Iterator<RHExtension> it;
for(int i=0;i<names.length;i++){
name=names[i];
if(StringUtil.isEmpty(name,true)) continue;
name=name.trim();
is = cl.getResourceAsStream("extensions/"+name);
if(is==null)is = cl.getResourceAsStream("/extensions/"+name);
if(is==null) {
log.error("extract-extension", "could not found extension ["+name+"] defined in the index in the lucee.jar");
continue;
}
try {
temp=SystemUtil.getTempFile("lex", true);
Util.copy(is, temp.getOutputStream(),false,true);
rhe = new RHExtension(cs, temp, false);
boolean alreadyExists=false;
it = existing.iterator();
while(it.hasNext()){
exist = it.next();
if(exist.equals(rhe)) {
alreadyExists=true;
break;
}
}
if(!alreadyExists) {
temp.moveTo(dir.getRealResource(name));
log.info("extract-extension", "added ["+name+"] to ["+dir+"]");
}
}
finally {
if(temp!=null && temp.exists())temp.delete();
}
}
}
catch(Throwable t){
log.error("extract-extension", t);
}
return;
}
private void deployBundledExtensionZip(ConfigServerImpl cs) {
Resource dir = cs.getLocalExtensionProviderDirectory();
List<RHExtension> existing = DeployHandler.getLocalExtensions(cs);
String sub="extensions/";
// MUST this does not work on windows! we need to add an index
ZipEntry entry;
ZipInputStream zis = null;
try {
CodeSource src = CFMLEngineFactory.class.getProtectionDomain().getCodeSource();
if (src == null) return;
URL loc = src.getLocation();
zis=new ZipInputStream(loc.openStream());
String path,name;
int index;
Resource temp;
RHExtension rhe;
Iterator<RHExtension> it;
RHExtension exist;
while ((entry = zis.getNextEntry())!= null) {
path = entry.getName();
if(path.startsWith(sub) && path.endsWith(".lex")) { // ignore non lex files or file from else where
index=path.lastIndexOf('/')+1;
if(index==sub.length()) { // ignore sub directories
name=path.substring(index);
temp=null;
try {
temp=SystemUtil.getTempFile("lex", true);
Util.copy(zis, temp.getOutputStream(),false,true);
rhe = new RHExtension(cs, temp, false);
boolean alreadyExists=false;
it = existing.iterator();
while(it.hasNext()){
exist = it.next();
if(exist.equals(rhe)) {
alreadyExists=true;
break;
}
}
if(!alreadyExists) {
temp.moveTo(dir.getRealResource(name));
}
}
finally {
if(temp!=null && temp.exists())temp.delete();
}
}
}
zis.closeEntry();
}
}
catch(Throwable t){
t.printStackTrace();// TODO log this
}
finally {
Util.closeEL(zis);
}
return;
}
public void touchMonitor(ConfigServerImpl cs) {
if(monitor!=null && monitor.isAlive()) return;
monitor = new Monitor(cs,controlerState);
monitor.setDaemon(true);
monitor.setPriority(Thread.MIN_PRIORITY);
monitor.start();
}
/**
* get singelton instance of the CFML Engine
* @param factory
* @return CFMLEngine
*/
public static synchronized CFMLEngine getInstance(CFMLEngineFactory factory,BundleCollection bc) {
if(engine==null) {
if(SystemUtil.getLoaderVersion()<5.9D) {
if(SystemUtil.getLoaderVersion()<5.8D)
throw new RuntimeException("You need to update your lucee.jar to run this version, you can download the latest jar from http://download.lucee.org.");
else
System.out.println("To use all features Lucee provides, you need to update your lucee.jar, you can download the latest jar from http://download.lucee.org.");
}
engine=new CFMLEngineImpl(factory,bc);
}
return engine;
}
/**
* get singelton instance of the CFML Engine, throwsexception when not already init
* @param factory
* @return CFMLEngine
*/
public static synchronized CFMLEngine getInstance() throws ServletException {
if(engine!=null) return engine;
throw new ServletException("CFML Engine is not loaded");
}
@Override
public void addServletConfig(ServletConfig config) throws ServletException {
servletConfigs.add(config);
String real=ReqRspUtil.getRootPath(config.getServletContext());
if(!initContextes.containsKey(real)) {
CFMLFactory jspFactory = loadJSPFactory(getConfigServerImpl(),config,initContextes.size());
initContextes.put(real,jspFactory);
}
}
@Override
public ConfigServer getConfigServer(Password password) throws PageException {
getConfigServerImpl().checkAccess(password);
return configServer;
}
@Override
public ConfigServer getConfigServer(String key, long timeNonce) throws PageException {
getConfigServerImpl().checkAccess(key,timeNonce);
return configServer;
}
public void setConfigServerImpl(ConfigServerImpl cs) {
this.configServer=cs;
}
private ConfigServerImpl getConfigServerImpl() {
if(configServer==null) {
try {
Resource context = getSeverContextConfigDirectory(factory);
//CFMLEngineFactory.registerInstance(this);// patch, not really good but it works
configServer=XMLConfigServerFactory.newInstance(
this,
initContextes,
contextes,
context);
} catch (Exception e) {
e.printStackTrace();
}
}
return configServer;
}
private Resource getSeverContextConfigDirectory(CFMLEngineFactory factory) throws IOException {
ResourceProvider frp = ResourcesImpl.getFileResourceProvider();
return frp.getResource(factory.getResourceRoot().getAbsolutePath()).getRealResource("context");
}
private CFMLFactoryImpl loadJSPFactory(ConfigServerImpl configServer, ServletConfig sg, int countExistingContextes) throws ServletException {
try {
// Load Config
RefBoolean isCustomSetting=new RefBooleanImpl();
Resource configDir=getConfigDirectory(sg,configServer,countExistingContextes,isCustomSetting);
CFMLFactoryImpl factory=new CFMLFactoryImpl(this,sg);
ConfigWebImpl config=XMLConfigWebFactory.newInstance(this,factory,configServer,configDir,isCustomSetting.toBooleanValue(),sg);
factory.setConfig(config);
return factory;
}
catch (Exception e) {
ServletException se= new ServletException(e.getMessage());
se.setStackTrace(e.getStackTrace());
throw se;
}
}
/**
* loads Configuration File from System, from init Parameter from web.xml
* @param sg
* @param configServer
* @param countExistingContextes
* @return return path to directory
*/
private Resource getConfigDirectory(ServletConfig sg, ConfigServerImpl configServer, int countExistingContextes, RefBoolean isCustomSetting) throws PageServletException {
isCustomSetting.setValue(true);
ServletContext sc=sg.getServletContext();
String strConfig=sg.getInitParameter("configuration");
if(StringUtil.isEmpty(strConfig))strConfig=sg.getInitParameter("lucee-web-directory");
if(StringUtil.isEmpty(strConfig))strConfig=System.getProperty("lucee.web.dir");
if(StringUtil.isEmpty(strConfig)) {
isCustomSetting.setValue(false);
strConfig="{web-root-directory}/WEB-INF/lucee/";
}
// only for backward compatibility
else if(strConfig.startsWith("/WEB-INF/lucee/"))strConfig="{web-root-directory}"+strConfig;
strConfig=StringUtil.removeQuotes(strConfig,true);
// static path is not allowed
if(countExistingContextes>1 && strConfig!=null && strConfig.indexOf('{')==-1){
String text="static path ["+strConfig+"] for servlet init param [lucee-web-directory] is not allowed, path must use a web-context specific placeholder.";
System.err.println(text);
throw new PageServletException(new ApplicationException(text));
}
strConfig=SystemUtil.parsePlaceHolder(strConfig,sc,configServer.getLabels());
ResourceProvider frp = ResourcesImpl.getFileResourceProvider();
Resource root = frp.getResource(ReqRspUtil.getRootPath(sc));
Resource res;
Resource configDir=ResourceUtil.createResource(res=root.getRealResource(strConfig), FileUtil.LEVEL_PARENT_FILE,FileUtil.TYPE_DIR);
if(configDir==null) {
configDir=ResourceUtil.createResource(res=frp.getResource(strConfig), FileUtil.LEVEL_GRAND_PARENT_FILE,FileUtil.TYPE_DIR);
}
if(configDir==null && !isCustomSetting.toBooleanValue()) {
try {
res.createDirectory(true);
configDir=res;
}
catch (IOException e) {
throw new PageServletException(Caster.toPageException(e));
}
}
if(configDir==null) {
throw new PageServletException(new ApplicationException("path ["+strConfig+"] is invalid"));
}
if(!configDir.exists() || ResourceUtil.isEmptyDirectory(configDir, null)){
Resource railoRoot;
// there is a railo directory
if(configDir.getName().equals("lucee") && (railoRoot=configDir.getParentResource().getRealResource("railo")).isDirectory()) {
try {
copyRecursiveAndRename(railoRoot,configDir);
}
catch (IOException e) {
try {
configDir.createDirectory(true);
}
catch (IOException ioe) {}
return configDir;
}
// zip the railo-server di and delete it (optional)
try {
Resource p=railoRoot.getParentResource();
CompressUtil.compress(CompressUtil.FORMAT_ZIP, railoRoot, p.getRealResource("railo-web-context-old.zip"), false, -1);
ResourceUtil.removeEL(railoRoot, true);
}
catch(Throwable t){t.printStackTrace();}
}
else {
try {
configDir.createDirectory(true);
}
catch (IOException e) {}
}
}
return configDir;
}
private File getDirectoryByProp(String name) {
String value=System.getProperty(name);
if(Util.isEmpty(value,true)) return null;
File dir=new File(value);
dir.mkdirs();
if (dir.isDirectory()) return dir;
return null;
}
private static void copyRecursiveAndRename(Resource src,Resource trg) throws IOException {
if(!src.exists()) return ;
if(src.isDirectory()) {
if(!trg.exists())trg.mkdirs();
Resource[] files = src.listResources();
for(int i=0;i<files.length;i++) {
copyRecursiveAndRename(files[i],trg.getRealResource(files[i].getName()));
}
}
else if(src.isFile()) {
if(trg.getName().endsWith(".rc") || trg.getName().startsWith(".")) {
return;
}
if(trg.getName().equals("railo-web.xml.cfm")) {
trg=trg.getParentResource().getRealResource("lucee-web.xml.cfm");
// cfLuceeConfiguration
InputStream is = src.getInputStream();
OutputStream os = trg.getOutputStream();
try{
String str=Util.toString(is);
str=str.replace("<cfRailoConfiguration", "<!-- copy from Railo context --><cfLuceeConfiguration");
str=str.replace("</cfRailoConfiguration", "</cfLuceeConfiguration");
str=str.replace("<railo-configuration", "<lucee-configuration");
str=str.replace("</railo-configuration", "</lucee-configuration");
str=str.replace("{railo-config}", "{lucee-config}");
str=str.replace("{railo-server}", "{lucee-server}");
str=str.replace("{railo-web}", "{lucee-web}");
str=str.replace("\"railo.commons.", "\"lucee.commons.");
str=str.replace("\"railo.runtime.", "\"lucee.runtime.");
str=str.replace("\"railo.cfx.", "\"lucee.cfx.");
str=str.replace("/railo-context.ra", "/lucee-context.lar");
str=str.replace("/railo-context", "/lucee");
str=str.replace("railo-server-context", "lucee-server");
str=str.replace("http:
str=str.replace("http:
ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());
try {
Util.copy(bais, os);
bais.close();
}
finally {
Util.closeEL(is, os);
}
}
finally {
Util.closeEL(is,os);
}
return;
}
InputStream is = src.getInputStream();
OutputStream os = trg.getOutputStream();
try{
Util.copy(is, os);
}
finally {
Util.closeEL(is, os);
}
}
}
@Override
public CFMLFactory getCFMLFactory(ServletConfig srvConfig,HttpServletRequest req) throws ServletException {
ServletContext srvContext = srvConfig.getServletContext();
String real=ReqRspUtil.getRootPath(srvContext);
ConfigServerImpl cs = getConfigServerImpl();
// Load JspFactory
CFMLFactory factory=contextes.get(real);
if(factory==null) {
factory=initContextes.get(real);
if(factory==null) {
factory=loadJSPFactory(cs,srvConfig,initContextes.size());
initContextes.put(real,factory);
}
contextes.put(real,factory);
try {
String cp = req.getContextPath();
if(cp==null)cp="";
((CFMLFactoryImpl)factory).setURL(new URL(req.getScheme(),req.getServerName(),req.getServerPort(),cp));
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}
return factory;
}
@Override
public void service(HttpServlet servlet, HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
CFMLFactory factory=getCFMLFactory(servlet.getServletConfig(), req);
// is Lucee dialect enabled?
if(!((ConfigImpl)factory.getConfig()).allowLuceeDialect()){
try {
PageContextImpl.notSupported();
} catch (ApplicationException e) {
throw new PageServletException(e);
}
}
PageContext pc = factory.getLuceePageContext(servlet,req,rsp,null,false,-1,false,true,-1,true,false);
ThreadQueue queue = factory.getConfig().getThreadQueue();
queue.enter(pc);
try {
pc.execute(pc.getHttpServletRequest().getServletPath(),false,true);
}
catch (PageException pe) {
throw new PageServletException(pe);
}
finally {
queue.exit(pc);
factory.releaseLuceePageContext(pc,true);
//FDControllerFactory.notifyPageComplete();
}
}
@Override
public void serviceCFML(HttpServlet servlet, HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
CFMLFactory factory=getCFMLFactory(servlet.getServletConfig(), req);
PageContext pc = factory.getLuceePageContext(servlet,req,rsp,null,false,-1,false,true,-1,true,false);
ThreadQueue queue = factory.getConfig().getThreadQueue();
queue.enter(pc);
try {
pc.executeCFML(pc.getHttpServletRequest().getServletPath(),false,true);
}
catch (PageException pe) {
throw new PageServletException(pe);
}
finally {
queue.exit(pc);
factory.releaseLuceePageContext(pc,true);
//FDControllerFactory.notifyPageComplete();
}
}
@Override
public void serviceFile(HttpServlet servlet, HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
req=new HTTPServletRequestWrap(req);
CFMLFactory factory=getCFMLFactory( servlet.getServletConfig(), req);
ConfigWeb config = factory.getConfig();
PageSource ps = config.getPageSourceExisting(null, null, req.getServletPath(), false, true, true, false);
//Resource res = ((ConfigWebImpl)config).getPhysicalResourceExistingX(null, null, req.getServletPath(), false, true, true);
if(ps==null) {
rsp.sendError(404);
}
else {
Resource res = ps.getResource();
if(res==null) {
rsp.sendError(404);
}
else {
ReqRspUtil.setContentLength(rsp,res.length());
String mt = servlet.getServletContext().getMimeType(req.getServletPath());
if(!StringUtil.isEmpty(mt))ReqRspUtil.setContentType(rsp,mt);
IOUtil.copy(res, rsp.getOutputStream(), true);
}
}
}
@Override
public void serviceRest(HttpServlet servlet, HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
req=new HTTPServletRequestWrap(req);
CFMLFactory factory=getCFMLFactory(servlet.getServletConfig(), req);
PageContext pc = factory.getLuceePageContext(servlet,req,rsp,null,false,-1,false,true,-1,true,false);
ThreadQueue queue = factory.getConfig().getThreadQueue();
queue.enter(pc);
try {
pc.executeRest(pc.getHttpServletRequest().getServletPath(),false);
}
catch (PageException pe) {
throw new PageServletException(pe);
}
finally {
queue.exit(pc);
factory.releaseLuceePageContext(pc,true);
//FDControllerFactory.notifyPageComplete();
}
}
/*private String getContextList() {
return List.arrayToList((String[])contextes.keySet().toArray(new String[contextes.size()]),", ");
}*/
@Override
public String getVersion() {
return info.getVersion().toString();
}
@Override
public Info getInfo() {
return info;
}
@Override
public String getUpdateType() {
return getConfigServerImpl().getUpdateType();
}
@Override
public URL getUpdateLocation() {
return getConfigServerImpl().getUpdateLocation();
}
@Override
public Identification getIdentification() {
return getConfigServerImpl().getIdentification();
}
@Override
public boolean can(int type, Password password) {
return getConfigServerImpl().passwordEqual(password);
}
@Override
public CFMLEngineFactory getCFMLEngineFactory() {
return factory;
}
@Override
public void serviceAMF(HttpServlet servlet, HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
req=new HTTPServletRequestWrap(req);
getCFMLFactory(servlet.getServletConfig(), req)
.getConfig().getAMFEngine().service(servlet,new HTTPServletRequestWrap(req),rsp);
}
@Override
public void reset() {
reset(null);
}
@Override
public void reset(String configId) {
getControler().close();
RetireOutputStreamFactory.close();
CFMLFactoryImpl cfmlFactory;
//ScopeContext scopeContext;
try {
Iterator<String> it = contextes.keySet().iterator();
while(it.hasNext()) {
try {
cfmlFactory=(CFMLFactoryImpl) contextes.get(it.next());
if(configId!=null && !configId.equals(cfmlFactory.getConfigWebImpl().getIdentification().getId())) continue;
// scopes
try{cfmlFactory.getScopeContext().clear();}catch(Throwable t){t.printStackTrace();}
// PageContext
try{cfmlFactory.resetPageContext();}catch(Throwable t){t.printStackTrace();}
// Query Cache
try{
PageContext pc = ThreadLocalPageContext.get();
if(pc!=null) {
pc.getConfig().getCacheHandlerCollection(Config.CACHE_TYPE_QUERY,null).clear(pc);
pc.getConfig().getCacheHandlerCollection(Config.CACHE_TYPE_FUNCTION,null).clear(pc);
pc.getConfig().getCacheHandlerCollection(Config.CACHE_TYPE_INCLUDE,null).clear(pc);
}
//cfmlFactory.getDefaultQueryCache().clear(null);
}catch(Throwable t){t.printStackTrace();}
// Gateway
try{ cfmlFactory.getConfigWebImpl().getGatewayEngine().reset();}catch(Throwable t){t.printStackTrace();}
}
catch(Throwable t){
t.printStackTrace();
}
}
}
finally {
// Controller
controlerState.setValue(false);
}
}
@Override
public Cast getCastUtil() {
return CastImpl.getInstance();
}
@Override
public Operation getOperatonUtil() {
return OperationImpl.getInstance();
}
@Override
public Decision getDecisionUtil() {
return DecisionImpl.getInstance();
}
@Override
public Excepton getExceptionUtil() {
return ExceptonImpl.getInstance();
}
@Override
public Object getJavaProxyUtil() { // FUTURE return JavaProxyUtil
return new JavaProxyUtilImpl();
}
@Override
public Creation getCreationUtil() {
return CreationImpl.getInstance(this);
}
@Override
public IO getIOUtil() {
return IOImpl.getInstance();
}
@Override
public Strings getStringUtil() {
return StringsImpl.getInstance();
}
@Override
public Object getFDController() {
engine.allowRequestTimeout(false);
return new FDControllerImpl(engine,engine.getConfigServerImpl().getSerialNumber());
}
public Map<String,CFMLFactory> getCFMLFactories() {
return initContextes;
}
@Override
public lucee.runtime.util.ResourceUtil getResourceUtil() {
return ResourceUtilImpl.getInstance();
}
@Override
public lucee.runtime.util.HTTPUtil getHTTPUtil() {
return HTTPUtilImpl.getInstance();
}
@Override
public PageContext getThreadPageContext() {
return ThreadLocalPageContext.get();
}
@Override
public Config getThreadConfig() {
return ThreadLocalPageContext.getConfig();
}
@Override
public void registerThreadPageContext(PageContext pc) {
ThreadLocalPageContext.register(pc);
}
@Override
public VideoUtil getVideoUtil() {
return VideoUtilImpl.getInstance();
}
@Override
public ZipUtil getZipUtil() {
return ZipUtilImpl.getInstance();
}
/*public String getState() {
return info.getStateAsString();
}*/
public void allowRequestTimeout(boolean allowRequestTimeout) {
this.allowRequestTimeout=allowRequestTimeout;
}
public boolean allowRequestTimeout() {
return allowRequestTimeout;
}
public boolean isRunning() {
try{
CFMLEngine other = CFMLEngineFactory.getInstance();
// FUTURE patch, do better impl when changing loader
if(other!=this && controlerState.toBooleanValue() && !(other instanceof CFMLEngineWrapper)) {
SystemOut.printDate("CFMLEngine is still set to true but no longer valid, "+lucee.runtime.config.Constants.NAME+" disable this CFMLEngine.");
controlerState.setValue(false);
reset();
return false;
}
}
catch(Throwable t){}
return controlerState.toBooleanValue();
}
@Override
public void cli(Map<String, String> config, ServletConfig servletConfig) throws IOException,JspException,ServletException {
ServletContext servletContext = servletConfig.getServletContext();
HTTPServletImpl servlet=new HTTPServletImpl(servletConfig, servletContext, servletConfig.getServletName());
// webroot
String strWebroot=config.get("webroot");
if(StringUtil.isEmpty(strWebroot,true)) throw new IOException("missing webroot configuration");
Resource root=ResourcesImpl.getFileResourceProvider().getResource(strWebroot);
root.mkdirs();
// serverName
String serverName=config.get("server-name");
if(StringUtil.isEmpty(serverName,true))serverName="localhost";
// uri
String strUri=config.get("uri");
if(StringUtil.isEmpty(strUri,true)) throw new IOException("missing uri configuration");
URI uri;
try {
uri = lucee.commons.net.HTTPUtil.toURI(strUri);
} catch (URISyntaxException e) {
throw Caster.toPageException(e);
}
// cookie
Cookie[] cookies;
String strCookie=config.get("cookie");
if(StringUtil.isEmpty(strCookie,true)) cookies=new Cookie[0];
else {
Map<String,String> mapCookies=HTTPUtil.parseParameterList(strCookie,false,null);
int index=0;
cookies=new Cookie[mapCookies.size()];
Entry<String, String> entry;
Iterator<Entry<String, String>> it = mapCookies.entrySet().iterator();
Cookie c;
while(it.hasNext()){
entry = it.next();
c=ReqRspUtil.toCookie(entry.getKey(),entry.getValue(),null);
if(c!=null)cookies[index++]=c;
else throw new IOException("cookie name ["+entry.getKey()+"] is invalid");
}
}
// header
Pair[] headers=new Pair[0];
// parameters
Pair[] parameters=new Pair[0];
// attributes
StructImpl attributes = new StructImpl();
ByteArrayOutputStream os=new ByteArrayOutputStream();
HttpServletRequestDummy req=new HttpServletRequestDummy(
root,serverName,uri.getPath(),uri.getQuery(),cookies,headers,parameters,attributes,null,null);
req.setProtocol("CLI/1.0");
HttpServletResponse rsp=new HttpServletResponseDummy(os);
serviceCFML(servlet, req, rsp);
String res = os.toString(ReqRspUtil.getCharacterEncoding(null,rsp).name());
System.out.println(res);
}
@Override
public ServletConfig[] getServletConfigs(){
return servletConfigs.toArray(new ServletConfig[servletConfigs.size()]);
}
@Override
public long uptime() {
return uptime;
}
/*public Bundle getCoreBundle() {
return bundle;
}*/
@Override
public BundleCollection getBundleCollection() {
return bundleCollection;
}
@Override
public BundleContext getBundleContext() {
return bundleCollection.getBundleContext();
}
@Override
public ClassUtil getClassUtil() {
return new ClassUtilImpl();
}
@Override
public ListUtil getListUtil() {
return new ListUtilImpl();
}
@Override
public DBUtil getDBUtil() {
return new DBUtilImpl();
}
@Override
public ORMUtil getORMUtil() {
return new ORMUtilImpl();
}
@Override
public TemplateUtil getTemplateUtil() {
return new TemplateUtilImpl();
}
@Override
public HTMLUtil getHTMLUtil() {
return new HTMLUtilImpl();
}
@Override
public ScriptEngineFactory getScriptEngineFactory(int dialect) {
if(dialect==CFMLEngine.DIALECT_CFML) {
if(cfmlScriptEngine==null) cfmlScriptEngine=new ScriptEngineFactoryImpl(this,false,dialect);
return cfmlScriptEngine;
}
if(luceeScriptEngine==null) luceeScriptEngine=new ScriptEngineFactoryImpl(this,false,dialect);
return luceeScriptEngine;
}
@Override
public ScriptEngineFactory getTagEngineFactory(int dialect) {
if(dialect==CFMLEngine.DIALECT_CFML) {
if(cfmlTagEngine==null) cfmlTagEngine=new ScriptEngineFactoryImpl(this,true,dialect);
return cfmlTagEngine;
}
if(luceeTagEngine==null) luceeTagEngine=new ScriptEngineFactoryImpl(this,true,dialect);
return luceeTagEngine;
}
@Override
public PageContext createPageContext(File contextRoot, String host, String scriptName, String queryString
, Cookie[] cookies,Map<String, Object> headers,Map<String, String> parameters,
Map<String, Object> attributes, OutputStream os, long timeout, boolean register) throws ServletException {
return PageContextUtil.getPageContext(contextRoot,host, scriptName, queryString, cookies, headers, parameters, attributes, os,register,timeout,false);
}
@Override
public ConfigWeb createConfig(File contextRoot,String host, String scriptName) throws ServletException {
// TODO do a mored rect approach
PageContext pc = null;
try{
pc = PageContextUtil.getPageContext(contextRoot,host,scriptName, null, null, null, null, null, null,false,-1,false);
return pc.getConfig();
}
finally{
pc.getConfig().getFactory().releaseLuceePageContext(pc, false);
}
}
@Override
public void releasePageContext(PageContext pc, boolean unregister) {
PageContextUtil.releasePageContext(pc,unregister);
}
@Override
public lucee.runtime.util.SystemUtil getSystemUtil() {
return new SystemUtilImpl();
}
@Override
public TimeZone getThreadTimeZone() {
return ThreadLocalPageContext.getTimeZone();
}
@Override
public Instrumentation getInstrumentation() {
return InstrumentationFactory.getInstrumentation(ThreadLocalPageContext.getConfig());
}
public Controler getControler() {
return controler;
}
}
|
package com.karateca.ddescriber.dialog;
import com.intellij.find.impl.FindResultImpl;
import com.intellij.mock.MockDocument;
import com.karateca.ddescriber.model.TestFindResult;
import com.karateca.ddescriber.model.TestState;
import junit.framework.TestCase;
import java.util.List;
/**
* @author Andres Dominguez.
*/
public class PendingChangesTest extends TestCase {
private PendingChanges pendingChanges;
public void setUp() throws Exception {
pendingChanges = new PendingChanges();
}
public void testGetTestsToChange() throws Exception {
pendingChanges.itemChanged(createPendingChange(10), TestState.Excluded);
pendingChanges.itemChanged(createPendingChange(30), TestState.Excluded);
pendingChanges.itemChanged(createPendingChange(20), TestState.Excluded);
pendingChanges.itemChanged(createPendingChange(40), TestState.Excluded);
List<TestFindResult> testsToChange = pendingChanges.getTestsToChange();
assertEquals(4, testsToChange.size());
assertEquals(10, testsToChange.get(0).getStartOffset());
assertEquals(20, testsToChange.get(1).getStartOffset());
assertEquals(30, testsToChange.get(2).getStartOffset());
assertEquals(40, testsToChange.get(3).getStartOffset());
}
public void testShouldAddItems() {
// When you add two items.
pendingChanges.itemChanged(getTestFindResult(TestState.Included), TestState.Excluded);
pendingChanges.itemChanged(getTestFindResult(TestState.Excluded), TestState.Included);
// Then ensure there are two items.
assertEquals(2, pendingChanges.getTestsToChange().size());
}
public void testShouldRemoveTestResultThatDidNotChangeStatus() {
// Given that you add two items.
TestFindResult included = getTestFindResult(TestState.Included);
TestFindResult excluded = getTestFindResult(TestState.Excluded);
TestFindResult notModified = getTestFindResult(TestState.NotModified);
pendingChanges.itemChanged(included, TestState.Excluded);
pendingChanges.itemChanged(excluded, TestState.Included);
pendingChanges.itemChanged(notModified, TestState.Included);
// When you remove the change of the included.
pendingChanges.itemChanged(included, TestState.Included);
pendingChanges.itemChanged(notModified, TestState.Included);
// Then ensure there is on item.
assertEquals(1, pendingChanges.getTestsToChange().size());
assertEquals(excluded, pendingChanges.getTestsToChange().get(0));
}
public void testShouldSetRollbackStateWhenRemovingFromPendingChanges() {
// Given that you have an included and an excluded tests.
TestFindResult included = getTestFindResult(TestState.Included);
TestFindResult excluded = getTestFindResult(TestState.Excluded);
// When you remove the changed state.
included.setPendingChangeState(TestState.Included);
excluded.setPendingChangeState(TestState.Excluded);
pendingChanges.itemChanged(included, TestState.Included);
pendingChanges.itemChanged(excluded, TestState.Excluded);
// Then ensure the new state is rolled back.
assertEquals(TestState.RolledBack, included.getPendingChangeState());
assertEquals(TestState.RolledBack, excluded.getPendingChangeState());
}
private TestFindResult getTestFindResult(TestState testState) {
TestFindResult pendingChange = createPendingChange(1);
pendingChange.setTestState(testState);
return pendingChange;
}
private TestFindResult createPendingChange(int startOffset) {
FindResultImpl findResult = new FindResultImpl(startOffset, startOffset + 10);
TestFindResult testFindResult = new TestFindResult(new MockDocument(""), findResult);
testFindResult.setTestState(TestState.NotModified);
return testFindResult;
}
}
|
package org.kohsuke.stapler.export;
import org.kohsuke.stapler.export.TreePruner.ByDepth;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.lang.reflect.Array;
import java.net.URL;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Exposes one {@link Exported exposed property} of {@link ExportedBean} to
* {@link DataWriter}.
*
* @author Kohsuke Kawaguchi
*/
public abstract class Property implements Comparable<Property> {
/**
* Name of the property.
*/
public final String name;
final ModelBuilder owner;
/**
* Visibility depth level of this property.
*
* @see Exported#visibility()
*/
public final int visibility;
/**
* Model to which this property belongs to.
* Never null.
*/
public final Model parent;
/**
* @see Exported#inline()
*/
public final boolean inline;
private String[] verboseMap;
Property(Model parent, String name, Exported exported) {
this.parent = parent;
this.owner = parent.parent;
this.name = exported.name().length()>1 ? exported.name() : name;
int v = exported.visibility();
if(v==0)
v = parent.defaultVisibility;
this.visibility = v;
this.inline = exported.inline();
String[] s = exported.verboseMap().split("/");
if (s.length<2)
this.verboseMap = null;
else
this.verboseMap = s;
}
public int compareTo(Property that) {
return this.name.compareTo(that.name);
}
public abstract Type getGenericType();
public abstract Class getType();
/**
* Gets the associated javadoc, if any, or null.
*/
public abstract String getJavadoc();
/**
* Writes one property of the given object to {@link DataWriter}.
*
* @param pruner
* Determines how to prune the object graph tree.
*/
public void writeTo(Object object, TreePruner pruner, DataWriter writer) throws IOException {
TreePruner child = pruner.accept(object, this);
if (child==null) return;
try {
writer.name(name);
writeValue(getValue(object),child,writer);
} catch (IllegalAccessException e) {
IOException x = new IOException("Failed to write " + name);
x.initCause(e);
throw x;
} catch (InvocationTargetException e) {
IOException x = new IOException("Failed to write " + name);
x.initCause(e);
throw x;
}
}
/**
* @deprecated as of 1.139
*/
public void writeTo(Object object, int depth, DataWriter writer) throws IOException {
writeTo(object,new ByDepth(depth),writer);
}
/**
* Writes one value of the property to {@link DataWriter}.
*/
private void writeValue(Object value, TreePruner pruner, DataWriter writer) throws IOException {
writeValue(value,pruner,writer,false);
}
/**
* Writes one value of the property to {@link DataWriter}.
*/
private void writeValue(Object value, TreePruner pruner, DataWriter writer, boolean skipIfFail) throws IOException {
if(value==null) {
writer.valueNull();
return;
}
if(value instanceof CustomExportedBean) {
writeValue(((CustomExportedBean)value).toExportedObject(),pruner,writer);
return;
}
Class c = value.getClass();
if(STRING_TYPES.contains(c)) {
writer.value(value.toString());
return;
}
if(PRIMITIVE_TYPES.contains(c)) {
writer.valuePrimitive(value);
return;
}
if(c.getComponentType()!=null) { // array
Range r = pruner.getRange();
writer.startArray();
if (value instanceof Object[]) {
// typical case
for (Object item : r.apply((Object[]) value)) {
writeValue(item,pruner,writer,true);
}
} else {
// more generic case
int len = Math.min(r.max,Array.getLength(value));
for (int i=r.min; i<len; i++) {
writeValue(Array.get(value,i),pruner,writer,true);
}
}
writer.endArray();
return;
}
if(value instanceof Collection) {
writer.startArray();
for (Object item : pruner.getRange().apply((Collection) value)) {
writeValue(item,pruner,writer,true);
}
writer.endArray();
return;
}
if(value instanceof Map) {
if (verboseMap!=null) {// verbose form
writer.startArray();
for (Map.Entry e : ((Map<?,?>) value).entrySet()) {
writer.startObject();
writer.name(verboseMap[0]);
writeValue(e.getKey(),pruner,writer);
writer.name(verboseMap[1]);
writeValue(e.getValue(),pruner,writer);
writer.endObject();
}
writer.endArray();
} else {// compact form
writer.startObject();
for (Map.Entry e : ((Map<?,?>) value).entrySet()) {
writer.name(e.getKey().toString());
writeValue(e.getValue(),pruner,writer);
}
writer.endObject();
}
return;
}
if(value instanceof Date) {
writer.valuePrimitive(((Date) value).getTime());
return;
}
if(value instanceof Calendar) {
writer.valuePrimitive(((Calendar) value).getTimeInMillis());
return;
}
if(value instanceof Enum) {
writer.value(value.toString());
return;
}
// otherwise handle it as a bean
writer.startObject();
Model model = null;
try {
model = owner.get(c, parent.type, name);
} catch (NotExportableException e) {
if (skipIfFail) {
Logger.getLogger(Property.class.getName()).log(Level.FINE, e.getMessage());
} else {
throw e;
}
// otherwise ignore this error by writing empty object
}
if(model!=null)
model.writeNestedObjectTo(value, pruner, writer, Collections.<String>emptySet());
writer.endObject();
}
/**
* Gets the value of this property from the bean.
*/
protected abstract Object getValue(Object bean) throws IllegalAccessException, InvocationTargetException;
/*package*/ static final Set<Class> STRING_TYPES = new HashSet<Class>(Arrays.asList(
String.class,
URL.class
));
/*package*/ static final Set<Class> PRIMITIVE_TYPES = new HashSet<Class>(Arrays.asList(
Integer.class,
Long.class,
Boolean.class,
Short.class,
Character.class,
Float.class,
Double.class
));
}
|
package org.xillium.core.util;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;
import java.util.logging.*;
import org.xillium.base.etc.Arrays;
import org.xillium.data.DataObject;
import org.xillium.data.DataBinder;
import org.xillium.data.CachedResultSet;
import org.xillium.core.Service;
import org.xillium.core.ServiceException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* An interface to a remote Xillium service.
*/
public class RemoteService {
private static final Logger _logger = Logger.getLogger(RemoteService.class.getName());
private static final ObjectMapper _mapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
/**
* This class represents a response from a remote Xillium service.
*/
public static class Response {
public Map<String, Object> params;
public Map<String, CachedResultSet> tables;
public transient byte[] body;
Response setResponseBody(byte[] body) {
this.body = body;
return this;
}
}
/**
* Calls a remote service with non-static member values in the given DataObject as arguments.
*/
public static Response call(String server, String service, DataObject data) {
List<String> params = new ArrayList<String>();
for (Field field: data.getClass().getFields()) {
if (Modifier.isStatic(field.getModifiers())) continue;
field.setAccessible(true);
try {
Object value = field.get(data);
if (value == null) value = "";
params.add(field.getName() + '=' + value);
} catch (IllegalAccessException x) {}
}
return call(server, service, params.toArray(new String[params.size()]));
}
/**
* Calls a remote service with parameters in the given DataBinder as arguments.
*/
public static Response call(String server, String service, DataBinder binder) {
List<String> params = new ArrayList<String>();
for (Map.Entry<String, String> entry: binder.entrySet()) {
String name = entry.getKey();
if (name.charAt(0) == '_' || name.charAt(0) == '#') continue;
params.add(name + '=' + entry.getValue());
}
return call(server, service, params.toArray(new String[params.size()]));
}
/**
* Calls a remote service with a list of "name=value" string values as arguments.
*/
public static Response call(String server, String service, String... params) {
try {
URL url = new URL(server + '/' + service);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
PrintWriter pw = new PrintWriter(connection.getOutputStream());
for (String param: params) {
_logger.fine(param);
pw.print(param); pw.print('&');
}
pw.close();
InputStream in = connection.getInputStream();
try {
byte[] bytes = Arrays.read(in);
Response response = _mapper.readValue(bytes, Response.class).setResponseBody(bytes);
if (response.params != null) {
String message = (String)response.params.get(Service.FAILURE_MESSAGE);
if (message != null) {
throw new ServiceException(message);
}
} else {
throw new ServiceException("***ProtocolErrorMissingParams");
}
return response;
} finally {
in.close();
}
} catch (RuntimeException x) {
throw x;
} catch (Exception x) {
throw new ServiceException("***RemoteServiceCallFailure", x);
}
}
}
|
package desperatehousepi.GUI;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import javax.swing.JPanel;
import java.awt.Color;
import javax.swing.border.LineBorder;
import java.awt.Toolkit;
import javax.swing.border.MatteBorder;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import java.awt.Font;
import java.awt.Insets;
import javax.swing.SwingConstants;
import javax.swing.JProgressBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MainWindow {
private JFrame frameMain;
public static void main(String[] args){ new MainWindow(); }
/**
* Create the application.
*/
public MainWindow() {
initialize();
frameMain.setVisible(true);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frameMain = new JFrame();
frameMain.setIconImage(Toolkit.getDefaultToolkit().getImage(MainWindow.class.getResource("/com/sun/java/swing/plaf/motif/icons/DesktopIcon.gif")));
frameMain.setTitle("Main");
frameMain.setBounds(100, 100, 507, 619);
frameMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameMain.getContentPane().setLayout(null);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setForeground(Color.BLACK);
tabbedPane.setBackground(Color.LIGHT_GRAY);
tabbedPane.setBounds(0, 366, 491, 215);
frameMain.getContentPane().add(tabbedPane);
JTabbedPane alertTab = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.addTab("Alerts", null, alertTab, null);
JTabbedPane statTab = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.addTab("Stats", null, statTab, null);
JTabbedPane relTab = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.addTab("Relationships", null, relTab, null);
JTabbedPane interestTab = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.addTab("Interests", null, interestTab, null);
JTabbedPane chatTab = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.addTab("Chat", null, chatTab, null);
JPanel crustImage = new JPanel();
crustImage.setBorder(new MatteBorder(0, 0, 3, 3, (Color) new Color(0, 0, 0)));
crustImage.setBackground(Color.RED);
crustImage.setBounds(0, 0, 185, 226);
frameMain.getContentPane().add(crustImage);
JPanel crustInfo = new JPanel();
crustInfo.setBorder(new MatteBorder(0, 0, 3, 0, (Color) new Color(0, 0, 0)));
crustInfo.setBounds(184, 0, 307, 226);
frameMain.getContentPane().add(crustInfo);
GridBagLayout gbl_crustInfo = new GridBagLayout();
gbl_crustInfo.columnWidths = new int[]{0, 0, 0, 0, 0};
gbl_crustInfo.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0};
gbl_crustInfo.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_crustInfo.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
crustInfo.setLayout(gbl_crustInfo);
JLabel lblName = new JLabel("Name: ");
lblName.setHorizontalAlignment(SwingConstants.RIGHT);
lblName.setFont(new Font("Tahoma", Font.PLAIN, 14));
GridBagConstraints gbc_lblName = new GridBagConstraints();
gbc_lblName.anchor = GridBagConstraints.EAST;
gbc_lblName.insets = new Insets(0, 0, 5, 5);
gbc_lblName.gridx = 0;
gbc_lblName.gridy = 0;
crustInfo.add(lblName, gbc_lblName);
JLabel lblFullName = new JLabel("John Jacob Schmitt");
lblFullName.setFont(new Font("Tahoma", Font.PLAIN, 14));
GridBagConstraints gbc_lblFullName = new GridBagConstraints();
gbc_lblFullName.anchor = GridBagConstraints.WEST;
gbc_lblFullName.gridwidth = 3;
gbc_lblFullName.insets = new Insets(0, 0, 5, 5);
gbc_lblFullName.gridx = 1;
gbc_lblFullName.gridy = 0;
crustInfo.add(lblFullName, gbc_lblFullName);
JLabel lblAge = new JLabel("Age: ");
lblAge.setHorizontalAlignment(SwingConstants.RIGHT);
lblAge.setFont(new Font("Tahoma", Font.PLAIN, 14));
GridBagConstraints gbc_lblAge = new GridBagConstraints();
gbc_lblAge.anchor = GridBagConstraints.EAST;
gbc_lblAge.insets = new Insets(0, 0, 5, 5);
gbc_lblAge.gridx = 0;
gbc_lblAge.gridy = 1;
crustInfo.add(lblAge, gbc_lblAge);
JLabel lblAgeVal = new JLabel("0");
lblAgeVal.setHorizontalAlignment(SwingConstants.CENTER);
lblAgeVal.setFont(new Font("Tahoma", Font.PLAIN, 14));
GridBagConstraints gbc_lblAgeVal = new GridBagConstraints();
gbc_lblAgeVal.gridwidth = 3;
gbc_lblAgeVal.anchor = GridBagConstraints.SOUTHWEST;
gbc_lblAgeVal.insets = new Insets(0, 0, 5, 5);
gbc_lblAgeVal.gridx = 1;
gbc_lblAgeVal.gridy = 1;
crustInfo.add(lblAgeVal, gbc_lblAgeVal);
JLabel lblStage = new JLabel("Stage: ");
lblStage.setHorizontalAlignment(SwingConstants.RIGHT);
lblStage.setFont(new Font("Tahoma", Font.PLAIN, 14));
GridBagConstraints gbc_lblStage = new GridBagConstraints();
gbc_lblStage.anchor = GridBagConstraints.EAST;
gbc_lblStage.insets = new Insets(0, 0, 5, 5);
gbc_lblStage.gridx = 0;
gbc_lblStage.gridy = 2;
crustInfo.add(lblStage, gbc_lblStage);
JLabel lblStageVal = new JLabel("Child");
lblStageVal.setFont(new Font("Tahoma", Font.PLAIN, 14));
GridBagConstraints gbc_lblStageVal = new GridBagConstraints();
gbc_lblStageVal.anchor = GridBagConstraints.WEST;
gbc_lblStageVal.gridwidth = 3;
gbc_lblStageVal.insets = new Insets(0, 0, 5, 5);
gbc_lblStageVal.gridx = 1;
gbc_lblStageVal.gridy = 2;
crustInfo.add(lblStageVal, gbc_lblStageVal);
JLabel lblEnergy = new JLabel("Energy: ");
lblEnergy.setHorizontalAlignment(SwingConstants.RIGHT);
lblEnergy.setFont(new Font("Tahoma", Font.PLAIN, 14));
GridBagConstraints gbc_lblEnergy = new GridBagConstraints();
gbc_lblEnergy.anchor = GridBagConstraints.EAST;
gbc_lblEnergy.insets = new Insets(0, 0, 5, 5);
gbc_lblEnergy.gridx = 0;
gbc_lblEnergy.gridy = 3;
crustInfo.add(lblEnergy, gbc_lblEnergy);
JProgressBar energyBar = new JProgressBar();
GridBagConstraints gbc_energyBar = new GridBagConstraints();
gbc_energyBar.gridwidth = 3;
gbc_energyBar.insets = new Insets(0, 0, 5, 0);
gbc_energyBar.gridx = 1;
gbc_energyBar.gridy = 3;
crustInfo.add(energyBar, gbc_energyBar);
JLabel lblEntertainment = new JLabel("Entertainment: ");
lblEntertainment.setHorizontalAlignment(SwingConstants.RIGHT);
lblEntertainment.setFont(new Font("Tahoma", Font.PLAIN, 14));
GridBagConstraints gbc_lblEntertainment = new GridBagConstraints();
gbc_lblEntertainment.anchor = GridBagConstraints.EAST;
gbc_lblEntertainment.insets = new Insets(0, 0, 5, 5);
gbc_lblEntertainment.gridx = 0;
gbc_lblEntertainment.gridy = 4;
crustInfo.add(lblEntertainment, gbc_lblEntertainment);
JProgressBar entertainmentBar = new JProgressBar();
GridBagConstraints gbc_entertainmentBar = new GridBagConstraints();
gbc_entertainmentBar.gridwidth = 3;
gbc_entertainmentBar.insets = new Insets(0, 0, 5, 0);
gbc_entertainmentBar.gridx = 1;
gbc_entertainmentBar.gridy = 4;
crustInfo.add(entertainmentBar, gbc_entertainmentBar);
JLabel lblHunger = new JLabel("Hunger: ");
lblHunger.setHorizontalAlignment(SwingConstants.RIGHT);
lblHunger.setFont(new Font("Tahoma", Font.PLAIN, 14));
GridBagConstraints gbc_lblHunger = new GridBagConstraints();
gbc_lblHunger.anchor = GridBagConstraints.EAST;
gbc_lblHunger.insets = new Insets(0, 0, 0, 5);
gbc_lblHunger.gridx = 0;
gbc_lblHunger.gridy = 5;
crustInfo.add(lblHunger, gbc_lblHunger);
JProgressBar hungerBar = new JProgressBar();
GridBagConstraints gbc_hungerBar = new GridBagConstraints();
gbc_hungerBar.gridwidth = 3;
gbc_hungerBar.gridx = 1;
gbc_hungerBar.gridy = 5;
crustInfo.add(hungerBar, gbc_hungerBar);
}
private static void addPopup(Component component, final JPopupMenu popup) {
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
private void showMenu(MouseEvent e) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}
|
package afc.ant.modular;
import java.io.File;
import junit.framework.TestCase;
/**
* <p>Unit tests for {@link ModuleUtil#normalisePath(String, File)}.</p>
*
* @author Dźmitry Laŭčuk
*/
public class ModuleUtil_NormalisePathTest extends TestCase
{
/**
* <p>Tests that {@link ModuleUtil#normalisePath(String, File)} throws
* {@link NullPointerException} if a {@code null} base directory is passed in.</p>
*/
public void testNormalisePath_BaseDirIsCurrentDir_NullBaseDir()
{
try {
ModuleUtil.normalisePath("foo/bar", null);
fail();
}
catch (NullPointerException ex) {
assertEquals("baseDir", ex.getMessage());
}
}
/**
* <p>Tests that {@link ModuleUtil#normalisePath(String, File)} throws
* {@link NullPointerException} if a {@code null} path is passed in.</p>
*/
public void testNormalisePath_BaseDirIsCurrentDir_NullPath()
{
try {
ModuleUtil.normalisePath(null, new File(""));
fail();
}
catch (NullPointerException ex) {
assertEquals("path", ex.getMessage());
}
}
/**
* <p>Tests that {@link ModuleUtil#normalisePath(String, File)} converts
* an empty string as a path to '.' that necessarily points to
* the base directory.</p>
*/
public void testNormalisePath_BaseDirIsCurrentDir_EmptyPath()
{
assertEquals(".", ModuleUtil.normalisePath("", new File("")));
}
/**
* <p>Tests that {@link ModuleUtil#normalisePath(String, File)} normalises
* a direct directory within the base directory to itself (without the
* tailing separator).</p>
*/
public void testNormalisePath_BaseDirIsCurrentDir_DirectChildPathInNormalisedForm()
{
assertEquals("foo", ModuleUtil.normalisePath("foo", new File("")));
}
/**
* <p>Tests that {@link ModuleUtil#normalisePath(String, File)} normalises
* a direct directory with tailing path separator within the base directory
* to itself but without the tailing separator.</p>
*/
public void testNormalisePath_BaseDirIsCurrentDir_DirectChildPathInNonNormalisedForm()
{
assertEquals("foo", ModuleUtil.normalisePath("foo/", new File("")));
}
public void testNormalisePath_BaseDirIsCurrentDir_DeepPathInNormalisedForm()
{
assertEquals("foo/bar/baz", ModuleUtil.normalisePath("foo/bar/baz", new File("")));
}
public void testNormalisePath_BaseDirIsCurrentDir_DeepPathPathInNonNormalisedForm()
{
assertEquals("foo/bar/baz", ModuleUtil.normalisePath("foo/bar/baz/", new File("")));
}
public void testNormalisePath_BaseDirIsCurrentDir_PathIsDotInNormalisedForm()
{
assertEquals(".", ModuleUtil.normalisePath(".", new File("")));
}
public void testNormalisePath_BaseDirIsCurrentDir_PathIsDotInNonNormalisedForm()
{
assertEquals(".", ModuleUtil.normalisePath("./", new File("")));
}
public void testNormalisePath_BaseDirIsCurrentDir_PathStartsWithDot()
{
assertEquals("foo/bar/baz", ModuleUtil.normalisePath("./foo/bar/baz", new File("")));
}
public void testNormalisePath_BaseDirIsCurrentDir_PathContainsDotElement()
{
assertEquals("foo/bar/baz", ModuleUtil.normalisePath("foo/bar/./baz/", new File("")));
}
public void testNormalisePath_BaseDirIsCurrentDir_PathContainsDoubleDotElement()
{
assertEquals("foo/baz", ModuleUtil.normalisePath("foo/bar/../baz/", new File("")));
}
public void testNormalisePath_BaseDirIsCurrentDir_PathContainsDotsAndDoubleDots()
{
assertEquals("foo/baz", ModuleUtil.normalisePath("foo/./bar/.././baz/quux/../", new File("")));
}
public void testNormalisePath_BaseDirIsNotCurrentDir_PathContainsDotsAndDoubleDots()
{
final File baseDir = new File("/hello/world");
assertEquals("foo/baz", ModuleUtil.normalisePath("foo/./bar/.././baz/quux/../", baseDir));
}
public void testNormalisePath_BaseDirIsNotCurrentDir_PathGoesOutsideBaseDir_SimpleCase()
{
final File baseDir = new File("/hello/world");
assertEquals("../foo", ModuleUtil.normalisePath("../foo/", baseDir));
}
public void testNormalisePath_BaseDirIsNotCurrentDir_PathGoesOutsideBaseDir_ComplicatedCase()
{
final File baseDir = new File("/hello/world");
assertEquals("../foo/baz", ModuleUtil.normalisePath("../foo/bar/../baz/./quux/..", baseDir));
}
public void testNormalisePath_BaseDirIsNotCurrentDir_PathGoesOutsideBaseDirAndPartiallyGoesBack()
{
final File baseDir = new File("/hello/world");
assertEquals("..", ModuleUtil.normalisePath("../../hello", baseDir));
}
public void testNormalisePath_BaseDirIsNotCurrentDir_PathGoesOutsideBaseDirAndPartiallyGoesBack_ComplicatedCase()
{
final File baseDir = new File("/hello/world");
assertEquals("../universe", ModuleUtil.normalisePath("../../hello/universe", baseDir));
}
public void testNormalisePath_BaseDirIsNotCurrentDir_PathGoesOutsideBaseDirAndPartiallyGoesBack_BackAndForce()
{
final File baseDir = new File("/hello/world");
assertEquals("..", ModuleUtil.normalisePath("../../hello/universe/..", baseDir));
}
public void testNormalisePath_BaseDirIsNotCurrentDir_PathGoesOutsideBaseDirAndReturnsToIt_SimpleCase()
{
final File baseDir = new File("/hello/world");
assertEquals("foo", ModuleUtil.normalisePath("../world/foo", baseDir));
}
public void testNormalisePath_BaseDirIsNotCurrentDir_PathGoesOutsideBaseDirAndReturnsToIt_NormalisedPathIsBaseDir()
{
final File baseDir = new File("/hello/world");
assertEquals(".", ModuleUtil.normalisePath("../world", baseDir));
}
public void testNormalisePath_BaseDirIsNotCurrentDir_PathGoesOutsideBaseDirAndReturnsToIt_ComplicatedCase()
{
final File baseDir = new File("/hello/world");
assertEquals("foo/baz", ModuleUtil.normalisePath(
"../qwe/../../hello/world/foo/bar/../baz/./quux/..", baseDir));
}
public void testNormalisePath_BaseDirIsNotCurrentDir_PathGoesBeyondRoot()
{
final File baseDir = new File("/hello/world");
assertEquals("foo/baz", ModuleUtil.normalisePath(
"../qwe/../../../hello/world/foo/bar/../baz/./quux/..", baseDir));
}
public void testNormalisePath_AbsolutePath_PointsToBaseDir_DirectMatch()
{
final File baseDir = new File("/hello/world");
assertEquals(".", ModuleUtil.normalisePath("/hello/world", baseDir));
}
public void testNormalisePath_AbsolutePath_PointsToBaseDir_DirectMatch_WithSeparator()
{
final File baseDir = new File("/hello/world");
assertEquals(".", ModuleUtil.normalisePath("/hello/world", baseDir));
}
public void testNormalisePath_AbsolutePath_PointsToBaseDir_GoingBackAndForth()
{
final File baseDir = new File("/hello/world");
assertEquals(".", ModuleUtil.normalisePath("/hello/../../hello/world/foo/..", baseDir));
}
public void testNormalisePath_AbsolutePath_PointsToParentDir()
{
final File baseDir = new File("/hello/world");
assertEquals("..", ModuleUtil.normalisePath("/hello", baseDir));
}
public void testNormalisePath_AbsolutePath_PointsToRoot()
{
final File baseDir = new File("/hello/world");
assertEquals("../..", ModuleUtil.normalisePath("/", baseDir));
}
public void testNormalisePath_AbsolutePath_PointsToSubDir()
{
final File baseDir = new File("/hello/world");
assertEquals("foo", ModuleUtil.normalisePath("/hello/world/foo", baseDir));
}
public void testNormalisePath_AbsolutePath_PointsToSubSubDir()
{
final File baseDir = new File("/hello/world/");
assertEquals("foo/bar", ModuleUtil.normalisePath("/hello/world/foo/./bar/baz/..", baseDir));
}
public void testNormalisePath_NonNormalisedRelativeBaseDir_RelativePath()
{
final File baseDir = new File("hello/./../world");
assertEquals("bar", ModuleUtil.normalisePath("foo/../bar/baz/..", baseDir));
}
public void testNormalisePath_NonNormalisedAbsoluteBaseDir_RelativePath()
{
final File baseDir = new File("/hello/./world");
assertEquals("foo/bar", ModuleUtil.normalisePath("/hello/world/foo/./bar/baz/..", baseDir));
}
public void testNormalisePath_NonNormalisedAbsoluteBaseDirThatGoesBeyondRoot()
{
final File baseDir = new File("/hello/./../../world");
assertEquals("foo/bar", ModuleUtil.normalisePath("/world/foo/./bar/baz/..", baseDir));
}
public void testNormalisePath_NonNormalisedAbsoluteBaseDir_AbsolutePath()
{
final File baseDir = new File("/hello/./world");
assertEquals("foo/bar", ModuleUtil.normalisePath("/hello/world/foo/./bar/baz/..", baseDir));
}
public void testNormalisePath_BaseDirIsRoot()
{
final File baseDir = new File("/");
assertEquals("baz", ModuleUtil.normalisePath("foo/bar/../../../baz", baseDir));
}
public void testNormalisePath_BaseDirIsRoot_PathGoesBeyondRootFromStart()
{
final File baseDir = new File("/");
assertEquals("foo/baz", ModuleUtil.normalisePath("../../../foo/bar/../baz", baseDir));
}
public void testNormalisePath_BaseDirIsRoot_WholePathGoesBeyondRoot()
{
final File baseDir = new File("/");
assertEquals(".", ModuleUtil.normalisePath("../../..", baseDir));
}
public void testNormalisePath_BaseDirEndsWithGoToParentElementsAndGoesBeyondRoot()
{
final File baseDir = new File("/hello/world/../../../");
assertEquals("baz", ModuleUtil.normalisePath("foo/bar/../../../baz", baseDir));
}
public void testNormalisePath_PathGoesUpAndDownAndDoesNotRepeatBaseDir()
{
final File baseDir = new File("/hello/world");
assertEquals("../../foo/bar", ModuleUtil.normalisePath("../../foo/bar", baseDir));
}
public void testNormalisePath_PathGoesUpAndDownAndDoesNotRepeatBaseDir_NamesMatchAtSomeLevel()
{
final File baseDir = new File("/hello/world/baz");
assertEquals("../../../foo/world/baz", ModuleUtil.normalisePath("../../../foo/world/../world/baz", baseDir));
}
}
|
package ifc.sdb;
import com.sun.star.container.XIndexAccess;
import com.sun.star.sdb.XParametersSupplier;
import lib.MultiMethodTest;
/**
* Testing <code>com.sun.star.sdb.XParametersSupplier</code>
* interface methods :
* <ul>
* <li><code> getParameters()</code></li>
* </ul> <p>
* Test is multithread compilant. <p>
* @see com.sun.star.sdb.XParametersSupplier
*/
public class _XParametersSupplier extends MultiMethodTest {
// oObj filled by MultiMethodTest
public XParametersSupplier oObj = null ;
/**
* checks of the return of <code>getParameters()</code>
* is not null
*/
public void _getParameters() {
XIndexAccess the_Set = oObj.getParameters();
if (the_Set == null) log.println("'getParameters()' returns NULL");
tRes.tested("getParameters()",the_Set != null);
}
} // finish class _XParametersSupplier
|
package uk.ac.ebi.quickgo.annotation.model;
import uk.ac.ebi.quickgo.common.validator.GeneProductIDList;
import uk.ac.ebi.quickgo.rest.search.request.FilterRequest;
import java.util.*;
import java.util.stream.Stream;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Pattern;
import static uk.ac.ebi.quickgo.annotation.common.document.AnnotationFields.ASSIGNED_BY;
import static uk.ac.ebi.quickgo.annotation.common.document.AnnotationFields.ECO_ID;
import static uk.ac.ebi.quickgo.annotation.common.document.AnnotationFields.GENE_PRODUCT_ID;
import static uk.ac.ebi.quickgo.annotation.common.document.AnnotationFields.GO_EVIDENCE;
import static uk.ac.ebi.quickgo.annotation.common.document.AnnotationFields.REFERENCE_SEARCH;
import static uk.ac.ebi.quickgo.annotation.common.document.AnnotationFields.TAXON_ID;
import static uk.ac.ebi.quickgo.annotation.common.document.AnnotationFields.WITH_FROM_SEARCH;
import static uk.ac.ebi.quickgo.annotation.common.document.AnnotationFields.QUALIFIER;
public class AnnotationRequest {
public static final int DEFAULT_ENTRIES_PER_PAGE = 25;
public static final int MAX_ENTRIES_PER_PAGE = 100;
private static final int DEFAULT_PAGE_NUMBER = 1;
private static final String COMMA = ",";
private static final String ASPECT_FIELD = "aspect";
private static final String[] targetFields = new String[]{ASPECT_FIELD, ASSIGNED_BY, TAXON_ID, GO_EVIDENCE,
QUALIFIER, REFERENCE_SEARCH, WITH_FROM_SEARCH, ECO_ID, GENE_PRODUCT_ID};
@Min(0) @Max(MAX_ENTRIES_PER_PAGE)
private int limit = DEFAULT_ENTRIES_PER_PAGE;
@Min(1)
private int page = DEFAULT_PAGE_NUMBER;
private final Map<String, String> filterMap = new HashMap<>();
/**
* E.g. ASPGD,Agbase,..
* In the format assignedBy=ASPGD,Agbase
*/
public void setAssignedBy(String assignedBy) {
if (assignedBy != null) {
filterMap.put(ASSIGNED_BY, assignedBy);
}
}
@Pattern(regexp = "^[A-Za-z][A-Za-z\\-_]+(,[A-Za-z][A-Za-z\\-_]+)*",
message = "At least one 'Assigned By' value is invalid: ${validatedValue}")
public String getAssignedBy() {
return filterMap.get(ASSIGNED_BY);
}
/**
* E.g. DOI, DOI:10.1002/adsc.201200590, GO_REF, PMID, PMID:12882977, Reactome, Reactome:R-RNO-912619,
* GO_REF:0000037 etc
* @param reference
* @return
*/
public void setReference(String reference){
filterMap.put(REFERENCE_SEARCH, reference);
}
//todo create validation pattern @Pattern(regexp = "")
public String getReference(){
return filterMap.get(REFERENCE_SEARCH);
}
public void setAspect(String aspect) {
if (aspect != null) {
filterMap.put(ASPECT_FIELD, aspect.toLowerCase());
}
}
@Pattern(regexp = "biological_process|molecular_function|cellular_component", flags = Pattern.Flag.CASE_INSENSITIVE,
message = "At least one 'Aspect' value is invalid: ${validatedValue}")
public String getAspect() {
return filterMap.get(ASPECT_FIELD);
}
/**
* Gene Product IDs, in CSV format.
*/
public void setGpId(String listOfGeneProductIDs){
if(listOfGeneProductIDs != null) {
filterMap.put(GENE_PRODUCT_ID, listOfGeneProductIDs);
}
}
@GeneProductIDList
public String getGpId(){
return filterMap.get(GENE_PRODUCT_ID);
}
public void setGoEvidence(String evidence) {
filterMap.put(GO_EVIDENCE, evidence);
}
/**
* NOT, enables etc
* @param qualifier
*/
public void setQualifier(String qualifier){
filterMap.put(QUALIFIER, qualifier);
}
public String getQualifter(){
return filterMap.get(QUALIFIER);
}
/**
* A list of with/from values, separated by commas
* In the format withFrom=PomBase:SPBP23A10.14c,RGD:621207 etc
* Users can supply just the id (e.g. PomBase) or id SPBP23A10.14c
* @param withFrom comma separated with/from values
*/
public void setWithFrom(String withFrom){
filterMap.put(WITH_FROM_SEARCH, withFrom);
}
/**
* Return a list of with/from values, separated by commas
* @return String containing comma separated list of with/From values.
*/
public String getWithFrom(){
return filterMap.get(WITH_FROM_SEARCH);
}
@Pattern(regexp = "^[A-Za-z]{2,3}(,[A-Za-z]{2,3})*",
message = "At least one 'GO Evidence' value is invalid: ${validatedValue}")
public String getGoEvidence() {
return filterMap.get(GO_EVIDENCE);
}
public void setTaxon(String taxId) {
filterMap.put(TAXON_ID, taxId);
}
@Pattern(regexp = "[0-9]+(,[0-9]+)*",
message = "At least one 'Taxonomic identifier' value is invalid: ${validatedValue}")
public String getTaxon() {
return filterMap.get(TAXON_ID);
}
/**
* Will receive a list of eco ids thus: EcoId=ECO:0000256,ECO:0000323
* @param ecoId
*/
public void setEcoId(String ecoId) {
filterMap.put(ECO_ID,ecoId);
}
@Pattern(regexp = "(?i)ECO:[0-9]{7}(,ECO:[0-9]{7})*",
message = "At least one invalid 'ECO identifier' value is invalid: ${validatedValue}")
public String getEcoId(){
return filterMap.get(ECO_ID);
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public List<FilterRequest> createRequestFilters() {
List<FilterRequest> filterRequests = new ArrayList<>();
Stream.of(targetFields)
.map(this::createSimpleFilter)
.forEach(f ->f.ifPresent(filterRequests::add));
return filterRequests;
}
private Optional<FilterRequest> createSimpleFilter(String key) {
Optional<FilterRequest> request;
if (filterMap.containsKey(key)) {
FilterRequest.Builder requestBuilder = FilterRequest.newBuilder();
requestBuilder.addProperty(key, filterMap.get(key).split(COMMA));
request = Optional.of(requestBuilder.build());
} else {
request = Optional.empty();
}
return request;
}
}
|
package org.spine3.examples.todolist.c.aggregate;
import com.google.protobuf.Message;
import com.google.protobuf.Timestamp;
import org.spine3.change.StringChange;
import org.spine3.change.TimestampChange;
import org.spine3.change.ValueMismatch;
import org.spine3.examples.todolist.LabelId;
import org.spine3.examples.todolist.PriorityChange;
import org.spine3.examples.todolist.TaskDefinition;
import org.spine3.examples.todolist.TaskDetails;
import org.spine3.examples.todolist.TaskId;
import org.spine3.examples.todolist.TaskLabels;
import org.spine3.examples.todolist.TaskPriority;
import org.spine3.examples.todolist.TaskStatus;
import org.spine3.examples.todolist.c.commands.CompleteTask;
import org.spine3.examples.todolist.c.commands.CreateBasicTask;
import org.spine3.examples.todolist.c.commands.CreateDraft;
import org.spine3.examples.todolist.c.commands.DeleteTask;
import org.spine3.examples.todolist.c.commands.FinalizeDraft;
import org.spine3.examples.todolist.c.commands.ReopenTask;
import org.spine3.examples.todolist.c.commands.RestoreDeletedTask;
import org.spine3.examples.todolist.c.commands.UpdateTaskDescription;
import org.spine3.examples.todolist.c.commands.UpdateTaskDueDate;
import org.spine3.examples.todolist.c.commands.UpdateTaskPriority;
import org.spine3.examples.todolist.c.events.DeletedTaskRestored;
import org.spine3.examples.todolist.c.events.LabelledTaskRestored;
import org.spine3.examples.todolist.c.events.TaskCompleted;
import org.spine3.examples.todolist.c.events.TaskCreated;
import org.spine3.examples.todolist.c.events.TaskDeleted;
import org.spine3.examples.todolist.c.events.TaskDescriptionUpdated;
import org.spine3.examples.todolist.c.events.TaskDraftCreated;
import org.spine3.examples.todolist.c.events.TaskDraftFinalized;
import org.spine3.examples.todolist.c.events.TaskDueDateUpdated;
import org.spine3.examples.todolist.c.events.TaskPriorityUpdated;
import org.spine3.examples.todolist.c.events.TaskReopened;
import org.spine3.examples.todolist.c.failures.CannotCompleteTask;
import org.spine3.examples.todolist.c.failures.CannotCreateBasicTask;
import org.spine3.examples.todolist.c.failures.CannotCreateDraft;
import org.spine3.examples.todolist.c.failures.CannotCreateTaskWithInappropriateDescription;
import org.spine3.examples.todolist.c.failures.CannotDeleteTask;
import org.spine3.examples.todolist.c.failures.CannotFinalizeDraft;
import org.spine3.examples.todolist.c.failures.CannotReopenTask;
import org.spine3.examples.todolist.c.failures.CannotRestoreDeletedTask;
import org.spine3.examples.todolist.c.failures.CannotUpdateTaskDescription;
import org.spine3.examples.todolist.c.failures.CannotUpdateTaskDueDate;
import org.spine3.examples.todolist.c.failures.CannotUpdateTaskPriority;
import org.spine3.examples.todolist.c.failures.CannotUpdateTaskWithInappropriateDescription;
import org.spine3.protobuf.Timestamps;
import org.spine3.server.aggregate.AggregatePart;
import org.spine3.server.aggregate.Apply;
import org.spine3.server.command.Assign;
import java.util.Collections;
import java.util.List;
import static com.google.common.collect.Lists.newLinkedList;
import static org.spine3.examples.todolist.c.aggregate.ExceptionMessages.create;
import static org.spine3.examples.todolist.c.aggregate.FailureHelper.CreateFailures.throwCannotCreateDraftFailure;
import static org.spine3.examples.todolist.c.aggregate.FailureHelper.CreateFailures.throwCannotCreateTaskWithInappropriateDescriptionFailure;
import static org.spine3.examples.todolist.c.aggregate.FailureHelper.TASK_DELETED_OR_COMPLETED_EXCEPTION_MESSAGE;
import static org.spine3.examples.todolist.c.aggregate.FailureHelper.UpdateFailures.throwCannotUpdateDescriptionFailure;
import static org.spine3.examples.todolist.c.aggregate.FailureHelper.UpdateFailures.throwCannotUpdateTaskDescriptionFailure;
import static org.spine3.examples.todolist.c.aggregate.FailureHelper.UpdateFailures.throwCannotUpdateTaskDueDateFailure;
import static org.spine3.examples.todolist.c.aggregate.FailureHelper.UpdateFailures.throwCannotUpdateTaskPriorityFailure;
import static org.spine3.examples.todolist.c.aggregate.FailureHelper.UpdateFailures.throwCannotUpdateTooShortDescriptionFailure;
import static org.spine3.examples.todolist.c.aggregate.FailureHelper.throwCannotCompleteTaskFailure;
import static org.spine3.examples.todolist.c.aggregate.FailureHelper.throwCannotDeleteTaskFailure;
import static org.spine3.examples.todolist.c.aggregate.FailureHelper.throwCannotFinalizeDraftFailure;
import static org.spine3.examples.todolist.c.aggregate.FailureHelper.throwCannotReopenTaskFailure;
import static org.spine3.examples.todolist.c.aggregate.FailureHelper.throwCannotRestoreDeletedTaskFailure;
import static org.spine3.examples.todolist.c.aggregate.MismatchHelper.of;
import static org.spine3.examples.todolist.c.aggregate.TaskFlowValidator.isValidCreateDraftCommand;
import static org.spine3.examples.todolist.c.aggregate.TaskFlowValidator.isValidTransition;
import static org.spine3.examples.todolist.c.aggregate.TaskFlowValidator.isValidUpdateTaskDueDateCommand;
import static org.spine3.examples.todolist.c.aggregate.TaskFlowValidator.isValidUpdateTaskPriorityCommand;
/**
* The aggregate managing the state of a {@link TaskDefinition}.
*
* @author Illia Shepilov
*/
@SuppressWarnings({"OverlyCoupledClass", "ClassWithTooManyMethods"})
// because according to the domain model task definition cannot be separated
// and should process all commands and methods related to him.
public class TaskDefinitionPart extends AggregatePart<TaskId, TaskDefinition, TaskDefinition.Builder> {
private static final int MIN_DESCRIPTION_LENGTH = 3;
/**
* {@inheritDoc}
*
* @param id
*/
public TaskDefinitionPart(TaskId id) {
super(id);
}
@Assign
List<? extends Message> handle(CreateBasicTask cmd)
throws CannotCreateBasicTask, CannotCreateTaskWithInappropriateDescription {
validateCommand(cmd);
final TaskId taskId = cmd.getId();
final TaskDetails.Builder taskDetails = TaskDetails.newBuilder()
.setDescription(cmd.getDescription());
final TaskCreated result = TaskCreated.newBuilder()
.setId(taskId)
.setDetails(taskDetails)
.build();
return Collections.singletonList(result);
}
@Assign
List<? extends Message> handle(UpdateTaskDescription cmd)
throws CannotUpdateTaskDescription, CannotUpdateTaskWithInappropriateDescription {
validateCommand(cmd);
final TaskDefinition state = getState();
final StringChange change = cmd.getDescriptionChange();
final String actualDescription = state.getDescription();
final String expectedDescription = change.getPreviousValue();
final boolean isEquals = actualDescription.equals(expectedDescription);
final TaskId taskId = cmd.getId();
if (!isEquals) {
final String newDescription = change.getNewValue();
final ValueMismatch mismatch = of(expectedDescription, actualDescription, newDescription, getVersion());
throwCannotUpdateDescriptionFailure(taskId, mismatch);
}
final TaskDescriptionUpdated taskDescriptionUpdated = TaskDescriptionUpdated.newBuilder()
.setTaskId(taskId)
.setDescriptionChange(change)
.build();
final List<? extends Message> result = Collections.singletonList(taskDescriptionUpdated);
return result;
}
@Assign
List<? extends Message> handle(UpdateTaskDueDate cmd) throws CannotUpdateTaskDueDate {
final TaskDefinition state = getState();
final TaskStatus taskStatus = state.getTaskStatus();
final boolean isValid = isValidUpdateTaskDueDateCommand(taskStatus);
final TaskId taskId = cmd.getId();
if (!isValid) {
throwCannotUpdateTaskDueDateFailure(taskId);
}
final TimestampChange change = cmd.getDueDateChange();
final Timestamp actualDueDate = state.getDueDate();
final Timestamp expectedDueDate = change.getPreviousValue();
final boolean isEquals = Timestamps.compare(actualDueDate, expectedDueDate) == 0;
if (!isEquals) {
final Timestamp newDueDate = change.getNewValue();
final ValueMismatch mismatch = of(expectedDueDate, actualDueDate, newDueDate, getVersion());
throwCannotUpdateTaskDueDateFailure(taskId, mismatch);
}
final TaskDueDateUpdated taskDueDateUpdated = TaskDueDateUpdated.newBuilder()
.setTaskId(taskId)
.setDueDateChange(cmd.getDueDateChange())
.build();
final List<? extends Message> result = Collections.singletonList(taskDueDateUpdated);
return result;
}
@Assign
List<? extends Message> handle(UpdateTaskPriority cmd) throws CannotUpdateTaskPriority {
final TaskDefinition state = getState();
final TaskStatus taskStatus = state.getTaskStatus();
final boolean isValid = isValidUpdateTaskPriorityCommand(taskStatus);
final TaskId taskId = cmd.getId();
if (!isValid) {
throwCannotUpdateTaskPriorityFailure(taskId);
}
final PriorityChange priorityChange = cmd.getPriorityChange();
final TaskPriority actualPriority = state.getPriority();
final TaskPriority expectedPriority = priorityChange.getPreviousValue();
boolean isEquals = actualPriority == expectedPriority;
if (!isEquals) {
final TaskPriority newPriority = priorityChange.getNewValue();
final ValueMismatch mismatch = of(expectedPriority, actualPriority, newPriority, getVersion());
throwCannotUpdateTaskPriorityFailure(taskId, mismatch);
}
final TaskPriorityUpdated taskPriorityUpdated = TaskPriorityUpdated.newBuilder()
.setTaskId(taskId)
.setPriorityChange(priorityChange)
.build();
final List<? extends Message> result = Collections.singletonList(taskPriorityUpdated);
return result;
}
@Assign
List<? extends Message> handle(ReopenTask cmd) throws CannotReopenTask {
final TaskDefinition state = getState();
final TaskStatus currentStatus = state.getTaskStatus();
final TaskStatus newStatus = TaskStatus.OPEN;
final boolean isValid = isValidTransition(currentStatus, newStatus);
final TaskId taskId = cmd.getId();
if (!isValid) {
final String message = create(currentStatus, newStatus);
throwCannotReopenTaskFailure(taskId, message);
}
final TaskReopened taskReopened = TaskReopened.newBuilder()
.setTaskId(taskId)
.build();
final List<TaskReopened> result = Collections.singletonList(taskReopened);
return result;
}
@Assign
List<? extends Message> handle(DeleteTask cmd) throws CannotDeleteTask {
final TaskDefinition state = getState();
final TaskStatus currentStatus = state.getTaskStatus();
final TaskStatus newStatus = TaskStatus.DELETED;
final TaskId taskId = cmd.getId();
final boolean isValid = isValidTransition(currentStatus, newStatus);
if (!isValid) {
final String message = create(currentStatus, newStatus);
throwCannotDeleteTaskFailure(taskId, message);
}
final TaskDeleted taskDeleted = TaskDeleted.newBuilder()
.setTaskId(taskId)
.build();
final List<TaskDeleted> result = Collections.singletonList(taskDeleted);
return result;
}
@Assign
List<? extends Message> handle(CompleteTask cmd) throws CannotCompleteTask {
final TaskDefinition state = getState();
final TaskStatus currentStatus = state.getTaskStatus();
final TaskStatus newStatus = TaskStatus.COMPLETED;
final TaskId taskId = cmd.getId();
final boolean isValid = isValidTransition(currentStatus, newStatus);
if (!isValid) {
final String message = create(currentStatus, newStatus);
throwCannotCompleteTaskFailure(taskId, message);
}
final TaskCompleted taskCompleted = TaskCompleted.newBuilder()
.setTaskId(taskId)
.build();
final List<TaskCompleted> result = Collections.singletonList(taskCompleted);
return result;
}
@Assign
List<? extends Message> handle(CreateDraft cmd) throws CannotCreateDraft {
final TaskId taskId = cmd.getId();
final boolean isValid = isValidCreateDraftCommand(getState().getTaskStatus());
if (!isValid) {
throwCannotCreateDraftFailure(taskId);
}
final TaskDraftCreated draftCreated = TaskDraftCreated.newBuilder()
.setId(taskId)
.setDraftCreationTime(Timestamps.getCurrentTime())
.build();
final List<TaskDraftCreated> result = Collections.singletonList(draftCreated);
return result;
}
@Assign
List<? extends Message> handle(FinalizeDraft cmd) throws CannotFinalizeDraft {
final TaskStatus currentStatus = getState().getTaskStatus();
final TaskStatus newStatus = TaskStatus.FINALIZED;
final TaskId taskId = cmd.getId();
final boolean isValid = isValidTransition(currentStatus, newStatus);
if (!isValid) {
final String message = create(currentStatus, newStatus);
throwCannotFinalizeDraftFailure(taskId, message);
}
final TaskDraftFinalized taskDraftFinalized = TaskDraftFinalized.newBuilder()
.setTaskId(taskId)
.build();
final List<TaskDraftFinalized> result = Collections.singletonList(taskDraftFinalized);
return result;
}
@Assign
List<? extends Message> handle(RestoreDeletedTask cmd) throws CannotRestoreDeletedTask {
final TaskStatus currentStatus = getState().getTaskStatus();
final TaskStatus newStatus = TaskStatus.OPEN;
final TaskId taskId = cmd.getId();
final boolean isValid = isValidTransition(currentStatus, newStatus);
if (!isValid) {
final String message = create(currentStatus, newStatus);
throwCannotRestoreDeletedTaskFailure(taskId, message);
}
final DeletedTaskRestored deletedTaskRestored = DeletedTaskRestored.newBuilder()
.setTaskId(taskId)
.build();
final List<Message> result = newLinkedList();
result.add(deletedTaskRestored);
final TaskAggregateRoot root = TaskAggregateRoot.get(taskId);
final TaskLabels taskLabels = root.getTaskLabelIdsState();
final List<LabelId> labelIdsList = taskLabels.getLabelIdsList()
.getIdsList();
for (LabelId labelId : labelIdsList) {
final LabelledTaskRestored labelledTaskRestored = LabelledTaskRestored.newBuilder()
.setTaskId(taskId)
.setLabelId(labelId)
.build();
result.add(labelledTaskRestored);
}
return result;
}
@Apply
private void taskCreated(TaskCreated event) {
final TaskDetails taskDetails = event.getDetails();
getBuilder().setId(event.getId())
.setCreated(Timestamps.getCurrentTime())
.setDescription(taskDetails.getDescription())
.setPriority(taskDetails.getPriority())
.setTaskStatus(TaskStatus.FINALIZED);
}
@Apply
private void taskDescriptionUpdated(TaskDescriptionUpdated event) {
final String newDescription = event.getDescriptionChange()
.getNewValue();
getBuilder().setDescription(newDescription);
}
@Apply
private void taskDueDateUpdated(TaskDueDateUpdated event) {
final Timestamp newDueDate = event.getDueDateChange()
.getNewValue();
getBuilder().setDueDate(newDueDate);
}
@Apply
private void taskPriorityUpdated(TaskPriorityUpdated event) {
final TaskPriority newPriority = event.getPriorityChange()
.getNewValue();
getBuilder().setPriority(newPriority);
}
@Apply
private void taskReopened(TaskReopened event) {
getBuilder().setTaskStatus(TaskStatus.OPEN);
}
@Apply
private void taskDeleted(TaskDeleted event) {
getBuilder().setTaskStatus(TaskStatus.DELETED);
}
@Apply
private void deletedTaskRestored(DeletedTaskRestored event) {
getBuilder().setTaskStatus(TaskStatus.OPEN);
}
@Apply
private void labelledTaskRestored(LabelledTaskRestored event) {
getBuilder().setTaskStatus(TaskStatus.OPEN);
}
@Apply
private void taskCompleted(TaskCompleted event) {
getBuilder().setTaskStatus(TaskStatus.COMPLETED);
}
@Apply
private void taskDraftFinalized(TaskDraftFinalized event) {
getBuilder().setTaskStatus(TaskStatus.FINALIZED);
}
@Apply
private void draftCreated(TaskDraftCreated event) {
getBuilder().setId(event.getId())
.setCreated(event.getDraftCreationTime())
.setDescription(event.getDetails()
.getDescription())
.setTaskStatus(TaskStatus.DRAFT);
}
private static void validateCommand(CreateBasicTask cmd)
throws CannotCreateBasicTask, CannotCreateTaskWithInappropriateDescription {
final String description = cmd.getDescription();
if (description != null && description.length() < MIN_DESCRIPTION_LENGTH) {
final TaskId taskId = cmd.getId();
throwCannotCreateTaskWithInappropriateDescriptionFailure(taskId);
}
}
private void validateCommand(UpdateTaskDescription cmd)
throws CannotUpdateTaskDescription, CannotUpdateTaskWithInappropriateDescription {
final String description = cmd.getDescriptionChange()
.getNewValue();
final TaskId taskId = cmd.getId();
if (description != null && description.length() < MIN_DESCRIPTION_LENGTH) {
throwCannotUpdateTooShortDescriptionFailure(taskId);
}
boolean isValid = TaskFlowValidator.ensureNeitherCompletedNorDeleted(getState().getTaskStatus());
if (!isValid) {
throwCannotUpdateTaskDescriptionFailure(taskId, TASK_DELETED_OR_COMPLETED_EXCEPTION_MESSAGE);
}
}
}
|
package de.dentrassi.pm.testing;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
public class UserTest extends AbstractServerTest
{
private static final String TEST_USER_REAL_NAME = "Drone Tester";
private static final String TEST_USER_EMAIL = "dronetester@dentrassi.de";
private static final String TEST_USER_PASSWORD = "123456";
@Test
public void testConfig ()
{
driver.get ( resolve ( "/user" ) );
// check if we are on the right page
Assert.assertEquals ( resolve ( "/user" ), driver.getCurrentUrl () );
// add
driver.get ( resolve ( "/user/add" ) );
Assert.assertEquals ( resolve ( "/user/add" ), driver.getCurrentUrl () );
// enter
driver.findElementById ( "email" ).sendKeys ( TEST_USER_EMAIL );
driver.findElementById ( "name" ).sendKeys ( TEST_USER_REAL_NAME );
driver.findElementById ( "command" ).submit ();
Assert.assertTrue ( driver.getCurrentUrl ().endsWith ( "/view" ) );
final String userId = driver.findElementById ( "userId" ).getText ();
driver.findElementByClassName ( "btn-primary" ).click ();
Assert.assertTrue ( driver.getCurrentUrl ().endsWith ( "/" + userId + "/edit" ) );
final WebElement newRoleInput = driver.findElement ( By.id ( "newRole" ) );
final WebElement newRoleButton = driver.findElement ( By.id ( "btnNewRole" ) );
newRole ( newRoleInput, newRoleButton, "ADMIN" );
newRole ( newRoleInput, newRoleButton, "MANAGER" );
driver.findElementById ( "command" ).submit ();
Assert.assertTrue ( driver.getCurrentUrl ().endsWith ( "/" + userId + "/view" ) );
driver.get ( resolve ( "/logout" ) );
setPassword ( userId, TEST_USER_PASSWORD );
driver.get ( resolve ( "/login" ) );
driver.findElementById ( "email" ).sendKeys ( TEST_USER_EMAIL );
driver.findElementById ( "password" ).sendKeys ( TEST_USER_PASSWORD );
driver.findElementById ( "command" ).submit ();
}
private void newRole ( final WebElement newRoleInput, final WebElement newRoleButton, final String role )
{
newRoleInput.clear ();
newRoleInput.sendKeys ( role );
newRoleButton.click ();
}
private void setPassword ( final String userId, final String password )
{
final String salt = Tokens.createToken ( 32 );
final String hash = Tokens.hashIt ( salt, password );
try
{
try ( final Connection con = DriverManager.getConnection ( getTestJdbcUrl (), getTestUser (), getTestUser () ) )
{
try ( PreparedStatement stmt = con.prepareStatement ( "UPDATE USERS SET PASSWORD_HASH=?, PASSWORD_SALT=? WHERE ID=?" ) )
{
stmt.setString ( 1, hash );
stmt.setString ( 2, salt );
stmt.setString ( 3, userId );
final int count = stmt.executeUpdate ();
Assert.assertEquals ( "Number of changed users", 1, count );
}
}
}
catch ( final Exception e )
{
throw new RuntimeException ( e );
}
}
}
|
import java.awt.*;
import javax.swing.*;
/**
* This class draws a tableau of dominoes.
* @author Tyson Gern
* @version 0.1
*/
public class DrawDomino extends Canvas
{
Tableau dominoTableau;
int scale = 50;
int offset = 10;
int titleHeight = 30;
int xLabelOffset = scale/15;
int yLabelOffset = scale/15;
public int width;
public int height;
public DrawDomino(Tableau input) {
dominoTableau = input;
width = scale*input.maxWidth() + 2*offset;
height = scale*input.maxHeight() + 2*offset + titleHeight;
}
public void paint(Graphics graphics) {
int longSide = 2*scale;
int shortSide = scale;
for (int i = 0; i < dominoTableau.getSize(); i++) {
Domino current = dominoTableau.getDomino(i);
int xVal = current.getFirstBlock().getXVal();
int yVal = current.getFirstBlock().getYVal();
int labelInt = current.getLabel();
String labelSt = Integer.toString(labelInt);
int xCoord = scale*(xVal-1)+offset;
int yCoord = scale*(yVal-1)+offset;
if (dominoTableau.getDomino(i).getIsVertical()) {
graphics.drawRect(xCoord, yCoord, shortSide, longSide);
graphics.drawString(labelSt, xCoord+scale/2-xLabelOffset, yCoord+scale+yLabelOffset);
}
else {
graphics.drawRect(xCoord, yCoord, longSide, shortSide);
graphics.drawString(labelSt, xCoord+scale-xLabelOffset, yCoord+scale/2+yLabelOffset);
}
}
}
}
|
package com.example.android.androidsimulator.activities;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import com.example.android.androidsimulator.data.Messages;
import com.example.android.androidsimulator.adapters.MessagesAdapter;
import com.example.android.androidsimulator.R;
import java.util.ArrayList;
public class MessagesActivity extends AppCompatActivity {
ArrayList<Messages> messages;
MessagesAdapter messagesAdapter;
Button newMessage_button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messages);
newMessage_button = (Button) findViewById(R.id.newMessage_button);
newMessage_button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// open the Activity SelectedMessageContact to create a new message
Intent intent = new Intent(MessagesActivity.this, SelectedMessageContact.class);
intent.putExtra("selectedContact", 0);
startActivity(intent);
}
});
showListMessages();
}
private void showListMessages() {
messages = new ArrayList<>();
messages.add(new Messages("Malucs", "Olá people, tudo?", "18/10"));
messages.add(new Messages("Developer", "Vem ter comigo", "18/10"));
addAdapter();
}
private void addAdapter() {
messagesAdapter = new MessagesAdapter(this, messages);
ListView listView = (ListView) findViewById(R.id.list_messages);
listView.setAdapter(messagesAdapter);
}
}
|
package com.microsoft.office365.msgraphsnippetapp.snippet;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import com.microsoft.office365.msgraphapiservices.MSGraphDrivesService;
import java.io.IOException;
import java.io.InputStreamReader;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedString;
import static com.microsoft.office365.msgraphsnippetapp.R.array.create_me_file;
import static com.microsoft.office365.msgraphsnippetapp.R.array.create_me_folder;
import static com.microsoft.office365.msgraphsnippetapp.R.array.delete_me_file;
import static com.microsoft.office365.msgraphsnippetapp.R.array.download_me_file;
import static com.microsoft.office365.msgraphsnippetapp.R.array.get_me_drive;
import static com.microsoft.office365.msgraphsnippetapp.R.array.get_me_files;
import static com.microsoft.office365.msgraphsnippetapp.R.array.get_organization_drives;
import static com.microsoft.office365.msgraphsnippetapp.R.array.rename_me_file;
import static com.microsoft.office365.msgraphsnippetapp.R.array.update_me_file;
abstract class DrivesSnippets<Result> extends AbstractSnippet<MSGraphDrivesService, Result> {
public DrivesSnippets(Integer descriptionArray) {
super(SnippetCategory.drivesSnippetCategory, descriptionArray);
}
static DrivesSnippets[] getDrivesSnippets() {
return new DrivesSnippets[]{
// Marker element
new DrivesSnippets(null) {
@Override
public void request(MSGraphDrivesService o, retrofit.Callback callback) {
//No implementation
}
},
//Snippets
new DrivesSnippets<Void>(get_me_drive) {
@Override
public void request(MSGraphDrivesService service, retrofit.Callback<Void> callback) {
service.getDrive(
getVersion(),
callback);
}
},
new DrivesSnippets<Void>(get_organization_drives) {
@Override
public void request(MSGraphDrivesService service, retrofit.Callback<Void> callback) {
service.getOrganizationDrives(
getVersion(),
callback);
}
},
new DrivesSnippets<Void>(get_me_files) {
@Override
public void request(final MSGraphDrivesService service, final retrofit.Callback<Void> callback) {
//Get first group
service.getCurrentUserFiles(getVersion(), callback);
}
},
new DrivesSnippets<Void>(create_me_file) {
@Override
public void request(final MSGraphDrivesService service, final retrofit.Callback<Void> callback) {
//Create a new file under root
TypedString fileContents = new TypedString("file contents");
service.putNewFile(getVersion(), java.util.UUID.randomUUID().toString(), fileContents, callback);
}
},
new DrivesSnippets<Void>(download_me_file) {
@Override
public void request(
final MSGraphDrivesService MSGraphDrivesService,
final Callback<Void> callback) {
TypedString body = new TypedString("file contents") {
@Override
public String mimeType() {
return "text/plain";
}
};
MSGraphDrivesService.putNewFile(getVersion(), java.util.UUID.randomUUID().toString(), body, new Callback<Void>() {
@Override
public void success(Void aVoid, Response response) {
//download the file we created
MSGraphDrivesService.downloadFile(
getVersion(),
getFileId(response),
callback);
}
@Override
public void failure(RetrofitError error) {
//pass along error to original callback
callback.failure(error);
}
});
}
},
new DrivesSnippets<Void>(update_me_file) {
@Override
public void request(
final MSGraphDrivesService MSGraphDrivesService,
final Callback<Void> callback) {
final TypedString body = new TypedString("file contents") {
@Override
public String mimeType() {
return "text/plain";
}
};
MSGraphDrivesService.putNewFile(getVersion(), java.util.UUID.randomUUID().toString(), body, new Callback<Void>() {
@Override
public void success(Void aVoid, Response response) {
final TypedString updatedBody = new TypedString("Updated file contents") {
@Override
public String mimeType() {
return "application/json";
}
};
//download the file we created
MSGraphDrivesService.updateFile(
getVersion(),
getFileId(response),
updatedBody,
callback);
}
@Override
public void failure(RetrofitError error) {
//pass along error to original callback
callback.failure(error);
}
});
}
},
new DrivesSnippets<Void>(delete_me_file) {
@Override
public void request(
final MSGraphDrivesService MSGraphDrivesService,
final Callback<Void> callback) {
final TypedString body = new TypedString("file contents") {
@Override
public String mimeType() {
return "application/json";
}
};
MSGraphDrivesService.putNewFile(getVersion(), java.util.UUID.randomUUID().toString(), body, new Callback<Void>() {
@Override
public void success(Void aVoid, Response response) {
//download the file we created
MSGraphDrivesService.deleteFile(
getVersion(),
getFileId(response),
callback);
}
@Override
public void failure(RetrofitError error) {
//pass along error to original callback
callback.failure(error);
}
});
}
},
new DrivesSnippets<Void>(rename_me_file) {
@Override
public void request(
final MSGraphDrivesService MSGraphDrivesService,
final Callback<Void> callback) {
final TypedString body = new TypedString("file contents") {
@Override
public String mimeType() {
return "application/json";
}
};
MSGraphDrivesService.putNewFile(getVersion(), java.util.UUID.randomUUID().toString(), body, new Callback<Void>() {
@Override
public void success(Void aVoid, Response response) {
// Build contents of post body and convert to StringContent object.
// Using line breaks for readability.
String patchBody = "{"
+ "'name':'" + java.util.UUID.randomUUID().toString() + "'}";
final TypedString body = new TypedString(patchBody){
@Override
public String mimeType() { return "application/json";}
};
//download the file we created
MSGraphDrivesService.renameFile(
getVersion(),
getFileId(response),
body,
callback);
}
@Override
public void failure(RetrofitError error) {
//pass along error to original callback
callback.failure(error);
}
});
}
},
new DrivesSnippets<Void>(create_me_folder) {
@Override
public void request(
final MSGraphDrivesService MSGraphDrivesService,
final Callback<Void> callback) {
String folderMetadata = "{"
+ "'name': '" + java.util.UUID.randomUUID().toString() + "',"
+ "'folder': {},"
+ "'@name.conflictBehavior': 'rename'"
+ "}"
;
final TypedString body = new TypedString(folderMetadata){
@Override
public String mimeType() { return "application/json";}
};
//download the file we created
MSGraphDrivesService.createFolder(
getVersion(),
body,
callback);
}
}
};
}
public abstract void request(MSGraphDrivesService MSGraphDrivesService, Callback<Result> callback);
protected String getFileId(retrofit.client.Response json) {
if (json == null)
return "";
String fileId;
try {
JsonReader reader = new JsonReader(new InputStreamReader(json.getBody().in(), "UTF-8"));
JsonElement responseElement = new JsonParser().parse(reader);
JsonObject responseObject = responseElement.getAsJsonObject();
fileId = responseObject.get("id").getAsString();
return fileId;
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
}
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// included in all copies or substantial portions of the Software.
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package com.permutassep.presentation.view.fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lalongooo.permutassep.R;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.IconicsDrawable;
import com.permutassep.presentation.interfaces.FragmentMenuItemSelectedListener;
import com.permutassep.presentation.interfaces.PostListListener;
import com.permutassep.presentation.internal.di.components.ApplicationComponent;
import com.permutassep.presentation.internal.di.components.DaggerPostComponent;
import com.permutassep.presentation.internal.di.components.PostComponent;
import com.permutassep.presentation.internal.di.modules.PostModule;
import com.permutassep.presentation.model.PostModel;
import com.permutassep.presentation.presenter.SearchPostsResultsPresenter;
import com.permutassep.presentation.utils.PrefUtils;
import com.permutassep.presentation.view.SearchPostsResultsView;
import com.permutassep.presentation.view.activity.BaseActivity;
import com.permutassep.presentation.view.adapter.PostsAdapter;
import com.permutassep.presentation.view.adapter.PostsLayoutManager;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import javax.inject.Inject;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* By Jorge E. Hernandez (@lalongooo) 2015
*/
public class FragmentSearchResults extends BaseFragment implements SearchPostsResultsView {
private static final String ARGUMENT_SEARCH_PARAMS = "argument_search_params";
@Inject
SearchPostsResultsPresenter postListPresenter;
@Bind(R.id.rv_users)
RecyclerView rv_posts;
private MaterialDialog progressDialog;
private HashMap<String, String> searchParams;
private PostComponent postComponent;
private FragmentMenuItemSelectedListener fragmentMenuItemSelectedListener;
private PostsAdapter postsAdapter;
private PostsLayoutManager postsLayoutManager;
private PostListListener postListListener;
public static FragmentSearchResults newInstance(HashMap<String, String> searchParams) {
FragmentSearchResults fragmentSearchResults = new FragmentSearchResults();
Bundle args = new Bundle();
args.putSerializable(ARGUMENT_SEARCH_PARAMS, searchParams);
fragmentSearchResults.setArguments(args);
return fragmentSearchResults;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.ca_fragment_post_list, container, false);
ButterKnife.bind(this, fragmentView);
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
actionBar.show();
}
setupUI();
setHasOptionsMenu(true);
return fragmentView;
}
private void setupUI() {
this.postsLayoutManager = new PostsLayoutManager(getActivity());
this.rv_posts.setLayoutManager(postsLayoutManager);
this.postsAdapter = new PostsAdapter(getActivity(), new ArrayList<PostModel>());
this.postsAdapter.setOnItemClickListener(onItemClickListener);
this.rv_posts.setAdapter(postsAdapter);
}
private PostsAdapter.OnItemClickListener onItemClickListener = new PostsAdapter.OnItemClickListener() {
@Override
public void onPostItemClicked(PostModel postModel) {
if (FragmentSearchResults.this.postListPresenter != null && postModel != null) {
FragmentSearchResults.this.postListPresenter.onPostClicked(postModel);
}
}
};
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.postListListener = (PostListListener) getActivity();
this.fragmentMenuItemSelectedListener = (FragmentMenuItemSelectedListener) getActivity();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.initialize();
this.loadUserList();
}
@SuppressWarnings("deprecation")
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
if (PrefUtils.getUser(getActivity()) != null) {
menu.findItem(R.id.action_post).setIcon(new IconicsDrawable(getActivity(), GoogleMaterial.Icon.gmd_add).color(Color.WHITE).actionBarSize()).setVisible(true);
menu.findItem(R.id.action_search).setIcon(new IconicsDrawable(getActivity(), GoogleMaterial.Icon.gmd_search).color(Color.WHITE).actionBarSize());
menu.findItem(R.id.action_logout).setVisible(true);
}
menu.findItem(R.id.action_search).setIcon(new IconicsDrawable(getActivity(), GoogleMaterial.Icon.gmd_search).color(Color.WHITE).actionBarSize());
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
fragmentMenuItemSelectedListener.onMenuItemSelected(item.getItemId());
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("unchecked")
private void initialize() {
this.searchParams = (HashMap<String, String>) getArguments().getSerializable(ARGUMENT_SEARCH_PARAMS);
this.postComponent = DaggerPostComponent.builder()
.applicationComponent(getComponent(ApplicationComponent.class))
.activityModule(((BaseActivity) getActivity()).getActivityModule())
.postModule(new PostModule(searchParams))
.build();
this.postComponent.inject(this);
this.postListPresenter.setView(this);
}
private void loadUserList() {
this.postListPresenter.initialize();
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
@Override
public Context getContext() {
return this.getActivity().getApplicationContext();
}
/**
* Methods from the implemented interface PostsListView
*/
@Override
public void renderPostList(Collection<PostModel> postModelCollection) {
if (postModelCollection != null) {
this.postsAdapter.setPostsCollection(postModelCollection);
}
}
@Override
public void viewPostDetail(PostModel postModel) {
if (this.postListListener != null) {
this.postListListener.onPostClicked(postModel);
}
}
@Override
public void showEmptyResultsMessage(){
new MaterialDialog.Builder(getActivity())
.title(R.string.search_fragment_results_empty_dlg_title)
.content(R.string.search_fragment_results_empty_dlg_msg)
.positiveText(android.R.string.ok)
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
getActivity().getSupportFragmentManager().popBackStack();
}
})
.show();
}
@Override
public void showLoading() {
progressDialog = new MaterialDialog.Builder(getActivity())
.title(R.string.please_wait)
.content(R.string.app_post_list_loading_dlg_msg)
.progress(true, 0)
.progressIndeterminateStyle(false)
.show();
}
@Override
public void hideLoading() {
if (progressDialog != null)
progressDialog.dismiss();
}
@Override
public void showRetry() {
new MaterialDialog.Builder(getActivity())
.cancelable(false)
.title(R.string.ups)
.content(R.string.app_post_list_retry_dlg_message)
.positiveText(R.string.retry)
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog materialDialog, @NonNull DialogAction dialogAction) {
loadUserList();
}
})
.show();
}
@Override
public void hideRetry() {
}
@Override
public void showError(String message) {
this.showToastMessage(message);
}
/**
* Synchronize with the fragment lifecycle by calling
* the corresponding presenter methods
*/
@Override
public void onResume() {
super.onResume();
this.postListPresenter.resume();
}
@Override
public void onPause() {
super.onPause();
this.postListPresenter.pause();
}
@Override
public void onDestroy() {
super.onDestroy();
this.postListPresenter.destroy();
}
}
|
package com.psychic_engine.cmput301w17t10.feelsappman;
import android.location.Location;
import java.util.Date;
public class EditMoodController {
static boolean updateMoodEventList(int moodEventPosition, String moodString, String socialSettingString, String trigger, Photograph photo, String location) {
Mood mood = null;
SocialSetting socialSetting;
switch (moodString) { // TODO refactor this - inside MoodState enum class?
case "Sad":
mood = new Mood(MoodState.SAD);
break;
case "Happy":
mood = new Mood(MoodState.HAPPY);
break;
case "Shame":
mood = new Mood(MoodState.SHAME);
break;
case "Fear":
mood = new Mood(MoodState.FEAR);
break;
case "Anger":
mood = new Mood(MoodState.ANGER);
break;
case "Surprised":
mood = new Mood(MoodState.SURPRISED);
break;
case "Disgust":
mood = new Mood(MoodState.DISGUST);
break;
case "Confused":
mood = new Mood(MoodState.CONFUSED);
break;
}
switch (socialSettingString) {
case "Alone":
socialSetting = SocialSetting.ALONE;
break;
case "One Other":
socialSetting = SocialSetting.ONEOTHER;
break;
case "Two To Several":
socialSetting = SocialSetting.TWOTOSEVERAL;
break;
case "Crowd":
socialSetting = SocialSetting.CROWD;
break;
default:
socialSetting = null;
}
MoodEvent moodEvent = new MoodEvent(mood, socialSetting, trigger, photo, null);
// replace old moodEvent with new one
ParticipantSingleton.getInstance().getSelfParticipant().setMoodEvent(moodEventPosition, moodEvent);
return true;
}
}
|
package com.support.android.designlibdemo.activities;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.makeramen.roundedimageview.RoundedTransformationBuilder;
import com.parse.GetDataCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.squareup.picasso.Transformation;
import com.support.android.designlibdemo.R;
import com.support.android.designlibdemo.dialogs.CameraDialog;
import com.support.android.designlibdemo.utils.BitmapScaler;
import org.json.JSONArray;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import io.card.payment.CardIOActivity;
import io.card.payment.CreditCard;
public class UserProfileActivity extends AppCompatActivity {
private static final int MY_SCAN_REQUEST_CODE = 765;
private String creditCardNumber=null;
private String creditCardExperation=null;
private static final int TAKE_PHOTO_CODE = 1;
private static final int PICK_PHOTO_CODE = 2;
private static final int CROP_PHOTO_CODE = 3;
ImageView ivUserProfile, ivUserPic;
TextView userName;
EditText userEmail;
EditText userPhoneNumber;
EditText userSite;
TextView tvCreditCardNumber;
TextView tvCreditCardExperation;
Button btAddCrefirCard;
TextView tv_update_picture;
private Uri photoUri;
private Bitmap photoBitmap;
final int[] selection = new int[1];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Check Internet connection
if (isNetworkAvailable()) {
setContentView(R.layout.activity_user_profile);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ivUserPic = (ImageView) findViewById(R.id.ivProfilePicProfile);
userName = (TextView) findViewById(R.id.tv_userNameDrawer);
userEmail = (EditText) findViewById(R.id.tv_userEmail);
userPhoneNumber = (EditText) findViewById(R.id.tv_userPhone);
userSite = (EditText) findViewById(R.id.tv_userSite);
tvCreditCardNumber = (TextView) findViewById(R.id.tv_cc_number);
tvCreditCardExperation = (TextView) findViewById(R.id.tv_cc_experation);
btAddCrefirCard = (Button) findViewById(R.id.bt_addCreditCard);
tv_update_picture = (TextView) findViewById(R.id.tv_update_picture);
final ParseUser currentUser = ParseUser.getCurrentUser();
//if user has CC attached, then show it and hide ADD CC BUTTON
if (currentUser.getString("creditNumber") != null) {
tvCreditCardNumber.setText(currentUser.getString("creditNumber"));
tvCreditCardExperation.setText(currentUser.getString("creditExpr"));
} else {
btAddCrefirCard.setVisibility(View.VISIBLE);
btAddCrefirCard.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onScanPress();
}
});
}
//making user profile photo oval
Transformation transformation = new RoundedTransformationBuilder()
.borderColor(this.getResources().getColor(R.color.grey_200))
.borderWidthDp(3)
.cornerRadiusDp(100)
.oval(false)
.build();
//setting user profile photo
/* Picasso.with(this)
.load(userProfilePhotoUrl).resize(400, 400)
.transform(transformation)
.into(ivUserProfile);
*/
JSONArray ar = currentUser.getJSONArray("myCampaigns");
int i = 0;
String contributions = ", welcome!" + "\n";
if (ar != null) {
i = ar.length();
}
if (i > 1) {
// ivUserProfile.setImageResource(R.drawable.profileactivist);
contributions = ", you have supported" + "\n" + i + " campaigns. Thank you!";
} else {
// ivUserProfile.setImageResource(R.drawable.iconbaby);
}
//Populate current UserName
Log.i("SumOfUs USER info", currentUser.getUsername());
userName.setText(currentUser.getUsername() + contributions);
userEmail.setText(currentUser.getEmail());
userPhoneNumber.setText(currentUser.getString("phoneNumber"));
userSite.setText(currentUser.getString("webSite"));
userSite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.setFocusable(true);
v.setActivated(true);
}
});
userPhoneNumber.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.setFocusable(true);
v.setActivated(true);
}
});
//Load image from Parse
ParseFile image = (ParseFile) currentUser.getParseFile("profilePicture");
//prevent form crash if omage is null
if (image != null) {
image.getDataInBackground(new GetDataCallback() {
public void done(byte[] data, ParseException e) {
if (e == null) {
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
ivUserPic.setImageBitmap(bmp);
} else {
e.printStackTrace();
}
}
});
}
//Update user profile picture
tv_update_picture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fm = getSupportFragmentManager();
final CameraDialog dialog = CameraDialog.newInstance("Add a new picture:");
dialog.setOnChoiceClickListener(new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
selection[0] = which;
}
});
dialog.setPositiveListener(new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (selection[0] == 0) {
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoUri = Uri.fromFile(getOutputMediaFile()); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); // set the image file name
// Start the image capture intent to take photo
startActivityForResult(intent, TAKE_PHOTO_CODE);
} else {
// Take the user to the gallery app to pick a photo
Intent photoGalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(photoGalleryIntent, PICK_PHOTO_CODE);
}
dialog.dismiss();
}
});
dialog.setCancelClickListener(new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show(fm, "TAG_DIALOG");
}
});
//Update User's profile
userEmail.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
String newEmail = s.toString();
Log.i("SumOfUs USER info", newEmail);
currentUser.setEmail(newEmail);
}
});
//Update User's phone
userPhoneNumber.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
String newPhone = s.toString();
Log.i("SumOfUs USER info", newPhone);
currentUser.put("phoneNumber", newPhone);
}
});
//Update User's Website
userSite.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
String webSite = s.toString();
// currentUser.put("profilePicture", file);
Log.i("SumOfUs USER info", webSite);
currentUser.put("webSite", webSite);
}
});
currentUser.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
// myObjectSavedSuccessfully();
Log.i("SumOfUs USER info", "Saveeee");
} else {
//myObjectSaveDidNotSucceed();
Log.i("SumOfUs USER info", "myObjectSaveDidNotSucceed");
}
}
});
}
else {
Toast.makeText(this, "Internet NOT Connected, please turn on your Internet" , Toast.LENGTH_SHORT).show();
}
}
//this is to create picture filename
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "sumofus");
if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()) {
return null;
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
File mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");
return mediaFile;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_user_profile, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if(id == android.R.id.home) {
NavUtils.navigateUpFromSameTask(this);
overridePendingTransition(R.anim.out_slide_in_left, R.anim.out_slide_out_right);
return true;
}
//noinspection SimplifiableIfStatement
if (id == R.id.logout) {
//return true;
LogOut();
}
return super.onOptionsItemSelected(item);
}
public void LogOut() {
ParseUser.logOut();
Intent intent = new Intent(UserProfileActivity.this, DispatchActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
public void onScanPress() {
Intent scanIntent = new Intent(this, CardIOActivity.class);
// customize these values to suit your needs.
scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_EXPIRY, true); // default: false
scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_CVV, false); // default: false
scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_POSTAL_CODE, false); // default: false
// hides the manual entry button
// if set, developers should provide their own manual entry mechanism in the app
scanIntent.putExtra(CardIOActivity.EXTRA_SUPPRESS_MANUAL_ENTRY, false); // default: false
// matches the theme of your application
scanIntent.putExtra(CardIOActivity.EXTRA_KEEP_APPLICATION_THEME, false); // default: false
// MY_SCAN_REQUEST_CODE is arbitrary and is only used within this activity.
startActivityForResult(scanIntent, MY_SCAN_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == TAKE_PHOTO_CODE) {
photoBitmap = BitmapFactory.decodeFile(photoUri.getPath());
Bitmap resizedImage = BitmapScaler.scaleToFitWidth(photoBitmap, 300);
ivUserPic.getAdjustViewBounds();
ivUserPic.setScaleType(ImageView.ScaleType.FIT_XY);
//ivUserPic.setImageResource(currentUser.getString("zipcode"));
|
package cz.uruba.ets2mpcompanion.preferences;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.GradientDrawable;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import butterknife.Bind;
import butterknife.ButterKnife;
import cz.uruba.ets2mpcompanion.R;
import cz.uruba.ets2mpcompanion.utils.UICompat;
import cz.uruba.ets2mpcompanion.views.viewgroups.RowedLayout;
public class FormattedEditTextPreference extends DialogPreference {
private ArrayList<CharSequence> formatStrings;
@Bind(R.id.edit_text) EditText editText;
@Bind(R.id.container_insert_format_string_buttons) RowedLayout containerButtons;
private String text;
public FormattedEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.formated_edit_text_preference);
try {
CharSequence[] entries = typedArray.getTextArray(R.styleable.formated_edit_text_preference_android_entries);
if (entries != null && entries.length > 0) {
formatStrings = new ArrayList<>(Arrays.asList(entries));
}
} finally {
typedArray.recycle();
}
}
public FormattedEditTextPreference(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FormattedEditTextPreference(Context context) {
this(context, null);
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
persistString(text);
}
@Override
protected View onCreateDialogView() {
View view = View.inflate(getContext(), R.layout.dialog_formatted_edit_text_preference, null);
ButterKnife.bind(this, view);
int themeColor = UICompat.getThemeColour(R.attr.colorPrimary, getContext());
for (CharSequence formatString : formatStrings) {
TextView textView = new TextView(getContext());
textView.setText(formatString);
GradientDrawable backgroundDrawable = (GradientDrawable) getContext().getResources().getDrawable(R.drawable.bckg_rounded_corners);
if (backgroundDrawable != null) {
backgroundDrawable.setColor(themeColor);
}
textView.setTextColor(getContext().getResources().getColor(android.R.color.white));
textView.setBackground(backgroundDrawable);
containerButtons.addView(textView, ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
return view;
}
@Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
editText.setText(getText());
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
String value = editText.getText().toString().trim();
if (callChangeListener(value)) {
setText(value);
}
}
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
setText(restoreValue ? getPersistedString(text) : (String) defaultValue);
}
@Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
if (isPersistent()) {
// No need to save instance state since it's persistent
return superState;
}
final SavedState myState = new SavedState(superState);
myState.text = getText();
return myState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state == null || !state.getClass().equals(SavedState.class)) {
// Didn't save state for us in onSaveInstanceState
super.onRestoreInstanceState(state);
return;
}
SavedState myState = (SavedState) state;
super.onRestoreInstanceState(myState.getSuperState());
setText(myState.text);
}
private static class SavedState extends BaseSavedState {
String text;
public SavedState(Parcel source) {
super(source);
text = source.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(text);
}
public SavedState(Parcelable superState) {
super(superState);
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
|
package im.tny.segvault.disturbances.ui.fragment.top;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.TextAppearanceSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TableRow;
import android.widget.TextView;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import com.squareup.picasso.Transformation;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import im.tny.segvault.disturbances.API;
import im.tny.segvault.disturbances.Application;
import im.tny.segvault.disturbances.CacheManager;
import im.tny.segvault.disturbances.Connectivity;
import im.tny.segvault.disturbances.Coordinator;
import im.tny.segvault.disturbances.MainService;
import im.tny.segvault.disturbances.MapManager;
import im.tny.segvault.disturbances.R;
import im.tny.segvault.disturbances.Util;
import im.tny.segvault.disturbances.exception.APIException;
import im.tny.segvault.disturbances.ui.util.SimpleDividerItemDecoration;
import im.tny.segvault.disturbances.ui.activity.StatsActivity;
import im.tny.segvault.disturbances.ui.adapter.TripRecyclerViewAdapter;
import im.tny.segvault.disturbances.model.Trip;
import im.tny.segvault.disturbances.ui.activity.MainActivity;
import im.tny.segvault.disturbances.ui.fragment.TopFragment;
import im.tny.segvault.subway.Network;
import io.realm.Realm;
/**
* A fragment representing a list of Items.
* <p/>
* Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
* interface.
*/
public class TripHistoryFragment extends TopFragment {
private static final String ARG_COLUMN_COUNT = "column-count";
private int mColumnCount = 1;
private OnListFragmentInteractionListener mListener;
private RecyclerView recyclerView = null;
private TextView emptyView;
private TextView tripCountView;
private TextView tripTotalLengthView;
private TextView tripTotalTimeView;
private TextView tripAverageSpeedView;
private TableRow posPlayLoadingRow;
private TableRow posPlayRow1;
private TableRow posPlayRow2;
private ImageView posPlayAvatarView;
private TextView posPlayUserView;
private TextView posPlayLevelView;
private ProgressBar posPlayLevelProgress;
private TextView posPlayNextLevelView;
private TextView posPlayOverallView;
private TextView posPlayWeekView;
private boolean showVisits = false;
private Menu menu;
private Realm realm = Application.getDefaultRealmInstance(getContext());
/**
* Mandatory constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public TripHistoryFragment() {
}
@Override
public boolean needsTopology() {
return true;
}
@Override
public int getNavDrawerId() {
return R.id.nav_trip_history;
}
@Override
public String getNavDrawerIdAsString() {
return "nav_trip_history";
}
@SuppressWarnings("unused")
public static TripHistoryFragment newInstance(int columnCount) {
TripHistoryFragment fragment = new TripHistoryFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setUpActivity(getString(R.string.frag_trip_history_title), false, false);
setHasOptionsMenu(true);
View view = inflater.inflate(R.layout.fragment_trip_history_list, container, false);
// Set the adapter
Context context = view.getContext();
emptyView = view.findViewById(R.id.no_trips_view);
tripCountView = view.findViewById(R.id.trip_count_view);
tripTotalLengthView = view.findViewById(R.id.trip_total_length_view);
tripTotalTimeView = view.findViewById(R.id.trip_total_time_view);
tripAverageSpeedView = view.findViewById(R.id.trip_average_speed_view);
posPlayLoadingRow = view.findViewById(R.id.posplay_loading_row);
posPlayRow1 = view.findViewById(R.id.posplay_row1);
posPlayRow2 = view.findViewById(R.id.posplay_row2);
posPlayAvatarView = view.findViewById(R.id.posplay_avatar_view);
posPlayUserView = view.findViewById(R.id.posplay_user_view);
posPlayLevelView = view.findViewById(R.id.posplay_level_view);
posPlayLevelProgress = view.findViewById(R.id.posplay_level_progress);
posPlayNextLevelView = view.findViewById(R.id.posplay_next_level_view);
posPlayOverallView = view.findViewById(R.id.posplay_overall_view);
posPlayWeekView = view.findViewById(R.id.posplay_week_view);
Drawable progressDrawable = posPlayLevelProgress.getProgressDrawable().mutate();
progressDrawable.setColorFilter(Color.parseColor("#0078E7"), android.graphics.PorterDuff.Mode.SRC_IN);
posPlayLevelProgress.setProgressDrawable(progressDrawable);
posPlayRow1.setOnClickListener(view1 -> {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.posplay_website)));
startActivity(browserIntent);
});
recyclerView = view.findViewById(R.id.list);
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(context));
// fix scroll fling. less than ideal, but apparently there's still no other solution
recyclerView.setNestedScrollingEnabled(false);
view.findViewById(R.id.stats_button).setOnClickListener(v -> {
Intent intent = new Intent(getContext(), StatsActivity.class);
startActivity(intent);
});
IntentFilter filter = new IntentFilter();
filter.addAction(MainActivity.ACTION_MAIN_SERVICE_BOUND);
filter.addAction(MapManager.ACTION_UPDATE_TOPOLOGY_FINISHED);
filter.addAction(MainService.ACTION_TRIP_REALM_UPDATED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(context);
bm.registerReceiver(mBroadcastReceiver, filter);
new TripHistoryFragment.UpdateDataTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.trip_history, menu);
if (showVisits) {
menu.findItem(R.id.menu_show_visits).setVisible(false);
} else {
menu.findItem(R.id.menu_hide_visits).setVisible(false);
}
this.menu = menu;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_show_visits:
showVisits = true;
item.setVisible(false);
menu.findItem(R.id.menu_hide_visits).setVisible(true);
new TripHistoryFragment.UpdateDataTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return true;
case R.id.menu_hide_visits:
showVisits = false;
item.setVisible(false);
menu.findItem(R.id.menu_show_visits).setVisible(true);
new TripHistoryFragment.UpdateDataTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
realm.close();
mListener = null;
}
private class UpdateDataTask extends AsyncTask<Void, Integer, Boolean> {
private List<TripRecyclerViewAdapter.TripItem> items = new ArrayList<>();
private int tripCount = 0;
private int tripTotalLength = 0;
private int tripTotalTimeableLength = 0;
private long tripTotalTime = 0;
private long tripTotalMovementTime = 0;
@Override
protected void onPreExecute() {
super.onPreExecute();
getSwipeRefreshLayout().setRefreshing(true);
}
protected Boolean doInBackground(Void... v) {
while (mListener == null || mListener.getMainService() == null) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
Collection<Network> networks = Coordinator.get(getContext()).getMapManager().getNetworks();
Realm realm = Application.getDefaultRealmInstance(getContext());
for (Trip t : realm.where(Trip.class).findAll()) {
TripRecyclerViewAdapter.TripItem item = new TripRecyclerViewAdapter.TripItem(t, networks);
if (!item.isVisit) {
tripCount++;
tripTotalLength += item.length;
tripTotalTimeableLength += item.timeableLength;
tripTotalTime += item.destTime.getTime() - item.originTime.getTime();
tripTotalMovementTime += item.movementMilliseconds;
}
if (showVisits || !item.isVisit) {
items.add(item);
}
}
realm.close();
if (items.size() == 0) {
return false;
}
Collections.sort(items, Collections.<TripRecyclerViewAdapter.TripItem>reverseOrder((tripItem, t1) -> Long.valueOf(tripItem.originTime.getTime()).compareTo(Long.valueOf(t1.originTime.getTime()))));
return true;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Boolean result) {
if (!isAdded()) {
// prevent onPostExecute from doing anything if no longer attached to an activity
return;
}
tripCountView.setText(String.format("%d", tripCount));
tripTotalLengthView.setText(String.format(getString(R.string.frag_trip_history_length_value), (double) tripTotalLength / 1000f));
long days = tripTotalTime / TimeUnit.DAYS.toMillis(1);
long hours = (tripTotalTime % TimeUnit.DAYS.toMillis(1)) / TimeUnit.HOURS.toMillis(1);
long minutes = (tripTotalTime % TimeUnit.HOURS.toMillis(1)) / TimeUnit.MINUTES.toMillis(1);
if (days == 0) {
tripTotalTimeView.setText(String.format(getString(R.string.frag_trip_history_duration_no_days), hours, minutes));
} else {
tripTotalTimeView.setText(String.format(getString(R.string.frag_trip_history_duration_with_days), days, hours, minutes));
}
tripAverageSpeedView.setText("
if (recyclerView != null && mListener != null) {
recyclerView.setAdapter(new TripRecyclerViewAdapter(items, mListener));
recyclerView.invalidate();
if (result) {
emptyView.setVisibility(View.GONE);
if (tripTotalMovementTime > 0) {
tripAverageSpeedView.setText(String.format(getString(R.string.frag_trip_history_speed_value),
((double) tripTotalTimeableLength / (double) (tripTotalMovementTime / 1000)) * 3.6));
}
} else {
emptyView.setVisibility(View.VISIBLE);
}
} else {
emptyView.setVisibility(View.VISIBLE);
}
new UpdatePosPlayTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
getSwipeRefreshLayout().setRefreshing(false);
}
}
private final static String POSPLAY_CACHE_KEY = "PosPlayStatus";
@JsonIgnoreProperties(ignoreUnknown = true)
private static class PosPlayStatus implements Serializable {
public String serviceName;
public long discordID;
public String username;
public String avatarURL;
public int level;
public float levelProgress;
public int xp;
public int xpThisWeek;
public int rank;
public int rankThisWeek;
}
private class UpdatePosPlayTask extends AsyncTask<Void, Void, Boolean> {
private PosPlayStatus status;
@Override
protected void onPreExecute() {
super.onPreExecute();
posPlayLoadingRow.setVisibility(View.VISIBLE);
}
@Override
protected Boolean doInBackground(Void... voids) {
CacheManager cm = Coordinator.get(getContext()).getCacheManager();
status = cm.fetchOrGet(POSPLAY_CACHE_KEY, (key, storeDate) -> false, key -> {
try {
List<API.PairConnection> connections = API.getInstance().getPairConnections();
for (API.PairConnection connection : connections) {
if (connection.service.equals("posplay")) {
PosPlayStatus status = API.getInstance().getMapper().convertValue(connection.extra, PosPlayStatus.class);
if (status != null) {
status.serviceName = connection.serviceName;
}
return status;
}
}
// if we got here, there's no PosPlay connection (device may have been unpaired)
// so delete key to ensure we don't show PosPlay info anymore
cm.remove(POSPLAY_CACHE_KEY);
} catch (IllegalArgumentException e) { // convertValue throws
return null;
} catch (APIException e) {
return null;
}
return null;
}, PosPlayStatus.class);
return status != null;
}
protected void onPostExecute(Boolean result) {
posPlayLoadingRow.setVisibility(View.GONE);
if (result) {
posPlayRow1.setVisibility(View.VISIBLE);
posPlayRow2.setVisibility(View.VISIBLE);
String userLine = String.format(getString(R.string.frag_trip_history_posplay_username), status.username, status.serviceName);
int nStart = userLine.indexOf(status.username);
int nEnd = nStart + status.username.length();
SpannableString userSpannable = new SpannableString(userLine);
userSpannable.setSpan(new StyleSpan(Typeface.BOLD), nStart, nEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
posPlayUserView.setText(userSpannable);
String levelAlone = String.format("%d", status.level);
String levelLine = String.format(getString(R.string.frag_trip_history_posplay_level), status.level);
int lStart = levelLine.indexOf(levelAlone);
int lEnd = lStart + levelAlone.length();
SpannableString levelSpannable = new SpannableString(levelLine);
levelSpannable.setSpan(new StyleSpan(Typeface.BOLD), lStart, lEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
posPlayLevelView.setText(levelSpannable);
posPlayLevelProgress.setProgress(Math.round(status.levelProgress));
posPlayNextLevelView.setText(String.format("%d", status.level + 1));
// all-time info
String placeLine;
if (status.rank == 0) {
placeLine = getString(R.string.frag_trip_history_posplay_no_participation);
} else if (Util.getCurrentLanguage(getContext()).equals("en")) {
placeLine = String.format(getString(R.string.frag_trip_history_posplay_xp_place_english),
status.xp, status.rank, Util.getOrdinalSuffix(status.rank));
} else {
placeLine = String.format(getString(R.string.frag_trip_history_posplay_xp_place), status.xp, status.rank);
}
Spannable placeSpannable = new SpannableString(placeLine);
if (status.rank == 1) {
placeSpannable.setSpan(new ForegroundColorSpan(Color.parseColor("#DAA520")), placeLine.indexOf("\n"), placeLine.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
posPlayOverallView.setText(placeSpannable);
// week info
if (status.rankThisWeek == 0) {
placeLine = getString(R.string.frag_trip_history_posplay_no_participation);
} else if (Util.getCurrentLanguage(getContext()).equals("en")) {
placeLine = String.format(getString(R.string.frag_trip_history_posplay_xp_place_english),
status.xpThisWeek, status.rankThisWeek, Util.getOrdinalSuffix(status.rankThisWeek));
} else {
placeLine = String.format(getString(R.string.frag_trip_history_posplay_xp_place), status.xpThisWeek, status.rankThisWeek);
}
placeSpannable = new SpannableString(placeLine);
if (status.rankThisWeek == 1) {
placeSpannable.setSpan(new ForegroundColorSpan(Color.parseColor("#DAA520")), placeLine.indexOf("\n"), placeLine.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
posPlayWeekView.setText(placeSpannable);
RequestCreator rc = Picasso.get().load(status.avatarURL);
if (!Connectivity.isConnectedWifi(getContext())) {
rc.networkPolicy(NetworkPolicy.OFFLINE);
}
rc.transform(new CircleTransform()).into(posPlayAvatarView);
} else {
posPlayRow1.setVisibility(View.GONE);
posPlayRow2.setVisibility(View.GONE);
}
}
}
public class CircleTransform implements Transformation {
@Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
if (squaredBitmap != source) {
source.recycle();
}
Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader = new BitmapShader(squaredBitmap,
BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
paint.setShader(shader);
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
squaredBitmap.recycle();
return bitmap;
}
@Override
public String key() {
return "circle";
}
}
public interface OnListFragmentInteractionListener extends OnInteractionListener, TripRecyclerViewAdapter.OnListFragmentInteractionListener {
}
private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case MainActivity.ACTION_MAIN_SERVICE_BOUND:
case MapManager.ACTION_UPDATE_TOPOLOGY_FINISHED:
case MainService.ACTION_TRIP_REALM_UPDATED:
if (getActivity() != null) {
new UpdateDataTask().execute();
}
break;
}
}
};
}
|
package info.nightscout.androidaps.plugins.Insulin;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
public abstract class InsulinOrefBasePlugin implements PluginBase, InsulinInterface {
public static double MIN_DIA = 5;
long lastWarned = 0;
@Override
public int getType() {
return INSULIN;
}
@Override
public String getNameShort() {
return MainApp.sResources.getString(R.string.insulin_shortname);
}
@Override
public boolean canBeHidden(int type) {
return true;
}
@Override
public boolean hasFragment() {
return true;
}
@Override
public boolean showInList(int type) {
return true;
}
@Override
public double getDia() {
double dia = getUserDefinedDia();
if(dia >= MIN_DIA){
return dia;
} else {
if((System.currentTimeMillis() - lastWarned) > 60*1000) {
lastWarned = System.currentTimeMillis();
Notification notification = new Notification(Notification.SHORT_DIA, String.format(MainApp.sResources.getString(R.string.dia_too_short), dia, MIN_DIA), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
}
return MIN_DIA;
}
}
public double getUserDefinedDia() {
return MainApp.getConfigBuilder().getProfile() != null ? MainApp.getConfigBuilder().getProfile().getDia() : MIN_DIA;
}
@Override
public Iob iobCalcForTreatment(Treatment treatment, long time, Double dia) {
Iob result = new Iob();
int peak = getPeak();
if (treatment.insulin != 0d) {
long bolusTime = treatment.date;
double t = (time - bolusTime) / 1000d / 60d;
double td = getDia()*60; //getDIA() always > 5
double tp = peak;
// force the IOB to 0 if over DIA hours have passed
if (t < td) {
double tau = tp * (1 - tp / td) / (1 - 2 * tp / td);
double a = 2 * tau / td;
double S = 1 / (1 - a + (1 + a) * Math.exp(-td / tau));
result.activityContrib = treatment.insulin * (S / Math.pow(tau, 2)) * t * (1 - t / td) * Math.exp(-t / tau);
result.iobContrib = treatment.insulin * (1 - S * (1 - a) * ((Math.pow(t, 2) / (tau * td * (1 - a)) - t / tau - 1) * Math.exp(-t / tau) + 1));
}
}
return result;
}
@Override
public String getComment() {
String comment = commentStandardText();
double userDia = getUserDefinedDia();
if(userDia < MIN_DIA){
comment += "\n" + String.format(MainApp.sResources.getString(R.string.dia_too_short), userDia, MIN_DIA);
}
return comment;
}
abstract int getPeak();
abstract String commentStandardText();
}
|
package im.actor.messenger.app.fragment.chat;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.ActionBar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import im.actor.messenger.BuildConfig;
import im.actor.messenger.R;
import im.actor.messenger.app.AppContext;
import im.actor.messenger.app.Intents;
import im.actor.messenger.app.base.BaseActivity;
import im.actor.messenger.app.emoji.SmileProcessor;
import im.actor.messenger.app.keyboard.emoji.EmojiKeyboard;
import im.actor.messenger.app.keyboard.KeyboardStatusListener;
import im.actor.messenger.app.keyboard.emoji.stickers.OnStickerClickListener;
import im.actor.messenger.app.util.RandomUtil;
import im.actor.messenger.app.util.Screen;
import im.actor.messenger.app.util.io.IOUtils;
import im.actor.messenger.app.view.AvatarView;
import im.actor.messenger.app.view.KeyboardHelper;
import im.actor.messenger.app.view.TintImageView;
import im.actor.messenger.app.view.TypingDrawable;
import im.actor.model.Messenger;
import im.actor.model.entity.Peer;
import im.actor.model.entity.PeerType;
import im.actor.model.mvvm.ValueChangedListener;
import im.actor.model.mvvm.ValueModel;
import im.actor.model.viewmodel.GroupVM;
import im.actor.model.viewmodel.UserVM;
import static im.actor.messenger.app.Core.getStickerProcessor;
import static im.actor.messenger.app.Core.groups;
import static im.actor.messenger.app.Core.messenger;
import static im.actor.messenger.app.Core.users;
import static im.actor.messenger.app.emoji.SmileProcessor.emoji;
public class ChatActivity extends BaseActivity {
private static final int REQUEST_GALLERY = 0;
private static final int REQUEST_PHOTO = 1;
private static final int REQUEST_VIDEO = 2;
private static final int REQUEST_DOC = 3;
private static final int REQUEST_LOCATION = 4;
private Peer peer;
private Messenger messenger;
private EditText messageBody;
private TintImageView sendButton;
private ImageButton attachButton;
private View kicked;
// Action bar
private View barView;
private AvatarView barAvatar;
private TextView barTitle;
private View barSubtitleContainer;
private TextView barSubtitle;
private View barTypingContainer;
private ImageView barTypingIcon;
private TextView barTyping;
private String fileName;
private KeyboardHelper keyboardUtils;
private boolean isTypingDisabled = false;
private boolean isCompose = false;
private EmojiKeyboard emojiKeyboard;
@Override
public void onCreate(Bundle saveInstance) {
super.onCreate(saveInstance);
keyboardUtils = new KeyboardHelper(this);
peer = Peer.fromUniqueId(getIntent().getExtras().getLong(Intents.EXTRA_CHAT_PEER));
isCompose = saveInstance == null && getIntent().getExtras().getBoolean(Intents.EXTRA_CHAT_COMPOSE, false);
messenger = messenger();
// Init action bar
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayUseLogoEnabled(false);
// Action bar header
barView = LayoutInflater.from(this).inflate(R.layout.bar_conversation, null);
barTitle = (TextView) barView.findViewById(R.id.title);
barSubtitleContainer = barView.findViewById(R.id.subtitleContainer);
barTypingIcon = (ImageView) barView.findViewById(R.id.typingImage);
barTypingIcon.setImageDrawable(new TypingDrawable());
barTyping = (TextView) barView.findViewById(R.id.typing);
barSubtitle = (TextView) barView.findViewById(R.id.subtitle);
barTypingContainer = barView.findViewById(R.id.typingContainer);
barTypingContainer.setVisibility(View.INVISIBLE);
barAvatar = (AvatarView) barView.findViewById(R.id.avatarPreview);
barAvatar.init(Screen.dp(32), 18);
ActionBar.LayoutParams layout = new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
getSupportActionBar().setCustomView(barView, layout);
barView.findViewById(R.id.titleContainer).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (peer.getPeerType() == PeerType.PRIVATE) {
startActivity(Intents.openProfile(peer.getPeerId(), ChatActivity.this));
} else if (peer.getPeerType() == PeerType.GROUP) {
startActivity(Intents.openGroup(peer.getPeerId(), ChatActivity.this));
} else {
// Nothing to do
}
}
});
// Init view
setContentView(R.layout.activity_dialog);
getWindow().setBackgroundDrawable(null);
if (saveInstance == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.messagesFragment, MessagesFragment.create(peer))
.commit();
}
messageBody = (EditText) findViewById(R.id.et_message);
messageBody.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (after > count && !isTypingDisabled) {
messenger.onTyping(peer);
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() > 0) {
sendButton.setTint(getResources().getColor(R.color.conv_send_enabled));
sendButton.setEnabled(true);
} else {
sendButton.setTint(getResources().getColor(R.color.conv_send_disabled));
sendButton.setEnabled(false);
}
}
});
messageBody.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int keycode, KeyEvent keyEvent) {
if (messenger().isSendByEnterEnabled()) {
if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && keycode == KeyEvent.KEYCODE_ENTER) {
sendMessage();
return true;
}
}
return false;
}
});
messageBody.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_SEND) {
sendMessage();
return true;
}
if (i == EditorInfo.IME_ACTION_DONE) {
sendMessage();
return true;
}
if (messenger().isSendByEnterEnabled()) {
if (keyEvent != null && i == EditorInfo.IME_NULL && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
sendMessage();
return true;
}
}
return false;
}
});
kicked = findViewById(R.id.kickedFromChat);
sendButton = (TintImageView) findViewById(R.id.ib_send);
sendButton.setResource(R.drawable.conv_send);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage();
}
});
attachButton = (ImageButton) findViewById(R.id.ib_attach);
attachButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Context wrapper = new ContextThemeWrapper(ChatActivity.this, R.style.AttachPopupTheme);
PopupMenu popup = new PopupMenu(wrapper, findViewById(R.id.attachAnchor));
try {
Field[] fields = popup.getClass().getDeclaredFields();
for (Field field : fields) {
if ("mPopup".equals(field.getName())) {
field.setAccessible(true);
Object menuPopupHelper = field.get(popup);
Class<?> classPopupHelper = Class.forName(menuPopupHelper
.getClass().getName());
Method setForceIcons = classPopupHelper.getMethod(
"setForceShowIcon", boolean.class);
setForceIcons.invoke(menuPopupHelper, true);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (BuildConfig.IS_CHROME_BUILD) {
popup.getMenuInflater().inflate(R.menu.attach_popup_chrome, popup.getMenu());
} else {
popup.getMenuInflater().inflate(R.menu.attach_popup, popup.getMenu());
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.gallery) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
|
package gr.sperfect.djuqbox.webapp.shared.data;
public class User extends BaseDataClass {
public User() {
// json needed
}
public User(String aName) {
super("User "+ aName);
}
//test git
}
|
package org.jboss.as.arquillian.service;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.management.MBeanServer;
import org.jboss.arquillian.protocol.jmx.JMXTestRunner;
import org.jboss.arquillian.protocol.jmx.JMXTestRunner.TestClassLoader;
import org.jboss.arquillian.spi.TestEnricher;
import org.jboss.arquillian.spi.TestResult;
import org.jboss.arquillian.spi.util.ServiceLoader;
import org.jboss.arquillian.testenricher.msc.ServiceContainerInjector;
import org.jboss.arquillian.testenricher.osgi.BundleAssociation;
import org.jboss.arquillian.testenricher.osgi.BundleContextAssociation;
import org.jboss.as.ee.naming.NamespaceSelectorService;
import org.jboss.as.jmx.MBeanServerService;
import org.jboss.as.osgi.deployment.OSGiDeploymentAttachment;
import org.jboss.as.osgi.service.BundleContextService;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.logging.Logger;
import org.jboss.modules.Module;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.jboss.osgi.deployment.deployer.Deployment;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
/**
* Service responsible for creating and managing the life-cycle of the Arquillian service.
*
* @author Thomas.Diesler@jboss.com
* @author Kabir Khan
* @since 17-Nov-2010
*/
public class ArquillianService implements Service<ArquillianService> {
public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("arquillian", "testrunner");
private static final Logger log = Logger.getLogger("org.jboss.as.arquillian");
private final InjectedValue<MBeanServer> injectedMBeanServer = new InjectedValue<MBeanServer>();
private ServiceContainer serviceContainer;
private final Map<String, ArquillianConfig> deployedTests = new HashMap<String, ArquillianConfig>();
private final Map<String, CountDownLatch> waitingTests = new HashMap<String, CountDownLatch>();
private JMXTestRunner jmxTestRunner;
public static void addService(final ServiceTarget serviceTarget) {
ArquillianService service = new ArquillianService();
ServiceBuilder<?> serviceBuilder = serviceTarget.addService(ArquillianService.SERVICE_NAME, service);
serviceBuilder.addDependency(MBeanServerService.SERVICE_NAME, MBeanServer.class, service.injectedMBeanServer);
serviceBuilder.install();
}
public synchronized void start(StartContext context) throws StartException {
log.debugf("Starting Arquillian Test Runner");
final MBeanServer mbeanServer = injectedMBeanServer.getValue();
final TestClassLoader testClassLoader = new TestClassLoaderImpl();
// Inject the ServiceContainer in the enrichers
serviceContainer = context.getController().getServiceContainer();
ServiceLoader<TestEnricher> loader = ServiceLoader.load(TestEnricher.class, testClassLoader.getServiceClassLoader());
for (TestEnricher enricher : loader.getProviders()) {
if (enricher instanceof ServiceContainerInjector)
((ServiceContainerInjector) enricher).inject(serviceContainer);
}
try {
jmxTestRunner = new JMXTestRunner() {
@Override
public TestResult runTestMethod(String className, String methodName, Map<String, String> props) {
NamespaceSelectorService namespaceSelectorService = null;
try {
// attempt to set up the JNDI contexts
ArquillianConfig config = getConfig(className);
if (config != null) {
ServiceName NamespaceContextSelectorServiceName = config.getDeploymentUnitContext()
.getServiceName().append(NamespaceSelectorService.NAME);
ServiceController<?> serviceController = serviceContainer
.getService(NamespaceContextSelectorServiceName);
if (serviceController != null) {
namespaceSelectorService = (NamespaceSelectorService) serviceController.getValue();
namespaceSelectorService.activate();
}
}
return super.runTestMethod(className, methodName, props);
} finally {
if (namespaceSelectorService != null) {
namespaceSelectorService.deactivate();
}
}
}
@Override
protected TestClassLoader getTestClassLoader() {
return testClassLoader;
}
};
jmxTestRunner.registerMBean(mbeanServer);
} catch (Throwable t) {
throw new StartException("Failed to start Arquillian Test Runner", t);
}
}
public synchronized void stop(StopContext context) {
log.debugf("Stopping Arquillian Test Runner");
try {
if (jmxTestRunner != null) {
jmxTestRunner.unregisterMBean(injectedMBeanServer.getValue());
}
} catch (Exception ex) {
log.errorf(ex, "Cannot stop Arquillian Test Runner");
}
}
@Override
public ArquillianService getValue() throws IllegalStateException {
return this;
}
void registerDeployment(ArquillianConfig arqConfig) {
synchronized (deployedTests) {
for (String className : arqConfig.getTestClasses()) {
deployedTests.put(className, arqConfig);
CountDownLatch latch = waitingTests.remove(className);
if (latch != null) {
latch.countDown();
}
}
}
}
void unregisterDeployment(ArquillianConfig arqConfig) {
synchronized (deployedTests) {
for (String className : arqConfig.getTestClasses()) {
deployedTests.remove(className);
}
}
}
private ArquillianConfig getConfig(String className) {
CountDownLatch latch = null;
synchronized (deployedTests) {
ArquillianConfig config = deployedTests.get(className);
if (config != null) {
return config;
}
latch = new CountDownLatch(1);
waitingTests.put(className, latch);
}
long end = System.currentTimeMillis() + 3000;
while (true) {
try {
latch.await(end - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
break;
} catch (InterruptedException e) {
}
}
synchronized (deployedTests) {
waitingTests.remove(className);
return deployedTests.get(className);
}
}
class TestClassLoaderImpl implements JMXTestRunner.TestClassLoader {
@Override
public Class<?> loadTestClass(String className) throws ClassNotFoundException {
ArquillianConfig arqConfig = getConfig(className);
if (arqConfig != null) {
if (arqConfig.getTestClasses().contains(className)) {
DeploymentUnit depunit = arqConfig.getDeploymentUnitContext();
Module module = depunit.getAttachment(Attachments.MODULE);
Deployment osgidep = OSGiDeploymentAttachment.getDeployment(depunit);
if (module != null && osgidep != null)
throw new IllegalStateException("Found MODULE attachment for Bundle deployment: " + depunit);
if (module != null)
return module.getClassLoader().loadClass(className);
if (osgidep != null) {
Bundle bundle = osgidep.getAttachment(Bundle.class);
BundleAssociation.setBundle(bundle);
BundleContext sysContext = getSystemBundleContext();
BundleContextAssociation.setBundleContext(sysContext);
return bundle.loadClass(className);
}
}
}
throw new ClassNotFoundException(className);
}
@Override
public ClassLoader getServiceClassLoader() {
return ArquillianService.class.getClassLoader();
}
private BundleContext getSystemBundleContext() {
ServiceController<?> controller = serviceContainer.getService(BundleContextService.SERVICE_NAME);
return (BundleContext) (controller != null ? controller.getValue() : null);
}
}
}
|
package com.chequer.axboot.admin.domain.program;
import com.chequer.axboot.admin.domain.BaseService;
import com.chequer.axboot.admin.domain.user.auth.menu.AuthGroupMenu;
import com.chequer.axboot.admin.domain.user.auth.menu.AuthGroupMenuService;
import com.chequer.axboot.core.parameter.RequestParams;
import com.chequer.axboot.core.utils.TemplateUtils;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAUpdateClause;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import java.util.List;
@Service
public class ProgramService extends BaseService<Program, String> {
private ProgramRepository programRepository;
@Inject
private AuthGroupMenuService authGroupMenuService;
@Inject
public ProgramService(ProgramRepository programRepository) {
super(programRepository);
this.programRepository = programRepository;
}
public List<Program> get(RequestParams<Program> requestParams) {
String filter = requestParams.getFilter();
BooleanBuilder builder = new BooleanBuilder();
List list = select().from(qProgram).where(builder).orderBy(qProgram.progNm.asc()).fetch();
if (isNotEmpty(filter)) {
list = filter(list, filter);
}
return list;
}
@Transactional
public void saveProgram(List<Program> programs) {
for (Program program : programs) {
if (program.isDeleted()) {
List<Long> menuIds = select().select(qMenu.menuId).distinct().from(qMenu).where(qMenu.progCd.eq(program.getProgCd())).fetch();
delete(qAuthGroupMenu).where(qAuthGroupMenu.menuId.in(menuIds)).execute();
update(qMenu).setNull(qMenu.progCd).where(qMenu.progCd.eq(program.getProgCd())).execute();
delete(program.getId());
}
else {
TemplateUtils.makeJspAndJsFiles(program.getProgPh());
if (isEmpty(program.getProgCd())) {
program.setProgCd(FilenameUtils.getBaseName(program.getProgPh()));
save(program);
} else {
List<Long> menuIds = select().select(qMenu.menuId).distinct().from(qMenu).where(qMenu.progCd.eq(program.getProgCd())).fetch();
List<AuthGroupMenu> authGroupMenuList = select().select(qAuthGroupMenu).from(qAuthGroupMenu).where(qAuthGroupMenu.menuId.in(menuIds)).fetch();
// (Y -> N )
if (isNotEmpty(authGroupMenuList)) {
for (AuthGroupMenu authGroupMenu : authGroupMenuList) {
authGroupMenu.updateAuthorization(program);
authGroupMenuService.save(authGroupMenu);
}
}
Program existProgram = findOne(program.getId());
if (notEquals(existProgram.getProgPh(), program.getProgPh())) {
program.setProgCd(FilenameUtils.getBaseName(program.getProgPh()));
delete(existProgram.getId());
new JPAUpdateClause(em, qMenu)
.set(qMenu.progCd, program.getProgCd())
.where(qMenu.progCd.eq(existProgram.getProgCd()))
.execute();
}
save(program);
}
}
}
}
}
|
package com.axelor.apps.message.web;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.axelor.apps.base.db.Wizard;
import com.axelor.apps.message.db.Message;
import com.axelor.apps.message.db.Template;
import com.axelor.apps.message.db.repo.MessageRepository;
import com.axelor.apps.message.db.repo.TemplateRepository;
import com.axelor.apps.message.exception.IExceptionMessage;
import com.axelor.apps.message.service.MessageService;
import com.axelor.apps.message.service.TemplateMessageService;
import com.axelor.db.Model;
import com.axelor.db.Query;
import com.axelor.exception.AxelorException;
import com.axelor.exception.service.TraceBackService;
import com.axelor.i18n.I18n;
import com.axelor.meta.schema.actions.ActionView;
import com.axelor.rpc.ActionRequest;
import com.axelor.rpc.ActionResponse;
import com.axelor.rpc.Context;
import com.google.inject.Inject;
import com.google.inject.Singleton;
@Singleton
public class GenerateMessageController {
private static final Logger LOG = LoggerFactory.getLogger( MethodHandles.lookup().lookupClass() );
@Inject
private TemplateMessageService templateMessageService;
@Inject
private TemplateRepository templateRepo;
@Inject
private MessageService messageService;
public void callMessageWizard(ActionRequest request, ActionResponse response) {
Model context = request.getContext().asType( Model.class );
String model = request.getModel();
LOG.debug("Call message wizard for model : {} ", model);
String[] decomposeModel = model.split("\\.");
String simpleModel = decomposeModel[ decomposeModel.length - 1 ];
Query<? extends Template> templateQuery = templateRepo.all().filter("self.metaModel.fullName = ?1 AND self.isSystem != true", model );
try {
long templateNumber = templateQuery.count();
LOG.debug("Template number : {} ", templateNumber);
if ( templateNumber == 0 ) {
response.setView(
ActionView.define( I18n.get(IExceptionMessage.MESSAGE_3) )
.model( Message.class.getName() )
.add("form", "message-form")
.param("forceEdit", "true")
.context("_mediaTypeSelect", MessageRepository.MEDIA_TYPE_EMAIL)
.context("_templateContextModel", model)
.context( "_objectId", context.getId().toString())
.map()
);
} else if ( templateNumber > 1 ) {
response.setView(
ActionView.define( I18n.get( IExceptionMessage.MESSAGE_2 ) )
.model(Wizard.class.getName())
.add("form", "generate-message-wizard-form")
.param("show-confirm", "false")
.context( "_objectId", context.getId().toString() )
.context( "_templateContextModel", model )
.context( "_tag", simpleModel )
.map()
);
} else {
response.setView( generateMessage( context.getId(), model, simpleModel, templateQuery.fetchOne() ) );
}
} catch(Exception e) { TraceBackService.trace(response, e); }
}
public void generateMessage(ActionRequest request, ActionResponse response) {
Context context = request.getContext();
Map<?,?> templateContext = (Map<?,?>) context.get("_xTemplate");
Template template = null;
if (templateContext != null) {
template = templateRepo.find( Long.parseLong( templateContext.get("id").toString() ) );
}
Long objectId = Long.parseLong( context.get("_objectId").toString() );
String model = (String) context.get("_templateContextModel");
String tag = (String) context.get("_tag");
try {
response.setView(generateMessage(objectId, model, tag, template));
response.setCanClose(true);
} catch(Exception e) { TraceBackService.trace(response, e); }
}
public Map<String, Object> generateMessage(long objectId, String model, String tag, Template template)
throws SecurityException, NoSuchFieldException, ClassNotFoundException, InstantiationException, IllegalAccessException, AxelorException, IOException {
LOG.debug("template : {} ", template);
LOG.debug("object id : {} ", objectId);
LOG.debug("model : {} ", model);
LOG.debug("tag : {} ", tag);
Message message = null;
if (template != null) {
message = templateMessageService.generateMessage(objectId, model, tag, template);
} else {
message = messageService.createMessage(model, Long.valueOf(objectId).intValue(), null, null, null, null,
null, null, null, null, null, MessageRepository.MEDIA_TYPE_EMAIL, null);
}
return ActionView.define( I18n.get(IExceptionMessage.MESSAGE_3) )
.model( Message.class.getName() )
.add("form", "message-form")
.param("forceEdit", "true")
.context("_showRecord", message.getId().toString() )
.map();
}
}
|
package org.orangeflamingo.namesandsongs.controller;
import java.util.List;
import org.apache.log4j.Logger;
import org.orangeflamingo.namesandsongs.domain.Remark;
import org.orangeflamingo.namesandsongs.domain.View;
import org.orangeflamingo.namesandsongs.service.RemarkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.annotation.JsonView;
/**
* Handles and retrieves song request
*/
@Controller
@RequestMapping("api")
public class RemarkController {
/**
* The LOGGER
*/
private static final Logger LOGGER = Logger
.getLogger(RemarkController.class);
@Autowired
RemarkService remarkService;
/**
* Returns all remarks
*
* @return all remarks
*/
@RequestMapping(value = "admin/remark", method = RequestMethod.GET)
@ResponseBody
@JsonView(View.Summary.class)
public List<Remark> allRemarks() {
LOGGER.debug("Calling remark service...");
return remarkService.getAll();
}
/**
* Gets a remark by id
*
* @param id
* the id of the remark
* @return the remark
*/
@RequestMapping("admin/remark/{id}")
@ResponseBody
@JsonView(View.AdminDetail.class)
public Remark getById(@PathVariable int id) {
LOGGER.debug("Getting remark with id " + id);
return (Remark) remarkService.get(id);
}
@RequestMapping(value = "admin/remark/{id}", method = RequestMethod.POST)
@ResponseBody
public Remark updateRemark(@RequestBody(required = true) Remark remark) {
LOGGER.info("Update request for admin/remark/" + remark.getId()
+ " with commentary: " + remark.getCommentary());
remarkService.update(remark);
return remark;
}
}
|
package com.github.games647.fastlogin.bungee.listener;
import com.github.games647.craftapi.UUIDAdapter;
import com.github.games647.fastlogin.bungee.BungeeLoginSession;
import com.github.games647.fastlogin.bungee.FastLoginBungee;
import com.github.games647.fastlogin.bungee.hook.floodgate.FloodgateHook;
import com.github.games647.fastlogin.bungee.hook.floodgate.FloodgateV1Hook;
import com.github.games647.fastlogin.bungee.hook.floodgate.FloodgateV2Hook;
import com.github.games647.fastlogin.bungee.task.AsyncPremiumCheck;
import com.github.games647.fastlogin.bungee.task.ForceLoginTask;
import com.github.games647.fastlogin.core.RateLimiter;
import com.github.games647.fastlogin.core.StoredProfile;
import com.github.games647.fastlogin.core.shared.LoginSession;
import com.google.common.base.Throwables;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Field;
import java.util.UUID;
import net.md_5.bungee.api.connection.PendingConnection;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.connection.Server;
import net.md_5.bungee.api.event.LoginEvent;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.PreLoginEvent;
import net.md_5.bungee.api.event.ServerConnectedEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.connection.InitialHandler;
import net.md_5.bungee.connection.LoginResult;
import net.md_5.bungee.connection.LoginResult.Property;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.event.EventPriority;
import org.geysermc.floodgate.FloodgateAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Enables online mode logins for specified users and sends plugin message to the Bukkit version of this plugin in
* order to clear that the connection is online mode.
*/
public class ConnectListener implements Listener {
private static final String UUID_FIELD_NAME = "uniqueId";
private static final MethodHandle uniqueIdSetter;
static {
MethodHandle setHandle = null;
boolean handlerFound = false;
try {
Lookup lookup = MethodHandles.lookup();
Class.forName("net.md_5.bungee.connection.InitialHandler");
handlerFound = true;
Field uuidField = InitialHandler.class.getDeclaredField(UUID_FIELD_NAME);
uuidField.setAccessible(true);
setHandle = lookup.unreflectSetter(uuidField);
} catch (ClassNotFoundException classNotFoundException) {
Logger logger = LoggerFactory.getLogger(ConnectListener.class);
logger.error(
"Cannot find Bungee initial handler; Disabling premium UUID and skin won't work.",
classNotFoundException
);
} catch (ReflectiveOperationException reflectiveOperationException) {
reflectiveOperationException.printStackTrace();
}
uniqueIdSetter = setHandle;
}
private final FastLoginBungee plugin;
private final RateLimiter rateLimiter;
private final Property[] emptyProperties = {};
private final FloodgateHook floodgateHook;
public ConnectListener(FastLoginBungee plugin, RateLimiter rateLimiter, String floodgateVersion) {
this.plugin = plugin;
this.rateLimiter = rateLimiter;
// Get the appropriate floodgate api hook based on the version
if (floodgateVersion.startsWith("1")) {
this.floodgateHook = new FloodgateV1Hook();
} else if (floodgateVersion.startsWith("2")) {
this.floodgateHook = new FloodgateV2Hook();
} else {
this.floodgateHook = null;
}
}
@EventHandler
public void onPreLogin(PreLoginEvent preLoginEvent) {
PendingConnection connection = preLoginEvent.getConnection();
if (preLoginEvent.isCancelled() || isBedrockPlayer(connection.getUniqueId())) {
return;
}
if (!rateLimiter.tryAcquire()) {
plugin.getLog().warn("Join limit hit - Ignoring player {}", connection);
return;
}
String username = connection.getName();
plugin.getLog().info("Incoming login request for {} from {}", username, connection.getSocketAddress());
preLoginEvent.registerIntent(plugin);
Runnable asyncPremiumCheck = new AsyncPremiumCheck(plugin, preLoginEvent, connection, username);
plugin.getScheduler().runAsync(asyncPremiumCheck);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onLogin(LoginEvent loginEvent) {
if (loginEvent.isCancelled()) {
return;
}
//use the login event instead of the post login event in order to send the login success packet to the client
//with the offline uuid this makes it possible to set the skin then
PendingConnection connection = loginEvent.getConnection();
if (connection.isOnlineMode()) {
LoginSession session = plugin.getSession().get(connection);
UUID verifiedUUID = connection.getUniqueId();
String verifiedUsername = connection.getName();
session.setUuid(verifiedUUID);
session.setVerifiedUsername(verifiedUsername);
StoredProfile playerProfile = session.getProfile();
playerProfile.setId(verifiedUUID);
// bungeecord will do this automatically so override it on disabled option
if (uniqueIdSetter != null) {
InitialHandler initialHandler = (InitialHandler) connection;
if (!plugin.getCore().getConfig().get("premiumUuid", true)) {
setOfflineId(initialHandler, verifiedUsername);
}
if (!plugin.getCore().getConfig().get("forwardSkin", true)) {
// this is null on offline mode
LoginResult loginProfile = initialHandler.getLoginProfile();
loginProfile.setProperties(emptyProperties);
}
}
}
}
private void setOfflineId(InitialHandler connection, String username) {
try {
final UUID oldPremiumId = connection.getUniqueId();
final UUID offlineUUID = UUIDAdapter.generateOfflineId(username);
// BungeeCord only allows setting the UUID in PreLogin events and before requesting online mode
// However if online mode is requested, it will override previous values
// So we have to do it with reflection
uniqueIdSetter.invokeExact(connection, offlineUUID);
String format = "Overridden UUID from {} to {} (based of {}) on {}";
plugin.getLog().info(format, oldPremiumId, offlineUUID, username, connection);
} catch (Exception ex) {
plugin.getLog().error("Failed to set offline uuid of {}", username, ex);
} catch (Throwable throwable) {
// throw remaining exceptions like outofmemory that we shouldn't handle ourself
Throwables.throwIfUnchecked(throwable);
}
}
@EventHandler
public void onServerConnected(ServerConnectedEvent serverConnectedEvent) {
ProxiedPlayer player = serverConnectedEvent.getPlayer();
Server server = serverConnectedEvent.getServer();
BungeeLoginSession session = plugin.getSession().get(player.getPendingConnection());
if (session == null) {
return;
}
// delay sending force command, because Paper will process the login event asynchronously
// In this case it means that the force command (plugin message) is already received and processed while
// player is still in the login phase and reported to be offline.
Runnable loginTask = new ForceLoginTask(plugin.getCore(), player, server, session);
plugin.getScheduler().runAsync(loginTask);
}
@EventHandler
public void onDisconnect(PlayerDisconnectEvent disconnectEvent) {
ProxiedPlayer player = disconnectEvent.getPlayer();
plugin.getSession().remove(player.getPendingConnection());
plugin.getCore().getPendingConfirms().remove(player.getUniqueId());
}
private boolean isBedrockPlayer(UUID correctedUUID) {
// Floodgate will set a correct UUID at the beginning of the PreLoginEvent
// and will cancel the online mode login for those players
// Therefore we just ignore those
if (floodgateHook == null) {
return false;
}
return this.floodgateHook.isBedrockPlayer(correctedUUID);
}
}
|
package gov.nih.nci.cabig.caaers.security;
import gov.nih.nci.cabig.caaers.domain.UserGroupType;
import gov.nih.nci.cabig.ctms.suite.authorization.SuiteRole;
import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.userdetails.User;
/**
*
* @author Biju Joseph
*
*/
public class SecurityUtils {
/**
* This method will find the login name, of the user available in
* SecurityContext.
* @return
*/
public static String getUserLoginName(){
return getUserLoginName(SecurityContextHolder.getContext().getAuthentication());
}
/**
* This method will find the login name, of the user available in
* SecurityContext.
* @return
*/
public static String getUserLoginName(Authentication authentication){
Object principal = authentication.getPrincipal();
String userName = "";
if (principal instanceof User) {
userName = ((User)principal).getUsername();
} else {
userName = principal.toString();
}
return userName;
}
/**
* Returns the granted authorities
* @param authentication
* @return
*/
public static GrantedAuthority[] getGrantedAuthorities() {
return getGrantedAuthorities(SecurityContextHolder.getContext().getAuthentication());
}
/**
* Returns the granted authorities
* @param authentication
* @return
*/
public static GrantedAuthority[] getGrantedAuthorities(Authentication authentication) {
Object principal = authentication.getPrincipal();
GrantedAuthority[] grantedAuthorities = null;
if (principal instanceof User) {
grantedAuthorities = ((User)principal).getAuthorities();
} else {
grantedAuthorities = authentication.getAuthorities();
}
return grantedAuthorities;
}
/**
* Checks whether the logged-in user has the roles supplied in the roles parameter
* @param roles
* @return
*/
public static boolean checkAuthorization(UserGroupType... roles){
return checkAuthorization(SecurityContextHolder.getContext().getAuthentication(), roles);
}
/**
* Checks whether the logged-in user has the roles supplied in the privilege
* @param privilege
* @return
*/
public static boolean checkAuthorization(String... privilege){
return checkAuthorization(SecurityContextHolder.getContext().getAuthentication(), privilege);
}
/**
* Checks whether the logged-in user has the roles supplied in the privilege
* @param authentication - A valid authentication object
* @param roles - A list of UserGroupType
* @return
*/
public static boolean checkAuthorization(Authentication authentication, UserGroupType... roles){
String[] privileges = new String[roles.length];
for(int i = 0; i < roles.length; i++){
privileges[i] = roles[i].getSecurityRoleName();
}
return checkAuthorization(authentication, privileges );
}
/**
* Checks whether the supplied authentication has the required privilege
* @param authentication
* @param privilege
* @return
*/
public static boolean checkAuthorization(Authentication authentication, String privilege){
return checkAuthorization(authentication, privilege );
}
/**
* Will check whether, the authentication, has all the privileges
* @param authentication
* @param privileges
* @return
*/
public static boolean checkAuthorization(Authentication authentication, String... privileges){
GrantedAuthority[] authorities = getGrantedAuthorities(authentication);
for (int i = 0; i < authorities.length; i++) {
for (int j = 0; j < privileges.length; j++) {
if (authorities[i].getAuthority().equals(privileges[j].trim())) {
return true;
}
}
}
return false;
}
/**
* Get the context related authentication object
*
* */
public static Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
/**
* This method will return false if the logged in user has at least one globally scoped role.
* @return
*/
public static boolean isScoped(){
SuiteRole suiteRole;
Authentication authentication = getAuthentication();
GrantedAuthority[] authorities = getGrantedAuthorities(authentication);
for (int i = 0; i < authorities.length; i++) {
suiteRole = SuiteRole.getByCsmName(authorities[i].getAuthority());
if(!suiteRole.isScoped()){
return false;
}
}
return true;
}
public static boolean isScoped(Authentication authentication){
SuiteRole suiteRole;
GrantedAuthority[] authorities = getGrantedAuthorities(authentication);
for (int i = 0; i < authorities.length; i++) {
suiteRole = SuiteRole.getByCsmName(authorities[i].getAuthority());
if(!suiteRole.isScoped()){
return false;
}
}
return true;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.