repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
StephaneMangin/V-V-TP3 | src/main/java/net/sourceforge/pmd/lang/ecmascript/ast/ASTObjectProperty.java | 657 | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.ecmascript.ast;
import org.mozilla.javascript.ast.ObjectProperty;
public class ASTObjectProperty extends AbstractInfixEcmascriptNode<ObjectProperty> {
public ASTObjectProperty(ObjectProperty objectProperty) {
super(objectProperty);
}
/**
* Accept the visitor.
*/
public Object jjtAccept(EcmascriptParserVisitor visitor, Object data) {
return visitor.visit(this, data);
}
public boolean isGetter() {
return node.isGetter();
}
public boolean isSetter() {
return node.isSetter();
}
}
| bsd-3-clause |
agmip/translator-dssat | src/test/java/org/agmip/translators/dssat/DssatAFileTest.java | 1568 | package org.agmip.translators.dssat;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import static org.agmip.util.MapUtil.getObjectOr;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
/**
* Unit test for simple App.
*/
/**
*
* @author Meng Zhang
*/
public class DssatAFileTest {
DssatAFileOutput obDssatAFileOutput;
DssatAFileInput obDssatAFileInput;
URL resource;
@Before
public void setUp() throws Exception {
obDssatAFileOutput = new DssatAFileOutput();
obDssatAFileInput = new DssatAFileInput();
resource = this.getClass().getResource("/UFGA8202_MZX.ZIP");
}
@Test
public void test() throws IOException, Exception {
HashMap result;
result = obDssatAFileInput.readFile(resource.getPath());
// System.out.println(JSONAdapter.toJSON(result));
// File f = new File("outputA.txt");
// BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(f));
// bo.write(JSONAdapter.toJSON(result).getBytes());
// bo.close();
// f.delete();
ArrayList<HashMap> expArr = getObjectOr(result, "experiments", new ArrayList());
obDssatAFileOutput.writeFile("output", expArr.get(0));
File file = obDssatAFileOutput.getOutputFile();
if (file != null) {
assertTrue(file.exists());
assertEquals("UFGA8202.MZA", file.getName());
assertTrue(file.delete());
}
}
}
| bsd-3-clause |
LWJGL-CI/lwjgl3 | modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/VkMemoryBarrier.java | 17291 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;
/**
* Structure specifying a global memory barrier.
*
* <h5>Description</h5>
*
* <p>The first <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-dependencies-access-scopes">access scope</a> is limited to access types in the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-access-masks">source access mask</a> specified by {@code srcAccessMask}.</p>
*
* <p>The second <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-dependencies-access-scopes">access scope</a> is limited to access types in the <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-access-masks">destination access mask</a> specified by {@code dstAccessMask}.</p>
*
* <h5>Valid Usage (Implicit)</h5>
*
* <ul>
* <li>{@code sType} <b>must</b> be {@link VK10#VK_STRUCTURE_TYPE_MEMORY_BARRIER STRUCTURE_TYPE_MEMORY_BARRIER}</li>
* <li>{@code pNext} <b>must</b> be {@code NULL}</li>
* <li>{@code srcAccessMask} <b>must</b> be a valid combination of {@code VkAccessFlagBits} values</li>
* <li>{@code dstAccessMask} <b>must</b> be a valid combination of {@code VkAccessFlagBits} values</li>
* </ul>
*
* <h5>See Also</h5>
*
* <p>{@link VK10#vkCmdPipelineBarrier CmdPipelineBarrier}, {@link VK10#vkCmdWaitEvents CmdWaitEvents}</p>
*
* <h3>Layout</h3>
*
* <pre><code>
* struct VkMemoryBarrier {
* VkStructureType {@link #sType};
* void const * {@link #pNext};
* VkAccessFlags {@link #srcAccessMask};
* VkAccessFlags {@link #dstAccessMask};
* }</code></pre>
*/
public class VkMemoryBarrier extends Struct implements NativeResource {
/** The struct size in bytes. */
public static final int SIZEOF;
/** The struct alignment in bytes. */
public static final int ALIGNOF;
/** The struct member offsets. */
public static final int
STYPE,
PNEXT,
SRCACCESSMASK,
DSTACCESSMASK;
static {
Layout layout = __struct(
__member(4),
__member(POINTER_SIZE),
__member(4),
__member(4)
);
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
STYPE = layout.offsetof(0);
PNEXT = layout.offsetof(1);
SRCACCESSMASK = layout.offsetof(2);
DSTACCESSMASK = layout.offsetof(3);
}
/**
* Creates a {@code VkMemoryBarrier} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public VkMemoryBarrier(ByteBuffer container) {
super(memAddress(container), __checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
/** the type of this structure. */
@NativeType("VkStructureType")
public int sType() { return nsType(address()); }
/** {@code NULL} or a pointer to a structure extending this structure. */
@NativeType("void const *")
public long pNext() { return npNext(address()); }
/** a bitmask of {@code VkAccessFlagBits} specifying a <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-access-masks">source access mask</a>. */
@NativeType("VkAccessFlags")
public int srcAccessMask() { return nsrcAccessMask(address()); }
/** a bitmask of {@code VkAccessFlagBits} specifying a <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#synchronization-access-masks">destination access mask</a>. */
@NativeType("VkAccessFlags")
public int dstAccessMask() { return ndstAccessMask(address()); }
/** Sets the specified value to the {@link #sType} field. */
public VkMemoryBarrier sType(@NativeType("VkStructureType") int value) { nsType(address(), value); return this; }
/** Sets the {@link VK10#VK_STRUCTURE_TYPE_MEMORY_BARRIER STRUCTURE_TYPE_MEMORY_BARRIER} value to the {@link #sType} field. */
public VkMemoryBarrier sType$Default() { return sType(VK10.VK_STRUCTURE_TYPE_MEMORY_BARRIER); }
/** Sets the specified value to the {@link #pNext} field. */
public VkMemoryBarrier pNext(@NativeType("void const *") long value) { npNext(address(), value); return this; }
/** Sets the specified value to the {@link #srcAccessMask} field. */
public VkMemoryBarrier srcAccessMask(@NativeType("VkAccessFlags") int value) { nsrcAccessMask(address(), value); return this; }
/** Sets the specified value to the {@link #dstAccessMask} field. */
public VkMemoryBarrier dstAccessMask(@NativeType("VkAccessFlags") int value) { ndstAccessMask(address(), value); return this; }
/** Initializes this struct with the specified values. */
public VkMemoryBarrier set(
int sType,
long pNext,
int srcAccessMask,
int dstAccessMask
) {
sType(sType);
pNext(pNext);
srcAccessMask(srcAccessMask);
dstAccessMask(dstAccessMask);
return this;
}
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public VkMemoryBarrier set(VkMemoryBarrier src) {
memCopy(src.address(), address(), SIZEOF);
return this;
}
// -----------------------------------
/** Returns a new {@code VkMemoryBarrier} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static VkMemoryBarrier malloc() {
return wrap(VkMemoryBarrier.class, nmemAllocChecked(SIZEOF));
}
/** Returns a new {@code VkMemoryBarrier} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static VkMemoryBarrier calloc() {
return wrap(VkMemoryBarrier.class, nmemCallocChecked(1, SIZEOF));
}
/** Returns a new {@code VkMemoryBarrier} instance allocated with {@link BufferUtils}. */
public static VkMemoryBarrier create() {
ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
return wrap(VkMemoryBarrier.class, memAddress(container), container);
}
/** Returns a new {@code VkMemoryBarrier} instance for the specified memory address. */
public static VkMemoryBarrier create(long address) {
return wrap(VkMemoryBarrier.class, address);
}
/** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static VkMemoryBarrier createSafe(long address) {
return address == NULL ? null : wrap(VkMemoryBarrier.class, address);
}
/**
* Returns a new {@link VkMemoryBarrier.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static VkMemoryBarrier.Buffer malloc(int capacity) {
return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity);
}
/**
* Returns a new {@link VkMemoryBarrier.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static VkMemoryBarrier.Buffer calloc(int capacity) {
return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity);
}
/**
* Returns a new {@link VkMemoryBarrier.Buffer} instance allocated with {@link BufferUtils}.
*
* @param capacity the buffer capacity
*/
public static VkMemoryBarrier.Buffer create(int capacity) {
ByteBuffer container = __create(capacity, SIZEOF);
return wrap(Buffer.class, memAddress(container), capacity, container);
}
/**
* Create a {@link VkMemoryBarrier.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static VkMemoryBarrier.Buffer create(long address, int capacity) {
return wrap(Buffer.class, address, capacity);
}
/** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static VkMemoryBarrier.Buffer createSafe(long address, int capacity) {
return address == NULL ? null : wrap(Buffer.class, address, capacity);
}
// -----------------------------------
/** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */
@Deprecated public static VkMemoryBarrier mallocStack() { return malloc(stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */
@Deprecated public static VkMemoryBarrier callocStack() { return calloc(stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */
@Deprecated public static VkMemoryBarrier mallocStack(MemoryStack stack) { return malloc(stack); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */
@Deprecated public static VkMemoryBarrier callocStack(MemoryStack stack) { return calloc(stack); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */
@Deprecated public static VkMemoryBarrier.Buffer mallocStack(int capacity) { return malloc(capacity, stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */
@Deprecated public static VkMemoryBarrier.Buffer callocStack(int capacity) { return calloc(capacity, stackGet()); }
/** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */
@Deprecated public static VkMemoryBarrier.Buffer mallocStack(int capacity, MemoryStack stack) { return malloc(capacity, stack); }
/** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */
@Deprecated public static VkMemoryBarrier.Buffer callocStack(int capacity, MemoryStack stack) { return calloc(capacity, stack); }
/**
* Returns a new {@code VkMemoryBarrier} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static VkMemoryBarrier malloc(MemoryStack stack) {
return wrap(VkMemoryBarrier.class, stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@code VkMemoryBarrier} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static VkMemoryBarrier calloc(MemoryStack stack) {
return wrap(VkMemoryBarrier.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
/**
* Returns a new {@link VkMemoryBarrier.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static VkMemoryBarrier.Buffer malloc(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link VkMemoryBarrier.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static VkMemoryBarrier.Buffer calloc(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
}
// -----------------------------------
/** Unsafe version of {@link #sType}. */
public static int nsType(long struct) { return UNSAFE.getInt(null, struct + VkMemoryBarrier.STYPE); }
/** Unsafe version of {@link #pNext}. */
public static long npNext(long struct) { return memGetAddress(struct + VkMemoryBarrier.PNEXT); }
/** Unsafe version of {@link #srcAccessMask}. */
public static int nsrcAccessMask(long struct) { return UNSAFE.getInt(null, struct + VkMemoryBarrier.SRCACCESSMASK); }
/** Unsafe version of {@link #dstAccessMask}. */
public static int ndstAccessMask(long struct) { return UNSAFE.getInt(null, struct + VkMemoryBarrier.DSTACCESSMASK); }
/** Unsafe version of {@link #sType(int) sType}. */
public static void nsType(long struct, int value) { UNSAFE.putInt(null, struct + VkMemoryBarrier.STYPE, value); }
/** Unsafe version of {@link #pNext(long) pNext}. */
public static void npNext(long struct, long value) { memPutAddress(struct + VkMemoryBarrier.PNEXT, value); }
/** Unsafe version of {@link #srcAccessMask(int) srcAccessMask}. */
public static void nsrcAccessMask(long struct, int value) { UNSAFE.putInt(null, struct + VkMemoryBarrier.SRCACCESSMASK, value); }
/** Unsafe version of {@link #dstAccessMask(int) dstAccessMask}. */
public static void ndstAccessMask(long struct, int value) { UNSAFE.putInt(null, struct + VkMemoryBarrier.DSTACCESSMASK, value); }
// -----------------------------------
/** An array of {@link VkMemoryBarrier} structs. */
public static class Buffer extends StructBuffer<VkMemoryBarrier, Buffer> implements NativeResource {
private static final VkMemoryBarrier ELEMENT_FACTORY = VkMemoryBarrier.create(-1L);
/**
* Creates a new {@code VkMemoryBarrier.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link VkMemoryBarrier#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}
public Buffer(long address, int cap) {
super(address, null, -1, 0, cap, cap);
}
Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected VkMemoryBarrier getElementFactory() {
return ELEMENT_FACTORY;
}
/** @return the value of the {@link VkMemoryBarrier#sType} field. */
@NativeType("VkStructureType")
public int sType() { return VkMemoryBarrier.nsType(address()); }
/** @return the value of the {@link VkMemoryBarrier#pNext} field. */
@NativeType("void const *")
public long pNext() { return VkMemoryBarrier.npNext(address()); }
/** @return the value of the {@link VkMemoryBarrier#srcAccessMask} field. */
@NativeType("VkAccessFlags")
public int srcAccessMask() { return VkMemoryBarrier.nsrcAccessMask(address()); }
/** @return the value of the {@link VkMemoryBarrier#dstAccessMask} field. */
@NativeType("VkAccessFlags")
public int dstAccessMask() { return VkMemoryBarrier.ndstAccessMask(address()); }
/** Sets the specified value to the {@link VkMemoryBarrier#sType} field. */
public VkMemoryBarrier.Buffer sType(@NativeType("VkStructureType") int value) { VkMemoryBarrier.nsType(address(), value); return this; }
/** Sets the {@link VK10#VK_STRUCTURE_TYPE_MEMORY_BARRIER STRUCTURE_TYPE_MEMORY_BARRIER} value to the {@link VkMemoryBarrier#sType} field. */
public VkMemoryBarrier.Buffer sType$Default() { return sType(VK10.VK_STRUCTURE_TYPE_MEMORY_BARRIER); }
/** Sets the specified value to the {@link VkMemoryBarrier#pNext} field. */
public VkMemoryBarrier.Buffer pNext(@NativeType("void const *") long value) { VkMemoryBarrier.npNext(address(), value); return this; }
/** Sets the specified value to the {@link VkMemoryBarrier#srcAccessMask} field. */
public VkMemoryBarrier.Buffer srcAccessMask(@NativeType("VkAccessFlags") int value) { VkMemoryBarrier.nsrcAccessMask(address(), value); return this; }
/** Sets the specified value to the {@link VkMemoryBarrier#dstAccessMask} field. */
public VkMemoryBarrier.Buffer dstAccessMask(@NativeType("VkAccessFlags") int value) { VkMemoryBarrier.ndstAccessMask(address(), value); return this; }
}
} | bsd-3-clause |
TreeBASE/treebasetest | treebase-web/src/main/java/org/cipres/treebase/web/controllers/DownloadATreeController.java | 4088 |
package org.cipres.treebase.web.controllers;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.cipres.treebase.TreebaseUtil;
import org.cipres.treebase.domain.nexus.NexusDataSet;
import org.cipres.treebase.domain.study.Study;
import org.cipres.treebase.domain.study.StudyService;
import org.cipres.treebase.domain.taxon.TaxonLabelSet;
import org.cipres.treebase.domain.tree.PhyloTree;
import org.cipres.treebase.domain.tree.PhyloTreeService;
import org.cipres.treebase.domain.tree.TreeBlock;
import org.cipres.treebase.web.util.ControllerUtil;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
/**
* DownloadATreeController.java
*
* Generate a file file dynamically for download
*
* Created on July 26, 2007
*
* @author Madhu
*
*
*/
public class DownloadATreeController extends AbstractDownloadController implements Controller {
private PhyloTreeService mPhyloTreeService;
private StudyService mStudyService;
public PhyloTreeService getPhyloTreeService() {
return mPhyloTreeService;
}
/**
* Set the PhyloTreeService
*/
public void setPhyloTreeService(PhyloTreeService pNewPhyloTreeService) {
mPhyloTreeService = pNewPhyloTreeService;
}
/**
* Return the StudyService field.
*
* @return StudyService mStudyService
*/
public StudyService getStudyService() {
return mStudyService;
}
/**
* Set the StudyService field.
*/
public void setStudyService(StudyService pNewStudyService) {
mStudyService = pNewStudyService;
}
/**
*
* @see org.springframework.web.servlet.mvc.Controller#handleRequest(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws Exception {
if (request.getParameter("treeid") == null) {
return null;
}
long treeid = Long.parseLong(request.getParameter("treeid"));
generateAFileDynamically(request, response, treeid);
return null;
}
@Override
protected String getFileNamePrefix() {
return "T";
}
@Override
protected String getFileContent(long pTreeId, HttpServletRequest request) {
Study study = ControllerUtil.findStudy(request, mStudyService);
PhyloTree tree = getPhyloTreeService().findByID(pTreeId);
tree = getPhyloTreeService().resurrect(tree);
TreeBlock enclosingTreeBlock = getPhyloTreeService().resurrect(tree.getTreeBlock());
TaxonLabelSet tls = getPhyloTreeService().resurrect(enclosingTreeBlock.getTaxonLabelSet());
if ( getFormat(request) == FORMAT_NEXML || getFormat(request) == FORMAT_RDF ) {
NexusDataSet nds = new NexusDataSet();
nds.getTaxonLabelSets().add(tls);
TreeBlock treeBlock = new TreeBlock();
treeBlock.setTaxonLabelSet(tls);
treeBlock.addPhyloTree(tree);
nds.getTreeBlocks().add(treeBlock);
return getNexmlService().serialize(nds,getDefaultProperties(request),tree.getStudy());
}
/*else if ( getFormat(request) == FORMAT_RDF ) {
NexusDataSet nds = new NexusDataSet();
nds.getTaxonLabelSets().add(tls);
TreeBlock treeBlock = new TreeBlock();
treeBlock.setTaxonLabelSet(tls);
treeBlock.addPhyloTree(tree);
nds.getTreeBlocks().add(treeBlock);
return getRdfaService().serialize(nds,getDefaultProperties(request),tree.getStudy());
} */
else {
StringBuilder builder = new StringBuilder();
builder.append("#NEXUS\n\n");
// header:
TreebaseUtil.attachStudyHeader(study, builder);
// taxa:
// one taxon label per line, no line number.
tls.buildNexusBlockTaxa(builder, true, false);
//tree block:
tree.buildNexusBlock(builder);
return builder.toString();
}
}
@Override
protected Study getStudy(long objectId, HttpServletRequest request) {
PhyloTree tree = getPhyloTreeService().findByID(objectId);
return tree.getStudy();
}
}
| bsd-3-clause |
mushroomhostage/ic2-nuclear-control | upstream/common/net/minecraft/src/nuclearcontrol/ItemRangeUpgrade.java | 424 | package net.minecraft.src.nuclearcontrol;
import net.minecraft.src.Item;
import net.minecraft.src.forge.ITextureProvider;
public class ItemRangeUpgrade extends Item implements ITextureProvider
{
public ItemRangeUpgrade(int i, int iconIndex)
{
super(i);
setIconIndex(iconIndex);
}
public String getTextureFile()
{
return "/img/texture_thermo.png";
}
}
| bsd-3-clause |
berlinguyinca/spectra-hash | validation/src/main/java/edu/ucdavis/fiehnlab/spectra/hash/core/validation/Application.java | 679 | package edu.ucdavis.fiehnlab.spectra.hash.core.validation;
import edu.ucdavis.fiehnlab.spectra.hash.core.Splash;
import edu.ucdavis.fiehnlab.spectra.hash.core.SplashFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan
@EnableAutoConfiguration
public class Application {
private Splash splash = SplashFactory.create();
/**
* main method to launch this applications
*
* @param args
*/
public static void main(String... args) {
SpringApplication.run(Application.class, args);
}
}
| bsd-3-clause |
jeking3/scheduling-server | Bookings/src/au/edu/uts/eng/remotelabs/schedserver/bookings/impl/BookingEngine.java | 8238 | /**
* SAHARA Scheduling Server
*
* Schedules and assigns local laboratory rigs.
*
* @license See LICENSE in the top level directory for complete license terms.
*
* Copyright (c) 2010, University of Technology, Sydney
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Technology, Sydney nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Michael Diponio (mdiponio)
* @date 18th November 2010
*/
package au.edu.uts.eng.remotelabs.schedserver.bookings.impl;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.hibernate.Session;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.Bookings;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.RequestCapabilities;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.ResourcePermission;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.Rig;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.RigType;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.User;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.listener.RigEventListener;
/**
* Booking engine interface.
*/
public interface BookingEngine
{
/**
* Initialise the booking engine. This returns a list of runnable tasks
* needed for engine management.
*
* @return list of runnable tasks or an empty list if non-needed
*/
public BookingInit init();
/**
* Cleanup the booking engine (for shutdown).
*/
public void cleanUp();
/**
* Gets free time periods for the rig in the requested time period. Each
* of the returned time periods needs to be at least as long as the
* specified duration.
*
* @param rig rig to find free durations of
* @param period the time period to find the free periods in
* @param minDuration minimum time of period in seconds
* @param ses database session the rig is loaded in
* @return list of time periods
*/
public List<TimePeriod> getFreeTimes(Rig rig, TimePeriod period, int minDuration, Session ses);
/**
* Gets free time periods for the rig type in the requested time period.
* Each of the returned time periods needs to be at least as long as
* the specified duration.
*
* @param rigType rig type to find free durations of
* @param period the time period to find the free periods in
* @param minDuration minimum time of period in seconds
* @param ses database session the capabilities are loaded in
* @return list of time periods
*/
public List<TimePeriod> getFreeTimes(RigType rigType, TimePeriod period, int minDuration, Session ses);
/**
* Gets free time periods for the request capabilities in the requested
* time period. Each of the returned time periods needs to be at least as
* long as the specified duration.
*
* @param caps request capabilities to find free durations of
* @param period the time period to find the free periods in
* @param minDuration minimum time of period in seconds
* @param ses database session the capabilities are loaded in
* @return list of time periods
*/
public List<TimePeriod> getFreeTimes(RequestCapabilities caps, TimePeriod period, int minDuration, Session ses);
/**
* Creates a booking. If creating the booking was unsuccessful a list
* of possible solutions are given.
*
* @param user user to create booking for
* @param perm permission detailing booking details
* @param tp period for booking
* @param ses database ses
* @return booking response
*/
public BookingCreation createBooking(User user, ResourcePermission perm, TimePeriod tp, Session ses);
/**
* Cancels a booking.
*
* @param booking booking to cancel
* @param reason the reason the booking is being canceled
* @param ses database session the booking is loaded in
* @return true if successful
*/
public boolean cancelBooking(Bookings booking, String reason, Session ses);
public static class TimePeriod
{
/** Period start. */
private Calendar startTime;
/** Period end. */
private Calendar endTime;
public TimePeriod(Calendar start, Calendar end)
{
this.startTime = start;
this.endTime = end;
}
public Calendar getStartTime()
{
return this.startTime;
}
public Calendar getEndTime()
{
return this.endTime;
}
}
public static class BookingCreation
{
/** Whether the booking was created. */
private boolean wasCreated;
/** The list of best fits which most closely
* match the requested booking. */
private List<TimePeriod> bestFits;
/** Booking created. */
private Bookings booking;
public BookingCreation()
{
this.bestFits = new ArrayList<BookingEngine.TimePeriod>();
}
public boolean wasCreated()
{
return this.wasCreated;
}
public void setWasCreated(boolean param)
{
this.wasCreated = param;
}
public Bookings getBooking()
{
return this.booking;
}
public void setBooking(Bookings param)
{
this.booking = param;
}
public void addBestFit(TimePeriod tp)
{
this.bestFits.add(tp);
}
public List<TimePeriod> getBestFits()
{
return this.bestFits;
}
}
/**
* Initialisation response, containing with management tasks and rig
* event listeners.
*/
public static class BookingInit
{
/** Management tasks. */
private List<BookingManagementTask> tasks;
/** Rig event listeners. */
private List<RigEventListener> listeners;
public BookingInit()
{
this.tasks = new ArrayList<BookingManagementTask>();
this.listeners = new ArrayList<RigEventListener>();
}
public void addTask(BookingManagementTask task)
{
this.tasks.add(task);
}
public List<BookingManagementTask> getTasks()
{
return this.tasks;
}
public void addListener(RigEventListener listener)
{
this.listeners.add(listener);
}
public List<RigEventListener> getListeners()
{
return this.listeners;
}
}
}
| bsd-3-clause |
dvbu-test/PDTool | CISAdminApi7.0.0/src/com/compositesw/services/system/admin/ParseSqlQuerySoapFault.java | 1176 |
package com.compositesw.services.system.admin;
import javax.xml.ws.WebFault;
import com.compositesw.services.system.util.common.Fault;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.1-b01-
* Generated source version: 2.2
*
*/
@WebFault(name = "fault", targetNamespace = "http://www.compositesw.com/services/system/util/common")
public class ParseSqlQuerySoapFault
extends Exception
{
/**
* Java type that goes as soapenv:Fault detail element.
*
*/
private Fault faultInfo;
/**
*
* @param message
* @param faultInfo
*/
public ParseSqlQuerySoapFault(String message, Fault faultInfo) {
super(message);
this.faultInfo = faultInfo;
}
/**
*
* @param message
* @param faultInfo
* @param cause
*/
public ParseSqlQuerySoapFault(String message, Fault faultInfo, Throwable cause) {
super(message, cause);
this.faultInfo = faultInfo;
}
/**
*
* @return
* returns fault bean: com.compositesw.services.system.util.common.Fault
*/
public Fault getFaultInfo() {
return faultInfo;
}
}
| bsd-3-clause |
Krudeboy51/Robot2017Code | src/org/usfirst/frc369/Robot2017Code/commands/GearHandlerDown.java | 1063 | package org.usfirst.frc369.Robot2017Code.commands;
import org.usfirst.frc369.Robot2017Code.Robot;
import edu.wpi.first.wpilibj.command.Command;
/**
*
*/
public class GearHandlerDown extends Command {
boolean isdone = false;
public GearHandlerDown() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
requires(Robot.gearHandler);
}
// Called just before this Command runs the first time
protected void initialize() {
Robot.gearHandler.putHandlerDown();
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
isdone = true;
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return isdone;
}
// 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() {
end();
}
}
| bsd-3-clause |
deshmnnit04/basex | basex-core/src/main/java/org/basex/gui/view/ViewContainer.java | 10662 | package org.basex.gui.view;
import static org.basex.core.Text.*;
import static org.basex.gui.GUIConstants.*;
import java.awt.*;
import java.util.*;
import org.basex.gui.*;
import org.basex.gui.layout.*;
import org.basex.util.*;
/**
* This class manages all visible and invisible views and allows drag and
* drop operations inside the panel.
*
* @author BaseX Team 2005-15, BSD License
* @author Christian Gruen
*/
public final class ViewContainer extends BaseXBack {
/** Dragging stroke. */
private static final BasicStroke STROKE = new BasicStroke(2);
/** Orientation enumerator. */
private enum Target {
/** North orientation. */ NORTH,
/** West orientation. */ WEST,
/** East orientation. */ EAST,
/** South orientation. */ SOUTH
}
/** Reference to main window. */
private final GUI gui;
/** View Layout. */
private ViewAlignment layout;
/** Current layout string. */
private String layoutString;
/** View panels. */
private final ViewPanel[] views;
/** Source View. */
private ViewPanel source;
/** Target View. */
private ViewPanel target;
/** Logo reference. */
private final Image logo;
/** Target orientation. */
private Target orient;
/** Temporary mouse position. */
private Point sp;
/** Temporary rectangle position. */
private final int[] pos = new int[4];
/**
* Constructor.
* @param main reference to the main window
* @param v view panels
*/
public ViewContainer(final GUI main, final View... v) {
layout(new BorderLayout());
setOpaque(true);
logo = BaseXImages.get("logo_transparent");
setBackground(BACK);
final int vl = v.length;
views = new ViewPanel[vl];
for(int i = 0; i < vl; ++i) views[i] = new ViewPanel(v[i]);
gui = main;
// build layout or use default if something goes wrong
if(!buildLayout(gui.gopts.get(GUIOptions.VIEWS)) && !buildLayout(VIEWS)) {
Util.errln(Util.className(this) + ": could not build layout \"%\"", VIEWS);
}
}
/**
* Updates and validates the views.
*/
public void updateViews() {
// update visibility of all components, dependent of the existence of a database
layout.setVisibility(gui.context.data() != null);
// check if the layout of visible components has changed
final String ls = layout.layoutString(false);
if(ls.equals(layoutString)) return;
// rebuild views
removeAll();
layout.createView(this);
validate();
repaint();
gui.gopts.set(GUIOptions.VIEWS, layout.layoutString(true));
layoutString = ls;
}
@Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
if(getComponentCount() != 0) return;
final int w = getWidth();
final int h = getHeight();
final int hh = Math.max(220, Math.min(700, h));
if(w < 150 || h < 160) return;
final int lh = logo.getHeight(this);
final int y = (hh - lh - 60) / 2;
g.drawImage(logo, (w - logo.getWidth(this)) / 2, y, this);
if(w < 200 || h < 200) return;
g.setColor(dgray);
g.setFont(lfont);
BaseXLayout.drawCenter(g, VERSINFO + ' ' + Prop.VERSION, w, y + 20 + lh);
}
/**
* Drags the current view.
* @param panel panel to be dragged
* @param p absolute mouse position
*/
void dragPanel(final ViewPanel panel, final Point p) {
source = panel;
sp = p;
calc();
repaint();
}
/**
* Drops a view and reorganizes the layout.
*/
void dropPanel() {
if(source == null) return;
if(orient != null) {
if(layout.delete(source) && !(layout.comp[0] instanceof ViewPanel))
layout = (ViewAlignment) layout.comp[0];
if(target == null) layout = addView(layout);
else add(layout);
updateViews();
}
source = null;
repaint();
}
/**
* Adds the dragged view after if it has been removed.
* @param lay layout instance
* @return true if component was successfully added
*/
private boolean add(final ViewAlignment lay) {
for(int o = 0; o < lay.comp.length; ++o) {
final ViewLayout comp = lay.comp[o];
if(comp instanceof ViewAlignment) {
if(add((ViewAlignment) comp)) return true;
} else if(comp == target) {
final boolean west = orient == Target.WEST;
final boolean east = orient == Target.EAST;
if(orient == Target.NORTH || west) {
if(lay.horiz == west) {
lay.add(source, o);
} else {
final ViewAlignment l = new ViewAlignment(west);
l.add(source);
l.add(target);
lay.comp[o] = l;
}
} else if(orient == Target.SOUTH || east) {
if(lay.horiz == east) {
lay.add(source, o + 1);
} else {
final ViewAlignment l = new ViewAlignment(east);
l.add(target);
l.add(source);
lay.comp[o] = l;
}
}
return true;
}
}
return false;
}
/**
* Adds the dragged view into the specified layout instance.
* @param lay layout instance
* @return resulting layout
*/
private ViewAlignment addView(final ViewAlignment lay) {
final boolean west = orient == Target.WEST;
final boolean east = orient == Target.EAST;
ViewAlignment l = lay;
if(orient == Target.NORTH || west) {
if(l.horiz == west) {
l.add(source, 0);
} else {
final ViewAlignment ll = new ViewAlignment(west);
ll.add(source);
ll.add(l);
l = ll;
}
} else if(orient == Target.SOUTH || east) {
if(l.horiz == east) {
l.add(source);
} else {
final ViewAlignment ll = new ViewAlignment(east);
ll.add(l);
ll.add(source);
l = ll;
}
}
return l;
}
/**
* Finds the view under the mouse position and returns it as possible
* target for dropping the dragged view.
* @return view container
*/
private ViewPanel getTarget() {
for(final ViewPanel v : views) {
if(v.isVisible() && new Rectangle(absLoc(v), v.getSize()).contains(sp))
return v;
}
return null;
}
/**
* Calculates the absolute location for the specified point and component.
* @param comp component
* @return absolute location
*/
private Point absLoc(final Component comp) {
Component c = comp;
final Point p = c.getLocation();
do {
c = c.getParent();
p.x += c.getX();
p.y += c.getY();
} while(c.getParent() != this);
return p;
}
@Override
public void paint(final Graphics g) {
super.paint(g);
if(source == null) return;
((Graphics2D) g).setStroke(STROKE);
if(orient != null) {
g.setColor(color(16));
g.drawRect(pos[0], pos[1], pos[2] - 1, pos[3] - 1);
((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f));
g.setColor(color(8));
g.fillRect(pos[0], pos[1], pos[2], pos[3]);
}
}
/**
* Calculates the target position.
*/
private void calc() {
final int hh = getHeight();
final int ww = getWidth();
pos[0] = 1;
pos[1] = 1;
pos[2] = ww - 2;
pos[3] = hh - 2;
orient = null;
target = getTarget();
// paint panel which is currently moved somewhere else
if(target != null && target != source) {
final Rectangle tr = new Rectangle(absLoc(target), target.getSize());
final int minx = tr.width >> 1;
final int miny = tr.height >> 1;
if(Math.abs(tr.x + tr.width / 2 - sp.x) < tr.width / 3) {
if(sp.y > tr.y && sp.y < tr.y + miny) {
pos[0] = tr.x;
pos[1] = tr.y;
pos[2] = tr.width;
pos[3] = miny;
orient = Target.NORTH;
} else if(sp.y > tr.y + tr.height - miny && sp.y < tr.y + tr.height) {
pos[0] = tr.x;
pos[1] = tr.y + tr.height - miny;
pos[2] = tr.width;
pos[3] = miny;
orient = Target.SOUTH;
}
} else if(Math.abs(tr.y + tr.height / 2 - sp.y) < tr.height / 3) {
if(sp.x > tr.x && sp.x < tr.x + minx) {
pos[0] = tr.x;
pos[1] = tr.y;
pos[2] = minx;
pos[3] = tr.height;
orient = Target.WEST;
} else if(sp.x > tr.x + tr.width - minx && sp.x < tr.x + tr.width) {
pos[0] = tr.x + tr.width - minx;
pos[1] = tr.y;
pos[2] = minx;
pos[3] = tr.height;
orient = Target.EAST;
}
}
}
if(orient == null) {
final int minx = ww >> 2;
final int miny = hh >> 2;
target = null;
if(sp.y < miny) {
pos[3] = miny;
orient = Target.NORTH;
} else if(sp.y > hh - miny) {
pos[3] = miny;
pos[1] = hh - miny;
orient = Target.SOUTH;
} else if(sp.x < minx) {
pos[2] = minx;
orient = Target.WEST;
} else if(sp.x > ww - minx) {
pos[2] = minx;
pos[0] = ww - minx;
orient = Target.EAST;
}
}
}
/**
* Builds the view layout by parsing the layout string.
* @param cnstr layout string
* @return true if everything went alright
*/
private boolean buildLayout(final String cnstr) {
try {
layout = null;
int lvl = -1;
final ViewAlignment[] l = new ViewAlignment[16];
final StringTokenizer st = new StringTokenizer(cnstr);
int nv = 0;
while(st.hasMoreTokens()) {
final String t = st.nextToken();
if(Strings.eq(t, "H", "V")) {
l[lvl + 1] = new ViewAlignment("H".equals(t));
if(layout == null) {
layout = l[0];
} else {
l[lvl].add(l[lvl + 1]);
}
++lvl;
} else if("-".equals(t)) {
--lvl;
} else {
final ViewPanel view = getView(t);
if(view == null) return false;
l[lvl].add(view);
++nv;
}
}
if(nv == views.length) return true;
Util.errln(Util.className(this) + ": initializing views: " + cnstr);
} catch(final Exception ex) {
Util.debug(ex);
Util.errln(Util.className(this) + ": could not build layout: " + cnstr);
}
return false;
}
/**
* Returns the view specified by its internal name. The view names
* are specified in the {@link GUIConstants} class.
* @param name name of the view
* @return found view container
*/
private ViewPanel getView(final String name) {
for(final ViewPanel view : views) {
if(view.toString().equals(name)) return view;
}
Util.debug(Util.className(this) + ": Unknown view \"%\"", name);
return null;
}
}
| bsd-3-clause |
andrewgaul/jSCSI | bundles/targetExtensions/scsi/src/org/jscsi/scsi/transport/Nexus.java | 8946 | /**
* Copyright (c) 2012, University of Konstanz, Distributed Systems Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Konstanz nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//Cleversafe open-source code header - Version 1.1 - December 1, 2006
//
//Cleversafe Dispersed Storage(TM) is software for secure, private and
//reliable storage of the world's data using information dispersal.
//
//Copyright (C) 2005-2007 Cleversafe, Inc.
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either version 2
//of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
//USA.
//
//Contact Information:
// Cleversafe, 10 W. 35th Street, 16th Floor #84,
// Chicago IL 60616
// email: licensing@cleversafe.org
//
//END-OF-HEADER
//-----------------------
//@author: John Quigley <jquigley@cleversafe.com>
//@date: January 1, 2008
//---------------------
package org.jscsi.scsi.transport;
/**
* Represents an I_T, I_T_L, or I_T_L_Q Nexus.
* <p>
* An I_T Nexus identification will have L and Q set to invalid (negative) values.
* <p>
* An I_T_L Nexus identification will have Q set to an invalid (negative) value.
*/
public class Nexus
{
private String initiatorPortIdentifier;
private String targetPortIdentifier;
private long logicalUnitNumber;
private long taskTag;
/**
* Contruct an I_T Nexus identification. L and Q are set to invalid (negative) values.
* @param initiatorPortIdentifier The initiator port identifier.
* @param targetPortIdentifier The target port identifier.
*/
public Nexus(String initiatorPortIdentifier, String targetPortIdentifier)
{
super();
this.initiatorPortIdentifier = initiatorPortIdentifier;
this.targetPortIdentifier = targetPortIdentifier;
this.logicalUnitNumber = -1;
this.taskTag = -1;
}
/**
* Construct an I_T_L Nexus identification. Q is set to an invalid (negative) value.
*
* @param initiatorPortIdentifier The initiator port identifier.
* @param targetPortIdentifier The target port identifier.
* @param logicalUnitNumber The Logical Unit Number.
*/
public Nexus(String initiatorPortIdentifier, String targetPortIdentifier, long logicalUnitNumber)
{
super();
this.initiatorPortIdentifier = initiatorPortIdentifier;
this.targetPortIdentifier = targetPortIdentifier;
this.logicalUnitNumber = logicalUnitNumber;
this.taskTag = -1;
}
/**
* Construct an I_T_L_Q Nexus identification.
*
* @param initiatorPortIdentifier The initiator port identifier.
* @param targetPortIdentifier The target port identifier.
* @param logicalUnitNumber The Logical Unit Number.
* @param taskTag The task tag.
*/
public Nexus(
String initiatorPortIdentifier,
String targetPortIdentifier,
long logicalUnitNumber,
long taskTag)
{
super();
this.initiatorPortIdentifier = initiatorPortIdentifier;
this.targetPortIdentifier = targetPortIdentifier;
this.logicalUnitNumber = logicalUnitNumber;
this.taskTag = taskTag;
}
/**
* Construct an I_T_L_Q Nexus identification from an I_T_L Nexus identification and a task tag.
* A convenience constructor for use with a sequence of commands using shifting task tags on
* a stable I_T_L Nexus.
*
* @param nexus An I_T_L Nexus identification.
* @param taskTag The task tag.
*/
public Nexus(Nexus nexus, long taskTag)
{
assert nexus.logicalUnitNumber > 0 : "I_T_L_Q Nexus should be constructed from I_T_L Nexus";
this.initiatorPortIdentifier = nexus.initiatorPortIdentifier;
this.targetPortIdentifier = nexus.targetPortIdentifier;
this.logicalUnitNumber = nexus.logicalUnitNumber;
this.taskTag = taskTag;
}
/**
* The Initiator Port Identifier.
*/
public String getInitiatorPortIdentifier()
{
return initiatorPortIdentifier;
}
/**
* The Target Port Identifier.
*/
public String getTargetPortIdentifier()
{
return targetPortIdentifier;
}
/**
* The Logical Unit Number. Negative for I_T Nexus identifiers.
*/
public long getLogicalUnitNumber()
{
return logicalUnitNumber;
}
/**
* The Task Tag. Negative for I_T and I_T_L Nexus identifiers.
*/
public long getTaskTag()
{
return taskTag;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result =
prime * result
+ ((initiatorPortIdentifier == null) ? 0 : initiatorPortIdentifier.hashCode());
result = prime * result + (int) (logicalUnitNumber ^ (logicalUnitNumber >>> 32));
result =
prime * result + ((targetPortIdentifier == null) ? 0 : targetPortIdentifier.hashCode());
result = prime * result + (int) (taskTag ^ (taskTag >>> 32));
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Nexus other = (Nexus) obj;
if (initiatorPortIdentifier == null)
{
if (other.initiatorPortIdentifier != null)
return false;
}
else if (!initiatorPortIdentifier.equals(other.initiatorPortIdentifier))
return false;
if (logicalUnitNumber != other.logicalUnitNumber)
return false;
if (targetPortIdentifier == null)
{
if (other.targetPortIdentifier != null)
return false;
}
else if (!targetPortIdentifier.equals(other.targetPortIdentifier))
return false;
if (taskTag != other.taskTag)
return false;
return true;
}
@Override
public String toString()
{
String output = new String();
if (this.logicalUnitNumber == -1 || this.taskTag == -1)
{
output +=
"<I_T nexus initiatorPort: " + this.initiatorPortIdentifier + " targetPort: "
+ this.targetPortIdentifier;
}
else if (this.taskTag == -1)
{
output +=
"<I_T_L nexus initiatorPort: " + this.initiatorPortIdentifier + " targetPort: "
+ this.targetPortIdentifier + " LUN: " + this.logicalUnitNumber;
}
else
{
output +=
"<I_T_L_Q nexus initiatorPort: " + this.initiatorPortIdentifier + " targetPort: "
+ this.targetPortIdentifier + " LUN: " + this.logicalUnitNumber + " taskTag: "
+ this.taskTag;
}
output += ">";
return output;
}
}
| bsd-3-clause |
bill-baumgartner/datasource | datasource-fileparsers/src/main/java/edu/ucdenver/ccp/datasource/fileparsers/obo/impl/MiOntologyClassIterator.java | 3009 | package edu.ucdenver.ccp.datasource.fileparsers.obo.impl;
/*
* #%L
* Colorado Computational Pharmacology's common module
* %%
* Copyright (C) 2012 - 2014 Regents of the University of Colorado
* %%
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the Regents of the University of Colorado nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
import java.io.File;
import java.io.IOException;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import edu.ucdenver.ccp.common.download.HttpDownload;
import edu.ucdenver.ccp.datasource.fileparsers.obo.OntologyClassIterator;
import edu.ucdenver.ccp.datasource.fileparsers.obo.OntologyUtil;
/**
* This class iterates over the gene ontology obo file and returns OBORecords
* for each class it encounters.
*
* @author bill
*
*/
public class MiOntologyClassIterator extends OntologyClassIterator {
public static final String FILE_URL = "http://purl.obolibrary.org/obo/mi.obo";
public static final String ENCODING = "ASCII";
@HttpDownload(url = FILE_URL)
private File oboFile;
public MiOntologyClassIterator(File oboOntologyFile) throws IOException, OWLOntologyCreationException {
super(oboOntologyFile);
}
public MiOntologyClassIterator(File workDirectory, boolean clean) throws IOException,
IllegalArgumentException, IllegalAccessException, OWLOntologyCreationException {
super(workDirectory, clean);
}
@Override
protected OntologyUtil initializeOboUtilFromDownload() throws IOException, OWLOntologyCreationException {
return new OntologyUtil(oboFile);
}
public File getOboFile() {
return oboFile;
}
}
| bsd-3-clause |
navalev/azure-sdk-for-java | sdk/network/mgmt-v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/TroubleshootingDetails.java | 3575 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2018_04_01;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Information gained from troubleshooting of specified resource.
*/
public class TroubleshootingDetails {
/**
* The id of the get troubleshoot operation.
*/
@JsonProperty(value = "id")
private String id;
/**
* Reason type of failure.
*/
@JsonProperty(value = "reasonType")
private String reasonType;
/**
* A summary of troubleshooting.
*/
@JsonProperty(value = "summary")
private String summary;
/**
* Details on troubleshooting results.
*/
@JsonProperty(value = "detail")
private String detail;
/**
* List of recommended actions.
*/
@JsonProperty(value = "recommendedActions")
private List<TroubleshootingRecommendedActions> recommendedActions;
/**
* Get the id of the get troubleshoot operation.
*
* @return the id value
*/
public String id() {
return this.id;
}
/**
* Set the id of the get troubleshoot operation.
*
* @param id the id value to set
* @return the TroubleshootingDetails object itself.
*/
public TroubleshootingDetails withId(String id) {
this.id = id;
return this;
}
/**
* Get reason type of failure.
*
* @return the reasonType value
*/
public String reasonType() {
return this.reasonType;
}
/**
* Set reason type of failure.
*
* @param reasonType the reasonType value to set
* @return the TroubleshootingDetails object itself.
*/
public TroubleshootingDetails withReasonType(String reasonType) {
this.reasonType = reasonType;
return this;
}
/**
* Get a summary of troubleshooting.
*
* @return the summary value
*/
public String summary() {
return this.summary;
}
/**
* Set a summary of troubleshooting.
*
* @param summary the summary value to set
* @return the TroubleshootingDetails object itself.
*/
public TroubleshootingDetails withSummary(String summary) {
this.summary = summary;
return this;
}
/**
* Get details on troubleshooting results.
*
* @return the detail value
*/
public String detail() {
return this.detail;
}
/**
* Set details on troubleshooting results.
*
* @param detail the detail value to set
* @return the TroubleshootingDetails object itself.
*/
public TroubleshootingDetails withDetail(String detail) {
this.detail = detail;
return this;
}
/**
* Get list of recommended actions.
*
* @return the recommendedActions value
*/
public List<TroubleshootingRecommendedActions> recommendedActions() {
return this.recommendedActions;
}
/**
* Set list of recommended actions.
*
* @param recommendedActions the recommendedActions value to set
* @return the TroubleshootingDetails object itself.
*/
public TroubleshootingDetails withRecommendedActions(List<TroubleshootingRecommendedActions> recommendedActions) {
this.recommendedActions = recommendedActions;
return this;
}
}
| mit |
Yashi100/rhodes3.3.2 | platform/bb/rhodes/platform/4.2.2/com/rho/BBVersionSpecific.java | 1576 | /*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
package com.rho;
import net.rim.device.api.system.RadioInfo;
public class BBVersionSpecific {
public static boolean isWifiActive() {
// BB 4.2.2: detecting WiFi: use getActiveWAFs
int wafs = RadioInfo.getActiveWAFs();
return (wafs & RadioInfo.WAF_WLAN) != 0;
}
}
| mit |
iPGz/CardinalPGM | src/main/java/in/twizmwaz/cardinal/Cardinal.java | 17150 | package in.twizmwaz.cardinal;
import com.sk89q.bukkit.util.CommandsManagerRegistration;
import com.sk89q.minecraft.util.commands.ChatColor;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.minecraft.util.commands.CommandPermissionsException;
import com.sk89q.minecraft.util.commands.CommandUsageException;
import com.sk89q.minecraft.util.commands.CommandsManager;
import com.sk89q.minecraft.util.commands.MissingNestedCommandException;
import com.sk89q.minecraft.util.commands.WrappedCommandException;
import in.twizmwaz.cardinal.chat.ChatConstant;
import in.twizmwaz.cardinal.chat.LocaleHandler;
import in.twizmwaz.cardinal.chat.LocalizedChatMessage;
import in.twizmwaz.cardinal.command.BroadcastCommands;
import in.twizmwaz.cardinal.command.CancelCommand;
import in.twizmwaz.cardinal.command.CardinalCommand;
import in.twizmwaz.cardinal.command.ChatCommands;
import in.twizmwaz.cardinal.command.ClassCommands;
import in.twizmwaz.cardinal.command.CycleCommand;
import in.twizmwaz.cardinal.command.InventoryCommand;
import in.twizmwaz.cardinal.command.JoinCommand;
import in.twizmwaz.cardinal.command.ListCommand;
import in.twizmwaz.cardinal.command.MapCommands;
import in.twizmwaz.cardinal.command.MatchCommand;
import in.twizmwaz.cardinal.command.ModesCommand;
import in.twizmwaz.cardinal.command.PollCommands;
import in.twizmwaz.cardinal.command.PrivateMessageCommands;
import in.twizmwaz.cardinal.command.ProximityCommand;
import in.twizmwaz.cardinal.command.PunishmentCommands;
import in.twizmwaz.cardinal.command.RankCommands;
import in.twizmwaz.cardinal.command.ReadyCommand;
import in.twizmwaz.cardinal.command.RepositoryCommands;
import in.twizmwaz.cardinal.command.ScoreCommand;
import in.twizmwaz.cardinal.command.SettingCommands;
import in.twizmwaz.cardinal.command.SnowflakesCommand;
import in.twizmwaz.cardinal.command.StartAndEndCommand;
import in.twizmwaz.cardinal.command.TeamCommands;
import in.twizmwaz.cardinal.command.TeleportCommands;
import in.twizmwaz.cardinal.command.TimeLimitCommand;
import in.twizmwaz.cardinal.command.WhitelistCommands;
import in.twizmwaz.cardinal.rank.Rank;
import in.twizmwaz.cardinal.repository.RepositoryManager;
import in.twizmwaz.cardinal.repository.exception.RotationLoadException;
import in.twizmwaz.cardinal.settings.Setting;
import in.twizmwaz.cardinal.settings.SettingValue;
import in.twizmwaz.cardinal.util.ChatUtil;
import in.twizmwaz.cardinal.util.Config;
import in.twizmwaz.cardinal.util.DomUtil;
import in.twizmwaz.cardinal.util.NonModuleFactory;
import in.twizmwaz.cardinal.util.Numbers;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public class Cardinal extends JavaPlugin {
private final static String CRAFTBUKKIT_VERSION = "1.11.1-R0.1-SNAPSHOT";
private final static String MINECRAFT_VERSION = "1.11.1";
private static Cardinal instance;
private static GameHandler gameHandler;
private static LocaleHandler localeHandler;
private static Database database;
private CommandsManager<CommandSender> commands;
private File databaseFile;
// Used to store objects that are not modules, like utils that need listeners, or the TabList
private NonModuleFactory nonModules;
public static LocaleHandler getLocaleHandler() {
return localeHandler;
}
public static Cardinal getInstance() {
return instance;
}
public static Database getCardinalDatabase() {
return database;
}
public static <T> T getNonModule(Class<T> clazz) {
return instance.nonModules.getNonModule(clazz);
}
public String getPluginFileName() {
return this.getFile().getName();
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
String locale = ChatUtil.getLocale(sender);
try {
this.commands.execute(cmd.getName(), args, sender, sender);
} catch (CommandPermissionsException e) {
sender.sendMessage(ChatUtil.getWarningMessage(new LocalizedChatMessage(ChatConstant.ERROR_NO_PERMISSION).getMessage(locale)));
} catch (MissingNestedCommandException e) {
sender.sendMessage(ChatUtil.getWarningMessage(e.getUsage().replace("{cmd}", cmd.getName())));
} catch (CommandUsageException e) {
sender.sendMessage(ChatUtil.getWarningMessage(e.getMessage()));
sender.sendMessage(ChatUtil.getWarningMessage(e.getUsage()));
} catch (WrappedCommandException e) {
if (e.getCause() instanceof NumberFormatException) {
sender.sendMessage(ChatUtil.getWarningMessage(new LocalizedChatMessage(ChatConstant.ERROR_NUMBER_STRING).getMessage(locale)));
} else {
sender.sendMessage(ChatUtil.getWarningMessage(new LocalizedChatMessage(ChatConstant.ERROR_UNKNOWN_ERROR).getMessage(locale)));
e.printStackTrace();
}
} catch (CommandException e) {
sender.sendMessage(ChatUtil.getWarningMessage(ChatColor.RED + e.getMessage()));
}
return true;
}
private void setupCommands() {
this.commands = new CommandsManager<CommandSender>() {
@Override
public boolean hasPermission(CommandSender sender, String perm) {
return sender instanceof ConsoleCommandSender || sender.hasPermission(perm);
}
};
CommandsManagerRegistration cmdRegister = new CommandsManagerRegistration(this, this.commands);
cmdRegister.register(BroadcastCommands.class);
cmdRegister.register(CancelCommand.class);
cmdRegister.register(CardinalCommand.class);
cmdRegister.register(ChatCommands.class);
cmdRegister.register(ClassCommands.class);
cmdRegister.register(CycleCommand.class);
cmdRegister.register(InventoryCommand.class);
cmdRegister.register(JoinCommand.class);
cmdRegister.register(ListCommand.class);
cmdRegister.register(MapCommands.class);
cmdRegister.register(MatchCommand.class);
cmdRegister.register(ModesCommand.ModesParentCommand.class);
cmdRegister.register(PrivateMessageCommands.class);
cmdRegister.register(ProximityCommand.class);
cmdRegister.register(PunishmentCommands.class);
cmdRegister.register(RankCommands.RankParentCommand.class);
cmdRegister.register(ReadyCommand.class);
cmdRegister.register(RepositoryCommands.class);
cmdRegister.register(ScoreCommand.class);
cmdRegister.register(SettingCommands.class);
cmdRegister.register(SnowflakesCommand.class);
cmdRegister.register(StartAndEndCommand.class);
cmdRegister.register(TeamCommands.TeamParentCommand.class);
cmdRegister.register(TeamCommands.class);
cmdRegister.register(TeleportCommands.class);
cmdRegister.register(TimeLimitCommand.class);
cmdRegister.register(WhitelistCommands.WhitelistParentCommand.class);
cmdRegister.register(PollCommands.class);
}
private void checkCraftVersion() {
if (!Bukkit.getServer().getBukkitVersion().equals(CRAFTBUKKIT_VERSION)) {
getLogger().warning("########################################");
getLogger().warning("##### YOUR VERSION OF SPORTBUKKIT #####");
getLogger().warning("##### IS NOT SUPPORTED. PLEASE #####");
getLogger().warning("##### USE SPORTBUKKIT " + MINECRAFT_VERSION + " #####");
getLogger().warning("########################################");
}
}
private void deleteMatches() {
if (Config.deleteMatches) {
getLogger().info("Deleting match files, this can be disabled via the configuration");
File matches = new File("matches/");
try {
FileUtils.deleteDirectory(matches);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void reloadConfig() {
super.reloadConfig();
Config.reload(getConfig());
saveConfig();
}
private void registerSettings() {
FileConfiguration config = YamlConfiguration.loadConfiguration(new InputStreamReader(this.getResource("settings.yml"), Charsets.UTF_8));
if (config.contains("settings")) {
for (String settingName : config.getStringList("settings")) {
List<String> names = new ArrayList<>();
String description = "No description.";
List<SettingValue> values = new ArrayList<>();
names.add(settingName.trim());
if (config.contains("setting." + settingName + ".aliases")) {
for (String alias : config.getStringList("setting." + settingName + ".aliases")) {
names.add(alias.trim());
}
}
if (config.contains("setting." + settingName + ".description"))
description = config.getString("setting." + settingName + ".description");
if (config.contains("setting." + settingName + ".values")) {
for (String valueName : config.getStringList("setting." + settingName + ".values")) {
if (valueName.endsWith("[default]"))
values.add(new SettingValue(valueName.trim().substring(0, valueName.length() - 9), true));
else values.add(new SettingValue(valueName.trim(), false));
}
}
new Setting(names, description, values);
}
}
new Setting(Arrays.asList("ChatChannel"), "Choose a default chat channel.", Arrays.asList(new SettingValue("global", false), new SettingValue("team", true), new SettingValue("admin", false)));
}
public void registerRanks() {
File file = new File(getDataFolder(), "ranks.xml");
if (!file.exists()) {
try {
FileUtils.copyInputStreamToFile(getResource("ranks.xml"), file);
} catch (IOException e) {
e.printStackTrace();
getLogger().warning("Could not copy default ranks file to 'ranks.xml'.");
}
}
try {
Rank.clearRanks();
Document document = DomUtil.parse(file);
for (Element rank : document.getRootElement().getChildren("rank")) {
String name = rank.getAttributeValue("name");
boolean defaultRank = rank.getAttributeValue("default") != null && Numbers.parseBoolean(rank.getAttributeValue("default"));
boolean staffRank = false;
String parent = rank.getAttributeValue("parent");
if (parent != null) {
for (Element element : document.getRootElement().getChildren("rank")) {
String elementName = element.getAttributeValue("name");
if (elementName.equalsIgnoreCase(parent) || elementName.toLowerCase().startsWith(parent.toLowerCase())) {
staffRank = element.getAttributeValue("staff") != null && Numbers.parseBoolean(element.getAttributeValue("staff"));
}
}
if (rank.getAttributeValue("staff") != null) {
staffRank = Numbers.parseBoolean(rank.getAttributeValue("staff"));
}
} else {
staffRank = rank.getAttributeValue("staff") != null && Numbers.parseBoolean(rank.getAttributeValue("staff"));
}
String flair = rank.getAttributeValue("flair") != null ? ChatColor.translateAlternateColorCodes('`', rank.getAttributeValue("flair")) : "";
List<String> permissions = new ArrayList<>(), disabledPermissions = new ArrayList<>();
for (Element permission : rank.getChildren("permission")) {
if (permission.getText().startsWith("-")) {
disabledPermissions.add(permission.getText().substring(1));
} else {
permissions.add(permission.getText());
}
}
new Rank(name, defaultRank, staffRank, flair, permissions, disabledPermissions, parent);
}
for (Rank rank : Rank.getRanks()) {
if (rank.getParent() != null &&
Rank.getRank(rank.getParent()) != null &&
Rank.getRank(rank.getParent()).getParent() != null &&
Rank.getRank(Rank.getRank(rank.getParent()).getParent()) != null &&
Rank.getRank(Rank.getRank(rank.getParent()).getParent()).equals(rank)) {
getLogger().warning("Rank inheritance processes were terminated because " + rank.getName() + " and " + Rank.getRank(rank.getParent()).getName() + " are parents of each other, which cannot occur.");
return;
}
}
List<Rank> completed = new ArrayList<>();
for (Rank rank : Rank.getRanks()) {
if (rank.getParent() == null) {
completed.add(rank);
}
}
while (!completed.containsAll(Rank.getRanks())) {
Rank inheriting = null;
for (Rank rank : Rank.getRanks()) {
if (!completed.contains(rank) && rank.getParent() != null && completed.contains(Rank.getRank(rank.getParent()))) {
inheriting = rank;
}
}
for (String permission : Rank.getRank(inheriting.getParent()).getPermissions()) {
inheriting.addPermission(permission);
}
completed.add(inheriting);
}
} catch (JDOMException | IOException e) {
e.printStackTrace();
getLogger().warning("Could not parse file 'ranks.xml' for ranks.");
}
}
@Override
public void onEnable() {
instance = this;
checkCraftVersion();
try {
localeHandler = new LocaleHandler(this);
} catch (IOException | JDOMException e) {
e.printStackTrace();
getLogger().severe("Failed to initialize because of invalid language files. Please make sure all language files in the plugin are present.");
setEnabled(false);
return;
}
getDataFolder().mkdir();
databaseFile = new File(getDataFolder(), "database.xml");
if (databaseFile.exists()) {
try {
database = Database.loadFromFile(databaseFile);
} catch (JDOMException | IOException e) {
e.printStackTrace();
getLogger().severe("Failed to initialize because of an IOException. Please try restarting your server.");
setEnabled(false);
return;
}
} else {
database = Database.newInstance(databaseFile);
}
Config.reload(getConfig());
saveConfig();
deleteMatches();
registerSettings();
registerRanks();
setupCommands();
nonModules = new NonModuleFactory();
try {
gameHandler = new GameHandler();
gameHandler.load();
} catch (RotationLoadException e) {
e.printStackTrace();
getLogger().severe(new LocalizedChatMessage(ChatConstant.GENERIC_REPO_RELOAD_FAIL, "" + RepositoryManager.get().getMapSize()).getMessage(Locale.getDefault().toString()));
setEnabled(false);
return;
}
if (Config.resetSpawnProtection && Bukkit.getServer().getSpawnRadius() != 0) {
Bukkit.getServer().setSpawnRadius(0);
}
}
@Override
public void onDisable() {
database.save(databaseFile);
saveConfig();
}
public GameHandler getGameHandler() {
return gameHandler;
}
public JavaPlugin getPlugin() {
return this;
}
public static String getNewRepoPath(String repoName) {
String reposPath = Cardinal.getInstance().getDataFolder().getAbsolutePath() +
File.separator + "repositories" + File.separator + repoName;
File repo = new File(reposPath);
if (!repo.exists()) repo.mkdirs();
return reposPath;
}
}
| mit |
navalev/azure-sdk-for-java | sdk/automation/mgmt-v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/ConnectionTypesImpl.java | 2985 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*
*/
package com.microsoft.azure.management.automation.v2015_10_31.implementation;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import com.microsoft.azure.management.automation.v2015_10_31.ConnectionTypes;
import rx.Completable;
import rx.Observable;
import rx.functions.Func1;
import com.microsoft.azure.Page;
import com.microsoft.azure.management.automation.v2015_10_31.ConnectionType;
class ConnectionTypesImpl extends WrapperImpl<ConnectionTypesInner> implements ConnectionTypes {
private final AutomationManager manager;
ConnectionTypesImpl(AutomationManager manager) {
super(manager.inner().connectionTypes());
this.manager = manager;
}
public AutomationManager manager() {
return this.manager;
}
@Override
public ConnectionTypeImpl define(String name) {
return wrapModel(name);
}
private ConnectionTypeImpl wrapModel(ConnectionTypeInner inner) {
return new ConnectionTypeImpl(inner, manager());
}
private ConnectionTypeImpl wrapModel(String name) {
return new ConnectionTypeImpl(name, this.manager());
}
@Override
public Observable<ConnectionType> listByAutomationAccountAsync(final String resourceGroupName, final String automationAccountName) {
ConnectionTypesInner client = this.inner();
return client.listByAutomationAccountAsync(resourceGroupName, automationAccountName)
.flatMapIterable(new Func1<Page<ConnectionTypeInner>, Iterable<ConnectionTypeInner>>() {
@Override
public Iterable<ConnectionTypeInner> call(Page<ConnectionTypeInner> page) {
return page.items();
}
})
.map(new Func1<ConnectionTypeInner, ConnectionType>() {
@Override
public ConnectionType call(ConnectionTypeInner inner) {
return wrapModel(inner);
}
});
}
@Override
public Observable<ConnectionType> getAsync(String resourceGroupName, String automationAccountName, String connectionTypeName) {
ConnectionTypesInner client = this.inner();
return client.getAsync(resourceGroupName, automationAccountName, connectionTypeName)
.map(new Func1<ConnectionTypeInner, ConnectionType>() {
@Override
public ConnectionType call(ConnectionTypeInner inner) {
return wrapModel(inner);
}
});
}
@Override
public Completable deleteAsync(String resourceGroupName, String automationAccountName, String connectionTypeName) {
ConnectionTypesInner client = this.inner();
return client.deleteAsync(resourceGroupName, automationAccountName, connectionTypeName).toCompletable();
}
}
| mit |
navalev/azure-sdk-for-java | sdk/network/mgmt-v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/RouteInner.java | 5938 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2017_10_01.implementation;
import com.microsoft.azure.management.network.v2017_10_01.RouteNextHopType;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.azure.SubResource;
/**
* Route resource.
*/
@JsonFlatten
public class RouteInner extends SubResource {
/**
* The destination CIDR to which the route applies.
*/
@JsonProperty(value = "properties.addressPrefix")
private String addressPrefix;
/**
* The type of Azure hop the packet should be sent to. Possible values are:
* 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance',
* and 'None'. Possible values include: 'VirtualNetworkGateway',
* 'VnetLocal', 'Internet', 'VirtualAppliance', 'None'.
*/
@JsonProperty(value = "properties.nextHopType", required = true)
private RouteNextHopType nextHopType;
/**
* The IP address packets should be forwarded to. Next hop values are only
* allowed in routes where the next hop type is VirtualAppliance.
*/
@JsonProperty(value = "properties.nextHopIpAddress")
private String nextHopIpAddress;
/**
* The provisioning state of the resource. Possible values are: 'Updating',
* 'Deleting', and 'Failed'.
*/
@JsonProperty(value = "properties.provisioningState")
private String provisioningState;
/**
* The name of the resource that is unique within a resource group. This
* name can be used to access the resource.
*/
@JsonProperty(value = "name")
private String name;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
@JsonProperty(value = "etag")
private String etag;
/**
* Get the destination CIDR to which the route applies.
*
* @return the addressPrefix value
*/
public String addressPrefix() {
return this.addressPrefix;
}
/**
* Set the destination CIDR to which the route applies.
*
* @param addressPrefix the addressPrefix value to set
* @return the RouteInner object itself.
*/
public RouteInner withAddressPrefix(String addressPrefix) {
this.addressPrefix = addressPrefix;
return this;
}
/**
* Get the type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. Possible values include: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', 'None'.
*
* @return the nextHopType value
*/
public RouteNextHopType nextHopType() {
return this.nextHopType;
}
/**
* Set the type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. Possible values include: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', 'None'.
*
* @param nextHopType the nextHopType value to set
* @return the RouteInner object itself.
*/
public RouteInner withNextHopType(RouteNextHopType nextHopType) {
this.nextHopType = nextHopType;
return this;
}
/**
* Get the IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is VirtualAppliance.
*
* @return the nextHopIpAddress value
*/
public String nextHopIpAddress() {
return this.nextHopIpAddress;
}
/**
* Set the IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is VirtualAppliance.
*
* @param nextHopIpAddress the nextHopIpAddress value to set
* @return the RouteInner object itself.
*/
public RouteInner withNextHopIpAddress(String nextHopIpAddress) {
this.nextHopIpAddress = nextHopIpAddress;
return this;
}
/**
* Get the provisioning state of the resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
*
* @return the provisioningState value
*/
public String provisioningState() {
return this.provisioningState;
}
/**
* Set the provisioning state of the resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
*
* @param provisioningState the provisioningState value to set
* @return the RouteInner object itself.
*/
public RouteInner withProvisioningState(String provisioningState) {
this.provisioningState = provisioningState;
return this;
}
/**
* Get the name of the resource that is unique within a resource group. This name can be used to access the resource.
*
* @return the name value
*/
public String name() {
return this.name;
}
/**
* Set the name of the resource that is unique within a resource group. This name can be used to access the resource.
*
* @param name the name value to set
* @return the RouteInner object itself.
*/
public RouteInner withName(String name) {
this.name = name;
return this;
}
/**
* Get a unique read-only string that changes whenever the resource is updated.
*
* @return the etag value
*/
public String etag() {
return this.etag;
}
/**
* Set a unique read-only string that changes whenever the resource is updated.
*
* @param etag the etag value to set
* @return the RouteInner object itself.
*/
public RouteInner withEtag(String etag) {
this.etag = etag;
return this;
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/storage/azure-storage-file-datalake/src/main/java/com/azure/storage/file/datalake/models/LeaseStatusType.java | 1148 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.storage.file.datalake.models;
/**
* Defines values for LeaseStatusType.
*/
public enum LeaseStatusType {
/**
* Enum value locked.
*/
LOCKED("locked"),
/**
* Enum value unlocked.
*/
UNLOCKED("unlocked");
/**
* The actual serialized value for a LeaseStatusType instance.
*/
private final String value;
LeaseStatusType(String value) {
this.value = value;
}
/**
* Parses a serialized value to a LeaseStatusType instance.
*
* @param value the serialized value to parse.
* @return the parsed LeaseStatusType object, or null if unable to parse.
*/
public static LeaseStatusType fromString(String value) {
LeaseStatusType[] items = LeaseStatusType.values();
for (LeaseStatusType item : items) {
if (item.toString().equalsIgnoreCase(value)) {
return item;
}
}
return null;
}
@Override
public String toString() {
return this.value;
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/NetworkManager.java | 20499 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2017_10_01.implementation;
import com.microsoft.azure.AzureEnvironment;
import com.microsoft.azure.AzureResponseBuilder;
import com.microsoft.azure.credentials.AzureTokenCredentials;
import com.microsoft.azure.management.apigeneration.Beta;
import com.microsoft.azure.management.apigeneration.Beta.SinceVersion;
import com.microsoft.azure.arm.resources.AzureConfigurable;
import com.microsoft.azure.serializer.AzureJacksonAdapter;
import com.microsoft.rest.RestClient;
import com.microsoft.azure.management.network.v2017_10_01.ApplicationGateways;
import com.microsoft.azure.management.network.v2017_10_01.ApplicationSecurityGroups;
import com.microsoft.azure.management.network.v2017_10_01.AvailableEndpointServices;
import com.microsoft.azure.management.network.v2017_10_01.ExpressRouteCircuitAuthorizations;
import com.microsoft.azure.management.network.v2017_10_01.ExpressRouteCircuitPeerings;
import com.microsoft.azure.management.network.v2017_10_01.ExpressRouteCircuits;
import com.microsoft.azure.management.network.v2017_10_01.ExpressRouteServiceProviders;
import com.microsoft.azure.management.network.v2017_10_01.LoadBalancers;
import com.microsoft.azure.management.network.v2017_10_01.LoadBalancerBackendAddressPools;
import com.microsoft.azure.management.network.v2017_10_01.LoadBalancerFrontendIPConfigurations;
import com.microsoft.azure.management.network.v2017_10_01.InboundNatRules;
import com.microsoft.azure.management.network.v2017_10_01.LoadBalancerLoadBalancingRules;
import com.microsoft.azure.management.network.v2017_10_01.LoadBalancerNetworkInterfaces;
import com.microsoft.azure.management.network.v2017_10_01.LoadBalancerProbes;
import com.microsoft.azure.management.network.v2017_10_01.NetworkInterfaces;
import com.microsoft.azure.management.network.v2017_10_01.NetworkInterfaceIPConfigurations;
import com.microsoft.azure.management.network.v2017_10_01.NetworkInterfaceLoadBalancers;
import com.microsoft.azure.management.network.v2017_10_01.NetworkSecurityGroups;
import com.microsoft.azure.management.network.v2017_10_01.SecurityRules;
import com.microsoft.azure.management.network.v2017_10_01.DefaultSecurityRules;
import com.microsoft.azure.management.network.v2017_10_01.NetworkWatchers;
import com.microsoft.azure.management.network.v2017_10_01.PacketCaptures;
import com.microsoft.azure.management.network.v2017_10_01.ConnectionMonitors;
import com.microsoft.azure.management.network.v2017_10_01.Operations;
import com.microsoft.azure.management.network.v2017_10_01.PublicIPAddresses;
import com.microsoft.azure.management.network.v2017_10_01.RouteFilters;
import com.microsoft.azure.management.network.v2017_10_01.RouteFilterRules;
import com.microsoft.azure.management.network.v2017_10_01.RouteTables;
import com.microsoft.azure.management.network.v2017_10_01.Routes;
import com.microsoft.azure.management.network.v2017_10_01.BgpServiceCommunities;
import com.microsoft.azure.management.network.v2017_10_01.Usages;
import com.microsoft.azure.management.network.v2017_10_01.VirtualNetworks;
import com.microsoft.azure.management.network.v2017_10_01.Subnets;
import com.microsoft.azure.management.network.v2017_10_01.VirtualNetworkPeerings;
import com.microsoft.azure.management.network.v2017_10_01.VirtualNetworkGateways;
import com.microsoft.azure.management.network.v2017_10_01.VirtualNetworkGatewayConnections;
import com.microsoft.azure.management.network.v2017_10_01.LocalNetworkGateways;
import com.microsoft.azure.arm.resources.implementation.AzureConfigurableCoreImpl;
import com.microsoft.azure.arm.resources.implementation.ManagerCore;
/**
* Entry point to Azure Network resource management.
*/
public final class NetworkManager extends ManagerCore<NetworkManager, NetworkManagementClientImpl> {
private ApplicationGateways applicationGateways;
private ApplicationSecurityGroups applicationSecurityGroups;
private AvailableEndpointServices availableEndpointServices;
private ExpressRouteCircuitAuthorizations expressRouteCircuitAuthorizations;
private ExpressRouteCircuitPeerings expressRouteCircuitPeerings;
private ExpressRouteCircuits expressRouteCircuits;
private ExpressRouteServiceProviders expressRouteServiceProviders;
private LoadBalancers loadBalancers;
private LoadBalancerBackendAddressPools loadBalancerBackendAddressPools;
private LoadBalancerFrontendIPConfigurations loadBalancerFrontendIPConfigurations;
private InboundNatRules inboundNatRules;
private LoadBalancerLoadBalancingRules loadBalancerLoadBalancingRules;
private LoadBalancerNetworkInterfaces loadBalancerNetworkInterfaces;
private LoadBalancerProbes loadBalancerProbes;
private NetworkInterfaces networkInterfaces;
private NetworkInterfaceIPConfigurations networkInterfaceIPConfigurations;
private NetworkInterfaceLoadBalancers networkInterfaceLoadBalancers;
private NetworkSecurityGroups networkSecurityGroups;
private SecurityRules securityRules;
private DefaultSecurityRules defaultSecurityRules;
private NetworkWatchers networkWatchers;
private PacketCaptures packetCaptures;
private ConnectionMonitors connectionMonitors;
private Operations operations;
private PublicIPAddresses publicIPAddresses;
private RouteFilters routeFilters;
private RouteFilterRules routeFilterRules;
private RouteTables routeTables;
private Routes routes;
private BgpServiceCommunities bgpServiceCommunities;
private Usages usages;
private VirtualNetworks virtualNetworks;
private Subnets subnets;
private VirtualNetworkPeerings virtualNetworkPeerings;
private VirtualNetworkGateways virtualNetworkGateways;
private VirtualNetworkGatewayConnections virtualNetworkGatewayConnections;
private LocalNetworkGateways localNetworkGateways;
/**
* Get a Configurable instance that can be used to create NetworkManager with optional configuration.
*
* @return the instance allowing configurations
*/
public static Configurable configure() {
return new NetworkManager.ConfigurableImpl();
}
/**
* Creates an instance of NetworkManager that exposes Network resource management API entry points.
*
* @param credentials the credentials to use
* @param subscriptionId the subscription UUID
* @return the NetworkManager
*/
public static NetworkManager authenticate(AzureTokenCredentials credentials, String subscriptionId) {
return new NetworkManager(new RestClient.Builder()
.withBaseUrl(credentials.environment(), AzureEnvironment.Endpoint.RESOURCE_MANAGER)
.withCredentials(credentials)
.withSerializerAdapter(new AzureJacksonAdapter())
.withResponseBuilderFactory(new AzureResponseBuilder.Factory())
.build(), subscriptionId);
}
/**
* Creates an instance of NetworkManager that exposes Network resource management API entry points.
*
* @param restClient the RestClient to be used for API calls.
* @param subscriptionId the subscription UUID
* @return the NetworkManager
*/
public static NetworkManager authenticate(RestClient restClient, String subscriptionId) {
return new NetworkManager(restClient, subscriptionId);
}
/**
* The interface allowing configurations to be set.
*/
public interface Configurable extends AzureConfigurable<Configurable> {
/**
* Creates an instance of NetworkManager that exposes Network management API entry points.
*
* @param credentials the credentials to use
* @param subscriptionId the subscription UUID
* @return the interface exposing Network management API entry points that work across subscriptions
*/
NetworkManager authenticate(AzureTokenCredentials credentials, String subscriptionId);
}
/**
* @return Entry point to manage ApplicationGateways.
*/
public ApplicationGateways applicationGateways() {
if (this.applicationGateways == null) {
this.applicationGateways = new ApplicationGatewaysImpl(this);
}
return this.applicationGateways;
}
/**
* @return Entry point to manage ApplicationSecurityGroups.
*/
public ApplicationSecurityGroups applicationSecurityGroups() {
if (this.applicationSecurityGroups == null) {
this.applicationSecurityGroups = new ApplicationSecurityGroupsImpl(this);
}
return this.applicationSecurityGroups;
}
/**
* @return Entry point to manage AvailableEndpointServices.
*/
public AvailableEndpointServices availableEndpointServices() {
if (this.availableEndpointServices == null) {
this.availableEndpointServices = new AvailableEndpointServicesImpl(this);
}
return this.availableEndpointServices;
}
/**
* @return Entry point to manage ExpressRouteCircuitAuthorizations.
*/
public ExpressRouteCircuitAuthorizations expressRouteCircuitAuthorizations() {
if (this.expressRouteCircuitAuthorizations == null) {
this.expressRouteCircuitAuthorizations = new ExpressRouteCircuitAuthorizationsImpl(this);
}
return this.expressRouteCircuitAuthorizations;
}
/**
* @return Entry point to manage ExpressRouteCircuitPeerings.
*/
public ExpressRouteCircuitPeerings expressRouteCircuitPeerings() {
if (this.expressRouteCircuitPeerings == null) {
this.expressRouteCircuitPeerings = new ExpressRouteCircuitPeeringsImpl(this);
}
return this.expressRouteCircuitPeerings;
}
/**
* @return Entry point to manage ExpressRouteCircuits.
*/
public ExpressRouteCircuits expressRouteCircuits() {
if (this.expressRouteCircuits == null) {
this.expressRouteCircuits = new ExpressRouteCircuitsImpl(this);
}
return this.expressRouteCircuits;
}
/**
* @return Entry point to manage ExpressRouteServiceProviders.
*/
public ExpressRouteServiceProviders expressRouteServiceProviders() {
if (this.expressRouteServiceProviders == null) {
this.expressRouteServiceProviders = new ExpressRouteServiceProvidersImpl(this);
}
return this.expressRouteServiceProviders;
}
/**
* @return Entry point to manage LoadBalancers.
*/
public LoadBalancers loadBalancers() {
if (this.loadBalancers == null) {
this.loadBalancers = new LoadBalancersImpl(this);
}
return this.loadBalancers;
}
/**
* @return Entry point to manage LoadBalancerBackendAddressPools.
*/
public LoadBalancerBackendAddressPools loadBalancerBackendAddressPools() {
if (this.loadBalancerBackendAddressPools == null) {
this.loadBalancerBackendAddressPools = new LoadBalancerBackendAddressPoolsImpl(this);
}
return this.loadBalancerBackendAddressPools;
}
/**
* @return Entry point to manage LoadBalancerFrontendIPConfigurations.
*/
public LoadBalancerFrontendIPConfigurations loadBalancerFrontendIPConfigurations() {
if (this.loadBalancerFrontendIPConfigurations == null) {
this.loadBalancerFrontendIPConfigurations = new LoadBalancerFrontendIPConfigurationsImpl(this);
}
return this.loadBalancerFrontendIPConfigurations;
}
/**
* @return Entry point to manage InboundNatRules.
*/
public InboundNatRules inboundNatRules() {
if (this.inboundNatRules == null) {
this.inboundNatRules = new InboundNatRulesImpl(this);
}
return this.inboundNatRules;
}
/**
* @return Entry point to manage LoadBalancerLoadBalancingRules.
*/
public LoadBalancerLoadBalancingRules loadBalancerLoadBalancingRules() {
if (this.loadBalancerLoadBalancingRules == null) {
this.loadBalancerLoadBalancingRules = new LoadBalancerLoadBalancingRulesImpl(this);
}
return this.loadBalancerLoadBalancingRules;
}
/**
* @return Entry point to manage LoadBalancerNetworkInterfaces.
*/
public LoadBalancerNetworkInterfaces loadBalancerNetworkInterfaces() {
if (this.loadBalancerNetworkInterfaces == null) {
this.loadBalancerNetworkInterfaces = new LoadBalancerNetworkInterfacesImpl(this);
}
return this.loadBalancerNetworkInterfaces;
}
/**
* @return Entry point to manage LoadBalancerProbes.
*/
public LoadBalancerProbes loadBalancerProbes() {
if (this.loadBalancerProbes == null) {
this.loadBalancerProbes = new LoadBalancerProbesImpl(this);
}
return this.loadBalancerProbes;
}
/**
* @return Entry point to manage NetworkInterfaces.
*/
public NetworkInterfaces networkInterfaces() {
if (this.networkInterfaces == null) {
this.networkInterfaces = new NetworkInterfacesImpl(this);
}
return this.networkInterfaces;
}
/**
* @return Entry point to manage NetworkInterfaceIPConfigurations.
*/
public NetworkInterfaceIPConfigurations networkInterfaceIPConfigurations() {
if (this.networkInterfaceIPConfigurations == null) {
this.networkInterfaceIPConfigurations = new NetworkInterfaceIPConfigurationsImpl(this);
}
return this.networkInterfaceIPConfigurations;
}
/**
* @return Entry point to manage NetworkInterfaceLoadBalancers.
*/
public NetworkInterfaceLoadBalancers networkInterfaceLoadBalancers() {
if (this.networkInterfaceLoadBalancers == null) {
this.networkInterfaceLoadBalancers = new NetworkInterfaceLoadBalancersImpl(this);
}
return this.networkInterfaceLoadBalancers;
}
/**
* @return Entry point to manage NetworkSecurityGroups.
*/
public NetworkSecurityGroups networkSecurityGroups() {
if (this.networkSecurityGroups == null) {
this.networkSecurityGroups = new NetworkSecurityGroupsImpl(this);
}
return this.networkSecurityGroups;
}
/**
* @return Entry point to manage SecurityRules.
*/
public SecurityRules securityRules() {
if (this.securityRules == null) {
this.securityRules = new SecurityRulesImpl(this);
}
return this.securityRules;
}
/**
* @return Entry point to manage DefaultSecurityRules.
*/
public DefaultSecurityRules defaultSecurityRules() {
if (this.defaultSecurityRules == null) {
this.defaultSecurityRules = new DefaultSecurityRulesImpl(this);
}
return this.defaultSecurityRules;
}
/**
* @return Entry point to manage NetworkWatchers.
*/
public NetworkWatchers networkWatchers() {
if (this.networkWatchers == null) {
this.networkWatchers = new NetworkWatchersImpl(this);
}
return this.networkWatchers;
}
/**
* @return Entry point to manage PacketCaptures.
*/
public PacketCaptures packetCaptures() {
if (this.packetCaptures == null) {
this.packetCaptures = new PacketCapturesImpl(this);
}
return this.packetCaptures;
}
/**
* @return Entry point to manage ConnectionMonitors.
*/
public ConnectionMonitors connectionMonitors() {
if (this.connectionMonitors == null) {
this.connectionMonitors = new ConnectionMonitorsImpl(this);
}
return this.connectionMonitors;
}
/**
* @return Entry point to manage Operations.
*/
public Operations operations() {
if (this.operations == null) {
this.operations = new OperationsImpl(this);
}
return this.operations;
}
/**
* @return Entry point to manage PublicIPAddresses.
*/
public PublicIPAddresses publicIPAddresses() {
if (this.publicIPAddresses == null) {
this.publicIPAddresses = new PublicIPAddressesImpl(this);
}
return this.publicIPAddresses;
}
/**
* @return Entry point to manage RouteFilters.
*/
public RouteFilters routeFilters() {
if (this.routeFilters == null) {
this.routeFilters = new RouteFiltersImpl(this);
}
return this.routeFilters;
}
/**
* @return Entry point to manage RouteFilterRules.
*/
public RouteFilterRules routeFilterRules() {
if (this.routeFilterRules == null) {
this.routeFilterRules = new RouteFilterRulesImpl(this);
}
return this.routeFilterRules;
}
/**
* @return Entry point to manage RouteTables.
*/
public RouteTables routeTables() {
if (this.routeTables == null) {
this.routeTables = new RouteTablesImpl(this);
}
return this.routeTables;
}
/**
* @return Entry point to manage Routes.
*/
public Routes routes() {
if (this.routes == null) {
this.routes = new RoutesImpl(this);
}
return this.routes;
}
/**
* @return Entry point to manage BgpServiceCommunities.
*/
public BgpServiceCommunities bgpServiceCommunities() {
if (this.bgpServiceCommunities == null) {
this.bgpServiceCommunities = new BgpServiceCommunitiesImpl(this);
}
return this.bgpServiceCommunities;
}
/**
* @return Entry point to manage Usages.
*/
public Usages usages() {
if (this.usages == null) {
this.usages = new UsagesImpl(this);
}
return this.usages;
}
/**
* @return Entry point to manage VirtualNetworks.
*/
public VirtualNetworks virtualNetworks() {
if (this.virtualNetworks == null) {
this.virtualNetworks = new VirtualNetworksImpl(this);
}
return this.virtualNetworks;
}
/**
* @return Entry point to manage Subnets.
*/
public Subnets subnets() {
if (this.subnets == null) {
this.subnets = new SubnetsImpl(this);
}
return this.subnets;
}
/**
* @return Entry point to manage VirtualNetworkPeerings.
*/
public VirtualNetworkPeerings virtualNetworkPeerings() {
if (this.virtualNetworkPeerings == null) {
this.virtualNetworkPeerings = new VirtualNetworkPeeringsImpl(this);
}
return this.virtualNetworkPeerings;
}
/**
* @return Entry point to manage VirtualNetworkGateways.
*/
public VirtualNetworkGateways virtualNetworkGateways() {
if (this.virtualNetworkGateways == null) {
this.virtualNetworkGateways = new VirtualNetworkGatewaysImpl(this);
}
return this.virtualNetworkGateways;
}
/**
* @return Entry point to manage VirtualNetworkGatewayConnections.
*/
public VirtualNetworkGatewayConnections virtualNetworkGatewayConnections() {
if (this.virtualNetworkGatewayConnections == null) {
this.virtualNetworkGatewayConnections = new VirtualNetworkGatewayConnectionsImpl(this);
}
return this.virtualNetworkGatewayConnections;
}
/**
* @return Entry point to manage LocalNetworkGateways.
*/
public LocalNetworkGateways localNetworkGateways() {
if (this.localNetworkGateways == null) {
this.localNetworkGateways = new LocalNetworkGatewaysImpl(this);
}
return this.localNetworkGateways;
}
/**
* The implementation for Configurable interface.
*/
private static final class ConfigurableImpl extends AzureConfigurableCoreImpl<Configurable> implements Configurable {
public NetworkManager authenticate(AzureTokenCredentials credentials, String subscriptionId) {
return NetworkManager.authenticate(buildRestClient(credentials), subscriptionId);
}
}
private NetworkManager(RestClient restClient, String subscriptionId) {
super(
restClient,
subscriptionId,
new NetworkManagementClientImpl(restClient).withSubscriptionId(subscriptionId));
}
}
| mit |
jenkinsci/ownership-plugin | src/main/java/org/jenkinsci/plugins/ownership/model/folders/FolderOwnershipDescriptionSource.java | 1801 | /*
* The MIT License
*
* Copyright (c) 2016 Oleg Nenashev.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.ownership.model.folders;
import com.cloudbees.hudson.plugins.folder.AbstractFolder;
import com.synopsys.arc.jenkins.plugins.ownership.OwnershipDescription;
import javax.annotation.CheckForNull;
import org.jenkinsci.plugins.ownership.model.OwnershipDescriptionSource;
/**
* References {@link OwnershipDescription}s provided by various {@link AbstractFolder}s.
* @author Oleg Nenashev
* @since 0.9
*/
public class FolderOwnershipDescriptionSource extends OwnershipDescriptionSource<AbstractFolder<?>> {
public FolderOwnershipDescriptionSource(@CheckForNull AbstractFolder<?> item) {
super(item);
}
}
| mit |
georghinkel/ttc2017smartGrids | solutions/eMoflon/rgse.ttc17.solution/src/com/beust/jcommander/Parameters.java | 1957 | /**
* Copyright (C) 2010 the original author or authors.
* See the notice.md file distributed with this work for additional
* information regarding copyright ownership.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.beust.jcommander;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
/**
* An annotation used to specify settings for parameter parsing.
*
* @author cbeust
*/
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({ TYPE })
@Inherited
public @interface Parameters {
/**
* The name of the resource bundle to use for this class.
*/
String resourceBundle() default "";
/**
* The character(s) that separate options.
*/
String separators() default " ";
/**
* If the annotated class was added to {@link JCommander} as a command with
* {@link JCommander#addCommand}, then this string will be displayed in the
* description when @{link JCommander#usage} is invoked.
*/
String commandDescription() default "";
/**
* @return the key used to find the command description in the resource bundle.
*/
String commandDescriptionKey() default "";
/**
* An array of allowed command names.
*/
String[] commandNames() default {};
/**
* If true, this command won't appear in the usage().
*/
boolean hidden() default false;
}
| mit |
csmith/DMDirc-Parser | common/src/main/java/com/dmdirc/parser/events/ErrorInfoEvent.java | 1766 | /*
* Copyright (c) 2006-2017 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.parser.events;
import com.dmdirc.parser.common.ParserError;
import com.dmdirc.parser.interfaces.Parser;
import java.time.LocalDateTime;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Called to give Error Information.
*/
public class ErrorInfoEvent extends ParserEvent {
private final ParserError errorInfo;
public ErrorInfoEvent(final Parser parser, final LocalDateTime date,
final ParserError errorInfo) {
super(parser, date);
this.errorInfo = checkNotNull(errorInfo);
}
public ParserError getErrorInfo() {
return errorInfo;
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/core/azure-core/src/main/java/com/azure/core/util/package-info.java | 178 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/**
* Package containing core utility classes.
*/
package com.azure.core.util;
| mit |
jonathangerbaud/Klyph | Klyph Core/src/com/abewy/android/apps/klyph/core/fql/serializer/UnifiedThreadDeserializer.java | 1237 | package com.abewy.android.apps.klyph.core.fql.serializer;
import org.json.JSONObject;
import com.abewy.android.apps.klyph.core.fql.UnifiedThread;
import com.abewy.android.apps.klyph.core.fql.UnifiedThread.Sender;
import com.abewy.android.apps.klyph.core.graph.GraphObject;
public class UnifiedThreadDeserializer extends Deserializer
{
@Override
public GraphObject deserializeObject(JSONObject data)
{
UnifiedThread thread = new UnifiedThread();
deserializePrimitives(thread, data);
thread.setSnippet_sender((Sender) new SenderDeserializer().deserializeObject(getJsonObject(data, "sender")));
thread.setParticipants(new SenderDeserializer().deserializeArray(getJsonArray(data, "participants"), Sender.class));
thread.setSenders(new SenderDeserializer().deserializeArray(getJsonArray(data, "senders"), Sender.class));
thread.setThread_participants(new SenderDeserializer().deserializeArray(getJsonArray(data, "thread_participants"), Sender.class));
return thread;
}
private static class SenderDeserializer extends Deserializer
{
@Override
public GraphObject deserializeObject(JSONObject data)
{
Sender sender = new Sender();
deserializePrimitives(sender, data);
return sender;
}
}
}
| mit |
Azure/azure-sdk-for-java | sdk/resourcemanagerhybrid/azure-resourcemanager-monitor/src/main/java/com/azure/resourcemanager/monitor/implementation/MetricAlertConditionBaseImpl.java | 3452 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.resourcemanager.monitor.implementation;
import com.azure.resourcemanager.monitor.models.MetricAlertRuleTimeAggregation;
import com.azure.resourcemanager.monitor.models.MetricDimension;
import com.azure.resourcemanager.monitor.models.MultiMetricCriteria;
import com.azure.resourcemanager.resources.fluentcore.model.implementation.WrapperImpl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.TreeMap;
/**
* Base class for MetricAlertConditionImpl and MetricDynamicAlertConditionImpl.
*
* @param <InnerT> inner class, MetricCriteria or DynamicMetricCriteria
* @param <SubclassT> subclass, i.e., MetricAlertConditionImpl or MetricDynamicAlertConditionImpl
*/
class MetricAlertConditionBaseImpl<
InnerT extends MultiMetricCriteria, SubclassT extends MetricAlertConditionBaseImpl<InnerT, SubclassT>>
extends WrapperImpl<InnerT> {
protected final MetricAlertImpl parent;
protected final TreeMap<String, MetricDimension> dimensions;
protected MetricAlertConditionBaseImpl(String name, InnerT innerObject, MetricAlertImpl parent) {
super(innerObject);
this.innerModel().withName(name);
this.parent = parent;
this.dimensions = new TreeMap<>();
if (this.innerModel().dimensions() != null) {
for (MetricDimension md : this.innerModel().dimensions()) {
dimensions.put(md.name(), md);
}
}
}
public String name() {
return this.innerModel().name();
}
public String metricName() {
return this.innerModel().metricName();
}
public String metricNamespace() {
return this.innerModel().metricNamespace();
}
public MetricAlertRuleTimeAggregation timeAggregation() {
return MetricAlertRuleTimeAggregation.fromString(this.innerModel().timeAggregation().toString());
}
public Collection<MetricDimension> dimensions() {
return Collections.unmodifiableCollection(this.innerModel().dimensions());
}
public MetricAlertImpl parent() {
this.innerModel().withDimensions(new ArrayList<>(this.dimensions.values()));
return this.parent;
}
@SuppressWarnings("unchecked")
public SubclassT withMetricName(String metricName) {
this.innerModel().withMetricName(metricName);
return (SubclassT) this;
}
public SubclassT withMetricName(String metricName, String metricNamespace) {
this.innerModel().withMetricNamespace(metricNamespace);
return this.withMetricName(metricName);
}
@SuppressWarnings("unchecked")
public SubclassT withDimension(String dimensionName, String... values) {
if (this.dimensions.containsKey(dimensionName)) {
dimensions.remove(dimensionName);
}
MetricDimension md = new MetricDimension();
md.withName(dimensionName);
md.withOperator("Include");
md.withValues(Arrays.asList(values));
dimensions.put(dimensionName, md);
return (SubclassT) this;
}
@SuppressWarnings("unchecked")
public SubclassT withoutDimension(String dimensionName) {
if (this.dimensions.containsKey(dimensionName)) {
dimensions.remove(dimensionName);
}
return (SubclassT) this;
}
}
| mit |
shengge/eoe-Libraries-for-Android-Developers | src/cn/eoe/FileUtil/filter/textFilter.java | 441 | package cn.eoe.FileUtil.filter;
import java.io.File;
public class textFilter extends AbFileFilter{
public textFilter(AbFileFilter filter) {
super(filter);
// TODO Auto-generated constructor stub
}
public boolean isaccept(File dir, String filename) {
// TODO Auto-generated method stub
return (filename.endsWith(".txt")
||filename.endsWith(".text")
||filename.endsWith(".TXT")
||filename.endsWith(".TEXT"));
}
}
| mit |
kekbur/logback-ext | logback-ext-cloudwatch-appender/src/main/java/org/eluder/logback/ext/cloudwatch/appender/CloudWatchAccessAppender.java | 979 | package org.eluder.logback.ext.cloudwatch.appender;
import ch.qos.logback.access.spi.IAccessEvent;
import ch.qos.logback.core.filter.Filter;
import org.eluder.logback.ext.aws.core.AwsSupport;
import org.eluder.logback.ext.core.CommonEventAttributes;
public class CloudWatchAccessAppender extends AbstractCloudWatchAppender<IAccessEvent> {
public CloudWatchAccessAppender() {
super();
}
protected CloudWatchAccessAppender(AwsSupport awsSupport, Filter<IAccessEvent> sdkLoggingFilter) {
super(awsSupport, sdkLoggingFilter);
}
@Override
protected CommonEventAttributes applyCommonEventAttributes(final IAccessEvent event) {
return new CommonEventAttributes() {
@Override
public String getThreadName() {
return event.getThreadName();
}
@Override
public long getTimeStamp() {
return event.getTimeStamp();
}
};
}
}
| mit |
akervern/che | ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/workspace/model/RuntimeImpl.java | 3826 | /*
* Copyright (c) 2012-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.ide.api.workspace.model;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import org.eclipse.che.api.core.model.workspace.Runtime;
import org.eclipse.che.api.core.model.workspace.Warning;
import org.eclipse.che.api.core.model.workspace.config.Command;
import org.eclipse.che.api.core.model.workspace.runtime.Machine;
import org.eclipse.che.ide.api.command.CommandImpl;
/** Data object for {@link Runtime}. */
public class RuntimeImpl implements Runtime {
private final String activeEnv;
private final String owner;
private final String machineToken;
private Map<String, MachineImpl> machines;
private List<CommandImpl> commands;
private List<Warning> warnings;
public RuntimeImpl(
String activeEnv,
Map<String, ? extends Machine> machines,
String owner,
String machineToken,
List<? extends Command> commands,
List<? extends Warning> warnings) {
this.activeEnv = activeEnv;
if (machines != null) {
this.machines =
machines
.entrySet()
.stream()
.collect(
toMap(
Map.Entry::getKey,
entry -> new MachineImpl(entry.getKey(), entry.getValue())));
}
this.owner = owner;
this.machineToken = machineToken;
if (commands != null) {
this.commands = commands.stream().map(CommandImpl::new).collect(toCollection(ArrayList::new));
}
if (warnings != null) {
this.warnings = warnings.stream().map(WarningImpl::new).collect(toList());
}
}
@Override
public String getActiveEnv() {
return activeEnv;
}
@Override
public Map<String, MachineImpl> getMachines() {
if (machines == null) {
machines = new HashMap<>();
}
return machines;
}
public Optional<MachineImpl> getMachineByName(String name) {
return Optional.ofNullable(getMachines().get(name));
}
@Override
public String getOwner() {
return owner;
}
public String getMachineToken() {
return machineToken;
}
@Override
public List<Warning> getWarnings() {
if (warnings == null) {
warnings = new ArrayList<>();
}
return warnings;
}
@Override
public List<CommandImpl> getCommands() {
if (commands == null) {
commands = new ArrayList<>();
}
return commands;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RuntimeImpl)) return false;
RuntimeImpl that = (RuntimeImpl) o;
return Objects.equals(activeEnv, that.activeEnv)
&& Objects.equals(machines, that.machines)
&& Objects.equals(owner, that.owner)
&& Objects.equals(commands, that.commands)
&& Objects.equals(warnings, that.warnings);
}
@Override
public int hashCode() {
return Objects.hash(activeEnv, machines, owner, commands, warnings);
}
@Override
public String toString() {
return "RuntimeImpl{"
+ "activeEnv='"
+ activeEnv
+ '\''
+ ", machines='"
+ machines
+ '\''
+ ", owner="
+ owner
+ ", commands="
+ commands
+ ", warnings="
+ warnings
+ '}';
}
}
| epl-1.0 |
maxeler/eclipse | eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/MoveInnerToTopLevel/test30/out/Inner.java | 177 | import static java.lang.Math.E;
public class Inner
{
/** Comment */
private A a;
Inner(A a) {
this.a= a;
int f= this.a.foo();
int g= this.a.bar();
double e= E;
}
} | epl-1.0 |
sistanlp/banner | src/main/java/edu/umass/cs/mallet/base/classify/AdaBoostTrainer.java | 6447 | /* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept.
This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit).
http://www.cs.umass.edu/~mccallum/mallet
This software is provided under the terms of the Common Public License,
version 1.0, as published by http://www.opensource.org. For further
information, see the file `LICENSE' included with this distribution. */
package edu.umass.cs.mallet.base.classify;
import edu.umass.cs.mallet.base.util.MalletLogger;
import edu.umass.cs.mallet.base.util.Maths;
import edu.umass.cs.mallet.base.types.*;
import java.util.Random;
import java.util.logging.*;
/**
* This version of AdaBoost should be used only for binary classification.
* Use AdaBoost.M2 for multi-class problems.
*
* <p>Robert E. Schapire.
* "A decision-theoretic generalization of on-line learning and
* an application to boosting"
* In Journal of Computer and System Sciences
* http://www.cs.princeton.edu/~schapire/uncompress-papers.cgi/FreundSc95.ps
*
* @author Andrew McCallum <a href="mailto:mccallum@cs.umass.edu">mccallum@cs.umass.edu</a>
*/
public class AdaBoostTrainer extends ClassifierTrainer
{
private static Logger logger = MalletLogger.getLogger(AdaBoostTrainer.class.getName());
private static int MAX_NUM_RESAMPLING_ITERATIONS = 10;
ClassifierTrainer weakLearner;
int numRounds;
public AdaBoostTrainer (ClassifierTrainer weakLearner, int numRounds)
{
if (! (weakLearner instanceof Boostable))
throw new IllegalArgumentException ("weak learner not boostable");
if (numRounds <= 0)
throw new IllegalArgumentException ("number of rounds must be positive");
this.weakLearner = weakLearner;
this.numRounds = numRounds;
}
public AdaBoostTrainer (ClassifierTrainer weakLearner)
{
this (weakLearner, 100);
}
/**
* Boosting method that resamples instances using their weights
*/
public Classifier train (InstanceList trainingList,
InstanceList validationList,
InstanceList testSet,
ClassifierEvaluating evaluator,
Classifier initialClassifier)
{
FeatureSelection selectedFeatures = trainingList.getFeatureSelection();
if (selectedFeatures != null)
throw new UnsupportedOperationException("FeatureSelection not yet implemented.");
java.util.Random random = new java.util.Random();
// Set the initial weights to be uniform
double w = 1.0 / trainingList.size();
InstanceList trainingInsts = new InstanceList();
for (int i = 0; i < trainingList.size(); i++)
trainingInsts.add(trainingList.getInstance(i), w);
boolean[] correct = new boolean[trainingInsts.size()];
int numClasses = trainingInsts.getTargetAlphabet().size();
if (numClasses != 2)
logger.info("AdaBoostTrainer.train: WARNING: more than two classes");
Classifier[] weakLearners = new Classifier[numRounds];
double[] alphas = new double[numRounds];
InstanceList roundTrainingInsts = new InstanceList();
// Boosting iterations
for (int round = 0; round < numRounds; round++) {
logger.info("=========== AdaBoostTrainer round " + (round+1) + " begin");
// Keep resampling the training instances (using the distribution
// of instance weights) on which to train the weak learner until
// either we exceed the preset number of maximum iterations, or
// the weak learner makes a non-zero error on trainingInsts
// (this makes sure we sample at least some 'hard' instances).
int resamplingIterations = 0;
double err;
do {
err = 0;
roundTrainingInsts = trainingInsts.sampleWithInstanceWeights(random);
weakLearners[round] = weakLearner.train (roundTrainingInsts, validationList);
// Calculate error
for (int i = 0; i < trainingInsts.size(); i++) {
Instance inst = trainingInsts.getInstance(i);
if (weakLearners[round].classify(inst).bestLabelIsCorrect())
correct[i] = true;
else {
correct[i] = false;
err += trainingInsts.getInstanceWeight(i);
}
}
resamplingIterations++;
}
while (Maths.almostEquals(err, 0) && resamplingIterations < MAX_NUM_RESAMPLING_ITERATIONS);
// Stop boosting when error is too big or 0,
// ignoring weak classifier trained this round
if (Maths.almostEquals(err, 0) || err > 0.5) {
logger.info("AdaBoostTrainer stopped at " + (round+1) + " / "
+ numRounds + " rounds: numClasses="
+ numClasses + " error=" + err);
// If we are in the first round, have to use the weak classifier in any case
int numClassifiersToUse = (round == 0) ? 1 : round;
if (round == 0)
alphas[0] = 1;
double[] betas = new double[numClassifiersToUse];
Classifier[] weakClassifiers = new Classifier[numClassifiersToUse];
System.arraycopy(alphas, 0, betas, 0, numClassifiersToUse);
System.arraycopy(weakLearners, 0, weakClassifiers, 0, numClassifiersToUse);
for (int i = 0; i < betas.length; i++)
logger.info("AdaBoostTrainer weight[weakLearner[" + i + "]]=" + betas[i]);
return new AdaBoost (roundTrainingInsts.getPipe(), weakClassifiers, betas);
}
// Calculate the weight to assign to this weak classifier
// This formula is really designed for binary classifiers that don't
// give a confidence score. Use AdaBoostMH for multi-class or
// multi-labeled data.
alphas[round] = Math.log((1 - err) / err);
double reweightFactor = err / (1 - err);
double sum = 0;
// Decrease weights of correctly classified instances
for (int i = 0; i < trainingInsts.size(); i++) {
w = trainingInsts.getInstanceWeight(i);
if (correct[i])
w *= reweightFactor;
trainingInsts.setInstanceWeight (i, w);
sum += w;
}
// Normalize the instance weights
for (int i = 0; i < trainingInsts.size(); i++) {
trainingInsts.setInstanceWeight (i, trainingInsts.getInstanceWeight(i) / sum);
}
logger.info("=========== AdaBoostTrainer round " + (round+1)
+ " finished, weak classifier training error = " + err);
}
for (int i = 0; i < alphas.length; i++)
logger.info("AdaBoostTrainer weight[weakLearner[" + i + "]]=" + alphas[i]);
return new AdaBoost (roundTrainingInsts.getPipe(), weakLearners, alphas);
}
}
| epl-1.0 |
sguan-actuate/birt | UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/ui/views/ElementAdapter.java | 4730 | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.ui.views;
import org.eclipse.core.expressions.Expression;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
/**
* ElementAdapter
*/
public class ElementAdapter
{
/**
* Comment for <code>id</code>
*/
private String id;
/**
* Priority for this ElementAdapter.
*/
private int priority = 2;
/**
* A id array of ElementAdapters to overwite (hide).
*/
private String[] overwrite;
/**
* Does this ElementAdapter look for workbench adapter chain.
*/
private boolean includeWorkbenchContribute;
/**
* Adapterabe type.
*/
private Class adaptableType;
/**
* Target adapter type.
*/
private Class adapterType;
private IConfigurationElement adapterConfig;
/**
* Comment for <code>adapterInstance</code>
*/
private Object adapterInstance;
/**
* Comment for <code>factory</code>
*/
private IAdapterFactory factory;
/**
* Comment for <code>isSingleton</code>
*/
private boolean isSingleton;
/**
* Adatper object instance.
*/
private Object cachedAdapter;
private Expression expression;
// getters and setters
public Class getAdaptableType( )
{
return adaptableType;
}
public void setAdaptableType( Class adaptableType )
{
this.adaptableType = adaptableType;
}
public IAdapterFactory getFactory( )
{
return factory;
}
public void setFactory( IAdapterFactory factory )
{
this.factory = factory;
}
public boolean isIncludeWorkbenchContribute( )
{
return includeWorkbenchContribute;
}
public void setIncludeWorkbenchContribute(
boolean includeWorkbenchContribute )
{
this.includeWorkbenchContribute = includeWorkbenchContribute;
}
public String[] getOverwrite( )
{
return overwrite;
}
public void setOverwrite( String[] overwrite )
{
this.overwrite = overwrite;
}
public int getPriority( )
{
return priority;
}
public void setPriority( int priority )
{
this.priority = priority;
}
public Class getAdapterType( )
{
return adapterType;
}
public void setAdapterType( Class type )
{
this.adapterType = type;
}
public String getId( )
{
return id;
}
public void setId( String id )
{
this.id = id;
}
public Object getAdapterInstance( )
{
return adapterInstance;
}
public void setAdapterInstance( Object adapterInstance )
{
this.adapterInstance = adapterInstance;
}
public void setAdapterConfig( IConfigurationElement config )
{
this.adapterConfig = config;
}
public boolean isSingleton( )
{
return isSingleton;
}
public void setSingleton( boolean isSingleton )
{
this.isSingleton = isSingleton;
}
public Expression getExpression( )
{
return expression;
}
public void setExpression( Expression expression )
{
this.expression = expression;
}
// public methods
// FIXME singleton, factory
public Object getAdater( Object adaptableObject )
{
if ( this.cachedAdapter != null && this.isSingleton )
{
return this.cachedAdapter;
}
if ( this.adapterInstance != null )
{
if ( !isSingleton && adapterConfig != null )
{
try
{
return adapterConfig.createExecutableExtension( "class" ); //$NON-NLS-1$
}
catch ( CoreException e )
{
e.printStackTrace( );
}
}
return this.adapterInstance;
}
Object apt = null;
if ( this.factory != null )
{
apt = this.factory.getAdapter( adaptableObject, this.adapterType );
}
if ( apt == null && this.includeWorkbenchContribute )
{
apt = Platform.getAdapterManager( ).getAdapter( adaptableObject,
this.adapterType );
}
if ( this.isSingleton )
{
// only when is singleton, we cache the instance
this.cachedAdapter = apt;
}
return apt;
}
@Override
public boolean equals( Object obj )
{
if ( obj == this )
{
return true;
}
if ( !( obj instanceof ElementAdapter ) )
{
return false;
}
return this.getId( ).equals( ( (ElementAdapter) obj ).getId( ) );
}
@Override
public int hashCode( )
{
return this.getId( ).hashCode( );
}
public String toString( )
{
return this.getId( );
}
}
| epl-1.0 |
golo-lang/golo-lang | src/main/java/org/eclipse/golo/runtime/InvalidDestructuringException.java | 1588 | /*
* Copyright (c) 2012-2021 Institut National des Sciences Appliquées de Lyon (INSA Lyon) and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.golo.runtime;
public class InvalidDestructuringException extends IllegalArgumentException {
// TODO: localize the error message?
public InvalidDestructuringException(String message) {
super(message);
}
public InvalidDestructuringException(String message, Throwable cause) {
super(message, cause);
}
public InvalidDestructuringException(Throwable cause) {
super(cause);
}
public static InvalidDestructuringException tooManyValues(int expected) {
return new InvalidDestructuringException(String.format(
"too many values (expecting %d).",
expected));
}
public static InvalidDestructuringException notEnoughValues(int expected, boolean sub) {
return new InvalidDestructuringException(String.format(
"not enough values (expecting%s %d).",
sub ? " at least" : "",
sub ? expected - 1 : expected));
}
public static InvalidDestructuringException notEnoughValues(int expected, int available, boolean sub) {
return new InvalidDestructuringException(String.format(
"not enough values (expecting%s %d and got %d).",
sub ? " at least" : "",
sub ? expected - 1 : expected,
available));
}
}
| epl-1.0 |
ControlSystemStudio/cs-studio | applications/apputil/apputil-plugins/org.csstudio.apputil/src/org/csstudio/apputil/formula/node/SubNode.java | 1023 | /*******************************************************************************
* Copyright (c) 2010 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package org.csstudio.apputil.formula.node;
import org.csstudio.apputil.formula.Node;
/** One computational node.
* @author Kay Kasemir
*/
public class SubNode extends AbstractBinaryNode
{
public SubNode(Node left, Node right)
{
super(left, right);
}
@Override
public double eval()
{
final double a = left.eval();
final double b = right.eval();
return a - b;
}
@SuppressWarnings("nls")
@Override
public String toString()
{
return "(" + left + " - " + right + ")";
}
}
| epl-1.0 |
rohitdubey12/kura | kura/org.eclipse.kura.api/src/main/java/org/eclipse/kura/KuraInvalidMessageException.java | 1056 | /*******************************************************************************
* Copyright (c) 2011, 2016 Eurotech and/or its affiliates
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eurotech
*******************************************************************************/
package org.eclipse.kura;
public class KuraInvalidMessageException extends KuraRuntimeException
{
private static final long serialVersionUID = -3636897647706575102L;
public KuraInvalidMessageException(Object argument) {
super(KuraErrorCode.INVALID_MESSAGE_EXCEPTION, argument);
}
public KuraInvalidMessageException(Throwable cause) {
super(KuraErrorCode.INVALID_MESSAGE_EXCEPTION, cause);
}
public KuraInvalidMessageException(Throwable cause, Object argument) {
super(KuraErrorCode.INVALID_MESSAGE_EXCEPTION, cause, argument);
}
}
| epl-1.0 |
akervern/che | wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/watcher/server/impl/FileWatcherByPathValue.java | 1637 | /*
* Copyright (c) 2012-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.api.watcher.server.impl;
import static java.nio.file.Files.isDirectory;
import com.google.inject.Inject;
import java.nio.file.Path;
import java.util.function.Consumer;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class FileWatcherByPathValue {
private static final Logger LOG = LoggerFactory.getLogger(FileWatcherByPathValue.class);
private final FileWatcherEventHandler handler;
private final FileWatcherService service;
@Inject
public FileWatcherByPathValue(FileWatcherService service, FileWatcherEventHandler handler) {
this.handler = handler;
this.service = service;
}
int watch(Path path, Consumer<String> create, Consumer<String> modify, Consumer<String> delete) {
LOG.debug("Watching path '{}'", path);
service.register(isDirectory(path) ? path : path.getParent());
int operationId = handler.register(path, create, modify, delete);
LOG.debug("Registered an operation set with id '{}'", operationId);
return operationId;
}
void unwatch(int operationId) {
LOG.debug("Unregisterng an operation set with id '{}'", operationId);
Path dir = handler.unRegister(operationId);
LOG.debug("Unwatching path '{}'");
service.unRegister(dir);
}
}
| epl-1.0 |
sguan-actuate/birt | chart/org.eclipse.birt.chart.engine/src/org/eclipse/birt/chart/model/component/impl/DialRegionImpl.java | 9672 | /***********************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
***********************************************************************/
package org.eclipse.birt.chart.model.component.impl;
import org.eclipse.birt.chart.model.attribute.Anchor;
import org.eclipse.birt.chart.model.attribute.LineAttributes;
import org.eclipse.birt.chart.model.attribute.LineStyle;
import org.eclipse.birt.chart.model.attribute.impl.ColorDefinitionImpl;
import org.eclipse.birt.chart.model.attribute.impl.LineAttributesImpl;
import org.eclipse.birt.chart.model.component.ComponentFactory;
import org.eclipse.birt.chart.model.component.ComponentPackage;
import org.eclipse.birt.chart.model.component.DialRegion;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc --> An implementation of the model object '<em><b>Dial Region</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.eclipse.birt.chart.model.component.impl.DialRegionImpl#getInnerRadius <em>Inner Radius</em>}</li>
* <li>{@link org.eclipse.birt.chart.model.component.impl.DialRegionImpl#getOuterRadius <em>Outer Radius</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class DialRegionImpl extends MarkerRangeImpl implements DialRegion
{
/**
* The default value of the '{@link #getInnerRadius() <em>Inner Radius</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getInnerRadius()
* @generated
* @ordered
*/
protected static final double INNER_RADIUS_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getInnerRadius() <em>Inner Radius</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getInnerRadius()
* @generated
* @ordered
*/
protected double innerRadius = INNER_RADIUS_EDEFAULT;
/**
* This is true if the Inner Radius attribute has been set. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
* @ordered
*/
protected boolean innerRadiusESet;
/**
* The default value of the '{@link #getOuterRadius() <em>Outer Radius</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getOuterRadius()
* @generated
* @ordered
*/
protected static final double OUTER_RADIUS_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getOuterRadius() <em>Outer Radius</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getOuterRadius()
* @generated
* @ordered
*/
protected double outerRadius = OUTER_RADIUS_EDEFAULT;
/**
* This is true if the Outer Radius attribute has been set. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
* @ordered
*/
protected boolean outerRadiusESet;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
protected DialRegionImpl( )
{
super( );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass( )
{
return ComponentPackage.Literals.DIAL_REGION;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public double getInnerRadius( )
{
return innerRadius;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void setInnerRadius( double newInnerRadius )
{
double oldInnerRadius = innerRadius;
innerRadius = newInnerRadius;
boolean oldInnerRadiusESet = innerRadiusESet;
innerRadiusESet = true;
if ( eNotificationRequired( ) )
eNotify( new ENotificationImpl( this,
Notification.SET,
ComponentPackage.DIAL_REGION__INNER_RADIUS,
oldInnerRadius,
innerRadius,
!oldInnerRadiusESet ) );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void unsetInnerRadius( )
{
double oldInnerRadius = innerRadius;
boolean oldInnerRadiusESet = innerRadiusESet;
innerRadius = INNER_RADIUS_EDEFAULT;
innerRadiusESet = false;
if ( eNotificationRequired( ) )
eNotify( new ENotificationImpl( this,
Notification.UNSET,
ComponentPackage.DIAL_REGION__INNER_RADIUS,
oldInnerRadius,
INNER_RADIUS_EDEFAULT,
oldInnerRadiusESet ) );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public boolean isSetInnerRadius( )
{
return innerRadiusESet;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public double getOuterRadius( )
{
return outerRadius;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void setOuterRadius( double newOuterRadius )
{
double oldOuterRadius = outerRadius;
outerRadius = newOuterRadius;
boolean oldOuterRadiusESet = outerRadiusESet;
outerRadiusESet = true;
if ( eNotificationRequired( ) )
eNotify( new ENotificationImpl( this,
Notification.SET,
ComponentPackage.DIAL_REGION__OUTER_RADIUS,
oldOuterRadius,
outerRadius,
!oldOuterRadiusESet ) );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void unsetOuterRadius( )
{
double oldOuterRadius = outerRadius;
boolean oldOuterRadiusESet = outerRadiusESet;
outerRadius = OUTER_RADIUS_EDEFAULT;
outerRadiusESet = false;
if ( eNotificationRequired( ) )
eNotify( new ENotificationImpl( this,
Notification.UNSET,
ComponentPackage.DIAL_REGION__OUTER_RADIUS,
oldOuterRadius,
OUTER_RADIUS_EDEFAULT,
oldOuterRadiusESet ) );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public boolean isSetOuterRadius( )
{
return outerRadiusESet;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet( int featureID, boolean resolve, boolean coreType )
{
switch ( featureID )
{
case ComponentPackage.DIAL_REGION__INNER_RADIUS :
return getInnerRadius( );
case ComponentPackage.DIAL_REGION__OUTER_RADIUS :
return getOuterRadius( );
}
return super.eGet( featureID, resolve, coreType );
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet( int featureID, Object newValue )
{
switch ( featureID )
{
case ComponentPackage.DIAL_REGION__INNER_RADIUS :
setInnerRadius( (Double) newValue );
return;
case ComponentPackage.DIAL_REGION__OUTER_RADIUS :
setOuterRadius( (Double) newValue );
return;
}
super.eSet( featureID, newValue );
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset( int featureID )
{
switch ( featureID )
{
case ComponentPackage.DIAL_REGION__INNER_RADIUS :
unsetInnerRadius( );
return;
case ComponentPackage.DIAL_REGION__OUTER_RADIUS :
unsetOuterRadius( );
return;
}
super.eUnset( featureID );
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet( int featureID )
{
switch ( featureID )
{
case ComponentPackage.DIAL_REGION__INNER_RADIUS :
return isSetInnerRadius( );
case ComponentPackage.DIAL_REGION__OUTER_RADIUS :
return isSetOuterRadius( );
}
return super.eIsSet( featureID );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
public String toString( )
{
if ( eIsProxy( ) )
return super.toString( );
StringBuffer result = new StringBuffer( super.toString( ) );
result.append( " (innerRadius: " ); //$NON-NLS-1$
if ( innerRadiusESet )
result.append( innerRadius );
else
result.append( "<unset>" ); //$NON-NLS-1$
result.append( ", outerRadius: " ); //$NON-NLS-1$
if ( outerRadiusESet )
result.append( outerRadius );
else
result.append( "<unset>" ); //$NON-NLS-1$
result.append( ')' );
return result.toString( );
}
/**
* @return instance of <code>DialRegion</code>.
*/
public static final DialRegion create( )
{
DialRegion dr = ComponentFactory.eINSTANCE.createDialRegion( );
( (DialRegionImpl) dr ).initialize( );
return dr;
}
public static final DialRegion createDefault( )
{
DialRegion dr = ComponentFactory.eINSTANCE.createDialRegion( );
( (DialRegionImpl) dr ).initDefault( );
return dr;
}
/**
*
*/
public final void initialize( )
{
LineAttributes liaOutline = LineAttributesImpl.create( ColorDefinitionImpl.BLACK( ),
LineStyle.SOLID_LITERAL,
1 );
liaOutline.setVisible( false );
setOutline( liaOutline );
setLabel( LabelImpl.create( ) );
setLabelAnchor( Anchor.NORTH_LITERAL );
}
public final void initDefault( )
{
LineAttributes liaOutline = LineAttributesImpl.createDefault( null,
LineStyle.SOLID_LITERAL,
1,
false );
setOutline( liaOutline );
setLabel( LabelImpl.createDefault( ) );
labelAnchor = Anchor.NORTH_LITERAL;
}
/**
* @generated
*/
public DialRegion copyInstance( )
{
DialRegionImpl dest = new DialRegionImpl( );
dest.set( this );
return dest;
}
/**
* @generated
*/
protected void set( DialRegion src )
{
super.set( src );
// attributes
innerRadius = src.getInnerRadius( );
innerRadiusESet = src.isSetInnerRadius( );
outerRadius = src.getOuterRadius( );
outerRadiusESet = src.isSetOuterRadius( );
}
} // DialRegionImpl
| epl-1.0 |
jsight/windup | tests/src/test/java/org/jboss/windup/tests/bootstrap/RunWindupCommandTest.java | 876 | package org.jboss.windup.tests.bootstrap;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class RunWindupCommandTest extends AbstractBootstrapTestWithRules {
@Test
public void checkFilePath() {
bootstrap( "--input", "../test-files/jee-example-app-1.0.0.ear", "--target", "eap7", "--overwrite");
assertTrue(capturedOutput().contains("Input Application"));
assertTrue(capturedOutput().contains("jee-example-app-1.0.0.ear"));
}
@Test
public void checkDirPath() {
bootstrap( "--input", "../test-files/", "--target", "eap7", "--overwrite");
assertTrue(capturedOutput().contains("Input Application"));
assertTrue(capturedOutput().contains("jee-example-app-1.0.0.ear"));
assertFalse(capturedOutput().contains("dummy.html"));
}
}
| epl-1.0 |
evidolob/che | plugins/plugin-git/che-plugin-git-ext-git/src/main/java/org/eclipse/che/ide/ext/git/client/reset/files/ResetFilesPresenter.java | 8436 | /*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.ext.git.client.reset.files;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.eclipse.che.ide.ext.git.client.GitLocalizationConstant;
import org.eclipse.che.ide.api.git.GitServiceClient;
import org.eclipse.che.api.git.shared.IndexFile;
import org.eclipse.che.api.git.shared.Status;
import org.eclipse.che.ide.api.app.AppContext;
import org.eclipse.che.ide.api.app.CurrentProject;
import org.eclipse.che.ide.api.notification.NotificationManager;
import org.eclipse.che.ide.dto.DtoFactory;
import org.eclipse.che.ide.ext.git.client.outputconsole.GitOutputConsole;
import org.eclipse.che.ide.ext.git.client.outputconsole.GitOutputConsoleFactory;
import org.eclipse.che.ide.extension.machine.client.processes.ConsolesPanelPresenter;
import org.eclipse.che.ide.rest.AsyncRequestCallback;
import org.eclipse.che.ide.rest.DtoUnmarshallerFactory;
import org.eclipse.che.ide.api.dialogs.DialogFactory;
import java.util.ArrayList;
import java.util.List;
import static org.eclipse.che.api.git.shared.ResetRequest.ResetType;
import static org.eclipse.che.ide.ext.git.client.status.StatusCommandPresenter.STATUS_COMMAND_NAME;
/**
* Presenter for resetting files from index.
* <p/>
* When user tries to reset files from index:
* 1. Find Git work directory by selected item in browser tree.
* 2. Get status for found work directory.
* 3. Display files ready for commit in grid. (Checked items will be reseted from index).
*
* @author Ann Zhuleva
*/
@Singleton
public class ResetFilesPresenter implements ResetFilesView.ActionDelegate {
private static final String RESET_COMMAND_NAME = "Git reset";
private final DtoFactory dtoFactory;
private final DtoUnmarshallerFactory dtoUnmarshallerFactory;
private final DialogFactory dialogFactory;
private final GitOutputConsoleFactory gitOutputConsoleFactory;
private final ConsolesPanelPresenter consolesPanelPresenter;
private final ResetFilesView view;
private final GitServiceClient service;
private final AppContext appContext;
private final GitLocalizationConstant constant;
private final NotificationManager notificationManager;
private CurrentProject project;
private List<IndexFile> indexedFiles;
/** Create presenter. */
@Inject
public ResetFilesPresenter(ResetFilesView view,
GitServiceClient service,
AppContext appContext,
GitLocalizationConstant constant,
NotificationManager notificationManager,
DtoFactory dtoFactory,
DtoUnmarshallerFactory dtoUnmarshallerFactory,
DialogFactory dialogFactory,
GitOutputConsoleFactory gitOutputConsoleFactory,
ConsolesPanelPresenter consolesPanelPresenter) {
this.view = view;
this.dtoFactory = dtoFactory;
this.dtoUnmarshallerFactory = dtoUnmarshallerFactory;
this.dialogFactory = dialogFactory;
this.gitOutputConsoleFactory = gitOutputConsoleFactory;
this.consolesPanelPresenter = consolesPanelPresenter;
this.view.setDelegate(this);
this.service = service;
this.appContext = appContext;
this.constant = constant;
this.notificationManager = notificationManager;
}
/** Show dialog. */
public void showDialog() {
project = appContext.getCurrentProject();
service.status(appContext.getDevMachine(), project.getRootProject(),
new AsyncRequestCallback<Status>(dtoUnmarshallerFactory.newUnmarshaller(Status.class)) {
@Override
protected void onSuccess(Status result) {
if (result.isClean()) {
dialogFactory.createMessageDialog(constant.messagesWarningTitle(), constant.indexIsEmpty(), null).show();
return;
}
List<IndexFile> values = new ArrayList<>();
List<String> valuesTmp = new ArrayList<>();
valuesTmp.addAll(result.getAdded());
valuesTmp.addAll(result.getChanged());
valuesTmp.addAll(result.getRemoved());
for (String value : valuesTmp) {
IndexFile indexFile = dtoFactory.createDto(IndexFile.class);
indexFile.setPath(value);
indexFile.setIndexed(true);
values.add(indexFile);
}
if (values.isEmpty()) {
dialogFactory.createMessageDialog(constant.messagesWarningTitle(), constant.indexIsEmpty(), null).show();
return;
}
view.setIndexedFiles(values);
indexedFiles = values;
view.showDialog();
}
@Override
protected void onFailure(Throwable exception) {
String errorMassage = exception.getMessage() != null ? exception.getMessage() : constant.statusFailed();
GitOutputConsole console = gitOutputConsoleFactory.create(STATUS_COMMAND_NAME);
console.printError(errorMassage);
consolesPanelPresenter.addCommandOutput(appContext.getDevMachine().getId(), console);
notificationManager.notify(errorMassage, project.getRootProject());
}
});
}
/** {@inheritDoc} */
@Override
public void onResetClicked() {
List<String> files = new ArrayList<>();
for (IndexFile indexFile : indexedFiles) {
if (!indexFile.isIndexed()) {
files.add(indexFile.getPath());
}
}
final GitOutputConsole console = gitOutputConsoleFactory.create(RESET_COMMAND_NAME);
if (files.isEmpty()) {
view.close();
console.print(constant.nothingToReset());
consolesPanelPresenter.addCommandOutput(appContext.getDevMachine().getId(), console);
notificationManager.notify(constant.nothingToReset(), project.getRootProject());
return;
}
view.close();
service.reset(appContext.getDevMachine(), project.getRootProject(), "HEAD", ResetType.MIXED, files, new AsyncRequestCallback<Void>() {
@Override
protected void onSuccess(Void result) {
console.print(constant.resetFilesSuccessfully());
consolesPanelPresenter.addCommandOutput(appContext.getDevMachine().getId(), console);
notificationManager.notify(constant.resetFilesSuccessfully(), project.getRootProject());
}
@Override
protected void onFailure(Throwable exception) {
String errorMassage = exception.getMessage() != null ? exception.getMessage() : constant.resetFilesFailed();
console.printError(errorMassage);
consolesPanelPresenter.addCommandOutput(appContext.getDevMachine().getId(), console);
notificationManager.notify(errorMassage, project.getRootProject());
}
});
}
/** {@inheritDoc} */
@Override
public void onCancelClicked() {
view.close();
}
}
| epl-1.0 |
evidolob/che | plugins/plugin-git/che-plugin-git-ext-git/src/main/java/org/eclipse/che/ide/ext/git/client/push/PushToRemotePresenter.java | 18346 | /*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.ext.git.client.push;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.eclipse.che.api.core.rest.shared.dto.ServiceError;
import org.eclipse.che.ide.api.git.GitServiceClient;
import org.eclipse.che.api.git.shared.Branch;
import org.eclipse.che.api.git.shared.PushResponse;
import org.eclipse.che.api.git.shared.Remote;
import org.eclipse.che.ide.api.app.AppContext;
import org.eclipse.che.ide.api.app.CurrentProject;
import org.eclipse.che.ide.api.notification.NotificationManager;
import org.eclipse.che.ide.api.notification.StatusNotification;
import org.eclipse.che.ide.commons.exception.UnauthorizedException;
import org.eclipse.che.ide.dto.DtoFactory;
import org.eclipse.che.ide.ext.git.client.BranchFilterByRemote;
import org.eclipse.che.ide.ext.git.client.BranchSearcher;
import org.eclipse.che.ide.ext.git.client.GitLocalizationConstant;
import org.eclipse.che.ide.ext.git.client.outputconsole.GitOutputConsole;
import org.eclipse.che.ide.ext.git.client.outputconsole.GitOutputConsoleFactory;
import org.eclipse.che.ide.extension.machine.client.processes.ConsolesPanelPresenter;
import org.eclipse.che.ide.rest.AsyncRequestCallback;
import org.eclipse.che.ide.rest.DtoUnmarshallerFactory;
import org.eclipse.che.ide.rest.StringMapUnmarshaller;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.eclipse.che.api.git.shared.BranchListRequest.LIST_LOCAL;
import static org.eclipse.che.api.git.shared.BranchListRequest.LIST_REMOTE;
import static org.eclipse.che.ide.api.notification.StatusNotification.DisplayMode.FLOAT_MODE;
import static org.eclipse.che.ide.api.notification.StatusNotification.Status.FAIL;
import static org.eclipse.che.ide.api.notification.StatusNotification.Status.PROGRESS;
import static org.eclipse.che.ide.api.notification.StatusNotification.Status.SUCCESS;
import static org.eclipse.che.ide.ext.git.client.compare.branchList.BranchListPresenter.BRANCH_LIST_COMMAND_NAME;
import static org.eclipse.che.ide.ext.git.client.remote.RemotePresenter.REMOTE_REPO_COMMAND_NAME;
/**
* Presenter for pushing changes to remote repository.
*
* @author Ann Zhuleva
* @author Sergii Leschenko
*/
@Singleton
public class PushToRemotePresenter implements PushToRemoteView.ActionDelegate {
public static final String PUSH_COMMAND_NAME = "Git push";
public static final String CONFIG_COMMAND_NAME = "Git config";
private final GitOutputConsoleFactory gitOutputConsoleFactory;
private final ConsolesPanelPresenter consolesPanelPresenter;
private final DtoFactory dtoFactory;
private final DtoUnmarshallerFactory dtoUnmarshallerFactory;
private final BranchSearcher branchSearcher;
private final PushToRemoteView view;
private final GitServiceClient service;
private final AppContext appContext;
private final GitLocalizationConstant constant;
private final NotificationManager notificationManager;
private CurrentProject project;
@Inject
public PushToRemotePresenter(DtoFactory dtoFactory,
PushToRemoteView view,
GitServiceClient service,
AppContext appContext,
GitLocalizationConstant constant,
NotificationManager notificationManager,
DtoUnmarshallerFactory dtoUnmarshallerFactory,
BranchSearcher branchSearcher,
GitOutputConsoleFactory gitOutputConsoleFactory,
ConsolesPanelPresenter consolesPanelPresenter) {
this.dtoFactory = dtoFactory;
this.branchSearcher = branchSearcher;
this.view = view;
this.dtoUnmarshallerFactory = dtoUnmarshallerFactory;
this.view.setDelegate(this);
this.service = service;
this.appContext = appContext;
this.constant = constant;
this.notificationManager = notificationManager;
this.gitOutputConsoleFactory = gitOutputConsoleFactory;
this.consolesPanelPresenter = consolesPanelPresenter;
}
/** Show dialog. */
public void showDialog() {
project = appContext.getCurrentProject();
updateRemotes();
}
/**
* Get the list of remote repositories for local one.
* If remote repositories are found, then get the list of branches (remote and local).
*/
void updateRemotes() {
service.remoteList(appContext.getDevMachine(), project.getRootProject(), null, true,
new AsyncRequestCallback<List<Remote>>(dtoUnmarshallerFactory.newListUnmarshaller(Remote.class)) {
@Override
protected void onSuccess(List<Remote> result) {
updateLocalBranches();
view.setRepositories(result);
view.setEnablePushButton(!result.isEmpty());
view.showDialog();
}
@Override
protected void onFailure(Throwable exception) {
String errorMessage =
exception.getMessage() != null ? exception.getMessage() : constant.remoteListFailed();
GitOutputConsole console = gitOutputConsoleFactory.create(REMOTE_REPO_COMMAND_NAME);
console.printError(errorMessage);
consolesPanelPresenter.addCommandOutput(appContext.getDevMachine().getId(), console);
notificationManager.notify(constant.remoteListFailed(), FAIL, FLOAT_MODE, project.getRootProject());
view.setEnablePushButton(false);
}
}
);
}
/**
* Update list of local and remote branches on view.
*/
void updateLocalBranches() {
//getting local branches
getBranchesForCurrentProject(LIST_LOCAL, new AsyncCallback<List<Branch>>() {
@Override
public void onSuccess(List<Branch> result) {
List<String> localBranches = branchSearcher.getLocalBranchesToDisplay(result);
view.setLocalBranches(localBranches);
for (Branch branch : result) {
if (branch.isActive()) {
view.selectLocalBranch(branch.getDisplayName());
break;
}
}
//getting remote branch only after selecting current local branch
updateRemoteBranches();
}
@Override
public void onFailure(Throwable exception) {
String errorMessage = exception.getMessage() != null ? exception.getMessage() : constant.localBranchesListFailed();
GitOutputConsole console = gitOutputConsoleFactory.create(BRANCH_LIST_COMMAND_NAME);
console.printError(errorMessage);
consolesPanelPresenter.addCommandOutput(appContext.getDevMachine().getId(), console);
notificationManager.notify(constant.localBranchesListFailed(), FAIL, FLOAT_MODE, project.getRootProject());
view.setEnablePushButton(false);
}
});
}
/**
* Update list of remote branches on view.
*/
void updateRemoteBranches() {
getBranchesForCurrentProject(LIST_REMOTE, new AsyncCallback<List<Branch>>() {
@Override
public void onSuccess(final List<Branch> result) {
// Need to add the upstream of local branch in the list of remote branches
// to be able to push changes to the remote upstream branch
getUpstreamBranch(new AsyncCallback<Branch>() {
@Override
public void onSuccess(Branch upstream) {
BranchFilterByRemote remoteRefsHandler = new BranchFilterByRemote(view.getRepository());
final List<String> remoteBranches = branchSearcher.getRemoteBranchesToDisplay(remoteRefsHandler, result);
String selectedRemoteBranch = null;
if (upstream != null && upstream.isRemote() && remoteRefsHandler.isLinkedTo(upstream)) {
String simpleUpstreamName = remoteRefsHandler.getBranchNameWithoutRefs(upstream);
if (!remoteBranches.contains(simpleUpstreamName)) {
remoteBranches.add(simpleUpstreamName);
}
selectedRemoteBranch = simpleUpstreamName;
}
// Need to add the current local branch in the list of remote branches
// to be able to push changes to the remote branch with same name
final String currentBranch = view.getLocalBranch();
if (!remoteBranches.contains(currentBranch)) {
remoteBranches.add(currentBranch);
}
if (selectedRemoteBranch == null) {
selectedRemoteBranch = currentBranch;
}
view.setRemoteBranches(remoteBranches);
view.selectRemoteBranch(selectedRemoteBranch);
}
@Override
public void onFailure(Throwable caught) {
GitOutputConsole console = gitOutputConsoleFactory.create(CONFIG_COMMAND_NAME);
console.printError(constant.failedGettingConfig());
consolesPanelPresenter.addCommandOutput(appContext.getDevMachine().getId(), console);
notificationManager.notify(constant.failedGettingConfig(), FAIL, FLOAT_MODE, project.getRootProject());
}
});
}
@Override
public void onFailure(Throwable exception) {
String errorMessage = exception.getMessage() != null ? exception.getMessage() : constant.remoteBranchesListFailed();
GitOutputConsole console = gitOutputConsoleFactory.create(BRANCH_LIST_COMMAND_NAME);
console.printError(errorMessage);
consolesPanelPresenter.addCommandOutput(appContext.getDevMachine().getId(), console);
notificationManager.notify(constant.remoteBranchesListFailed(), FAIL, FLOAT_MODE, project.getRootProject());
view.setEnablePushButton(false);
}
});
}
/**
* Get upstream branch for selected local branch. Can invoke {@code onSuccess(null)} if upstream branch isn't set
*/
private void getUpstreamBranch(final AsyncCallback<Branch> result) {
final String configBranchRemote = "branch." + view.getLocalBranch() + ".remote";
final String configUpstreamBranch = "branch." + view.getLocalBranch() + ".merge";
service.config(appContext.getDevMachine(), project.getRootProject(), Arrays.asList(configUpstreamBranch, configBranchRemote), false,
new AsyncRequestCallback<Map<String, String>>(new StringMapUnmarshaller()) {
@Override
protected void onSuccess(Map<String, String> configs) {
if (configs.containsKey(configBranchRemote) && configs.containsKey(configUpstreamBranch)) {
String displayName = configs.get(configBranchRemote) + "/" + configs.get(configUpstreamBranch);
Branch upstream = dtoFactory.createDto(Branch.class)
.withActive(false)
.withRemote(true)
.withDisplayName(displayName)
.withName("refs/remotes/" + displayName);
result.onSuccess(upstream);
} else {
result.onSuccess(null);
}
}
@Override
protected void onFailure(Throwable exception) {
result.onFailure(exception);
}
});
}
/**
* Get the list of branches.
*
* @param remoteMode
* is a remote mode
*/
void getBranchesForCurrentProject(@NotNull final String remoteMode,
final AsyncCallback<List<Branch>> asyncResult) {
service.branchList(appContext.getDevMachine(), project.getRootProject(),
remoteMode,
new AsyncRequestCallback<List<Branch>>(dtoUnmarshallerFactory.newListUnmarshaller(Branch.class)) {
@Override
protected void onSuccess(List<Branch> result) {
asyncResult.onSuccess(result);
}
@Override
protected void onFailure(Throwable exception) {
asyncResult.onFailure(exception);
}
}
);
}
/** {@inheritDoc} */
@Override
public void onPushClicked() {
final StatusNotification notification =
notificationManager.notify(constant.pushProcess(), PROGRESS, FLOAT_MODE, project.getRootProject());
final String repository = view.getRepository();
final GitOutputConsole console = gitOutputConsoleFactory.create(PUSH_COMMAND_NAME);
service.push(appContext.getDevMachine(), project.getRootProject(), getRefs(), repository, false,
new AsyncRequestCallback<PushResponse>(dtoUnmarshallerFactory.newUnmarshaller(PushResponse.class)) {
@Override
protected void onSuccess(PushResponse result) {
console.print(result.getCommandOutput());
consolesPanelPresenter.addCommandOutput(appContext.getDevMachine().getId(), console);
notification.setStatus(SUCCESS);
if (result.getCommandOutput().contains("Everything up-to-date")) {
notification.setTitle(constant.pushUpToDate());
} else {
notification.setTitle(constant.pushSuccess(repository));
}
}
@Override
protected void onFailure(Throwable exception) {
handleError(exception, notification, console);
consolesPanelPresenter.addCommandOutput(appContext.getDevMachine().getId(), console);
}
});
view.close();
}
/** @return list of refs to push */
@NotNull
private List<String> getRefs() {
String localBranch = view.getLocalBranch();
String remoteBranch = view.getRemoteBranch();
return new ArrayList<>(Arrays.asList(localBranch + ":" + remoteBranch));
}
/** {@inheritDoc} */
@Override
public void onCancelClicked() {
view.close();
}
/** {@inheritDoc} */
@Override
public void onLocalBranchChanged() {
view.addRemoteBranch(view.getLocalBranch());
view.selectRemoteBranch(view.getLocalBranch());
}
@Override
public void onRepositoryChanged() {
updateRemoteBranches();
}
/**
* Handler some action whether some exception happened.
*
* @param throwable
* exception what happened
*/
void handleError(@NotNull Throwable throwable, StatusNotification notification, GitOutputConsole console) {
notification.setStatus(FAIL);
if (throwable instanceof UnauthorizedException) {
console.printError(constant.messagesNotAuthorized());
notification.setTitle(constant.messagesNotAuthorized());
return;
}
String errorMessage = throwable.getMessage();
if (errorMessage == null) {
console.printError(constant.pushFail());
notification.setTitle(constant.pushFail());
return;
}
try {
errorMessage = dtoFactory.createDtoFromJson(errorMessage, ServiceError.class).getMessage();
if (errorMessage.equals("Unable get private ssh key")) {
console.printError(constant.messagesUnableGetSshKey());
notification.setTitle(constant.messagesUnableGetSshKey());
return;
}
console.printError(errorMessage);
notification.setTitle(errorMessage);
} catch (Exception e) {
console.printError(errorMessage);
notification.setTitle(errorMessage);
}
}
}
| epl-1.0 |
csust-dreamstation/dreamstation | src/com/ds/service/impl/Message_Service_Impl.java | 919 | package com.ds.service.impl;
import java.util.List;
import com.ds.bean.Message;
import com.ds.dao.Message_DAO;
import com.ds.service.Message_Service;
public class Message_Service_Impl implements Message_Service {
private Message_DAO message_dao;
public Message_DAO getMessage_dao() {
return message_dao;
}
public void setMessage_dao(Message_DAO message_dao) {
this.message_dao = message_dao;
}
public void save(Message message) {
this.message_dao.saveMessage(message);
}
public Message findById(int id) {
return this.message_dao.findMessageById(id);
}
public void update(Message message) {
this.message_dao.updateMessage(message);
}
public void delete(Message message) {
this.message_dao.deleteMessage(message);
}
public List<Message> find_ALL() {
return this.message_dao.find_ALL();
}
public List<Message> find_By_State() {
return this.message_dao.find_By_State();
}
}
| gpl-2.0 |
AntumDeluge/arianne-stendhal | src/games/stendhal/server/maps/quests/SimpleQuestCreator.java | 16523 | /***************************************************************************
* Copyright © 2020 - Arianne *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package games.stendhal.server.maps.quests;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import games.stendhal.common.grammar.Grammar;
import games.stendhal.common.parser.Sentence;
import games.stendhal.server.core.engine.SingletonRepository;
import games.stendhal.server.core.rule.EntityManager;
import games.stendhal.server.entity.Entity;
import games.stendhal.server.entity.item.Item;
import games.stendhal.server.entity.item.StackableItem;
import games.stendhal.server.entity.npc.ChatAction;
import games.stendhal.server.entity.npc.ChatCondition;
import games.stendhal.server.entity.npc.ConversationPhrases;
import games.stendhal.server.entity.npc.ConversationStates;
import games.stendhal.server.entity.npc.EventRaiser;
import games.stendhal.server.entity.npc.SpeakerNPC;
import games.stendhal.server.entity.npc.action.SayTimeRemainingAction;
import games.stendhal.server.entity.npc.condition.AndCondition;
import games.stendhal.server.entity.npc.condition.NotCondition;
import games.stendhal.server.entity.npc.condition.PlayerHasItemWithHimCondition;
import games.stendhal.server.entity.npc.condition.QuestActiveCondition;
import games.stendhal.server.entity.npc.condition.QuestCompletedCondition;
import games.stendhal.server.entity.npc.condition.QuestInStateCondition;
import games.stendhal.server.entity.npc.condition.TimePassedCondition;
import games.stendhal.server.entity.player.Player;
public class SimpleQuestCreator {
private static final Logger logger = Logger.getLogger(SimpleQuestCreator.class);
private static SimpleQuestCreator instance;
public static final String ID_REQUEST = "request";
public static final String ID_ACCEPT = "accept";
public static final String ID_REJECT = "reject";
public static final String ID_REWARD = "reward";
public static final String ID_VERBOSE_REWARD_PREFIX = "verbose_reward_prefix";
public static final String ID_ALREADY_ACTIVE = "already_active";
public static final String ID_MISSING = "missing";
public static final String ID_NO_REPEAT = "no_repeat";
public static final String ID_COOLDOWN_PREFIX = "cooldown_prefix"; // prefix for SayTimeRemainingAction when player cannot repeat quest yet
public static final String ID_XP = "xp";
public static final String ID_DEF = "def";
public static final String ID_ATK = "atk";
public static final String ID_RATK = "ratk";
public static SimpleQuestCreator getInstance() {
if (instance == null) {
instance = new SimpleQuestCreator();
}
return instance;
}
public SimpleQuest create(final String slotName, final String properName, final String npcName) {
return new SimpleQuest(slotName, properName, npcName);
}
public class SimpleQuest extends AbstractQuest {
private final String QUEST_SLOT;
private final String name;
private final SpeakerNPC npc;
private String description;
private int repeatDelay = -1;
private String itemToCollect;
private int quantityToCollect = 1;
/**
* usable replies are:
* request, accept, reject, reward, already_active, missing,
* no_repeat, verbose_reward_prefix, cooldown_prefix
*/
private final Map<String, String> replies = new HashMap<String, String>() {{
put(ID_REQUEST, "Will you help me?");
put(ID_REJECT, "Okay. Perhaps another time then.");
put(ID_REWARD, "Thank you.");
put(ID_VERBOSE_REWARD_PREFIX, "As a reward I will give you");
put(ID_NO_REPEAT, "Thanks, but I don't need any more help.");
put(ID_COOLDOWN_PREFIX, "If you want to help me again, please come back in");
}};
private double karmaReward = 0;
private double karmaAcceptReward = 0;
private double karmaRejectReward = 0;
// list of items to be rewarded to player upon completion
private final Map<String, Integer> itemReward = new HashMap<String, Integer>();
// usable stat rewards are: xp, def, atk, ratk
private final Map<String, Integer> statReward = new HashMap<String, Integer>();
// if <code>true</code>, NPC will tell player what items were given as a reward
private boolean verboseReward = true;
private String region;
public SimpleQuest(final String slotName, final String properName, final String npcName) {
QUEST_SLOT = slotName;
name = properName;
npc = SingletonRepository.getNPCList().get(npcName);
}
public void setDescription(final String descr) {
description = descr;
}
/**
* Sets the quest's repeatable status & repeat delay.
*
* @param delay
* Number of minutes player must wait before repeating quest.
* `0` means immediately repeatable. `null` or less than `0`
* means not repeatable.
*/
public void setRepeatable(Integer delay) {
if (delay == null) {
delay = -1;
}
repeatDelay = delay;
}
public void setItemToCollect(final String itemName, final int quantity) {
itemToCollect = itemName;
quantityToCollect = quantity;
}
public void setXPReward(final int xp) {
statReward.put(ID_XP, xp);
}
public void setKarmaReward(final double karma) {
karmaReward = karma;
}
public void setKarmaAcceptReward(final double karma) {
karmaAcceptReward = karma;
}
public void setKarmaRejectReward(final double karma) {
karmaRejectReward = karma;
}
public void addItemReward(final String itemName, final int quantity) {
itemReward.put(itemName, quantity);
}
public void addStatReward(final String id, final int amount) {
statReward.put(id, amount);
}
@SuppressWarnings("unused")
public void addItemReward(final String itemName) {
addItemReward(itemName, 1);
}
public void setVerboseReward(final boolean verbose) {
verboseReward = verbose;
}
public void setReply(final String id, final String reply) {
if (id == null) {
logger.warn("Reply ID cannot by null");
return;
}
if (reply == null) {
logger.warn("Reply cannot be null");
return;
}
replies.put(id, reply);
}
/**
* Retrieves some predefined responses.
*
* @param id
* @return
*/
private String getReply(final String id) {
String reply = replies.get(id);
if (reply == null) {
if (id.equals(ID_ACCEPT)) {
reply = "I need you to get " + Integer.toString(quantityToCollect) + " " + Grammar.plnoun(quantityToCollect, itemToCollect) + ".";
} else if (id.equals(ID_ALREADY_ACTIVE)) {
reply = "I have already asked you to get " + Integer.toString(quantityToCollect) + " " + Grammar.plnoun(quantityToCollect, itemToCollect)
+ ". Are you #done?";
} else if (id.equals(ID_MISSING)) {
reply = "I asked you to bring me " + Integer.toString(quantityToCollect) + " " + Grammar.plnoun(quantityToCollect, itemToCollect) + ".";
}
}
return reply;
}
public void setRegion(final String regionName) {
region = regionName;
}
/**
* Retrives the number of times the player has completed the quest.
*
* @param player
* The Player to check.
* @return
* Number of times completed.
*/
private int getCompletedCount(final Player player) {
final String state = player.getQuest(QUEST_SLOT, 0);
if (state == null) {
return 0;
}
int completedIndex = 2;
if (state.equals("start") || state.equals("rejected")) {
completedIndex = 1;
}
try {
return Integer.parseInt(player.getQuest(QUEST_SLOT, completedIndex));
} catch (NumberFormatException e) {
return 0;
}
}
/**
* Action to execute when player starts quest.
*
* @return
* `ChatAction`
*/
private ChatAction startAction() {
return new ChatAction() {
@Override
public void fire(final Player player, final Sentence sentence, final EventRaiser npc) {
player.addKarma(karmaAcceptReward);
player.setQuest(QUEST_SLOT, "start;" + Integer.toString(getCompletedCount(player)));
}
};
}
/**
* Action to execute when player rejects quest.
*
* @return
* `ChatAction`
*/
private ChatAction rejectAction() {
return new ChatAction() {
@Override
public void fire(final Player player, final Sentence sentence, final EventRaiser npc) {
player.addKarma(karmaRejectReward);
player.setQuest(QUEST_SLOT, "rejected;" + Integer.toString(getCompletedCount(player)));
}
};
}
/**
* Action to execute when player completes quest
*
* @return
* `ChatAction`
*/
private ChatAction completeAction() {
return new ChatAction() {
@Override
public void fire(Player player, Sentence sentence, EventRaiser npc) {
// drop collected items
player.drop(itemToCollect, quantityToCollect);
final StringBuilder sb = new StringBuilder();
sb.append(getReply(ID_REWARD));
final int rewardCount = itemReward.size();
if (verboseReward && rewardCount > 0) {
sb.append(" " + getReply(ID_VERBOSE_REWARD_PREFIX).trim() + " ");
int idx = 0;
for (final String itemName: itemReward.keySet()) {
final int quantity = itemReward.get(itemName);
if (idx == rewardCount - 1) {
sb.append("and ");
}
sb.append(Integer.toString(quantity) + " " + Grammar.plnoun(quantity, itemName));
if (idx < rewardCount - 1) {
if (rewardCount == 2) {
sb.append(" ");
} else {
sb.append(", ");
}
}
idx++;
}
sb.append(".");
}
npc.say(sb.toString());
// reward player
final Integer xpReward = statReward.get(ID_XP);
final Integer defReward = statReward.get(ID_DEF);
final Integer atkReward = statReward.get(ID_ATK);
final Integer ratkReward = statReward.get(ID_RATK);
if (xpReward != null) {
player.addXP(xpReward);
}
if (defReward != null) {
player.addDefXP(defReward);
}
if (atkReward != null) {
player.addAtkXP(atkReward);
}
if (ratkReward != null) {
player.addRatkXP(ratkReward);
}
player.addKarma(karmaReward);
for (final String itemName: itemReward.keySet()) {
final EntityManager em = SingletonRepository.getEntityManager();
final Item item = em.getItem(itemName);
final int quantity = itemReward.get(itemName);
if (item instanceof StackableItem) {
((StackableItem) item).setQuantity(quantity);
}
if (item != null) {
player.equipOrPutOnGround(item);
}
}
player.setQuest(QUEST_SLOT, "done;" + System.currentTimeMillis() + ";" + Integer.toString(getCompletedCount(player) + 1));
}
};
}
@Override
public void addToWorld() {
fillQuestInfo(name, description, isRepeatable());
final ChatCondition canStartCondition = new ChatCondition() {
@Override
public boolean fire(final Player player, final Sentence sentence, final Entity npc) {
final String questState = player.getQuest(QUEST_SLOT, 0);
if (questState == null || questState.equals("rejected")) {
return true;
}
if (isRepeatable() && questState.equals("done")) {
return new TimePassedCondition(QUEST_SLOT, 1, repeatDelay).fire(player, sentence, npc);
}
return false;
}
};
final ChatCondition questRepeatableCondition = new ChatCondition() {
@Override
public boolean fire(Player player, Sentence sentence, Entity npc) {
return isRepeatable();
}
};
npc.add(ConversationStates.ATTENDING,
ConversationPhrases.QUEST_MESSAGES,
canStartCondition,
ConversationStates.QUEST_OFFERED,
getReply(ID_REQUEST),
null);
npc.add(ConversationStates.ATTENDING,
ConversationPhrases.QUEST_MESSAGES,
new AndCondition(
questRepeatableCondition,
new QuestInStateCondition(QUEST_SLOT, 0, "done")),
ConversationStates.ATTENDING,
null,
new SayTimeRemainingAction(QUEST_SLOT, 1, repeatDelay, getReply(ID_COOLDOWN_PREFIX)));
npc.add(ConversationStates.ATTENDING,
ConversationPhrases.QUEST_MESSAGES,
new AndCondition(
new NotCondition(questRepeatableCondition),
new QuestInStateCondition(QUEST_SLOT, 0, "done")),
ConversationStates.ATTENDING,
getReply(ID_NO_REPEAT),
null);
npc.add(ConversationStates.ATTENDING,
ConversationPhrases.QUEST_MESSAGES,
new QuestActiveCondition(QUEST_SLOT),
ConversationStates.ATTENDING,
getReply(ID_ALREADY_ACTIVE),
null);
npc.add(ConversationStates.QUEST_OFFERED,
ConversationPhrases.YES_MESSAGES,
null,
ConversationStates.ATTENDING,
getReply(ID_ACCEPT),
startAction());
npc.add(ConversationStates.QUEST_OFFERED,
ConversationPhrases.NO_MESSAGES,
null,
ConversationStates.ATTENDING,
getReply(ID_REJECT),
rejectAction());
npc.add(ConversationStates.ATTENDING,
ConversationPhrases.FINISH_MESSAGES,
new AndCondition(
new QuestActiveCondition(QUEST_SLOT),
new PlayerHasItemWithHimCondition(itemToCollect, quantityToCollect)),
ConversationStates.ATTENDING,
null,
completeAction());
npc.add(ConversationStates.ATTENDING,
ConversationPhrases.FINISH_MESSAGES,
new AndCondition(
new QuestActiveCondition(QUEST_SLOT),
new NotCondition(new PlayerHasItemWithHimCondition(itemToCollect, quantityToCollect))),
ConversationStates.ATTENDING,
getReply(ID_MISSING),
null);
}
@Override
public String getSlotName() {
return QUEST_SLOT;
}
@Override
public String getName() {
final StringBuilder sb = new StringBuilder();
boolean titleCase = true;
for (char c: name.toCharArray()) {
if (Character.isSpaceChar(c)) {
titleCase = true;
} else if (titleCase) {
c = Character.toTitleCase(c);
titleCase = false;
}
sb.append(c);
}
return sb.toString().replace(" ", "");
}
@Override
public String getNPCName() {
if (npc == null) {
return null;
}
return npc.getName();
}
@Override
public String getRegion() {
return region;
}
@Override
public boolean isRepeatable(final Player player) {
if (!isRepeatable()) {
return false;
}
return new AndCondition(new QuestCompletedCondition(QUEST_SLOT),
new TimePassedCondition(QUEST_SLOT, 1, repeatDelay)).fire(player, null, null);
}
/**
* Checks if this quest has be set for repetition.
*
* @return
* <code>true</code> if players are allowed to do this quest more than once.
*/
private boolean isRepeatable() {
return repeatDelay >= 0;
}
@Override
public List<String> getHistory(final Player player) {
final List<String> res = new ArrayList<String>();
if (!player.hasQuest(QUEST_SLOT)) {
return res;
}
final String[] questState = player.getQuest(QUEST_SLOT).split(";");
if (questState[0].equals("rejected")) {
res.add("I do not want to help " + getNPCName() + ".");
} else if (questState[0].equals("start")) {
res.add(getNPCName() + " asked me to get " + Integer.toString(quantityToCollect) + " " + Grammar.plnoun(quantityToCollect, itemToCollect) + ".");
if (player.isEquipped(itemToCollect, quantityToCollect)) {
res.add("I have what " + getNPCName() + " asked for.");
} else {
res.add("I have not found what I am looking for yet.");
}
} else if (questState[0].equals("done")) {
res.add("I found " + Integer.toString(quantityToCollect) + " " + Grammar.plnoun(quantityToCollect, itemToCollect) + " for " + getNPCName() + ".");
if (isRepeatable()) {
final int completions = getCompletedCount(player);
String plural = "time";
if (completions != 1) {
plural += "s";
}
res.add("I have done this quest " + Integer.toString(completions) + " " + plural + ".");
}
}
return res;
}
}
}
| gpl-2.0 |
21011996/metastone | app/src/main/java/net/demilich/metastone/gui/trainingmode/SaveTrainingDataCommand.java | 650 | package net.demilich.metastone.gui.trainingmode;
import net.demilich.metastone.trainingmode.TrainingData;
import net.demilich.nittygrittymvc.SimpleCommand;
import net.demilich.nittygrittymvc.interfaces.INotification;
import net.demilich.metastone.GameNotification;
public class SaveTrainingDataCommand extends SimpleCommand<GameNotification> {
@Override
public void execute(INotification<GameNotification> notification) {
TrainingData trainingData = (TrainingData) notification.getBody();
TrainingProxy trainingProxy = (TrainingProxy) getFacade().retrieveProxy(TrainingProxy.NAME);
trainingProxy.saveTrainingData(trainingData);
;
}
}
| gpl-2.0 |
sujeet14108/teammates | src/main/java/teammates/ui/controller/InstructorFeedbackEditSaveAction.java | 8559 | package teammates.ui.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.appengine.api.datastore.Text;
import teammates.common.datatransfer.FeedbackSessionType;
import teammates.common.datatransfer.attributes.FeedbackSessionAttributes;
import teammates.common.exception.EntityDoesNotExistException;
import teammates.common.exception.InvalidParametersException;
import teammates.common.util.Assumption;
import teammates.common.util.Const;
import teammates.common.util.EmailType;
import teammates.common.util.Logger;
import teammates.common.util.StatusMessage;
import teammates.common.util.StatusMessageColor;
import teammates.common.util.TimeHelper;
import teammates.ui.pagedata.InstructorFeedbackEditPageData;
public class InstructorFeedbackEditSaveAction extends Action {
private static final Logger log = Logger.getLogger();
@Override
protected ActionResult execute() throws EntityDoesNotExistException {
String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID);
String feedbackSessionName = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME);
Assumption.assertPostParamNotNull(Const.ParamsNames.COURSE_ID, courseId);
Assumption.assertPostParamNotNull(Const.ParamsNames.FEEDBACK_SESSION_NAME, feedbackSessionName);
gateKeeper.verifyAccessible(
logic.getInstructorForGoogleId(courseId, account.googleId),
logic.getFeedbackSession(feedbackSessionName, courseId),
false,
Const.ParamsNames.INSTRUCTOR_PERMISSION_MODIFY_SESSION);
InstructorFeedbackEditPageData data = new InstructorFeedbackEditPageData(account, sessionToken);
FeedbackSessionAttributes feedbackSession = extractFeedbackSessionData();
// A session opening reminder email is always sent as students
// without accounts need to receive the email to be able to respond
feedbackSession.setOpeningEmailEnabled(true);
try {
logic.updateFeedbackSession(feedbackSession);
statusToUser.add(new StatusMessage(Const.StatusMessages.FEEDBACK_SESSION_EDITED, StatusMessageColor.SUCCESS));
statusToAdmin =
"Updated Feedback Session "
+ "<span class=\"bold\">(" + feedbackSession.getFeedbackSessionName() + ")</span> for Course "
+ "<span class=\"bold\">[" + feedbackSession.getCourseId() + "]</span> created.<br>"
+ "<span class=\"bold\">From:</span> " + feedbackSession.getStartTime()
+ "<span class=\"bold\"> to</span> " + feedbackSession.getEndTime()
+ "<br><span class=\"bold\">Session visible from:</span> " + feedbackSession.getSessionVisibleFromTime()
+ "<br><span class=\"bold\">Results visible from:</span> " + feedbackSession.getResultsVisibleFromTime()
+ "<br><br><span class=\"bold\">Instructions:</span> " + feedbackSession.getInstructions();
data.setStatusForAjax(Const.StatusMessages.FEEDBACK_SESSION_EDITED);
data.setHasError(false);
} catch (InvalidParametersException e) {
setStatusForException(e);
data.setStatusForAjax(e.getMessage());
data.setHasError(true);
}
return createAjaxResult(data);
}
private FeedbackSessionAttributes extractFeedbackSessionData() {
//TODO make this method stateless
// null checks for parameters not done as null values do not affect data integrity
FeedbackSessionAttributes newSession = new FeedbackSessionAttributes();
newSession.setCourseId(getRequestParamValue(Const.ParamsNames.COURSE_ID));
newSession.setFeedbackSessionName(getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME));
newSession.setCreatorEmail(getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_CREATOR));
newSession.setStartTime(TimeHelper.combineDateTime(
getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_STARTDATE),
getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_STARTTIME)));
newSession.setEndTime(TimeHelper.combineDateTime(
getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_ENDDATE),
getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_ENDTIME)));
String paramTimeZone = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_TIMEZONE);
if (paramTimeZone != null) {
try {
newSession.setTimeZone(Double.parseDouble(paramTimeZone));
} catch (NumberFormatException nfe) {
log.warning("Failed to parse time zone parameter: " + paramTimeZone);
}
}
String paramGracePeriod = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_GRACEPERIOD);
try {
newSession.setGracePeriod(Integer.parseInt(paramGracePeriod));
} catch (NumberFormatException nfe) {
log.warning("Failed to parse graced period parameter: " + paramGracePeriod);
}
newSession.setFeedbackSessionType(FeedbackSessionType.STANDARD);
newSession.setInstructions(new Text(getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_INSTRUCTIONS)));
String type = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_RESULTSVISIBLEBUTTON);
switch (type) {
case Const.INSTRUCTOR_FEEDBACK_RESULTS_VISIBLE_TIME_CUSTOM:
newSession.setResultsVisibleFromTime(TimeHelper.combineDateTime(
getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_PUBLISHDATE),
getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_PUBLISHTIME)));
break;
case Const.INSTRUCTOR_FEEDBACK_RESULTS_VISIBLE_TIME_ATVISIBLE:
newSession.setResultsVisibleFromTime(Const.TIME_REPRESENTS_FOLLOW_VISIBLE);
break;
case Const.INSTRUCTOR_FEEDBACK_RESULTS_VISIBLE_TIME_LATER:
newSession.setResultsVisibleFromTime(Const.TIME_REPRESENTS_LATER);
break;
case Const.INSTRUCTOR_FEEDBACK_RESULTS_VISIBLE_TIME_NEVER:
newSession.setResultsVisibleFromTime(Const.TIME_REPRESENTS_NEVER);
break;
default:
log.severe("Invalid resultsVisibleFrom setting editing " + newSession.getIdentificationString());
break;
}
// handle session visible after results visible to avoid having a
// results visible date when session is private (session not visible)
type = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_SESSIONVISIBLEBUTTON);
switch (type) {
case Const.INSTRUCTOR_FEEDBACK_SESSION_VISIBLE_TIME_CUSTOM:
newSession.setSessionVisibleFromTime(TimeHelper.combineDateTime(
getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_VISIBLEDATE),
getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_VISIBLETIME)));
break;
case Const.INSTRUCTOR_FEEDBACK_SESSION_VISIBLE_TIME_ATOPEN:
newSession.setSessionVisibleFromTime(Const.TIME_REPRESENTS_FOLLOW_OPENING);
break;
case Const.INSTRUCTOR_FEEDBACK_SESSION_VISIBLE_TIME_NEVER:
newSession.setSessionVisibleFromTime(Const.TIME_REPRESENTS_NEVER);
// overwrite if private
newSession.setResultsVisibleFromTime(Const.TIME_REPRESENTS_NEVER);
newSession.setEndTime(null);
newSession.setFeedbackSessionType(FeedbackSessionType.PRIVATE);
break;
default:
log.severe("Invalid sessionVisibleFrom setting editing " + newSession.getIdentificationString());
break;
}
String[] sendReminderEmailsArray = getRequestParamValues(Const.ParamsNames.FEEDBACK_SESSION_SENDREMINDEREMAIL);
List<String> sendReminderEmailsList = sendReminderEmailsArray == null ? new ArrayList<String>()
: Arrays.asList(sendReminderEmailsArray);
newSession.setOpeningEmailEnabled(sendReminderEmailsList.contains(EmailType.FEEDBACK_OPENING.toString()));
newSession.setClosingEmailEnabled(sendReminderEmailsList.contains(EmailType.FEEDBACK_CLOSING.toString()));
newSession.setPublishedEmailEnabled(sendReminderEmailsList.contains(EmailType.FEEDBACK_PUBLISHED.toString()));
return newSession;
}
}
| gpl-2.0 |
dbfit/dbfit | dbfit-java/core/src/test/java/dbfit/util/DefaultDataTableProcessorTest.java | 1068 | package dbfit.util;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.Mock;
import org.mockito.Captor;
import org.mockito.ArgumentCaptor;
import static org.mockito.Mockito.*;
import static java.util.Arrays.asList;
@RunWith(MockitoJUnitRunner.class)
public class DefaultDataTableProcessorTest {
@Mock DataRow r1, r2;
@Mock DataRowProcessor mockedChildProcessor;
@Captor ArgumentCaptor<DataRow> captor;
@Test
public void shouldInvokeProcessOnEachChild() {
DataTable dt = createDt(r1, r2);
new DefaultDataTableProcessor(mockedChildProcessor).process(dt);
verify(mockedChildProcessor, times(2)).process(captor.capture());
assertThat(captor.getAllValues(), contains(r1, r2));
}
private DataTable createDt(DataRow... rows) {
DataTable dt = mock(DataTable.class);
when(dt.getRows()).thenReturn(asList(rows));
return dt;
}
}
| gpl-2.0 |
sagittaros/motherbrain | src/com/zillabyte/motherbrain/container/ContainerException.java | 502 | package com.zillabyte.motherbrain.container;
import com.zillabyte.motherbrain.top.MotherbrainException;
/**
* Exceptions related to the container interface itself
* @author sjarvie
*
*/
public class ContainerException extends MotherbrainException {
private static final long serialVersionUID = -789788594951874062L;
public ContainerException() {
super();
}
public ContainerException(String s) {
super(s);
}
public ContainerException(Throwable e) {
super(e);
}
}
| gpl-2.0 |
md-5/jdk10 | src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.jtt/src/org/graalvm/compiler/jtt/lang/Class_isInstance02.java | 2037 | /*
* Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
*/
package org.graalvm.compiler.jtt.lang;
import org.junit.Test;
import org.graalvm.compiler.jtt.JTTTest;
public final class Class_isInstance02 extends JTTTest {
static final String string = "";
static final Object obj = new Object();
static final DummyTestClass thisObject = new DummyTestClass();
public static boolean test(int i) {
Object object = null;
if (i == 0) {
object = obj;
}
if (i == 1) {
object = string;
}
if (i == 2) {
object = thisObject;
}
return String.class.isInstance(object);
}
@Test
public void run0() throws Throwable {
runTest("test", 0);
}
@Test
public void run1() throws Throwable {
runTest("test", 1);
}
@Test
public void run2() throws Throwable {
runTest("test", 2);
}
@Test
public void run3() throws Throwable {
runTest("test", 3);
}
}
| gpl-2.0 |
ps7z/tetrad | tetrad-lib/src/test/java/edu/cmu/tetrad/test/TestDM.java | 41724 | ///////////////////////////////////////////////////////////////////////////////
// For information as to what this class does, see the Javadoc, below. //
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, //
// 2007, 2008, 2009, 2010, 2014 by Peter Spirtes, Richard Scheines, Joseph //
// Ramsey, and Clark Glymour. //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program; if not, write to the Free Software //
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //
///////////////////////////////////////////////////////////////////////////////
package edu.cmu.tetrad.test;
import edu.cmu.tetrad.data.BigDataSetUtility;
import edu.cmu.tetrad.data.DataSet;
import edu.cmu.tetrad.graph.*;
import edu.cmu.tetrad.sem.SemIm;
import edu.cmu.tetrad.sem.SemPm;
import edu.cmu.tetrad.util.RandomUtil;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import edu.cmu.tetrad.search.DMSearch;
import java.io.*;
import java.util.List;
/**
* Tests the DM search.
*
* @author Alexander Murray-Watters
*/
public class TestDM extends TestCase {
/**
* Standard constructor for JUnit test cases.
*/
public TestDM(String name) {
super(name);
}
public void test1() {
//setting seed for debug.
RandomUtil.getInstance().setSeed(29483818483L);
Graph graph = GraphUtils.emptyGraph(4);
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X2"));
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X3"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X2"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X3"));
SemPm pm = new SemPm(graph);
SemIm im = new SemIm(pm);
DataSet data = im.simulateData(100000, false);
DMSearch search = new DMSearch();
search.setInputs(new int[]{0, 1});
search.setOutputs(new int[]{2, 3});
search.setData(data);
search.setTrueInputs(search.getInputs());
Graph foundGraph = search.search();
System.out.println("Test Case 1");
// System.out.println(search.getDmStructure());
// System.out.println(foundGraph);
Graph trueGraph = new EdgeListGraph();
trueGraph.addNode(new GraphNode("X0"));
trueGraph.addNode(new GraphNode("X1"));
trueGraph.addNode(new GraphNode("X2"));
trueGraph.addNode(new GraphNode("X3"));
trueGraph.addNode(new GraphNode("L0"));
trueGraph.addDirectedEdge(new GraphNode("X0"), new GraphNode("L0"));
trueGraph.addDirectedEdge(new GraphNode("X1"), new GraphNode("L0"));
trueGraph.addDirectedEdge(new GraphNode("L0"), new GraphNode("X2"));
trueGraph.addDirectedEdge(new GraphNode("L0"), new GraphNode("X3"));
// System.out.println(trueGraph);
assertTrue(trueGraph.equals(foundGraph));
}
public void test2() {
//setting seed for debug.
RandomUtil.getInstance().setSeed(29483818483L);
Graph graph = GraphUtils.emptyGraph(8);
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X2"));
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X3"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X2"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X3"));
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X6"));
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X7"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X6"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X7"));
graph.addDirectedEdge(new GraphNode("X4"), new GraphNode("X6"));
graph.addDirectedEdge(new GraphNode("X4"), new GraphNode("X7"));
graph.addDirectedEdge(new GraphNode("X5"), new GraphNode("X6"));
graph.addDirectedEdge(new GraphNode("X5"), new GraphNode("X7"));
SemPm pm = new SemPm(graph);
SemIm im = new SemIm(pm);
DataSet data = im.simulateData(100000, false);
DMSearch search = new DMSearch();
search.setInputs(new int[]{0, 1, 4, 5});
search.setOutputs(new int[]{2, 3, 6, 7});
search.setData(data);
search.setTrueInputs(search.getInputs());
Graph foundGraph = search.search();
System.out.println("Test Case 2");
System.out.println(search.getDmStructure());
Graph trueGraph = new EdgeListGraph();
trueGraph.addNode(new GraphNode("X0"));
trueGraph.addNode(new GraphNode("X1"));
trueGraph.addNode(new GraphNode("X2"));
trueGraph.addNode(new GraphNode("X3"));
trueGraph.addNode(new GraphNode("X4"));
trueGraph.addNode(new GraphNode("X5"));
trueGraph.addNode(new GraphNode("X6"));
trueGraph.addNode(new GraphNode("X7"));
trueGraph.addNode(new GraphNode("L0"));
trueGraph.addNode(new GraphNode("L1"));
trueGraph.addDirectedEdge(new GraphNode("X0"), new GraphNode("L0"));
trueGraph.addDirectedEdge(new GraphNode("X1"), new GraphNode("L0"));
trueGraph.addDirectedEdge(new GraphNode("L0"), new GraphNode("X2"));
trueGraph.addDirectedEdge(new GraphNode("L0"), new GraphNode("X3"));
// trueGraph.addDirectedEdge(new GraphNode("L0"), new GraphNode("X1"));
trueGraph.addDirectedEdge(new GraphNode("X0"), new GraphNode("L1"));
trueGraph.addDirectedEdge(new GraphNode("X1"), new GraphNode("L1"));
trueGraph.addDirectedEdge(new GraphNode("X4"), new GraphNode("L1"));
trueGraph.addDirectedEdge(new GraphNode("X5"), new GraphNode("L1"));
trueGraph.addDirectedEdge(new GraphNode("L1"), new GraphNode("X6"));
trueGraph.addDirectedEdge(new GraphNode("L1"), new GraphNode("X7"));
System.out.println(foundGraph);
System.out.println(trueGraph);
assertTrue(foundGraph.equals(trueGraph));
}
public void test3() {
//setting seed for debug.
RandomUtil.getInstance().setSeed(29483818483L);
Graph graph = GraphUtils.emptyGraph(12);
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X2"));
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X3"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X2"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X3"));
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X6"));
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X7"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X6"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X7"));
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X10"));
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X11"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X10"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X11"));
graph.addDirectedEdge(new GraphNode("X4"), new GraphNode("X6"));
graph.addDirectedEdge(new GraphNode("X4"), new GraphNode("X7"));
graph.addDirectedEdge(new GraphNode("X5"), new GraphNode("X6"));
graph.addDirectedEdge(new GraphNode("X5"), new GraphNode("X7"));
graph.addDirectedEdge(new GraphNode("X4"), new GraphNode("X10"));
graph.addDirectedEdge(new GraphNode("X4"), new GraphNode("X11"));
graph.addDirectedEdge(new GraphNode("X5"), new GraphNode("X10"));
graph.addDirectedEdge(new GraphNode("X5"), new GraphNode("X11"));
graph.addDirectedEdge(new GraphNode("X8"), new GraphNode("X10"));
graph.addDirectedEdge(new GraphNode("X8"), new GraphNode("X11"));
graph.addDirectedEdge(new GraphNode("X9"), new GraphNode("X10"));
graph.addDirectedEdge(new GraphNode("X9"), new GraphNode("X11"));
SemPm pm = new SemPm(graph);
SemIm im = new SemIm(pm);
DataSet data = im.simulateData(100000, false);
DMSearch search = new DMSearch();
search.setInputs(new int[]{0, 1, 4, 5, 8, 9});
search.setOutputs(new int[]{2, 3, 6, 7, 10, 11});
search.setData(data);
search.setTrueInputs(search.getInputs());
Graph foundGraph = search.search();
System.out.println("Test Case 3");
System.out.println(search.getDmStructure());
Graph trueGraph = new EdgeListGraph();
trueGraph.addNode(new GraphNode("X0"));
trueGraph.addNode(new GraphNode("X1"));
trueGraph.addNode(new GraphNode("X2"));
trueGraph.addNode(new GraphNode("X3"));
trueGraph.addNode(new GraphNode("X4"));
trueGraph.addNode(new GraphNode("X5"));
trueGraph.addNode(new GraphNode("X6"));
trueGraph.addNode(new GraphNode("X7"));
trueGraph.addNode(new GraphNode("X8"));
trueGraph.addNode(new GraphNode("X9"));
trueGraph.addNode(new GraphNode("X10"));
trueGraph.addNode(new GraphNode("X11"));
trueGraph.addNode(new GraphNode("L0"));
trueGraph.addNode(new GraphNode("L1"));
trueGraph.addNode(new GraphNode("L2"));
trueGraph.addDirectedEdge(new GraphNode("X0"), new GraphNode("L1"));
trueGraph.addDirectedEdge(new GraphNode("X1"), new GraphNode("L1"));
trueGraph.addDirectedEdge(new GraphNode("L1"), new GraphNode("X2"));
trueGraph.addDirectedEdge(new GraphNode("L1"), new GraphNode("X3"));
trueGraph.addDirectedEdge(new GraphNode("X0"), new GraphNode("L2"));
trueGraph.addDirectedEdge(new GraphNode("X1"), new GraphNode("L2"));
trueGraph.addDirectedEdge(new GraphNode("X4"), new GraphNode("L2"));
trueGraph.addDirectedEdge(new GraphNode("X5"), new GraphNode("L2"));
trueGraph.addDirectedEdge(new GraphNode("L2"), new GraphNode("X6"));
trueGraph.addDirectedEdge(new GraphNode("L2"), new GraphNode("X7"));
trueGraph.addDirectedEdge(new GraphNode("X0"), new GraphNode("L0"));
trueGraph.addDirectedEdge(new GraphNode("X1"), new GraphNode("L0"));
trueGraph.addDirectedEdge(new GraphNode("X4"), new GraphNode("L0"));
trueGraph.addDirectedEdge(new GraphNode("X5"), new GraphNode("L0"));
trueGraph.addDirectedEdge(new GraphNode("X8"), new GraphNode("L0"));
trueGraph.addDirectedEdge(new GraphNode("X9"), new GraphNode("L0"));
trueGraph.addDirectedEdge(new GraphNode("L0"), new GraphNode("X10"));
trueGraph.addDirectedEdge(new GraphNode("L0"), new GraphNode("X11"));
assertTrue(foundGraph.equals(trueGraph));
}
//Three latent fork case
public void test4() {
//setting seed for debug.
RandomUtil.getInstance().setSeed(29483818483L);
Graph graph = GraphUtils.emptyGraph(6);
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X3"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X3"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X4"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X5"));
graph.addDirectedEdge(new GraphNode("X2"), new GraphNode("X5"));
SemPm pm = new SemPm(graph);
SemIm im = new SemIm(pm);
DataSet data = im.simulateData(100000, false);
DMSearch search = new DMSearch();
search.setInputs(new int[]{0, 1, 2});
search.setOutputs(new int[]{3, 4, 5});
search.setData(data);
search.setTrueInputs(search.getInputs());
Graph foundGraph = search.search();
System.out.println("Three Latent Fork Case");
System.out.println(search.getDmStructure());
Graph trueGraph = new EdgeListGraph();
trueGraph.addNode(new GraphNode("X0"));
trueGraph.addNode(new GraphNode("X1"));
trueGraph.addNode(new GraphNode("X2"));
trueGraph.addNode(new GraphNode("X3"));
trueGraph.addNode(new GraphNode("X4"));
trueGraph.addNode(new GraphNode("X5"));
trueGraph.addNode(new GraphNode("L0"));
trueGraph.addNode(new GraphNode("L1"));
trueGraph.addNode(new GraphNode("L2"));
trueGraph.addDirectedEdge(new GraphNode("X0"), new GraphNode("L0"));
trueGraph.addDirectedEdge(new GraphNode("X1"), new GraphNode("L0"));
trueGraph.addDirectedEdge(new GraphNode("L0"), new GraphNode("X3"));
trueGraph.addDirectedEdge(new GraphNode("X1"), new GraphNode("L1"));
trueGraph.addDirectedEdge(new GraphNode("L1"), new GraphNode("X4"));
trueGraph.addDirectedEdge(new GraphNode("X1"), new GraphNode("L2"));
trueGraph.addDirectedEdge(new GraphNode("X2"), new GraphNode("L2"));
trueGraph.addDirectedEdge(new GraphNode("L2"), new GraphNode("X5"));
assertTrue(foundGraph.equals(trueGraph));
}
// Three latent collider case
public void test5() {
//setting seed for debug.
RandomUtil.getInstance().setSeed(29483818483L);
Graph graph = GraphUtils.emptyGraph(6);
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X3"));
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X4"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X4"));
graph.addDirectedEdge(new GraphNode("X2"), new GraphNode("X4"));
graph.addDirectedEdge(new GraphNode("X2"), new GraphNode("X5"));
SemPm pm = new SemPm(graph);
SemIm im = new SemIm(pm);
DataSet data = im.simulateData(100000, false);
DMSearch search = new DMSearch();
search.setInputs(new int[]{0, 1, 2});
search.setOutputs(new int[]{3, 4, 5});
search.setData(data);
search.setTrueInputs(search.getInputs());
Graph foundGraph = search.search();
System.out.println("Three Latent Collider Case");
System.out.println(search.getDmStructure());
Graph trueGraph = new EdgeListGraph();
trueGraph.addNode(new GraphNode("X0"));
trueGraph.addNode(new GraphNode("X1"));
trueGraph.addNode(new GraphNode("X2"));
trueGraph.addNode(new GraphNode("X3"));
trueGraph.addNode(new GraphNode("X4"));
trueGraph.addNode(new GraphNode("X5"));
trueGraph.addNode(new GraphNode("L0"));
trueGraph.addNode(new GraphNode("L1"));
trueGraph.addNode(new GraphNode("L2"));
trueGraph.addDirectedEdge(new GraphNode("X0"), new GraphNode("L0"));
trueGraph.addDirectedEdge(new GraphNode("L0"), new GraphNode("X3"));
trueGraph.addDirectedEdge(new GraphNode("X0"), new GraphNode("L1"));
trueGraph.addDirectedEdge(new GraphNode("X1"), new GraphNode("L1"));
trueGraph.addDirectedEdge(new GraphNode("X2"), new GraphNode("L1"));
trueGraph.addDirectedEdge(new GraphNode("L1"), new GraphNode("X4"));
trueGraph.addDirectedEdge(new GraphNode("X2"), new GraphNode("L2"));
trueGraph.addDirectedEdge(new GraphNode("L2"), new GraphNode("X5"));
assertTrue(foundGraph.equals(trueGraph));
}
//Four latent case.
public void test6() {
//setting seed for debug.
RandomUtil.getInstance().setSeed(29483818483L);
Graph graph = GraphUtils.emptyGraph(8);
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X4"));
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X5"));
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X6"));
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X7"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X5"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X6"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X7"));
graph.addDirectedEdge(new GraphNode("X2"), new GraphNode("X6"));
graph.addDirectedEdge(new GraphNode("X2"), new GraphNode("X7"));
graph.addDirectedEdge(new GraphNode("X3"), new GraphNode("X7"));
SemPm pm = new SemPm(graph);
SemIm im = new SemIm(pm);
DataSet data = im.simulateData(1000000, false);
DMSearch search = new DMSearch();
search.setInputs(new int[]{0, 1, 2, 3});
search.setOutputs(new int[]{4, 5, 6, 7});
search.setData(data);
search.setTrueInputs(search.getInputs());
Graph foundGraph = search.search();
System.out.println("Four Latent Case");
System.out.println(search.getDmStructure());
System.out.println("search.getDmStructure().latentStructToEdgeListGraph(search.getDmStructure())");
System.out.println(search.getDmStructure().latentStructToEdgeListGraph(search.getDmStructure()));
Graph trueGraph = new EdgeListGraph();
trueGraph.addNode(new GraphNode("X0"));
trueGraph.addNode(new GraphNode("X1"));
trueGraph.addNode(new GraphNode("X2"));
trueGraph.addNode(new GraphNode("X3"));
trueGraph.addNode(new GraphNode("X4"));
trueGraph.addNode(new GraphNode("X5"));
trueGraph.addNode(new GraphNode("X6"));
trueGraph.addNode(new GraphNode("X7"));
trueGraph.addNode(new GraphNode("L0"));
trueGraph.addNode(new GraphNode("L1"));
trueGraph.addNode(new GraphNode("L2"));
trueGraph.addNode(new GraphNode("L3"));
trueGraph.addDirectedEdge(new GraphNode("X0"), new GraphNode("L0"));
trueGraph.addDirectedEdge(new GraphNode("L0"), new GraphNode("X4"));
trueGraph.addDirectedEdge(new GraphNode("X0"), new GraphNode("L1"));
trueGraph.addDirectedEdge(new GraphNode("X1"), new GraphNode("L1"));
trueGraph.addDirectedEdge(new GraphNode("L1"), new GraphNode("X5"));
trueGraph.addDirectedEdge(new GraphNode("X0"), new GraphNode("L2"));
trueGraph.addDirectedEdge(new GraphNode("X1"), new GraphNode("L2"));
trueGraph.addDirectedEdge(new GraphNode("X2"), new GraphNode("L2"));
trueGraph.addDirectedEdge(new GraphNode("L2"), new GraphNode("X6"));
trueGraph.addDirectedEdge(new GraphNode("X0"), new GraphNode("L3"));
trueGraph.addDirectedEdge(new GraphNode("X1"), new GraphNode("L3"));
trueGraph.addDirectedEdge(new GraphNode("X2"), new GraphNode("L3"));
trueGraph.addDirectedEdge(new GraphNode("X3"), new GraphNode("L3"));
trueGraph.addDirectedEdge(new GraphNode("L3"), new GraphNode("X7"));
assertTrue(foundGraph.equals(trueGraph));
}
// Test cases after here serve as examples and/or were used to diagnose a no longer applicable problem.
// Still have to clean up.
public void rtest7() {
System.out.println("test 7");
DMSearch result =
readAndSearchData("src/edu/cmu/tetradproj/amurrayw/testcase7.txt",
new int[]{0, 1}, new int[]{2, 3}, true, new int[]{0, 1});
File file = new File("src/edu/cmu/tetradproj/amurrayw/output_test7.txt");
try {
FileOutputStream out = new FileOutputStream(file);
PrintStream outStream = new PrintStream(out);
outStream.println(result.getDmStructure().latentStructToEdgeListGraph(result.getDmStructure()));
outStream.println();
} catch (java.io.FileNotFoundException e) {
System.out.println("Can't write to file.");
}
System.out.println(result.getDmStructure().latentStructToEdgeListGraph(result.getDmStructure()));
System.out.println("DONE");
}
public void test8() {
//
// int nInputs=17610;
// int nOutputs=12042;
//
// int[] inputs = new int[nInputs];
// int[] outputs = new int[nOutputs];
//
// for(int i=0; i<nInputs; i++){inputs[i]=i;}
// for(int i=0; i<nOutputs; i++){outputs[i]=nInputs+i-1;}
//
// System.out.println("test 8");
//
// DMSearch result = new DMSearch();
// result.setAlphaPC(.000001);
// result.setAlphaSober(.000001);
// result.setDiscount(1);
//
// result =
// readAndSearchData("src/edu/cmu/tetradproj/amurrayw/combined_renamed.txt",
// inputs, outputs);
//
//
// System.out.println("Finished search, now writing output to file.");
//
//
// File file=new File("src/edu/cmu/tetradproj/amurrayw/output_old_inputs.txt");
// try {
// FileOutputStream out = new FileOutputStream(file);
// PrintStream outStream = new PrintStream(out);
// outStream.println(result.getDmStructure().latentStructToEdgeListGraph(result.getDmStructure()));
// //outStream.println();
// }
// catch (java.io.FileNotFoundException e) {
// System.out.println("Can't write to file.");
//
// }
//
//
// //System.out.println(result.getDmStructure().latentStructToEdgeListGraph(result.getDmStructure()));
// System.out.println("DONE");
}
public void rtest9() {
internaltest9(10);
}
public int internaltest9(double initialDiscount) {
RandomUtil.getInstance().setSeed(29483818483L);
int nInputs = 17610;
int nOutputs = 12042;
int[] inputs = new int[nInputs];
int[] outputs = new int[nOutputs];
for (int i = 0; i < nInputs; i++) {
inputs[i] = i;
}
for (int i = 0; i < nOutputs; i++) {
outputs[i] = nInputs + i - 1;
}
System.out.println("test 9");
//Trying recursion as while loop seems to reduce speed below that of non-loop version.
//double initialDiscount = 20;
// while(initialDiscount>0){
DMSearch result = new DMSearch();
result.setAlphaPC(.000001);
result.setAlphaSober(.000001);
result.setDiscount(initialDiscount);
result =
readAndSearchData("src/edu/cmu/tetradproj/amurrayw/final_joined_data_no_par.txt",
inputs, outputs, true, inputs);
System.out.println("Finished search, now writing output to file.");
File file = new File("src/edu/cmu/tetradproj/amurrayw/final_output_" + initialDiscount + "_.txt");
try {
FileOutputStream out = new FileOutputStream(file);
PrintStream outStream = new PrintStream(out);
outStream.println(result.getDmStructure().latentStructToEdgeListGraph(result.getDmStructure()));
//outStream.println();
} catch (java.io.FileNotFoundException e) {
System.out.println("Can't write to file.");
}
File file2 = new File("src/edu/cmu/tetradproj/amurrayw/unconverted_output" + initialDiscount + "_.txt");
try {
FileOutputStream out = new FileOutputStream(file2);
PrintStream outStream = new PrintStream(out);
outStream.println(result.getDmStructure());
//outStream.println();
} catch (java.io.FileNotFoundException e) {
System.out.println("Can't write to file.");
}
// initialDiscount--;
// }
//System.out.println(result.getDmStructure().latentStructToEdgeListGraph(result.getDmStructure()));
System.out.println("DONE");
// if(initialDiscount>1){
// result=null;
// internaltest9(initialDiscount-1);
// }
return (1);
}
//
public void test10() {
//setting seed for debug.
RandomUtil.getInstance().setSeed(29483818483L);
Graph graph = GraphUtils.emptyGraph(5);
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X2"));
graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X3"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X3"));
graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X4"));
SemPm pm = new SemPm(graph);
SemIm im = new SemIm(pm);
DataSet data = im.simulateData(100000, false);
DMSearch search = new DMSearch();
search.setUseGES(false);
search.setInputs(new int[]{0, 1});
search.setOutputs(new int[]{2, 3, 4});
search.setData(data);
search.setTrueInputs(search.getInputs());
search.search();
System.out.println("Test Case 10");
System.out.println(search.getDmStructure());
assertTrue(true);
}
public boolean listHasDuplicates(List<Node> list) {
for (Node node : list) {
list.remove(node);
if (list.contains(node)) {
return (true);
}
}
return (false);
}
public boolean cycleExists(Graph graph, List<Node> adjacentNodes, List<Node> path, Node currentNode) {
if (adjacentNodes.isEmpty() && path.isEmpty()) {
for (Node node : graph.getNodes()) {
adjacentNodes = graph.getAdjacentNodes(node);
if (adjacentNodes.isEmpty()) {
continue;
}
path.add(node);
currentNode = node;
System.out.println("RAN: " + adjacentNodes + " " + path + " " + currentNode);
return (cycleExists(graph, adjacentNodes, path, currentNode));
}
} else {
adjacentNodes = graph.getAdjacentNodes(currentNode);
for (Node node : adjacentNodes) {
if (path.lastIndexOf(node) == (path.size() - 1)) {
continue;
} else {
path.add(node);
currentNode = node;
return (cycleExists(graph, adjacentNodes, path, currentNode));
}
}
if (listHasDuplicates(path)) {
return (true);
}
}
return (false);
}
public void rtest11() {
//setting seed for debug.
RandomUtil.getInstance().setSeed(29483818483L);
Graph graph = GraphUtils.emptyGraph(4);
Node X0 = graph.getNode("X0");
Node X1 = graph.getNode("X1");
Node X2 = graph.getNode("X2");
Node X3 = graph.getNode("X3");
graph.addDirectedEdge(X0, X2);
graph.addDirectedEdge(X2, X3);
graph.addDirectedEdge(X3, X0);
System.out.print(graph.existsDirectedPathFromTo(X0, X3));
System.out.print(graph.existsDirectedPathFromTo(X3, X0));
for (Node node : graph.getNodes()) {
System.out.println("Nodes adjacent to " + node + ": " + graph.getAdjacentNodes(node) + "\n");
}
System.out.println("graph.existsDirectedCycle: " + graph.existsDirectedCycle());
System.out.println("Graph structure: " + graph);
assertTrue(true);
}
public void rtest12() {
//setting seed for debug.
RandomUtil.getInstance().setSeed(29483818483L);
Graph graph = GraphUtils.emptyGraph(9);
Node X0 = graph.getNode("X0");
Node X1 = graph.getNode("X1");
Node X2 = graph.getNode("X2");
Node X3 = graph.getNode("X3");
Node X4 = graph.getNode("X4");
Node X5 = graph.getNode("X5");
Node X6 = graph.getNode("X6");
Node X7 = graph.getNode("X7");
Node X8 = graph.getNode("X8");
graph.addDirectedEdge(X0, X6);
graph.addDirectedEdge(X0, X7);
graph.addDirectedEdge(X0, X8);
graph.addDirectedEdge(X1, X6);
graph.addDirectedEdge(X1, X7);
graph.addDirectedEdge(X1, X8);
graph.addDirectedEdge(X2, X6);
graph.addDirectedEdge(X2, X7);
graph.addDirectedEdge(X2, X8);
graph.addDirectedEdge(X3, X8);
graph.addDirectedEdge(X3, X7);
graph.addDirectedEdge(X4, X8);
graph.addDirectedEdge(X4, X7);
graph.addDirectedEdge(X5, X8);
RandomUtil.getInstance().setSeed(29483818483L);
SemPm pm = new SemPm(graph);
SemIm im = new SemIm(pm);
DataSet data = im.simulateData(100000, false);
DMSearch search = new DMSearch();
search.setInputs(new int[]{0, 1, 2, 3, 4, 5});
search.setOutputs(new int[]{6, 7, 8});
search.setData(data);
search.setTrueInputs(search.getInputs());
search.search();
System.out.println("");
System.out.println("" + search.getDmStructure());
System.out.println("graph.existsDirectedCycle: " + search.getDmStructure().latentStructToEdgeListGraph(search.getDmStructure()).existsDirectedCycle());
System.out.println("Graph structure: " + search);
assertTrue(true);
}
public void rtest13() {
//setting seed for debug.
RandomUtil.getInstance().setSeed(29483818483L);
Graph graph = GraphUtils.emptyGraph(12);
Node X0 = graph.getNode("X0");
Node X1 = graph.getNode("X1");
Node X2 = graph.getNode("X2");
Node X3 = graph.getNode("X3");
Node X4 = graph.getNode("X4");
Node X5 = graph.getNode("X5");
Node X6 = graph.getNode("X6");
Node X7 = graph.getNode("X7");
Node X8 = graph.getNode("X8");
Node X9 = graph.getNode("X9");
Node X10 = graph.getNode("X10");
Node X11 = graph.getNode("X11");
graph.addDirectedEdge(X0, X6);
graph.addDirectedEdge(X1, X6);
graph.addDirectedEdge(X1, X7);
graph.addDirectedEdge(X1, X8);
graph.addDirectedEdge(X2, X8);
graph.addDirectedEdge(X3, X8);
graph.addDirectedEdge(X3, X9);
graph.addDirectedEdge(X3, X10);
graph.addDirectedEdge(X3, X9);
graph.addDirectedEdge(X4, X10);
graph.addDirectedEdge(X4, X11);
graph.addDirectedEdge(X5, X11);
//
// graph.addDirectedEdge(X1, X8);
// graph.addDirectedEdge(X2, X6);
// graph.addDirectedEdge(X2, X7);
// graph.addDirectedEdge(X2, X8);
//
//
// graph.addDirectedEdge(X3, X8);
// graph.addDirectedEdge(X3, X7);
// graph.addDirectedEdge(X4, X8);
// graph.addDirectedEdge(X4, X7);
//
//
// graph.addDirectedEdge(X5, X8);
RandomUtil.getInstance().setSeed(29483818483L);
SemPm pm = new SemPm(graph);
SemIm im = new SemIm(pm);
DataSet data = im.simulateData(100000, false);
DMSearch search = new DMSearch();
search.setInputs(new int[]{0, 1, 2, 3, 4, 5});
search.setOutputs(new int[]{6, 7, 8, 9, 10, 11});
search.setData(data);
search.setTrueInputs(search.getInputs());
search.search();
System.out.println("");
System.out.println("" + search.getDmStructure());
System.out.println("graph.existsDirectedCycle: " + search.getDmStructure().latentStructToEdgeListGraph(search.getDmStructure()).existsDirectedCycle());
System.out.println("Graph structure: " + search);
assertTrue(true);
}
public void rtest16() {
System.out.println("test PC");
DMSearch result =
readAndSearchData("src/edu/cmu/tetradproj/amurrayw/testcase7_fixed.txt",
new int[]{0, 1}, new int[]{2, 3}, false, new int[]{0, 1});
File file = new File("src/edu/cmu/tetradproj/amurrayw/output_test7_fixed.txt");
try {
FileOutputStream out = new FileOutputStream(file);
PrintStream outStream = new PrintStream(out);
outStream.println(result.getDmStructure().latentStructToEdgeListGraph(result.getDmStructure()));
outStream.println();
} catch (java.io.FileNotFoundException e) {
System.out.println("Can't write to file.");
}
System.out.println(result.getDmStructure().latentStructToEdgeListGraph(result.getDmStructure()));
System.out.println("DONE");
}
public void rtest17() {
internaltest17(999);
}
public int internaltest17(double initialDiscount) {
//TODO: to fix input files, need to run following sed: sed -i 's/[[:space:]]\+/ /g'
RandomUtil.getInstance().setSeed(29483818483L);
int nInputs = 17610;
int nOutputs = 12042;
int[] inputs = new int[nInputs];
int[] outputs = new int[nOutputs];
int[] trueInputs = new int[]{2761, 2762, 4450, 2247, 16137, 13108, 12530, 231, 1223, 1379, 5379, 12745,
14913, 16066, 16197, 16199, 17353, 17392, 4397, 3009, 3143, 5478, 5479, 5480,
5481, 5482, 7474, 12884, 12885, 12489, 9112, 1943, 9114, 1950, 9644, 9645,
9647};
for (int i = 0; i < nInputs; i++) {
inputs[i] = i;
}
for (int i = 0; i < nOutputs; i++) {
outputs[i] = nInputs + i - 1;
}
System.out.println("test 17");
//Trying recursion as while loop seems to reduce speed below that of non-loop version.
//double initialDiscount = 20;
// while(initialDiscount>0){
DMSearch result = new DMSearch();
// result.setAlphaPC(1e-30);
// result.setAlphaSober(1e-30);
result.setAlphaPC(1e-6);
result.setAlphaSober(1e-6);
result.setDiscount(initialDiscount);
result =
readAndSearchData("src/edu/cmu/tetradproj/amurrayw/final_joined_data_no_par_fixed.txt",
inputs, outputs, false, trueInputs);
System.out.println("Finished search, now writing output to file.");
File file = new File("src/edu/cmu/tetradproj/amurrayw/final_output_" + initialDiscount + "_.txt");
try {
FileOutputStream out = new FileOutputStream(file);
PrintStream outStream = new PrintStream(out);
outStream.println(result.getDmStructure().latentStructToEdgeListGraph(result.getDmStructure()));
//outStream.println();
} catch (java.io.FileNotFoundException e) {
System.out.println("Can't write to file.");
}
File file2 = new File("src/edu/cmu/tetradproj/amurrayw/unconverted_output" + initialDiscount + "_.txt");
try {
FileOutputStream out = new FileOutputStream(file2);
PrintStream outStream = new PrintStream(out);
outStream.println(result.getDmStructure());
//outStream.println();
} catch (java.io.FileNotFoundException e) {
System.out.println("Can't write to file.");
}
// initialDiscount--;
// }
//System.out.println(result.getDmStructure().latentStructToEdgeListGraph(result.getDmStructure()));
System.out.println("DONE");
// if(initialDiscount>1){
// result=null;
// internaltest9(initialDiscount-1);
// }
return (1);
}
public void rtest14() {
//setting seed for debug.
// RandomUtil.getInstance().setSeed(29483818483L);
//
//
// Graph graph = GraphUtils.emptyGraph(5);
//
// graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X2"));
// graph.addDirectedEdge(new GraphNode("X0"), new GraphNode("X3"));
// graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X3"));
// graph.addDirectedEdge(new GraphNode("X1"), new GraphNode("X4"));
//
//
// SemPm pm = new SemPm(graph);
// SemIm im = new SemIm(pm);
//
// DataSet data = im.simulateData(100000, false);
//
// DMSearch search = new DMSearch();
//
// search.setInputs(new int[]{0, 1});
// search.setOutputs(new int[]{2, 3, 4});
//
// search.search(data);
//
// System.out.println("Test Case 10");
// System.out.println(search.getDmStructure());
assertTrue(true);
}
public void rtest15() {
// for(int i=10; i>=4; i--){
// finishRenaming(i);
// }
finishRenaming(999);
}
public void finishRenaming(int penalty) {
String currentLine;
try {
FileReader file = new FileReader("src/edu/cmu/tetradproj/amurrayw/final_run/renamed_graph_penalty" + penalty + ".r.txt");
BufferedReader br = new BufferedReader(file);
String[] varNames = null;
int nVar = 0;
int lineNumber = 0;
Graph graph = new EdgeListGraph();
while ((currentLine = br.readLine()) != null) {
//finds/gets variable names and adds to graph. Note that it assumes no whitespace in variable names.
if (lineNumber == 0) {
varNames = currentLine.split("\\s+");
nVar = varNames.length;
for (String nodeName : varNames) {
graph.addNode(new GraphNode(nodeName));
}
} else {
//splits line to single
String[] adjInfoString = currentLine.split("\\s+");
for (int i = 0; i < nVar; i++) {
;
if (Integer.parseInt(adjInfoString[i]) > 1) {
System.out.println(adjInfoString[i]);
} else if (Integer.parseInt(adjInfoString[i]) < 0) {
System.out.println(adjInfoString[i]);
}
// System.out.println(adjInfoString[i]);
if (Integer.parseInt(adjInfoString[i]) == 1) {
// System.out.println("i");
// System.out.println(i);
//
// System.out.println("varNames[i]");
// System.out.println(varNames[i]);
//
//
// System.out.println("lineNumber");
// System.out.println(lineNumber);
//
// System.out.println("varNames.length");
// System.out.println(varNames.length);
//
//
// System.out.println("varNames[lineNumber]");
// System.out.println(varNames[lineNumber]);
graph.addDirectedEdge(graph.getNode(varNames[lineNumber - 1]), graph.getNode(varNames[i]));
// graph.addDirectedEdge(graph.getNode(varNames[i]), graph.getNode(varNames[lineNumber]));
}
}
}
lineNumber++;
// System.out.println(currentLine);
}
File outfile = new File("src/edu/cmu/tetradproj/amurrayw/final_run/renamed_final_output_" + penalty + "_.txt");
try {
FileOutputStream out = new FileOutputStream(outfile);
PrintStream outStream = new PrintStream(out);
outStream.println(graph);
//outStream.println();
} catch (java.io.FileNotFoundException e) {
System.out.println("Can't write to file.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
//Reads in data and runs search. Note: Assumes variable names are of the form X0, X1, etc.
// Both input and output integer arrays are the indexes of their respective variables.
public DMSearch readAndSearchData(String fileLocation, int[] inputs, int[] outputs, boolean useGES, int[] trueInputs) {
File file = new File(fileLocation);
DataSet data = null;
try {
data = BigDataSetUtility.readInContinuousData(file, ' ');
} catch (IOException e) {
System.out.println("Failed to read in data.");
e.printStackTrace();
}
System.out.println("Read Data");
DMSearch search = new DMSearch();
search.setInputs(inputs);
search.setOutputs(outputs);
if (useGES == false) {
search.setAlphaPC(.05);
search.setUseGES(useGES);
search.setData(data);
search.setTrueInputs(trueInputs);
search.search();
} else {
search.setData(data);
search.setTrueInputs(trueInputs);
search.search();
// search.search(data, trueInputs);
}
return (search);
}
/**
* This method uses reflection to collect up all of the test methods from this class and return them to the test
* runner.
*/
public static Test suite() {
// Edit the name of the class in the parens to match the name
// of this class.
return new TestSuite(TestDM.class);
}
public static void main(String... args) {
new TestDM("Foo").test8();
}
}
| gpl-2.0 |
leonjaramillo/VARIAMOS | com.variamos.syntaxsupport/src/com/variamos/syntaxsupport/metamodelsupport/IntervalDomain.java | 515 | package com.variamos.syntaxsupport.metamodelsupport;
/**
* document
* Part of PhD work at University of Paris 1
* @author Juan C. Muñoz Fernández <jcmunoz@gmail.com>
*
* @version 1.1
* @since 2014-11-24
*/
public class IntervalDomain extends Domain {
/**
*
*/
private static final long serialVersionUID = -1645145411048599254L;
private int lowerValue;
private int upperValue;
public int getLowerValue() {
return lowerValue;
}
public int getUpperValue() {
return upperValue;
}
}
| gpl-2.0 |
Taichi-SHINDO/jdk9-jdk | src/java.naming/share/classes/com/sun/naming/internal/ResourceManager.java | 23466 | /*
* Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.naming.internal;
import java.io.InputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.List;
import java.util.ArrayList;
import java.util.WeakHashMap;
import javax.naming.*;
/**
* The ResourceManager class facilitates the reading of JNDI resource files.
*
* @author Rosanna Lee
* @author Scott Seligman
*/
public final class ResourceManager {
/*
* Name of provider resource files (without the package-name prefix.)
*/
private static final String PROVIDER_RESOURCE_FILE_NAME =
"jndiprovider.properties";
/*
* Name of application resource files.
*/
private static final String APP_RESOURCE_FILE_NAME = "jndi.properties";
/*
* Name of properties file in <java.home>/conf.
*/
private static final String JRE_CONF_PROPERTY_FILE_NAME = "jndi.properties";
/*
* Internal environment property, that when set to "true", disables
* application resource files lookup to prevent recursion issues
* when validating signed JARs.
*/
private static final String DISABLE_APP_RESOURCE_FILES =
"com.sun.naming.disable.app.resource.files";
/*
* The standard JNDI properties that specify colon-separated lists.
*/
private static final String[] listProperties = {
Context.OBJECT_FACTORIES,
Context.URL_PKG_PREFIXES,
Context.STATE_FACTORIES,
// The following shouldn't create a runtime dependence on ldap package.
javax.naming.ldap.LdapContext.CONTROL_FACTORIES
};
private static final VersionHelper helper =
VersionHelper.getVersionHelper();
/*
* A cache of the properties that have been constructed by
* the ResourceManager. A Hashtable from a provider resource
* file is keyed on a class in the resource file's package.
* One from application resource files is keyed on the thread's
* context class loader.
*/
// WeakHashMap<Class | ClassLoader, Hashtable>
private static final WeakHashMap<Object, Hashtable<? super String, Object>>
propertiesCache = new WeakHashMap<>(11);
/*
* A cache of factory objects (ObjectFactory, StateFactory, ControlFactory).
*
* A two-level cache keyed first on context class loader and then
* on propValue. Value is a list of class or factory objects,
* weakly referenced so as not to prevent GC of the class loader.
* Used in getFactories().
*/
private static final
WeakHashMap<ClassLoader, Map<String, List<NamedWeakReference<Object>>>>
factoryCache = new WeakHashMap<>(11);
/*
* A cache of URL factory objects (ObjectFactory).
*
* A two-level cache keyed first on context class loader and then
* on classSuffix+propValue. Value is the factory itself (weakly
* referenced so as not to prevent GC of the class loader) or
* NO_FACTORY if a previous search revealed no factory. Used in
* getFactory().
*/
private static final
WeakHashMap<ClassLoader, Map<String, WeakReference<Object>>>
urlFactoryCache = new WeakHashMap<>(11);
private static final WeakReference<Object> NO_FACTORY =
new WeakReference<>(null);
// There should be no instances of this class.
private ResourceManager() {
}
// ---------- Public methods ----------
/**
* Given the environment parameter passed to the initial context
* constructor, returns the full environment for that initial
* context (never null). This is based on the environment
* parameter, the system properties, and all application resource files.
*
* <p> This method will modify <tt>env</tt> and save
* a reference to it. The caller may no longer modify it.
*
* @param env environment passed to initial context constructor.
* Null indicates an empty environment.
*
* @throws NamingException if an error occurs while reading a
* resource file
*/
@SuppressWarnings("unchecked")
public static Hashtable<?, ?> getInitialEnvironment(Hashtable<?, ?> env)
throws NamingException
{
String[] props = VersionHelper.PROPS; // system properties
if (env == null) {
env = new Hashtable<>(11);
}
// Merge property values from env param, and system properties.
// The first value wins: there's no concatenation of
// colon-separated lists.
// Read system properties by first trying System.getProperties(),
// and then trying System.getProperty() if that fails. The former
// is more efficient due to fewer permission checks.
//
String[] jndiSysProps = helper.getJndiProperties();
for (int i = 0; i < props.length; i++) {
Object val = env.get(props[i]);
if (val == null) {
// Read system property.
val = (jndiSysProps != null)
? jndiSysProps[i]
: helper.getJndiProperty(i);
}
if (val != null) {
((Hashtable<String, Object>)env).put(props[i], val);
}
}
// Return without merging if application resource files lookup
// is disabled.
String disableAppRes = (String)env.get(DISABLE_APP_RESOURCE_FILES);
if (disableAppRes != null && disableAppRes.equalsIgnoreCase("true")) {
return env;
}
// Merge the above with the values read from all application
// resource files. Colon-separated lists are concatenated.
mergeTables((Hashtable<Object, Object>)env, getApplicationResources());
return env;
}
/**
* Retrieves the property from the environment, or from the provider
* resource file associated with the given context. The environment
* may in turn contain values that come from system properties,
* or application resource files.
*
* If <tt>concat</tt> is true and both the environment and the provider
* resource file contain the property, the two values are concatenated
* (with a ':' separator).
*
* Returns null if no value is found.
*
* @param propName The non-null property name
* @param env The possibly null environment properties
* @param ctx The possibly null context
* @param concat True if multiple values should be concatenated
* @return the property value, or null is there is none.
* @throws NamingException if an error occurs while reading the provider
* resource file.
*/
public static String getProperty(String propName, Hashtable<?,?> env,
Context ctx, boolean concat)
throws NamingException {
String val1 = (env != null) ? (String)env.get(propName) : null;
if ((ctx == null) ||
((val1 != null) && !concat)) {
return val1;
}
String val2 = (String)getProviderResource(ctx).get(propName);
if (val1 == null) {
return val2;
} else if ((val2 == null) || !concat) {
return val1;
} else {
return (val1 + ":" + val2);
}
}
/**
* Retrieves an enumeration of factory classes/object specified by a
* property.
*
* The property is gotten from the environment and the provider
* resource file associated with the given context and concatenated.
* See getProperty(). The resulting property value is a list of class names.
*<p>
* This method then loads each class using the current thread's context
* class loader and keeps them in a list. Any class that cannot be loaded
* is ignored. The resulting list is then cached in a two-level
* hash table, keyed first by the context class loader and then by
* the property's value.
* The next time threads of the same context class loader call this
* method, they can use the cached list.
*<p>
* After obtaining the list either from the cache or by creating one from
* the property value, this method then creates and returns a
* FactoryEnumeration using the list. As the FactoryEnumeration is
* traversed, the cached Class object in the list is instantiated and
* replaced by an instance of the factory object itself. Both class
* objects and factories are wrapped in weak references so as not to
* prevent GC of the class loader.
*<p>
* Note that multiple threads can be accessing the same cached list
* via FactoryEnumeration, which locks the list during each next().
* The size of the list will not change,
* but a cached Class object might be replaced by an instantiated factory
* object.
*
* @param propName The non-null property name
* @param env The possibly null environment properties
* @param ctx The possibly null context
* @return An enumeration of factory classes/objects; null if none.
* @exception NamingException If encounter problem while reading the provider
* property file.
* @see javax.naming.spi.NamingManager#getObjectInstance
* @see javax.naming.spi.NamingManager#getStateToBind
* @see javax.naming.spi.DirectoryManager#getObjectInstance
* @see javax.naming.spi.DirectoryManager#getStateToBind
* @see javax.naming.ldap.ControlFactory#getControlInstance
*/
public static FactoryEnumeration getFactories(String propName,
Hashtable<?,?> env, Context ctx) throws NamingException {
String facProp = getProperty(propName, env, ctx, true);
if (facProp == null)
return null; // no classes specified; return null
// Cache is based on context class loader and property val
ClassLoader loader = helper.getContextClassLoader();
Map<String, List<NamedWeakReference<Object>>> perLoaderCache = null;
synchronized (factoryCache) {
perLoaderCache = factoryCache.get(loader);
if (perLoaderCache == null) {
perLoaderCache = new HashMap<>(11);
factoryCache.put(loader, perLoaderCache);
}
}
synchronized (perLoaderCache) {
List<NamedWeakReference<Object>> factories =
perLoaderCache.get(facProp);
if (factories != null) {
// Cached list
return factories.size() == 0 ? null
: new FactoryEnumeration(factories, loader);
} else {
// Populate list with classes named in facProp; skipping
// those that we cannot load
StringTokenizer parser = new StringTokenizer(facProp, ":");
factories = new ArrayList<>(5);
while (parser.hasMoreTokens()) {
try {
// System.out.println("loading");
String className = parser.nextToken();
Class<?> c = helper.loadClass(className, loader);
factories.add(new NamedWeakReference<Object>(c, className));
} catch (Exception e) {
// ignore ClassNotFoundException, IllegalArgumentException
}
}
// System.out.println("adding to cache: " + factories);
perLoaderCache.put(facProp, factories);
return new FactoryEnumeration(factories, loader);
}
}
}
/**
* Retrieves a factory from a list of packages specified in a
* property.
*
* The property is gotten from the environment and the provider
* resource file associated with the given context and concatenated.
* classSuffix is added to the end of this list.
* See getProperty(). The resulting property value is a list of package
* prefixes.
*<p>
* This method then constructs a list of class names by concatenating
* each package prefix with classSuffix and attempts to load and
* instantiate the class until one succeeds.
* Any class that cannot be loaded is ignored.
* The resulting object is then cached in a two-level hash table,
* keyed first by the context class loader and then by the property's
* value and classSuffix.
* The next time threads of the same context class loader call this
* method, they use the cached factory.
* If no factory can be loaded, NO_FACTORY is recorded in the table
* so that next time it'll return quickly.
*
* @param propName The non-null property name
* @param env The possibly null environment properties
* @param ctx The possibly null context
* @param classSuffix The non-null class name
* (e.g. ".ldap.ldapURLContextFactory).
* @param defaultPkgPrefix The non-null default package prefix.
* (e.g., "com.sun.jndi.url").
* @return An factory object; null if none.
* @exception NamingException If encounter problem while reading the provider
* property file, or problem instantiating the factory.
*
* @see javax.naming.spi.NamingManager#getURLContext
* @see javax.naming.spi.NamingManager#getURLObject
*/
public static Object getFactory(String propName, Hashtable<?,?> env,
Context ctx, String classSuffix, String defaultPkgPrefix)
throws NamingException {
// Merge property with provider property and supplied default
String facProp = getProperty(propName, env, ctx, true);
if (facProp != null)
facProp += (":" + defaultPkgPrefix);
else
facProp = defaultPkgPrefix;
// Cache factory based on context class loader, class name, and
// property val
ClassLoader loader = helper.getContextClassLoader();
String key = classSuffix + " " + facProp;
Map<String, WeakReference<Object>> perLoaderCache = null;
synchronized (urlFactoryCache) {
perLoaderCache = urlFactoryCache.get(loader);
if (perLoaderCache == null) {
perLoaderCache = new HashMap<>(11);
urlFactoryCache.put(loader, perLoaderCache);
}
}
synchronized (perLoaderCache) {
Object factory = null;
WeakReference<Object> factoryRef = perLoaderCache.get(key);
if (factoryRef == NO_FACTORY) {
return null;
} else if (factoryRef != null) {
factory = factoryRef.get();
if (factory != null) { // check if weak ref has been cleared
return factory;
}
}
// Not cached; find first factory and cache
StringTokenizer parser = new StringTokenizer(facProp, ":");
String className;
while (factory == null && parser.hasMoreTokens()) {
className = parser.nextToken() + classSuffix;
try {
// System.out.println("loading " + className);
factory = helper.loadClass(className, loader).newInstance();
} catch (InstantiationException e) {
NamingException ne =
new NamingException("Cannot instantiate " + className);
ne.setRootCause(e);
throw ne;
} catch (IllegalAccessException e) {
NamingException ne =
new NamingException("Cannot access " + className);
ne.setRootCause(e);
throw ne;
} catch (Exception e) {
// ignore ClassNotFoundException, IllegalArgumentException,
// etc.
}
}
// Cache it.
perLoaderCache.put(key, (factory != null)
? new WeakReference<>(factory)
: NO_FACTORY);
return factory;
}
}
// ---------- Private methods ----------
/*
* Returns the properties contained in the provider resource file
* of an object's package. Returns an empty hash table if the
* object is null or the resource file cannot be found. The
* results are cached.
*
* @throws NamingException if an error occurs while reading the file.
*/
private static Hashtable<? super String, Object>
getProviderResource(Object obj)
throws NamingException
{
if (obj == null) {
return (new Hashtable<>(1));
}
synchronized (propertiesCache) {
Class<?> c = obj.getClass();
Hashtable<? super String, Object> props =
propertiesCache.get(c);
if (props != null) {
return props;
}
props = new Properties();
InputStream istream =
helper.getResourceAsStream(c, PROVIDER_RESOURCE_FILE_NAME);
if (istream != null) {
try {
((Properties)props).load(istream);
} catch (IOException e) {
NamingException ne = new ConfigurationException(
"Error reading provider resource file for " + c);
ne.setRootCause(e);
throw ne;
}
}
propertiesCache.put(c, props);
return props;
}
}
/*
* Returns the Hashtable (never null) that results from merging
* all application resource files available to this thread's
* context class loader. The properties file in <java.home>/conf
* is also merged in. The results are cached.
*
* SECURITY NOTES:
* 1. JNDI needs permission to read the application resource files.
* 2. Any class will be able to use JNDI to view the contents of
* the application resource files in its own classpath. Give
* careful consideration to this before storing sensitive
* information there.
*
* @throws NamingException if an error occurs while reading a resource
* file.
*/
private static Hashtable<? super String, Object> getApplicationResources()
throws NamingException {
ClassLoader cl = helper.getContextClassLoader();
synchronized (propertiesCache) {
Hashtable<? super String, Object> result = propertiesCache.get(cl);
if (result != null) {
return result;
}
try {
NamingEnumeration<InputStream> resources =
helper.getResources(cl, APP_RESOURCE_FILE_NAME);
try {
while (resources.hasMore()) {
Properties props = new Properties();
InputStream istream = resources.next();
try {
props.load(istream);
} finally {
istream.close();
}
if (result == null) {
result = props;
} else {
mergeTables(result, props);
}
}
} finally {
while (resources.hasMore()) {
resources.next().close();
}
}
// Merge in properties from file in <java.home>/conf.
InputStream istream =
helper.getJavaHomeConfStream(JRE_CONF_PROPERTY_FILE_NAME);
if (istream != null) {
try {
Properties props = new Properties();
props.load(istream);
if (result == null) {
result = props;
} else {
mergeTables(result, props);
}
} finally {
istream.close();
}
}
} catch (IOException e) {
NamingException ne = new ConfigurationException(
"Error reading application resource file");
ne.setRootCause(e);
throw ne;
}
if (result == null) {
result = new Hashtable<>(11);
}
propertiesCache.put(cl, result);
return result;
}
}
/*
* Merge the properties from one hash table into another. Each
* property in props2 that is not in props1 is added to props1.
* For each property in both hash tables that is one of the
* standard JNDI properties that specify colon-separated lists,
* the values are concatenated and stored in props1.
*/
private static void mergeTables(Hashtable<? super String, Object> props1,
Hashtable<? super String, Object> props2) {
for (Object key : props2.keySet()) {
String prop = (String)key;
Object val1 = props1.get(prop);
if (val1 == null) {
props1.put(prop, props2.get(prop));
} else if (isListProperty(prop)) {
String val2 = (String)props2.get(prop);
props1.put(prop, ((String)val1) + ":" + val2);
}
}
}
/*
* Is a property one of the standard JNDI properties that specify
* colon-separated lists?
*/
private static boolean isListProperty(String prop) {
prop = prop.intern();
for (int i = 0; i < listProperties.length; i++) {
if (prop == listProperties[i]) {
return true;
}
}
return false;
}
}
| gpl-2.0 |
dmacvicar/spacewalk | java/code/src/com/redhat/rhn/domain/kickstart/KickstartDefaultRegToken.java | 3047 | /**
* Copyright (c) 2009--2010 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package com.redhat.rhn.domain.kickstart;
import com.redhat.rhn.domain.token.Token;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import java.io.Serializable;
import java.util.Date;
/**
* KickstartDefaultRegToken - Class representation of the table rhnkickstartdefaultregtoken.
* @version $Rev: 1 $
*/
public class KickstartDefaultRegToken implements Serializable {
private KickstartData ksdata;
private Token token;
private Date created;
private Date modified;
/**
* Getter for kickstartId
* @return KickstartData to get
*/
public KickstartData getKsdata() {
return this.ksdata;
}
/**
* Setter for ksdata
* @param ksdataIn to set
*/
public void setKsdata(KickstartData ksdataIn) {
this.ksdata = ksdataIn;
}
/**
* Getter for token
* @return Token to get
*/
public Token getToken() {
return this.token;
}
/**
* Setter for regtokenId
* @param tokenIn to set
*/
public void setToken(Token tokenIn) {
this.token = tokenIn;
}
/**
* Getter for created
* @return Date to get
*/
public Date getCreated() {
return this.created;
}
/**
* Setter for created
* @param createdIn to set
*/
public void setCreated(Date createdIn) {
this.created = createdIn;
}
/**
* Getter for modified
* @return Date to get
*/
public Date getModified() {
return this.modified;
}
/**
* Setter for modified
* @param modifiedIn to set
*/
public void setModified(Date modifiedIn) {
this.modified = modifiedIn;
}
/**
* {@inheritDoc}
*/
public boolean equals(final Object other) {
if (!(other instanceof KickstartDefaultRegToken)) {
return false;
}
KickstartDefaultRegToken castOther = (KickstartDefaultRegToken) other;
return new EqualsBuilder().append(ksdata, castOther.ksdata)
.append(token, castOther.token)
.isEquals();
}
/**
* {@inheritDoc}
*/
public int hashCode() {
return new HashCodeBuilder().append(ksdata)
.append(token)
.toHashCode();
}
}
| gpl-2.0 |
smarr/GraalVM | graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/SafepointNode.java | 1798 | /*
* Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.nodes;
import com.oracle.graal.compiler.common.type.*;
import com.oracle.graal.graph.*;
import com.oracle.graal.nodeinfo.*;
import com.oracle.graal.nodes.spi.*;
/**
* Marks a position in the graph where a safepoint should be emitted.
*/
@NodeInfo
public final class SafepointNode extends DeoptimizingFixedWithNextNode implements LIRLowerable {
public static final NodeClass<SafepointNode> TYPE = NodeClass.create(SafepointNode.class);
public SafepointNode() {
super(TYPE, StampFactory.forVoid());
}
@Override
public void generate(NodeLIRBuilderTool gen) {
gen.visitSafepointNode(this);
}
@Override
public boolean canDeoptimize() {
return true;
}
}
| gpl-2.0 |
armenrz/adempiere | base/src/org/eevolution/model/X_PP_Order_Node.java | 39101 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/** Generated Model - DO NOT CHANGE */
package org.eevolution.model;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Properties;
import org.compiere.model.*;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
/** Generated Model for PP_Order_Node
* @author Adempiere (generated)
* @version Release 3.8.0 - $Id$ */
public class X_PP_Order_Node extends PO implements I_PP_Order_Node, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20150101L;
/** Standard Constructor */
public X_PP_Order_Node (Properties ctx, int PP_Order_Node_ID, String trxName)
{
super (ctx, PP_Order_Node_ID, trxName);
/** if (PP_Order_Node_ID == 0)
{
setAction (null);
// Z
setAD_WF_Node_ID (0);
setAD_Workflow_ID (0);
setCost (Env.ZERO);
setEntityType (null);
// U
setIsCentrallyMaintained (false);
setJoinElement (null);
// X
setLimit (0);
setName (null);
setPP_Order_ID (0);
setPP_Order_Node_ID (0);
setPP_Order_Workflow_ID (0);
setPriority (0);
setSplitElement (null);
// X
setValue (null);
setWaitingTime (0);
setWorkingTime (0);
setXPosition (0);
setYPosition (0);
} */
}
/** Load Constructor */
public X_PP_Order_Node (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 3 - Client - Org
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_PP_Order_Node[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Action AD_Reference_ID=302 */
public static final int ACTION_AD_Reference_ID=302;
/** Wait (Sleep) = Z */
public static final String ACTION_WaitSleep = "Z";
/** User Choice = C */
public static final String ACTION_UserChoice = "C";
/** Sub Workflow = F */
public static final String ACTION_SubWorkflow = "F";
/** Set Variable = V */
public static final String ACTION_SetVariable = "V";
/** User Window = W */
public static final String ACTION_UserWindow = "W";
/** User Form = X */
public static final String ACTION_UserForm = "X";
/** Apps Task = T */
public static final String ACTION_AppsTask = "T";
/** Apps Report = R */
public static final String ACTION_AppsReport = "R";
/** Apps Process = P */
public static final String ACTION_AppsProcess = "P";
/** Document Action = D */
public static final String ACTION_DocumentAction = "D";
/** EMail = M */
public static final String ACTION_EMail = "M";
/** User Workbench = B */
public static final String ACTION_UserWorkbench = "B";
/** Smart View = Q */
public static final String ACTION_SmartView = "Q";
/** Smart Browse = S */
public static final String ACTION_SmartBrowse = "S";
/** Set Action.
@param Action
Indicates the Action to be performed
*/
public void setAction (String Action)
{
set_Value (COLUMNNAME_Action, Action);
}
/** Get Action.
@return Indicates the Action to be performed
*/
public String getAction ()
{
return (String)get_Value(COLUMNNAME_Action);
}
public org.compiere.model.I_AD_Column getAD_Column() throws RuntimeException
{
return (org.compiere.model.I_AD_Column)MTable.get(getCtx(), org.compiere.model.I_AD_Column.Table_Name)
.getPO(getAD_Column_ID(), get_TrxName()); }
/** Set Column.
@param AD_Column_ID
Column in the table
*/
public void setAD_Column_ID (int AD_Column_ID)
{
if (AD_Column_ID < 1)
set_Value (COLUMNNAME_AD_Column_ID, null);
else
set_Value (COLUMNNAME_AD_Column_ID, Integer.valueOf(AD_Column_ID));
}
/** Get Column.
@return Column in the table
*/
public int getAD_Column_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Column_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_Form getAD_Form() throws RuntimeException
{
return (org.compiere.model.I_AD_Form)MTable.get(getCtx(), org.compiere.model.I_AD_Form.Table_Name)
.getPO(getAD_Form_ID(), get_TrxName()); }
/** Set Special Form.
@param AD_Form_ID
Special Form
*/
public void setAD_Form_ID (int AD_Form_ID)
{
if (AD_Form_ID < 1)
set_Value (COLUMNNAME_AD_Form_ID, null);
else
set_Value (COLUMNNAME_AD_Form_ID, Integer.valueOf(AD_Form_ID));
}
/** Get Special Form.
@return Special Form
*/
public int getAD_Form_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Form_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_Image getAD_Image() throws RuntimeException
{
return (org.compiere.model.I_AD_Image)MTable.get(getCtx(), org.compiere.model.I_AD_Image.Table_Name)
.getPO(getAD_Image_ID(), get_TrxName()); }
/** Set Image.
@param AD_Image_ID
Image or Icon
*/
public void setAD_Image_ID (int AD_Image_ID)
{
if (AD_Image_ID < 1)
set_Value (COLUMNNAME_AD_Image_ID, null);
else
set_Value (COLUMNNAME_AD_Image_ID, Integer.valueOf(AD_Image_ID));
}
/** Get Image.
@return Image or Icon
*/
public int getAD_Image_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Image_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_Process getAD_Process() throws RuntimeException
{
return (org.compiere.model.I_AD_Process)MTable.get(getCtx(), org.compiere.model.I_AD_Process.Table_Name)
.getPO(getAD_Process_ID(), get_TrxName()); }
/** Set Process.
@param AD_Process_ID
Process or Report
*/
public void setAD_Process_ID (int AD_Process_ID)
{
if (AD_Process_ID < 1)
set_Value (COLUMNNAME_AD_Process_ID, null);
else
set_Value (COLUMNNAME_AD_Process_ID, Integer.valueOf(AD_Process_ID));
}
/** Get Process.
@return Process or Report
*/
public int getAD_Process_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Process_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_Task getAD_Task() throws RuntimeException
{
return (org.compiere.model.I_AD_Task)MTable.get(getCtx(), org.compiere.model.I_AD_Task.Table_Name)
.getPO(getAD_Task_ID(), get_TrxName()); }
/** Set OS Task.
@param AD_Task_ID
Operation System Task
*/
public void setAD_Task_ID (int AD_Task_ID)
{
if (AD_Task_ID < 1)
set_Value (COLUMNNAME_AD_Task_ID, null);
else
set_Value (COLUMNNAME_AD_Task_ID, Integer.valueOf(AD_Task_ID));
}
/** Get OS Task.
@return Operation System Task
*/
public int getAD_Task_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Task_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_WF_Block getAD_WF_Block() throws RuntimeException
{
return (org.compiere.model.I_AD_WF_Block)MTable.get(getCtx(), org.compiere.model.I_AD_WF_Block.Table_Name)
.getPO(getAD_WF_Block_ID(), get_TrxName()); }
/** Set Workflow Block.
@param AD_WF_Block_ID
Workflow Transaction Execution Block
*/
public void setAD_WF_Block_ID (int AD_WF_Block_ID)
{
if (AD_WF_Block_ID < 1)
set_Value (COLUMNNAME_AD_WF_Block_ID, null);
else
set_Value (COLUMNNAME_AD_WF_Block_ID, Integer.valueOf(AD_WF_Block_ID));
}
/** Get Workflow Block.
@return Workflow Transaction Execution Block
*/
public int getAD_WF_Block_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_WF_Block_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_WF_Node getAD_WF_Node() throws RuntimeException
{
return (org.compiere.model.I_AD_WF_Node)MTable.get(getCtx(), org.compiere.model.I_AD_WF_Node.Table_Name)
.getPO(getAD_WF_Node_ID(), get_TrxName()); }
/** Set Node.
@param AD_WF_Node_ID
Workflow Node (activity), step or process
*/
public void setAD_WF_Node_ID (int AD_WF_Node_ID)
{
if (AD_WF_Node_ID < 1)
set_Value (COLUMNNAME_AD_WF_Node_ID, null);
else
set_Value (COLUMNNAME_AD_WF_Node_ID, Integer.valueOf(AD_WF_Node_ID));
}
/** Get Node.
@return Workflow Node (activity), step or process
*/
public int getAD_WF_Node_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_WF_Node_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_WF_Responsible getAD_WF_Responsible() throws RuntimeException
{
return (org.compiere.model.I_AD_WF_Responsible)MTable.get(getCtx(), org.compiere.model.I_AD_WF_Responsible.Table_Name)
.getPO(getAD_WF_Responsible_ID(), get_TrxName()); }
/** Set Workflow Responsible.
@param AD_WF_Responsible_ID
Responsible for Workflow Execution
*/
public void setAD_WF_Responsible_ID (int AD_WF_Responsible_ID)
{
if (AD_WF_Responsible_ID < 1)
set_Value (COLUMNNAME_AD_WF_Responsible_ID, null);
else
set_Value (COLUMNNAME_AD_WF_Responsible_ID, Integer.valueOf(AD_WF_Responsible_ID));
}
/** Get Workflow Responsible.
@return Responsible for Workflow Execution
*/
public int getAD_WF_Responsible_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_WF_Responsible_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException
{
return (org.compiere.model.I_AD_Window)MTable.get(getCtx(), org.compiere.model.I_AD_Window.Table_Name)
.getPO(getAD_Window_ID(), get_TrxName()); }
/** Set Window.
@param AD_Window_ID
Data entry or display window
*/
public void setAD_Window_ID (int AD_Window_ID)
{
if (AD_Window_ID < 1)
set_Value (COLUMNNAME_AD_Window_ID, null);
else
set_Value (COLUMNNAME_AD_Window_ID, Integer.valueOf(AD_Window_ID));
}
/** Get Window.
@return Data entry or display window
*/
public int getAD_Window_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_Workflow getAD_Workflow() throws RuntimeException
{
return (org.compiere.model.I_AD_Workflow)MTable.get(getCtx(), org.compiere.model.I_AD_Workflow.Table_Name)
.getPO(getAD_Workflow_ID(), get_TrxName()); }
/** Set Workflow.
@param AD_Workflow_ID
Workflow or combination of tasks
*/
public void setAD_Workflow_ID (int AD_Workflow_ID)
{
if (AD_Workflow_ID < 1)
set_Value (COLUMNNAME_AD_Workflow_ID, null);
else
set_Value (COLUMNNAME_AD_Workflow_ID, Integer.valueOf(AD_Workflow_ID));
}
/** Get Workflow.
@return Workflow or combination of tasks
*/
public int getAD_Workflow_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Workflow_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Attribute Name.
@param AttributeName
Name of the Attribute
*/
public void setAttributeName (String AttributeName)
{
set_Value (COLUMNNAME_AttributeName, AttributeName);
}
/** Get Attribute Name.
@return Name of the Attribute
*/
public String getAttributeName ()
{
return (String)get_Value(COLUMNNAME_AttributeName);
}
/** Set Attribute Value.
@param AttributeValue
Value of the Attribute
*/
public void setAttributeValue (String AttributeValue)
{
set_Value (COLUMNNAME_AttributeValue, AttributeValue);
}
/** Get Attribute Value.
@return Value of the Attribute
*/
public String getAttributeValue ()
{
return (String)get_Value(COLUMNNAME_AttributeValue);
}
public org.compiere.model.I_C_BPartner getC_BPartner() throws RuntimeException
{
return (org.compiere.model.I_C_BPartner)MTable.get(getCtx(), org.compiere.model.I_C_BPartner.Table_Name)
.getPO(getC_BPartner_ID(), get_TrxName()); }
/** Set Business Partner .
@param C_BPartner_ID
Identifies a Business Partner
*/
public void setC_BPartner_ID (int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_Value (COLUMNNAME_C_BPartner_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID));
}
/** Get Business Partner .
@return Identifies a Business Partner
*/
public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Cost.
@param Cost
Cost information
*/
public void setCost (BigDecimal Cost)
{
set_Value (COLUMNNAME_Cost, Cost);
}
/** Get Cost.
@return Cost information
*/
public BigDecimal getCost ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Cost);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Finish Date.
@param DateFinish
Finish or (planned) completion date
*/
public void setDateFinish (Timestamp DateFinish)
{
set_Value (COLUMNNAME_DateFinish, DateFinish);
}
/** Get Finish Date.
@return Finish or (planned) completion date
*/
public Timestamp getDateFinish ()
{
return (Timestamp)get_Value(COLUMNNAME_DateFinish);
}
/** Set Date Finish Schedule.
@param DateFinishSchedule
Scheduled Finish date for this Order
*/
public void setDateFinishSchedule (Timestamp DateFinishSchedule)
{
set_Value (COLUMNNAME_DateFinishSchedule, DateFinishSchedule);
}
/** Get Date Finish Schedule.
@return Scheduled Finish date for this Order
*/
public Timestamp getDateFinishSchedule ()
{
return (Timestamp)get_Value(COLUMNNAME_DateFinishSchedule);
}
/** Set Date Start.
@param DateStart
Date Start for this Order
*/
public void setDateStart (Timestamp DateStart)
{
set_Value (COLUMNNAME_DateStart, DateStart);
}
/** Get Date Start.
@return Date Start for this Order
*/
public Timestamp getDateStart ()
{
return (Timestamp)get_Value(COLUMNNAME_DateStart);
}
/** Set Date Start Schedule.
@param DateStartSchedule
Scheduled start date for this Order
*/
public void setDateStartSchedule (Timestamp DateStartSchedule)
{
set_Value (COLUMNNAME_DateStartSchedule, DateStartSchedule);
}
/** Get Date Start Schedule.
@return Scheduled start date for this Order
*/
public Timestamp getDateStartSchedule ()
{
return (Timestamp)get_Value(COLUMNNAME_DateStartSchedule);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** DocAction AD_Reference_ID=135 */
public static final int DOCACTION_AD_Reference_ID=135;
/** Complete = CO */
public static final String DOCACTION_Complete = "CO";
/** Approve = AP */
public static final String DOCACTION_Approve = "AP";
/** Reject = RJ */
public static final String DOCACTION_Reject = "RJ";
/** Post = PO */
public static final String DOCACTION_Post = "PO";
/** Void = VO */
public static final String DOCACTION_Void = "VO";
/** Close = CL */
public static final String DOCACTION_Close = "CL";
/** Reverse - Correct = RC */
public static final String DOCACTION_Reverse_Correct = "RC";
/** Reverse - Accrual = RA */
public static final String DOCACTION_Reverse_Accrual = "RA";
/** Invalidate = IN */
public static final String DOCACTION_Invalidate = "IN";
/** Re-activate = RE */
public static final String DOCACTION_Re_Activate = "RE";
/** <None> = -- */
public static final String DOCACTION_None = "--";
/** Prepare = PR */
public static final String DOCACTION_Prepare = "PR";
/** Unlock = XL */
public static final String DOCACTION_Unlock = "XL";
/** Wait Complete = WC */
public static final String DOCACTION_WaitComplete = "WC";
/** Set Document Action.
@param DocAction
The targeted status of the document
*/
public void setDocAction (String DocAction)
{
set_Value (COLUMNNAME_DocAction, DocAction);
}
/** Get Document Action.
@return The targeted status of the document
*/
public String getDocAction ()
{
return (String)get_Value(COLUMNNAME_DocAction);
}
/** DocStatus AD_Reference_ID=131 */
public static final int DOCSTATUS_AD_Reference_ID=131;
/** Drafted = DR */
public static final String DOCSTATUS_Drafted = "DR";
/** Completed = CO */
public static final String DOCSTATUS_Completed = "CO";
/** Approved = AP */
public static final String DOCSTATUS_Approved = "AP";
/** Not Approved = NA */
public static final String DOCSTATUS_NotApproved = "NA";
/** Voided = VO */
public static final String DOCSTATUS_Voided = "VO";
/** Invalid = IN */
public static final String DOCSTATUS_Invalid = "IN";
/** Reversed = RE */
public static final String DOCSTATUS_Reversed = "RE";
/** Closed = CL */
public static final String DOCSTATUS_Closed = "CL";
/** Unknown = ?? */
public static final String DOCSTATUS_Unknown = "??";
/** In Progress = IP */
public static final String DOCSTATUS_InProgress = "IP";
/** Waiting Payment = WP */
public static final String DOCSTATUS_WaitingPayment = "WP";
/** Waiting Confirmation = WC */
public static final String DOCSTATUS_WaitingConfirmation = "WC";
/** Set Document Status.
@param DocStatus
The current status of the document
*/
public void setDocStatus (String DocStatus)
{
set_Value (COLUMNNAME_DocStatus, DocStatus);
}
/** Get Document Status.
@return The current status of the document
*/
public String getDocStatus ()
{
return (String)get_Value(COLUMNNAME_DocStatus);
}
/** Set Duration.
@param Duration
Normal Duration in Duration Unit
*/
public void setDuration (int Duration)
{
set_Value (COLUMNNAME_Duration, Integer.valueOf(Duration));
}
/** Get Duration.
@return Normal Duration in Duration Unit
*/
public int getDuration ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Duration);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Duration Real.
@param DurationReal Duration Real */
public void setDurationReal (int DurationReal)
{
set_Value (COLUMNNAME_DurationReal, Integer.valueOf(DurationReal));
}
/** Get Duration Real.
@return Duration Real */
public int getDurationReal ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DurationReal);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Duration Required.
@param DurationRequired Duration Required */
public void setDurationRequired (int DurationRequired)
{
set_Value (COLUMNNAME_DurationRequired, Integer.valueOf(DurationRequired));
}
/** Get Duration Required.
@return Duration Required */
public int getDurationRequired ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DurationRequired);
if (ii == null)
return 0;
return ii.intValue();
}
/** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entity Type.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entity Type.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** FinishMode AD_Reference_ID=303 */
public static final int FINISHMODE_AD_Reference_ID=303;
/** Automatic = A */
public static final String FINISHMODE_Automatic = "A";
/** Manual = M */
public static final String FINISHMODE_Manual = "M";
/** Set Finish Mode.
@param FinishMode
Workflow Activity Finish Mode
*/
public void setFinishMode (String FinishMode)
{
set_Value (COLUMNNAME_FinishMode, FinishMode);
}
/** Get Finish Mode.
@return Workflow Activity Finish Mode
*/
public String getFinishMode ()
{
return (String)get_Value(COLUMNNAME_FinishMode);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Centrally maintained.
@param IsCentrallyMaintained
Information maintained in System Element table
*/
public void setIsCentrallyMaintained (boolean IsCentrallyMaintained)
{
set_Value (COLUMNNAME_IsCentrallyMaintained, Boolean.valueOf(IsCentrallyMaintained));
}
/** Get Centrally maintained.
@return Information maintained in System Element table
*/
public boolean isCentrallyMaintained ()
{
Object oo = get_Value(COLUMNNAME_IsCentrallyMaintained);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Is Milestone.
@param IsMilestone Is Milestone */
public void setIsMilestone (boolean IsMilestone)
{
set_Value (COLUMNNAME_IsMilestone, Boolean.valueOf(IsMilestone));
}
/** Get Is Milestone.
@return Is Milestone */
public boolean isMilestone ()
{
Object oo = get_Value(COLUMNNAME_IsMilestone);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Is Subcontracting.
@param IsSubcontracting Is Subcontracting */
public void setIsSubcontracting (boolean IsSubcontracting)
{
set_Value (COLUMNNAME_IsSubcontracting, Boolean.valueOf(IsSubcontracting));
}
/** Get Is Subcontracting.
@return Is Subcontracting */
public boolean isSubcontracting ()
{
Object oo = get_Value(COLUMNNAME_IsSubcontracting);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** JoinElement AD_Reference_ID=301 */
public static final int JOINELEMENT_AD_Reference_ID=301;
/** AND = A */
public static final String JOINELEMENT_AND = "A";
/** XOR = X */
public static final String JOINELEMENT_XOR = "X";
/** Set Join Element.
@param JoinElement
Semantics for multiple incoming Transitions
*/
public void setJoinElement (String JoinElement)
{
set_Value (COLUMNNAME_JoinElement, JoinElement);
}
/** Get Join Element.
@return Semantics for multiple incoming Transitions
*/
public String getJoinElement ()
{
return (String)get_Value(COLUMNNAME_JoinElement);
}
/** Set Duration Limit.
@param Limit
Maximum Duration in Duration Unit
*/
public void setLimit (int Limit)
{
set_Value (COLUMNNAME_Limit, Integer.valueOf(Limit));
}
/** Get Duration Limit.
@return Maximum Duration in Duration Unit
*/
public int getLimit ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Limit);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Moving Time.
@param MovingTime Moving Time */
public void setMovingTime (int MovingTime)
{
set_Value (COLUMNNAME_MovingTime, Integer.valueOf(MovingTime));
}
/** Get Moving Time.
@return Moving Time */
public int getMovingTime ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MovingTime);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Overlap Units.
@param OverlapUnits
Overlap Units are number of units that must be completed before they are moved the next activity
*/
public void setOverlapUnits (int OverlapUnits)
{
set_Value (COLUMNNAME_OverlapUnits, Integer.valueOf(OverlapUnits));
}
/** Get Overlap Units.
@return Overlap Units are number of units that must be completed before they are moved the next activity
*/
public int getOverlapUnits ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_OverlapUnits);
if (ii == null)
return 0;
return ii.intValue();
}
public org.eevolution.model.I_PP_Order getPP_Order() throws RuntimeException
{
return (org.eevolution.model.I_PP_Order)MTable.get(getCtx(), org.eevolution.model.I_PP_Order.Table_Name)
.getPO(getPP_Order_ID(), get_TrxName()); }
/** Set Manufacturing Order.
@param PP_Order_ID
Manufacturing Order
*/
public void setPP_Order_ID (int PP_Order_ID)
{
if (PP_Order_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, Integer.valueOf(PP_Order_ID));
}
/** Get Manufacturing Order.
@return Manufacturing Order
*/
public int getPP_Order_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Manufacturing Order Activity.
@param PP_Order_Node_ID
Workflow Node (activity), step or process
*/
public void setPP_Order_Node_ID (int PP_Order_Node_ID)
{
if (PP_Order_Node_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Node_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Node_ID, Integer.valueOf(PP_Order_Node_ID));
}
/** Get Manufacturing Order Activity.
@return Workflow Node (activity), step or process
*/
public int getPP_Order_Node_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_Node_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.eevolution.model.I_PP_Order_Workflow getPP_Order_Workflow() throws RuntimeException
{
return (org.eevolution.model.I_PP_Order_Workflow)MTable.get(getCtx(), org.eevolution.model.I_PP_Order_Workflow.Table_Name)
.getPO(getPP_Order_Workflow_ID(), get_TrxName()); }
/** Set Manufacturing Order Workflow.
@param PP_Order_Workflow_ID Manufacturing Order Workflow */
public void setPP_Order_Workflow_ID (int PP_Order_Workflow_ID)
{
if (PP_Order_Workflow_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Workflow_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Workflow_ID, Integer.valueOf(PP_Order_Workflow_ID));
}
/** Get Manufacturing Order Workflow.
@return Manufacturing Order Workflow */
public int getPP_Order_Workflow_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_Workflow_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Priority.
@param Priority
Indicates if this request is of a high, medium or low priority.
*/
public void setPriority (int Priority)
{
set_Value (COLUMNNAME_Priority, Integer.valueOf(Priority));
}
/** Get Priority.
@return Indicates if this request is of a high, medium or low priority.
*/
public int getPriority ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Priority);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Delivered Quantity.
@param QtyDelivered
Delivered Quantity
*/
public void setQtyDelivered (BigDecimal QtyDelivered)
{
set_Value (COLUMNNAME_QtyDelivered, QtyDelivered);
}
/** Get Delivered Quantity.
@return Delivered Quantity
*/
public BigDecimal getQtyDelivered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyDelivered);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Qty Reject.
@param QtyReject Qty Reject */
public void setQtyReject (BigDecimal QtyReject)
{
set_Value (COLUMNNAME_QtyReject, QtyReject);
}
/** Get Qty Reject.
@return Qty Reject */
public BigDecimal getQtyReject ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReject);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Qty Required.
@param QtyRequired Qty Required */
public void setQtyRequired (BigDecimal QtyRequired)
{
set_Value (COLUMNNAME_QtyRequired, QtyRequired);
}
/** Get Qty Required.
@return Qty Required */
public BigDecimal getQtyRequired ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyRequired);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Scrap %.
@param QtyScrap
Scrap % Quantity for this componet
*/
public void setQtyScrap (BigDecimal QtyScrap)
{
set_Value (COLUMNNAME_QtyScrap, QtyScrap);
}
/** Get Scrap %.
@return Scrap % Quantity for this componet
*/
public BigDecimal getQtyScrap ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyScrap);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Queuing Time.
@param QueuingTime
Queue time is the time a job waits at a work center before begin handled.
*/
public void setQueuingTime (int QueuingTime)
{
set_Value (COLUMNNAME_QueuingTime, Integer.valueOf(QueuingTime));
}
/** Get Queuing Time.
@return Queue time is the time a job waits at a work center before begin handled.
*/
public int getQueuingTime ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_QueuingTime);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Setup Time.
@param SetupTime
Setup time before starting Production
*/
public void setSetupTime (int SetupTime)
{
set_Value (COLUMNNAME_SetupTime, Integer.valueOf(SetupTime));
}
/** Get Setup Time.
@return Setup time before starting Production
*/
public int getSetupTime ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SetupTime);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Setup Time Real.
@param SetupTimeReal Setup Time Real */
public void setSetupTimeReal (int SetupTimeReal)
{
set_Value (COLUMNNAME_SetupTimeReal, Integer.valueOf(SetupTimeReal));
}
/** Get Setup Time Real.
@return Setup Time Real */
public int getSetupTimeReal ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SetupTimeReal);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Setup Time Required.
@param SetupTimeRequired Setup Time Required */
public void setSetupTimeRequired (int SetupTimeRequired)
{
set_Value (COLUMNNAME_SetupTimeRequired, Integer.valueOf(SetupTimeRequired));
}
/** Get Setup Time Required.
@return Setup Time Required */
public int getSetupTimeRequired ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SetupTimeRequired);
if (ii == null)
return 0;
return ii.intValue();
}
/** SplitElement AD_Reference_ID=301 */
public static final int SPLITELEMENT_AD_Reference_ID=301;
/** AND = A */
public static final String SPLITELEMENT_AND = "A";
/** XOR = X */
public static final String SPLITELEMENT_XOR = "X";
/** Set Split Element.
@param SplitElement
Semantics for multiple outgoing Transitions
*/
public void setSplitElement (String SplitElement)
{
set_Value (COLUMNNAME_SplitElement, SplitElement);
}
/** Get Split Element.
@return Semantics for multiple outgoing Transitions
*/
public String getSplitElement ()
{
return (String)get_Value(COLUMNNAME_SplitElement);
}
public org.compiere.model.I_S_Resource getS_Resource() throws RuntimeException
{
return (org.compiere.model.I_S_Resource)MTable.get(getCtx(), org.compiere.model.I_S_Resource.Table_Name)
.getPO(getS_Resource_ID(), get_TrxName()); }
/** Set Resource.
@param S_Resource_ID
Resource
*/
public void setS_Resource_ID (int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_Value (COLUMNNAME_S_Resource_ID, null);
else
set_Value (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID));
}
/** Get Resource.
@return Resource
*/
public int getS_Resource_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_Resource_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** StartMode AD_Reference_ID=303 */
public static final int STARTMODE_AD_Reference_ID=303;
/** Automatic = A */
public static final String STARTMODE_Automatic = "A";
/** Manual = M */
public static final String STARTMODE_Manual = "M";
/** Set Start Mode.
@param StartMode
Workflow Activity Start Mode
*/
public void setStartMode (String StartMode)
{
set_Value (COLUMNNAME_StartMode, StartMode);
}
/** Get Start Mode.
@return Workflow Activity Start Mode
*/
public String getStartMode ()
{
return (String)get_Value(COLUMNNAME_StartMode);
}
/** SubflowExecution AD_Reference_ID=307 */
public static final int SUBFLOWEXECUTION_AD_Reference_ID=307;
/** Asynchronously = A */
public static final String SUBFLOWEXECUTION_Asynchronously = "A";
/** Synchronously = S */
public static final String SUBFLOWEXECUTION_Synchronously = "S";
/** Set Subflow Execution.
@param SubflowExecution
Mode how the sub-workflow is executed
*/
public void setSubflowExecution (String SubflowExecution)
{
set_Value (COLUMNNAME_SubflowExecution, SubflowExecution);
}
/** Get Subflow Execution.
@return Mode how the sub-workflow is executed
*/
public String getSubflowExecution ()
{
return (String)get_Value(COLUMNNAME_SubflowExecution);
}
/** Set Units by Cycles.
@param UnitsCycles
The Units by Cycles are defined for process type Flow Repetitive Dedicated and indicated the product to be manufactured on a production line for duration unit.
*/
public void setUnitsCycles (int UnitsCycles)
{
set_Value (COLUMNNAME_UnitsCycles, Integer.valueOf(UnitsCycles));
}
/** Get Units by Cycles.
@return The Units by Cycles are defined for process type Flow Repetitive Dedicated and indicated the product to be manufactured on a production line for duration unit.
*/
public int getUnitsCycles ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UnitsCycles);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
/** Set Waiting Time.
@param WaitingTime
Workflow Simulation Waiting time
*/
public void setWaitingTime (int WaitingTime)
{
set_Value (COLUMNNAME_WaitingTime, Integer.valueOf(WaitingTime));
}
/** Get Waiting Time.
@return Workflow Simulation Waiting time
*/
public int getWaitingTime ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_WaitingTime);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_Workflow getWorkflow() throws RuntimeException
{
return (org.compiere.model.I_AD_Workflow)MTable.get(getCtx(), org.compiere.model.I_AD_Workflow.Table_Name)
.getPO(getWorkflow_ID(), get_TrxName()); }
/** Set Workflow.
@param Workflow_ID
Workflow or tasks
*/
public void setWorkflow_ID (int Workflow_ID)
{
if (Workflow_ID < 1)
set_Value (COLUMNNAME_Workflow_ID, null);
else
set_Value (COLUMNNAME_Workflow_ID, Integer.valueOf(Workflow_ID));
}
/** Get Workflow.
@return Workflow or tasks
*/
public int getWorkflow_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Workflow_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Working Time.
@param WorkingTime
Workflow Simulation Execution Time
*/
public void setWorkingTime (int WorkingTime)
{
set_Value (COLUMNNAME_WorkingTime, Integer.valueOf(WorkingTime));
}
/** Get Working Time.
@return Workflow Simulation Execution Time
*/
public int getWorkingTime ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_WorkingTime);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set X Position.
@param XPosition
Absolute X (horizontal) position in 1/72 of an inch
*/
public void setXPosition (int XPosition)
{
set_Value (COLUMNNAME_XPosition, Integer.valueOf(XPosition));
}
/** Get X Position.
@return Absolute X (horizontal) position in 1/72 of an inch
*/
public int getXPosition ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_XPosition);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Yield %.
@param Yield
The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent
*/
public void setYield (int Yield)
{
set_Value (COLUMNNAME_Yield, Integer.valueOf(Yield));
}
/** Get Yield %.
@return The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent
*/
public int getYield ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Yield);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Y Position.
@param YPosition
Absolute Y (vertical) position in 1/72 of an inch
*/
public void setYPosition (int YPosition)
{
set_Value (COLUMNNAME_YPosition, Integer.valueOf(YPosition));
}
/** Get Y Position.
@return Absolute Y (vertical) position in 1/72 of an inch
*/
public int getYPosition ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_YPosition);
if (ii == null)
return 0;
return ii.intValue();
}
} | gpl-2.0 |
YamatoMiura/kuruchan | volley/src/test/java/com/android/volley/toolbox/AndroidAuthenticatorTest.java | 4317 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.volley.toolbox;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.android.volley.AuthFailureError;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import static org.mockito.Mockito.*;
@RunWith(RobolectricTestRunner.class)
public class AndroidAuthenticatorTest {
private AccountManager mAccountManager;
private Account mAccount;
private AccountManagerFuture<Bundle> mFuture;
private AndroidAuthenticator mAuthenticator;
@Before
public void setUp() {
mAccountManager = mock(AccountManager.class);
mFuture = mock(AccountManagerFuture.class);
mAccount = new Account("coolperson", "cooltype");
mAuthenticator = new AndroidAuthenticator(mAccountManager, mAccount, "cooltype", false);
}
@Test(expected = AuthFailureError.class)
public void failedGetAuthToken() throws Exception {
when(mAccountManager.getAuthToken(mAccount, "cooltype", false, null, null)).thenReturn(mFuture);
when(mFuture.getResult()).thenThrow(new AuthenticatorException("sadness!"));
mAuthenticator.getAuthToken();
}
@Test(expected = AuthFailureError.class)
public void resultContainsIntent() throws Exception {
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
when(mAccountManager.getAuthToken(mAccount, "cooltype", false, null, null)).thenReturn(mFuture);
when(mFuture.getResult()).thenReturn(bundle);
when(mFuture.isDone()).thenReturn(true);
when(mFuture.isCancelled()).thenReturn(false);
mAuthenticator.getAuthToken();
}
@Test(expected = AuthFailureError.class)
public void missingAuthToken() throws Exception {
Bundle bundle = new Bundle();
when(mAccountManager.getAuthToken(mAccount, "cooltype", false, null, null)).thenReturn(mFuture);
when(mFuture.getResult()).thenReturn(bundle);
when(mFuture.isDone()).thenReturn(true);
when(mFuture.isCancelled()).thenReturn(false);
mAuthenticator.getAuthToken();
}
@Test
public void invalidateAuthToken() throws Exception {
mAuthenticator.invalidateAuthToken("monkey");
verify(mAccountManager).invalidateAuthToken("cooltype", "monkey");
}
@Test
public void goodToken() throws Exception {
Bundle bundle = new Bundle();
bundle.putString(AccountManager.KEY_AUTHTOKEN, "monkey");
when(mAccountManager.getAuthToken(mAccount, "cooltype", false, null, null)).thenReturn(mFuture);
when(mFuture.getResult()).thenReturn(bundle);
when(mFuture.isDone()).thenReturn(true);
when(mFuture.isCancelled()).thenReturn(false);
Assert.assertEquals("monkey", mAuthenticator.getAuthToken());
}
@Test
public void publicMethods() throws Exception {
// Catch-all test to find API-breaking changes.
Context context = mock(Context.class);
new AndroidAuthenticator(context, mAccount, "cooltype");
new AndroidAuthenticator(context, mAccount, "cooltype", true);
Assert.assertSame(mAccount, mAuthenticator.getAccount());
}
}
| gpl-2.0 |
karthikaacharya/teammates | src/main/java/teammates/ui/controller/StudentProfilePictureEditAction.java | 9571 | package teammates.ui.controller;
import java.io.IOException;
import teammates.common.util.Assumption;
import teammates.common.util.Const;
import teammates.common.util.GoogleCloudStorageHelper;
import teammates.common.util.StatusMessage;
import teammates.common.util.StatusMessageColor;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.images.CompositeTransform;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.OutputSettings;
import com.google.appengine.api.images.Transform;
/**
* Action: edits the profile picture based on the coordinates of
* the cropped photograph.
*/
public class StudentProfilePictureEditAction extends Action {
private BlobKey blobKey;
private String widthString;
private String heightString;
private String bottomYString;
private String rightXString;
private String topYString;
private String leftXString;
private String rotateString;
@Override
protected ActionResult execute() {
gateKeeper.verifyLoggedInUserPrivileges();
readAllPostParamterValuesToFields();
if (!validatePostParameters()) {
return createRedirectResult(Const.ActionURIs.STUDENT_PROFILE_PAGE);
}
try {
byte[] transformedImage = this.transformImage();
if (!isError) {
// this branch is covered in UiTests (look at todo in transformImage())
GoogleCloudStorageHelper.writeImageDataToGcs(account.googleId, transformedImage);
}
} catch (IOException e) {
// Happens when GCS Service is down
isError = true;
statusToUser.add(new StatusMessage(Const.StatusMessages.STUDENT_PROFILE_PIC_SERVICE_DOWN,
StatusMessageColor.DANGER));
statusToAdmin = Const.ACTION_RESULT_FAILURE + " : Writing transformed image to file failed. Error: "
+ e.getMessage();
}
return createRedirectResult(Const.ActionURIs.STUDENT_PROFILE_PAGE);
}
private byte[] transformImage() {
try {
/*
* This branch is covered in UiTests as the following method does
* not behave the same in dev as in staging.
* TODO: find a way to cover it in Action Tests.
*/
Image newImage = getTransformedImage();
return newImage.getImageData();
} catch (RuntimeException re) {
isError = true;
statusToUser.add(new StatusMessage(Const.StatusMessages.STUDENT_PROFILE_PICTURE_EDIT_FAILED,
StatusMessageColor.DANGER));
statusToAdmin = Const.ACTION_RESULT_FAILURE + " : Reading and transforming image failed."
+ re.getMessage();
}
return new byte[0];
}
private Image getTransformedImage() {
Assumption.assertNotNull(blobKey);
Image oldImage = ImagesServiceFactory.makeImageFromBlob(blobKey);
CompositeTransform finalTransform = getCompositeTransformToApply();
OutputSettings settings = new OutputSettings(ImagesService.OutputEncoding.PNG);
return ImagesServiceFactory.getImagesService().applyTransform(finalTransform, oldImage, settings);
}
private Transform getScaleTransform() {
Double width = Double.parseDouble(widthString);
Double height = Double.parseDouble(heightString);
return ImagesServiceFactory.makeResize((int) Math.round(width), (int) Math.round(height));
}
private Transform getRotateTransform() {
Double rotate = Double.parseDouble(rotateString);
return ImagesServiceFactory.makeRotate((int) Math.round(rotate));
}
private Transform getCropTransform() {
Double height = Double.parseDouble(heightString);
Double width = Double.parseDouble(widthString);
Double leftX = Double.parseDouble(leftXString) / width;
Double topY = Double.parseDouble(topYString) / height;
Double rightX = Double.parseDouble(rightXString) / width;
Double bottomY = Double.parseDouble(bottomYString) / height;
return ImagesServiceFactory.makeCrop(leftX, topY, rightX, bottomY);
}
private CompositeTransform getCompositeTransformToApply() {
Transform standardCompress = ImagesServiceFactory.makeResize(150, 150);
CompositeTransform finalTransform = ImagesServiceFactory.makeCompositeTransform()
.concatenate(getScaleTransform())
.concatenate(getRotateTransform())
.concatenate(getCropTransform())
.concatenate(standardCompress);
return finalTransform;
}
/**
* Checks that the information given via POST is valid
*/
private boolean validatePostParameters() {
if (leftXString.isEmpty() || topYString.isEmpty()
|| rightXString.isEmpty() || bottomYString.isEmpty()) {
isError = true;
statusToUser.add(new StatusMessage("Given crop locations were not valid. Please try again",
StatusMessageColor.DANGER));
statusToAdmin = Const.ACTION_RESULT_FAILURE + " : One or more of the given coords were empty.";
return false;
} else if (heightString.isEmpty() || widthString.isEmpty()) {
isError = true;
statusToUser.add(new StatusMessage("Given crop locations were not valid. Please try again",
StatusMessageColor.DANGER));
statusToAdmin = Const.ACTION_RESULT_FAILURE + " : One or both of the image dimensions were empty.";
return false;
} else if (Double.parseDouble(widthString) == 0
|| Double.parseDouble(heightString) == 0) {
isError = true;
statusToUser.add(new StatusMessage("Given crop locations were not valid. Please try again",
StatusMessageColor.DANGER));
statusToAdmin = Const.ACTION_RESULT_FAILURE + " : One or both of the image dimensions were zero.";
return false;
}
return true;
}
/**
* Gets all the parameters from the Request and ensures that
* they are not null
*/
private void readAllPostParamterValuesToFields() {
leftXString = getLeftXString();
topYString = getTopYString();
rightXString = getRightXString();
bottomYString = getBottomYString();
heightString = getPictureHeight();
widthString = getPictureWidth();
blobKey = getBlobKey();
rotateString = getRotateString();
}
private BlobKey getBlobKey() {
Assumption.assertPostParamNotNull(Const.ParamsNames.BLOB_KEY,
getRequestParamValue(Const.ParamsNames.BLOB_KEY));
return new BlobKey(getRequestParamValue(Const.ParamsNames.BLOB_KEY));
}
private String getPictureWidth() {
Assumption.assertPostParamNotNull(Const.ParamsNames.PROFILE_PICTURE_WIDTH,
getRequestParamValue(Const.ParamsNames.PROFILE_PICTURE_WIDTH));
return getRequestParamValue(Const.ParamsNames.PROFILE_PICTURE_WIDTH);
}
private String getPictureHeight() {
Assumption.assertPostParamNotNull(Const.ParamsNames.PROFILE_PICTURE_HEIGHT,
getRequestParamValue(Const.ParamsNames.PROFILE_PICTURE_HEIGHT));
return getRequestParamValue(Const.ParamsNames.PROFILE_PICTURE_HEIGHT);
}
private String getBottomYString() {
Assumption.assertPostParamNotNull(Const.ParamsNames.PROFILE_PICTURE_BOTTOMY,
getRequestParamValue(Const.ParamsNames.PROFILE_PICTURE_BOTTOMY));
return getRequestParamValue(Const.ParamsNames.PROFILE_PICTURE_BOTTOMY);
}
private String getRightXString() {
Assumption.assertPostParamNotNull(Const.ParamsNames.PROFILE_PICTURE_RIGHTX,
getRequestParamValue(Const.ParamsNames.PROFILE_PICTURE_RIGHTX));
return getRequestParamValue(Const.ParamsNames.PROFILE_PICTURE_RIGHTX);
}
private String getTopYString() {
Assumption.assertPostParamNotNull(Const.ParamsNames.PROFILE_PICTURE_TOPY,
getRequestParamValue(Const.ParamsNames.PROFILE_PICTURE_TOPY));
return getRequestParamValue(Const.ParamsNames.PROFILE_PICTURE_TOPY);
}
private String getLeftXString() {
Assumption.assertPostParamNotNull(Const.ParamsNames.PROFILE_PICTURE_LEFTX,
getRequestParamValue(Const.ParamsNames.PROFILE_PICTURE_LEFTX));
return getRequestParamValue(Const.ParamsNames.PROFILE_PICTURE_LEFTX);
}
private String getRotateString() {
Assumption.assertPostParamNotNull(Const.ParamsNames.PROFILE_PICTURE_ROTATE,
getRequestParamValue(Const.ParamsNames.PROFILE_PICTURE_ROTATE));
return getRequestParamValue(Const.ParamsNames.PROFILE_PICTURE_ROTATE);
}
}
| gpl-2.0 |
malaporte/kaziranga | src/jdk/nashorn/internal/runtime/WithObject.java | 15798 | /*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.internal.runtime;
import static jdk.nashorn.internal.lookup.Lookup.MH;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.SwitchPoint;
import jdk.internal.dynalink.CallSiteDescriptor;
import jdk.internal.dynalink.linker.GuardedInvocation;
import jdk.internal.dynalink.linker.LinkRequest;
import jdk.internal.dynalink.support.CallSiteDescriptorFactory;
import jdk.nashorn.api.scripting.AbstractJSObject;
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor;
import jdk.nashorn.internal.runtime.linker.NashornGuards;
/**
* This class supports the handling of scope in a with body.
*
*/
public final class WithObject extends Scope {
private static final MethodHandle WITHEXPRESSIONGUARD = findOwnMH("withExpressionGuard", boolean.class, Object.class, PropertyMap.class, SwitchPoint.class);
private static final MethodHandle WITHEXPRESSIONFILTER = findOwnMH("withFilterExpression", Object.class, Object.class);
private static final MethodHandle WITHSCOPEFILTER = findOwnMH("withFilterScope", Object.class, Object.class);
private static final MethodHandle BIND_TO_EXPRESSION_OBJ = findOwnMH("bindToExpression", Object.class, Object.class, Object.class);
private static final MethodHandle BIND_TO_EXPRESSION_FN = findOwnMH("bindToExpression", Object.class, ScriptFunction.class, Object.class);
/** With expression object. */
private final ScriptObject expression;
/**
* Constructor
*
* @param scope scope object
* @param expression with expression
*/
WithObject(final ScriptObject scope, final ScriptObject expression) {
super(scope, null);
this.expression = expression;
}
/**
* Delete a property based on a key.
* @param key Any valid JavaScript value.
* @param strict strict mode execution.
* @return True if deleted.
*/
@Override
public boolean delete(final Object key, final boolean strict) {
final ScriptObject self = expression;
final String propName = JSType.toString(key);
final FindProperty find = self.findProperty(propName, true);
if (find != null) {
return self.delete(propName, strict);
}
return false;
}
@Override
public GuardedInvocation lookup(final CallSiteDescriptor desc, final LinkRequest request) {
if (request.isCallSiteUnstable()) {
// Fall back to megamorphic invocation which performs a complete lookup each time without further relinking.
return super.lookup(desc, request);
}
// With scopes can never be observed outside of Nashorn code, so all call sites that can address it will of
// necessity have a Nashorn descriptor - it is safe to cast.
final NashornCallSiteDescriptor ndesc = (NashornCallSiteDescriptor)desc;
FindProperty find = null;
GuardedInvocation link = null;
ScriptObject self;
final boolean isNamedOperation;
final String name;
if (desc.getNameTokenCount() > 2) {
isNamedOperation = true;
name = desc.getNameToken(CallSiteDescriptor.NAME_OPERAND);
} else {
isNamedOperation = false;
name = null;
}
self = expression;
if (isNamedOperation) {
find = self.findProperty(name, true);
}
if (find != null) {
link = self.lookup(desc, request);
if (link != null) {
return fixExpressionCallSite(ndesc, link);
}
}
final ScriptObject scope = getProto();
if (isNamedOperation) {
find = scope.findProperty(name, true);
}
if (find != null) {
return fixScopeCallSite(scope.lookup(desc, request), name, find.getOwner());
}
// the property is not found - now check for
// __noSuchProperty__ and __noSuchMethod__ in expression
if (self != null) {
final String fallBack;
final String operator = CallSiteDescriptorFactory.tokenizeOperators(desc).get(0);
switch (operator) {
case "callMethod":
throw new AssertionError(); // Nashorn never emits callMethod
case "getMethod":
fallBack = NO_SUCH_METHOD_NAME;
break;
case "getProp":
case "getElem":
fallBack = NO_SUCH_PROPERTY_NAME;
break;
default:
fallBack = null;
break;
}
if (fallBack != null) {
find = self.findProperty(fallBack, true);
if (find != null) {
switch (operator) {
case "getMethod":
link = self.noSuchMethod(desc, request);
break;
case "getProp":
case "getElem":
link = self.noSuchProperty(desc, request);
break;
default:
break;
}
}
}
if (link != null) {
return fixExpressionCallSite(ndesc, link);
}
}
// still not found, may be scope can handle with it's own
// __noSuchProperty__, __noSuchMethod__ etc.
link = scope.lookup(desc, request);
if (link != null) {
return fixScopeCallSite(link, name, null);
}
return null;
}
/**
* Overridden to try to find the property first in the expression object (and its prototypes), and only then in this
* object (and its prototypes).
*
* @param key Property key.
* @param deep Whether the search should look up proto chain.
* @param start the object on which the lookup was originally initiated
*
* @return FindPropertyData or null if not found.
*/
@Override
protected FindProperty findProperty(final String key, final boolean deep, final ScriptObject start) {
// We call findProperty on 'expression' with 'expression' itself as start parameter.
// This way in ScriptObject.setObject we can tell the property is from a 'with' expression
// (as opposed from another non-scope object in the proto chain such as Object.prototype).
final FindProperty exprProperty = expression.findProperty(key, true, expression);
if (exprProperty != null) {
return exprProperty;
}
return super.findProperty(key, deep, start);
}
@Override
protected Object invokeNoSuchProperty(final String name, final int programPoint) {
FindProperty find = expression.findProperty(NO_SUCH_PROPERTY_NAME, true);
if (find != null) {
final Object func = find.getObjectValue();
if (func instanceof ScriptFunction) {
return ScriptRuntime.apply((ScriptFunction)func, expression, name);
}
}
return getProto().invokeNoSuchProperty(name, programPoint);
}
@Override
public void setSplitState(final int state) {
((Scope) getNonWithParent()).setSplitState(state);
}
@Override
public int getSplitState() {
return ((Scope) getNonWithParent()).getSplitState();
}
@Override
public void addBoundProperties(final ScriptObject source, final Property[] properties) {
// Declared variables in nested eval go to first normal (non-with) parent scope.
getNonWithParent().addBoundProperties(source, properties);
}
/**
* Get first parent scope that is not an instance of WithObject.
*/
private ScriptObject getNonWithParent() {
ScriptObject proto = getProto();
while (proto != null && proto instanceof WithObject) {
proto = proto.getProto();
}
return proto;
}
private static GuardedInvocation fixReceiverType(final GuardedInvocation link, final MethodHandle filter) {
// The receiver may be an Object or a ScriptObject.
final MethodType invType = link.getInvocation().type();
final MethodType newInvType = invType.changeParameterType(0, filter.type().returnType());
return link.asType(newInvType);
}
private static GuardedInvocation fixExpressionCallSite(final NashornCallSiteDescriptor desc, final GuardedInvocation link) {
// If it's not a getMethod, just add an expression filter that converts WithObject in "this" position to its
// expression.
if (!"getMethod".equals(desc.getFirstOperator())) {
return fixReceiverType(link, WITHEXPRESSIONFILTER).filterArguments(0, WITHEXPRESSIONFILTER);
}
final MethodHandle linkInvocation = link.getInvocation();
final MethodType linkType = linkInvocation.type();
final boolean linkReturnsFunction = ScriptFunction.class.isAssignableFrom(linkType.returnType());
return link.replaceMethods(
// Make sure getMethod will bind the script functions it receives to WithObject.expression
MH.foldArguments(
linkReturnsFunction ?
BIND_TO_EXPRESSION_FN :
BIND_TO_EXPRESSION_OBJ,
filterReceiver(
linkInvocation.asType(
linkType.changeReturnType(
linkReturnsFunction ?
ScriptFunction.class :
Object.class).
changeParameterType(
0,
Object.class)),
WITHEXPRESSIONFILTER)),
filterGuardReceiver(link, WITHEXPRESSIONFILTER));
// No clever things for the guard -- it is still identically filtered.
}
private GuardedInvocation fixScopeCallSite(final GuardedInvocation link, final String name, final ScriptObject owner) {
final GuardedInvocation newLink = fixReceiverType(link, WITHSCOPEFILTER);
final MethodHandle expressionGuard = expressionGuard(name, owner);
final MethodHandle filterGuardReceiver = filterGuardReceiver(newLink, WITHSCOPEFILTER);
return link.replaceMethods(
filterReceiver(
newLink.getInvocation(),
WITHSCOPEFILTER),
NashornGuards.combineGuards(
expressionGuard,
filterGuardReceiver));
}
private static MethodHandle filterGuardReceiver(final GuardedInvocation link, final MethodHandle receiverFilter) {
final MethodHandle test = link.getGuard();
if (test == null) {
return null;
}
final Class<?> receiverType = test.type().parameterType(0);
final MethodHandle filter = MH.asType(receiverFilter,
receiverFilter.type().changeParameterType(0, receiverType).
changeReturnType(receiverType));
return filterReceiver(test, filter);
}
private static MethodHandle filterReceiver(final MethodHandle mh, final MethodHandle receiverFilter) {
//With expression filter == receiverFilter, i.e. receiver is cast to withobject and its expression returned
return MH.filterArguments(mh, 0, receiverFilter.asType(receiverFilter.type().changeReturnType(mh.type().parameterType(0))));
}
/**
* Drops the WithObject wrapper from the expression.
* @param receiver WithObject wrapper.
* @return The with expression.
*/
public static Object withFilterExpression(final Object receiver) {
return ((WithObject)receiver).expression;
}
@SuppressWarnings("unused")
private static Object bindToExpression(final Object fn, final Object receiver) {
if (fn instanceof ScriptFunction) {
return bindToExpression((ScriptFunction) fn, receiver);
} else if (fn instanceof ScriptObjectMirror) {
final ScriptObjectMirror mirror = (ScriptObjectMirror)fn;
if (mirror.isFunction()) {
// We need to make sure correct 'this' is used for calls with Ident call
// expressions. We do so here using an AbstractJSObject instance.
return new AbstractJSObject() {
@Override
public Object call(final Object thiz, final Object... args) {
return mirror.call(withFilterExpression(receiver), args);
}
};
}
}
return fn;
}
private static Object bindToExpression(final ScriptFunction fn, final Object receiver) {
return fn.makeBoundFunction(withFilterExpression(receiver), ScriptRuntime.EMPTY_ARRAY);
}
private MethodHandle expressionGuard(final String name, final ScriptObject owner) {
final PropertyMap map = expression.getMap();
final SwitchPoint sp = expression.getProtoSwitchPoint(name, owner);
return MH.insertArguments(WITHEXPRESSIONGUARD, 1, map, sp);
}
@SuppressWarnings("unused")
private static boolean withExpressionGuard(final Object receiver, final PropertyMap map, final SwitchPoint sp) {
return ((WithObject)receiver).expression.getMap() == map && (sp == null || !sp.hasBeenInvalidated());
}
/**
* Drops the WithObject wrapper from the scope.
* @param receiver WithObject wrapper.
* @return The with scope.
*/
public static Object withFilterScope(final Object receiver) {
return ((WithObject)receiver).getProto();
}
/**
* Get the with expression for this {@code WithObject}
* @return the with expression
*/
public ScriptObject getExpression() {
return expression;
}
private static MethodHandle findOwnMH(final String name, final Class<?> rtype, final Class<?>... types) {
return MH.findStatic(MethodHandles.lookup(), WithObject.class, name, MH.type(rtype, types));
}
}
| gpl-2.0 |
GiGatR00n/Aion-Core-v4.7.5 | AL-EventEngine/EventEngine/data/scripts/system/handlers/instance/f14events/BaseEventHandler.java | 14259 | /*
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* Aion-Lightning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*
* Credits goes to all Open Source Core Developer Groups listed below
* Please do not change here something, ragarding the developer credits, except the "developed by XXXX".
* Even if you edit a lot of files in this source, you still have no rights to call it as "your Core".
* Everybody knows that this Emulator Core was developed by Aion Lightning
* @-Aion-Unique-
* @-Aion-Lightning
* @Aion-Engine
* @Aion-Extreme
* @Aion-NextGen
* @Aion-Core Dev.
*
*/
package system.handlers.instance.f14events;
import com.aionemu.gameserver.instance.handlers.GeneralEventHandler;
import com.aionemu.gameserver.model.ChatType;
import com.aionemu.gameserver.model.EmotionType;
import com.aionemu.gameserver.model.gameobjects.Creature;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.model.items.ItemCooldown;
import com.aionemu.gameserver.network.aion.serverpackets.SM_DIE;
import com.aionemu.gameserver.network.aion.serverpackets.SM_EMOTION;
import com.aionemu.gameserver.network.aion.serverpackets.SM_ITEM_COOLDOWN;
import com.aionemu.gameserver.network.aion.serverpackets.SM_QUEST_ACTION;
import com.aionemu.gameserver.network.aion.serverpackets.SM_SKILL_COOLDOWN;
import com.aionemu.gameserver.services.teleport.TeleportService2;
import com.aionemu.gameserver.skillengine.SkillEngine;
import com.aionemu.gameserver.skillengine.effect.EffectTemplate;
import com.aionemu.gameserver.skillengine.model.Effect;
import com.aionemu.gameserver.skillengine.model.Skill;
import com.aionemu.gameserver.utils.PacketSendUtility;
import com.aionemu.gameserver.utils.ThreadPoolManager;
import com.aionemu.gameserver.world.WorldMapInstance;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import javolution.util.FastList;
import javolution.util.FastMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pirate.events.EventScore;
/**
*
* @author flashman
*/
public class BaseEventHandler extends GeneralEventHandler {
protected static final Logger log = LoggerFactory.getLogger(BaseEventHandler.class);
public final String EventManager = "EventManager";
protected int round = 1;
protected int winNeeded = 0;
protected int waitingTime = 0;
protected int battle_time = 0;
protected boolean eventIsComplete = false;
protected List<EventScore> score;
protected long StartTime;
protected long InstanceTime;
protected FastMap<Integer, ScheduledFuture> prestartTasks;
protected List<Player> players;
@Override
public void onInstanceCreate(WorldMapInstance instance) {
super.onInstanceCreate(instance);
this.score = new FastList<EventScore>();
this.StartTime = System.currentTimeMillis() + this.waitingTime * 1000;
this.InstanceTime = this.StartTime;
this.players = new FastList<Player>();
this.prestartTasks = new FastMap<Integer, ScheduledFuture>().shared();
}
/*
@Override
public void onEnterInstance(Player player) {
// this.removeCd(player, true);
}
*/
@Override
public void onPlayerLogin(Player player) {
TeleportService2.moveToBindLocation(player, false);
}
@Override
public boolean onDie(Player player, Creature lastAttacker) {
this.sendDeathPacket(player, lastAttacker);
return true;
}
@Override
public void onPlayerLogOut(Player player) {
players.remove(player);
}
@Override
public void onLeaveInstance(Player player) {
players.remove(player);
}
protected void DoReward() {
}
protected void HealPlayer(Player player) {
this.HealPlayer(player, true, true);
}
protected void HealPlayer(Player player, boolean withDp, boolean sendUpdatePacket) {
player.getLifeStats().setCurrentHpPercent(100);
player.getLifeStats().setCurrentMpPercent(100);
if (withDp) {
player.getCommonData().setDp(4000);
}
if (sendUpdatePacket) {
player.getLifeStats().sendHpPacketUpdate();
player.getLifeStats().sendMpPacketUpdate();
}
}
/**
*
* @param p
* @param duration в миллисекундах
*/
protected void AddProtection(final Player p, int duration) {
Skill protector = SkillEngine.getInstance().getSkill(p, 9833, 1, p.getTarget());
Effect e = new Effect(p, p, protector.getSkillTemplate(), protector.getSkillLevel(), duration);
for (EffectTemplate et : e.getEffectTemplates()) {
et.setDuration2(duration);
}
e.initialize();
e.applyEffect();
ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
RemoveProtection(p);
}
}, duration);
}
/**
*
* @param p
* @param duration в миллисекундах
* @param delay в миллисекундах
*/
protected void AddProtection(final Player p, final int duration, int delay) {
if (delay == 0) {
this.AddProtection(p, duration);
} else {
ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
AddProtection(p, duration);
}
}, delay);
}
}
protected void RemoveProtection(Player p) {
p.getEffectController().removeEffect(9833);
}
/**
* Посылает всем игрокам в инстансе системное сообщение
*
* @param msg
*/
protected final void sendSysMessageToAll(String msg) {
for (Player p : this.players) {
PacketSendUtility.sendBrightYellowMessageOnCenter(p, msg);
}
}
/**
* Посылает указанному игроку системное сообщение.
*
* @param p
* @param msg
*/
protected final void sendSysMessageToPlayer(Player p, String msg) {
PacketSendUtility.sendBrightYellowMessageOnCenter(p, msg);
}
/**
* Посылает сообщение всем игрокам в инстансе, тип сообщения <tt>оранжевый
* текст без бокса по центру</tt>
*
* @param msg
*/
protected final void sendSpecMessage(String sender, String msg) {
for (Player p : this.players) {
PacketSendUtility.sendMessage(p, sender, msg, ChatType.GROUP_LEADER);
}
}
/**
* Посылает игроку в инстансе, тип сообщения <tt>оранжевый текст без бокса
* по центру</tt>
*
* @param msg
*/
protected final void sendSpecMessage(String sender, String msg, Player target) {
PacketSendUtility.sendMessage(target, sender, msg, ChatType.GROUP_LEADER);
}
/**
* Посылает сообщение всем игрокам в инстансе, с указанной задержкой в
* секундах, тип сообщения <tt>оранжевый текст без бокса по центру</tt>
*
* @param sender
* @param msg
* @param delay
*/
protected final void sendSpecMessage(final String sender, final String msg, int delay) {
if (delay == 0) {
this.sendSpecMessage(sender, msg);
} else {
ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
sendSpecMessage(sender, msg);
}
}, delay * 1000);
}
}
/**
* Посылает игроку в инстансе, с указанной задержкой в секундах, тип
* сообщения <tt>оранжевый текст без бокса по центру</tt>
*
* @param sender
* @param msg
* @param delay
*/
protected final void sendSpecMessage(final String sender, final String msg, final Player target, int delay) {
if (delay == 0) {
this.sendSpecMessage(sender, msg, target);
} else {
ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
sendSpecMessage(sender, msg, target);
}
}, delay * 1000);
}
}
protected void sendDeathPacket(Player player, Creature lastAttacker) {
PacketSendUtility.broadcastPacket(player, new SM_EMOTION(player, EmotionType.DIE, 0, player.equals(lastAttacker) ? 0 : lastAttacker.getObjectId()), true);
PacketSendUtility.sendPacket(player, new SM_DIE(false, false, 0, 8));
}
protected void removeCd(Player player, boolean withItemsCd) {
try {
List<Integer> delayIds = new ArrayList<Integer>();
if (player.getSkillCoolDowns() != null) {
long currentTime = System.currentTimeMillis();
for (Map.Entry<Integer, Long> en : player.getSkillCoolDowns().entrySet())
delayIds.add(en.getKey());
for (Integer delayId : delayIds)
player.setSkillCoolDown(delayId, currentTime);
delayIds.clear();
PacketSendUtility.sendPacket(player, new SM_SKILL_COOLDOWN(player.getSkillCoolDowns()));
}
if (withItemsCd) {
if (player.getItemCoolDowns() != null) {
for (Map.Entry<Integer, ItemCooldown> en : player.getItemCoolDowns().entrySet()) {
delayIds.add(en.getKey());
}
for (Integer delayId : delayIds) {
player.addItemCoolDown(delayId, 0, 0);
}
delayIds.clear();
PacketSendUtility.sendPacket(player, new SM_ITEM_COOLDOWN(player.getItemCoolDowns()));
}
}
if (player.getSummon() != null) {
for (Map.Entry<Integer, Long> en : player.getSummon().getSkillCoolDowns().entrySet()) {
delayIds.add(en.getKey());
}
for (Integer delayId : delayIds) {
player.getSummon().setSkillCoolDown(delayId, 0);
}
delayIds.clear();
PacketSendUtility.sendPacket(player, new SM_SKILL_COOLDOWN(player.getSkillCoolDowns()));
}
} catch (Exception ex) {
log.error("[RemoveCD] Error: ", ex);
}
}
protected void moveToEntry(final Player p) {
ThreadPoolManager.getInstance().schedule(new Runnable() {
@Override
public void run() {
TeleportService2.moveToBindLocation(p, true);
}
}, 5000);
}
protected boolean containsPlayer(int id) {
for (Player p : this.players) {
if (p != null && p.isOnline() && p.getObjectId() == id) {
return true;
}
}
return false;
}
protected Player getPlayerFromEventList(int id) {
for (Player p : this.players) {
if (p != null && p.isOnline() && p.getObjectId() == id) {
return p;
}
}
return null;
}
protected boolean containsInScoreList(int plrObjId) {
for (EventScore es : this.score) {
if (es.PlayerObjectId == plrObjId) {
return true;
}
}
return false;
}
protected void addToScoreList(Player player) {
EventScore es = new EventScore(player.getObjectId());
this.score.add(es);
}
protected boolean removeFromScoreList(int id) {
for (EventScore es : this.score) {
if (es.PlayerObjectId == id) {
this.score.remove(es);
return true;
}
}
return false;
}
protected EventScore getScore(int id) {
for (EventScore es : this.score) {
if (es.PlayerObjectId == id) {
return es;
}
}
return null;
}
protected Player getWinnerFromScoreByKills() {
int kills = -1;
Player winner = null;
for (Player p : this.players) {
EventScore es = this.getScore(p.getObjectId());
if (es.getKills() > kills) {
kills = es.getKills();
winner = p;
}
}
return winner;
}
protected boolean ifOnePlayer() {
if (this.players.size() == 1) {
EventScore es = this.score.get(0);
es.setWins(this.winNeeded);
es.setLoses(0);
es.isWinner = true;
DoReward();
return true;
}
return false;
}
protected void startTimer(int time) {
for (Player player : this.players) {
PacketSendUtility.sendPacket(player, new SM_QUEST_ACTION(0, time));
}
}
protected void stopTimer() {
for (Player player : this.players) {
this.stopTimer(player);
}
}
protected void startTimer(Player player, int time) {
PacketSendUtility.sendPacket(player, new SM_QUEST_ACTION(0, time));
}
protected void stopTimer(Player player) {
PacketSendUtility.sendPacket(player, new SM_QUEST_ACTION(0, 0));
}
}
| gpl-2.0 |
melissalinkert/bioformats | components/formats-gpl/src/loci/formats/in/MetamorphReader.java | 75029 | /*
* #%L
* OME Bio-Formats package for reading and converting biological file formats.
* %%
* Copyright (C) 2005 - 2017 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package loci.formats.in;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.HashMap;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.Vector;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import loci.common.DataTools;
import loci.common.DateTools;
import loci.common.Location;
import loci.common.Constants;
import loci.common.RandomAccessInputStream;
import loci.common.services.DependencyException;
import loci.common.services.ServiceFactory;
import loci.common.xml.XMLTools;
import loci.formats.CoreMetadata;
import loci.formats.CoreMetadataList;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.MissingLibraryException;
import loci.formats.meta.MetadataStore;
import loci.formats.services.OMEXMLService;
import loci.formats.services.OMEXMLServiceImpl;
import loci.formats.tiff.IFD;
import loci.formats.tiff.IFDList;
import loci.formats.tiff.PhotoInterp;
import loci.formats.tiff.TiffIFDEntry;
import loci.formats.tiff.TiffParser;
import loci.formats.tiff.TiffRational;
import ome.xml.model.enums.NamingConvention;
import ome.xml.model.primitives.NonNegativeInteger;
import ome.xml.model.primitives.PositiveInteger;
import ome.xml.model.primitives.Timestamp;
import ome.units.quantity.Frequency;
import ome.units.quantity.Length;
import ome.units.quantity.Temperature;
import ome.units.quantity.Time;
import ome.units.UNITS;
import org.apache.commons.lang.ArrayUtils;
/**
* Reader is the file format reader for Metamorph STK files.
*
* @author Eric Kjellman egkjellman at wisc.edu
* @author Melissa Linkert melissa at glencoesoftware.com
* @author Curtis Rueden ctrueden at wisc.edu
* @author Sebastien Huart Sebastien dot Huart at curie.fr
*/
public class MetamorphReader extends BaseTiffReader {
// -- Constants --
/** Logger for this class. */
private static final Logger LOGGER =
LoggerFactory.getLogger(MetamorphReader.class);
public static final String SHORT_DATE_FORMAT = "yyyyMMdd HH:mm:ss";
public static final String LONG_DATE_FORMAT = "dd/MM/yyyy HH:mm:ss";
public static final String[] ND_SUFFIX = {"nd", "scan"};
public static final String[] STK_SUFFIX = {"stk", "tif", "tiff"};
public static final Pattern WELL_COORDS = Pattern.compile(
"\\b([a-z])(\\d+)", Pattern.CASE_INSENSITIVE
);
// IFD tag numbers of important fields
private static final int METAMORPH_ID = 33628;
private static final int UIC1TAG = METAMORPH_ID;
private static final int UIC2TAG = 33629;
private static final int UIC3TAG = 33630;
private static final int UIC4TAG = 33631;
// NDInfoFile Version Strings
private static final String NDINFOFILE_VER1 = "Version 1.0";
private static final String NDINFOFILE_VER2 = "Version 2.0";
// -- Fields --
/** The TIFF's name */
private String imageName;
/** The TIFF's creation date */
private String imageCreationDate;
/** The TIFF's emWavelength */
private long[] emWavelength;
private boolean isHCS;
private String[] stageLabels;
private double[] wave;
private String binning;
private double zoom, stepSize;
private Double exposureTime;
private List<String> waveNames;
private List<String> stageNames;
private long[] internalStamps;
private double[] zDistances;
private Length[] stageX, stageY;
private double zStart;
private Double sizeX = null, sizeY = null;
private double tempZ;
private boolean validZ;
private Double gain;
private int mmPlanes; //number of metamorph planes
private MetamorphReader[][] stkReaders;
/** List of STK files in the dataset. */
private String[][] stks;
private String ndFilename;
private boolean canLookForND = true;
private boolean[] firstSeriesChannels;
private boolean bizarreMultichannelAcquisition = false;
private int openFiles = 0;
private boolean hasStagePositions = false;
private boolean hasChipOffsets = false;
private boolean hasAbsoluteZ = false;
private boolean hasAbsoluteZValid = false;
// -- Constructor --
/** Constructs a new Metamorph reader. */
public MetamorphReader() {
super("Metamorph STK", new String[] {"stk", "nd", "scan", "tif", "tiff"});
domains = new String[] {FormatTools.LM_DOMAIN, FormatTools.HCS_DOMAIN};
hasCompanionFiles = true;
suffixSufficient = false;
datasetDescription = "One or more .stk or .tif/.tiff files plus an " +
"optional .nd or .scan file";
canSeparateSeries = false;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#getDomains() */
@Override
public String[] getDomains() {
FormatTools.assertId(currentId, true, 1);
return isHCS ? new String[] {FormatTools.HCS_DOMAIN} :
new String[] {FormatTools.LM_DOMAIN};
}
/* @see loci.formats.IFormatReader#isThisType(String, boolean) */
@Override
public boolean isThisType(String name, boolean open) {
Location location = new Location(name);
if (!location.exists()) {
return false;
}
if (checkSuffix(name, ND_SUFFIX)) return true;
if (open) {
location = location.getAbsoluteFile();
Location parent = location.getParentFile();
String baseName = location.getName();
while (baseName.indexOf('_') >= 0) {
baseName = baseName.substring(0, baseName.lastIndexOf("_"));
if (checkSuffix(name, suffixes)) {
for (String ext : ND_SUFFIX) {
if (new Location(parent, baseName + "." + ext).exists() ||
new Location(parent, baseName + "." + ext.toUpperCase()).exists()) {
return true;
}
}
if (new Location(parent, baseName + ".htd").exists() ||
new Location(parent, baseName + ".HTD").exists()) {
return false;
}
}
}
}
return super.isThisType(name, open);
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
@Override
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
TiffParser tp = new TiffParser(stream);
IFD ifd = tp.getFirstIFD();
if (ifd == null) return false;
String software = ifd.getIFDTextValue(IFD.SOFTWARE);
boolean validSoftware = software != null &&
software.trim().toLowerCase().startsWith("metamorph");
return validSoftware || (ifd.containsKey(UIC1TAG) &&
ifd.containsKey(UIC3TAG) && ifd.containsKey(UIC4TAG));
}
/* @see loci.formats.IFormatReader#isSingleFile(String) */
@Override
public boolean isSingleFile(String id) throws FormatException, IOException {
return !checkSuffix(id, ND_SUFFIX);
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
@Override
public int fileGroupOption(String id) throws FormatException, IOException {
if (checkSuffix(id, ND_SUFFIX)) return FormatTools.MUST_GROUP;
Location l = new Location(id).getAbsoluteFile();
String[] files = l.getParentFile().list();
for (String file : files) {
if (checkSuffix(file, ND_SUFFIX) &&
l.getName().startsWith(file.substring(0, file.lastIndexOf("."))))
{
return FormatTools.MUST_GROUP;
}
}
return FormatTools.CANNOT_GROUP;
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
@Override
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
if (!noPixels && stks == null) return new String[] {currentId};
else if (stks == null) return ArrayUtils.EMPTY_STRING_ARRAY;
final List<String> v = new ArrayList<String>();
if (ndFilename != null) v.add(ndFilename);
if (!noPixels) {
for (String stk : stks[getSeries()]) {
if (stk != null && new Location(stk).exists()) {
v.add(stk);
}
}
}
return v.toArray(new String[v.size()]);
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
@Override
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
if (stks == null) {
return super.openBytes(no, buf, x, y, w, h);
}
int[] coords = FormatTools.getZCTCoords(this, no % getSizeZ());
int ndx = no / getSizeZ();
if (bizarreMultichannelAcquisition) {
int[] pos = getZCTCoords(no);
ndx = getIndex(pos[0], 0, pos[2]) / getSizeZ();
}
if (stks[getSeries()].length == 1) ndx = 0;
String file = stks[getSeries()][ndx];
if (file == null) return buf;
// the original file is a .nd file, so we need to construct a new reader
// for the constituent STK files
stkReaders[getSeries()][ndx].setMetadataOptions(
new DefaultMetadataOptions(MetadataLevel.MINIMUM));
int plane = stks[getSeries()].length == 1 ? no : coords[0];
try {
if (!file.equals(stkReaders[getSeries()][ndx].getCurrentFile())) {
openFiles++;
}
stkReaders[getSeries()][ndx].setId(file);
if (bizarreMultichannelAcquisition) {
int realX = getZCTCoords(no)[1] == 0 ? x : x + getSizeX();
stkReaders[getSeries()][ndx].openBytes(plane, buf, realX, y, w, h);
}
else {
stkReaders[getSeries()][ndx].openBytes(plane, buf, x, y, w, h);
}
}
finally {
int count = stkReaders[getSeries()][ndx].getImageCount();
if (plane == count - 1 || openFiles > 128) {
stkReaders[getSeries()][ndx].close();
openFiles--;
}
}
return buf;
}
/* @see loci.formats.IFormatReader#close(boolean) */
@Override
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (stkReaders != null) {
for (MetamorphReader[] s : stkReaders) {
if (s != null) {
for (MetamorphReader reader : s) {
if (reader != null) reader.close(fileOnly);
}
}
}
}
if (!fileOnly) {
imageName = imageCreationDate = null;
emWavelength = null;
stks = null;
mmPlanes = 0;
ndFilename = null;
wave = null;
binning = null;
zoom = stepSize = 0;
exposureTime = null;
waveNames = stageNames = null;
internalStamps = null;
zDistances = null;
stageX = stageY = null;
firstSeriesChannels = null;
sizeX = sizeY = null;
tempZ = 0d;
validZ = false;
stkReaders = null;
gain = null;
bizarreMultichannelAcquisition = false;
openFiles = 0;
hasStagePositions = false;
hasChipOffsets = false;
hasAbsoluteZ = false;
hasAbsoluteZValid = false;
stageLabels = null;
isHCS = false;
}
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
Location ndfile = null;
if (checkSuffix(id, ND_SUFFIX)) {
ndfile = new Location(id);
LOGGER.info("Initializing " + id);
// find an associated STK file
String stkFile = id.substring(0, id.lastIndexOf("."));
if (stkFile.indexOf(File.separatorChar) != -1) {
stkFile = stkFile.substring(stkFile.lastIndexOf(File.separator) + 1);
}
Location parent = new Location(id).getAbsoluteFile().getParentFile();
LOGGER.info("Looking for STK file in {}", parent.getAbsolutePath());
String[] dirList = parent.list(true);
Arrays.sort(dirList);
String suffix = getNDVersionSuffix(ndfile);
for (String f : dirList) {
if (!checkSuffix(f, suffix)) {
continue;
}
if (!f.startsWith(stkFile)) {
continue;
}
String s = f.substring(stkFile.length(), f.lastIndexOf("."));
if (s.isEmpty() || s.startsWith("_w") || s.startsWith("_s") || s.startsWith("_t") )
{
stkFile = new Location(parent.getAbsolutePath(), f).getAbsolutePath();
break;
}
}
if (!checkSuffix(stkFile, STK_SUFFIX)) {
throw new FormatException(suffix + " file not found in " +
parent.getAbsolutePath() + ".");
}
super.initFile(stkFile);
}
else super.initFile(id);
if (!checkSuffix(id, ND_SUFFIX) && canLookForND && isGroupFiles()) {
// an STK file was passed to initFile
// let's check the parent directory for an .nd file
Location stk = new Location(id).getAbsoluteFile();
String stkName = stk.getName();
String stkPrefix = stkName;
if (stkPrefix.indexOf('_') >= 0) {
stkPrefix = stkPrefix.substring(0, stkPrefix.indexOf('_') + 1);
}
Location parent = stk.getParentFile();
String[] list = parent.list(true);
int matchingChars = 0;
for (String f : list) {
if (checkSuffix(f, ND_SUFFIX)) {
String prefix = f.substring(0, f.lastIndexOf("."));
if (prefix.indexOf('_') >= 0) {
prefix = prefix.substring(0, prefix.indexOf('_') + 1);
}
if (stkName.startsWith(prefix) || prefix.equals(stkPrefix)) {
int charCount = 0;
for (int i=0; i<f.length(); i++) {
if (i >= stkName.length()) {
break;
}
if (f.charAt(i) == stkName.charAt(i)) {
charCount++;
}
else {
break;
}
}
if (charCount > matchingChars || (charCount == matchingChars &&
f.charAt(charCount) == '.'))
{
ndfile = new Location(parent, f).getAbsoluteFile();
matchingChars = charCount;
}
}
}
}
}
String creationTime = null;
if (ndfile != null && ndfile.exists() &&
(fileGroupOption(id) == FormatTools.MUST_GROUP || isGroupFiles()))
{
// parse key/value pairs from .nd file
int zc = getSizeZ(), cc = getSizeC(), tc = getSizeT();
int nstages = 0;
String z = null, c = null, t = null;
final List<Boolean> hasZ = new ArrayList<Boolean>();
waveNames = new ArrayList<String>();
stageNames = new ArrayList<String>();
boolean useWaveNames = true;
ndFilename = ndfile.getAbsolutePath();
String[] lines = DataTools.readFile(ndFilename).split("\n");
boolean globalDoZ = true;
boolean doTimelapse = false;
boolean doWavelength = false;
String version = NDINFOFILE_VER1;
StringBuilder currentValue = new StringBuilder();
String key = "";
for (String line : lines) {
int comma = line.indexOf(',');
if (comma <= 0 && line.indexOf("EndFile") < 0) {
currentValue.append("\n");
currentValue.append(line);
continue;
}
String value = currentValue.toString();
addGlobalMeta(key, value);
if (key.equals("NDInfoFile")) version = value;
if (key.equals("NZSteps")) z = value;
else if (key.equals("DoTimelapse")) {
doTimelapse = Boolean.parseBoolean(value);
}
else if (key.equals("NWavelengths")) c = value;
else if (key.equals("NTimePoints")) t = value;
else if (key.startsWith("WaveDoZ")) {
hasZ.add(Boolean.parseBoolean(value));
}
else if (key.startsWith("WaveName")) {
String waveName = value.substring(1, value.length() - 1);
if (waveName.equals("Both lasers") || waveName.startsWith("DUAL")) {
bizarreMultichannelAcquisition = true;
}
waveNames.add(waveName);
}
else if (key.startsWith("Stage")) {
stageNames.add(value);
}
else if (key.startsWith("StartTime")) {
creationTime = value;
}
else if (key.equals("ZStepSize")) {
value = value.replace(',', '.');
stepSize = Double.parseDouble(value);
}
else if (key.equals("NStagePositions")) {
nstages = Integer.parseInt(value);
}
else if (key.equals("WaveInFileName")) {
useWaveNames = Boolean.parseBoolean(value);
}
else if (key.equals("DoZSeries")) {
globalDoZ = Boolean.parseBoolean(value);
}
else if (key.equals("DoWave")) {
doWavelength = Boolean.parseBoolean(value);
}
if (comma >= 1) {
key = line.substring(1, comma - 1).trim();
}
else {
key = "";
}
currentValue.delete(0, currentValue.length());
currentValue.append(line.substring(comma + 1).trim());
}
if (!globalDoZ) {
for (int i=0; i<hasZ.size(); i++) {
hasZ.set(i, false);
}
}
// figure out how many files we need
if (z != null) zc = Integer.parseInt(z);
if (c != null) cc = Integer.parseInt(c);
if (t != null) tc = Integer.parseInt(t);
else if (!doTimelapse) {
tc = 1;
}
if (cc == 0) cc = 1;
if (cc == 1 && bizarreMultichannelAcquisition) {
cc = 2;
}
if (tc == 0) {
tc = 1;
}
int numFiles = cc * tc;
if (nstages > 0) numFiles *= nstages;
// determine series count
int stagesCount = nstages == 0 ? 1 : nstages;
int seriesCount = stagesCount;
firstSeriesChannels = new boolean[cc];
Arrays.fill(firstSeriesChannels, true);
boolean differentZs = false;
for (int i=0; i<cc; i++) {
boolean hasZ1 = i < hasZ.size() && hasZ.get(i);
boolean hasZ2 = i != 0 && (i - 1 < hasZ.size()) &&
hasZ.get(i - 1);
if (i > 0 && hasZ1 != hasZ2 && globalDoZ) {
if (!differentZs) seriesCount *= 2;
differentZs = true;
}
}
int channelsInFirstSeries = cc;
if (differentZs) {
channelsInFirstSeries = 0;
for (int i=0; i<cc; i++) {
if ((!hasZ.get(0) && i == 0) ||
(hasZ.get(0) && hasZ.get(i)))
{
channelsInFirstSeries++;
}
else firstSeriesChannels[i] = false;
}
}
stks = new String[seriesCount][];
if (seriesCount == 1) stks[0] = new String[numFiles];
else if (differentZs) {
for (int i=0; i<stagesCount; i++) {
stks[i * 2] = new String[channelsInFirstSeries * tc];
stks[i * 2 + 1] = new String[(cc - channelsInFirstSeries) * tc];
}
}
else {
for (int i=0; i<stks.length; i++) {
stks[i] = new String[numFiles / stks.length];
}
}
String prefix = ndfile.getPath();
prefix = prefix.substring(prefix.lastIndexOf(File.separator) + 1,
prefix.lastIndexOf("."));
// build list of STK files
boolean anyZ = hasZ.contains(Boolean.TRUE);
int[] pt = new int[seriesCount];
for (int i=0; i<tc; i++) {
for (int s=0; s<stagesCount; s++) {
for (int j=0; j<cc; j++) {
boolean validZ = j >= hasZ.size() || hasZ.get(j);
int seriesNdx = s * (seriesCount / stagesCount);
if ((seriesCount != 1 &&
(!validZ || (hasZ.size() > 0 && !hasZ.get(0)))) ||
(nstages == 0 && ((!validZ && cc > 1) || seriesCount > 1)))
{
if (anyZ && j > 0 && seriesNdx < seriesCount - 1 &&
(!validZ || !hasZ.get(0)))
{
seriesNdx++;
}
}
if (seriesNdx >= stks.length || seriesNdx >= pt.length ||
pt[seriesNdx] >= stks[seriesNdx].length)
{
continue;
}
stks[seriesNdx][pt[seriesNdx]] = prefix;
String formatSuffix = ".STK";
if (version.equals(NDINFOFILE_VER1)) {
formatSuffix = ".TIF";
if ((anyZ && j < hasZ.size() && hasZ.get(j)) || globalDoZ) {
formatSuffix = ".STK";
}
}
else if (version.equals(NDINFOFILE_VER2)) {
formatSuffix = ".TIF";
}
if (j < waveNames.size() && waveNames.get(j) != null) {
if (doWavelength) {
stks[seriesNdx][pt[seriesNdx]] += "_w" + (j + 1);
if (useWaveNames) {
String waveName = waveNames.get(j);
// If there are underscores in the wavelength name, translate
// them to hyphens. (See #558)
waveName = waveName.replace('_', '-');
// If there are slashes (forward or backward) in the wavelength
// name, translate them to hyphens. (See #5922)
waveName = waveName.replace('/', '-');
waveName = waveName.replace('\\', '-');
waveName = waveName.replace('(', '-');
waveName = waveName.replace(')', '-');
stks[seriesNdx][pt[seriesNdx]] += waveName;
}
}
}
if (nstages > 0) {
stks[seriesNdx][pt[seriesNdx]] += "_s" + (s + 1);
}
if (tc > 1 || doTimelapse) {
stks[seriesNdx][pt[seriesNdx]] += "_t" + (i + 1) + formatSuffix;
}
else stks[seriesNdx][pt[seriesNdx]] += formatSuffix;
pt[seriesNdx]++;
}
}
}
ndfile = ndfile.getAbsoluteFile();
// check that each STK file exists
for (int s=0; s<stks.length; s++) {
for (int f=0; f<stks[s].length; f++) {
Location l = new Location(ndfile.getParent(), stks[s][f]);
stks[s][f] = getRealSTKFile(l);
}
}
String file = locateFirstValidFile();
if (file == null) {
throw new FormatException(
"Unable to locate at least one valid STK file!");
}
IFD ifd = null;
try (RandomAccessInputStream s = new RandomAccessInputStream(file, 16)) {
TiffParser tp = new TiffParser(s);
ifd = tp.getFirstIFD();
}
CoreMetadata ms0 = core.get(0, 0);
ms0.sizeX = (int) ifd.getImageWidth();
ms0.sizeY = (int) ifd.getImageLength();
if (bizarreMultichannelAcquisition) {
ms0.sizeX /= 2;
}
ms0.sizeZ = hasZ.size() > 0 && !hasZ.get(0) ? 1 : zc;
ms0.sizeC = cc;
ms0.sizeT = tc;
ms0.imageCount = getSizeZ() * getSizeC() * getSizeT();
if (isRGB()) {
ms0.sizeC *= 3;
}
ms0.dimensionOrder = "XYZCT";
if (stks != null && stks.length > 1) {
// Note that core can't be replaced with newCore until the end of this block.
CoreMetadataList newCore = new CoreMetadataList();
for (int i=0; i<stks.length; i++) {
CoreMetadata ms = new CoreMetadata();
newCore.add(ms);
ms.sizeX = getSizeX();
ms.sizeY = getSizeY();
ms.sizeZ = getSizeZ();
ms.sizeC = getSizeC();
ms.sizeT = getSizeT();
ms.pixelType = getPixelType();
ms.imageCount = getImageCount();
ms.dimensionOrder = getDimensionOrder();
ms.rgb = isRGB();
ms.littleEndian = isLittleEndian();
ms.interleaved = isInterleaved();
ms.orderCertain = true;
}
if (stks.length > nstages) {
for (int j=0; j<stagesCount; j++) {
int idx = j * 2 + 1;
CoreMetadata midx = newCore.get(idx, 0);
CoreMetadata pmidx = newCore.get(j * 2, 0);
pmidx.sizeC = stks[j * 2].length / getSizeT();
midx.sizeC = stks[idx].length / midx.sizeT;
midx.sizeZ =
hasZ.size() > 1 && hasZ.get(1) && core.get(0, 0).sizeZ == 1 ? zc : 1;
pmidx.imageCount = pmidx.sizeC *
pmidx.sizeT * pmidx.sizeZ;
midx.imageCount =
midx.sizeC * midx.sizeT * midx.sizeZ;
}
}
core = newCore;
}
}
if (stks == null) {
stkReaders = new MetamorphReader[1][1];
stkReaders[0][0] = new MetamorphReader();
stkReaders[0][0].setCanLookForND(false);
}
else {
stkReaders = new MetamorphReader[stks.length][];
for (int i=0; i<stks.length; i++) {
stkReaders[i] = new MetamorphReader[stks[i].length];
for (int j=0; j<stkReaders[i].length; j++) {
stkReaders[i][j] = new MetamorphReader();
stkReaders[i][j].setCanLookForND(false);
if (j > 0) {
stkReaders[i][j].setMetadataOptions(
new DefaultMetadataOptions(MetadataLevel.MINIMUM));
}
}
}
}
// check stage labels for plate data
int rows = 0;
int cols = 0;
Map<String, Integer> rowMap = null;
Map<String, Integer> colMap = null;
isHCS = true;
if (stageLabels == null && stageNames != null) {
stageLabels = stageNames.toArray(new String[stageNames.size()]);
}
if (null == stageLabels) {
isHCS = false;
} else if (stks == null ||
(stks != null && stageLabels.length == stks.length))
{
Set<Map.Entry<Integer, Integer>> uniqueWells =
new HashSet<Map.Entry<Integer, Integer>>();
rowMap = new HashMap<String, Integer>();
colMap = new HashMap<String, Integer>();
for (String label : stageLabels) {
if (null == label) {
isHCS = false;
break;
}
Map.Entry<Integer, Integer> wellCoords = getWellCoords(label);
if (null == wellCoords) {
isHCS = false;
break;
}
uniqueWells.add(wellCoords);
rowMap.put(label, wellCoords.getKey());
colMap.put(label, wellCoords.getValue());
}
if (uniqueWells.size() != stageLabels.length ||
rowMap.size() == 0)
{
isHCS = false;
} else {
rows = Collections.max(rowMap.values()) + 1;
cols = Collections.max(colMap.values()) + 1;
if (rows > 0 && cols > 0) {
CoreMetadata c = core.get(0, 0);
core.clear();
c.sizeZ = 1;
c.sizeT = 1;
c.imageCount = 1;
for (int s = 0; s < uniqueWells.size(); s++) {
CoreMetadata toAdd = new CoreMetadata(c);
if (s > 0) {
toAdd.seriesMetadata.clear();
}
core.add(toAdd);
}
seriesToIFD = true;
}
}
}
if (rows <= 0 || cols <= 0) {
isHCS = false;
}
List<String> timestamps = null;
MetamorphHandler handler = null;
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
if (isHCS) {
store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
store.setPlateRows(new PositiveInteger(rows), 0);
store.setPlateColumns(new PositiveInteger(cols), 0);
store.setPlateRowNamingConvention(NamingConvention.LETTER, 0);
store.setPlateColumnNamingConvention(NamingConvention.NUMBER, 0);
}
int nextObjective = 0;
String instrumentID = MetadataTools.createLSID("Instrument", 0);
String detectorID = MetadataTools.createLSID("Detector", 0, 0);
store.setInstrumentID(instrumentID, 0);
store.setDetectorID(detectorID, 0, 0);
store.setDetectorType(MetadataTools.getDetectorType("Other"), 0, 0);
for (int i=0; i<getSeriesCount(); i++) {
setSeries(i);
// do not reparse the same XML for every well
if (i == 0 || !isHCS) {
handler = new MetamorphHandler(getSeriesMetadata());
}
if (isHCS) {
String label = stageLabels[i];
String wellID = MetadataTools.createLSID("Well", 0, i);
store.setWellID(wellID, 0, i);
store.setWellColumn(new NonNegativeInteger(colMap.get(label)), 0, i);
store.setWellRow(new NonNegativeInteger(rowMap.get(label)), 0, i);
store.setWellSampleID(MetadataTools.createLSID("WellSample", 0, i, 0), 0, i, 0);
store.setWellSampleImageRef(MetadataTools.createLSID("Image", i), 0, i, 0);
store.setWellSampleIndex(new NonNegativeInteger(i), 0, i, 0);
}
store.setImageInstrumentRef(instrumentID, i);
String comment = getFirstComment(i);
if (i == 0 || !isHCS) {
if (comment != null && comment.startsWith("<MetaData>")) {
try {
XMLTools.parseXML(XMLTools.sanitizeXML(comment), handler);
}
catch (IOException e) { }
}
}
if (creationTime != null) {
String date = DateTools.formatDate(creationTime, SHORT_DATE_FORMAT, ".");
if (date != null) {
store.setImageAcquisitionDate(new Timestamp(date), 0);
}
}
store.setImageName(makeImageName(i).trim(), i);
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
continue;
}
store.setImageDescription("", i);
store.setImagingEnvironmentTemperature(
new Temperature(handler.getTemperature(), UNITS.CELSIUS), i);
if (sizeX == null) sizeX = handler.getPixelSizeX();
if (sizeY == null) sizeY = handler.getPixelSizeY();
Length physicalSizeX = FormatTools.getPhysicalSizeX(sizeX);
Length physicalSizeY = FormatTools.getPhysicalSizeY(sizeY);
if (physicalSizeX != null) {
store.setPixelsPhysicalSizeX(physicalSizeX, i);
}
if (physicalSizeY != null) {
store.setPixelsPhysicalSizeY(physicalSizeY, i);
}
if (zDistances != null) {
stepSize = zDistances[0];
}
else {
List<Double> zPositions = new ArrayList<Double>();
final List<Double> uniqueZ = new ArrayList<Double>();
for (IFD ifd : ifds) {
MetamorphHandler zPlaneHandler = new MetamorphHandler();
String zComment = ifd.getComment();
if (zComment != null &&
zComment.startsWith("<MetaData>"))
{
try {
XMLTools.parseXML(XMLTools.sanitizeXML(zComment),
zPlaneHandler);
}
catch (IOException e) { }
}
zPositions = zPlaneHandler.getZPositions();
for (Double z : zPositions) {
if (!uniqueZ.contains(z)) uniqueZ.add(z);
}
}
if (uniqueZ.size() > 1 && uniqueZ.size() == getSizeZ()) {
BigDecimal lastZ = BigDecimal.valueOf(uniqueZ.get(uniqueZ.size() - 1));
BigDecimal firstZ = BigDecimal.valueOf(uniqueZ.get(0));
BigDecimal zRange = (lastZ.subtract(firstZ)).abs();
BigDecimal zSize = BigDecimal.valueOf((double)(getSizeZ() - 1));
MathContext mc = new MathContext(10, RoundingMode.HALF_UP);
stepSize = zRange.divide(zSize, mc).doubleValue();
}
}
Length physicalSizeZ = FormatTools.getPhysicalSizeZ(stepSize);
if (physicalSizeZ != null) {
store.setPixelsPhysicalSizeZ(physicalSizeZ, i);
}
if (handler.getLensNA() != 0 || handler.getLensRI() != 0) {
String objectiveID = MetadataTools.createLSID("Objective", 0, nextObjective);
store.setObjectiveID(objectiveID, 0, nextObjective);
if (handler.getLensNA() != 0) {
store.setObjectiveLensNA(handler.getLensNA(), 0, nextObjective);
}
store.setObjectiveSettingsID(objectiveID, i);
if (handler.getLensRI() != 0) {
store.setObjectiveSettingsRefractiveIndex(handler.getLensRI(), i);
}
nextObjective++;
}
int waveIndex = 0;
for (int c=0; c<getEffectiveSizeC(); c++) {
if (firstSeriesChannels == null ||
(stageNames != null && stageNames.size() == getSeriesCount()))
{
waveIndex = c;
}
else if (firstSeriesChannels != null) {
int s = i % 2;
while (firstSeriesChannels[waveIndex] == (s == 1) &&
waveIndex < firstSeriesChannels.length)
{
waveIndex++;
}
}
if (waveNames != null && waveIndex < waveNames.size()) {
store.setChannelName(waveNames.get(waveIndex).trim(), i, c);
}
if (handler.getBinning() != null) binning = handler.getBinning();
if (binning != null) {
store.setDetectorSettingsBinning(MetadataTools.getBinning(binning), i, c);
}
if (handler.getReadOutRate() != 0) {
store.setDetectorSettingsReadOutRate(
new Frequency(handler.getReadOutRate(), UNITS.HERTZ), i, c);
}
if (gain == null) {
gain = handler.getGain();
}
if (gain != null) {
store.setDetectorSettingsGain(gain, i, c);
}
store.setDetectorSettingsID(detectorID, i, c);
if (wave == null && handler.getWavelengths() != null) {
Vector<Integer> xmlWavelengths = handler.getWavelengths();
wave = new double[xmlWavelengths.size()];
for (int w=0; w<wave.length; w++) {
wave[w] = xmlWavelengths.get(w);
}
}
if (wave != null && waveIndex < wave.length) {
Length wavelength =
FormatTools.getWavelength(wave[waveIndex]);
if ((int) wave[waveIndex] >= 1) {
// link LightSource to Image
int laserIndex = i * getEffectiveSizeC() + c;
try {
ServiceFactory factory = new ServiceFactory();
OMEXMLService omexmlService = factory.getInstance(OMEXMLService.class);
laserIndex = omexmlService.asRetrieve(getMetadataStore()).getLightSourceCount(0);
}
catch (DependencyException de) {
throw new MissingLibraryException(OMEXMLServiceImpl.NO_OME_XML_MSG, de);
}
String lightSourceID =
MetadataTools.createLSID("LightSource", 0, laserIndex);
store.setLaserID(lightSourceID, 0, laserIndex);
store.setChannelLightSourceSettingsID(lightSourceID, i, c);
store.setLaserType(MetadataTools.getLaserType("Other"), 0, laserIndex);
store.setLaserLaserMedium(MetadataTools.getLaserMedium("Other"), 0, laserIndex);
if (wavelength != null) {
store.setChannelLightSourceSettingsWavelength(wavelength, i, c);
store.setChannelEmissionWavelength(wavelength, i, c);
}
}
}
waveIndex++;
}
timestamps = handler.getTimestamps();
for (int t=0; t<timestamps.size(); t++) {
String date = DateTools.convertDate(DateTools.getTime(
timestamps.get(t), SHORT_DATE_FORMAT, "."), DateTools.UNIX,
SHORT_DATE_FORMAT + ".SSS");
addSeriesMetaList("timestamp", date);
}
long startDate = 0;
if (timestamps.size() > 0) {
startDate = DateTools.getTime(timestamps.get(0), SHORT_DATE_FORMAT, ".");
}
final Length positionX = handler.getStagePositionX();
final Length positionY = handler.getStagePositionY();
final List<Double> exposureTimes = handler.getExposures();
if (exposureTimes.size() == 0) {
for (int p=0; p<getImageCount(); p++) {
exposureTimes.add(exposureTime);
}
}
else if (exposureTimes.size() == 1 && exposureTimes.size() < getEffectiveSizeC()) {
for (int c=1; c<getEffectiveSizeC(); c++) {
MetamorphHandler channelHandler = new MetamorphHandler();
String channelComment = getComment(i, c);
if (channelComment != null &&
channelComment.startsWith("<MetaData>"))
{
try {
XMLTools.parseXML(XMLTools.sanitizeXML(channelComment),
channelHandler);
}
catch (IOException e) { }
}
final List<Double> channelExpTime = channelHandler.getExposures();
exposureTimes.add(channelExpTime.get(0));
}
}
int lastFile = -1;
IFDList lastIFDs = null;
IFD lastIFD = null;
double distance = zStart;
TiffParser tp = null;
RandomAccessInputStream stream = null;
for (int p=0; p<getImageCount(); p++) {
int[] coords = getZCTCoords(p);
Double deltaT = 0d;
Double expTime = exposureTime;
Double xmlZPosition = null;
int fileIndex = getIndex(0, coords[1], coords[2]) / getSizeZ();
if (fileIndex >= 0) {
String file = stks == null ? currentId : stks[i][fileIndex];
if (file != null) {
if (fileIndex != lastFile) {
if (stream != null) {
stream.close();
}
stream = new RandomAccessInputStream(file, 16);
tp = new TiffParser(stream);
tp.checkHeader();
IFDList f = tp.getMainIFDs();
if (f.size() > 0) {
lastFile = fileIndex;
lastIFDs = f;
}
else {
file = null;
stks[i][fileIndex] = null;
}
}
}
if (file != null) {
lastIFD = lastIFDs.get(p % lastIFDs.size());
Object commentEntry = lastIFD.get(IFD.IMAGE_DESCRIPTION);
if (commentEntry != null) {
if (commentEntry instanceof String) {
comment = (String) commentEntry;
}
else if (commentEntry instanceof TiffIFDEntry) {
comment = tp.getIFDValue((TiffIFDEntry) commentEntry).toString();
}
}
if (comment != null) comment = comment.trim();
if (comment != null && comment.startsWith("<MetaData>")) {
String[] lines = comment.split("\n");
timestamps = new ArrayList<String>();
for (String line : lines) {
line = line.trim();
if (line.startsWith("<prop")) {
int firstQuote = line.indexOf("\"") + 1;
int lastQuote = line.lastIndexOf("\"");
String key =
line.substring(firstQuote, line.indexOf("\"", firstQuote));
String value = line.substring(
line.lastIndexOf("\"", lastQuote - 1) + 1, lastQuote);
if (key.equals("z-position")) {
xmlZPosition = new Double(value);
}
else if (key.equals("acquisition-time-local")) {
timestamps.add(value);
}
}
}
}
}
}
int index = 0;
if (timestamps.size() > 0) {
if (coords[2] < timestamps.size()) index = coords[2];
String stamp = timestamps.get(index);
long ms = DateTools.getTime(stamp, SHORT_DATE_FORMAT, ".");
deltaT = (ms - startDate) / 1000.0;
}
else if (internalStamps != null && p < internalStamps.length) {
long delta = internalStamps[p] - internalStamps[0];
deltaT = delta / 1000.0;
if (coords[2] < exposureTimes.size()) index = coords[2];
}
if (index == 0 && p > 0 && exposureTimes.size() > 0) {
index = coords[1] % exposureTimes.size();
}
if (index < exposureTimes.size()) {
expTime = exposureTimes.get(index);
}
if (deltaT != null) {
store.setPlaneDeltaT(new Time(deltaT, UNITS.SECOND), i, p);
}
if (expTime != null) {
store.setPlaneExposureTime(new Time(expTime, UNITS.SECOND), i, p);
}
if (stageX != null && p < stageX.length) {
store.setPlanePositionX(stageX[p], i, p);
}
else if (positionX != null) {
store.setPlanePositionX(positionX, i, p);
}
if (stageY != null && p < stageY.length) {
store.setPlanePositionY(stageY[p], i, p);
}
else if (positionY != null) {
store.setPlanePositionY(positionY, i, p);
}
if (zDistances != null && p < zDistances.length) {
if (p > 0) {
if (zDistances[p] != 0d) distance += zDistances[p];
else distance += zDistances[0];
}
final Length zPos = new Length(distance, UNITS.REFERENCEFRAME);
store.setPlanePositionZ(zPos, i, p);
}
else if (xmlZPosition != null) {
final Length zPos = new Length(xmlZPosition, UNITS.REFERENCEFRAME);
store.setPlanePositionZ(zPos, i, p);
}
}
if (stream != null) {
stream.close();
}
}
setSeries(0);
}
// -- Internal BaseTiffReader API methods --
/* @see BaseTiffReader#initStandardMetadata() */
@Override
protected void initStandardMetadata() throws FormatException, IOException {
super.initStandardMetadata();
CoreMetadata ms0 = core.get(0, 0);
ms0.sizeZ = 1;
ms0.sizeT = 0;
int rgbChannels = getSizeC();
// Now that the base TIFF standard metadata has been parsed, we need to
// parse out the STK metadata from the UIC4TAG.
TiffIFDEntry uic1tagEntry = null;
TiffIFDEntry uic2tagEntry = null;
TiffIFDEntry uic4tagEntry = null;
try {
uic1tagEntry = tiffParser.getFirstIFDEntry(UIC1TAG);
uic2tagEntry = tiffParser.getFirstIFDEntry(UIC2TAG);
uic4tagEntry = tiffParser.getFirstIFDEntry(UIC4TAG);
}
catch (IllegalArgumentException exc) {
LOGGER.debug("Unknown tag", exc);
}
try {
if (uic4tagEntry != null) {
mmPlanes = uic4tagEntry.getValueCount();
}
if (mmPlanes == 0) {
mmPlanes = ifds.size();
}
if (uic2tagEntry != null) {
parseUIC2Tags(uic2tagEntry.getValueOffset());
}
if (uic4tagEntry != null) {
parseUIC4Tags(uic4tagEntry.getValueOffset());
}
if (uic1tagEntry != null) {
parseUIC1Tags(uic1tagEntry.getValueOffset(),
uic1tagEntry.getValueCount());
}
in.seek(uic4tagEntry.getValueOffset());
}
catch (NullPointerException exc) {
LOGGER.debug("", exc);
}
catch (IOException exc) {
LOGGER.debug("Failed to parse proprietary tags", exc);
}
try {
// copy ifds into a new array of Hashtables that will accommodate the
// additional image planes
IFD firstIFD = ifds.get(0);
long[] uic2 = firstIFD.getIFDLongArray(UIC2TAG);
if (uic2 == null) {
throw new FormatException("Invalid Metamorph file. Tag " + UIC2TAG +
" not found.");
}
ms0.imageCount = uic2.length;
Object entry = firstIFD.getIFDValue(UIC3TAG);
TiffRational[] uic3 = entry instanceof TiffRational[] ?
(TiffRational[]) entry : new TiffRational[] {(TiffRational) entry};
wave = new double[uic3.length];
final List<Double> uniqueWavelengths = new ArrayList<Double>();
for (int i=0; i<uic3.length; i++) {
wave[i] = uic3[i].doubleValue();
addSeriesMeta("Wavelength [" + intFormatMax(i, mmPlanes) + "]",
wave[i]);
final Double v = wave[i];
if (!uniqueWavelengths.contains(v)) uniqueWavelengths.add(v);
}
if (getSizeC() == 1) {
ms0.sizeC = uniqueWavelengths.size();
if (getSizeC() < getImageCount() &&
getSizeC() > (getImageCount() - getSizeC()) &&
(getImageCount() % getSizeC()) != 0)
{
ms0.sizeC = getImageCount();
}
}
IFDList tempIFDs = new IFDList();
long[] oldOffsets = firstIFD.getStripOffsets();
long[] stripByteCounts = firstIFD.getStripByteCounts();
int rowsPerStrip = (int) firstIFD.getRowsPerStrip()[0];
int stripsPerImage = getSizeY() / rowsPerStrip;
if (stripsPerImage * rowsPerStrip != getSizeY()) stripsPerImage++;
PhotoInterp check = firstIFD.getPhotometricInterpretation();
if (check == PhotoInterp.RGB_PALETTE) {
firstIFD.putIFDValue(IFD.PHOTOMETRIC_INTERPRETATION,
PhotoInterp.BLACK_IS_ZERO);
}
emWavelength = firstIFD.getIFDLongArray(UIC3TAG);
// for each image plane, construct an IFD hashtable
IFD temp;
for (int i=0; i<getImageCount(); i++) {
// copy data from the first IFD
temp = new IFD(firstIFD);
// now we need a StripOffsets entry - the original IFD doesn't have this
long[] newOffsets = new long[stripsPerImage];
if (stripsPerImage * (i + 1) <= oldOffsets.length) {
System.arraycopy(oldOffsets, stripsPerImage * i, newOffsets, 0,
stripsPerImage);
}
else {
System.arraycopy(oldOffsets, 0, newOffsets, 0, stripsPerImage);
long image = (stripByteCounts[0] / rowsPerStrip) * getSizeY();
for (int q=0; q<stripsPerImage; q++) {
newOffsets[q] += i * image;
}
}
temp.putIFDValue(IFD.STRIP_OFFSETS, newOffsets);
long[] newByteCounts = new long[stripsPerImage];
if (stripsPerImage * i < stripByteCounts.length) {
System.arraycopy(stripByteCounts, stripsPerImage * i, newByteCounts,
0, stripsPerImage);
}
else {
Arrays.fill(newByteCounts, stripByteCounts[0]);
}
temp.putIFDValue(IFD.STRIP_BYTE_COUNTS, newByteCounts);
tempIFDs.add(temp);
}
ifds = tempIFDs;
}
catch (IllegalArgumentException exc) {
LOGGER.debug("Unknown tag", exc);
}
catch (NullPointerException exc) {
LOGGER.debug("", exc);
}
catch (FormatException exc) {
LOGGER.debug("Failed to build list of IFDs", exc);
}
// parse (mangle) TIFF comment
String descr = ifds.get(0).getComment();
if (descr != null) {
String[] lines = descr.split("\n");
final StringBuilder sb = new StringBuilder();
for (int i=0; i<lines.length; i++) {
String line = lines[i].trim();
if (line.startsWith("<") && line.endsWith(">")) {
// XML comment; this will have already been parsed so can be ignored
break;
}
int colon = line.indexOf(':');
if (colon < 0) {
// normal line (not a key/value pair)
if (line.length() > 0) {
// not a blank line
sb.append(line);
sb.append(" ");
}
}
else {
String descrValue = null;
if (i == 0) {
// first line could be mangled; make a reasonable guess
int dot = line.lastIndexOf(".", colon);
if (dot >= 0) {
descrValue = line.substring(0, dot + 1);
}
line = line.substring(dot + 1);
colon -= dot + 1;
}
// append value to description
if (descrValue != null) {
sb.append(descrValue);
if (!descrValue.endsWith(".")) sb.append(".");
sb.append(" ");
}
// add key/value pair embedded in comment as separate metadata
String key = line.substring(0, colon);
String value = line.substring(colon + 1).trim();
addSeriesMeta(key, value);
if (key.equals("Exposure")) {
if (value.indexOf('=') != -1) {
value = value.substring(value.indexOf('=') + 1).trim();
}
if (value.indexOf(' ') != -1) {
value = value.substring(0, value.indexOf(' '));
}
try {
value = value.replace(',', '.');
double exposure = Double.parseDouble(value);
exposureTime = exposure / 1000;
}
catch (NumberFormatException e) { }
}
else if (key.equals("Bit Depth")) {
if (value.indexOf('-') != -1) {
value = value.substring(0, value.indexOf('-'));
}
try {
ms0.bitsPerPixel = Integer.parseInt(value);
}
catch (NumberFormatException e) { }
}
else if (key.equals("Gain")) {
int space = value.indexOf(' ');
if (space != -1) {
int nextSpace = value.indexOf(" ", space + 1);
if (nextSpace < 0) {
nextSpace = value.length();
}
try {
gain = new Double(value.substring(space, nextSpace));
}
catch (NumberFormatException e) { }
}
}
else if (key.equalsIgnoreCase("wavelength")) {
try {
if (wave == null || wave.length == 0) {
wave = new double[1];
}
wave[0] = DataTools.parseDouble(value);
}
catch (NumberFormatException e) {
}
}
}
}
// replace comment with trimmed version
descr = sb.toString().trim();
if (descr.equals("")) metadata.remove("Comment");
else addSeriesMeta("Comment", descr);
}
ms0.sizeT = getImageCount() / (getSizeZ() * (getSizeC() / rgbChannels));
if (getSizeT() * getSizeZ() * (getSizeC() / rgbChannels) !=
getImageCount())
{
ms0.sizeT = 1;
ms0.sizeZ = getImageCount() / (getSizeC() / rgbChannels);
}
// if '_t' is present in the file name, swap Z and T sizes
// this file was probably part of a larger dataset, but the .nd file is
// missing
String filename =
currentId.substring(currentId.lastIndexOf(File.separator) + 1);
if (filename.contains("_t") && getSizeT() > 1) {
int z = getSizeZ();
ms0.sizeZ = getSizeT();
ms0.sizeT = z;
}
if (getSizeZ() == 0) ms0.sizeZ = 1;
if (getSizeT() == 0) ms0.sizeT = 1;
if (getSizeZ() * getSizeT() * (isRGB() ? 1 : getSizeC()) != getImageCount())
{
ms0.sizeZ = getImageCount();
ms0.sizeT = 1;
if (!isRGB()) ms0.sizeC = 1;
}
}
// -- Helper methods --
/**
* Check that the given STK file exists. If it does, then return the
* absolute path. If it does not, then apply various formatting rules until
* an existing file is found.
*
* @return the absolute path of an STK file, or null if no STK file is found.
*/
private String getRealSTKFile(Location l) {
if (l.exists()) return l.getAbsolutePath();
String name = l.getName();
String parent = l.getParent();
if (name.indexOf('_') > 0) {
String prefix = name.substring(0, name.indexOf('_'));
String suffix = name.substring(name.indexOf('_'));
String basePrefix = new Location(currentId).getName();
int end = basePrefix.indexOf('_');
if (end < 0) end = basePrefix.indexOf('.');
basePrefix = basePrefix.substring(0, end);
if (!basePrefix.equals(prefix)) {
name = basePrefix + suffix;
Location p = new Location(parent, name);
if (p.exists()) return p.getAbsolutePath();
}
}
// '%' can be converted to '-'
if (name.indexOf('%') != -1) {
name = name.replaceAll("%", "-");
l = new Location(parent, name);
if (!l.exists()) {
// try replacing extension
name = name.substring(0, name.lastIndexOf(".")) + ".TIF";
l = new Location(parent, name);
if (!l.exists()) {
name = name.substring(0, name.lastIndexOf(".")) + ".tif";
l = new Location(parent, name);
return l.exists() ? l.getAbsolutePath() : null;
}
}
}
if (!l.exists()) {
// try replacing extension
int index = name.lastIndexOf(".");
if (index < 0) index = name.length();
name = name.substring(0, index) + ".TIF";
l = new Location(parent, name);
if (!l.exists()) {
name = name.substring(0, name.lastIndexOf(".")) + ".tif";
l = new Location(parent, name);
if (!l.exists()) {
name = name.substring(0, name.lastIndexOf(".")) + ".stk";
l = new Location(parent, name);
return l.exists() ? l.getAbsolutePath() : null;
}
}
}
return l.getAbsolutePath();
}
/**
* Returns the TIFF comment from the first IFD of the first STK file in the
* given series.
*/
private String getFirstComment(int i) throws IOException {
return getComment(i, 0);
}
private String getComment(int i, int no) throws IOException {
if (stks != null && stks[i][no] != null) {
try (RandomAccessInputStream stream = new RandomAccessInputStream(stks[i][no], 16)) {
TiffParser tp = new TiffParser(stream);
return tp.getComment();
}
}
return ifds.get(0).getComment();
}
/** Create an appropriate name for the given series. */
private String makeImageName(int i) {
StringBuilder name = new StringBuilder();
if (stageNames != null && stageNames.size() > 0) {
int stagePosition = i / (getSeriesCount() / stageNames.size());
name.append("Stage");
name.append(stagePosition + 1);
name.append(" ");
name.append(stageNames.get(stagePosition));
}
if (firstSeriesChannels != null &&
(stageNames == null || stageNames.size() == 0 ||
stageNames.size() != getSeriesCount()))
{
if (name.length() > 0) {
name.append("; ");
}
for (int c=0; c<firstSeriesChannels.length; c++) {
if (firstSeriesChannels[c] == ((i % 2) == 0) && c < waveNames.size()) {
name.append(waveNames.get(c));
name.append("/");
}
}
if (name.length() > 0) {
return name.substring(0, name.length() - 1);
}
}
if (name.length() == 0 && isHCS) {
return stageLabels[i];
}
return name.toString();
}
/**
* Populates metadata fields with some contained in MetaMorph UIC2 Tag.
* (for each plane: 6 integers:
* zdistance numerator, zdistance denominator,
* creation date, creation time, modif date, modif time)
* @param uic2offset offset to UIC2 (33629) tag entries
*
* not a regular tiff tag (6*N entries, N being the tagCount)
* @throws IOException
*/
void parseUIC2Tags(long uic2offset) throws IOException {
long saveLoc = in.getFilePointer();
in.seek(uic2offset);
/*number of days since the 1st of January 4713 B.C*/
String cDate;
/*milliseconds since 0:00*/
String cTime;
/*z step, distance separating previous slice from current one*/
String iAsString;
zDistances = new double[mmPlanes];
internalStamps = new long[mmPlanes];
for (int i=0; i<mmPlanes; i++) {
iAsString = intFormatMax(i, mmPlanes);
if (in.getFilePointer() + 8 > in.length()) break;
zDistances[i] = readRational(in).doubleValue();
addSeriesMeta("zDistance[" + iAsString + "]", zDistances[i]);
if (zDistances[i] != 0.0) core.get(0, 0).sizeZ++;
cDate = decodeDate(in.readInt());
cTime = decodeTime(in.readInt());
internalStamps[i] = DateTools.getTime(cDate + " " + cTime,
LONG_DATE_FORMAT, ":");
addSeriesMeta("creationDate[" + iAsString + "]", cDate);
addSeriesMeta("creationTime[" + iAsString + "]", cTime);
// modification date and time are skipped as they all seem equal to 0...?
in.skip(8);
}
if (getSizeZ() == 0) core.get(0, 0).sizeZ = 1;
in.seek(saveLoc);
}
/**
* UIC4 metadata parser
*
* UIC4 Table contains per-plane blocks of metadata
* stage X/Y positions,
* camera chip offsets,
* stage labels...
* @param uic4offset offset of UIC4 table (not tiff-compliant)
* @throws IOException
*/
private void parseUIC4Tags(long uic4offset) throws IOException {
long saveLoc = in.getFilePointer();
in.seek(uic4offset);
if (in.getFilePointer() + 2 >= in.length()) return;
tempZ = 0d;
validZ = false;
short id = in.readShort();
while (id != 0) {
switch (id) {
case 28:
readStagePositions();
hasStagePositions = true;
break;
case 29:
readRationals(
new String[] {"cameraXChipOffset", "cameraYChipOffset"});
hasChipOffsets = true;
break;
case 37:
readStageLabels();
break;
case 40:
readRationals(new String[] {"UIC4 absoluteZ"});
hasAbsoluteZ = true;
break;
case 41:
readAbsoluteZValid();
hasAbsoluteZValid = true;
break;
case 46:
in.skipBytes((long) mmPlanes * 8); // TODO
break;
default:
in.skipBytes(4);
}
id = in.readShort();
}
in.seek(saveLoc);
if (validZ) zStart = tempZ;
}
private void readStagePositions() throws IOException {
stageX = new Length[mmPlanes];
stageY = new Length[mmPlanes];
String pos;
for (int i=0; i<mmPlanes; i++) {
pos = intFormatMax(i, mmPlanes);
final Double posX = readRational(in).doubleValue();
final Double posY = readRational(in).doubleValue();
stageX[i] = new Length(posX, UNITS.REFERENCEFRAME);
stageY[i] = new Length(posY, UNITS.REFERENCEFRAME);
addSeriesMeta("stageX[" + pos + "]", posX);
addSeriesMeta("stageY[" + pos + "]", posY);
addGlobalMeta("X position for position #" + (getSeries() + 1), posX);
addGlobalMeta("Y position for position #" + (getSeries() + 1), posY);
}
}
private void readRationals(String[] labels) throws IOException {
String pos;
Set<Double> uniqueZ = new HashSet<Double>();
for (int i=0; i<mmPlanes; i++) {
pos = intFormatMax(i, mmPlanes);
for (int q=0; q<labels.length; q++) {
double v = readRational(in).doubleValue();
if (labels[q].endsWith("absoluteZ")) {
if (i == 0) {
tempZ = v;
}
uniqueZ.add(v);
}
addSeriesMeta(labels[q] + "[" + pos + "]", v);
}
}
if (uniqueZ.size() == mmPlanes) {
core.get(0, 0).sizeZ = mmPlanes;
}
}
void readStageLabels() throws IOException {
int strlen;
String iAsString;
stageLabels = new String[mmPlanes];
for (int i=0; i<mmPlanes; i++) {
iAsString = intFormatMax(i, mmPlanes);
strlen = in.readInt();
stageLabels[i] = readCString(in, strlen);
addSeriesMeta("stageLabel[" + iAsString + "]", stageLabels[i]);
}
}
void readAbsoluteZValid() throws IOException {
for (int i=0; i<mmPlanes; i++) {
int valid = in.readInt();
addSeriesMeta("absoluteZValid[" + intFormatMax(i, mmPlanes) + "]", valid);
if (i == 0) {
validZ = valid == 1;
}
}
}
/**
* UIC1 entry parser
* @throws IOException
* @param uic1offset offset as found in the tiff tag 33628 (UIC1Tag)
* @param uic1count number of entries in UIC1 table (not tiff-compliant)
*/
private void parseUIC1Tags(long uic1offset, int uic1count) throws IOException
{
// Loop through and parse out each field. A field whose
// code is "0" represents the end of the fields so we'll stop
// when we reach that; much like a NULL terminated C string.
long saveLoc = in.getFilePointer();
in.seek(uic1offset);
int currentID;
long valOrOffset;
// variable declarations, because switch is dumb
int num;
String thedate, thetime;
long lastOffset;
tempZ = 0d;
validZ = false;
for (int i=0; i<uic1count; i++) {
if (in.getFilePointer() >= in.length()) break;
currentID = in.readInt();
valOrOffset = in.readInt() & 0xffffffffL;
lastOffset = in.getFilePointer();
String key = getKey(currentID);
Object value = String.valueOf(valOrOffset);
boolean skipKey = false;
switch (currentID) {
case 3:
value = valOrOffset != 0 ? "on" : "off";
break;
case 4:
case 5:
case 21:
case 22:
case 23:
case 24:
case 38:
case 39:
value = readRational(in, valOrOffset);
break;
case 6:
case 25:
if (valOrOffset < in.length()) {
in.seek(valOrOffset);
num = in.readInt();
if (num + in.getFilePointer() >= in.length()) {
num = (int) (in.length() - in.getFilePointer() - 1);
}
if (num >= 0) {
value = in.readString(num);
}
}
break;
case 7:
if (valOrOffset < in.length()) {
in.seek(valOrOffset);
num = in.readInt();
if (num >= 0) {
imageName = in.readString(num);
value = imageName;
}
}
break;
case 8:
if (valOrOffset == 1) value = "inside";
else if (valOrOffset == 2) value = "outside";
else value = "off";
break;
case 17: // oh how we hate you Julian format...
if (valOrOffset < in.length()) {
in.seek(valOrOffset);
thedate = decodeDate(in.readInt());
thetime = decodeTime(in.readInt());
imageCreationDate = thedate + " " + thetime;
value = imageCreationDate;
}
break;
case 16:
if (valOrOffset < in.length()) {
in.seek(valOrOffset);
thedate = decodeDate(in.readInt());
thetime = decodeTime(in.readInt());
value = thedate + " " + thetime;
}
break;
case 26:
if (valOrOffset < in.length()) {
in.seek(valOrOffset);
int standardLUT = in.readInt();
switch (standardLUT) {
case 0:
value = "monochrome";
break;
case 1:
value = "pseudocolor";
break;
case 2:
value = "Red";
break;
case 3:
value = "Green";
break;
case 4:
value = "Blue";
break;
case 5:
value = "user-defined";
break;
default:
value = "monochrome";
}
}
break;
case 28:
if (valOrOffset < in.length()) {
if (!hasStagePositions) {
in.seek(valOrOffset);
readStagePositions();
}
skipKey = true;
}
break;
case 29:
if (valOrOffset < in.length()) {
if (!hasChipOffsets) {
in.seek(valOrOffset);
readRationals(
new String[] {"cameraXChipOffset", "cameraYChipOffset"});
}
skipKey = true;
}
break;
case 34:
value = String.valueOf(in.readInt());
break;
case 42:
if (valOrOffset < in.length()) {
in.seek(valOrOffset);
value = String.valueOf(in.readInt());
}
break;
case 46:
if (valOrOffset < in.length()) {
in.seek(valOrOffset);
int xBin = in.readInt();
int yBin = in.readInt();
binning = xBin + "x" + yBin;
value = binning;
}
break;
case 40:
if (valOrOffset != 0 && valOrOffset < in.length()) {
if (!hasAbsoluteZ) {
in.seek(valOrOffset);
readRationals(new String[] {"UIC1 absoluteZ"});
}
skipKey = true;
}
break;
case 41:
if (valOrOffset != 0 && valOrOffset < in.length()) {
if (!hasAbsoluteZValid) {
in.seek(valOrOffset);
readAbsoluteZValid();
}
skipKey = true;
}
else if (valOrOffset == 0 && getSizeZ() < mmPlanes) {
core.get(0, 0).sizeZ = 1;
}
break;
case 49:
if (valOrOffset < in.length()) {
in.seek(valOrOffset);
readPlaneData();
skipKey = true;
}
break;
}
if (!skipKey) {
addSeriesMeta(key, value);
}
in.seek(lastOffset);
if ("Zoom".equals(key) && value != null) {
zoom = Double.parseDouble(value.toString());
}
if ("XCalibration".equals(key) && value != null) {
if (value instanceof TiffRational) {
sizeX = ((TiffRational) value).doubleValue();
}
else sizeX = new Double(value.toString());
}
if ("YCalibration".equals(key) && value != null) {
if (value instanceof TiffRational) {
sizeY = ((TiffRational) value).doubleValue();
}
else sizeY = new Double(value.toString());
}
}
in.seek(saveLoc);
if (validZ) zStart = tempZ;
}
// -- Utility methods --
/** Converts a Julian date value into a human-readable string. */
public static String decodeDate(int julian) {
long a, b, c, d, e, alpha, z;
short day, month, year;
// code reused from the Metamorph data specification
z = julian + 1;
if (z < 2299161L) a = z;
else {
alpha = (long) ((z - 1867216.25) / 36524.25);
a = z + 1 + alpha - alpha / 4;
}
b = (a > 1721423L ? a + 1524 : a + 1158);
c = (long) ((b - 122.1) / 365.25);
d = (long) (365.25 * c);
e = (long) ((b - d) / 30.6001);
day = (short) (b - d - (long) (30.6001 * e));
month = (short) ((e < 13.5) ? e - 1 : e - 13);
year = (short) ((month > 2.5) ? (c - 4716) : c - 4715);
return intFormat(day, 2) + "/" + intFormat(month, 2) + "/" + year;
}
/** Converts a time value in milliseconds into a human-readable string. */
public static String decodeTime(int millis) {
DateTime tm = new DateTime(millis, DateTimeZone.UTC);
String hours = intFormat(tm.getHourOfDay(), 2);
String minutes = intFormat(tm.getMinuteOfHour(), 2);
String seconds = intFormat(tm.getSecondOfMinute(), 2);
String ms = intFormat(tm.getMillisOfSecond(), 3);
return hours + ":" + minutes + ":" + seconds + ":" + ms;
}
/** Formats an integer value with leading 0s if needed. */
public static String intFormat(int myint, int digits) {
return String.format("%0" + digits + "d", myint);
}
/**
* Formats an integer with leading 0 using maximum sequence number.
*
* @param myint integer to format
* @param maxint max of "myint"
* @return String
*/
public static String intFormatMax(int myint, int maxint) {
return intFormat(myint, String.valueOf(maxint).length());
}
/**
* Locates the first valid file in the STK arrays.
* @return Path to the first valid file.
*/
private String locateFirstValidFile() {
for (int q = 0; q < stks.length; q++) {
for (int f = 0; f < stks[q].length; f++) {
if (stks[q][f] != null) {
return stks[q][f];
}
}
}
return null;
}
private TiffRational readRational(RandomAccessInputStream s)
throws IOException
{
return readRational(s, s.getFilePointer());
}
private TiffRational readRational(RandomAccessInputStream s, long offset)
throws IOException
{
if (offset >= s.length() - 8) {
return null;
}
s.seek(offset);
int num = s.readInt();
int denom = s.readInt();
return new TiffRational(num, denom);
}
private void setCanLookForND(boolean v) {
FormatTools.assertId(currentId, false, 1);
canLookForND = v;
}
private void readPlaneData() throws IOException {
in.skipBytes(4);
int keyLength = in.read();
String key = in.readString(keyLength);
in.skipBytes(4);
int type = in.read();
int index = 0;
switch (type) {
case 1:
while (getGlobalMeta("Channel #" + index + " " + key) != null) {
index++;
}
addGlobalMeta("Channel #" + index + " " + key, readRational(in).doubleValue());
break;
case 2:
int valueLength = in.read();
String value = in.readString(valueLength);
if (valueLength == 0) {
in.skipBytes(4);
valueLength = in.read();
value = in.readString(valueLength);
}
while (getGlobalMeta("Channel #" + index + " " + key) != null) {
index++;
}
addGlobalMeta("Channel #" + index + " " + key, value);
if (key.equals("_IllumSetting_")) {
if (waveNames == null) waveNames = new ArrayList<String>();
waveNames.add(value);
}
break;
}
}
private String getKey(int id) {
switch (id) {
case 0: return "AutoScale";
case 1: return "MinScale";
case 2: return "MaxScale";
case 3: return "Spatial Calibration";
case 4: return "XCalibration";
case 5: return "YCalibration";
case 6: return "CalibrationUnits";
case 7: return "Name";
case 8: return "ThreshState";
case 9: return "ThreshStateRed";
// there is no 10
case 11: return "ThreshStateGreen";
case 12: return "ThreshStateBlue";
case 13: return "ThreshStateLo";
case 14: return "ThreshStateHi";
case 15: return "Zoom";
case 16: return "DateTime";
case 17: return "LastSavedTime";
case 18: return "currentBuffer";
case 19: return "grayFit";
case 20: return "grayPointCount";
case 21: return "grayX";
case 22: return "grayY";
case 23: return "grayMin";
case 24: return "grayMax";
case 25: return "grayUnitName";
case 26: return "StandardLUT";
case 27: return "Wavelength";
case 28: return "StagePosition";
case 29: return "CameraChipOffset";
case 30: return "OverlayMask";
case 31: return "OverlayCompress";
case 32: return "Overlay";
case 33: return "SpecialOverlayMask";
case 34: return "SpecialOverlayCompress";
case 35: return "SpecialOverlay";
case 36: return "ImageProperty";
case 38: return "AutoScaleLoInfo";
case 39: return "AutoScaleHiInfo";
case 40: return "AbsoluteZ";
case 41: return "AbsoluteZValid";
case 42: return "Gamma";
case 43: return "GammaRed";
case 44: return "GammaGreen";
case 45: return "GammaBlue";
case 46: return "CameraBin";
case 47: return "NewLUT";
case 48: return "ImagePropertyEx";
case 49: return "PlaneProperty";
case 50: return "UserLutTable";
case 51: return "RedAutoScaleInfo";
case 52: return "RedAutoScaleLoInfo";
case 53: return "RedAutoScaleHiInfo";
case 54: return "RedMinScaleInfo";
case 55: return "RedMaxScaleInfo";
case 56: return "GreenAutoScaleInfo";
case 57: return "GreenAutoScaleLoInfo";
case 58: return "GreenAutoScaleHiInfo";
case 59: return "GreenMinScaleInfo";
case 60: return "GreenMaxScaleInfo";
case 61: return "BlueAutoScaleInfo";
case 62: return "BlueAutoScaleLoInfo";
case 63: return "BlueAutoScaleHiInfo";
case 64: return "BlueMinScaleInfo";
case 65: return "BlueMaxScaleInfo";
case 66: return "OverlayPlaneColor";
}
return null;
}
private Map.Entry<Integer, Integer> getWellCoords(String label) {
if (label.indexOf(",") >= 0) {
label = label.substring(0, label.indexOf(","));
}
if (label.indexOf(":") >= 0) {
label = label.substring(label.indexOf(":") + 1);
}
Matcher matcher = WELL_COORDS.matcher(label);
if (!matcher.find()) return null;
int nGroups = matcher.groupCount();
if (nGroups != 2) return null;
return new AbstractMap.SimpleEntry(
(int) (matcher.group(1).toUpperCase().charAt(0) - 'A'),
Integer.parseInt(matcher.group(2)) - 1
);
}
/**
* Read a null-terminated string. Read at most n characters if the null
* character is not found.
*/
private static String readCString(RandomAccessInputStream s, int n)
throws IOException {
int avail = s.available();
if (n > avail) n = avail;
byte[] b = new byte[n];
s.readFully(b);
int i;
for (i = 0; i < b.length && b[i] != 0; i++) { }
return new String(b, 0, i, Constants.ENCODING);
}
/**
* Parses the given ND file to determined the version and return
* the expected file suffix
* @param ndfile
* The ND file which should be parsed
* @return The file suffix to be used for associated files based on the ND version
* @throws IOException
*/
private String getNDVersionSuffix(Location ndfile) throws IOException {
ndFilename = ndfile.getAbsolutePath();
String[] lines = DataTools.readFile(ndFilename).split("\n");
boolean globalDoZ = true;
String version = NDINFOFILE_VER1;
StringBuilder currentValue = new StringBuilder();
String key = "";
for (String line : lines) {
int comma = line.indexOf(',');
if (comma <= 0 && line.indexOf("EndFile") < 0) {
currentValue.append("\n");
currentValue.append(line);
continue;
}
String value = currentValue.toString();
if (key.equals("NDInfoFile")) version = value;
else if (key.equals("DoZSeries")) {
globalDoZ = Boolean.parseBoolean(value);
}
if (comma >= 1) {
key = line.substring(1, comma - 1).trim();
}
else {
key = "";
}
currentValue.delete(0, currentValue.length());
currentValue.append(line.substring(comma + 1).trim());
}
String formatSuffix = "stk";
if (version.equals(NDINFOFILE_VER1)) {
formatSuffix = "tif";
if (globalDoZ) {
formatSuffix = "stk";
}
}
else if (version.equals(NDINFOFILE_VER2)) {
formatSuffix = "tif";
}
return formatSuffix;
}
}
| gpl-2.0 |
geneos/adempiere | base/src/org/compiere/model/X_AD_Session.java | 6203 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/** Generated Model - DO NOT CHANGE */
package org.compiere.model;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Properties;
import org.compiere.util.KeyNamePair;
/** Generated Model for AD_Session
* @author Adempiere (generated)
* @version Release 3.7.0LTS - $Id$ */
public class X_AD_Session extends PO implements I_AD_Session, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20110831L;
/** Standard Constructor */
public X_AD_Session (Properties ctx, int AD_Session_ID, String trxName)
{
super (ctx, AD_Session_ID, trxName);
/** if (AD_Session_ID == 0)
{
setAD_Session_ID (0);
setProcessed (false);
} */
}
/** Load Constructor */
public X_AD_Session (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 6 - System - Client
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_Session[")
.append(get_ID()).append("]");
return sb.toString();
}
public org.compiere.model.I_AD_Role getAD_Role() throws RuntimeException
{
return (org.compiere.model.I_AD_Role)MTable.get(getCtx(), org.compiere.model.I_AD_Role.Table_Name)
.getPO(getAD_Role_ID(), get_TrxName()); }
/** Set Role.
@param AD_Role_ID
Responsibility Role
*/
public void setAD_Role_ID (int AD_Role_ID)
{
if (AD_Role_ID < 0)
set_Value (COLUMNNAME_AD_Role_ID, null);
else
set_Value (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID));
}
/** Get Role.
@return Responsibility Role
*/
public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Session.
@param AD_Session_ID
User Session Online or Web
*/
public void setAD_Session_ID (int AD_Session_ID)
{
if (AD_Session_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Session_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Session_ID, Integer.valueOf(AD_Session_ID));
}
/** Get Session.
@return User Session Online or Web
*/
public int getAD_Session_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Session_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getAD_Session_ID()));
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Login date.
@param LoginDate Login date */
public void setLoginDate (Timestamp LoginDate)
{
set_Value (COLUMNNAME_LoginDate, LoginDate);
}
/** Get Login date.
@return Login date */
public Timestamp getLoginDate ()
{
return (Timestamp)get_Value(COLUMNNAME_LoginDate);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Remote Addr.
@param Remote_Addr
Remote Address
*/
public void setRemote_Addr (String Remote_Addr)
{
set_ValueNoCheck (COLUMNNAME_Remote_Addr, Remote_Addr);
}
/** Get Remote Addr.
@return Remote Address
*/
public String getRemote_Addr ()
{
return (String)get_Value(COLUMNNAME_Remote_Addr);
}
/** Set Remote Host.
@param Remote_Host
Remote host Info
*/
public void setRemote_Host (String Remote_Host)
{
set_ValueNoCheck (COLUMNNAME_Remote_Host, Remote_Host);
}
/** Get Remote Host.
@return Remote host Info
*/
public String getRemote_Host ()
{
return (String)get_Value(COLUMNNAME_Remote_Host);
}
/** Set Web Session.
@param WebSession
Web Session ID
*/
public void setWebSession (String WebSession)
{
set_ValueNoCheck (COLUMNNAME_WebSession, WebSession);
}
/** Get Web Session.
@return Web Session ID
*/
public String getWebSession ()
{
return (String)get_Value(COLUMNNAME_WebSession);
}
} | gpl-2.0 |
bigdataviewer/SPIM_Registration | src/main/java/spim/process/fusion/deconvolution/MVDeconInput.java | 2227 | /*-
* #%L
* Fiji distribution of ImageJ for the life sciences.
* %%
* Copyright (C) 2007 - 2017 Fiji developers.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
package spim.process.fusion.deconvolution;
import java.util.ArrayList;
import net.imglib2.exception.IncompatibleTypeException;
import net.imglib2.img.ImgFactory;
import net.imglib2.type.numeric.real.FloatType;
import spim.process.fusion.deconvolution.MVDeconFFT.PSFTYPE;
public class MVDeconInput
{
public final static float minValue = 0.0001f;
final ArrayList< MVDeconFFT > views = new ArrayList< MVDeconFFT >();
final private ImgFactory< FloatType > imgFactory;
/**
* the imgfactory used for PSI, the temporary images and inputs
* @param imgFactory
*/
public MVDeconInput( final ImgFactory< FloatType > imgFactory )
{
this.imgFactory = imgFactory;
}
public ImgFactory< FloatType > imgFactory() { return imgFactory; }
public void add( final MVDeconFFT view )
{
views.add( view );
for ( final MVDeconFFT v : views )
v.setNumViews( getNumViews() );
}
/**
* init all views
*
* @return the same instance again for convenience
* @throws IncompatibleTypeException
*/
public MVDeconInput init( final PSFTYPE iterationType ) throws IncompatibleTypeException
{
for ( final MVDeconFFT view : views )
view.init( iterationType, views );
return this;
}
/**
* @return - the image data
*/
public ArrayList< MVDeconFFT > getViews() { return views; }
/**
* The number of views for this deconvolution
* @return
*/
public int getNumViews() { return views.size(); }
}
| gpl-2.0 |
apruden/onyx | onyx-webapp/src/main/java/org/obiba/onyx/webapp/participant/panel/AddCommentPanel.java | 2283 | /*******************************************************************************
* Copyright 2008(c) The OBiBa Consortium. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package org.obiba.onyx.webapp.participant.panel;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.markup.html.basic.MultiLineLabel;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.validation.validator.StringValidator;
import org.obiba.onyx.engine.Action;
import org.obiba.onyx.engine.ActionType;
import org.obiba.onyx.wicket.behavior.FocusBehavior;
import org.obiba.onyx.wicket.behavior.RequiredFormFieldBehavior;
/**
* Content of InterviewPage's "Add Comment" dialog.
*/
public class AddCommentPanel extends Panel {
//
// Constants
//
private static final long serialVersionUID = 1L;
private TextArea commentField;
//
// Constructors
//
public AddCommentPanel(String id) {
super(id);
Action action = new Action();
action.setActionType(ActionType.COMMENT);
setDefaultModel(new Model<Action>(action));
initPanel();
}
//
// Methods
//
private void initPanel() {
add(new MultiLineLabel("instructions", new ResourceModel("AnonymousComments")));
commentField = new TextArea("comment", new PropertyModel(getDefaultModelObject(), "comment"));
commentField.setOutputMarkupId(true);
commentField.add(new AttributeModifier("class", true, new Model("comment-text")));
commentField.add(new FocusBehavior());
commentField.add(new RequiredFormFieldBehavior());
commentField.add(new StringValidator.MaximumLengthValidator(2000));
add(commentField);
}
public void clearCommentField() {
((Action) getDefaultModelObject()).setComment("");
commentField.clearInput();
}
}
| gpl-3.0 |
yesimwearingpants/Terracraft-Engine | lib/src/org/lwjgl/opencl/CLDeviceTopologyAMD.java | 5554 | /*
* Copyright LWJGL. All rights reserved.
* License terms: http://lwjgl.org/license.php
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.opencl;
import java.nio.*;
import org.lwjgl.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.MemoryUtil.*;
/** The struct returned by {@link CL10#clGetDeviceInfo} with {@code param_name} set to {@link AMDDeviceTopology#CL_DEVICE_TOPOLOGY_AMD}. */
public final class CLDeviceTopologyAMD implements Pointer {
/** The struct size in bytes. */
public static final int SIZEOF;
/** The struct member offsets. */
public static final int
RAW,
RAW_TYPE,
RAW_DATA,
PCIE,
PCIE_TYPE,
PCIE_BUS,
PCIE_DEVICE,
PCIE_FUNCTION;
static {
IntBuffer offsets = BufferUtils.createIntBuffer(8);
SIZEOF = offsets(memAddress(offsets));
RAW = offsets.get(0);
RAW_TYPE = offsets.get(1);
RAW_DATA = offsets.get(2);
PCIE = offsets.get(3);
PCIE_TYPE = offsets.get(4);
PCIE_BUS = offsets.get(5);
PCIE_DEVICE = offsets.get(6);
PCIE_FUNCTION = offsets.get(7);
}
private final ByteBuffer struct;
public CLDeviceTopologyAMD() {
this(malloc());
}
public CLDeviceTopologyAMD(ByteBuffer struct) {
if ( LWJGLUtil.CHECKS )
checkBuffer(struct, SIZEOF);
this.struct = struct;
}
public ByteBuffer buffer() {
return struct;
}
@Override
public long getPointer() {
return memAddress(struct);
}
public void setRawType(int type) { rawType(struct, type); }
public void setRawData(ByteBuffer data) { rawDataSet(struct, data); }
public void setRawData(int index, int data) { rawData(struct, index, data); }
public void setPcieType(int type) { pcieType(struct, type); }
public void setPcieBus(int bus) { pcieBus(struct, bus); }
public void setPcieDevice(int device) { pcieDevice(struct, device); }
public void setPcieFunction(int function) { pcieFunction(struct, function); }
public int getRawType() { return rawType(struct); }
public void getRawData(ByteBuffer data) { rawDataGet(struct, data); }
public int getPcieType() { return pcieType(struct); }
public int getPcieBus() { return pcieBus(struct); }
public int getPcieDevice() { return pcieDevice(struct); }
public int getPcieFunction() { return pcieFunction(struct); }
// -----------------------------------
private static native int offsets(long buffer);
/** Returns a new {@link ByteBuffer} instance with a capacity equal to {@link #SIZEOF}. */
public static ByteBuffer malloc() { return BufferUtils.createByteBuffer(SIZEOF); }
/** Virtual constructor. Calls {@link #malloc} and initializes the returned {@link ByteBuffer} instance with the specified values. */
public static ByteBuffer malloc(
int raw_type,
ByteBuffer raw_data,
int pcie_type,
int pcie_bus,
int pcie_device,
int pcie_function
) {
ByteBuffer cl_device_topology_amd = malloc();
rawType(cl_device_topology_amd, raw_type);
rawDataSet(cl_device_topology_amd, raw_data);
pcieType(cl_device_topology_amd, pcie_type);
pcieBus(cl_device_topology_amd, pcie_bus);
pcieDevice(cl_device_topology_amd, pcie_device);
pcieFunction(cl_device_topology_amd, pcie_function);
return cl_device_topology_amd;
}
public static void rawType(ByteBuffer cl_device_topology_amd, int type) { cl_device_topology_amd.putInt(cl_device_topology_amd.position() + RAW_TYPE, type); }
public static void rawDataSet(ByteBuffer cl_device_topology_amd, ByteBuffer data) {
if ( LWJGLUtil.CHECKS ) {
checkBufferGT(data, 5 * 4);
}
memCopy(memAddress(data), memAddress(cl_device_topology_amd) + RAW_DATA, data.remaining());
}
public static void rawData(ByteBuffer cl_device_topology_amd, int index, int data) { cl_device_topology_amd.putInt(RAW_DATA + index * 4, data); }
public static void pcieType(ByteBuffer cl_device_topology_amd, int type) { cl_device_topology_amd.putInt(cl_device_topology_amd.position() + PCIE_TYPE, type); }
public static void pcieBus(ByteBuffer cl_device_topology_amd, int bus) { cl_device_topology_amd.put(cl_device_topology_amd.position() + PCIE_BUS, (byte)bus); }
public static void pcieDevice(ByteBuffer cl_device_topology_amd, int device) { cl_device_topology_amd.put(cl_device_topology_amd.position() + PCIE_DEVICE, (byte)device); }
public static void pcieFunction(ByteBuffer cl_device_topology_amd, int function) { cl_device_topology_amd.put(cl_device_topology_amd.position() + PCIE_FUNCTION, (byte)function); }
public static int rawType(ByteBuffer cl_device_topology_amd) { return cl_device_topology_amd.getInt(cl_device_topology_amd.position() + RAW_TYPE); }
public static void rawDataGet(ByteBuffer cl_device_topology_amd, ByteBuffer data) {
if ( LWJGLUtil.CHECKS ) checkBufferGT(data, 5 * 4);
memCopy(memAddress(cl_device_topology_amd) + RAW_DATA, memAddress(data), data.remaining());
}
public static int rawData(ByteBuffer cl_device_topology_amd, int index) {
return cl_device_topology_amd.getInt(RAW_DATA + index * 4);
}
public static int pcieType(ByteBuffer cl_device_topology_amd) { return cl_device_topology_amd.getInt(cl_device_topology_amd.position() + PCIE_TYPE); }
public static int pcieBus(ByteBuffer cl_device_topology_amd) { return cl_device_topology_amd.get(cl_device_topology_amd.position() + PCIE_BUS); }
public static int pcieDevice(ByteBuffer cl_device_topology_amd) { return cl_device_topology_amd.get(cl_device_topology_amd.position() + PCIE_DEVICE); }
public static int pcieFunction(ByteBuffer cl_device_topology_amd) { return cl_device_topology_amd.get(cl_device_topology_amd.position() + PCIE_FUNCTION); }
} | gpl-3.0 |
MuVethrfolnir/vethrfolnir-mu | src/main/game-core/com/vethrfolnir/game/templates/npc/SpawnTemplate.java | 1220 | /**
* Copyright (C) 2013-2014 Project-Vethrfolnir
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.vethrfolnir.game.templates.npc;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
/**
* @author Vlad
*/
@JsonInclude(Include.NON_DEFAULT)
public class SpawnTemplate {
public int NpcId;
public int MapId;
public int Radius;
public int x;
public int y;
public int heading;
public boolean Attackable;
// Spawn Groups
public int StartX = -1;
public int StartY = -1;
public int Count;
}
| gpl-3.0 |
bordertechorg/wcomponents | wcomponents-core/src/test/java/com/github/bordertech/wcomponents/util/ObjectGraphDump_Test.java | 1581 | package com.github.bordertech.wcomponents.util;
import com.github.bordertech.wcomponents.AbstractWComponentTestCase;
import com.github.bordertech.wcomponents.WLabel;
import com.github.bordertech.wcomponents.WPanel;
import com.github.bordertech.wcomponents.layout.BorderLayout;
import org.junit.Assert;
import org.junit.Test;
/**
* ObjectGraphDump_Test - unit tests for {@link ObjectGraphDump}.
*
* @author Anthony O'Connor
* @since 1.0.0
*/
public class ObjectGraphDump_Test extends AbstractWComponentTestCase {
/**
* label for testing.
*/
private static final String TEST_LABEL = "TEST_LABEL";
@Test
public void testDump() {
WPanel component = new WPanel();
component.setLayout(new BorderLayout());
component.add(new WLabel(TEST_LABEL), BorderLayout.NORTH);
ObjectGraphNode graphNode = ObjectGraphDump.dump(component);
String result = graphNode.toXml();
// ObjectGraphNode tested independently
// for the input 'component' above - the dump result must at least contain the following
// and have run without exceptions
Assert.assertTrue("",
result.indexOf("type=\"com.github.bordertech.wcomponents.WPanel\"") != -1);
Assert.assertTrue("", result.indexOf(
"field=\"label\" type=\"com.github.bordertech.wcomponents.WLabel\"") != -1);
Assert.assertTrue("", result.indexOf("field=\"text\" value=\""" + TEST_LABEL
+ ""\" type=\"java.io.Serializable\"") != -1);
Assert.assertTrue("", result.indexOf(
"field=\"value\" type=\"com.github.bordertech.wcomponents.layout.BorderLayout$BorderLayoutConstraint\"") != -1);
}
}
| gpl-3.0 |
epearson-nmdp/genotype-list | gl-service-nomenclature-kir/src/main/java/org/nmdp/gl/service/nomenclature/kir/IpdKir2_6_1.java | 1896 | /*
gl-service-nomenclature-ipd IPD-KIR nomenclature.
Copyright (c) 2012-2015 National Marrow Donor Program (NMDP)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 3 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; with out even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
> http://www.fsf.org/licensing/licenses/lgpl.html
> http://www.opensource.org/licenses/lgpl-license.php
*/
package org.nmdp.gl.service.nomenclature.kir;
import org.nmdp.gl.service.GlRegistry;
import org.nmdp.gl.service.GlstringResolver;
import org.nmdp.gl.service.IdResolver;
import org.nmdp.gl.service.nomenclature.ClasspathNomenclature;
import com.google.inject.Inject;
/**
* IPD-KIR version 2.6.1 nomenclature.
*/
public final class IpdKir2_6_1 extends ClasspathNomenclature {
@Inject
public IpdKir2_6_1(final GlstringResolver glstringResolver,
final IdResolver idResolver,
final GlRegistry glRegistry) {
super("ipd-kir-2.6.1.txt", glstringResolver, idResolver, glRegistry);
}
@Override
public String getName() {
return "IPD-KIR Database";
}
@Override
public String getVersion() {
return "2.6.1";
}
@Override
public String getURL() {
return "https://www.ebi.ac.uk/ipd/kir/";
}
}
| gpl-3.0 |
kingtang/spring-learn | spring-webmvc/src/main/java/org/springframework/web/servlet/handler/package-info.java | 181 |
/**
*
* Provides standard HandlerMapping implementations,
* including abstract base classes for custom implementations.
*
*/
package org.springframework.web.servlet.handler;
| gpl-3.0 |
apruden/onyx | onyx-core/src/test/java/org/obiba/onyx/core/etl/participant/impl/XmlParticipantReaderTest.java | 18788 | /*******************************************************************************
* Copyright 2008(c) The OBiBa Consortium. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package org.obiba.onyx.core.etl.participant.impl;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.obiba.onyx.core.domain.participant.Gender;
import org.obiba.onyx.core.domain.participant.Participant;
import org.obiba.onyx.core.domain.participant.ParticipantAttribute;
import org.obiba.onyx.core.domain.participant.ParticipantAttributeReader;
import org.obiba.onyx.core.domain.participant.ParticipantMetadata;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemStreamException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
/**
* Unit tests for <code>DefaultParticipantExcelReader</code>.
*/
public class XmlParticipantReaderTest {
//private Logger logger = LoggerFactory.getLogger(getClass());
//
// Constants
//
private static final String TEST_RESOURCES_DIR = XmlParticipantReaderTest.class.getSimpleName();
// private static final String APPOINTMENTS_RESOURCES_DIR = "appointments";
//
// Instance Variables
//
private ParticipantMetadata participantMetadata;
@Autowired(required = true)
ExecutionContext context;
private Map<String, String> columnNameToAttributeNameMap;
//
// Fixture Methods (setUp / tearDown)
//
@Before
public void setUp() throws Exception {
initParticipantMetadata();
initAttributeDefinition();
}
//
// Test Methods
//
// @Test
// public void testIsUpdateAvailableFalse() {
//
// try {
// XmlParticipantReader reader = createXmlParticipantReader(false, APPOINTMENTS_RESOURCES_DIR + "/inNoData");
// Assert.assertEquals(false, reader.isUpdateAvailable());
// reader = createXmlParticipantReader(false, APPOINTMENTS_RESOURCES_DIR + "/in");
// Assert.assertEquals(false, reader.isUpdateAvailable());
//
// } catch(IOException e) {
// throw new RuntimeException(e);
// }
// }
// @Test
// public void testIsUpdateAvailableTrue() {
// XmlParticipantReader reader = createXmlParticipantReader(false, APPOINTMENTS_RESOURCES_DIR + "/inXml");
//
// try {
// Assert.assertEquals(true, reader.isUpdateAvailable());
// } catch(IOException e) {
// throw new RuntimeException(e);
// }
// }
/**
* Tests processing of an appointment list that contains no configured attributes (i.e., essential attributes only).
* @throws Exception
* @throws ParseException
* @throws UnexpectedInputException
*/
@Test
public void testProcessWithNoConfiguredAttributes() throws UnexpectedInputException, ParseException, Exception {
XmlParticipantReaderForTest reader = createXmlParticipantReaderForTest(false, TEST_RESOURCES_DIR + "/appointmentList_noConfiguredAttributes.xml");
reader.setColumnNameToAttributeNameMap(columnNameToAttributeNameMap);
reader.setParticipantMetadata(participantMetadata);
reader.open(context);
List<Participant> participants = new ArrayList<Participant>();
while(reader.getIterator().hasNext()) {
Participant participant = reader.read();
if(participant != null) participants.add(participant);
}
Assert.assertEquals(3, participants.size());
Assert.assertEquals("Tremblay", participants.get(0).getLastName());
Assert.assertEquals("Casserly", participants.get(2).getLastName());
}
/**
* Tests processing of an appointment list where a tag is missing for a mandatory attribute (Birth Date). XmlReader
* should not return an error as it is a validation done in the ParticipantProcessor (Management is different here
* from the default ParticipantReader class).
*
* @throws IOException if the appointment list could not be read
*/
@Test
public void testProcessWithMissingMandatoryAttributeTag() throws IOException {
XmlParticipantReaderForTest reader = createXmlParticipantReaderForTest(false, TEST_RESOURCES_DIR + "/appointmentList_missingMandatoryAttributeTag.xml");
reader.setColumnNameToAttributeNameMap(columnNameToAttributeNameMap);
reader.setParticipantMetadata(participantMetadata);
reader.open(context);
List<Participant> participants = new ArrayList<Participant>();
try {
while(reader.getIterator().hasNext()) {
Participant participant = reader.read();
if(participant != null) participants.add(participant);
}
} catch(Exception e) {
throw new RuntimeException(e);
}
Assert.assertEquals(3, participants.size());
Assert.assertEquals("Tremblay", participants.get(0).getLastName());
Assert.assertNull(participants.get(0).getBirthDate());
Assert.assertEquals("Smith", participants.get(1).getLastName());
Assert.assertNull(participants.get(1).getBirthDate());
Assert.assertEquals("Casserly", participants.get(2).getLastName());
Assert.assertNull(participants.get(2).getBirthDate());
}
/**
* Tests processing of an appointment list where a mandatory attribute (Enrollment ID, at line 4) has not been
* assigned a value. Reader should not return an error as it is a validation done in the ParticipantProcessor.
*
* @throws IOException if the appointment list could not be read
*/
@Test
public void testProcessWithMissingMandatoryAttributeValue() throws IOException {
XmlParticipantReaderForTest reader = createXmlParticipantReaderForTest(false, TEST_RESOURCES_DIR + "/appointmentList_missingMandatoryAttributeValue.xml");
reader.setColumnNameToAttributeNameMap(columnNameToAttributeNameMap);
reader.setParticipantMetadata(participantMetadata);
reader.open(context);
List<Participant> participants = new ArrayList<Participant>();
try {
while(reader.getIterator().hasNext()) {
Participant participant = reader.read();
if(participant != null) participants.add(participant);
}
} catch(Exception e) {
throw new RuntimeException(e);
}
Assert.assertEquals(3, participants.size());
Assert.assertEquals("Tremblay", participants.get(0).getLastName());
Assert.assertEquals("100001", participants.get(0).getEnrollmentId());
Assert.assertEquals("Smith", participants.get(1).getLastName());
Assert.assertNull(participants.get(1).getEnrollmentId());
Assert.assertEquals("Casserly", participants.get(2).getLastName());
Assert.assertNull(participants.get(2).getEnrollmentId());
}
/**
* Tests processing of an appointment list where an attribute (Appointment Time, line 5) has been assigned a value of
* the wrong type.
*
* @throws IOException if the appointment list could not be read
*/
@Test
public void testProcessWithWrongAttributeValueType() throws IOException {
XmlParticipantReaderForTest reader = createXmlParticipantReaderForTest(false, TEST_RESOURCES_DIR + "/appointmentList_wrongAttributeValueType.xml");
reader.setColumnNameToAttributeNameMap(columnNameToAttributeNameMap);
reader.setParticipantMetadata(participantMetadata);
reader.open(context);
List<Participant> participants = new ArrayList<Participant>();
try {
while(reader.getIterator().hasNext()) {
Participant participant = reader.read();
if(participant != null) participants.add(participant);
}
} catch(Exception e) {
String errorMessage = e.getMessage();
Assert.assertEquals("Wrong data type value for field 'Appointment Time': TEST", errorMessage);
return;
}
Assert.fail("Should have thrown an IllegalArgumentException");
}
/**
* Tests processing of an appointment list where an attribute (Gender, line 3) has been assigned value that is not
* allowed (i.e., is not with the attribute's "allowed value" list). Reader should not return an error as it is a
* validation done in the ParticipantProcessor.
*
* @throws IOException if the appointment list could not be read
*/
@Test
public void testProcessWithNotAllowedAttributeValue() throws IOException {
XmlParticipantReaderForTest reader = createXmlParticipantReaderForTest(false, TEST_RESOURCES_DIR + "/appointmentList_notAllowedAttributeValue.xml");
reader.setColumnNameToAttributeNameMap(columnNameToAttributeNameMap);
reader.setParticipantMetadata(participantMetadata);
reader.open(context);
List<Participant> participants = new ArrayList<Participant>();
try {
while(reader.getIterator().hasNext()) {
Participant participant = reader.read();
if(participant != null) participants.add(participant);
}
} catch(Exception e) {
throw new RuntimeException(e);
}
Assert.assertEquals(3, participants.size());
Assert.assertEquals("Tremblay", participants.get(0).getLastName());
Assert.assertNull(participants.get(0).getGender());
Assert.assertEquals(Gender.MALE, participants.get(1).getGender());
Assert.assertEquals("Casserly", participants.get(2).getLastName());
Assert.assertEquals(Gender.FEMALE, participants.get(2).getGender());
}
/**
* Tests processing of an appointment list that contains a duplicate attribute column (Last Name).
*
* @throws IOException if the appointment list could not be read
*/
@Test
public void testProcessWithDuplicateAttributeTag() throws IOException {
XmlParticipantReaderForTest reader = createXmlParticipantReaderForTest(false, TEST_RESOURCES_DIR + "/appointmentList_duplicateAttributeTag.xml");
reader.setColumnNameToAttributeNameMap(columnNameToAttributeNameMap);
reader.setParticipantMetadata(participantMetadata);
reader.open(context);
List<Participant> participants = new ArrayList<Participant>();
try {
while(reader.getIterator().hasNext()) {
Participant participant = reader.read();
if(participant != null) participants.add(participant);
}
} catch(Exception e) {
String errorMessage = e.getMessage();
Assert.assertEquals("Duplicate tag for field: Nom", errorMessage);
return;
}
Assert.fail("Should have thrown an IllegalArgumentException");
}
@Test
public void testProcessWithConfiguredAttributes() {
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(2008, 9 - 1, 1, 9, 0);
final Date expectedAppointmentTime = cal.getTime();
cal.clear();
cal.set(1964, 10 - 1, 1);
final Date expectedBirthDate = cal.getTime();
initConfiguredAttributeDefinition();
XmlParticipantReaderForTest reader = createXmlParticipantReaderForTest(true, TEST_RESOURCES_DIR + "/appointmentList_includesConfiguredAttributes.xml");
reader.setColumnNameToAttributeNameMap(columnNameToAttributeNameMap);
reader.setParticipantMetadata(participantMetadata);
reader.open(context);
List<Participant> participants = new ArrayList<Participant>();
try {
while(reader.getIterator().hasNext()) {
Participant participant = reader.read();
if(participant != null) participants.add(participant);
}
} catch(Exception e) {
throw new RuntimeException(e);
}
Assert.assertEquals(1, participants.size());
Assert.assertEquals(expectedAppointmentTime, participants.get(0).getAppointment().getDate());
Assert.assertEquals("cag001", participants.get(0).getSiteNo());
Assert.assertEquals("100001", participants.get(0).getEnrollmentId());
Assert.assertEquals("Tremblay", participants.get(0).getLastName());
Assert.assertEquals("Chantal", participants.get(0).getFirstName());
Assert.assertEquals("F", (participants.get(0).getGender().equals(Gender.FEMALE) ? "F" : "M"));
Assert.assertEquals(expectedBirthDate, participants.get(0).getBirthDate());
// Verify that the participant's configured attributes have been assigned the correct values.
Assert.assertEquals("299, Avenue des Pins Ouest", participants.get(0).getConfiguredAttributeValue("Street").getValue());
Assert.assertEquals("Montr\u00e9al", participants.get(0).getConfiguredAttributeValue("City").getValue());
Assert.assertEquals("QC", participants.get(0).getConfiguredAttributeValue("Province").getValue());
Assert.assertEquals("Canada", participants.get(0).getConfiguredAttributeValue("Country").getValue());
Assert.assertEquals("H1T 2M4", participants.get(0).getConfiguredAttributeValue("Postal Code").getValue());
Assert.assertEquals("514-343-9898 ext 9494", participants.get(0).getConfiguredAttributeValue("Phone").getValue());
}
@Test
public void testProcessWithRowContainingWhitespaceOnly() {
XmlParticipantReaderForTest reader = createXmlParticipantReaderForTest(false, TEST_RESOURCES_DIR + "/appointmentList_rowContainingWhitespaceOnly.xml");
reader.setColumnNameToAttributeNameMap(columnNameToAttributeNameMap);
reader.setParticipantMetadata(participantMetadata);
reader.open(context);
List<Participant> participants = new ArrayList<Participant>();
try {
while(reader.getIterator().hasNext()) {
Participant participant = reader.read();
if(participant != null) participants.add(participant);
}
} catch(Exception e) {
throw new RuntimeException(e);
}
Assert.assertEquals(3, participants.size());
}
/**
* Tests processing of an appointment list containing a duplicate enrollment id. Reader should not return an error as
* it is a validation done in the ParticipantProcessor.
*
* @throws IOException if the appointment list could not be read
*/
@Test
public void testProcessWithDuplicateDuplicateEnrollmentId() throws IOException {
XmlParticipantReaderForTest reader = createXmlParticipantReaderForTest(false, TEST_RESOURCES_DIR + "/appointmentList_duplicateEnrollmentId.xml");
reader.setColumnNameToAttributeNameMap(columnNameToAttributeNameMap);
reader.setParticipantMetadata(participantMetadata);
reader.open(context);
List<Participant> participants = new ArrayList<Participant>();
try {
while(reader.getIterator().hasNext()) {
Participant participant = reader.read();
if(participant != null) participants.add(participant);
}
} catch(Exception e) {
throw new RuntimeException(e);
}
Assert.assertEquals(3, participants.size());
Assert.assertEquals("Tremblay", participants.get(0).getLastName());
Assert.assertEquals("100001", participants.get(0).getEnrollmentId());
Assert.assertEquals("Smith", participants.get(1).getLastName());
Assert.assertEquals("100002", participants.get(1).getEnrollmentId());
Assert.assertEquals("Casserly", participants.get(2).getLastName());
Assert.assertEquals("100001", participants.get(2).getEnrollmentId());
}
//
// Helper Methods
//
// private XmlParticipantReader createXmlParticipantReader(boolean includeConfiguredAttributes, String resourcePath) {
// if(!includeConfiguredAttributes) {
// participantMetadata.setConfiguredAttributes(null);
// }
//
// XmlParticipantReader reader = new XmlParticipantReader();
// reader.setParticipantMetadata(participantMetadata);
// Resource[] resources = new Resource[] { new ClassPathResource(resourcePath) };
// reader.setInputDirectory(resources[0]);
//
// return reader;
// }
private void initParticipantMetadata() throws IOException {
participantMetadata = new ParticipantMetadata();
ParticipantAttributeReader attributeReader = new ParticipantAttributeReader();
attributeReader.setResources(new Resource[] { new ClassPathResource(TEST_RESOURCES_DIR + "/essential-attributes.xml") });
List<ParticipantAttribute> essentialAttributes = attributeReader.read();
participantMetadata.setEssentialAttributes(essentialAttributes);
attributeReader.setResources(new Resource[] { new ClassPathResource(TEST_RESOURCES_DIR + "/configured-attributes.xml") });
List<ParticipantAttribute> configuredAttributes = attributeReader.read();
participantMetadata.setConfiguredAttributes(configuredAttributes);
}
private class XmlParticipantReaderForTest extends XmlParticipantReader {
Resource resource;
public XmlParticipantReaderForTest(Resource resource) {
this.resource = resource;
}
@Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
try {
setFileInputStream(new FileInputStream(resource.getFile()));
} catch(IOException e) {
}
super.open(executionContext);
}
}
private XmlParticipantReaderForTest
createXmlParticipantReaderForTest(boolean includeConfiguredAttributes, String resourcePath) {
if(!includeConfiguredAttributes) {
participantMetadata.setConfiguredAttributes(null);
}
Resource[] resources = new Resource[] { new ClassPathResource(resourcePath) };
XmlParticipantReaderForTest reader = new XmlParticipantReaderForTest(resources[0]);
return reader;
}
private void initAttributeDefinition() {
columnNameToAttributeNameMap = new HashMap<String, String>();
columnNameToAttributeNameMap.put("Code_participant", "Enrollment ID");
columnNameToAttributeNameMap.put("Prenom", "First Name");
columnNameToAttributeNameMap.put("Nom", "Last Name");
columnNameToAttributeNameMap.put("Date_naissance", "Birth Date");
columnNameToAttributeNameMap.put("Sexe", "Gender");
columnNameToAttributeNameMap.put("Site", "Assessment Center ID");
columnNameToAttributeNameMap.put("Date_heure_RDV", "Appointment Time");
}
private void initConfiguredAttributeDefinition() {
if(columnNameToAttributeNameMap == null) columnNameToAttributeNameMap = new HashMap<String, String>();
columnNameToAttributeNameMap.put("Rue", "Street");
columnNameToAttributeNameMap.put("Ville", "City");
columnNameToAttributeNameMap.put("Province", "Province");
columnNameToAttributeNameMap.put("Pays", "Country");
columnNameToAttributeNameMap.put("Code_postal", "Postal Code");
columnNameToAttributeNameMap.put("Telephone", "Phone");
}
} | gpl-3.0 |
edmundoa/graylog2-server | graylog2-server/src/main/java/org/graylog2/plugin/indexer/searches/timeranges/AbsoluteRange.java | 4040 | /**
* This file is part of Graylog.
*
* Graylog is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Graylog is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Graylog. If not, see <http://www.gnu.org/licenses/>.
*/
package org.graylog2.plugin.indexer.searches.timeranges;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableMap;
import org.graylog2.plugin.Tools;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import java.util.Map;
@AutoValue
@JsonTypeName(value = AbsoluteRange.ABSOLUTE)
public abstract class AbsoluteRange extends TimeRange {
public static final String ABSOLUTE = "absolute";
@JsonProperty
@Override
public abstract String type();
@JsonProperty
public abstract DateTime from();
@JsonProperty
public abstract DateTime to();
public static Builder builder() {
return new AutoValue_AbsoluteRange.Builder();
}
@JsonCreator
public static AbsoluteRange create(@JsonProperty("type") String type,
@JsonProperty("from") DateTime from,
@JsonProperty("to") DateTime to) {
return builder().type(type).from(from).to(to).build();
}
public static AbsoluteRange create(DateTime from, DateTime to) {
return builder().type(ABSOLUTE).from(from).to(to).build();
}
public static AbsoluteRange create(String from, String to) throws InvalidRangeParametersException {
return builder().type(ABSOLUTE).from(from).to(to).build();
}
@Override
public DateTime getFrom() {
return from();
}
@Override
public DateTime getTo() {
return to();
}
@Override
public Map<String, Object> getPersistedConfig() {
return ImmutableMap.<String, Object>of(
"type", ABSOLUTE,
"from", getFrom(),
"to", getTo());
}
@AutoValue.Builder
public abstract static class Builder {
public abstract AbsoluteRange build();
public abstract Builder type(String type);
public abstract Builder to(DateTime to);
public abstract Builder from(DateTime to);
// TODO replace with custom build()
public Builder to(String to) throws InvalidRangeParametersException {
try {
return to(parseDateTime(to));
} catch (IllegalArgumentException e) {
throw new InvalidRangeParametersException("Invalid end of range: " + to, e);
}
}
// TODO replace with custom build()
public Builder from(String from) throws InvalidRangeParametersException {
try {
return from(parseDateTime(from));
} catch (IllegalArgumentException e) {
throw new InvalidRangeParametersException("Invalid start of range: " + from, e);
}
}
private DateTime parseDateTime(String to) {
final DateTimeFormatter formatter;
if (to.contains("T")) {
formatter = ISODateTimeFormat.dateTime();
} else {
formatter = Tools.timeFormatterWithOptionalMilliseconds();
}
// Use withOffsetParsed() to keep the timezone!
return formatter.withOffsetParsed().parseDateTime(to);
}
}
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | external/apache-http/src/org/apache/http/auth/InvalidCredentialsException.java | 2897 | /*
* $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/module-client/src/main/java/org/apache/http/auth/InvalidCredentialsException.java $
* $Revision: 505684 $
* $Date: 2007-02-10 04:40:02 -0800 (Sat, 10 Feb 2007) $
*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.auth;
/**
* Authentication credentials required to respond to a authentication
* challenge are invalid
*
* @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
*
* @since 4.0
*
* @deprecated Please use {@link java.net.URL#openConnection} instead.
* Please visit <a href="http://android-developers.blogspot.com/2011/09/androids-http-clients.html">this webpage</a>
* for further details.
*/
@Deprecated
public class InvalidCredentialsException extends AuthenticationException {
private static final long serialVersionUID = -4834003835215460648L;
/**
* Creates a new InvalidCredentialsException with a <tt>null</tt> detail message.
*/
public InvalidCredentialsException() {
super();
}
/**
* Creates a new InvalidCredentialsException with the specified message.
*
* @param message the exception detail message
*/
public InvalidCredentialsException(String message) {
super(message);
}
/**
* Creates a new InvalidCredentialsException with the specified detail message and cause.
*
* @param message the exception detail message
* @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
* if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
*/
public InvalidCredentialsException(String message, Throwable cause) {
super(message, cause);
}
}
| gpl-3.0 |
sechaparroc/proscene | src/remixlab/bias/Profile.java | 20157 | /**************************************************************************************
* bias_tree
* Copyright (c) 2014-2017 National University of Colombia, https://github.com/remixlab
* @author Jean Pierre Charalambos, http://otrolado.info/
*
* All rights reserved. Library that eases the creation of interactive
* scenes, released under the terms of the GNU Public License v3.0
* which is available at http://www.gnu.org/licenses/gpl.html
**************************************************************************************/
package remixlab.bias;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.Map.Entry;
/**
* A {@link Grabber} extension which allows to define
* {@link Shortcut} to {@link java.lang.reflect.Method} bindings. See
* {@link #setBinding(Shortcut, String)} and {@link #setBinding(Object, Shortcut, String)}
* .
* <p>
* To attach a profile to a grabber first override your
* {@link Grabber#performInteraction(BogusEvent)} method like this:
* <p>
* <pre>
* {@code
* public void performInteraction(BogusEvent event) {
* profile.handle(event);
* }
* }
* </pre>
* <p>
* (see {@link #handle(BogusEvent)}) and then simply pass the grabber instance to the
* {@link #Profile(Grabber)} constructor.
*/
public class Profile {
class ObjectMethodTuple {
Object object;
Method method;
ObjectMethodTuple(Object o, Method m) {
object = o;
method = m;
}
}
protected HashMap<Shortcut, ObjectMethodTuple> map;
protected Grabber grabber;
// static stuff
/**
* Utility function to programmatically register virtual keys to a {@link remixlab.bias.Shortcut} class,
* typically {@code KeyboardShortcuts}.
*/
public static void registerVKeys(Class<? extends Shortcut> shortcutClass, Class<?> keyEventClass) {
// TODO android needs testing
// idea took from here:
// http://stackoverflow.com/questions/15313469/java-keyboard-keycodes-list
// and here:
// http://www.java2s.com/Code/JavaAPI/java.lang.reflect/FieldgetIntObjectobj.htm
String prefix = keyEventClass.getName().contains("android") ? "KEYCODE_" : "VK_";
int l = prefix.length();
Field[] fields = keyEventClass.getDeclaredFields();
for (Field f : fields) {
if (Modifier.isStatic(f.getModifiers()) && Modifier.isPublic(f.getModifiers())) {
Class<?> clazzType = f.getType();
if (clazzType.toString().equals("int")) {
int id = -1;
try {
id = f.getInt(keyEventClass);
String name = f.getName();
if (!Shortcut.hasID(shortcutClass, id) && name.substring(0, l).equals(prefix))
Shortcut.registerID(shortcutClass, id, name);
} catch (Exception e) {
System.out.println("Warning: couldn't register key");
e.printStackTrace();
}
}
}
}
}
public static Object context = null;
/**
* Attaches a profile to the given grabber.
*/
public Profile(Grabber g) {
map = new HashMap<Shortcut, ObjectMethodTuple>();
grabber = g;
}
/**
* Instantiates this profile from another profile. Both Profile {@link #grabber()}
* should be of the same type.
*/
public void set(Profile p) {
if (grabber.getClass() != p.grabber.getClass()) {
System.err.println("Profile grabbers should be of the same type");
return;
}
map = new HashMap<Shortcut, ObjectMethodTuple>();
for (Map.Entry<Shortcut, ObjectMethodTuple> entry : p.map().entrySet()) {
if (entry.getValue().object == p.grabber)
map.put(entry.getKey(), new ObjectMethodTuple(grabber, entry.getValue().method));
else
map.put(entry.getKey(), new ObjectMethodTuple(entry.getValue().object, entry.getValue().method));
}
}
// public HashMap<Shortcut, Method>
/**
* Returns this profile set of shortcuts.
*/
public Set<Shortcut> shortcuts() {
return map.keySet();
}
/**
* Returns the grabber to which this profile is attached.
*/
public Grabber grabber() {
return grabber;
}
/**
* Internal use. Shortcut to object-method map.
*/
protected HashMap<Shortcut, ObjectMethodTuple> map() {
return map;
}
/**
* Returns the {@link java.lang.reflect.Method} binding for the given
* {@link Shortcut} key.
*
* @see #action(Shortcut)
*/
public Method method(Shortcut shortcut) {
return map.get(shortcut) == null ? null : map.get(shortcut).method;
}
/**
* Returns the {@link java.lang.reflect.Method} binding for the given
* {@link Shortcut} key.
*
* @see #method(Shortcut)
*/
public String action(Shortcut shortcut) {
Method m = method(shortcut);
if (m == null)
return null;
return m.getName();
}
/**
* Returns the action performing object. Either the {@link #grabber()} or an external
* object.
*/
public Object object(Shortcut shortcut) {
return map.get(shortcut) == null ? null : map.get(shortcut).object;
}
/**
* Main class method to be called from
* {@link Grabber#performInteraction(BogusEvent)}. Calls an action
* handler if the {@link BogusEvent#shortcut()} is bound.
*
* @see #setBinding(Shortcut, String)
* @see #setBinding(Object, Shortcut, String)
*/
public boolean handle(BogusEvent event) {
Method iHandlerMethod = method(event.shortcut());
if (iHandlerMethod != null) {
try {
if (object(event.shortcut()) == grabber)
iHandlerMethod.invoke(object(event.shortcut()), new Object[]{event});
else
iHandlerMethod.invoke(object(event.shortcut()), new Object[]{grabber, event});
return true;
} catch (Exception e) {
try {
if (object(event.shortcut()) == grabber)
iHandlerMethod.invoke(object(event.shortcut()), new Object[]{});
else
iHandlerMethod.invoke(object(event.shortcut()), new Object[]{grabber});
return true;
} catch (Exception empty) {
System.out.println("Something went wrong when invoking your " + iHandlerMethod.getName() + " method");
empty.printStackTrace();
}
System.out.println("Something went wrong when invoking your " + iHandlerMethod.getName() + " method");
e.printStackTrace();
}
}
return false;
}
/**
* Internal macro.
*/
protected boolean printWarning(Shortcut shortcut, String action) {
if (action == null) {
this.removeBinding(shortcut);
System.out.println(shortcut.description() + " removed");
return true;
}
if (hasBinding(shortcut)) {
Method a = method(shortcut);
if (a.getName().equals(action)) {
System.out.println("Warning: shortcut " + shortcut.description() + " already bound to " + a.getName());
return true;
} else {
System.out.println(
"Warning: overwriting shortcut " + shortcut.description() + " which was previously bound to " + a.getName());
return false;
}
}
return false;
}
/**
* Defines the shortcut that triggers the given action.
* <p>
* Attempt to set a shortcut for the {@code action} implemented by the {@link #context}
* (e.g., the {@code PApplet} in the case of a Processing application) or the
* {@link #grabber()} (e.g., the {@code InteractiveFrame} instance this profile is
* attached to, in the case of a Processing application) when no prototype is found in
* the {@link #context}.
* <p>
* The available action prototypes for the {@link #context} are:
* <ol>
* <li><b>public void action(grabber.getClass(), BogusEvent)</b></li>
* <li><b>public void action(grabber.getClass())</b></li>
* </ol>
* <p>
* The available action prototypes for the {@link #grabber()} are:
* <ol>
* <li><b>public void action(BogusEvent)</b></li>
* <li><b>public void action()</b></li>
* </ol>
* <p>
* The bogus-event type that may be passed to the above prototypes is the one specified
* by the {@link Shortcut#eventClass()} method:
* <ol>
* <li>A {@link remixlab.bias.event.ClickEvent} for a
* {@link remixlab.bias.event.ClickShortcut}</li>
* <li>A {@link remixlab.bias.event.KeyboardEvent} for a
* {@link remixlab.bias.event.KeyboardShortcut}</li>
* <li>A {@code DOFnEvent} for a {@link remixlab.bias.event.MotionShortcut}, where
* {@code n} is the {@link remixlab.bias.event.MotionShortcut#dofs(int)} of the
* motion-shortcut {@link remixlab.bias.event.MotionShortcut#id()}.</li>
* </ol>
* <b>Note</b> that in the latter case a {@link remixlab.bias.event.MotionEvent} may be
* passed too.
*
* @param shortcut {@link Shortcut}
* @param action {@link java.lang.String}
* @see #setBinding(Object, Shortcut, String)
* @see Shortcut#eventClass()
* @see remixlab.bias.event.MotionShortcut#eventClass()
* @see remixlab.bias.event.MotionShortcut#dofs(int)
* @see remixlab.bias.event.MotionShortcut#registerID(int, int, String)
*/
public boolean setBinding(Shortcut shortcut, String action) {
if (printWarning(shortcut, action))
return false;
// 1. Search at context:
String proto1 = null;
Method method = null;
if (context != null && context != grabber) {
try {
method = context.getClass().getMethod(action, new Class<?>[]{grabber.getClass(), shortcut.eventClass()});
} catch (Exception clazz) {
try {
method = context.getClass().getMethod(action, new Class<?>[]{grabber.getClass()});
} catch (Exception empty) {
if (shortcut.defaultEventClass() != null)
try {
method = context.getClass().getMethod(action, new Class<?>[]{grabber.getClass(), shortcut.defaultEventClass()});
} catch (Exception e) {
proto1 = prototypes(context, shortcut, action);
}
else {
proto1 = prototypes(context, shortcut, action);
}
}
}
if (method != null) {
map.put(shortcut, new ObjectMethodTuple(context, method));
return true;
}
}
// 2. If not found, search at grabber:
String proto2 = null;
String other = ". Or, if your binding lies within other object, use setBinding(Object object, Shortcut key, String action) instead.";
try {
method = grabber.getClass().getMethod(action, new Class<?>[]{shortcut.eventClass()});
} catch (Exception clazz) {
try {
method = grabber.getClass().getMethod(action, new Class<?>[]{});
} catch (Exception empty) {
if (shortcut.defaultEventClass() != null)
try {
method = grabber.getClass().getMethod(action, new Class<?>[]{shortcut.defaultEventClass()});
} catch (Exception motion) {
proto2 = prototypes(shortcut, action);
System.out.println("Warning: not binding set! Check the existence of one of the following method prototypes: " + (
proto1 != null ?
proto1 + ", " + proto2 :
proto2) + other);
}
else {
proto2 = prototypes(shortcut, action);
System.out.println("Warning: not binding set! Check the existence of one of the following method prototypes: " + (
proto1 != null ?
proto1 + ", " + proto2 :
proto2) + other);
}
}
}
if (method != null) {
map.put(shortcut, new ObjectMethodTuple(grabber, method));
return true;
}
return false;
}
/**
* Defines the shortcut that triggers the given action.
* <p>
* Attempt to set a shortcut for the {@code action} implemented by {@code object}. The
* action procedure may have two different prototypes:
* <ol>
* <li><b>public void action(BogusEvent)</b></li>
* <li><b>public void action()</b></li>
* </ol>
* The bogus-event type that may be passed to the first prototype is the one specified
* by the {@link Shortcut#eventClass()} method:
* <ol>
* <li>A {@link remixlab.bias.event.ClickEvent} for a
* {@link remixlab.bias.event.ClickShortcut}</li>
* <li>A {@link remixlab.bias.event.KeyboardEvent} for a
* {@link remixlab.bias.event.KeyboardShortcut}</li>
* <li>A {@code DOFnEvent} for a {@link remixlab.bias.event.MotionShortcut}, where
* {@code n} is the {@link remixlab.bias.event.MotionShortcut#dofs(int)} of the
* motion-shortcut {@link remixlab.bias.event.MotionShortcut#id()}.</li>
* </ol>
* <b>Note</b> that in the latter case a {@link remixlab.bias.event.MotionEvent} may be
* passed too.
*
* @param object {@link java.lang.Object}
* @param shortcut {@link Shortcut}
* @param action {@link java.lang.String}
* @see #setBinding(Object, Shortcut, String)
* @see Shortcut#eventClass()
* @see remixlab.bias.event.MotionShortcut#eventClass()
* @see remixlab.bias.event.MotionShortcut#dofs(int)
* @see remixlab.bias.event.MotionShortcut#registerID(int, int, String)
*/
public boolean setBinding(Object object, Shortcut shortcut, String action) {
if (object == null) {
System.out.println("Warning: no binding set. Object can't be null");
return false;
}
if (object == grabber())
return setBinding(shortcut, action);
if (printWarning(shortcut, action))
return false;
Method method = null;
try {
method = object.getClass().getMethod(action, new Class<?>[]{grabber.getClass(), shortcut.eventClass()});
} catch (Exception clazz) {
try {
method = object.getClass().getMethod(action, new Class<?>[]{grabber.getClass()});
} catch (Exception empty) {
if (shortcut.defaultEventClass() != null)
try {
method = object.getClass().getMethod(action, new Class<?>[]{grabber.getClass(), shortcut.defaultEventClass()});
} catch (Exception e) {
System.out.println(
"Warning: not binding set! Check the existence of one of the following method prototypes: " + prototypes(
object, shortcut, action));
}
else {
System.out.println(
"Warning: not binding set! Check the existence of one of the following method prototypes:: " + prototypes(
object, shortcut, action));
}
}
}
if (method != null) {
map.put(shortcut, new ObjectMethodTuple(object, method));
return true;
}
return false;
}
/**
* Internal use.
*
* @see #setBinding(Shortcut, String)
* @see #setBinding(Object, Shortcut, String)
*/
protected String prototypes(Object object, Shortcut shortcut, String action) {
String sgn1 =
"public void " + object.getClass().getSimpleName() + "." + action + "(" + grabber().getClass().getSimpleName()
+ ")";
String sgn2 =
"public void " + object.getClass().getSimpleName() + "." + action + "(" + grabber().getClass().getSimpleName()
+ ", " + shortcut.eventClass().getSimpleName() + ")";
if (shortcut.defaultEventClass() != null) {
String sgn3 =
"public void " + object.getClass().getSimpleName() + "." + action + "(" + grabber().getClass().getSimpleName()
+ ", " + shortcut.defaultEventClass().getSimpleName() + ")";
return sgn1 + ", " + sgn2 + ", " + sgn3;
} else
return sgn1 + ", " + sgn2;
}
/**
* Internal use.
*
* @see #setBinding(Shortcut, String)
*/
protected String prototypes(Shortcut shortcut, String action) {
String sgn1 = "public void " + grabber.getClass().getSimpleName() + "." + action + "()";
String sgn2 =
"public void " + grabber.getClass().getSimpleName() + "." + action + "(" + shortcut.eventClass().getSimpleName() + ")";
if (shortcut.defaultEventClass() != null) {
String sgn3 =
"public void " + grabber.getClass().getSimpleName() + "." + action + "(" + shortcut.defaultEventClass().getSimpleName()
+ ")";
return sgn1 + ", " + sgn2 + ", " + sgn3;
} else
return sgn1 + ", " + sgn2;
}
/**
* Removes the shortcut binding.
*
* @param shortcut {@link Shortcut}
*/
public void removeBinding(Shortcut shortcut) {
map.remove(shortcut);
}
/**
* Removes all the shortcuts from this object.
*/
public void removeBindings() {
map.clear();
}
/**
* Removes all the shortcuts from the given shortcut class.
*/
public void removeBindings(Class<? extends Shortcut> cls) {
Iterator<Entry<Shortcut, ObjectMethodTuple>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Shortcut, ObjectMethodTuple> pair = it.next();
if (cls.equals(pair.getKey().getClass()))
it.remove();
}
}
/**
* Returns a description of all the bindings this profile holds from the given shortcut
* class.
*/
public String info(Class<? extends Shortcut> cls) {
String result = new String();
HashMap<Shortcut, ObjectMethodTuple> clsMap = map(cls);
String info = new String();
for (Entry<Shortcut, ObjectMethodTuple> entry : clsMap.entrySet())
info += entry.getKey().description() + " -> " + entry.getValue().method.getName() + "\n";
if (!info.isEmpty()) {
result += cls.getSimpleName() + " bindings:\n";
result += info;
}
return result;
}
/**
* (Internal) Used by {@link #info(Class)}.
*/
protected HashMap<Shortcut, ObjectMethodTuple> map(Class<? extends Shortcut> cls) {
HashMap<Shortcut, ObjectMethodTuple> result = new HashMap<Shortcut, ObjectMethodTuple>();
for (Entry<Shortcut, ObjectMethodTuple> entry : map.entrySet())
if (entry.getKey() != null && entry.getValue() != null)
if (cls.equals(entry.getKey().getClass()))
result.put(entry.getKey(), entry.getValue());
return result;
}
/**
* Returns a description of all the bindings this profile holds.
*/
public String info() {
// 1. Shortcut class list
ArrayList<Class<? extends Shortcut>> list = new ArrayList<Class<? extends Shortcut>>();
for (Shortcut s : map.keySet())
if (!list.contains(s.getClass()))
list.add(s.getClass());
// 2. Print info per Shortcut class
String result = new String();
for (Class<? extends Shortcut> clazz : list) {
String info = info(clazz);
if (!info.isEmpty())
result += info;
}
return result;
}
/**
* Returns true if this object contains a binding for the specified shortcut.
*
* @param shortcut {@link Shortcut}
* @return true if this object contains a binding for the specified shortcut.
*/
public boolean hasBinding(Shortcut shortcut) {
return map.containsKey(shortcut);
}
/**
* Returns true if this object maps one or more shortcuts to the action specified by the
* {@link #grabber()}.
*
* @param action {@link java.lang.String}
* @return true if this object maps one or more shortcuts to the specified action.
*/
public boolean isActionBound(String action) {
for (ObjectMethodTuple tuple : map.values()) {
if (grabber == tuple.object && tuple.method.getName().equals(action))
return true;
}
return false;
}
/**
* Returns true if this object maps one or more shortcuts to method specified by the
* {@link #grabber()}.
*
* @param method {@link java.lang.reflect.Method}
* @return true if this object maps one or more shortcuts to the specified action.
*/
protected boolean isMethodBound(Method method) {
return isMethodBound(grabber, method);
}
/**
* Returns true if this object maps one or more shortcuts to the {@code method}
* specified by the {@code object}.
*
* @param object {@link java.lang.Object}
* @param method {@link java.lang.reflect.Method}
* @return true if this object maps one or more shortcuts to the specified action.
*/
protected boolean isMethodBound(Object object, Method method) {
return map.containsValue(new ObjectMethodTuple(object, method));
}
} | gpl-3.0 |
debard/georchestra-ird | mapfishapp/src/test/java/org/georchestra/mapfishapp/ws/upload/UpLoadFileManagementGTImplTest.java | 10435 | /**
*
*/
package org.georchestra.mapfishapp.ws.upload;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.junit.Assume.assumeNoException;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URL;
import org.apache.commons.io.FilenameUtils;
import org.geotools.feature.FeatureIterator;
import org.geotools.geojson.feature.FeatureJSON;
import org.geotools.referencing.CRS;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assume;
import org.junit.Ignore;
import org.junit.Test;
import org.opengis.feature.simple.SimpleFeature;
import com.vividsolutions.jts.geom.Point;
/**
* Unit Test for {@link UpLoadFileManagement}
*
* Test the geotools implementation {@link GeotoolsFeatureReader}.
*
* @author Mauricio Pazos
*
*/
public class UpLoadFileManagementGTImplTest {
public UpLoadFileManagementGTImplTest() {
System.setProperty("org.geotools.referencing.forceXY", "true");
}
/**
* Test method for
* {@link mapfishapp.ws.upload.UpLoadFileManagement#getFeatureCollectionAsJSON()}
* .
*
* @throws IOException
*/
@Test
public void testSHPAsJSON() throws Exception {
String fileName = "points-4326.shp";
String fullName = makeFullName(fileName);
testGetGeofileToJSON(fullName, null);
}
@Test
public void testSHPAsJSONReporjectedTo2154() throws Exception {
String fileName = "points-4326.shp";
String fullName = makeFullName(fileName);
testGetGeofileToJSON(fullName, "EPSG:2154");
}
/**
* Tests the coordinates order.
*
* @throws Exception
*/
@Test
public void testSHPCoordinatesEPSG4326() throws Exception {
String fileName = "shp_4326_accidents.shp";
String fullName = makeFullName(fileName);
String json = testGetGeofileToJSON(fullName, "EPSG:4326");
assertCoordinateContains(-2.265330624649336, 48.421434814828025, json);
}
/**
* Tests the coordinates order.
* <p>
* The retrieved features aren't reprojected. They will be in the base srs.
* </p>
*
* @throws Exception
*/
@Test
public void testSHPCoordinatesNoReprojected() throws Exception {
String fileName = "shp_4326_accidents.shp";
String fullName = makeFullName(fileName);
String json = testGetGeofileToJSON(fullName, null);
assertCoordinateContains(-2.265330624649336, 48.421434814828025, json);
}
@Test
public void testKML22AsJSON() throws Exception {
String fileName = "regions.kml";
String fullName = makeFullName(fileName);
String regions = testGetGeofileToJSON(fullName, null);
JSONObject list = new JSONObject(regions);
JSONArray jsonArray = list.getJSONArray("features");
JSONObject reg = jsonArray.getJSONObject(0);
String id = reg.getString("id");
}
@Test
public void testKML22ExtendedData() throws Exception {
String fileName = "kml_4326_accidents.kml";
String fullName = makeFullName(fileName);
String regions = testGetGeofileToJSON(fullName, null);
JSONObject list = new JSONObject(regions);
JSONArray jsonArray = list.getJSONArray("features");
JSONObject reg = jsonArray.getJSONObject(0);
JSONObject properties = reg.getJSONObject("properties");
assertNotNull(getJsonFieldValue(properties, "id"));
assertNotNull(getJsonFieldValue(properties, "date"));
assertNotNull(getJsonFieldValue(properties, "plage_hora"));
assertNotNull(getJsonFieldValue(properties, "jour_nuit"));
assertNotNull(getJsonFieldValue(properties, "meteo"));
assertNotNull(getJsonFieldValue(properties, "voie_type"));
assertNotNull(getJsonFieldValue(properties, "milieu"));
assertNotNull(getJsonFieldValue(properties, "voie_type"));
assertNotNull(getJsonFieldValue(properties, "tues_nb"));
assertNotNull(getJsonFieldValue(properties, "milieu"));
assertNotNull(getJsonFieldValue(properties, "tues_18_24"));
assertNotNull(getJsonFieldValue(properties, "tues_moto_"));
assertNotNull(getJsonFieldValue(properties, "tues_pieto"));
assertNotNull(getJsonFieldValue(properties, "tues_velo_"));
assertNotNull(getJsonFieldValue(properties, "vehicules_"));
assertNotNull(getJsonFieldValue(properties, "pl_impliqu"));
assertNotNull(getJsonFieldValue(properties, "commune"));
assertNotNull(getJsonFieldValue(properties, "departemen"));
assertNotNull(getJsonFieldValue(properties, "commentair"));
assertNotNull(getJsonFieldValue(properties, "consolide"));
assertNotNull(getJsonFieldValue(properties, "anciennete"));
assertNotNull(getJsonFieldValue(properties, "f_mois"));
assertNotNull(getJsonFieldValue(properties, "f_annee"));
}
private String getJsonFieldValue(JSONObject properties, String field) {
String value;
try {
value = properties.getString(field);
} catch (JSONException e) {
value = null;
}
return value;
}
/**
* Tests the coordinates order.
*
* @throws Exception
*/
@Test
public void testKMLCoordinatesEPSG4326() throws Exception {
String fileName = "kml_4326_accidents.kml";
String fullName = makeFullName(fileName);
String json = testGetGeofileToJSON(fullName, "EPSG:4326");
assertCoordinateContains(-2.265330624649336, 48.421434814828025, json);
}
/**
* Read features no reprojected
*
* @throws Exception
*/
@Test
public void testGMLAsJSON() throws Exception {
String fileName = "border.gml";
String fullName = makeFullName(fileName);
testGetGeofileToJSON(fullName, null);
}
@Test
public void testMIFAsJSON() throws Exception {
String fileName = "pigma_regions_POLYGON.mif";
String fullName = makeFullName(fileName);
testGetGeofileToJSON(fullName, null);
}
/**
* Tests the coordinates order.
*
* @throws Exception
*/
@Test
public void testMIFCoordinatesEPSG4326() throws Exception {
String fileName = "mif_4326_accidents.mif";
String fullName = makeFullName(fileName);
String json = testGetGeofileToJSON(fullName, "EPSG:4326");
assertCoordinateContains(-2.265330624649336, 48.421434814828025, json);
}
@Test
public void testMIFAsJSONReprojectedTo2154() throws Exception {
String fileName = "pigma_regions_POLYGON.mif";
String fullName = makeFullName(fileName);
testGetGeofileToJSON(fullName, "EPSG:2154");
}
/**
* Tests the coordinates order.
*
* @throws Exception
*/
@Test
public void testGMLCoordinatesEPSG4326() throws Exception {
String fileName = "gml_4326_accidents.gml";
String fullName = makeFullName(fileName);
String json = testGetGeofileToJSON(fullName, "EPSG:4326");
assertCoordinateContains(-2.265330624649336, 48.421434814828025, json);
}
/**
* Tests the coordinates order. The input layer is projected in epsg:4326,
* the result is reprojected to epsg:3857.
*
* @throws Exception
*/
@Test
public void testGMLCoordinatesFrom4326to3857() throws Exception {
String fileName = "gml_4326_accidents.gml";
String fullName = makeFullName(fileName);
String json = testGetGeofileToJSON(fullName, "EPSG:3857");
assertCoordinateContains(-252175.451614371791948,
6177255.152005254290998, json);
}
/**
* Assert that the feature in json syntax contains its coordinate in the
* order x, y.
*
* @param x
* @param y
* @param json
* @throws Exception
*/
protected void assertCoordinateContains(final double x, final double y,
final String json) throws Exception {
FeatureJSON featureJSON = new FeatureJSON();
FeatureIterator<SimpleFeature> iter = featureJSON
.streamFeatureCollection(json);
assertTrue(iter.hasNext()); // the test data only contains one feature
SimpleFeature f = iter.next();
Point geom = (Point) f.getDefaultGeometry();
assertEquals(x, geom.getCoordinate().x, 10e-8);
assertEquals(y, geom.getCoordinate().y, 10e-8);
}
protected String testGetGeofileToJSON(final String fileName, final String epsg) throws Exception {
assertTrue(fileName.length() > 0);
String jsonFeatures = getFeatureCollectionAsJSON(fileName, epsg);
assertNotNull(jsonFeatures);
return jsonFeatures;
}
/**
* Sets the bridge {@link AbstractFeatureGeoFileReader} with the
* {@link GeotoolsFeatureReader} implementation, then retrieves the file as
* Json collection. The return value will be null if the file is empty.
*
* @param fileName
* @param epsg
* @return
* @throws Exception
*/
protected String getFeatureCollectionAsJSON(final String fileName,
final String epsg) throws Exception {
FileDescriptor fd = new FileDescriptor(fileName);
fd.listOfFiles.add(fileName);
fd.listOfExtensions.add(FilenameUtils.getExtension(fileName));
UpLoadFileManagement fm = create();
fm.setWorkDirectory(FilenameUtils.getFullPath(fileName));
fm.setFileDescriptor(fd);
StringWriter out = new StringWriter();
if (epsg != null) {
fm.writeFeatureCollectionAsJSON(out, CRS.decode(epsg));
} else {
fm.writeFeatureCollectionAsJSON(out, null);
}
return out.toString();
}
/**
* @return UpLoadFileManagement set with geotools implementation
*/
protected UpLoadFileManagement create() throws IOException {
return UpLoadFileManagement
.create(UpLoadFileManagement.Implementation.geotools);
}
/**
* Returns path+fileName
*
* @param fileName
* @return
* @throws Exception
*/
protected String makeFullName(String fileName) throws Exception {
URL url = this.getClass().getResource(fileName);
String fullFileName = url.toURI().getPath();
return fullFileName;
}
}
| gpl-3.0 |
kidaa/RealmSpeak | magic_realm/utility/components/source/com/robin/magic_realm/components/effect/SeeChangeWeatherEffect.java | 1118 | package com.robin.magic_realm.components.effect;
import com.robin.general.swing.FrameManager;
import com.robin.magic_realm.components.WeatherChit;
import com.robin.magic_realm.components.wrapper.CharacterWrapper;
public class SeeChangeWeatherEffect implements ISpellEffect {
@Override
public void apply(SpellEffectContext context) {
String type = context.Spell.getExtraIdentifier();
if (type.toLowerCase().startsWith("change")) {
context.Game.updateWeatherChit();
FrameManager.showDefaultManagedFrame(context.Parent,"The weather chit has been changed.","Change Weather",null,true);
}
else {
// See the weather chit
int wc = context.Game.getWeatherChit();
WeatherChit chit = new WeatherChit(wc);
FrameManager.showDefaultManagedFrame(context.Parent,"The weather chit is a "+wc,"See Weather",chit.getIcon(),true);
CharacterWrapper character = new CharacterWrapper(context.Caster);
character.addNote(context.Caster,"See Weather","The weather chit is a "+wc);
}
}
@Override
public void unapply(SpellEffectContext context) {
// TODO Auto-generated method stub
}
}
| gpl-3.0 |
buehner/momo3-backend | src/main/java/de/terrestris/momo/security/access/entity/FilePermissionEvaluator.java | 1269 | /**
*
*/
package de.terrestris.momo.security.access.entity;
import de.terrestris.momo.util.security.MomoSecurityUtil;
import de.terrestris.shogun2.model.File;
import de.terrestris.shogun2.model.User;
import de.terrestris.shogun2.model.security.Permission;
/**
* @author Johannes Weskamm
* @param <E>
*
*/
public class FilePermissionEvaluator<E extends File> extends MomoPersistentObjectPermissionEvaluator<E> {
/**
* Default constructor
*/
@SuppressWarnings("unchecked")
public FilePermissionEvaluator() {
this((Class<E>) File.class);
}
/**
* Constructor for subclasses
*
* @param entityClass
*/
protected FilePermissionEvaluator(Class<E> entityClass) {
super(entityClass);
}
/**
*
*/
@Override
public boolean hasPermission(User user, E file, Permission permission) {
// all users with at least role_user are allowed to create files here
if (permission.equals(Permission.CREATE) && (file == null || file.getId() == null) &&
MomoSecurityUtil.currentUsersHighestRoleIsEditor() ||
MomoSecurityUtil.currentUserHasRoleSubAdmin() ||
MomoSecurityUtil.currentUserIsSuperAdmin()) {
return true;
}
/**
* by default look for granted rights
*/
return hasDefaultMomoPermission(user, file, permission);
}
}
| gpl-3.0 |
srnsw/xena | xena/ext/src/javahelp/jhMaster/JavaHelp/src/new/javax/help/resources/Constants_sk.java | 5597 | /*
* @(#)Constants_sk.java 1.10 06/10/30
*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.help.resources;
import java.util.ListResourceBundle;
/**
* Constants used for localizing JavaHelp.
*
* These are in the form of key, value.
* Translators take care to only translate the values.
*
* @author Richard Gregor
* @version 1.10 10/30/06
*
*/
public class Constants_sk extends ListResourceBundle {
/**
* Overrides ListResourceBundle.
*/
public Object[][] getContents() {
return new Object[][] {
// Constant strings and patterns
{ "helpset.wrongPublicID",
"Nezn\u00e1me PublicID {0}"},
{ "helpset.wrongTitle",
"Pokus o nastavenie Title na {0} Title u\u017E m\u00e1 hodnotu {1}."},
{ "helpset.wrongHomeID",
"Pokus o nastavenie homeID na {0} homeID u\u017E m\u00e1 hodnotu {1}."},
{ "helpset.subHelpSetTrouble",
"Probl\u00e9m pri vytv\u00e1ran\u00ed subhelpsetu: {0}."},
{ "helpset.malformedURL",
"Chybn\u00fd form\u00e1t URL: {0}."},
{ "helpset.incorrectURL",
"Nespr\u00e1vne URL: {0}."},
{ "helpset.wrongText",
"{0} nem\u00f4\u017Ee obsahova\u0165 text {1}."},
{ "helpset.wrongTopLevel",
"{0} Nespr\u00e1vny top level tag."},
{ "helpset.wrongParent",
"Rodi\u010Dovsk\u00fd tag {0} nem\u00f4\u017Ee by\u0165 {1}."},
{ "helpset.unbalanced",
"Neukon\u010Den\u00fd tag {0}."},
{ "helpset.wrongLocale",
"Pozor!: xml:lang atrib\u00fat {0} je v konflikte s {1} a s {2}"},
{ "helpset.unknownVersion",
"Nezn\u00e1ma verzia {0}."},
// IndexView messages
{ "index.invalidIndexFormat",
"Pozor!: Index m\u00e1 chybn\u00fd form\u00e1t"},
{ "index.unknownVersion",
"Nezn\u00e1ma verzia {0}."},
// TOCView messages
{ "toc.wrongPublicID",
"Nezn\u00e1me PublicID {0}"},
{ "toc.invalidTOCFormat",
"Pozor!: TOC m\u00e1 chybn\u00fd form\u00e1t"},
{ "toc.unknownVersion",
"Nezn\u00e1ma verzia {0}."},
//FavoritesView messages
{ "favorites.invalidFavoritesFormat",
"Pozor!: Nespr\u00e1vny form\u00e1t s\u00faboru Favorites.xml"},
{ "favorites.unknownVersion",
"Nespr\u00e1vna verzia {0}."},
// Map messages
{ "map.wrongPublicID",
"Nezn\u00e1me PublicID {0}"},
{ "map.invalidMapFormat",
"Pozor!: Map m\u00e1 nespr\u00e1vny form\u00e1t"},
{ "map.unknownVersion",
"Nezn\u00e1ma verzia {0}."},
// GUI components
// Labels
{ "index.findLabel", "Vyh\u013Eada\u0165 : "},
{ "search.findLabel", "Vyh\u013Eada\u0165 : "},
{ "search.hitDesc", "Po\u010Det v\u00fdskytov v dokumente"},
{ "search.qualityDesc", "Miera nepresnosti" },
{ "search.high", "Najvy\u0161\u0161ia"},
{ "search.midhigh", "Vysok\u00e1"},
{ "search.mid", "Stredn\u00e1"},
{ "search.midlow", "N\u00edzka"},
{ "search.low", "Najni\u0161\u0161ia"},
{ "favorites.add", "Pridaj"},
{ "favorites.remove", "Zma\u017e"},
{ "favorites.folder", "Zlo\u017eka"},
{ "favorites.name", "N\u00e1zov"},
{ "favorites.cut", "Vystrihni"},
{ "favorites.paste", "Vlo\u017e"},
{ "favorites.copy" ,"Kop\u00edruj" },
{ "history.homePage", "Domovsk\u00e1 str\u00e1nka"},
{ "history.unknownTitle", "<nezn\u00e1my titul str\u00e1nky>"},
// ToolTips for Actions
{ "tooltip.BackAction", "Predch\u00e1dzaj\u00face"},
{ "tooltip.ForwardAction", "\u010Eal\u0161ie"},
{ "tooltip.PrintAction", "Tla\u010D"},
{ "tooltip.PrintSetupAction", "Nastavenie str\u00e1nky"},
{ "tooltip.ReloadAction", "Obnovi\u0165"},
{ "tooltip.FavoritesAction", "Pridaj k ob\u013E\u00faben\u00fdm polo\u017Ek\u00e1m"},
{ "tooltip.HomeAction", "Zobraz domovsk\u00fa str\u00e1nku"},
// Accessibility names
{ "access.BackAction", "Spiatky"},
{ "access.ForwardAction", "Vpred"},
{ "access.HistoryAction", "Hist\u00f3ria"},
{ "access.PrintAction", "Tla\u010D"},
{ "access.PrintSetupAction", "Nastavenie Tla\u010De"},
{ "access.ReloadAction", "Obnovenie"},
{ "access.HomeAction", "Domovsk\u00e1 Str\u00e1nka"},
{ "access.FavoritesAction", "Pridaj k ob\u013E\u00faben\u00fdm polo\u017ek\u00e1m"},
{ "access.contentViewer", "Prehliada\u010D obsahu"}
};
}
}
| gpl-3.0 |
Greznor/chanu | app/src/main/java/com/chanapps/four/data/ChanThread.java | 14826 | package com.chanapps.four.data;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.DateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import android.content.Context;
import android.database.MatrixCursor;
import android.util.Log;
import com.chanapps.four.activity.R;
import com.chanapps.four.component.URLFormatComponent;
import com.chanapps.four.service.NetworkProfileManager;
public class ChanThread extends ChanPost {
private static final String TAG = ChanThread.class.getSimpleName();
private static final boolean DEBUG = false;
public static final double MAX_THUMBNAIL_PX = 250;
@JsonDeserialize(using=JacksonNonBlockingObjectMapperFactory.NonBlockingLongDeserializer.class)
public long lastFetched = 0;
@JsonDeserialize(using=JacksonNonBlockingObjectMapperFactory.NonBlockingBooleanDeserializer.class)
public boolean loadedFromBoard = false;
public ChanPost posts[] = new ChanPost[0];
@JsonProperty("last_replies")
public ChanPost[] lastReplies = new ChanPost[0];
@JsonDeserialize(using=JacksonNonBlockingObjectMapperFactory.NonBlockingIntegerDeserializer.class)
public int viewPosition = -1;
public int viewOffset = 0;
public static final String THREAD_COMPOSITE_ID = "_id";
public static final String THREAD_BOARD_CODE = "threadBoardCode";
public static final String THREAD_NO = "threadNo";
public static final String THREAD_SUBJECT = "threadSub";
public static final String THREAD_HEADLINE = "threadHeadline";
public static final String THREAD_TEXT = "threadText";
public static final String THREAD_THUMBNAIL_URL = "threadThumb";
public static final String THREAD_COUNTRY_FLAG_URL = "threadFlag";
public static final String THREAD_CLICK_URL = "threadClick";
public static final String THREAD_NUM_REPLIES = "threadNumReplies";
public static final String THREAD_NUM_IMAGES = "threadNumImages";
public static final String THREAD_TN_W = "threadThumbWidth";
public static final String THREAD_TN_H = "threadThumbHeight";
public static final String THREAD_JUMP_TO_POST_NO = "threadJumpToPostNo";
public static final String THREAD_FLAGS = "threadFlags";
public static final String THREAD_NUM_LAST_REPLIES = "numLastReplies";
public static final String THREAD_LAST_REPLIES_BLOB = "lastRepliesBlob";
public static final int THREAD_FLAG_DEAD = 0x001;
public static final int THREAD_FLAG_CLOSED = 0x002;
public static final int THREAD_FLAG_STICKY = 0x004;
public static final int THREAD_FLAG_BOARD = 0x010;
public static final int THREAD_FLAG_BOARD_TYPE = 0x010;
public static final int THREAD_FLAG_POPULAR_THREAD = 0x080;
public static final int THREAD_FLAG_LATEST_POST = 0x100;
public static final int THREAD_FLAG_RECENT_IMAGE = 0x200;
public static final int THREAD_FLAG_HEADER = 0x400;
private static final String[] THREAD_COLUMNS = {
THREAD_COMPOSITE_ID,
THREAD_BOARD_CODE,
THREAD_NO,
THREAD_SUBJECT,
THREAD_HEADLINE,
THREAD_TEXT,
THREAD_THUMBNAIL_URL,
THREAD_COUNTRY_FLAG_URL,
THREAD_CLICK_URL,
THREAD_NUM_REPLIES,
THREAD_NUM_IMAGES,
THREAD_TN_W,
THREAD_TN_H,
THREAD_JUMP_TO_POST_NO,
THREAD_NUM_LAST_REPLIES,
THREAD_LAST_REPLIES_BLOB,
THREAD_FLAGS
};
public static MatrixCursor buildMatrixCursor(int capacity) {
return new MatrixCursor(THREAD_COLUMNS, capacity);
}
private static int threadFlags(ChanPost post) {
int flags = 0;
if (post.isDead)
flags |= THREAD_FLAG_DEAD;
if (post.closed > 0)
flags |= THREAD_FLAG_CLOSED;
if (post.sticky > 0)
flags |= THREAD_FLAG_STICKY;
return flags;
}
public static Object[] makeRow(Context context, ChanThread thread, String query, int extraFlags,
boolean showNumReplies, boolean abbrev) {
String id = thread.board + "/" + thread.no;
String[] textComponents = thread.textComponents(query);
byte[] lastRepliesBlob = blobifyLastReplies(thread.lastReplies);
if (DEBUG) Log.i(TAG, "makeRow /" + thread.board + "/" + thread.no + " lastRepliesBlob=" + lastRepliesBlob);
return new Object[] {
id.hashCode(),
thread.board,
thread.no,
textComponents[0],
thread.headline(context, query, true, null, showNumReplies, abbrev),
textComponents[1],
thread.thumbnailUrl(context),
thread.countryFlagUrl(context),
"",
thread.replies,
thread.images,
thread.tn_w > 0 ? thread.tn_w : MAX_THUMBNAIL_PX,
thread.tn_h > 0 ? thread.tn_h : MAX_THUMBNAIL_PX,
thread.jumpToPostNo,
thread.lastReplies == null ? 0 : thread.lastReplies.length,
lastRepliesBlob,
threadFlags(thread) | extraFlags
};
}
public static Object[] makeBoardRow(Context context, String boardCode, String boardName, int boardImageResourceId, int extraFlags) {
return new Object[] {
boardCode.hashCode(),
boardCode,
0,
boardName,
ChanBoard.getDescription(context, boardCode),
"",
boardImageResourceId > 0 ? "drawable://" + boardImageResourceId : "",
"",
"",
0,
0,
MAX_THUMBNAIL_PX,
MAX_THUMBNAIL_PX,
0,
0,
null,
THREAD_FLAG_BOARD | extraFlags
};
}
public static Object[] makeHeaderRow(Context context, ChanBoard board) {
String boardCode = board.link;
String boardName = "/" + boardCode + "/ " + board.getName(context);
//String safeText = context.getString(board.isWorksafe(context, boardCode) ? R.string.board_type_worksafe : R.string.board_type_adult);
String dateText = String.format(context.getString(R.string.board_last_updated),
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(new Date(board.lastFetched)));
//String description = board.getDescription(context) + "<br/>"
// + safeText + "<br/>"
// + dateText;
String description = dateText;
return new Object[] {
boardCode.hashCode(),
boardCode,
0,
boardName,
description,
"",
"",
"",
"",
0,
0,
MAX_THUMBNAIL_PX,
MAX_THUMBNAIL_PX,
0,
0,
null,
THREAD_FLAG_BOARD | THREAD_FLAG_HEADER
};
}
public static boolean threadNeedsRefresh(Context context, String boardCode, long threadNo, boolean forceRefresh) {
ChanThread thread = ChanFileStorage.loadThreadData(context, boardCode, threadNo);
if (thread == null)
return true;
if (forceRefresh)
return true;
return thread.threadNeedsRefresh();
}
public boolean threadNeedsRefresh() {
if (isDead)
return false;
else if (defData)
return true;
else if (posts == null || posts.length == 0)
return true;
else if (posts[0] == null || posts[0].defData)
return true;
else if (posts.length < replies)
return true;
else if (!isCurrent())
return true;
else
return false;
}
public String toString() {
return "Thread " + no + ", defData:" + defData + " dead:" + isDead + ", images: " + images
+ " com: " + com + ", sub:" + sub + ", replies: " + replies + ", posts.length: " + posts.length
+ (posts.length > 0
? ", posts[0].no: " + posts[0].no + ", posts[0].replies: " + posts[0].replies
+ ", posts[0].images: " + posts[0].images + ", posts[0].defData: " + posts[0].defData
+ ", posts[0].isDead: " + posts[0].isDead
: "")
+ ", tn_w: " + tn_w + " tn_h: " + tn_h;
}
public void mergePosts(List<ChanPost> newPosts) {
Map<Long,ChanPost> postMap = new HashMap<Long,ChanPost>(this.posts.length);
for (ChanPost post : this.posts)
postMap.put(post.no, post);
for (ChanPost newPost: newPosts)
postMap.put(newPost.no, newPost); // overwrite any existing posts
ChanPost[] postArray = postMap.values().toArray(new ChanPost[0]);
Arrays.sort(postArray, new Comparator<ChanPost>() {
@Override
public int compare(ChanPost lhs, ChanPost rhs) {
if (lhs.no == rhs.no)
return 0;
else if (lhs.no < rhs.no)
return -1;
else
return 1;
}
});
this.posts = postArray; // swap
}
public Map<Long, HashSet<Long>> backlinksMap() {
Map<Long, HashSet<Long>> backlinksMap = new HashMap<Long, HashSet<Long>>();
for (ChanPost post : posts) {
HashSet<Long> backlinks = post.backlinks();
if (backlinks != null && !backlinks.isEmpty())
backlinksMap.put(post.no, backlinks);
}
return backlinksMap;
}
public Map<Long, HashSet<Long>> repliesMap(Map<Long, HashSet<Long>> backlinksMap) {
Map<Long, HashSet<Long>> repliesMap = new HashMap<Long, HashSet<Long>>();
for (Long laterPostNo : backlinksMap.keySet()) {
for (Long originalPostNo : backlinksMap.get(laterPostNo)) {
HashSet<Long> replies = repliesMap.get(originalPostNo);
if (replies == null) {
replies = new HashSet<Long>();
repliesMap.put(originalPostNo, replies);
}
replies.add(laterPostNo);
}
}
return repliesMap;
}
public Map<String, HashSet<Long>> sameIdsMap() {
Map<String, HashSet<Long>> sameIdsMap = new HashMap<String, HashSet<Long>>();
for (ChanPost post : posts) {
if (post.id == null || post.id.isEmpty() || post.id.equals(ChanPost.SAGE_POST_ID))
continue;
HashSet<Long> sameIds = sameIdsMap.get(post.id);
if (sameIds == null) {
sameIds = new HashSet<Long>();
sameIdsMap.put(post.id, sameIds);
}
sameIds.add(post.no);
}
return sameIdsMap;
}
public ChanThread cloneForWatchlist() {
ChanThread t = new ChanThread();
t.no = no;
t.board = board;
t.closed = closed;
t.created = created;
t.omitted_images = omitted_images;
t.omitted_posts = omitted_posts;
t.resto = resto;
t.jumpToPostNo = jumpToPostNo;
t.defData = false;
if (posts.length > 0 && posts[0] != null) {
t.replies = posts[0].replies;
t.images = posts[0].images;
t.bumplimit = posts[0].bumplimit;
t.capcode = posts[0].capcode;
t.com = posts[0].com;
t.country = posts[0].country;
t.country_name = posts[0].country_name;
t.email = posts[0].email;
t.ext = posts[0].ext;
t.filedeleted = posts[0].filedeleted;
t.filename = posts[0].filename;
t.fsize = posts[0].fsize;
t.h = posts[0].h;
t.hideAllText = posts[0].hideAllText;
t.hidePostNumbers = posts[0].hidePostNumbers;
t.id = posts[0].id;
t.now = posts[0].now;
t.spoiler = posts[0].spoiler;
t.sticky = posts[0].sticky;
t.sub = posts[0].sub;
t.tim = posts[0].tim;
t.tn_h = posts[0].tn_h;
t.tn_w = posts[0].tn_w;
t.trip = posts[0].trip;
t.useFriendlyIds = posts[0].useFriendlyIds;
t.w = posts[0].w;
t.jumpToPostNo = posts[0].jumpToPostNo;
}
return t;
}
public static String threadUrl(Context context, String boardCode, long threadNo) {
return String.format(URLFormatComponent.getUrl(context, URLFormatComponent.CHAN_WEB_THREAD_URL_FORMAT), boardCode, threadNo);
}
public boolean isCurrent() {
FetchParams params = NetworkProfileManager.instance().getCurrentProfile().getFetchParams();
if (defData)
return false;
else if (lastFetched <= 0)
return false;
else if (Math.abs(new Date().getTime() - lastFetched) > params.refreshDelay)
return false;
else
return true;
}
public static byte[] blobifyLastReplies(ChanPost[] list) {
if (list == null || list.length == 0)
return null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(list);
return baos.toByteArray();
}
catch (IOException e) {
Log.e(TAG, "Couldn't serialize list=" + list, e);
}
return null;
}
public static ChanPost[] parseLastRepliesBlob(final byte[] b) {
if (b == null || b.length == 0)
return null;
try {
InputStream bais = new BufferedInputStream(new ByteArrayInputStream(b));
ObjectInputStream ois = new ObjectInputStream(bais);
ChanPost[] list = (ChanPost[])ois.readObject();
return list;
}
catch (Exception e) {
Log.e(TAG, "Couldn't deserialize blob=" + b);
}
return null;
}
public boolean matchesQuery(String query) {
if (query == null || query.isEmpty())
return true;
if (super.matchesQuery(query))
return true;
if (lastReplies != null) {
for (ChanPost p : lastReplies) {
if (p.matchesQuery(query))
return true;
}
}
return false;
}
} | gpl-3.0 |
CitySDK/tourism_library_java | src/main/java/citysdk/tourism/client/exceptions/UnknownErrorException.java | 1406 | /**
* COPYRIGHT NOTICE:
*
* This file is part of CitySDK WP5 Tourism Java Library.
*
* CitySDK WP5 Tourism Java Library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CitySDK WP5 Tourism Java Library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with CitySDK WP5 Tourism Java Library. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2013, IST
*/
package citysdk.tourism.client.exceptions;
/**
* Exception thrown when a given JSON has formatting errors or any given unforeseen error.
*
* @author Pedro Cruz
*/
public class UnknownErrorException extends Exception {
private static final long serialVersionUID = 378349367349853216L;
public UnknownErrorException() {
super();
}
public UnknownErrorException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
public UnknownErrorException(String arg0) {
super(arg0);
}
public UnknownErrorException(Throwable arg0) {
super(arg0);
}
}
| gpl-3.0 |
kidaa/RealmSpeak | magic_realm/applications/RealmCharacterBuilder/source/com/robin/magic_realm/RealmCharacterBuilder/EditPanel/ItemRestrictionsEditPanel.java | 4143 | /*
* RealmSpeak is the Java application for playing the board game Magic Realm.
* Copyright (c) 2005-2015 Robin Warren
* E-mail: robin@dewkid.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
*
* http://www.gnu.org/licenses/
*/
package com.robin.magic_realm.RealmCharacterBuilder.EditPanel;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import com.robin.general.util.StringBufferedList;
import com.robin.magic_realm.components.utility.Constants;
import com.robin.magic_realm.components.wrapper.CharacterWrapper;
public class ItemRestrictionsEditPanel extends AdvantageEditPanel {
/*
* Embodies item restrictions (items that cannot be activated)
*/
private static final String[][][] ITEM_LIST = {
{
{"Melee Weapons","Spear","Mace","Axe","Great Axe","Morning Star","Staff"},
{"Ranged Weapons","Crossbow","Light Bow","Medium Bow"},
{"Expansion","Halberd","Sword of Legend"},
},
{
{"Swords","Short Sword","Thrusting Sword","Broadsword","Great Sword"},
{"Magic Swords","Bane Sword","Truesteel Sword","Devil Sword","Living Sword"},
},
{
{"Armor","Helmet","Breastplate","Shield","Armor"},
{"Horses","Pony","Horse","Warhorse"},
{"Treasure","Boots","Gloves","Books"}, // These will require special handling
},
};
private Hashtable<String,JCheckBox> hash;
public ItemRestrictionsEditPanel(CharacterWrapper pChar, String levelKey) {
super(pChar, levelKey);
hash = new Hashtable<String,JCheckBox>();
setLayout(new BorderLayout());
JPanel main = new JPanel(new GridLayout(1,ITEM_LIST.length));
for (int i=0;i<ITEM_LIST.length;i++) {
Box box = Box.createVerticalBox();
for (int n=0;n<ITEM_LIST[i].length;n++) {
addOptionList(box,ITEM_LIST[i][n]);
}
box.add(Box.createVerticalGlue());
main.add(box);
}
add(main,"Center");
JLabel description = new JLabel("Items that cannot be activated:",JLabel.LEFT);
description.setFont(new Font("Dialog",Font.BOLD,16));
add(description,"North");
ArrayList list = getAttributeList(Constants.ITEM_RESTRICTIONS);
if (list!=null) {
for (Iterator i=list.iterator();i.hasNext();) {
String val = (String)i.next();
JCheckBox option = hash.get(val);
if (option!=null) {
option.setSelected(true);
}
}
}
}
private void addOptionList(Box box,String[] list) {
JPanel panel = new JPanel(new GridLayout(list.length-1,1));
panel.setBorder(BorderFactory.createTitledBorder(list[0]));
for (int i=1;i<list.length;i++) {
JCheckBox option = new JCheckBox(list[i],false);
panel.add(option);
hash.put(list[i],option);
}
box.add(panel);
}
protected void applyAdvantage() {
ArrayList list = new ArrayList();
for (Iterator i=hash.keySet().iterator();i.hasNext();) {
String val = (String)i.next();
JCheckBox option = hash.get(val);
if (option.isSelected()) {
list.add(val);
}
}
setAttributeList(Constants.ITEM_RESTRICTIONS,list);
}
public String getSuggestedDescription() {
StringBuffer sb = new StringBuffer();
sb.append("Restricted from having an active ");
StringBufferedList list = new StringBufferedList(", ","or ");
for (Iterator i=hash.keySet().iterator();i.hasNext();) {
String val = (String)i.next();
JCheckBox option = hash.get(val);
if (option.isSelected()) {
list.append(option.getText());
}
}
sb.append(list.toString());
sb.append(" in inventory.");
return sb.toString();
}
public boolean isCurrent() {
return hasAttribute(Constants.ITEM_RESTRICTIONS);
}
public String toString() {
return "Item Restrictions";
}
} | gpl-3.0 |
HtmlUnit/htmlunit-rhino-fork | src/org/mozilla/javascript/IteratorLikeIterable.java | 4057 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.javascript;
import java.io.Closeable;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* This is a class that makes it easier to iterate over "iterator-like" objects as defined in the
* ECMAScript spec. The caller is responsible for retrieving an object that implements the
* "iterator" pattern. This class will follow that pattern and throw appropriate JavaScript
* exceptions.
*
* <p>The pattern that the target class should follow is: * It must have a function property called
* "next" * The function must return an object with a boolean value called "done". * If "done" is
* true, then the returned object should also contain a "value" property. * If it has a function
* property called "return" then it will be called when the caller is done iterating.
*/
public class IteratorLikeIterable implements Iterable<Object>, Closeable {
private final Context cx;
private final Scriptable scope;
private final Callable next;
private final Callable returnFunc;
private final Scriptable iterator;
private boolean closed;
public IteratorLikeIterable(Context cx, Scriptable scope, Object target) {
this.cx = cx;
this.scope = scope;
// This will throw if "next" is not a function or undefined
next = ScriptRuntime.getPropFunctionAndThis(target, ES6Iterator.NEXT_METHOD, cx, scope);
iterator = ScriptRuntime.lastStoredScriptable(cx);
Object retObj =
ScriptRuntime.getObjectPropNoWarn(target, ES6Iterator.RETURN_PROPERTY, cx, scope);
// We only care about "return" if it is not null or undefined
if ((retObj != null) && !Undefined.isUndefined(retObj)) {
if (!(retObj instanceof Callable)) {
throw ScriptRuntime.notFunctionError(target, retObj, ES6Iterator.RETURN_PROPERTY);
}
returnFunc = (Callable) retObj;
} else {
returnFunc = null;
}
}
@Override
public void close() {
if (!closed) {
closed = true;
if (returnFunc != null) {
returnFunc.call(cx, scope, iterator, ScriptRuntime.emptyArgs);
}
}
}
@Override
public Itr iterator() {
return new Itr();
}
public final class Itr implements Iterator<Object> {
private Object nextVal;
private boolean isDone;
@Override
public boolean hasNext() {
if (isDone) {
return false;
}
Object val = next.call(cx, scope, iterator, ScriptRuntime.emptyArgs);
// This will throw if "val" is not an object.
// "getObjectPropNoWarn" won't, so do this as follows.
Object doneval =
ScriptableObject.getProperty(
ScriptableObject.ensureScriptable(val), ES6Iterator.DONE_PROPERTY);
if (doneval == Scriptable.NOT_FOUND) {
doneval = Undefined.instance;
}
// It's OK if done is undefined.
if (ScriptRuntime.toBoolean(doneval)) {
isDone = true;
return false;
}
nextVal = ScriptRuntime.getObjectPropNoWarn(val, ES6Iterator.VALUE_PROPERTY, cx, scope);
return true;
}
@Override
public Object next() {
if (isDone) {
throw new NoSuchElementException();
}
return nextVal;
}
/** Find out if "hasNext" returned done without invoking the function again. */
public boolean isDone() {
return isDone;
}
/** Manually set "done." Used for exception handling in promises. */
public void setDone(boolean done) {
this.isDone = done;
}
}
}
| mpl-2.0 |
USAID-DELIVER-PROJECT/elmis | modules/openlmis-web/src/test/java/org/openlmis/web/logger/ApplicationLoggerTest.java | 2954 | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2013 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses. For additional information contact info@OpenLMIS.org.
*/
package org.openlmis.web.logger;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.WriterAppender;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.openlmis.LmisThreadLocal;
import org.openlmis.core.logging.ApplicationLogger;
import org.openlmis.db.categories.UnitTests;
import java.io.ByteArrayOutputStream;
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.containsString;
import static org.mockito.Mockito.when;
@Category(UnitTests.class)
public class ApplicationLoggerTest {
private Logger logger;
private ByteArrayOutputStream outputStream;
@Mock @SuppressWarnings("unused")
private JoinPoint joinPoint;
@Mock @SuppressWarnings("unused")
private Signature signature;
private ApplicationLogger applicationLogger;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
logger = Logger.getLogger(ApplicationLogger.class);
outputStream = new ByteArrayOutputStream();
logger.addAppender(new WriterAppender(new SimpleLayout(), outputStream));
applicationLogger = new ApplicationLogger();
LmisThreadLocal.set("TEST_USER");
}
@Test
public void shouldLogExceptions() {
Exception exception = new RuntimeException("An exception was thrown !!");
when(joinPoint.getSignature()).thenReturn(signature);
when(signature.getName()).thenReturn("Method Name");
when(signature.getDeclaringTypeName()).thenReturn("com.x.y.Class");
applicationLogger.logException(joinPoint, exception);
String lineSeparator = System.getProperty("line.separator");
assertThat(outputStream.toString(),
containsString("ERROR - TEST_USER | com.x.y.Class.Method Name() | Exception"+lineSeparator+"java.lang.RuntimeException: An exception was thrown !!"));
}
}
| agpl-3.0 |
ufosky-server/actor-platform | actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/api/rpc/ResponseLoadAdminSettings.java | 1650 | package im.actor.core.api.rpc;
/*
* Generated by the Actor API Scheme generator. DO NOT EDIT!
*/
import im.actor.runtime.bser.*;
import im.actor.runtime.collections.*;
import static im.actor.runtime.bser.Utils.*;
import im.actor.core.network.parser.*;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NotNull;
import com.google.j2objc.annotations.ObjectiveCName;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import im.actor.core.api.*;
public class ResponseLoadAdminSettings extends Response {
public static final int HEADER = 0xaea;
public static ResponseLoadAdminSettings fromBytes(byte[] data) throws IOException {
return Bser.parse(new ResponseLoadAdminSettings(), data);
}
private ApiAdminSettings settings;
public ResponseLoadAdminSettings(@NotNull ApiAdminSettings settings) {
this.settings = settings;
}
public ResponseLoadAdminSettings() {
}
@NotNull
public ApiAdminSettings getSettings() {
return this.settings;
}
@Override
public void parse(BserValues values) throws IOException {
this.settings = values.getObj(1, new ApiAdminSettings());
}
@Override
public void serialize(BserWriter writer) throws IOException {
if (this.settings == null) {
throw new IOException();
}
writer.writeObject(1, this.settings);
}
@Override
public String toString() {
String res = "tuple LoadAdminSettings{";
res += "}";
return res;
}
@Override
public int getHeaderKey() {
return HEADER;
}
}
| agpl-3.0 |
yoann-dufresne/Smiles2Monomers | src/algorithms/TwoColoration.java | 264 | package algorithms;
import org._3pq.jgrapht.graph.SimpleGraph;
public class TwoColoration {
public boolean isTwoColorable (SimpleGraph g) {
if (g.edgeSet().size() == 0)
return true;
System.err.println("TODO : Two Coloration");
return false;
}
}
| agpl-3.0 |
fqqb/yamcs | yamcs-core/src/main/java/org/yamcs/tctm/TcTmException.java | 409 | package org.yamcs.tctm;
/**
* Generic exception to throw for problems encountered during TC or TM processing
*
* @author nm
*
*/
public class TcTmException extends Exception {
public TcTmException() {
super();
}
public TcTmException(String message) {
super(message);
}
public TcTmException(String message, Throwable cause) {
super(message, cause);
}
}
| agpl-3.0 |
CecileBONIN/Silverpeas-Core | web-core/src/test/java/org/silverpeas/admin/web/ComponentGettingTest.java | 3705 | /*
* Copyright (C) 2000 - 2013 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.silverpeas.admin.web;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.silverpeas.admin.web.AdminResourceURIs.COMPONENTS_BASE_URI;
import static org.silverpeas.admin.web.AdminTestResources.JAVA_PACKAGE;
import static org.silverpeas.admin.web.AdminTestResources.SPRING_CONTEXT;
import static org.silverpeas.admin.web.AdminTestResources.getComponentBuilder;
import static org.silverpeas.admin.web.AdminTestResources.getSpaceBuilder;
import static org.silverpeas.admin.web.ComponentEntityMatcher.matches;
import org.junit.Before;
import org.junit.Test;
import org.silverpeas.admin.web.ComponentEntity;
import com.silverpeas.web.ResourceGettingTest;
import com.stratelia.webactiv.beans.admin.ComponentInstLight;
import com.stratelia.webactiv.beans.admin.UserDetail;
/**
* Tests on the comment getting by the CommentResource web service.
* @author Yohann Chastagnier
*/
public class ComponentGettingTest extends ResourceGettingTest<AdminTestResources> {
private UserDetail user;
private String sessionKey;
private ComponentInstLight expected;
public ComponentGettingTest() {
super(JAVA_PACKAGE, SPRING_CONTEXT);
}
@Before
public void prepareTestResources() {
user = aUser();
sessionKey = authenticate(user);
for (int i = 1; i <= 10; i++) {
if (i == 2 || i == 6 || i == 9) {
getTestResources().save(getSpaceBuilder(i).withParentId(3).build());
} else {
getTestResources().save(getSpaceBuilder(i).build());
}
}
expected = getComponentBuilder(5).withParentSpaceId(3).build();
getTestResources().save(expected);
getTestResources().save(getComponentBuilder(3).withParentSpaceId(3).build());
}
@Test
public void get() {
final ComponentEntity entity = getAt(aResourceURI(), ComponentEntity.class);
assertNotNull(entity);
assertThat(entity, matches(expected));
}
@Override
public String aResourceURI() {
return aResourceURI("5");
}
public String aResourceURI(final String id) {
return COMPONENTS_BASE_URI + "/" + id;
}
@Override
public String anUnexistingResourceURI() {
return aResourceURI("100");
}
@Override
public ComponentInstLight aResource() {
return expected;
}
@Override
public String getSessionKey() {
return sessionKey;
}
@Override
public Class<?> getWebEntityClass() {
return ComponentEntity.class;
}
@Override
public String[] getExistingComponentInstances() {
return new String[] { "componentName5" };
}
}
| agpl-3.0 |
xien777/yajsw | yajsw/hessian4/src/main/java/com/caucho/hessian4/io/HessianEnvelope.java | 3061 | /*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian4.io;
import java.io.*;
/**
* Factory class for wrapping and unwrapping hessian streams.
*/
abstract public class HessianEnvelope {
/**
* Wrap the Hessian output stream in an envelope.
*/
abstract public Hessian2Output wrap(Hessian2Output out)
throws IOException;
/**
* Unwrap the Hessian input stream with this envelope. It is an
* error if the actual envelope does not match the expected envelope
* class.
*/
abstract public Hessian2Input unwrap(Hessian2Input in)
throws IOException;
/**
* Unwrap the envelope after having read the envelope code ('E') and
* the envelope method. Called by the EnvelopeFactory for dynamic
* reading of the envelopes.
*/
abstract public Hessian2Input unwrapHeaders(Hessian2Input in)
throws IOException;
}
| lgpl-2.1 |
ruby-processing/toxiclibs | src/main/java/toxi/physics3d/VerletPhysics3D.java | 9983 | /*
* __ .__ .__ ._____.
* _/ |_ _______ __|__| ____ | | |__\_ |__ ______
* \ __\/ _ \ \/ / |/ ___\| | | || __ \ / ___/
* | | ( <_> > <| \ \___| |_| || \_\ \\___ \
* |__| \____/__/\_ \__|\___ >____/__||___ /____ >
* \/ \/ \/ \/
*
* Copyright (c) 2006-2011 Karsten Schmidt
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* http://creativecommons.org/licenses/LGPL/2.1/
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
package toxi.physics3d;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import toxi.geom.AABB;
import toxi.geom.Vec3D;
import toxi.physics3d.behaviors.GravityBehavior3D;
import toxi.physics3d.behaviors.ParticleBehavior3D;
import toxi.physics3d.constraints.ParticleConstraint3D;
/**
* 3D particle physics engine using Verlet integration based on:
* http://en.wikipedia.org/wiki/Verlet_integration
* http://www.teknikus.dk/tj/gdc2001.htm
*
*/
public class VerletPhysics3D {
public static void addConstraintToAll(ParticleConstraint3D c,
List<VerletParticle3D> list) {
for (VerletParticle3D p : list) {
p.addConstraint(c);
}
}
public static void removeConstraintFromAll(ParticleConstraint3D c,
List<VerletParticle3D> list) {
for (VerletParticle3D p : list) {
p.removeConstraint(c);
}
}
/**
* List of particles (Vec3D subclassed)
*/
public List<VerletParticle3D> particles;
/**
* List of spring/sticks connectors
*/
public List<VerletSpring3D> springs;
/**
* Default time step = 1.0
*/
protected float timeStep;
/**
* Default iterations for verlet solver = 50
*/
protected int numIterations;
/**
* Optional 3D bounding box to constrain particles too
*/
protected AABB worldBounds;
public final List<ParticleBehavior3D> behaviors = new ArrayList<ParticleBehavior3D>(
1);
public final List<ParticleConstraint3D> constraints = new ArrayList<ParticleConstraint3D>(
1);
protected float drag;
/**
* Initializes a Verlet engine instance using the default values.
*/
public VerletPhysics3D() {
this(null, 50, 0, 1);
}
/**
* Initializes an Verlet engine instance with the passed in configuration.
*
* @param gravity
* 3D gravity vector
* @param numIterations
* iterations per time step for verlet solver
* @param drag
* drag value 0...1
* @param timeStep
* time step for calculating forces
*/
public VerletPhysics3D(Vec3D gravity, int numIterations, float drag,
float timeStep) {
particles = new ArrayList<VerletParticle3D>();
springs = new ArrayList<VerletSpring3D>();
this.numIterations = numIterations;
this.timeStep = timeStep;
setDrag(drag);
if (gravity != null) {
addBehavior(new GravityBehavior3D(gravity));
}
}
public void addBehavior(ParticleBehavior3D behavior) {
behavior.configure(timeStep);
behaviors.add(behavior);
}
public void addConstraint(ParticleConstraint3D constraint) {
constraints.add(constraint);
}
/**
* Adds a particle to the list
*
* @param p
* @return itself
*/
public VerletPhysics3D addParticle(VerletParticle3D p) {
particles.add(p);
return this;
}
/**
* Adds a spring connector
*
* @param s
* @return itself
*/
public VerletPhysics3D addSpring(VerletSpring3D s) {
if (getSpring(s.a, s.b) == null) {
springs.add(s);
}
return this;
}
/**
* Applies all global constraints and constrains all particle positions to
* the world bounding box set
*/
protected void applyConstaints() {
boolean hasGlobalConstraints = constraints.size() > 0;
for (VerletParticle3D p : particles) {
if (hasGlobalConstraints) {
for (ParticleConstraint3D c : constraints) {
c.apply(p);
}
}
if (p.bounds != null) {
p.constrain(p.bounds);
}
if (worldBounds != null) {
p.constrain(worldBounds);
}
}
}
public VerletPhysics3D clear() {
behaviors.clear();
constraints.clear();
particles.clear();
springs.clear();
return this;
}
public AABB getCurrentBounds() {
Vec3D min = new Vec3D(Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE);
Vec3D max = new Vec3D(Float.MIN_VALUE, Float.MIN_VALUE, Float.MIN_VALUE);
for (Iterator<VerletParticle3D> i = particles.iterator(); i.hasNext();) {
VerletParticle3D p = i.next();
min.minSelf(p);
max.maxSelf(p);
}
return AABB.fromMinMax(min, max);
}
public float getDrag() {
return 1f - drag;
}
/**
* @return the numIterations
*/
public int getNumIterations() {
return numIterations;
}
/**
* Attempts to find the spring element between the 2 particles supplied
*
* @param a
* particle 1
* @param b
* particle 2
* @return spring instance, or null if not found
*/
public VerletSpring3D getSpring(Vec3D a, Vec3D b) {
for (VerletSpring3D s : springs) {
if ((s.a == a && s.b == b) || (s.a == b && s.b == a)) {
return s;
}
}
return null;
}
/**
* @return the timeStep
*/
public float getTimeStep() {
return timeStep;
}
/**
* @return the worldBounds
*/
public AABB getWorldBounds() {
return worldBounds;
}
public boolean removeBehavior(ParticleBehavior3D b) {
return behaviors.remove(b);
}
public boolean removeConstraint(ParticleConstraint3D c) {
return constraints.remove(c);
}
/**
* Removes a particle from the simulation.
*
* @param p
* particle to remove
* @return true, if removed successfully
*/
public boolean removeParticle(VerletParticle3D p) {
return particles.remove(p);
}
/**
* Removes a spring connector from the simulation instance.
*
* @param s
* spring to remove
* @return true, if the spring has been removed
*/
public boolean removeSpring(VerletSpring3D s) {
return springs.remove(s);
}
/**
* Removes a spring connector and its both end point particles from the
* simulation
*
* @param s
* spring to remove
* @return true, only if spring AND particles have been removed successfully
*/
public boolean removeSpringElements(VerletSpring3D s) {
if (removeSpring(s)) {
return (removeParticle(s.a) && removeParticle(s.b));
}
return false;
}
public void setDrag(float drag) {
this.drag = 1f - drag;
}
/**
* @param numIterations
* the numIterations to set
*/
public void setNumIterations(int numIterations) {
this.numIterations = numIterations;
}
/**
* @param timeStep
* the timeStep to set
*/
public void setTimeStep(float timeStep) {
this.timeStep = timeStep;
for (ParticleBehavior3D b : behaviors) {
b.configure(timeStep);
}
}
/**
* Sets bounding box
*
* @param world
* @return itself
*/
public VerletPhysics3D setWorldBounds(AABB world) {
worldBounds = world;
return this;
}
/**
* Progresses the physics simulation by 1 time step and updates all forces
* and particle positions accordingly
*
* @return itself
*/
public VerletPhysics3D update() {
updateParticles();
updateSprings();
applyConstaints();
return this;
}
/**
* Updates all particle positions
*/
protected void updateParticles() {
for (ParticleBehavior3D b : behaviors) {
for (VerletParticle3D p : particles) {
b.apply(p);
}
}
for (VerletParticle3D p : particles) {
p.scaleVelocity(drag);
p.update();
}
}
/**
* Updates all spring connections based on new particle positions
*/
protected void updateSprings() {
if (springs.size() > 0) {
for (int i = numIterations; i > 0; i--) {
for (VerletSpring3D s : springs) {
s.update(i == 1);
}
}
}
}
}
| lgpl-2.1 |
ethaneldridge/vassal | src/VASSAL/configure/ValidationReport.java | 1122 | /*
* $Id$
*
* Copyright (c) 2004 by Rodney Kinney
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.configure;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Summarizes error/warning messages about invalid module configuration
*/
public class ValidationReport {
private List<String> messages = new ArrayList<String>();
public void addWarning(String msg) {
messages.add(msg);
}
public List<String> getWarnings() {
return Collections.unmodifiableList(messages);
}
}
| lgpl-2.1 |
Godin/checkstyle | src/main/java/com/puppycrawl/tools/checkstyle/checks/OuterTypeFilenameCheck.java | 3674 | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2015 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks;
import java.io.File;
import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
/**
* Checks that the outer type name and the file name match.
* @author Oliver Burn
* @author maxvetrenko
*/
public class OuterTypeFilenameCheck extends Check {
/** indicates whether the first token has been seen in the file. */
private boolean seenFirstToken;
/** Current file name*/
private String fileName;
/** If file has public type*/
private boolean hasPublic;
/** If first type has has same name as file*/
private boolean validFirst;
/** Outer type with mismatched file name*/
private DetailAST wrongType;
@Override
public int[] getDefaultTokens() {
return new int[] {
TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF,
TokenTypes.ENUM_DEF, TokenTypes.ANNOTATION_DEF,
};
}
@Override
public int[] getAcceptableTokens() {
return new int[] {
TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF,
TokenTypes.ENUM_DEF, TokenTypes.ANNOTATION_DEF,
};
}
@Override
public void beginTree(DetailAST ast) {
fileName = getFileName();
seenFirstToken = false;
validFirst = false;
hasPublic = false;
wrongType = null;
}
@Override
public void visitToken(DetailAST ast) {
final String outerTypeName = ast.findFirstToken(TokenTypes.IDENT).getText();
if (seenFirstToken) {
final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS);
if (modifiers.findFirstToken(TokenTypes.LITERAL_PUBLIC) != null
&& ast.getParent() == null) {
hasPublic = true;
}
}
else {
if (fileName.equals(outerTypeName)) {
validFirst = true;
}
else {
wrongType = ast;
}
}
seenFirstToken = true;
}
@Override
public void finishTree(DetailAST rootAST) {
if (!validFirst && !hasPublic && wrongType != null) {
log(wrongType.getLineNo(), "type.file.mismatch");
}
}
/**
* Get source file name.
* @return source file name.
*/
private String getFileName() {
String fname = getFileContents().getFileName();
fname = fname.substring(fname.lastIndexOf(File.separatorChar) + 1);
fname = fname.replaceAll("\\.[^\\.]*$", "");
return fname;
}
}
| lgpl-2.1 |
codeaudit/openccg | src/opennlp/ccg/hylo/graph/LFEdgeFactory.java | 1989 | //////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2012 Scott Martin
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//////////////////////////////////////////////////////////////////////////////
package opennlp.ccg.hylo.graph;
import org.jgrapht.EdgeFactory;
/**
* A factory for LF edges that creates edges from specified source and target vertices and an edge label.
* This interface extends the {@link EdgeFactory} interface for the specialized case of
* directed, labeled LF edges with LF vertices as their nodes. A default implementation
* is provided in {@link DefaultLFEdgeFactory}.
*
* @author <a href="http://www.ling.ohio-state.edu/~scott/">Scott Martin</a>
*/
public interface LFEdgeFactory extends EdgeFactory<LFVertex, LFEdge> {
/**
* Creates a new labeled, directed edge from a specified vertex pair and edge label.
* @param sourceVertex The source vertex of the new edge.
* @param targetVertex The target vertex of the new edge.
* @param label The label of the new edge.
* @return An instance of {@link LFEdge} with the specified parameters.
*
* @see LFEdge#LFEdge(LFVertex, LFVertex, LFEdgeLabel)
*/
public LFEdge createLabeledEdge(LFVertex sourceVertex, LFVertex targetVertex, LFEdgeLabel label);
}
| lgpl-2.1 |
oskopek/jfreechart-fse | src/test/java/org/jfree/chart/renderer/category/StackedBarRendererTest.java | 5681 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2012, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ----------------------------
* StackedBarRendererTests.java
* ----------------------------
* (C) Copyright 2003-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 25-Mar-2003 : Version 1 (DG);
* 23-Apr-2008 : Added testPublicCloneable() (DG);
*
*/
package org.jfree.chart.renderer.category;
import org.jfree.chart.util.PublicCloneable;
import org.jfree.data.Range;
import org.jfree.data.category.DefaultCategoryDataset;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/**
* Tests for the {@link StackedBarRenderer} class.
*/
public class StackedBarRendererTest {
/**
* Check that the equals() method distinguishes all fields.
*/
@Test
public void testEquals() {
StackedBarRenderer r1 = new StackedBarRenderer();
StackedBarRenderer r2 = new StackedBarRenderer();
assertEquals(r1, r2);
assertEquals(r2, r1);
r1.setRenderAsPercentages(true);
assertFalse(r1.equals(r2));
r2.setRenderAsPercentages(true);
assertEquals(r1, r2);
}
/**
* Two objects that are equal are required to return the same hashCode.
*/
@Test
public void testHashCode() {
StackedBarRenderer r1 = new StackedBarRenderer();
StackedBarRenderer r2 = new StackedBarRenderer();
assertEquals(r1, r2);
int h1 = r1.hashCode();
int h2 = r2.hashCode();
assertEquals(h1, h2);
}
/**
* Confirm that cloning works.
*/
@Test
public void testCloning() throws CloneNotSupportedException {
StackedBarRenderer r1 = new StackedBarRenderer();
StackedBarRenderer r2 = (StackedBarRenderer) r1.clone();
assertNotSame(r1, r2);
assertSame(r1.getClass(), r2.getClass());
assertEquals(r1, r2);
}
/**
* Check that this class implements PublicCloneable.
*/
@Test
public void testPublicCloneable() {
StackedBarRenderer r1 = new StackedBarRenderer();
assertTrue(r1 instanceof PublicCloneable);
}
/**
* Serialize an instance, restore it, and check for equality.
*/
@Test
public void testSerialization() throws IOException, ClassNotFoundException {
StackedBarRenderer r1 = new StackedBarRenderer();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(r1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
StackedBarRenderer r2 = (StackedBarRenderer) in.readObject();
in.close();
assertEquals(r1, r2);
}
/**
* Some checks for the findRangeBounds() method.
*/
@Test
public void testFindRangeBounds() {
StackedBarRenderer r = new StackedBarRenderer();
assertNull(r.findRangeBounds(null));
// an empty dataset should return a null range
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
assertNull(r.findRangeBounds(dataset));
dataset.addValue(1.0, "R1", "C1");
assertEquals(new Range(0.0, 1.0), r.findRangeBounds(dataset));
dataset.addValue(-2.0, "R1", "C2");
assertEquals(new Range(-2.0, 1.0), r.findRangeBounds(dataset));
dataset.addValue(null, "R1", "C3");
assertEquals(new Range(-2.0, 1.0), r.findRangeBounds(dataset));
dataset.addValue(2.0, "R2", "C1");
assertEquals(new Range(-2.0, 3.0), r.findRangeBounds(dataset));
dataset.addValue(null, "R2", "C2");
assertEquals(new Range(-2.0, 3.0), r.findRangeBounds(dataset));
}
}
| lgpl-2.1 |
lgassman/embebidos-unq | icecaptools/src/icecaptools/ProjectResourceManager.java | 1844 | package icecaptools;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IProject;
public class ProjectResourceManager extends ResourceManager {
private IProject project;
private Map<String,String> resourcesMap;
public ProjectResourceManager(IProject project, Map<String, String> resources) {
this.project = project;
Set<String> keySet = resources.keySet();
String[] resourcesToLoad = new String[keySet.size()];
int i = 0;
for(String s : keySet) {
resourcesToLoad[i++] = s;
}
this.setResourcesToLoad(resourcesToLoad);
this.resourcesMap = resources;
}
@Override
public Iterator<StreamResource> getResources(PrintStream out) {
return new ResourceManagerIterator(out);
}
@Override
public StreamResource getResource(PrintStream out, String resourceName) {
InputStream stream;
try {
stream = this.project.getFile(resourceName).getContents();
StreamResource streamResource = new StreamResource(stream, resourcesMap.get(resourceName));
return streamResource;
} catch (Exception e) {
e.printStackTrace(out);
}
return null;
}
private class ResourceManagerIterator implements Iterator<StreamResource> {
Iterator<String> inner;
private PrintStream out;
private ResourceManagerIterator(PrintStream out) {
this.out = out;
List<String> list = new ArrayList<String>();
for(String s : getResourcesToLoad()) {
list.add(s);
}
inner = list.iterator();
}
@Override
public boolean hasNext() {
return inner.hasNext();
}
@Override
public StreamResource next() {
return getResource(out,inner.next());
}
}
}
| lgpl-3.0 |
samaitra/ignite | modules/core/src/main/java/org/apache/ignite/internal/client/thin/ClientComputeImpl.java | 19874 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.client.thin;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Consumer;
import java.util.function.Function;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.client.ClientClusterGroup;
import org.apache.ignite.client.ClientCompute;
import org.apache.ignite.client.ClientConnectionException;
import org.apache.ignite.client.ClientException;
import org.apache.ignite.client.ClientFeatureNotSupportedByServerException;
import org.apache.ignite.client.IgniteClientFuture;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.binary.BinaryRawWriterEx;
import org.apache.ignite.internal.binary.streams.BinaryHeapInputStream;
import org.apache.ignite.internal.processors.platform.client.ClientStatus;
import org.apache.ignite.internal.util.IgniteUtils;
import org.apache.ignite.internal.util.future.GridFutureAdapter;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.T2;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteUuid;
import org.jetbrains.annotations.Nullable;
import static org.apache.ignite.internal.client.thin.ClientOperation.COMPUTE_TASK_EXECUTE;
import static org.apache.ignite.internal.client.thin.ClientOperation.RESOURCE_CLOSE;
/**
* Implementation of {@link ClientCompute}.
*/
class ClientComputeImpl implements ClientCompute, NotificationListener {
/** No failover flag mask. */
private static final byte NO_FAILOVER_FLAG_MASK = 0x01;
/** No result cache flag mask. */
private static final byte NO_RESULT_CACHE_FLAG_MASK = 0x02;
/** Channel. */
private final ReliableChannel ch;
/** Utils for serialization/deserialization. */
private final ClientUtils utils;
/** Default cluster group. */
private final ClientClusterGroupImpl dfltGrp;
/** Active tasks. */
private final Map<ClientChannel, Map<Long, ClientComputeTask<Object>>> activeTasks = new ConcurrentHashMap<>();
/** Guard lock for active tasks. */
private final ReadWriteLock guard = new ReentrantReadWriteLock();
/** Constructor. */
ClientComputeImpl(ReliableChannel ch, ClientBinaryMarshaller marsh, ClientClusterGroupImpl dfltGrp) {
this.ch = ch;
this.dfltGrp = dfltGrp;
utils = new ClientUtils(marsh);
ch.addNotificationListener(this);
ch.addChannelCloseListener(clientCh -> {
guard.writeLock().lock();
try {
Map<Long, ClientComputeTask<Object>> chTasks = activeTasks.remove(clientCh);
if (!F.isEmpty(chTasks)) {
for (ClientComputeTask<?> task : chTasks.values())
task.fut.onDone(new ClientConnectionException("Channel to server is closed"));
}
}
finally {
guard.writeLock().unlock();
}
});
}
/** {@inheritDoc} */
@Override public ClientClusterGroup clusterGroup() {
return dfltGrp;
}
/** {@inheritDoc} */
@Override public <T, R> R execute(String taskName, @Nullable T arg) throws ClientException, InterruptedException {
return execute0(taskName, arg, dfltGrp, (byte)0, 0L);
}
/** {@inheritDoc} */
@Override public <T, R> Future<R> executeAsync(String taskName, @Nullable T arg) throws ClientException {
return executeAsync0(taskName, arg, dfltGrp, (byte)0, 0L);
}
/** {@inheritDoc} */
@Override public <T, R> IgniteClientFuture<R> executeAsync2(String taskName, @Nullable T arg) throws ClientException {
return executeAsync0(taskName, arg, dfltGrp, (byte)0, 0L);
}
/** {@inheritDoc} */
@Override public ClientCompute withTimeout(long timeout) {
return timeout == 0L ? this : new ClientComputeModificator(this, dfltGrp, (byte)0, timeout);
}
/** {@inheritDoc} */
@Override public ClientCompute withNoFailover() {
return new ClientComputeModificator(this, dfltGrp, NO_FAILOVER_FLAG_MASK, 0L);
}
/** {@inheritDoc} */
@Override public ClientCompute withNoResultCache() {
return new ClientComputeModificator(this, dfltGrp, NO_RESULT_CACHE_FLAG_MASK, 0L);
}
/**
* Gets compute facade over the specified cluster group.
*
* @param grp Cluster group.
*/
public ClientCompute withClusterGroup(ClientClusterGroupImpl grp) {
return new ClientComputeModificator(this, grp, (byte)0, 0L);
}
/**
* @param taskName Task name.
* @param arg Argument.
* @param clusterGrp Cluster group.
* @param flags Flags.
* @param timeout Timeout.
*/
private <T, R> R execute0(
String taskName,
@Nullable T arg,
ClientClusterGroupImpl clusterGrp,
byte flags,
long timeout
) throws ClientException {
try {
return (R)executeAsync0(taskName, arg, clusterGrp, flags, timeout).get();
}
catch (ExecutionException | InterruptedException e) {
throw convertException(e);
}
}
/**
* Converts the exception.
*
* @param t Throwable.
* @return Resulting client exception.
*/
private ClientException convertException(Throwable t) {
if (t instanceof ClientException) {
return (ClientException) t;
} else if (t.getCause() instanceof ClientException)
return (ClientException)t.getCause();
else
return new ClientException(t);
}
/**
* @param taskName Task name.
* @param arg Argument.
* @param clusterGrp Cluster group.
* @param flags Flags.
* @param timeout Timeout.
*/
private <T, R> IgniteClientFuture<R> executeAsync0(
String taskName,
@Nullable T arg,
ClientClusterGroupImpl clusterGrp,
byte flags,
long timeout
) throws ClientException {
Collection<UUID> nodeIds = clusterGrp.nodeIds();
if (F.isEmpty(taskName))
throw new ClientException("Task name can't be null or empty.");
if (nodeIds != null && nodeIds.isEmpty())
throw new ClientException("Cluster group is empty.");
Consumer<PayloadOutputChannel> payloadWriter =
ch -> writeExecuteTaskRequest(ch, taskName, arg, nodeIds, flags, timeout);
Function<PayloadInputChannel, T2<ClientChannel, Long>> payloadReader =
ch -> new T2<>(ch.clientChannel(), ch.in().readLong());
IgniteClientFuture<T2<ClientChannel, Long>> initFut = ch.serviceAsync(
COMPUTE_TASK_EXECUTE, payloadWriter, payloadReader);
CompletableFuture<R> resFut = new CompletableFuture<>();
AtomicReference<Object> cancellationToken = new AtomicReference<>();
initFut.handle((taskParams, err) ->
handleExecuteInitFuture(payloadWriter, payloadReader, resFut, cancellationToken, taskParams, err));
return new IgniteClientFutureImpl<>(resFut, mayInterruptIfRunning -> {
// 1. initFut has not completed - store cancellation flag.
// 2. initFut has completed - cancel compute future.
if (!cancellationToken.compareAndSet(null, mayInterruptIfRunning)) {
try {
GridFutureAdapter<?> fut = (GridFutureAdapter<?>) cancellationToken.get();
if (cancelGridFuture(fut, mayInterruptIfRunning)) {
resFut.cancel(mayInterruptIfRunning);
return true;
} else {
return false;
}
} catch (IgniteCheckedException e) {
throw IgniteUtils.convertException(e);
}
}
resFut.cancel(mayInterruptIfRunning);
return true;
});
}
/**
* Handles execute initialization.
* @param payloadWriter Writer.
* @param payloadReader Reader.
* @param resFut Resulting future.
* @param cancellationToken Cancellation token holder.
* @param taskParams Task parameters.
* @param err Error
* @param <R> Result type.
* @return Null.
*/
private <R> Object handleExecuteInitFuture(
Consumer<PayloadOutputChannel> payloadWriter,
Function<PayloadInputChannel, T2<ClientChannel, Long>> payloadReader,
CompletableFuture<R> resFut,
AtomicReference<Object> cancellationToken,
T2<ClientChannel, Long> taskParams,
Throwable err) {
if (err != null) {
resFut.completeExceptionally(new ClientException(err));
} else {
ClientComputeTask<Object> task = addTask(taskParams.get1(), taskParams.get2());
if (task == null) {
// Channel closed - try again recursively.
ch.serviceAsync(COMPUTE_TASK_EXECUTE, payloadWriter, payloadReader)
.handle((r, e) ->
handleExecuteInitFuture(payloadWriter, payloadReader, resFut, cancellationToken, r, e));
}
if (!cancellationToken.compareAndSet(null, task.fut)) {
try {
cancelGridFuture(task.fut, (Boolean) cancellationToken.get());
} catch (IgniteCheckedException e) {
throw U.convertException(e);
}
}
task.fut.listen(f -> {
// Don't remove task if future was canceled by user. This task can be added again later by notification.
// To prevent leakage tasks for cancelled futures will be removed on notification (or channel close event).
if (!f.isCancelled()) {
removeTask(task.ch, task.taskId);
try {
resFut.complete(((GridFutureAdapter<R>) f).get());
} catch (IgniteCheckedException e) {
resFut.completeExceptionally(e.getCause());
}
}
});
}
return null;
}
/**
* Cancels grid future.
*
* @param fut Future.
* @param mayInterruptIfRunning true if the thread executing this task should be interrupted;
* otherwise, in-progress tasks are allowed to complete.
*/
private static boolean cancelGridFuture(GridFutureAdapter<?> fut, Boolean mayInterruptIfRunning)
throws IgniteCheckedException {
return mayInterruptIfRunning ? fut.cancel() : fut.onCancelled();
}
/**
*
*/
private <T> void writeExecuteTaskRequest(
PayloadOutputChannel ch,
String taskName,
@Nullable T arg,
Collection<UUID> nodeIds,
byte flags,
long timeout
) throws ClientException {
if (!ch.clientChannel().protocolCtx().isFeatureSupported(ProtocolBitmaskFeature.EXECUTE_TASK_BY_NAME)) {
throw new ClientFeatureNotSupportedByServerException("Compute grid functionality for thin " +
"client not supported by server node (" + ch.clientChannel().serverNodeId() + ')');
}
try (BinaryRawWriterEx w = utils.createBinaryWriter(ch.out())) {
if (nodeIds == null) // Include all nodes.
w.writeInt(0);
else {
w.writeInt(nodeIds.size());
for (UUID nodeId : nodeIds) {
w.writeLong(nodeId.getMostSignificantBits());
w.writeLong(nodeId.getLeastSignificantBits());
}
}
w.writeByte(flags);
w.writeLong(timeout);
w.writeString(taskName);
w.writeObject(arg);
}
}
/** {@inheritDoc} */
@Override public void acceptNotification(
ClientChannel ch,
ClientOperation op,
long rsrcId,
byte[] payload,
Exception err
) {
if (op == ClientOperation.COMPUTE_TASK_FINISHED) {
Object res = payload == null ? null : utils.readObject(new BinaryHeapInputStream(payload), false);
ClientComputeTask<Object> task = addTask(ch, rsrcId);
if (task != null) { // If channel is closed concurrently, task is already done with "channel closed" reason.
if (err == null)
task.fut.onDone(res);
else
task.fut.onDone(err);
if (task.fut.isCancelled())
removeTask(ch, rsrcId);
}
}
}
/**
* @param ch Client channel.
* @param taskId Task id.
* @return Already registered task, new task if task wasn't registered before, or {@code null} if channel was
* closed concurrently.
*/
private ClientComputeTask<Object> addTask(ClientChannel ch, long taskId) {
guard.readLock().lock();
try {
// If channel is closed we should only get task if it was registered before, but not add new one.
boolean closed = ch.closed();
Map<Long, ClientComputeTask<Object>> chTasks = closed ? activeTasks.get(ch) :
activeTasks.computeIfAbsent(ch, c -> new ConcurrentHashMap<>());
if (chTasks == null)
return null;
return closed ? chTasks.get(taskId) :
chTasks.computeIfAbsent(taskId, t -> new ClientComputeTask<>(ch, taskId));
}
finally {
guard.readLock().unlock();
}
}
/**
* @param ch Client channel.
* @param taskId Task id.
*/
private ClientComputeTask<Object> removeTask(ClientChannel ch, long taskId) {
Map<Long, ClientComputeTask<Object>> chTasks = activeTasks.get(ch);
if (!F.isEmpty(chTasks))
return chTasks.remove(taskId);
return null;
}
/**
* Gets tasks future for active tasks started by client.
* Used only for tests.
*
* @return Map of active tasks keyed by their unique per client task ID.
*/
Map<IgniteUuid, IgniteInternalFuture<?>> activeTaskFutures() {
Map<IgniteUuid, IgniteInternalFuture<?>> res = new HashMap<>();
for (Map.Entry<ClientChannel, Map<Long, ClientComputeTask<Object>>> chTasks : activeTasks.entrySet()) {
for (Map.Entry<Long, ClientComputeTask<Object>> task : chTasks.getValue().entrySet())
res.put(new IgniteUuid(chTasks.getKey().serverNodeId(), task.getKey()), task.getValue().fut);
}
return res;
}
/**
* ClientCompute with modificators.
*/
private static class ClientComputeModificator implements ClientCompute {
/** Delegate. */
private final ClientComputeImpl delegate;
/** Cluster group. */
private final ClientClusterGroupImpl clusterGrp;
/** Task flags. */
private final byte flags;
/** Task timeout. */
private final long timeout;
/**
* Constructor.
*/
private ClientComputeModificator(ClientComputeImpl delegate, ClientClusterGroupImpl clusterGrp, byte flags,
long timeout) {
this.delegate = delegate;
this.clusterGrp = clusterGrp;
this.flags = flags;
this.timeout = timeout;
}
/** {@inheritDoc} */
@Override public ClientClusterGroup clusterGroup() {
return clusterGrp;
}
/** {@inheritDoc} */
@Override public <T, R> R execute(String taskName, @Nullable T arg) throws ClientException, InterruptedException {
return delegate.execute0(taskName, arg, clusterGrp, flags, timeout);
}
/** {@inheritDoc} */
@Override public <T, R> IgniteClientFuture<R> executeAsync(String taskName, @Nullable T arg) throws ClientException {
return delegate.executeAsync0(taskName, arg, clusterGrp, flags, timeout);
}
/** {@inheritDoc} */
@Override public <T, R> IgniteClientFuture<R> executeAsync2(String taskName, @Nullable T arg) throws ClientException {
return delegate.executeAsync0(taskName, arg, clusterGrp, flags, timeout);
}
/** {@inheritDoc} */
@Override public ClientCompute withTimeout(long timeout) {
return timeout == this.timeout ? this : new ClientComputeModificator(delegate, clusterGrp, flags, timeout);
}
/** {@inheritDoc} */
@Override public ClientCompute withNoFailover() {
return (flags & NO_FAILOVER_FLAG_MASK) != 0 ? this :
new ClientComputeModificator(delegate, clusterGrp, (byte) (flags | NO_FAILOVER_FLAG_MASK), timeout);
}
/** {@inheritDoc} */
@Override public ClientCompute withNoResultCache() {
return (flags & NO_RESULT_CACHE_FLAG_MASK) != 0 ? this :
new ClientComputeModificator(delegate, clusterGrp, (byte) (flags | NO_RESULT_CACHE_FLAG_MASK), timeout);
}
}
/**
* Compute task internal class.
*
* @param <R> Result type.
*/
private static class ClientComputeTask<R> {
/** Client channel. */
private final ClientChannel ch;
/** Task id. */
private final long taskId;
/** Future. */
private final GridFutureAdapter<R> fut;
/**
* @param ch Client channel.
* @param taskId Task id.
*/
private ClientComputeTask(ClientChannel ch, long taskId) {
this.ch = ch;
this.taskId = taskId;
fut = new GridFutureAdapter<R>() {
@Override public boolean cancel() {
if (onCancelled()) {
try {
ch.service(RESOURCE_CLOSE, req -> req.out().writeLong(taskId), null);
}
catch (ClientServerError e) {
// Ignore "resource doesn't exist" error. The task can be completed concurrently on the
// server, but we already complete future with "cancelled" state, so result will never be
// received by a client.
if (e.getCode() != ClientStatus.RESOURCE_DOES_NOT_EXIST)
throw new ClientException(e);
}
return true;
}
else
return false;
}
};
}
}
}
| apache-2.0 |
christophd/camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/ElsqlComponentBuilderFactory.java | 8781 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.builder.component.dsl;
import javax.annotation.Generated;
import org.apache.camel.Component;
import org.apache.camel.builder.component.AbstractComponentBuilder;
import org.apache.camel.builder.component.ComponentBuilder;
import org.apache.camel.component.elsql.ElsqlComponent;
/**
* Use ElSql to define SQL queries. Extends the SQL Component.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.ComponentDslMojo")
public interface ElsqlComponentBuilderFactory {
/**
* ElSQL (camel-elsql)
* Use ElSql to define SQL queries. Extends the SQL Component.
*
* Category: database,sql
* Since: 2.16
* Maven coordinates: org.apache.camel:camel-elsql
*
* @return the dsl builder
*/
@Deprecated
static ElsqlComponentBuilder elsql() {
return new ElsqlComponentBuilderImpl();
}
/**
* Builder for the ElSQL component.
*/
interface ElsqlComponentBuilder extends ComponentBuilder<ElsqlComponent> {
/**
* To use a vendor specific com.opengamma.elsql.ElSqlConfig.
*
* The option is a:
* <code>org.apache.camel.component.elsql.ElSqlDatabaseVendor</code> type.
*
* Group: common
*
* @param databaseVendor the value to set
* @return the dsl builder
*/
default ElsqlComponentBuilder databaseVendor(
org.apache.camel.component.elsql.ElSqlDatabaseVendor databaseVendor) {
doSetProperty("databaseVendor", databaseVendor);
return this;
}
/**
* Sets the DataSource to use to communicate with the database.
*
* The option is a: <code>javax.sql.DataSource</code> type.
*
* Group: common
*
* @param dataSource the value to set
* @return the dsl builder
*/
default ElsqlComponentBuilder dataSource(javax.sql.DataSource dataSource) {
doSetProperty("dataSource", dataSource);
return this;
}
/**
* The resource file which contains the elsql SQL statements to use. You
* can specify multiple resources separated by comma. The resources are
* loaded on the classpath by default, you can prefix with file: to load
* from file system. Notice you can set this option on the component and
* then you do not have to configure this on the endpoint.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param resourceUri the value to set
* @return the dsl builder
*/
default ElsqlComponentBuilder resourceUri(java.lang.String resourceUri) {
doSetProperty("resourceUri", resourceUri);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions occurred while the consumer is trying to
* pickup incoming messages, or the likes, will now be processed as a
* message and handled by the routing Error Handler. By default the
* consumer will use the org.apache.camel.spi.ExceptionHandler to deal
* with exceptions, that will be logged at WARN or ERROR level and
* ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default ElsqlComponentBuilder bridgeErrorHandler(
boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default ElsqlComponentBuilder lazyStartProducer(
boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether autowiring is enabled. This is used for automatic autowiring
* options (the option must be marked as autowired) by looking up in the
* registry to find if there is a single instance of matching type,
* which then gets configured on the component. This can be used for
* automatic configuring JDBC data sources, JMS connection factories,
* AWS Clients, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param autowiredEnabled the value to set
* @return the dsl builder
*/
default ElsqlComponentBuilder autowiredEnabled(boolean autowiredEnabled) {
doSetProperty("autowiredEnabled", autowiredEnabled);
return this;
}
/**
* To use a specific configured ElSqlConfig. It may be better to use the
* databaseVendor option instead.
*
* The option is a:
* <code>com.opengamma.elsql.ElSqlConfig</code> type.
*
* Group: advanced
*
* @param elSqlConfig the value to set
* @return the dsl builder
*/
default ElsqlComponentBuilder elSqlConfig(
com.opengamma.elsql.ElSqlConfig elSqlConfig) {
doSetProperty("elSqlConfig", elSqlConfig);
return this;
}
}
class ElsqlComponentBuilderImpl
extends
AbstractComponentBuilder<ElsqlComponent>
implements
ElsqlComponentBuilder {
@Override
protected ElsqlComponent buildConcreteComponent() {
return new ElsqlComponent();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "databaseVendor": ((ElsqlComponent) component).setDatabaseVendor((org.apache.camel.component.elsql.ElSqlDatabaseVendor) value); return true;
case "dataSource": ((ElsqlComponent) component).setDataSource((javax.sql.DataSource) value); return true;
case "resourceUri": ((ElsqlComponent) component).setResourceUri((java.lang.String) value); return true;
case "bridgeErrorHandler": ((ElsqlComponent) component).setBridgeErrorHandler((boolean) value); return true;
case "lazyStartProducer": ((ElsqlComponent) component).setLazyStartProducer((boolean) value); return true;
case "autowiredEnabled": ((ElsqlComponent) component).setAutowiredEnabled((boolean) value); return true;
case "elSqlConfig": ((ElsqlComponent) component).setElSqlConfig((com.opengamma.elsql.ElSqlConfig) value); return true;
default: return false;
}
}
}
} | apache-2.0 |
apache/manifoldcf | connectors/mongodb/connector/src/main/java/org/apache/manifoldcf/agents/output/mongodboutput/MongodbOutputConnector.java | 37630 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.manifoldcf.agents.output.mongodboutput;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCursor;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.DBTCPConnector;
import com.mongodb.DBPort;
import com.mongodb.DBPortPool;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
import com.mongodb.MongoException;
import org.bson.types.Binary;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.manifoldcf.agents.interfaces.IOutputAddActivity;
import org.apache.manifoldcf.agents.interfaces.IOutputRemoveActivity;
import org.apache.manifoldcf.agents.interfaces.RepositoryDocument;
import org.apache.manifoldcf.agents.interfaces.ServiceInterruption;
import org.apache.manifoldcf.agents.output.BaseOutputConnector;
import org.apache.manifoldcf.core.interfaces.IThreadContext;
import org.apache.manifoldcf.core.interfaces.IHTTPOutput;
import org.apache.manifoldcf.core.interfaces.IPasswordMapperActivity;
import org.apache.manifoldcf.core.interfaces.IPostParameters;
import org.apache.manifoldcf.core.interfaces.ConfigParams;
import org.apache.manifoldcf.core.interfaces.VersionContext;
import org.apache.manifoldcf.core.interfaces.ManifoldCFException;
import org.apache.manifoldcf.crawler.system.Logging;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.rmi.RemoteException;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Date;
import java.util.Iterator;
/**
* This is the "output connector" for MongoDB.
*
* @author Irindu Nugawela
*/
public class MongodbOutputConnector extends BaseOutputConnector {
// Tab name properties
private static final String MONGODB_TAB_PARAMETERS = "MongodbConnector.Parameters";
// Template names
/**
* Forward to the javascript to check the configuration parameters
*/
private static final String EDIT_CONFIG_HEADER_FORWARD = "editConfiguration.js";
/**
* Server tab template
*/
private static final String EDIT_CONFIG_FORWARD_SERVER = "editConfiguration_Parameters.html";
/**
* Forward to the HTML template to view the configuration parameters
*/
private static final String VIEW_CONFIG_FORWARD = "viewConfiguration.html";
/**
* Save activity
*/
protected final static String ACTIVITY_INJECTION = "Injection";
/**
* Delete activity
*/
protected final static String ACTIVITY_DELETE = "Delete";
/**
* Document accepted
*/
private final static int DOCUMENT_STATUS_ACCEPTED = 0;
private static final String DOCUMENT_STATUS_ACCEPTED_DESC = "Injection OK - ";
private static final String DOCUMENT_STATUS_REJECTED_DESC = "Injection KO - ";
/**
* Document permanently rejected
*/
private final static int DOCUMENT_STATUS_REJECTED = 1;
/**
* Document remove accepted
*/
private final static String DOCUMENT_DELETION_STATUS_ACCEPTED = "Remove request accepted";
/**
* Document remove permanently rejected
*/
private final static String DOCUMENT_DELETION_STATUS_REJECTED = "Remove request rejected";
/** Location of host where MongoDB server is hosted*/
protected String host = null;
/** port number associated with MongoDB server process */
protected String port = null;
/** Name of the target database */
protected String database = null;
/** Name of the target collection that belongs to the database specified above */
protected String collection = null;
/** username and password associated with the target database */
protected String username = null;
protected String password = null;
/**
* Session expiration time in milliseconds.
*/
protected static final long timeToRelease = 300000L;
/**
* Last session fetch time.
*/
protected long lastSessionFetch = -1L;
/**
* MongoDB client instance used to make the connection to the MongoDB server
*/
private MongoClient client = null;
/**
* MongoDB database handle instance
*/
private DB mongoDatabase = null;
/**
* Constructor
*/
public MongodbOutputConnector() {
super();
}
/**
* Return the list of activities that this connector supports (i.e. writes
* into the log).
*
* @return the list.
*/
@Override
public String[] getActivitiesList() {
return new String[]{ACTIVITY_INJECTION, ACTIVITY_DELETE};
}
/**
* This method is periodically called for all connectors that are connected
* but not in active use.
*/
@Override
public void poll() throws ManifoldCFException {
if (lastSessionFetch == -1L)
return;
long currentTime = System.currentTimeMillis();
if (currentTime >= lastSessionFetch + timeToRelease) {
DestroySessionThread t = new DestroySessionThread();
try {
t.start();
t.join();
Throwable thr = t.getException();
if (thr != null) {
if (thr instanceof RemoteException)
throw (RemoteException) thr;
else
throw (Error) thr;
}
client = null;
lastSessionFetch = -1L;
} catch (InterruptedException e) {
t.interrupt();
throw new ManifoldCFException("Interrupted: " + e.getMessage(), e, ManifoldCFException.INTERRUPTED);
} catch (RemoteException e) {
Throwable e2 = e.getCause();
if (e2 instanceof InterruptedException || e2 instanceof InterruptedIOException)
throw new ManifoldCFException(e2.getMessage(), e2, ManifoldCFException.INTERRUPTED);
client = null;
lastSessionFetch = -1L;
// Treat this as a transient problem
Logging.connectors.warn("MongoDB: Transient remote exception closing session: " + e.getMessage(), e);
}
}
}
/**
* This method is called to assess whether to count this connector instance
* should actually be counted as being connected.
*
* @return true if the connector instance is actually connected.
*/
@Override
public boolean isConnected() {
if (client == null) {
return false;
}
DBTCPConnector currentTCPConnection = client.getConnector();
return currentTCPConnection.isOpen();
}
/**
* Read the content of a resource, replace the variable ${PARAMNAME} with the
* value and copy it to the out.
*
* @param resName
* @param out
* @throws ManifoldCFException
*/
private static void outputResource(String resName, IHTTPOutput out, Locale locale, Map<String, String> paramMap)
throws ManifoldCFException {
Messages.outputResourceWithVelocity(out, locale, resName, paramMap, true);
}
/**
* Fill in a Server tab configuration parameter map for calling a Velocity
* template.
*
* @param newMap is the map to fill in
* @param parameters is the current set of configuration parameters
*/
private static void fillInServerConfigurationMap(Map<String, String> newMap, IPasswordMapperActivity mapper,
ConfigParams parameters) {
String username = parameters.getParameter(MongodbOutputConfig.USERNAME_PARAM);
String password = parameters.getParameter(MongodbOutputConfig.PASSWORD_PARAM);
String host = parameters.getParameter(MongodbOutputConfig.HOST_PARAM);
String port = parameters.getParameter(MongodbOutputConfig.PORT_PARAM);
String database = parameters.getParameter(MongodbOutputConfig.DATABASE_PARAM);
String collection = parameters.getParameter(MongodbOutputConfig.COLLECTION_PARAM);
if (username == null)
username = StringUtils.EMPTY;
if (password == null)
password = StringUtils.EMPTY;
else
password = mapper.mapPasswordToKey(password);
if (host == null)
host = MongodbOutputConfig.HOST_DEFAULT_VALUE;
if (port == null)
port = MongodbOutputConfig.PORT_DEFAULT_VALUE;
if (database == null)
database = MongodbOutputConfig.DATABASE_DEFAULT_VALUE;
if (collection == null)
collection = MongodbOutputConfig.COLLECTION_DEFAULT_VALUE;
newMap.put(MongodbOutputConfig.USERNAME_PARAM, username);
newMap.put(MongodbOutputConfig.PASSWORD_PARAM, password);
newMap.put(MongodbOutputConfig.HOST_PARAM, host);
newMap.put(MongodbOutputConfig.PORT_PARAM, port);
newMap.put(MongodbOutputConfig.DATABASE_PARAM, database);
newMap.put(MongodbOutputConfig.COLLECTION_PARAM, collection);
}
/**
* View configuration. This method is called in the body section of the
* connector's view configuration page. Its purpose is to present the
* connection information to the user. The coder can presume that the HTML
* that is output from this configuration will be within appropriate
* <html> and <body>tags.
*
* @param threadContext is the local thread context.
* @param out is the output to which any HTML should be sent.
* @param parameters are the configuration parameters, as they currently exist, for
* this connection being configured.
*/
@Override
public void viewConfiguration(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters)
throws ManifoldCFException, IOException {
Map<String, String> paramMap = new HashMap<String, String>();
// Fill in map from each tab
fillInServerConfigurationMap(paramMap, out, parameters);
outputResource(VIEW_CONFIG_FORWARD, out, locale, paramMap);
}
/**
* Output the configuration header section. This method is called in the head
* section of the connector's configuration page. Its purpose is to add the
* required tabs to the list, and to output any javascript methods that might
* be needed by the configuration editing HTML.
*
* @param threadContext is the local thread context.
* @param out is the output to which any HTML should be sent.
* @param parameters are the configuration parameters, as they currently exist, for
* this connection being configured.
* @param tabsArray is an array of tab names. Add to this array any tab names that are
* specific to the connector.
*/
@Override
public void outputConfigurationHeader(IThreadContext threadContext, IHTTPOutput out, Locale locale,
ConfigParams parameters, List<String> tabsArray) throws ManifoldCFException, IOException {
// Add the Server tab
tabsArray.add(Messages.getString(locale, MONGODB_TAB_PARAMETERS));
// Map the parameters
Map<String, String> paramMap = new HashMap<String, String>();
// Fill in the parameters from each tab
fillInServerConfigurationMap(paramMap, out, parameters);
// Output the Javascript - only one Velocity template for all tabs
outputResource(EDIT_CONFIG_HEADER_FORWARD, out, locale, paramMap);
}
@Override
public void outputConfigurationBody(IThreadContext threadContext, IHTTPOutput out, Locale locale,
ConfigParams parameters, String tabName) throws ManifoldCFException, IOException {
// Call the Velocity templates for each tab
// Server tab
Map<String, String> paramMap = new HashMap<String, String>();
// Set the tab name
paramMap.put("TabName", tabName);
// Fill in the parameters
fillInServerConfigurationMap(paramMap, out, parameters);
outputResource(EDIT_CONFIG_FORWARD_SERVER, out, locale, paramMap);
}
/**
* Process a configuration post. This method is called at the start of the
* connector's configuration page, whenever there is a possibility that form
* data for a connection has been posted. Its purpose is to gather form
* information and modify the configuration parameters accordingly. The name
* of the posted form is "editconnection".
*
* @param threadContext is the local thread context.
* @param variableContext is the set of variables available from the post, including binary
* file post information.
* @param parameters are the configuration parameters, as they currently exist, for
* this connection being configured.
* @return null if all is well, or a string error message if there is an error
* that should prevent saving of the connection (and cause a
* redirection to an error page).
*/
@Override
public String processConfigurationPost(IThreadContext threadContext, IPostParameters variableContext,
ConfigParams parameters) throws ManifoldCFException {
String username = variableContext.getParameter(MongodbOutputConfig.USERNAME_PARAM);
if (username != null)
parameters.setParameter(MongodbOutputConfig.USERNAME_PARAM, username);
String password = variableContext.getParameter(MongodbOutputConfig.PASSWORD_PARAM);
if (password != null)
parameters.setParameter(MongodbOutputConfig.PASSWORD_PARAM, variableContext.mapKeyToPassword(password));
String host = variableContext.getParameter(MongodbOutputConfig.HOST_PARAM);
if (host != null)
parameters.setParameter(MongodbOutputConfig.HOST_PARAM, host);
String port = variableContext.getParameter(MongodbOutputConfig.PORT_PARAM);
if (port != null && !StringUtils.isEmpty(port)) {
try {
Integer.parseInt(port);
parameters.setParameter(MongodbOutputConfig.PORT_PARAM, port);
} catch (NumberFormatException e) {
return "Invalid Port Number";
}
}
String database = variableContext.getParameter(MongodbOutputConfig.DATABASE_PARAM);
if (database != null)
parameters.setParameter(MongodbOutputConfig.DATABASE_PARAM, database);
String collection = variableContext.getParameter(MongodbOutputConfig.COLLECTION_PARAM);
if (collection != null)
parameters.setParameter(MongodbOutputConfig.COLLECTION_PARAM, collection);
return null;
}
/**
* Close the connection. Call this before discarding the connection.
*/
@Override
public void disconnect() throws ManifoldCFException {
if (client != null) {
DestroySessionThread t = new DestroySessionThread();
try {
t.start();
t.join();
Throwable thr = t.getException();
if (thr != null) {
if (thr instanceof RemoteException)
throw (RemoteException) thr;
else
throw (Error) thr;
}
client = null;
mongoDatabase = null;
lastSessionFetch = -1L;
} catch (InterruptedException e) {
t.interrupt();
throw new ManifoldCFException("Interrupted: " + e.getMessage(), e, ManifoldCFException.INTERRUPTED);
} catch (RemoteException e) {
Throwable e2 = e.getCause();
if (e2 instanceof InterruptedException || e2 instanceof InterruptedIOException)
throw new ManifoldCFException(e2.getMessage(), e2, ManifoldCFException.INTERRUPTED);
client = null;
mongoDatabase = null;
lastSessionFetch = -1L;
// Treat this as a transient problem
Logging.connectors.warn("MongoDB: Transient remote exception closing session: " + e.getMessage(), e);
}
}
username = null;
password = null;
host = null;
port = null;
database = null;
collection = null;
}
/**
* This method creates a new MongoDB Session for a MongoDB repository,
*
* @param configParams is the set of configuration parameters, which in this case
* describe the target, basic auth configuration, etc.
*/
@Override
public void connect(ConfigParams configParams) {
super.connect(configParams);
username = params.getParameter(MongodbOutputConfig.USERNAME_PARAM);
password = params.getParameter(MongodbOutputConfig.PASSWORD_PARAM);
host = params.getParameter(MongodbOutputConfig.HOST_PARAM);
port = params.getParameter(MongodbOutputConfig.PORT_PARAM);
database = params.getParameter(MongodbOutputConfig.DATABASE_PARAM);
collection = params.getParameter(MongodbOutputConfig.COLLECTION_PARAM);
}
/**
* Test the connection. Returns a string describing the connection integrity.
*
* @return the connection's status as a displayable string.
*/
@Override
public String check() throws ManifoldCFException {
try {
checkConnection();
return super.check();
} catch (ServiceInterruption e) {
return "Connection temporarily failed: " + e.getMessage();
} catch (ManifoldCFException e) {
return "Connection failed: " + e.getMessage();
}
}
/**
* Set up a session
*/
protected void getSession() throws ManifoldCFException, ServiceInterruption {
// Check for parameter validity
if (StringUtils.isEmpty(database))
throw new ManifoldCFException("Parameter " + MongodbOutputConfig.DATABASE_PARAM + " required but not set");
if (StringUtils.isEmpty(collection))
throw new ManifoldCFException("Parameter " + MongodbOutputConfig.COLLECTION_PARAM + " required but not set");
long currentTime;
GetSessionThread t = new GetSessionThread();
try {
t.start();
t.join();
Throwable thr = t.getException();
if (thr != null) {
if (thr instanceof ManifoldCFException)
throw new ManifoldCFException("MongoDB: Error during getting a new session: " + thr.getMessage(), thr);
else if (thr instanceof RemoteException)
throw (RemoteException) thr;
else if (thr instanceof MongoException)
throw new ManifoldCFException("MongoDB: Error during getting a new session: " + thr.getMessage(), thr);
else if (thr instanceof java.net.ConnectException)
throw new ManifoldCFException("MongoDB: Error Connecting to MongoDB is mongod running? : " + thr.getMessage(), thr);
else
throw (Error) thr;
}
} catch (InterruptedException e) {
t.interrupt();
throw new ManifoldCFException("Interrupted: " + e.getMessage(), e, ManifoldCFException.INTERRUPTED);
} catch (RemoteException e) {
Throwable e2 = e.getCause();
if (e2 instanceof InterruptedException || e2 instanceof InterruptedIOException)
throw new ManifoldCFException(e2.getMessage(), e2, ManifoldCFException.INTERRUPTED);
// Treat this as a transient problem
Logging.connectors.warn("MongoDB: Transient remote exception creating session: " + e.getMessage(), e);
currentTime = System.currentTimeMillis();
throw new ServiceInterruption(e.getMessage(), currentTime + 60000L);
}
lastSessionFetch = System.currentTimeMillis();
}
/**
* Release the session, if it's time.
*/
protected void releaseCheck() throws ManifoldCFException {
if (lastSessionFetch == -1L)
return;
long currentTime = System.currentTimeMillis();
if (currentTime >= lastSessionFetch + timeToRelease) {
DestroySessionThread t = new DestroySessionThread();
try {
t.start();
t.join();
Throwable thr = t.getException();
if (thr != null) {
if (thr instanceof RemoteException)
throw (RemoteException) thr;
else
throw (Error) thr;
}
client = null;
lastSessionFetch = -1L;
} catch (InterruptedException e) {
t.interrupt();
throw new ManifoldCFException("Interrupted: " + e.getMessage(), e, ManifoldCFException.INTERRUPTED);
} catch (RemoteException e) {
Throwable e2 = e.getCause();
if (e2 instanceof InterruptedException || e2 instanceof InterruptedIOException)
throw new ManifoldCFException(e2.getMessage(), e2, ManifoldCFException.INTERRUPTED);
client = null;
lastSessionFetch = -1L;
// Treat this as a transient problem
Logging.connectors.warn("MongoDB: Transient remote exception closing session: " + e.getMessage(), e);
}
}
}
protected void checkConnection() throws ManifoldCFException, ServiceInterruption {
while (true) {
boolean noSession = (client == null);
getSession();
long currentTime;
CheckConnectionThread t = new CheckConnectionThread();
try {
t.start();
t.join();
Throwable thr = t.getException();
if (thr != null) {
if (thr instanceof RemoteException)
throw (RemoteException) thr;
else if (thr instanceof ConnectException)
throw new ManifoldCFException("MongoDB: Error during checking connection: is Mongod running?" + thr.getMessage(), thr);
else if (thr instanceof MongoException)
throw new ManifoldCFException("MongoDB: Error during checking connection: " + thr.getMessage(), thr);
else if (thr instanceof ManifoldCFException)
throw new ManifoldCFException(thr.getMessage(), thr);
else
throw (Error) thr;
}
return;
} catch (InterruptedException e) {
t.interrupt();
throw new ManifoldCFException("Interrupted: " + e.getMessage(), e, ManifoldCFException.INTERRUPTED);
} catch (RemoteException e) {
Throwable e2 = e.getCause();
if (e2 instanceof InterruptedException || e2 instanceof InterruptedIOException)
throw new ManifoldCFException(e2.getMessage(), e2, ManifoldCFException.INTERRUPTED);
if (noSession) {
currentTime = System.currentTimeMillis();
throw new ServiceInterruption("Transient error connecting to filenet service: " + e.getMessage(),
currentTime + 60000L);
}
client = null;
lastSessionFetch = -1L;
continue;
}
}
}
protected class GetSessionThread extends Thread {
protected Throwable exception = null;
public GetSessionThread() {
super();
setDaemon(true);
}
public void run() {
try {
// Create a session
if (client == null) {
if (StringUtils.isEmpty(host) && StringUtils.isEmpty(port)) {
try {
client = new MongoClient();
mongoDatabase = client.getDB(database);
} catch (UnknownHostException ex) {
throw new ManifoldCFException("MongoDB: Default host is not found. Is mongod process running?" + ex.getMessage(), ex);
}
} else if (!StringUtils.isEmpty(host) && StringUtils.isEmpty(port)) {
try {
client = new MongoClient(host);
mongoDatabase = client.getDB(database);
} catch (UnknownHostException ex) {
throw new ManifoldCFException("MongoDB: Given host information is not valid or mongod process doesn't run" + ex.getMessage(), ex);
}
} else if (!StringUtils.isEmpty(host) && !StringUtils.isEmpty(port)) {
try {
int integerPort = Integer.parseInt(port);
client = new MongoClient(host, integerPort);
mongoDatabase = client.getDB(database);
} catch (UnknownHostException ex) {
throw new ManifoldCFException("MongoDB: Given information is not valid or mongod process doesn't run" + ex.getMessage(), ex);
} catch (NumberFormatException ex) {
throw new ManifoldCFException("MongoDB: Given port is not a valid number. " + ex.getMessage(), ex);
}
} else if (StringUtils.isEmpty(host) && !StringUtils.isEmpty(port)) {
try {
int integerPort = Integer.parseInt(port);
client = new MongoClient("localhost", integerPort);
mongoDatabase = client.getDB(database);
} catch (UnknownHostException e) {
Logging.connectors.warn("MongoDB: Given information is not valid or mongod process doesn't run" + e.getMessage(), e);
throw new ManifoldCFException("MongoDB: Given information is not valid or mongod process doesn't run" + e.getMessage(), e);
} catch (NumberFormatException e) {
Logging.connectors.warn("MongoDB: Given port is not valid number. " + e.getMessage(), e);
throw new ManifoldCFException("MongoDB: Given port is not valid number. " + e.getMessage(), e);
}
}
if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
boolean auth = mongoDatabase.authenticate(username, password.toCharArray());
if (!auth) {
Logging.connectors.warn("MongoDB:Authentication Error! Given database username and password doesn't match for the database given.");
throw new ManifoldCFException("MongoDB: Given database username and password doesn't match for the database given.");
} else {
if (Logging.connectors.isDebugEnabled()) {
Logging.connectors.debug("MongoDB: Username = '" + username + "'");
Logging.connectors.debug("MongoDB: Password exists");
}
}
}
}
} catch (Throwable e) {
this.exception = e;
}
}
public Throwable getException() {
return exception;
}
}
protected class CheckConnectionThread extends Thread {
protected Throwable exception = null;
public CheckConnectionThread() {
super();
setDaemon(true);
}
public void run() {
try {
if (client != null) {
DBTCPConnector dbtcpConnector = client.getConnector();
DBPortPool dbPortPool = dbtcpConnector.getDBPortPool(client.getAddress());
DBPort dbPort = dbPortPool.get();
dbPort.ensureOpen();
client = null;
}
} catch (Throwable e) {
Logging.connectors.warn("MongoDB: Error checking repository: " + e.getMessage(), e);
this.exception = e;
}
}
public Throwable getException() {
return exception;
}
}
protected class DestroySessionThread extends Thread {
protected Throwable exception = null;
public DestroySessionThread() {
super();
setDaemon(true);
}
public void run() {
try {
client = null;
mongoDatabase = null;
} catch (Throwable e) {
this.exception = e;
}
}
public Throwable getException() {
return exception;
}
}
@Override
public int addOrReplaceDocumentWithException(String documentURI, VersionContext pipelineDescription,
RepositoryDocument document, String authorityNameString, IOutputAddActivity activities)
throws ManifoldCFException, ServiceInterruption, IOException {
getSession();
//to get an exception if write fails
client.setWriteConcern(WriteConcern.SAFE);
long startTime = System.currentTimeMillis();
String resultDescription = StringUtils.EMPTY;
// Standard document fields
String fileName = document.getFileName();
Long binaryLength = document.getBinaryLength();
String mimeType = document.getMimeType();
Date creationDate = document.getCreatedDate();
Date lastModificationDate = document.getModifiedDate();
Date indexingDate = document.getIndexingDate();
// check if the repository connector includes the content path
String primaryPath = StringUtils.EMPTY;
List<String> sourcePath = document.getSourcePath();
if (sourcePath != null && !sourcePath.isEmpty()) {
primaryPath = sourcePath.get(0);
}
// Content Stream
InputStream inputStream = document.getBinaryStream();
try {
byte[] bytes = IOUtils.toByteArray(inputStream);
Binary content = new Binary(bytes);
DBCollection mongoCollection = mongoDatabase.getCollection(collection);
BasicDBObject newDocument = new BasicDBObject();
newDocument.append("fileName", fileName)
.append("creationDate", creationDate)
.append("lastModificationDate", lastModificationDate)
.append("indexingDate", indexingDate)
.append("binaryLength", binaryLength)
.append("documentURI", documentURI)
.append("mimeType", mimeType)
.append("content", content)
.append("primaryPath", primaryPath);
// Rest of the fields
Iterator<String> i = document.getFields();
while (i.hasNext()) {
String fieldName = i.next();
Date[] dateFieldValues = document.getFieldAsDates(fieldName);
if (dateFieldValues != null) {
newDocument.append(fieldName, dateFieldValues);
} else {
String[] fieldValues = document.getFieldAsStrings(fieldName);
newDocument.append(fieldName, fieldValues);
}
}
BasicDBObject searchQuery = new BasicDBObject().append("documentURI", documentURI);
DBCursor cursor = mongoCollection.find(searchQuery);
Long numberOfDocumentsBeforeInsert = mongoCollection.count();
WriteResult result;
if (cursor.count() > 0) {
result = mongoCollection.update(searchQuery, newDocument);
} else {
result = mongoCollection.insert(newDocument);
}
//result.getLastError().get("err") == null
//To get the number of documents indexed i.e. tne number of documents inserted or updated
Long numberOfDocumentsAfterInsert = mongoCollection.count();
Long numberOfDocumentsInserted = numberOfDocumentsAfterInsert - numberOfDocumentsBeforeInsert;
Long numberOfDocumentsIndexed = (numberOfDocumentsInserted != 0) ? numberOfDocumentsInserted : result.getN();
Logging.connectors.info("Number of documents indexed : " + numberOfDocumentsIndexed);
//check if a document is inserted or updated (numberOfDocumentsInserted > 0) || (result.getN() > 0)
if (numberOfDocumentsIndexed > 0) {
resultDescription = DOCUMENT_STATUS_ACCEPTED_DESC;
return DOCUMENT_STATUS_ACCEPTED;
} else {
resultDescription = DOCUMENT_STATUS_REJECTED_DESC;
return DOCUMENT_STATUS_REJECTED;
}
} catch (MongoException e) {
resultDescription = DOCUMENT_STATUS_REJECTED_DESC;
Logging.connectors.info("MongoDB: Error inserting or updating : " + e.getMessage());
throw new ManifoldCFException(e.getMessage(), e);
} catch (IOException e) {
resultDescription = DOCUMENT_STATUS_REJECTED_DESC;
Logging.connectors.info("Error converting the input stream to byte array : " + e.getMessage());
throw new ManifoldCFException(e.getMessage(), e);
} catch (Exception e) {
resultDescription = DOCUMENT_STATUS_REJECTED_DESC;
Logging.connectors.info("Error encoding content : " + e.getMessage());
throw new ManifoldCFException(e.getMessage(), e);
} finally {
if (inputStream != null) {
inputStream.close();
}
activities.recordActivity(startTime, ACTIVITY_INJECTION, document.getBinaryLength(), documentURI, resultDescription,
resultDescription);
}
}
@Override
public void removeDocument(String documentURI, String outputDescription, IOutputRemoveActivity activities)
throws ManifoldCFException, ServiceInterruption {
getSession();
long startTime = System.currentTimeMillis();
String resultDescription = StringUtils.EMPTY;
try {
DBCollection mongoCollection = mongoDatabase.getCollection(collection);
BasicDBObject query = new BasicDBObject();
query.append("documentURI", documentURI);
WriteResult result = mongoCollection.remove(query);
Logging.connectors.info("Number of documents deleted : " + result.getN());
if (result.getN() > 0) {
resultDescription = DOCUMENT_DELETION_STATUS_ACCEPTED;
} else {
resultDescription = DOCUMENT_DELETION_STATUS_REJECTED;
}
} catch (Exception e) {
resultDescription = DOCUMENT_DELETION_STATUS_REJECTED;
throw new ManifoldCFException(e.getMessage(), e);
} finally {
activities.recordActivity(startTime, ACTIVITY_DELETE, null, documentURI, null, resultDescription);
}
}
}
| apache-2.0 |
mrijke/druid | extensions-core/stats/src/main/java/io/druid/query/aggregation/variance/VarianceAggregatorFactory.java | 8530 | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.query.aggregation.variance;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.google.common.base.Preconditions;
import com.metamx.common.IAE;
import com.metamx.common.StringUtils;
import io.druid.query.aggregation.Aggregator;
import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.aggregation.AggregatorFactoryNotMergeableException;
import io.druid.query.aggregation.Aggregators;
import io.druid.query.aggregation.BufferAggregator;
import io.druid.segment.ColumnSelectorFactory;
import io.druid.segment.ObjectColumnSelector;
import org.apache.commons.codec.binary.Base64;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
/**
*/
@JsonTypeName("variance")
public class VarianceAggregatorFactory extends AggregatorFactory
{
protected static final byte CACHE_TYPE_ID = 16;
protected final String fieldName;
protected final String name;
protected final String estimator;
private final String inputType;
protected final boolean isVariancePop;
@JsonCreator
public VarianceAggregatorFactory(
@JsonProperty("name") String name,
@JsonProperty("fieldName") String fieldName,
@JsonProperty("estimator") String estimator,
@JsonProperty("inputType") String inputType
)
{
Preconditions.checkNotNull(name, "Must have a valid, non-null aggregator name");
Preconditions.checkNotNull(fieldName, "Must have a valid, non-null fieldName");
this.name = name;
this.fieldName = fieldName;
this.estimator = estimator;
this.isVariancePop = VarianceAggregatorCollector.isVariancePop(estimator);
this.inputType = inputType == null ? "float" : inputType;
}
public VarianceAggregatorFactory(String name, String fieldName)
{
this(name, fieldName, null, null);
}
@Override
public String getTypeName()
{
return "variance";
}
@Override
public int getMaxIntermediateSize()
{
return VarianceAggregatorCollector.getMaxIntermediateSize();
}
@Override
public Aggregator factorize(ColumnSelectorFactory metricFactory)
{
ObjectColumnSelector selector = metricFactory.makeObjectColumnSelector(fieldName);
if (selector == null) {
return Aggregators.noopAggregator();
}
if ("float".equalsIgnoreCase(inputType)) {
return new VarianceAggregator.FloatVarianceAggregator(
name,
metricFactory.makeFloatColumnSelector(fieldName)
);
} else if ("long".equalsIgnoreCase(inputType)) {
return new VarianceAggregator.LongVarianceAggregator(
name,
metricFactory.makeLongColumnSelector(fieldName)
);
} else if ("variance".equalsIgnoreCase(inputType)) {
return new VarianceAggregator.ObjectVarianceAggregator(name, selector);
}
throw new IAE(
"Incompatible type for metric[%s], expected a float, long or variance, got a %s", fieldName, inputType
);
}
@Override
public BufferAggregator factorizeBuffered(ColumnSelectorFactory metricFactory)
{
ObjectColumnSelector selector = metricFactory.makeObjectColumnSelector(fieldName);
if (selector == null) {
return Aggregators.noopBufferAggregator();
}
if ("float".equalsIgnoreCase(inputType)) {
return new VarianceBufferAggregator.FloatVarianceAggregator(
name,
metricFactory.makeFloatColumnSelector(fieldName)
);
} else if ("long".equalsIgnoreCase(inputType)) {
return new VarianceBufferAggregator.LongVarianceAggregator(
name,
metricFactory.makeLongColumnSelector(fieldName)
);
} else if ("variance".equalsIgnoreCase(inputType)) {
return new VarianceBufferAggregator.ObjectVarianceAggregator(name, selector);
}
throw new IAE(
"Incompatible type for metric[%s], expected a float, long or variance, got a %s", fieldName, inputType
);
}
@Override
public AggregatorFactory getCombiningFactory()
{
return new VarianceFoldingAggregatorFactory(name, name, estimator);
}
@Override
public List<AggregatorFactory> getRequiredColumns()
{
return Arrays.<AggregatorFactory>asList(new VarianceAggregatorFactory(fieldName, fieldName, estimator, inputType));
}
@Override
public AggregatorFactory getMergingFactory(AggregatorFactory other) throws AggregatorFactoryNotMergeableException
{
if (Objects.equals(getName(), other.getName()) && this.getClass() == other.getClass()) {
return getCombiningFactory();
} else {
throw new AggregatorFactoryNotMergeableException(this, other);
}
}
@Override
public Comparator getComparator()
{
return VarianceAggregatorCollector.COMPARATOR;
}
@Override
public Object getAggregatorStartValue()
{
return new VarianceAggregatorCollector();
}
@Override
public Object combine(Object lhs, Object rhs)
{
return VarianceAggregatorCollector.combineValues(lhs, rhs);
}
@Override
public Object finalizeComputation(Object object)
{
return ((VarianceAggregatorCollector) object).getVariance(isVariancePop);
}
@Override
public Object deserialize(Object object)
{
if (object instanceof byte[]) {
return VarianceAggregatorCollector.from(ByteBuffer.wrap((byte[]) object));
} else if (object instanceof ByteBuffer) {
return VarianceAggregatorCollector.from((ByteBuffer) object);
} else if (object instanceof String) {
return VarianceAggregatorCollector.from(
ByteBuffer.wrap(Base64.decodeBase64(StringUtils.toUtf8((String) object)))
);
}
return object;
}
@JsonProperty
public String getFieldName()
{
return fieldName;
}
@Override
@JsonProperty
public String getName()
{
return name;
}
@JsonProperty
public String getEstimator()
{
return estimator;
}
@JsonProperty
public String getInputType()
{
return inputType;
}
@Override
public List<String> requiredFields()
{
return Arrays.asList(fieldName);
}
@Override
public byte[] getCacheKey()
{
byte[] fieldNameBytes = StringUtils.toUtf8(fieldName);
byte[] inputTypeBytes = StringUtils.toUtf8(inputType);
return ByteBuffer.allocate(2 + fieldNameBytes.length + 1 + inputTypeBytes.length)
.put(CACHE_TYPE_ID)
.put(isVariancePop ? (byte) 1 : 0)
.put(fieldNameBytes)
.put((byte) 0xFF)
.put(inputTypeBytes)
.array();
}
@Override
public String toString()
{
return getClass().getSimpleName() + "{" +
"fieldName='" + fieldName + '\'' +
", name='" + name + '\'' +
", isVariancePop='" + isVariancePop + '\'' +
", inputType='" + inputType + '\'' +
'}';
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
VarianceAggregatorFactory that = (VarianceAggregatorFactory) o;
if (!Objects.equals(name, that.name)) {
return false;
}
if (!Objects.equals(isVariancePop, that.isVariancePop)) {
return false;
}
if (!Objects.equals(inputType, that.inputType)) {
return false;
}
return true;
}
@Override
public int hashCode()
{
int result = fieldName.hashCode();
result = 31 * result + Objects.hashCode(name);
result = 31 * result + Objects.hashCode(isVariancePop);
result = 31 * result + Objects.hashCode(inputType);
return result;
}
}
| apache-2.0 |
DieBauer/flink | flink-runtime/src/main/java/org/apache/flink/runtime/minicluster/MiniClusterConfiguration.java | 8084 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.minicluster;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.ConfigConstants;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.TaskManagerOptions;
import org.apache.flink.runtime.akka.AkkaUtils;
import org.apache.flink.runtime.util.EnvironmentInformation;
import scala.concurrent.duration.FiniteDuration;
import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;
public class MiniClusterConfiguration {
private final Configuration config;
private boolean singleRpcService = true;
private int numJobManagers = 1;
private int numTaskManagers = 1;
private int numResourceManagers = 1;
private String commonBindAddress;
private long managedMemoryPerTaskManager = -1;
// ------------------------------------------------------------------------
// Construction
// ------------------------------------------------------------------------
public MiniClusterConfiguration() {
this.config = new Configuration();
}
public MiniClusterConfiguration(Configuration config) {
checkNotNull(config);
this.config = new Configuration(config);
}
// ------------------------------------------------------------------------
// setters
// ------------------------------------------------------------------------
public void addConfiguration(Configuration config) {
checkNotNull(config, "configuration must not be null");
this.config.addAll(config);
}
public void setUseSingleRpcService() {
this.singleRpcService = true;
}
public void setUseRpcServicePerComponent() {
this.singleRpcService = false;
}
public void setNumJobManagers(int numJobManagers) {
checkArgument(numJobManagers >= 1, "must have at least one JobManager");
this.numJobManagers = numJobManagers;
}
public void setNumTaskManagers(int numTaskManagers) {
checkArgument(numTaskManagers >= 1, "must have at least one TaskManager");
this.numTaskManagers = numTaskManagers;
}
public void setNumResourceManagers(int numResourceManagers) {
checkArgument(numResourceManagers >= 1, "must have at least one ResourceManager");
this.numResourceManagers = numResourceManagers;
}
public void setNumTaskManagerSlots(int numTaskSlots) {
checkArgument(numTaskSlots >= 1, "must have at least one task slot per TaskManager");
this.config.setInteger(ConfigConstants.TASK_MANAGER_NUM_TASK_SLOTS, numTaskSlots);
}
public void setCommonRpcBindAddress(String bindAddress) {
checkNotNull(bindAddress, "bind address must not be null");
this.commonBindAddress = bindAddress;
}
public void setManagedMemoryPerTaskManager(long managedMemoryPerTaskManager) {
checkArgument(managedMemoryPerTaskManager > 0, "must have more than 0 MB of memory for the TaskManager.");
this.managedMemoryPerTaskManager = managedMemoryPerTaskManager;
}
// ------------------------------------------------------------------------
// getters
// ------------------------------------------------------------------------
public boolean getUseSingleRpcSystem() {
return singleRpcService;
}
public int getNumJobManagers() {
return numJobManagers;
}
public int getNumTaskManagers() {
return numTaskManagers;
}
public int getNumResourceManagers() {
return numResourceManagers;
}
public int getNumSlotsPerTaskManager() {
return config.getInteger(ConfigConstants.TASK_MANAGER_NUM_TASK_SLOTS, 1);
}
public String getJobManagerBindAddress() {
return commonBindAddress != null ?
commonBindAddress :
config.getString(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY, "localhost");
}
public String getTaskManagerBindAddress() {
return commonBindAddress != null ?
commonBindAddress :
config.getString(ConfigConstants.TASK_MANAGER_HOSTNAME_KEY, "localhost");
}
public String getResourceManagerBindAddress() {
return commonBindAddress != null ?
commonBindAddress :
config.getString(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY, "localhost"); // TODO: Introduce proper configuration constant for the resource manager hostname
}
public Time getRpcTimeout() {
FiniteDuration duration = AkkaUtils.getTimeout(config);
return Time.of(duration.length(), duration.unit());
}
public long getManagedMemoryPerTaskManager() {
return getOrCalculateManagedMemoryPerTaskManager();
}
// ------------------------------------------------------------------------
// utils
// ------------------------------------------------------------------------
public Configuration generateConfiguration() {
Configuration newConfiguration = new Configuration(config);
// set the memory
long memory = getOrCalculateManagedMemoryPerTaskManager();
newConfiguration.setLong(TaskManagerOptions.MANAGED_MEMORY_SIZE, memory);
return newConfiguration;
}
@Override
public String toString() {
return "MiniClusterConfiguration {" +
"singleRpcService=" + singleRpcService +
", numJobManagers=" + numJobManagers +
", numTaskManagers=" + numTaskManagers +
", numResourceManagers=" + numResourceManagers +
", commonBindAddress='" + commonBindAddress + '\'' +
", config=" + config +
'}';
}
/**
* Get or calculate the managed memory per task manager. The memory is calculated in the
* following order:
*
* 1. Return {@link #managedMemoryPerTaskManager} if set
* 2. Return config.getInteger(ConfigConstants.TASK_MANAGER_MEMORY_SIZE_KEY) if set
* 3. Distribute the available free memory equally among all components (JMs, RMs and TMs) and
* calculate the managed memory from the share of memory for a single task manager.
*
* @return
*/
private long getOrCalculateManagedMemoryPerTaskManager() {
if (managedMemoryPerTaskManager == -1) {
// no memory set in the mini cluster configuration
long memorySize = config.getLong(TaskManagerOptions.MANAGED_MEMORY_SIZE);
// we could probably use config.contains() but the previous implementation compared to
// the default (-1) thus allowing the user to explicitly specify this as well
// -> don't change this behaviour now
if (memorySize == TaskManagerOptions.MANAGED_MEMORY_SIZE.defaultValue()) {
// no memory set in the flink configuration
// share the available memory among all running components
float memoryFraction = config.getFloat(TaskManagerOptions.MANAGED_MEMORY_FRACTION);
long networkBuffersMemory =
(long) config.getInteger(TaskManagerOptions.NETWORK_NUM_BUFFERS) *
(long) config.getInteger(TaskManagerOptions.MEMORY_SEGMENT_SIZE);
long freeMemory = EnvironmentInformation.getSizeOfFreeHeapMemoryWithDefrag();
// we assign each component the same amount of free memory
// (might be a bit of overkill for the JMs and RMs)
long memoryPerComponent = freeMemory / (numTaskManagers + numResourceManagers + numJobManagers);
// subtract the network buffer memory
long memoryMinusNetworkBuffers = memoryPerComponent - networkBuffersMemory;
// calculate the managed memory size
long managedMemoryBytes = (long) (memoryMinusNetworkBuffers * memoryFraction);
return managedMemoryBytes >>> 20;
} else {
return memorySize;
}
} else {
return managedMemoryPerTaskManager;
}
}
}
| apache-2.0 |
SourceStudyNotes/log4j2 | src/main/java/org/apache/logging/log4j/message/ParameterizedMessageFactory.java | 1793 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.message;
/**
* Enables use of <code>{}</code> parameter markers in message strings.
* <p>
* Creates {@link ParameterizedMessage} instances for {@link #newMessage(String, Object...)}.
* </p>
* <p>
* This class is immutable.
* </p>
*/
public final class ParameterizedMessageFactory extends AbstractMessageFactory {
/**
* Instance of StringFormatterMessageFactory.
*/
public static final ParameterizedMessageFactory INSTANCE = new ParameterizedMessageFactory();
private static final long serialVersionUID = 1L;
/**
* Creates {@link ParameterizedMessage} instances.
*
* @param message The message pattern.
* @param params The message parameters.
* @return The Message.
*
* @see MessageFactory#newMessage(String, Object...)
*/
@Override
public Message newMessage(final String message, final Object... params) {
return new ParameterizedMessage(message, params);
}
}
| apache-2.0 |
madhawa-gunasekara/product-ei | integration/mediation-tests/tests-common/admin-clients/src/main/java/org/wso2/esb/integration/common/clients/rest/api/RestApiAdminClient.java | 5851 | /*
*Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*WSO2 Inc. licenses this file to you under the Apache License,
*Version 2.0 (the "License"); you may not use this file except
*in compliance with the License.
*You may obtain a copy of the License at
*
*http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing,
*software distributed under the License is distributed on an
*"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
*KIND, either express or implied. See the License for the
*specific language governing permissions and limitations
*under the License.
*/
package org.wso2.esb.integration.common.clients.rest.api;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.rest.api.stub.RestApiAdminAPIException;
import org.wso2.carbon.rest.api.stub.RestApiAdminStub;
import org.wso2.carbon.rest.api.stub.types.carbon.APIData;
import org.wso2.carbon.rest.api.stub.types.carbon.ResourceData;
import org.wso2.esb.integration.common.clients.client.utils.AuthenticateStub;
import java.rmi.RemoteException;
public class RestApiAdminClient {
private static final Log log = LogFactory.getLog(RestApiAdminClient.class);
private RestApiAdminStub restApiAdminStub;
private final String serviceName = "RestApiAdmin";
public RestApiAdminClient(String backEndUrl, String sessionCookie) throws AxisFault {
String endPoint = backEndUrl + serviceName;
restApiAdminStub = new RestApiAdminStub(endPoint);
AuthenticateStub.authenticateStub(sessionCookie, restApiAdminStub);
}
public RestApiAdminClient(String backEndUrl, String userName, String password) throws AxisFault {
String endPoint = backEndUrl + serviceName;
restApiAdminStub = new RestApiAdminStub(endPoint);
AuthenticateStub.authenticateStub(userName, password, restApiAdminStub);
}
public boolean add(OMElement apiData) throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.addApiFromString(apiData.toString());
}
public boolean deleteApi(String apiName) throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.deleteApi(apiName);
}
public boolean deleteApiForTenant(String apiName, String tenant) throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.deleteApiForTenant(apiName, tenant);
}
public String[] getApiNames() throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.getApiNames();
}
public String getServerContext() throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.getServerContext();
}
public boolean addAPI(APIData apiData) throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.addApi(apiData);
}
public boolean addAPIFromTenant(String apiData, String tenantDomain)
throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.addApiForTenant(apiData, tenantDomain);
}
public APIData getAPIbyName(String apiName) throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.getApiByName(apiName);
}
public APIData getAPIForTenantByName(String apiName, String tenantDomain)
throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.getApiForTenant(apiName, tenantDomain);
}
public boolean updateAPIFromString(String apiName, String updateData)
throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.updateApiFromString(apiName, updateData);
}
public boolean updateAPIFromAPIData(String apiName, APIData apiData)
throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.updateApi(apiName, apiData);
}
public boolean updateAPIForTenant(String apiName, String updateData, String tenant)
throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.updateApiForTenant(apiName, updateData, tenant);
}
public void deleteAllApis() throws RestApiAdminAPIException, RemoteException {
restApiAdminStub.deleteAllApi();
}
public int getAPICount() throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.getAPICount();
}
public String getAPISource(APIData apiData) throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.getApiSource(apiData);
}
public String[] getAPISequences() throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.getSequences();
}
public String enableStatisticsForAPI(String apiName) throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.enableStatistics(apiName);
}
public String disableStatisticsForAPI(String apiName) throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.disableStatistics(apiName);
}
public String enableTracingForAPI(String apiName) throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.enableTracing(apiName);
}
public String disableTracingForAPI(String apiName) throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.disableTracing(apiName);
}
public APIData[] getAPIList(int page, int count) throws RestApiAdminAPIException, RemoteException{
return restApiAdminStub.getAPIsForListing(page,count);
}
public String getAPIResource(ResourceData resourceData) throws RestApiAdminAPIException, RemoteException {
return restApiAdminStub.getResourceSource(resourceData);
}
}
| apache-2.0 |
nsivabalan/ambry | ambry-api/src/main/java/com.github.ambry/config/ReplicationConfig.java | 4816 | /**
* Copyright 2016 LinkedIn Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package com.github.ambry.config;
/**
* The configs for the replication layer
*/
public class ReplicationConfig {
/**
* The factory class the replication uses to creates its tokens
*/
@Config("replication.token.factory")
@Default("com.github.ambry.store.StoreFindTokenFactory")
public final String replicationTokenFactory;
/**
* The number of replica threads on each server that runs the replication protocol for intra dc replication
*/
@Config("replication.no.of.intra.dc.replica.threads")
@Default("1")
public final int replicationNumOfIntraDCReplicaThreads;
/**
* The number of replica threads on each server that runs the replication protocol for inter dc replication
*/
@Config("replication.no.of.inter.dc.replica.threads")
@Default("1")
public final int replicationNumOfInterDCReplicaThreads;
/**
* The timeout to get a connection checkout from the connection pool for replication
*/
@Config("replication.connection.pool.checkout.timeout.ms")
@Default("5000")
public final int replicationConnectionPoolCheckoutTimeoutMs;
/**
* The flush interval for persisting the replica tokens to disk
*/
@Config("replication.token.flush.interval.seconds")
@Default("300")
public final int replicationTokenFlushIntervalSeconds;
/**
* The initial delay to start the replica token flush thread
*/
@Config("replication.token.flush.delay.seconds")
@Default("5")
public final int replicationTokenFlushDelaySeconds;
/**
* The fetch size is an approximate total size that a remote server would return on a fetch request.
* This is not guaranteed to be always obeyed. For example, if a single blob is larger than the fetch size
* the entire blob would be returned
*/
@Config("replication.fetch.size.in.bytes")
@Default("1048576")
public final long replicationFetchSizeInBytes;
/**
* The time for which replication waits between replication of remote replicas of a partition
*/
@Config("replication.wait.time.between.replicas.ms")
@Default("1000")
public final int replicaWaitTimeBetweenReplicasMs;
/**
* The max lag above which replication does not wait between replicas. A larger value would slow down replication
* while reduces the chance of conflicts with direct puts. A smaller value would speed up replication but
* increase the chance of conflicts with direct puts
*/
@Config("replication.max.lag.for.wait.time.in.bytes")
@Default("5242880")
public final long replicationMaxLagForWaitTimeInBytes;
/**
* Whether message stream should be tested for validity so that only valid ones are considered during replication
*/
@Config("replication.validate.message.stream")
@Default("false")
public final boolean replicationValidateMessageStream;
public ReplicationConfig(VerifiableProperties verifiableProperties) {
replicationTokenFactory =
verifiableProperties.getString("replication.token.factory", "com.github.ambry.store.StoreFindTokenFactory");
replicationNumOfIntraDCReplicaThreads =
verifiableProperties.getInt("replication.no.of.intra.dc.replica.threads", 1);
replicationNumOfInterDCReplicaThreads =
verifiableProperties.getInt("replication.no.of.inter.dc.replica.threads", 1);
replicationConnectionPoolCheckoutTimeoutMs =
verifiableProperties.getIntInRange("replication.connection.pool.checkout.timeout.ms", 5000, 1000, 10000);
replicationTokenFlushIntervalSeconds =
verifiableProperties.getIntInRange("replication.token.flush.interval.seconds", 300, 5, Integer.MAX_VALUE);
replicationTokenFlushDelaySeconds =
verifiableProperties.getIntInRange("replication.token.flush.delay.seconds", 5, 1, Integer.MAX_VALUE);
replicationFetchSizeInBytes =
verifiableProperties.getLongInRange("replication.fetch.size.in.bytes", 1048576, 0, 20971520);
replicaWaitTimeBetweenReplicasMs =
verifiableProperties.getIntInRange("replication.wait.time.between.replicas.ms", 1000, 0, 1000000);
replicationMaxLagForWaitTimeInBytes =
verifiableProperties.getLongInRange("replication.max.lag.for.wait.time.in.bytes", 5242880, 0, 104857600);
replicationValidateMessageStream = verifiableProperties.getBoolean("replication.validate.message.stream", false);
}
}
| apache-2.0 |
google/dokka | core/testdata/java/InheritorLinks.java | 109 | public class InheritorLinks {
public static class Foo {
}
public static class Bar extends Foo {
}
}
| apache-2.0 |
nhudacin/xunit-converter | src/main/java/com/tw/xunit/model/mstest/RunInfo.java | 2361 | package com.tw.xunit.model.mstest;
/**
* Created by nhudacin on 5/13/2015.
*/
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
public class RunInfo {
@Attribute(required = false)
private String computerName;
@Attribute(required = false)
private String outcome;
@Attribute(required = false)
private String timestamp;
@Element(name = "Text", required = false)
private Text text;
public RunInfo() {
}
public RunInfo(String computerName, String outcome, String timestamp, Text text) {
this.computerName = computerName;
this.outcome = outcome;
this.timestamp = timestamp;
this.text = text;
}
public String getComputerName() {
return computerName;
}
public void setComputerName(String computerName) {
this.computerName = computerName;
}
public String getOutcome() {
return outcome;
}
public void setOutcome(String outcome) {
this.outcome = outcome;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public Text getText() {
return text;
}
public void setText(Text text) {
this.text = text;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RunInfo runInfo = (RunInfo) o;
if (computerName != null ? !computerName.equals(runInfo.computerName) : runInfo.computerName != null)
return false;
if (outcome != null ? !outcome.equals(runInfo.outcome) : runInfo.outcome != null) return false;
if (text != null ? !text.equals(runInfo.text) : runInfo.text != null) return false;
if (timestamp != null ? !timestamp.equals(runInfo.timestamp) : runInfo.timestamp != null) return false;
return true;
}
@Override
public int hashCode() {
int result = computerName != null ? computerName.hashCode() : 0;
result = 31 * result + (outcome != null ? outcome.hashCode() : 0);
result = 31 * result + (timestamp != null ? timestamp.hashCode() : 0);
result = 31 * result + (text != null ? text.hashCode() : 0);
return result;
}
}
| apache-2.0 |
spring-projects/spring-boot | spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/data/cassandra/CassandraRepositoriesAutoConfiguration.java | 2020 | /*
* Copyright 2012-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.data.cassandra;
import com.datastax.oss.driver.api.core.CqlSession;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.ConditionalOnRepositoryType;
import org.springframework.boot.autoconfigure.data.RepositoryType;
import org.springframework.context.annotation.Import;
import org.springframework.data.cassandra.repository.CassandraRepository;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
import org.springframework.data.cassandra.repository.support.CassandraRepositoryFactoryBean;
/**
* {@link EnableAutoConfiguration Auto-configuration} for Spring Data's Cassandra
* Repositories.
*
* @author Eddú Meléndez
* @since 1.3.0
* @see EnableCassandraRepositories
*/
@AutoConfiguration
@ConditionalOnClass({ CqlSession.class, CassandraRepository.class })
@ConditionalOnRepositoryType(store = "cassandra", type = RepositoryType.IMPERATIVE)
@ConditionalOnMissingBean(CassandraRepositoryFactoryBean.class)
@Import(CassandraRepositoriesRegistrar.class)
public class CassandraRepositoriesAutoConfiguration {
}
| apache-2.0 |