repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
EHJ-52n/SOS | hibernate/common/src/main/java/org/n52/sos/ds/hibernate/util/procedure/create/FileDescriptionCreationStrategy.java | 3890 | /*
* Copyright (C) 2012-2021 52°North Spatial Information Research GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* License version 2 and the aforementioned licenses.
*
* 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.
*/
package org.n52.sos.ds.hibernate.util.procedure.create;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import org.hibernate.Session;
import org.n52.series.db.beans.ProcedureEntity;
import org.n52.shetland.ogc.ows.exception.NoApplicableCodeException;
import org.n52.shetland.ogc.ows.exception.OwsExceptionReport;
import org.n52.shetland.ogc.sos.SosProcedureDescription;
import org.n52.shetland.util.StringHelper;
import org.n52.sos.ds.hibernate.util.procedure.HibernateProcedureCreationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Strings;
/**
* Strategy to create the {@link SosProcedureDescription} from a file.
*/
public class FileDescriptionCreationStrategy extends XmlStringDescriptionCreationStrategy {
private static final Logger LOGGER = LoggerFactory.getLogger(FileDescriptionCreationStrategy.class);
private static final String STANDARD = "standard";
@Override
public SosProcedureDescription<?> create(ProcedureEntity p, String descriptionFormat, Locale i18n,
HibernateProcedureCreationContext ctx, Session s) throws OwsExceptionReport {
try {
SosProcedureDescription<?> desc =
new SosProcedureDescription<>(readXml(read(p.getDescriptionFile(), ctx), ctx));
desc.setIdentifier(p.getIdentifier());
desc.setDescriptionFormat(p.getFormat().getFormat());
return desc;
} catch (IOException ex) {
throw new NoApplicableCodeException().causedBy(ex);
}
}
private InputStream getDocumentAsStream(String filename, HibernateProcedureCreationContext ctx) {
final StringBuilder builder = new StringBuilder();
// check if filename contains placeholder for configured
// sensor directory
String f = filename;
if (filename.startsWith(STANDARD)) {
f = filename.replace(STANDARD, "");
builder.append(ctx.getSensorDirectory());
builder.append("/");
}
builder.append(f);
LOGGER.debug("Procedure description file name '{}'!", filename);
return this.getClass().getResourceAsStream(builder.toString());
}
private String read(String path, HibernateProcedureCreationContext ctx) throws IOException {
InputStream stream = getDocumentAsStream(path, ctx);
return StringHelper.convertStreamToString(stream);
}
@Override
public boolean apply(ProcedureEntity p) {
return p != null && !Strings.isNullOrEmpty(p.getDescriptionFile());
}
}
| gpl-2.0 |
mvehar/zanata-server | functional-test/src/main/java/org/zanata/page/dashboard/dashboardsettings/DashboardAccountTab.java | 3747 | /*
* Copyright 2014, Red Hat, Inc. and individual contributors as indicated by the
* @author tags. See the copyright.txt file in the distribution for a full
* listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
* site: http://www.fsf.org.
*/
package org.zanata.page.dashboard.dashboardsettings;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.zanata.page.dashboard.DashboardBasePage;
/**
* @author Carlos Munoz <a href="mailto:camunoz@redhat.com">camunoz@redhat.com</a>
*/
@Slf4j
public class DashboardAccountTab extends DashboardBasePage {
public static final String INCORRECT_OLD_PASSWORD_ERROR =
"Old password is incorrect, please check and try again.";
public static final String FIELD_EMPTY_ERROR = "may not be empty";
public static final String PASSWORD_LENGTH_ERROR =
"size must be between 6 and 1024";
public static final String EMAIL_TAKEN_ERROR =
"This email address is already taken";
private By emailForm = By.id("email-update-form");
private By emailField = By.id("email-update-form:emailField:input:email");
// Use form and button tag to find the item, as its id is altered by jsf
private By updateEmailButton = By.tagName("button");
private By oldPasswordField = By.id("passwordChangeForm:oldPasswordField:input:oldPassword");
private By newPasswordField = By.id("passwordChangeForm:newPasswordField:input:newPassword");
private By changePasswordButton = By.cssSelector("button[id^='passwordChangeForm:changePasswordButton']");
public DashboardAccountTab(WebDriver driver) {
super(driver);
}
public DashboardAccountTab typeNewAccountEmailAddress(String emailAddress) {
log.info("Enter email {}", emailAddress);
readyElement(emailField).clear();
enterText(readyElement(emailField), emailAddress);
return new DashboardAccountTab(getDriver());
}
public DashboardAccountTab clickUpdateEmailButton() {
log.info("Click Update Email");
clickElement(readyElement(emailForm).findElement(updateEmailButton));
return new DashboardAccountTab(getDriver());
}
public DashboardAccountTab typeOldPassword(String oldPassword) {
log.info("Enter old password {}", oldPassword);
readyElement(oldPasswordField).clear();
enterText(readyElement(oldPasswordField), oldPassword);
return new DashboardAccountTab(getDriver());
}
public DashboardAccountTab typeNewPassword(String newPassword) {
log.info("Enter new password {}", newPassword);
readyElement(newPasswordField).clear();
enterText(readyElement(newPasswordField), newPassword);
return new DashboardAccountTab(getDriver());
}
public DashboardAccountTab clickUpdatePasswordButton() {
log.info("Click Update Password");
clickElement(changePasswordButton);
return new DashboardAccountTab(getDriver());
}
}
| gpl-2.0 |
frederikkaspar/Kaspar | src/mediawiki/event/CompletedListener.java | 92 | package mediawiki.event;
public interface CompletedListener {
public void completed();
}
| gpl-2.0 |
knabar/openmicroscopy | components/insight/SRC/org/openmicroscopy/shoola/agents/fsimporter/view/FailedImportDialog.java | 5672 | /*
*------------------------------------------------------------------------------
* Copyright (C) 2018 University of Dundee. All rights reserved.
*
*
* 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.
*
*------------------------------------------------------------------------------
*/
package org.openmicroscopy.shoola.agents.fsimporter.view;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import java.util.Iterator;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import org.openmicroscopy.shoola.agents.fsimporter.util.FileImportComponentI;
import org.openmicroscopy.shoola.util.file.ImportErrorObject;
import org.openmicroscopy.shoola.util.ui.UIUtilities;
/**
* A dialog for displaying the error logs for files which failed to import.
*
* @author Domink Lindner <a
* href="mailto:d.lindner@dundee.ac.uk">d.lindner@dundee.ac.uk</a>
*/
public class FailedImportDialog extends JDialog {
/** Holds the error logs (key: file name) */
private SortedMap<String, String> errors = new TreeMap<String, String>();
/** Maximum broken import files to list */
private final int MAX_ENTRIES = 50;
/**
* Create new instance
*
* @param owner
* The dialog owner
* @param components
* The failed imports
*/
public FailedImportDialog(JFrame owner,
Collection<FileImportComponentI> components) {
super(owner);
for (FileImportComponentI c : components) {
ImportErrorObject obj = c.getImportErrorObject();
errors.put(UIUtilities.formatPartialName(obj.getFile()
.getAbsolutePath(), 60), UIUtilities.printErrorText(obj
.getException()));
}
buildUI();
}
private void buildUI() {
setTitle("Failed imports");
JPanel con = new JPanel();
con.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
con.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.ipadx = 2;
c.ipady = 2;
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.NONE;
con.add(new JLabel("File:"), c);
String[] tmp = null;
if (errors.keySet().size() < MAX_ENTRIES) {
tmp = new String[errors.keySet().size()];
tmp = errors.keySet().toArray(tmp);
} else {
tmp = new String[MAX_ENTRIES + 1];
Iterator<String> it = errors.keySet().iterator();
for (int i = 0; i < MAX_ENTRIES; i++)
tmp[i] = it.next();
tmp[50] = "... and " + (errors.keySet().size() - MAX_ENTRIES) + " more.";
}
String selected = tmp[0];
final JComboBox<String> filesBox = new JComboBox<String>(tmp);
filesBox.setSelectedItem(selected);
c.gridx = 1;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
con.add(filesBox, c);
selected = errors.get(selected);
final JTextArea errorText = new JTextArea(20, 60);
errorText.setEditable(false);
errorText.setText(selected);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 2;
c.fill = GridBagConstraints.HORIZONTAL;
con.add(new JLabel("Error log:"), c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
c.fill = GridBagConstraints.BOTH;
final JScrollPane sp = new JScrollPane(errorText);
con.add(sp, c);
filesBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String sel = (String) filesBox.getSelectedItem();
String text = errors.get(sel);
errorText.setText(text != null ? text : "");
errorText.setCaretPosition(0);
}
});
final JButton close = new JButton("Close");
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 1;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.LAST_LINE_END;
c.fill = GridBagConstraints.NONE;
con.add(close, c);
close.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FailedImportDialog.this.dispose();
}
});
getContentPane().setLayout(new BorderLayout());
getContentPane().add(con, BorderLayout.CENTER);
pack();
errorText.setCaretPosition(0);
}
}
| gpl-2.0 |
klst-com/metasfresh | de.metas.adempiere.libero.libero/src/main/java/org/eevolution/model/validator/PP_Order_Node_Product.java | 1420 | package org.eevolution.model.validator;
/*
* #%L
* de.metas.adempiere.libero.libero
* %%
* Copyright (C) 2015 metas GmbH
* %%
* 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%
*/
import org.adempiere.ad.modelvalidator.annotations.ModelChange;
import org.adempiere.ad.modelvalidator.annotations.Validator;
import org.compiere.model.ModelValidator;
import org.compiere.util.Env;
import org.eevolution.model.I_PP_Order_Node_Product;
@Validator(I_PP_Order_Node_Product.class)
public class PP_Order_Node_Product
{
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE })
public void beforeSave(I_PP_Order_Node_Product nodeProduct)
{
if (nodeProduct.getQty().signum() == 0 && nodeProduct.isSubcontracting())
{
nodeProduct.setQty(Env.ONE);
}
}
}
| gpl-2.0 |
universsky/openjdk | langtools/test/tools/jdeps/VerboseFormat/use/indirect2/DontUseUnsafe3.java | 1130 | /*
* Copyright (c) 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 use.indirect2;
import use.unsafe.*;
public class DontUseUnsafe3 {
}
| gpl-2.0 |
kephale/java3d-core | src/classes/share/javax/media/j3d/TextureBin.java | 48529 | /*
* Copyright 1999-2008 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.media.j3d;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
/**
* The TextureBin manages a collection of TextureSetting objects.
* All objects in the TextureBin share the same Texture reference.
*/
//class TextureBin extends Object implements ObjectUpdate, NodeComponentUpdate {
class TextureBin extends Object implements ObjectUpdate {
TextureUnitStateRetained [] texUnitState = null;
// number of active texture unit
private int numActiveTexUnit;
/**
* The RenderBin for this object
*/
RenderBin renderBin = null;
/**
* The EnvironmentSet that this TextureBin resides
*/
EnvironmentSet environmentSet = null;
/**
* The AttributeBin that this TextureBin resides
*/
AttributeBin attributeBin = null;
/**
* The ShaderBin that this TextureBin resides
*/
ShaderBin shaderBin = null;
/**
* The references to the next and previous TextureBins in the
* list.
*/
TextureBin next = null;
TextureBin prev = null;
/**
* Oring of the equivalence bits for all appearance attrs under
* this renderBin
*/
int equivalent = 0;
/**
* If any of the texture reference in an appearance is frequently
* changable, then a separate TextureBin will be created for this
* appearance, and this TextureBin is marked as the sole user of
* this appearance, and app will be pointing to the appearance
* being referenced by this TextureBin. Otherwise, app is null
*/
AppearanceRetained app = null;
/**
* Sole user node component dirty mask. The first bit is reserved
* for node component reference dirty bit. It is set if any of the
* texture related node component reference in the appearance is
* being modified. The second bit onwords are for the individual
* TextureUnitState dirty bit. The ith bit set means the (i-1)
* texture unit state is modified. Note, this mask only supports
* 30 texture unit states. If the appearance uses more than 31
* texture unit states, then the modification of the 32nd texture
* unit state and up will have the first bit set, that means
* the TextureBin will be reset, rather than only the particular
* texture unit state will be reset.
*/
int soleUserCompDirty;
static final int SOLE_USER_DIRTY_REF = 0x1;
static final int SOLE_USER_DIRTY_TA = 0x2;
static final int SOLE_USER_DIRTY_TC = 0x4;
static final int SOLE_USER_DIRTY_TEXTURE = 0x8;
static final int SOLE_USER_DIRTY_TUS = 0x10;
/**
* The hashMap of RenderMolecules in this TextureBin this is used in rendering,
* the key used is localToVworld
*/
HashMap<Transform3D[], ArrayList<RenderMolecule>> addOpaqueRMs = new HashMap<Transform3D[], ArrayList<RenderMolecule>>();
HashMap<Transform3D[], ArrayList<RenderMolecule>> addTransparentRMs = new HashMap<Transform3D[], ArrayList<RenderMolecule>>();
// A hashmap based on localToVworld for fast
// insertion of new renderMolecules
HashMap<Transform3D[], RenderMolecule> opaqueRenderMoleculeMap = new HashMap<Transform3D[], RenderMolecule>();
HashMap<Transform3D[], RenderMolecule> transparentRenderMoleculeMap = new HashMap<Transform3D[], RenderMolecule>();
// List of renderMolecules - used in rendering ..
RenderMolecule opaqueRMList = null;
RenderMolecule transparentRMList = null;
TransparentRenderingInfo parentTInfo;
int numRenderMolecules = 0;
int numEditingRenderMolecules = 0;
int tbFlag = 0; // a general bitmask for TextureBin
// Following are the bits used in flag
final static int ON_RENDER_BIN_LIST = 0x0001;
final static int ON_UPDATE_LIST = 0x0002;
final static int SOLE_USER = 0x0004;
final static int CONTIGUOUS_ACTIVE_UNITS = 0x0008;
final static int RESORT = 0x0010;
final static int ON_UPDATE_CHECK_LIST = 0x0020;
final static int USE_DISPLAYLIST = -2;
final static int USE_VERTEXARRAY = -1;
TextureBin(TextureUnitStateRetained[] state, AppearanceRetained app,
RenderBin rb) {
renderBin = rb;
tbFlag = 0;
reset(state, app);
}
/**
* For now, clone everything just like the other NodeComponent
*/
void reset(TextureUnitStateRetained[] state, AppearanceRetained app) {
prev = null;
next = null;
opaqueRMList = null;
transparentRMList = null;
numEditingRenderMolecules = 0;
// Issue 249 - check for sole user only if property is set
// determine if this appearance is a sole user of this
// TextureBin
tbFlag &= ~TextureBin.SOLE_USER;
if (VirtualUniverse.mc.allowSoleUser) {
if ((app != null) &&
(app.changedFrequent &
(AppearanceRetained.TEXTURE |
AppearanceRetained.TEXCOORD_GEN |
AppearanceRetained.TEXTURE_ATTR |
AppearanceRetained.TEXTURE_UNIT_STATE)) != 0) {
tbFlag |= TextureBin.SOLE_USER;
}
}
if ((tbFlag & TextureBin.SOLE_USER) != 0) {
this.app = app;
} else {
this.app = null;
}
resetTextureState(state);
if ((tbFlag & TextureBin.ON_RENDER_BIN_LIST) == 0) {
renderBin.addTextureBin(this);
tbFlag |= TextureBin.ON_RENDER_BIN_LIST;
}
}
void resetTextureState(TextureUnitStateRetained[] state) {
int i;
boolean foundDisableUnit = false;
numActiveTexUnit = 0;
boolean soleUser = ((tbFlag & TextureBin.SOLE_USER) != 0);
TextureRetained prevFirstTexture = null;
TextureRetained tex;
tbFlag |= TextureBin.CONTIGUOUS_ACTIVE_UNITS;
if (state != null) {
foundDisableUnit = false;
if (texUnitState == null || (texUnitState.length != state.length)) {
texUnitState = new TextureUnitStateRetained[state.length];
} else if (texUnitState.length > 0 && texUnitState[0] != null) {
prevFirstTexture = texUnitState[0].texture;
}
for (i = 0; i < state.length; i++) {
if (state[i] == null) {
texUnitState[i] = null;
foundDisableUnit = true;
} else {
// create a clone texture unit state
if (texUnitState[i] == null) {
texUnitState[i] = new TextureUnitStateRetained();
}
// for sole user TextureUnitState, save
// the node component reference in the mirror reference
// of the cloned copy for equal test, and
// for native download optimization
if (soleUser || state[i].changedFrequent != 0) {
texUnitState[i].mirror = state[i];
}
// for the lowest level of node component in
// TextureBin, clone it only if it is not
// changedFrequent; in other words, if the
// lowest level of texture related node components
// such as TextureAttributes & TexCoordGen is
// changedFrequent, have the cloned texUnitState
// reference the mirror of those node components
// directly. For Texture, we'll always reference
// the mirror.
// decrement the TextureBin ref count of the previous
// texture
tex = texUnitState[i].texture;
if (tex != null) {
tex.decTextureBinRefCount(this);
if (soleUser &&
(tex.getTextureBinRefCount(this) == 0) &&
(tex != state[i].texture)) {
// In this case texture change but
// TextureBin will not invoke clear() to reset.
// So we need to free the texture resource here.
renderBin.addTextureResourceFreeList(tex);
}
}
texUnitState[i].texture = state[i].texture;
// increment the TextureBin ref count of the new
// texture
if (texUnitState[i].texture != null) {
texUnitState[i].texture.incTextureBinRefCount(this);
}
if (state[i].texAttrs != null) {
if (state[i].texAttrs.changedFrequent != 0) {
texUnitState[i].texAttrs = state[i].texAttrs;
} else {
// need to check for texAttrs.source because
// texAttrs could be pointing to the mirror
// in the last frame, so don't want to
// overwrite the mirror
if (texUnitState[i].texAttrs == null ||
texUnitState[i].texAttrs.source != null) {
texUnitState[i].texAttrs =
new TextureAttributesRetained();
}
texUnitState[i].texAttrs.set(
state[i].texAttrs);
texUnitState[i].texAttrs.mirrorCompDirty = true;
// for sole user TextureBin, we are saving
// the mirror node component in the mirror
// reference in the clone object. This
// will be used in state download to
// avoid redundant download
if (soleUser) {
texUnitState[i].texAttrs.mirror =
state[i].texAttrs;
} else {
texUnitState[i].texAttrs.mirror = null;
}
}
} else {
texUnitState[i].texAttrs = null;
}
if (state[i].texGen != null) {
if (state[i].texGen.changedFrequent != 0) {
texUnitState[i].texGen = state[i].texGen;
} else {
// need to check for texGen.source because
// texGen could be pointing to the mirror
// in the last frame, so don't want to
// overwrite the mirror
if (texUnitState[i].texGen == null ||
texUnitState[i].texGen.source != null) {
texUnitState[i].texGen =
new TexCoordGenerationRetained();
}
texUnitState[i].texGen.set(state[i].texGen);
texUnitState[i].texGen.mirrorCompDirty = true;
// for sole user TextureBin, we are saving
// the mirror node component in the mirror
// reference in the clone object. This
// will be used in state download to
// avoid redundant download
if (soleUser) {
texUnitState[i].texGen.mirror = state[i].texGen;
} else {
texUnitState[i].texGen.mirror = null;
}
}
} else {
texUnitState[i].texGen = null;
}
// Track the last active texture unit and the total number
// of active texture units. Note that this total number
// now includes disabled units so that there is always
// a one-to-one mapping. We no longer remap texture units.
if (texUnitState[i].isTextureEnabled()) {
numActiveTexUnit = i + 1;
if (foundDisableUnit) {
// mark that active texture units are not
// contiguous
tbFlag &= ~TextureBin.CONTIGUOUS_ACTIVE_UNITS;
}
} else {
foundDisableUnit = true;
}
}
}
// check to see if the TextureBin sorting criteria is
// modified for this textureBin; if yes, mark that
// resorting is needed
if ((texUnitState[0] == null && prevFirstTexture != null) ||
(texUnitState[0] != null &&
texUnitState[0].texture != prevFirstTexture)) {
tbFlag |= TextureBin.RESORT;
}
} else {
// check to see if the TextureBin sorting criteria is
// modified for this textureBin; if yes, mark that
// resorting is needed
if (texUnitState != null && texUnitState[0].texture != null) {
tbFlag |= TextureBin.RESORT;
}
texUnitState = null;
}
soleUserCompDirty = 0;
}
/**
* The TextureBin is to be removed from RenderBin,
* do the proper unsetting of any references
*/
void clear() {
// make sure there is no reference to the scenegraph
app = null;
// for each texture referenced in the texture units, decrement
// the reference count. If the reference count == 0, tell
// the renderer to free up the resource
if (texUnitState != null) {
TextureRetained tex;
for (int i = 0; i < texUnitState.length; i++) {
if (texUnitState[i] != null) {
if (texUnitState[i].texture != null) {
tex = texUnitState[i].texture;
tex.decTextureBinRefCount(this);
if (tex.getTextureBinRefCount(this) == 0) {
renderBin.addTextureResourceFreeList(tex);
}
texUnitState[i].texture = null;
}
// make sure there is no more reference to the scenegraph
texUnitState[i].mirror = null;
texUnitState[i].texture = null;
if (texUnitState[i].texAttrs != null &&
texUnitState[i].texAttrs.source != null) {
texUnitState[i].texAttrs = null;
}
if (texUnitState[i].texGen != null &&
texUnitState[i].texGen.source != null) {
texUnitState[i].texGen = null;
}
}
}
}
}
/**
* This tests if the qiven textureUnitState matches this TextureBin
*/
boolean equals(TextureUnitStateRetained state[], RenderAtom ra) {
// if this TextureBin is a soleUser case or the incoming
// app has changedFrequent bit set for any of the texture
// related component, then either the current TextureBin
// or the incoming app requires the same app match
if (((tbFlag & TextureBin.SOLE_USER) != 0) ||
((ra.app != null) &&
(ra.app.changedFrequent &
(AppearanceRetained.TEXTURE |
AppearanceRetained.TEXCOORD_GEN |
AppearanceRetained.TEXTURE_ATTR |
AppearanceRetained.TEXTURE_UNIT_STATE)) != 0)) {
if (app == ra.app) {
// if this textureBin is currently on a zombie state,
// we'll need to put it on the update list to reevaluate
// the state, because while it is on a zombie state,
// texture state could have been changed. Example,
// application could have detached an appearance,
// made changes to the texture references, and then
// reattached the appearance. In this case, the texture
// changes would not have reflected to the textureBin
if (numEditingRenderMolecules == 0) {
//System.err.println("===> TB in zombie state " + this);
if (soleUserCompDirty == 0) {
this.renderBin.tbUpdateList.add(this);
}
soleUserCompDirty |= TextureBin.SOLE_USER_DIRTY_REF;
}
return true;
} else {
return false;
}
}
if (texUnitState == null && state == null)
return (true);
if (texUnitState == null || state == null)
return (false);
if (state.length != texUnitState.length)
return (false);
for (int i = 0; i < texUnitState.length; i++) {
// If texture Unit State is null
if (texUnitState[i] == null) {
if (state[i] != null)
return (false);
}
else {
if (!texUnitState[i].equivalent(state[i])) {
return (false);
}
}
}
// Check if the image component has changed(may be a clearLive texture
// change img component. setLive case)
//
if ((tbFlag & TextureBin.ON_RENDER_BIN_LIST) == 0) {
renderBin.addTextureBin(this);
tbFlag |= TextureBin.ON_RENDER_BIN_LIST;
}
return (true);
}
/*
// updateNodeComponentCheck is called for each soleUser TextureBin
// into which new renderAtom has been added. This method is called before
// updateNodeComponent() to allow TextureBin to catch any node
// component changes that have been missed because the changes
// come when there is no active renderAtom associated with the
// TextureBin. See bug# 4503926 for details.
public void updateNodeComponentCheck() {
//System.err.println("TextureBin.updateNodeComponentCheck()");
tbFlag &= ~TextureBin.ON_UPDATE_CHECK_LIST;
if ((soleUserCompDirty & SOLE_USER_DIRTY_REF) != 0) {
return ;
}
if ((app.compChanged & (AppearanceRetained.TEXTURE |
AppearanceRetained.TEXCOORD_GEN |
AppearanceRetained.TEXTURE_ATTR |
AppearanceRetained.TEXTURE_UNIT_STATE)) != 0) {
if (soleUserCompDirty == 0) {
this.renderBin.tbUpdateList.add(this);
}
soleUserCompDirty |= TextureBin.SOLE_USER_DIRTY_REF;
} else if (app.texUnitState != null) {
// if one texture unit state has to be reevaluated, then
// it's enough update checking because reevaluating texture unit
// state will automatically take care of its node component
// updates.
boolean done = false;
for (int i = 0; i < app.texUnitState.length && !done; i++) {
if (app.texUnitState[i] != null) {
if (app.texUnitState[i].compChanged != 0) {
if (soleUserCompDirty == 0) {
this.renderBin.tbUpdateList.add(this);
}
soleUserCompDirty |= TextureBin.SOLE_USER_DIRTY_TUS;
done = true;
} else {
if (app.texUnitState[i].texAttrs != null &&
app.texUnitState[i].texAttrs.compChanged != 0) {
if (soleUserCompDirty == 0) {
this.renderBin.tbUpdateList.add(this);
}
soleUserCompDirty |= TextureBin.SOLE_USER_DIRTY_TA;
}
if (app.texUnitState[i].texGen != null &&
app.texUnitState[i].texGen.compChanged != 0) {
if (soleUserCompDirty == 0) {
this.renderBin.tbUpdateList.add(this);
}
soleUserCompDirty |= TextureBin.SOLE_USER_DIRTY_TC;
}
if (app.texUnitState[i].texture != null &&
((app.texUnitState[i].texture.compChanged &
TextureRetained.ENABLE_CHANGED) != 0)) {
if (soleUserCompDirty == 0) {
this.renderBin.tbUpdateList.add(this);
}
soleUserCompDirty |= TextureBin.SOLE_USER_DIRTY_TEXTURE;
}
}
}
}
}
}
*/
/**
* updateNodeComponent is called from RenderBin to update the
* clone copy of the sole user node component in TextureBin when the
* corresponding node component is being modified
*/
public void updateNodeComponent() {
// don't bother to update if the TextureBin is already
// removed from RenderBin
if ((tbFlag & TextureBin.ON_RENDER_BIN_LIST) == 0)
return;
// if any of the texture reference in the appearance referenced
// by a sole user TextureBin is being modified, just do a reset
if (((tbFlag & TextureBin.SOLE_USER) != 0) &&
((soleUserCompDirty & TextureBin.SOLE_USER_DIRTY_REF) != 0)) {
resetTextureState(app.texUnitState);
return;
}
if (texUnitState == null) {
soleUserCompDirty = 0;
return;
}
if ((soleUserCompDirty & TextureBin.SOLE_USER_DIRTY_TUS) != 0) {
// Now take care of the Texture Unit State changes
TextureUnitStateRetained tus, mirrorTUS = null;
boolean soleUser = ((tbFlag & TextureBin.SOLE_USER) != 0);
for (int i = 0; i < texUnitState.length; i++) {
tus = texUnitState[i];
if (tus != null) {
if (tus.mirror != null) {
mirrorTUS = (TextureUnitStateRetained)tus.mirror;
if (tus.texture != mirrorTUS.texture) {
if (tus.texture != null) {
tus.texture.decTextureBinRefCount(this);
}
tus.texture = mirrorTUS.texture;
if (tus.texture != null) {
tus.texture.incTextureBinRefCount(this);
}
// the first texture (TextureBin sorting
// criteria) is modified, so needs to resort
if (i == 0) {
tbFlag |= TextureBin.RESORT;
}
}
if (mirrorTUS.texAttrs != null) {
if (mirrorTUS.texAttrs.changedFrequent != 0) {
tus.texAttrs = mirrorTUS.texAttrs;
} else {
if (tus.texAttrs == null ||
tus.texAttrs.source != null) {
tus.texAttrs =
new TextureAttributesRetained();
}
tus.texAttrs.set(mirrorTUS.texAttrs);
tus.texAttrs.mirrorCompDirty = true;
if (soleUser) {
tus.texAttrs.mirror = mirrorTUS.texAttrs;
} else {
tus.texAttrs.mirror = null;
}
}
} else {
tus.texAttrs = null;
}
if (mirrorTUS.texGen != null) {
if (mirrorTUS.texGen.changedFrequent != 0) {
tus.texGen = mirrorTUS.texGen;
} else {
if (tus.texGen == null ||
tus.texGen.source != null) {
tus.texGen =
new TexCoordGenerationRetained();
}
tus.texGen.set(mirrorTUS.texGen);
tus.texGen.mirrorCompDirty = true;
if (soleUser) {
tus.texGen.mirror = mirrorTUS.texGen;
} else {
tus.texGen.mirror = null;
}
}
} else {
tus.texGen = null;
}
}
}
}
// need to reEvaluate # of active textures after the update
soleUserCompDirty |= TextureBin.SOLE_USER_DIRTY_TEXTURE;
// TextureUnitState update automatically taken care of
// TextureAttributes & TexCoordGeneration update
soleUserCompDirty &= ~(TextureBin.SOLE_USER_DIRTY_TA |
TextureBin.SOLE_USER_DIRTY_TC);
}
if ((soleUserCompDirty & TextureBin.SOLE_USER_DIRTY_TEXTURE) != 0) {
boolean foundDisableUnit = false;
numActiveTexUnit = 0;
tbFlag |= TextureBin.CONTIGUOUS_ACTIVE_UNITS;
for (int i = 0; i < texUnitState.length; i++) {
// Track the last active texture unit and the total number
// of active texture units. Note that this total number
// now includes disabled units so that there is always
// a one-to-one mapping. We no longer remap texture units.
if (texUnitState[i] != null &&
texUnitState[i].isTextureEnabled()) {
numActiveTexUnit = i + 1;
if (foundDisableUnit) {
// mark that active texture units are not
// contiguous
tbFlag &= ~TextureBin.CONTIGUOUS_ACTIVE_UNITS;
}
} else {
foundDisableUnit = true;
}
}
}
if ((soleUserCompDirty & TextureBin.SOLE_USER_DIRTY_TA) != 0) {
for (int i = 0; i < texUnitState.length; i++) {
if (texUnitState[i] != null &&
texUnitState[i].texAttrs != null &&
texUnitState[i].texAttrs.mirror != null &&
texUnitState[i].texAttrs.mirror.changedFrequent != 0) {
texUnitState[i].texAttrs = (TextureAttributesRetained)
texUnitState[i].texAttrs.mirror;
}
}
}
if ((soleUserCompDirty & TextureBin.SOLE_USER_DIRTY_TC) != 0) {
for (int i = 0; i < texUnitState.length; i++) {
if (texUnitState[i] != null &&
texUnitState[i].texGen != null &&
texUnitState[i].texGen.mirror != null &&
texUnitState[i].texGen.mirror.changedFrequent != 0) {
texUnitState[i].texGen = (TexCoordGenerationRetained)
texUnitState[i].texGen.mirror;
}
}
}
soleUserCompDirty = 0;
}
@Override
public void updateObject() {
if (!addOpaqueRMs.isEmpty()) {
opaqueRMList = addAll(opaqueRenderMoleculeMap, addOpaqueRMs,
opaqueRMList, true);
}
if (!addTransparentRMs.isEmpty()) {
// If transparent and not in bg geometry and inodepth
// sorted transparency
if (transparentRMList == null &&
(renderBin.transpSortMode == View.TRANSPARENCY_SORT_NONE ||
environmentSet.lightBin.geometryBackground != null)) {
// System.err.println("========> addTransparentTextureBin "+this);
transparentRMList = addAll(transparentRenderMoleculeMap,
addTransparentRMs, transparentRMList, false);
// Eventhough we are adding to transparentList , if all the RMS
// have been switched already due to changeLists, then there is
// nothing to add, and TBIN does not have any transparentRMList
if (transparentRMList != null) {
renderBin.addTransparentObject(this);
}
}
else {
transparentRMList = addAll(transparentRenderMoleculeMap,
addTransparentRMs, transparentRMList, false);
}
}
tbFlag &= ~TextureBin.ON_UPDATE_LIST;
}
/**
* Each list of renderMoledule with the same localToVworld
* is connect by rm.next and rm.prev.
* At the end of the list (i.e. rm.next = null) the field
* rm.nextMap is link to another list (with the same
* localToVworld). So during rendering it will traverse
* rm.next until this is null, then follow the .nextMap
* to access another list and use rm.next to continue
* until both rm.next and rm.nextMap are null.
*
* renderMoleculeMap is use to assist faster location of
* renderMolecule List with the same localToVWorld. The
* start of renderMolecule in the list with same
* localToVworld is insert in renderMoleculeMap. This
* map is clean up at removeRenderMolecule(). TextureBin
* also use the map for quick location of renderMolecule
* with the same localToVworld and attributes in
* findRenderMolecule().
*/
RenderMolecule addAll(HashMap<Transform3D[], RenderMolecule> renderMoleculeMap,
HashMap<Transform3D[], ArrayList<RenderMolecule>> addRMs,
RenderMolecule startList, boolean opaqueList) {
int i;
Collection<ArrayList<RenderMolecule>> c = addRMs.values();
Iterator<ArrayList<RenderMolecule>> listIterator = c.iterator();
RenderMolecule renderMoleculeList, head;
while (listIterator.hasNext()) {
boolean changed = false;
ArrayList<RenderMolecule> curList = listIterator.next();
RenderMolecule r = curList.get(0);
// If this is a opaque one , but has been switched to a transparentList or
// vice-versa (dur to changeLists function called before this), then
// do nothing!
// For changedFrequent case: Consider the case when a RM is added
// (so is in the addRM list) and then
// a change in transparent value occurs that make it from opaque to
// transparent (the switch is handled before this function is called)
if (r.isOpaqueOrInOG != opaqueList) {
continue;
}
// Get the list of renderMolecules for this transform
renderMoleculeList = renderMoleculeMap.get(r.localToVworld);
if (renderMoleculeList == null) {
renderMoleculeList = r;
renderMoleculeMap.put(r.localToVworld, renderMoleculeList);
// Add this renderMolecule at the beginning of RM list
if (startList == null) {
startList = r;
r.nextMap = null;
r.prevMap = null;
startList.dirtyAttrsAcrossRms = RenderMolecule.ALL_DIRTY_BITS;
}
else {
r.nextMap = startList;
startList.prevMap = r;
startList = r;
startList.nextMap.checkEquivalenceWithLeftNeighbor(r,
RenderMolecule.ALL_DIRTY_BITS);
}
}
else {
// Insert the renderMolecule next to a RM that has equivalent
// texture unit state
if ((head = insertRenderMolecule(r, renderMoleculeList)) != null) {
if (renderMoleculeList.prevMap != null) {
renderMoleculeList.prevMap.nextMap = head;
}
head.prevMap = renderMoleculeList.prevMap;
renderMoleculeList.prevMap = null;
renderMoleculeList = head;
changed = true;
}
}
for (i = 1; i < curList.size(); i++) {
r = curList.get(i);
// If this is a opaque one , but has been switched to a transparentList or
// vice-versa (dur to changeLists function called before this), then
// do nothing!
// For changedFrequent case: Consider the case when a RM is added
// (so is in the addRM list) and then
// a change in transparent value occurs that make it from opaque to
// transparent (the switch is handled before this function is called)
if (r.isOpaqueOrInOG != opaqueList)
continue;
if ((head = insertRenderMolecule(r, renderMoleculeList)) != null) {
if (renderMoleculeList.prevMap != null) {
renderMoleculeList.prevMap.nextMap = head;
}
head.prevMap = renderMoleculeList.prevMap;
renderMoleculeList.prevMap = null;
renderMoleculeList = head;
changed = true;
}
}
if (changed) {
renderMoleculeMap.put(r.localToVworld, renderMoleculeList);
if (renderMoleculeList.prevMap != null) {
renderMoleculeList.checkEquivalenceWithLeftNeighbor(
renderMoleculeList.prevMap,
RenderMolecule.ALL_DIRTY_BITS);
}
else {
startList = renderMoleculeList;
startList.dirtyAttrsAcrossRms =
RenderMolecule.ALL_DIRTY_BITS;
}
}
}
addRMs.clear();
return startList;
}
// XXXX: Could the analysis be done during insertRenderMolecule?
// Return the head of the list,
// if the insertion occurred at beginning of the list
RenderMolecule insertRenderMolecule(RenderMolecule r,
RenderMolecule renderMoleculeList) {
RenderMolecule rm, retval;
// Look for a RM that has an equivalent material
rm = renderMoleculeList;
while (rm != null) {
if (rm.material == r.material ||
(rm.definingMaterial != null &&
rm.definingMaterial.equivalent(r.definingMaterial))) {
// Put it here
r.next = rm;
r.prev = rm.prev;
if (rm.prev == null) {
renderMoleculeList = r;
retval = renderMoleculeList;
} else {
rm.prev.next = r;
retval = null;
}
rm.prev = r;
r.checkEquivalenceWithBothNeighbors(RenderMolecule.ALL_DIRTY_BITS);
return retval;
}
// If they are not equivalent, then skip to the first one
// that has a different material using the dirty bits
else {
rm = rm.next;
while (rm != null &&
((rm.dirtyAttrsAcrossRms & RenderMolecule.MATERIAL_DIRTY) == 0)) {
rm = rm.next;
}
}
}
// Just put it up front
r.next = renderMoleculeList;
renderMoleculeList.prev = r;
renderMoleculeList = r;
r.checkEquivalenceWithBothNeighbors(RenderMolecule.ALL_DIRTY_BITS);
return renderMoleculeList;
}
/**
* Adds the given RenderMolecule to this TextureBin
*/
void addRenderMolecule(RenderMolecule r, RenderBin rb) {
r.textureBin = this;
HashMap<Transform3D[], ArrayList<RenderMolecule>> map;
if (r.isOpaqueOrInOG)
map = addOpaqueRMs;
else
map = addTransparentRMs;
ArrayList<RenderMolecule> list = map.get(r.localToVworld);
if (list == null) {
list = new ArrayList<RenderMolecule>();
map.put(r.localToVworld, list);
}
list.add(r);
if ((tbFlag & TextureBin.ON_UPDATE_LIST) == 0) {
tbFlag |= TextureBin.ON_UPDATE_LIST;
rb.objUpdateList.add(this);
}
}
/**
* Removes the given RenderMolecule from this TextureBin
*/
void removeRenderMolecule(RenderMolecule r) {
int index;
boolean found = false;
RenderMolecule rmlist;
HashMap<Transform3D[], ArrayList<RenderMolecule>> addMap;
HashMap<Transform3D[], RenderMolecule> allMap;
r.textureBin = null;
if (r.isOpaqueOrInOG) {
rmlist = opaqueRMList;
allMap = opaqueRenderMoleculeMap;
addMap = addOpaqueRMs;
}
else {
rmlist = transparentRMList;
allMap = transparentRenderMoleculeMap;
addMap = addTransparentRMs;
}
// If the renderMolecule being remove is contained in addRMs, then
// remove the renderMolecule from the addList
ArrayList<RenderMolecule> list = addMap.get(r.localToVworld);
if (list != null) {
if ((index = list.indexOf(r)) != -1) {
list.remove(index);
// If this was the last element for this localToVworld, then remove
// the entry from the addRMs list
if (list.isEmpty()) {
addMap.remove(r.localToVworld);
}
r.prev = null;
r.next = null;
found = true;
}
}
if (!found) {
RenderMolecule head = removeOneRM(r, allMap, rmlist);
r.soleUserCompDirty = 0;
r.onUpdateList = 0;
if (r.definingPolygonAttributes != null &&
(r.definingPolygonAttributes.changedFrequent != 0))
r.definingPolygonAttributes = null;
if (r.definingLineAttributes != null &&
(r.definingLineAttributes.changedFrequent != 0))
r.definingLineAttributes = null;
if (r.definingPointAttributes != null &&
(r.definingPointAttributes.changedFrequent != 0))
r.definingPointAttributes = null;
if (r.definingMaterial != null &&
(r.definingMaterial.changedFrequent != 0))
r.definingMaterial = null;
if (r.definingColoringAttributes != null &&
(r.definingColoringAttributes.changedFrequent != 0))
r.definingColoringAttributes = null;
if (r.definingTransparency != null &&
(r.definingTransparency.changedFrequent != 0))
r.definingTransparency = null;
renderBin.removeRenderMolecule(r);
if (r.isOpaqueOrInOG) {
opaqueRMList = head;
}
else {
transparentRMList = head;
}
}
// If the renderMolecule removed is not opaque then ..
if (!r.isOpaqueOrInOG && transparentRMList == null && (renderBin.transpSortMode == View.TRANSPARENCY_SORT_NONE ||
environmentSet.lightBin.geometryBackground != null)) {
renderBin.removeTransparentObject(this);
}
// If the rm removed is the one that is referenced in the tinfo
// then change this reference
else if (parentTInfo != null && parentTInfo.rm == r) {
parentTInfo.rm = transparentRMList;
}
// Removal of this texture setting from the texCoordGenartion
// is done during the removeRenderAtom routine in RenderMolecule.java
// Only remove this texture bin if there are no more renderMolcules
// waiting to be added
if (opaqueRenderMoleculeMap.isEmpty() && addOpaqueRMs.isEmpty() &&
transparentRenderMoleculeMap.isEmpty() && addTransparentRMs.isEmpty()) {
if ((tbFlag & TextureBin.ON_RENDER_BIN_LIST) != 0) {
tbFlag &= ~TextureBin.ON_RENDER_BIN_LIST;
renderBin.removeTextureBin(this);
}
shaderBin.removeTextureBin(this);
texUnitState = null;
}
}
/**
* This method is called to update the state for this
* TextureBin. This is only applicable in the single-pass case.
* Multi-pass render will have to take care of its own
* state update.
*/
void updateAttributes(Canvas3D cv) {
boolean dirty = ((cv.canvasDirty & (Canvas3D.TEXTUREBIN_DIRTY|
Canvas3D.TEXTUREATTRIBUTES_DIRTY)) != 0);
if (cv.textureBin == this && !dirty) {
return;
}
cv.textureBin = this;
// save the current number of active texture unit so as
// to be able to reset the one that is not enabled in this bin
int lastActiveTexUnitIdx = -1;
// Get the number of available texture units; this depends on
// whether or not shaders are being used.
boolean useShaders = (shaderBin.shaderProgram != null);
int availableTextureUnits =
useShaders ? cv.maxTextureImageUnits : cv.maxTextureUnits;
// If the number of active texture units is greater than the number of
// supported units, then we
// need to set a flag indicating that the texture units are invalid.
boolean disableTexture = false;
if (numActiveTexUnit > availableTextureUnits) {
disableTexture = true;
// System.err.println("*** TextureBin : number of texture units exceeded");
}
// set the number active texture unit in Canvas3D
if (disableTexture) {
cv.setNumActiveTexUnit(0);
}
else {
cv.setNumActiveTexUnit(numActiveTexUnit);
}
// state update
if (numActiveTexUnit <= 0 || disableTexture) {
if (cv.getLastActiveTexUnit() >= 0) {
// no texture units enabled
// when the canvas supports multi texture units,
// we'll need to reset texture for all texture units
if (cv.multiTexAccelerated) {
for (int i = 0; i <= cv.getLastActiveTexUnit(); i++) {
cv.resetTexture(cv.ctx, i);
}
// set the active texture unit back to 0
cv.setNumActiveTexUnit(0);
cv.activeTextureUnit(cv.ctx, 0);
} else {
cv.resetTexture(cv.ctx, -1);
}
cv.setLastActiveTexUnit(-1);
}
} else {
int j = 0;
for (int i = 0; i < texUnitState.length; i++) {
if (j >= cv.texUnitState.length) {
// We finish enabling the texture state.
// Note that it is possible
// texUnitState.length > cv.texUnitState.length
break;
}
if ((texUnitState[i] != null) &&
texUnitState[i].isTextureEnabled()) {
if (dirty ||
cv.texUnitState[j].mirror == null ||
cv.texUnitState[j].mirror != texUnitState[i].mirror) {
// update the texture unit state
texUnitState[i].updateNative(j, cv, false, false);
cv.texUnitState[j].mirror = texUnitState[i].mirror;
}
// create a mapping that maps an active texture
// unit to a texture unit state
lastActiveTexUnitIdx = j;
} else {
if (j <= cv.getLastActiveTexUnit()) {
cv.resetTexture(cv.ctx, j);
}
}
j++;
}
// make sure to disable the remaining texture units
// since they could have been enabled from the previous
// texture bin
for (int i = j; i <= cv.getLastActiveTexUnit(); i++) {
cv.resetTexture(cv.ctx, i);
}
cv.setLastActiveTexUnit(lastActiveTexUnitIdx);
// set the active texture unit back to 0
cv.activeTextureUnit(cv.ctx, 0);
}
cv.canvasDirty &= ~Canvas3D.TEXTUREBIN_DIRTY;
}
/**
* Renders this TextureBin
*/
void render(Canvas3D cv) {
render(cv, opaqueRMList);
}
void render(Canvas3D cv, RenderMolecule rlist) {
// include this TextureBin to the to-be-updated state set in canvas
cv.setStateToUpdate(Canvas3D.TEXTUREBIN_BIT, this);
renderList(cv, USE_DISPLAYLIST, rlist);
}
void render(Canvas3D cv, TransparentRenderingInfo rlist) {
// include this TextureBin to the to-be-updated state set in canvas
cv.setStateToUpdate(Canvas3D.TEXTUREBIN_BIT, this);
renderList(cv, USE_DISPLAYLIST, rlist);
}
/**
* render list of RenderMolecule
*/
void renderList(Canvas3D cv, int pass, RenderMolecule rlist) {
assert pass < 0;
// bit mask of all attr fields that are equivalent across
// renderMolecules thro. ORing of invisible RMs.
int combinedDirtyBits = 0;
boolean rmVisible = true;
RenderMolecule rm = rlist;
while (rm != null) {
if(rmVisible) {
combinedDirtyBits = rm.dirtyAttrsAcrossRms;
}
else {
combinedDirtyBits |= rm.dirtyAttrsAcrossRms;
}
rmVisible = rm.render(cv, pass, combinedDirtyBits);
// next render molecule or the nextmap
if (rm.next == null) {
rm = rm.nextMap;
}
else {
rm = rm.next;
}
}
}
/**
* render sorted transparent list
*/
void renderList(Canvas3D cv, int pass, TransparentRenderingInfo tinfo) {
assert pass < 0;
RenderMolecule rm = tinfo.rm;
if (rm.isSwitchOn()) {
rm.transparentSortRender(cv, pass, tinfo);
}
}
void changeLists(RenderMolecule r) {
RenderMolecule renderMoleculeList, rmlist = null, head;
HashMap<Transform3D[], RenderMolecule> allMap = null;
boolean newRM = false;
// System.err.println("changeLists r = "+r+" tBin = "+this);
// If its a new RM then do nothing, otherwise move lists
if (r.isOpaqueOrInOG) {
if (opaqueRMList == null &&
(r.prev == null && r.prevMap == null && r.next == null &&
r.nextMap == null)) {
newRM = true;
}
else {
rmlist = opaqueRMList;
allMap = opaqueRenderMoleculeMap;
}
}
else {
if (transparentRMList == null &&
(r.prev == null && r.prevMap == null && r.next == null &&
r.nextMap == null) ){
newRM = true;
}
else {
rmlist = transparentRMList;
allMap = transparentRenderMoleculeMap;
}
}
if (!newRM) {
head = removeOneRM(r, allMap, rmlist);
if (r.isOpaqueOrInOG) {
opaqueRMList = head;
}
else {
transparentRMList = head;
if (transparentRMList == null &&
(renderBin.transpSortMode == View.TRANSPARENCY_SORT_NONE ||
environmentSet.lightBin.geometryBackground != null)) {
renderBin.removeTransparentObject(this);
}
// Issue 129: remove the RM's render atoms from the
// list of transparent render atoms
if ((renderBin.transpSortMode == View.TRANSPARENCY_SORT_GEOMETRY) &&
(environmentSet.lightBin.geometryBackground == null)) {
r.addRemoveTransparentObject(renderBin, false);
}
}
}
HashMap<Transform3D[], RenderMolecule> renderMoleculeMap;
RenderMolecule startList;
// Now insert in the other bin
r.evalAlphaUsage(shaderBin.attributeBin.definingRenderingAttributes, texUnitState);
r.isOpaqueOrInOG = r.isOpaque() ||r.inOrderedGroup;
if (r.isOpaqueOrInOG) {
startList = opaqueRMList;
renderMoleculeMap = opaqueRenderMoleculeMap;
markDlistAsDirty(r);
}
else {
startList = transparentRMList;
renderMoleculeMap = transparentRenderMoleculeMap;
if ((r.primaryMoleculeType &RenderMolecule.DLIST_MOLECULE) != 0 &&
renderBin.transpSortMode != View.TRANSPARENCY_SORT_NONE) {
renderBin.addDisplayListResourceFreeList(r);
renderBin.removeDirtyRenderMolecule(r);
r.vwcBounds.set(null);
r.displayListId = 0;
r.displayListIdObj = null;
// Change the group type for all the rlistInfo in the primaryList
RenderAtomListInfo rinfo = r.primaryRenderAtomList;
while (rinfo != null) {
rinfo.groupType = RenderAtom.SEPARATE_DLIST_PER_RINFO;
if (rinfo.renderAtom.dlistIds == null) {
rinfo.renderAtom.dlistIds = new int[rinfo.renderAtom.rListInfo.length];
for (int k = 0; k < rinfo.renderAtom.dlistIds.length; k++) {
rinfo.renderAtom.dlistIds[k] = -1;
}
}
if (rinfo.renderAtom.dlistIds[rinfo.index] == -1) {
rinfo.renderAtom.dlistIds[rinfo.index] = VirtualUniverse.mc.getDisplayListId().intValue();
renderBin.addDlistPerRinfo.add(rinfo);
}
rinfo = rinfo.next;
}
r.primaryMoleculeType = RenderMolecule.SEPARATE_DLIST_PER_RINFO_MOLECULE;
}
else {
markDlistAsDirty(r);
}
}
renderMoleculeList = renderMoleculeMap.get(r.localToVworld);
if (renderMoleculeList == null) {
renderMoleculeList = r;
renderMoleculeMap.put(r.localToVworld, renderMoleculeList);
// Add this renderMolecule at the beginning of RM list
if (startList == null) {
startList = r;
r.nextMap = null;
r.prevMap = null;
}
else {
r.nextMap = startList;
startList.prevMap = r;
startList = r;
startList.nextMap.checkEquivalenceWithLeftNeighbor(r,RenderMolecule.ALL_DIRTY_BITS);
}
// Issue 67 : since we are adding the new RM at the head, we must
// set all dirty bits unconditionally
startList.dirtyAttrsAcrossRms = RenderMolecule.ALL_DIRTY_BITS;
}
else {
// Insert the renderMolecule next to a RM that has equivalent
// texture unit state
if ((head = insertRenderMolecule(r, renderMoleculeList)) != null) {
if (renderMoleculeList.prevMap != null) {
renderMoleculeList.prevMap.nextMap = head;
}
head.prevMap = renderMoleculeList.prevMap;
renderMoleculeList.prevMap = null;
renderMoleculeList = head;
renderMoleculeMap.put(r.localToVworld, renderMoleculeList);
if (renderMoleculeList.prevMap != null) {
renderMoleculeList.checkEquivalenceWithLeftNeighbor(renderMoleculeList.prevMap,
RenderMolecule.ALL_DIRTY_BITS);
}
else {
startList.dirtyAttrsAcrossRms = RenderMolecule.ALL_DIRTY_BITS;
startList = renderMoleculeList;
}
}
}
if (r.isOpaqueOrInOG) {
opaqueRMList = startList;
}
else {
// If transparent and not in bg geometry and inodepth sorted transparency
if (transparentRMList == null&&
(renderBin.transpSortMode == View.TRANSPARENCY_SORT_NONE ||
environmentSet.lightBin.geometryBackground != null)) {
transparentRMList = startList;
renderBin.addTransparentObject(this);
}
else {
transparentRMList = startList;
}
// Issue 129: add the RM's render atoms to the list of
// transparent render atoms
// XXXX: do we need to resort the list after the add???
if ((renderBin.transpSortMode == View.TRANSPARENCY_SORT_GEOMETRY) &&
(environmentSet.lightBin.geometryBackground == null)) {
r.addRemoveTransparentObject(renderBin, true);
}
}
}
RenderMolecule removeOneRM(RenderMolecule r, HashMap<Transform3D[], RenderMolecule> allMap, RenderMolecule list) {
RenderMolecule rmlist = list;
// In the middle, just remove and update
if (r.prev != null && r.next != null) {
r.prev.next = r.next;
r.next.prev = r.prev;
r.next.checkEquivalenceWithLeftNeighbor(r.prev,RenderMolecule.ALL_DIRTY_BITS);
}
// If whats is removed is at the end of an entry
else if (r.prev != null && r.next == null) {
r.prev.next = r.next;
r.prev.nextMap = r.nextMap;
if (r.nextMap != null) {
r.nextMap.prevMap = r.prev;
r.nextMap.checkEquivalenceWithLeftNeighbor(r.prev,RenderMolecule.ALL_DIRTY_BITS);
}
}
else if (r.prev == null && r.next != null) {
r.next.prev = null;
r.next.prevMap = r.prevMap;
if (r.prevMap != null) {
r.prevMap.nextMap = r.next;
r.next.checkEquivalenceWithLeftNeighbor(r.prevMap,RenderMolecule.ALL_DIRTY_BITS);
}
// Head of the rmList
else {
rmlist = r.next;
rmlist.dirtyAttrsAcrossRms = RenderMolecule.ALL_DIRTY_BITS;
}
allMap.put(r.localToVworld, r.next);
}
// Update the maps and remove this entry from the map list
else if (r.prev == null && r.next == null) {
if (r.prevMap != null) {
r.prevMap.nextMap = r.nextMap;
}
else {
rmlist = r.nextMap;
if (r.nextMap != null) {
rmlist.dirtyAttrsAcrossRms = RenderMolecule.ALL_DIRTY_BITS;
}
}
if (r.nextMap != null) {
r.nextMap.prevMap = r.prevMap;
if (r.prevMap != null) {
r.nextMap.checkEquivalenceWithLeftNeighbor(r.prevMap,RenderMolecule.ALL_DIRTY_BITS);
}
}
allMap.remove(r.localToVworld);
}
r.prev = null;
r.next = null;
r.prevMap = null;
r.nextMap = null;
return rmlist;
}
void markDlistAsDirty(RenderMolecule r) {
if (r.primaryMoleculeType == RenderMolecule.DLIST_MOLECULE) {
renderBin.addDirtyRenderMolecule(r);
}
else if (r.primaryMoleculeType == RenderMolecule.SEPARATE_DLIST_PER_RINFO_MOLECULE) {
RenderAtomListInfo ra = r.primaryRenderAtomList;
while (ra != null) {
renderBin.addDlistPerRinfo.add(ra);
ra = ra.next;
}
}
}
void decrActiveRenderMolecule() {
numEditingRenderMolecules--;
if (numEditingRenderMolecules == 0) {
// if number of editing renderMolecules goes to 0,
// inform the shaderBin that this textureBin goes to
// zombie state
shaderBin.decrActiveTextureBin();
}
}
void incrActiveRenderMolecule() {
if (numEditingRenderMolecules == 0) {
// if this textureBin is in zombie state, inform
// the shaderBin that this textureBin is activated again.
shaderBin.incrActiveTextureBin();
}
numEditingRenderMolecules++;
}
}
| gpl-2.0 |
arodchen/MaxSim | maxine/com.oracle.max.cri/src/com/sun/cri/ri/RiRegisterAttributes.java | 4019 | /*
* Copyright (c) 2010, 2011, 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.sun.cri.ri;
import java.util.*;
import com.sun.cri.ci.*;
/**
* A collection of register attributes. The specific attribute values for a register may be
* local to a compilation context. For example, a {@link RiRegisterConfig} in use during
* a compilation will determine which registers are callee saved.
*/
public class RiRegisterAttributes {
/**
* Denotes a register whose value preservation (if required) across a call is the responsibility of the caller.
*/
public final boolean isCallerSave;
/**
* Denotes a register whose value preservation (if required) across a call is the responsibility of the callee.
*/
public final boolean isCalleeSave;
/**
* Denotes a register that is available for use by a register allocator.
*/
public final boolean isAllocatable;
/**
* Denotes a register guaranteed to be non-zero if read in compiled Java code.
* For example, a register dedicated to holding the current thread.
*/
public boolean isNonZero;
public RiRegisterAttributes(boolean isCallerSave, boolean isCalleeSave, boolean isAllocatable) {
this.isCallerSave = isCallerSave;
this.isCalleeSave = isCalleeSave;
this.isAllocatable = isAllocatable;
}
public static final RiRegisterAttributes NONE = new RiRegisterAttributes(false, false, false);
/**
* Creates a map from register {@linkplain CiRegister#number numbers} to register
* {@linkplain RiRegisterAttributes attributes} for a given register configuration and set of
* registers.
*
* @param registerConfig a register configuration
* @param registers a set of registers
* @return an array whose length is the max register number in {@code registers} plus 1. An element at index i holds
* the attributes of the register whose number is i.
*/
public static RiRegisterAttributes[] createMap(RiRegisterConfig registerConfig, CiRegister[] registers) {
RiRegisterAttributes[] map = new RiRegisterAttributes[registers.length];
for (CiRegister reg : registers) {
if (reg != null) {
CiCalleeSaveLayout csl = registerConfig.getCalleeSaveLayout();
RiRegisterAttributes attr = new RiRegisterAttributes(
Arrays.asList(registerConfig.getCallerSaveRegisters()).contains(reg),
csl == null ? false : Arrays.asList(csl.registers).contains(reg),
Arrays.asList(registerConfig.getAllocatableRegisters()).contains(reg));
if (map.length <= reg.number) {
map = Arrays.copyOf(map, reg.number + 1);
}
map[reg.number] = attr;
}
}
for (int i = 0; i < map.length; i++) {
if (map[i] == null) {
map[i] = NONE;
}
}
return map;
}
}
| gpl-2.0 |
midaboghetich/netnumero | src/com/numhero/shared/exception/NotAuthorizedException.java | 342 | package com.numhero.shared.exception;
public class NotAuthorizedException extends ClientWarningException {
private static final long serialVersionUID = -3123770607841752215L;
public NotAuthorizedException() {
// for GWT
}
public NotAuthorizedException(String message) {
super(message);
}
}
| gpl-2.0 |
arodchen/MaxSim | maxine/com.oracle.max.base/src/com/sun/max/io/SeekableByteArrayOutputStream.java | 2853 | /*
* Copyright (c) 2007, 2011, 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.sun.max.io;
import java.io.*;
/**
* A {@link ByteArrayOutputStream} that can have its write position {@linkplain #seek(int) updated}.
*/
public class SeekableByteArrayOutputStream extends ByteArrayOutputStream {
private int highestCount;
/**
* @see ByteArrayOutputStream#ByteArrayOutputStream()
*/
public SeekableByteArrayOutputStream() {
}
/**
* @see ByteArrayOutputStream#ByteArrayOutputStream(int)
*/
public SeekableByteArrayOutputStream(int size) {
super(size);
}
/**
* Updates the write position of this stream. The stream can only be repositioned between 0 and the
* {@linkplain #endOfStream() end of the stream}.
*
* @param index
* the index to which the write position of this stream will be set
* @throws IllegalArgumentException
* if {@code index > highestSeekIndex()}
*/
public void seek(int index) throws IllegalArgumentException {
if (endOfStream() < index) {
throw new IllegalArgumentException();
}
count = index;
}
/**
* Gets the index one past the highest index that has been written to in this stream.
*/
public int endOfStream() {
if (highestCount < count) {
highestCount = count;
}
return highestCount;
}
@Override
public void reset() {
super.reset();
highestCount = 0;
}
/**
* Copies the {@code length} bytes of this byte array output stream starting at {@code offset} to {@code buf}
* starting at {@code bufOffset}.
*/
public void copyTo(int offset, byte[] toBuffer, int toOffset, int length) {
System.arraycopy(this.buf, offset, toBuffer, toOffset, length);
}
}
| gpl-2.0 |
Esleelkartea/aonGTA | aongta_v1.0.0_src/Fuentes y JavaDoc/aon-planner/src/com/code/aon/planner/enumeration/Priority.java | 6007 | /*
* Created on 23-nov-2005
*
*/
package com.code.aon.planner.enumeration;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* Enumeración para identificar los diferentes tipos de estado de la tarea.
*
* @author Consulting & Development. Iñaki Ayerbe - 23-nov-2005
* @version 1.0
*
* @since 1.0
*/
public class Priority implements Serializable, Comparable {
/**
* Tamaño del array para almacenar todos los tipos.
*/
private static final int LENGTH = 4;
/**
* Array para almacenar todos los tipos.
*/
private static Priority[] ALL = new Priority[LENGTH];
/**
* Ruta base del fichero de mensajes.
*/
private static final String BASE_NAME = "com.code.aon.planner.i18n.messages";
/**
* Prefijo de la llave de mensajes.
*/
private static final String MSG_KEY_PREFIX = "aon_enum_priority_";
/**
* Ninguna.
*/
public static final Priority NONE = new Priority(0);
/**
* Baja.
*/
public static final Priority LOW = new Priority(1);
/**
* Media.
*/
public static final Priority MEDIUM = new Priority(2);
/**
* Alta.
*/
public static final Priority HIGH = new Priority(3);
/**
* Indice que ocupa este objeto en el array.
*/
private int index;
/**
* Constructor for Priority
*
* @param index
* int
*/
private Priority(int index) {
this.index = index;
ALL[index] = this;
}
/**
* Method readResolve
*
* @return Object
*/
private Object readResolve() {
return ALL[index];
}
/**
* Indica cuándo otro objeto "es igual" a éste.
*
* @param obj
* La referencia al objeto que se quiere comparar.
* @return boolean True si el objeto es igual al del parámetro; False de
* otra manera.
* @see java.lang.Object#equals(Object)
*/
public boolean equals(Object obj) {
if (obj instanceof Priority) {
Priority as = (Priority) obj;
return as.index == index;
}
return false;
}
/**
* Devuelve un valor "hash code" para el objeto. Este método se implementa
* en beneficio de las "hashtables".
*
* @return Devuelve un valor "hash code" para el objeto.
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return index;
}
/**
* Devuelve un String que representa a este objeto.
*
* @return String Un String que representa a este objeto.
* @see java.lang.Object#toString()
*/
public String toString() {
return Integer.toString(index);
}
/**
* Devuelve un <code>int</code> que representa a este objeto.
*
* @return int un <code>int</code> que representa a este objeto.
*/
public int getValue() {
return index;
}
/**
* Devuelve un <code>String</code> con la traducción correspondiente al <code>Locale</code>
* pasado por parámetro.
*
* @return String un <code>String</code>.
*/
public String getName(Locale locale) {
ResourceBundle bundle = ResourceBundle.getBundle(BASE_NAME, locale);
return bundle.getString(MSG_KEY_PREFIX + getValue());
}
/**
* Compara este objeto con el especificado. Devuelve un entero negativo,
* cero o un entero positivo si este objeto es menor, igual o mayor que el
* indicado.
*
* @param obj
* El objeto a ser comparado.
* @return Un entero negativo, cero o un entero positivo si este objeto es
* menor, igual o mayor que el indicado.
* @see java.lang.Comparable#compareTo(Object)
*/
public int compareTo(Object obj) {
return compareTo((Priority) obj);
}
/**
* Compara este objeto con el especificado. Devuelve un entero negativo,
* cero o un entero positivo si este objeto es menor, igual o mayor que el
* indicado.
*
* @param ds
* El objeto a ser comparado.
* @return Un entero negativo, cero o un entero positivo si este objeto es
* menor, igual o mayor que el indicado.
* @see java.lang.Comparable#compareTo(Object)
*/
private int compareTo(Priority ds) {
if (this == ds) {
return 0;
}
return (this.index < ds.index) ? (-1) : (+1);
}
/**
* Devuelve el tipo de estado del evento correspondiente.
*
* @param b
* El identificativo de este estado del evento.
* @return El tipo de estado del evento.
*/
public static Priority get(byte b) {
if (b < 0 || b >= ALL.length) {
throw new ArrayIndexOutOfBoundsException(" Looking for item " + b //$NON-NLS-1$
+ " on a " + ALL.length + "-length array."); //$NON-NLS-2$ //$NON-NLS-1$
}
return ALL[b];
}
/**
* Devuelve el tipo de estado del expediente correspondiente.
*
* @param name
* @param locale
* @return El tipo de estado del evento.
*/
public static Priority get(String name, Locale locale) {
Iterator iter = getList().iterator();
while (iter.hasNext()) {
Priority element = (Priority) iter.next();
if (name.equals(element.getName(locale)))
return element;
}
return null;
}
/**
* Devuelve una lista no modificable los enumerados de <code>Priority</code>.
*
* @return
*/
public static List getList() {
return Arrays.asList(ALL);
}
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | development/samples/training/bitmapfun/src/com/example/android/bitmapfun/util/ImageResizer.java | 9037 | /*
* Copyright (C) 2012 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.example.android.bitmapfun.util;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import com.example.android.bitmapfun.BuildConfig;
import java.io.FileDescriptor;
/**
* A simple subclass of {@link ImageWorker} that resizes images from resources given a target width
* and height. Useful for when the input images might be too large to simply load directly into
* memory.
*/
public class ImageResizer extends ImageWorker {
private static final String TAG = "ImageResizer";
protected int mImageWidth;
protected int mImageHeight;
/**
* Initialize providing a single target image size (used for both width and height);
*
* @param context
* @param imageWidth
* @param imageHeight
*/
public ImageResizer(Context context, int imageWidth, int imageHeight) {
super(context);
setImageSize(imageWidth, imageHeight);
}
/**
* Initialize providing a single target image size (used for both width and height);
*
* @param context
* @param imageSize
*/
public ImageResizer(Context context, int imageSize) {
super(context);
setImageSize(imageSize);
}
/**
* Set the target image width and height.
*
* @param width
* @param height
*/
public void setImageSize(int width, int height) {
mImageWidth = width;
mImageHeight = height;
}
/**
* Set the target image size (width and height will be the same).
*
* @param size
*/
public void setImageSize(int size) {
setImageSize(size, size);
}
/**
* The main processing method. This happens in a background task. In this case we are just
* sampling down the bitmap and returning it from a resource.
*
* @param resId
* @return
*/
private Bitmap processBitmap(int resId) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "processBitmap - " + resId);
}
return decodeSampledBitmapFromResource(mResources, resId, mImageWidth, mImageHeight);
}
@Override
protected Bitmap processBitmap(Object data) {
return processBitmap(Integer.parseInt(String.valueOf(data)));
}
/**
* Decode and sample down a bitmap from resources to the requested width and height.
*
* @param res The resources object containing the image data
* @param resId The resource id of the image data
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @return A bitmap sampled down from the original with the same aspect ratio and dimensions
* that are equal to or greater than the requested width and height
*/
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
/**
* Decode and sample down a bitmap from a file to the requested width and height.
*
* @param filename The full path of the file to decode
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @return A bitmap sampled down from the original with the same aspect ratio and dimensions
* that are equal to or greater than the requested width and height
*/
public static Bitmap decodeSampledBitmapFromFile(String filename,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filename, options);
}
/**
* Decode and sample down a bitmap from a file input stream to the requested width and height.
*
* @param fileDescriptor The file descriptor to read from
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @return A bitmap sampled down from the original with the same aspect ratio and dimensions
* that are equal to or greater than the requested width and height
*/
public static Bitmap decodeSampledBitmapFromDescriptor(
FileDescriptor fileDescriptor, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
}
/**
* Calculate an inSampleSize for use in a {@link BitmapFactory.Options} object when decoding
* bitmaps using the decode* methods from {@link BitmapFactory}. This implementation calculates
* the closest inSampleSize that will result in the final decoded bitmap having a width and
* height equal to or larger than the requested width and height. This implementation does not
* ensure a power of 2 is returned for inSampleSize which can be faster when decoding but
* results in a larger bitmap which isn't as useful for caching purposes.
*
* @param options An options object with out* params already populated (run through a decode*
* method with inJustDecodeBounds==true
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @return The value to be used for inSampleSize
*/
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee a final image
// with both dimensions larger than or equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
}
| gpl-2.0 |
jchalco/Ate | sistema/sistema-ejb/src/java/bc/MercadoFacadeLocal.java | 481 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package bc;
import be.Mercado;
import java.util.List;
import javax.ejb.Local;
/**
*
* @author argos
*/
@Local
public interface MercadoFacadeLocal {
void create(Mercado mercado);
void edit(Mercado mercado);
void remove(Mercado mercado);
Mercado find(Object id);
List<Mercado> findAll();
List<Mercado> findRange(int[] range);
int count();
}
| gpl-2.0 |
Chris35Wills/SEB_model_java_files | SEB_model/source_code/Historical_Model_Precip_Elev_Fixed.java | 142083 | /**
*
* Distributed Surface Energy Balance (SEB) model source code (developed for my PhD)
* Copyright (C) 2013 Chris Williams
* 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
* 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.
*
* ****************************************************************************
*
*
* Historic model - normal data upload
* This version of the model fixes surface elevation. It updates elevation as a
* function ofice melt to enable updated slope and aspect geometries. However,
* lapse rate surfces (for bulk flux and sumemr precipitation calculations) and
* elevation surfaces for the winter precipitation thickness claculation are
* based on the initial DEM elevation values. The surface from which these are
* called is set outside of the main model loop. The changing elevation for
* thickness, slope and aspect change is calculated within the loop and
* therefore is allowed, itself, to change.
*
* @Chris 20/8/13
*/
package energymodels;
import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.ListIterator;
/**
*
* @author Chris
*/
public class Historical_Model_Precip_Elev_Fixed implements ActionListener {
private GUIPanel panel = null;
private Storage store = null;
Historical_Model_Precip_Elev_Fixed(GUIPanel panel, Storage store) {
this.panel = panel;
this.store = store;
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Historical model working");
double save_arrays = 4; // Set to 1, array saving code will be turned on
// | Set to 0, array saving code will be turned
// off
// | Set to 4 and Q surface will be saved
//***********************************
Iterator<Integer> iterator0 = store.getMonthFile_MAIN().iterator();
Iterator<Integer> iterator1 = store.getYearFile_MAIN().iterator();
Iterator<Double> iterator2 = store.getTemperatureFile().iterator();
Iterator<Double> iterator3 = store.getPrecipFile().iterator();
Iterator<Double> iterator4 = store.getPrecipSeasonList_MAIN().iterator();
Iterator<Double> iterator5 = store.getTauEstimateList().iterator();
Iterator<Integer> iterator6 = store.getYearFile_WinterPrecip().iterator();
Iterator<Double> iterator7 = store.get_Winter_PrecipFile().iterator();
Iterator<Double> iterator8 = store.get_Winter_MonthFile().iterator();
// ListIterator iterator6b = store.getYearFile_WinterPrecip().listIterator();
// ListIterator iterator7b = store.get_Winter_PrecipFile().listIterator();
// ListIterator iterator8b = store.get_Winter_MonthFile().listIterator();
// Loop counters
int Loop_counter = 0; //Must be initialized outside of loop
System.out.println("Let the historical model.....begin!");
// File f_stats = new File("F:/Melt_modelling/Historical_model_outputs/Historical_model_run_mean_stats.txt");
//// File f_stats = new File("F:/Melt_modelling/Historical_model_outputs_snow_thickness_m05/Historical_model_run_mean_stats.txt");
File f_stats = new File("C:/Users/Chris/Desktop/19261943/Historical_model_outputs_Elev_Fixed/Historical_model_run_mean_stats.txt");
FileWriter fw_stats;
DecimalFormat df_stats = new DecimalFormat("#.####");
try {
BufferedWriter bw_stats = new BufferedWriter(new FileWriter(f_stats));
bw_stats.write("Loop number" + ", " + "Month" + ", " + "Year" + ", " + "Mean Radiation (Wm^-2)" + ", "
+ "Mean Psi (Wm^-2)" + ", " + "Mean Q (Wm^-2)" + ", "
+ "Mean glacier air temp. (deg C)" + ", " + "Mean snowfall (m)"
+ ", " + "Mean surface melt (m)" + ", "
+ "Mean volume change (m^3)");
bw_stats.newLine();
double NODATA_value = -9999;
// VARIABLES TO CHANGE FOR SENSITIVITY ANALYSIS
double sensitivity_tau = 0.45;
store.setTauEstimate(sensitivity_tau);
double ice_density = 900.0;
double summer_snow_density = 200.0; // Taken from Paterson (1994) (p9, table 2.1)
double winter_snow_density = 407.13; // Average density value from 2008 - 2011 snow pit analysis
double snow_wind_stripping_factor = 0.5; //
double psi_min = -19;
double c = 8.4;
double T_tip = +0.2;
double ice_albedo = 0.39;//0.39
double snow_albedo = 0.70;
//double threshold_snow_thickness_for_albedo = 0.05; // Subject to change - threshold for acquiring albedo from layer beneath
double snow_threshold = 1.5; //1.5
// Temperature below which rain falls as snow
//double fresh_snow_density = 0.400; // Relative to 1.0 for water
System.out.println("Ice density: " + ice_density);
System.out.println("Summer snow density: " + summer_snow_density);
System.out.println("Winter snow density: " + winter_snow_density);
System.out.println("Snow stripping [wind] factor : " + snow_wind_stripping_factor);
System.out.println("Psi min: " + psi_min);
System.out.println("Variable c: " + c);
System.out.println("T_tip (Temp at which precip. falls as snow): " + T_tip);
System.out.println("Ice albedo: " + ice_albedo);
System.out.println("Snow_albedo: " + snow_albedo);
//System.out.println("Threshold for degradation of albedo according to snow thickness:" + threshold_snow_thickness_for_albedo);
/**
* Create empty surfaces for the summer and winter precipitation
* (these are populated in the iterator loops)
*/
double elevation1[][] = store.getElevation();
double elev_initial_size[][] = store.getElevation();
double summer_snow_thickness_INITIAL[][] = new double[elev_initial_size.length][elev_initial_size[0].length];
double winter_snow_thickness_INITIAL[][] = new double[elev_initial_size.length][elev_initial_size[0].length];
for (int i = 0; i < elevation1.length; i++) {
for (int j = 0; j < elevation1[i].length; j++) {
if (elevation1[i][j] != NODATA_value) {
summer_snow_thickness_INITIAL[i][j] = 0.0;
winter_snow_thickness_INITIAL[i][j] = 0.0;
} else {
summer_snow_thickness_INITIAL[i][j] = NODATA_value;
winter_snow_thickness_INITIAL[i][j] = NODATA_value;
}
}
}
store.setSummerSnowSurface(summer_snow_thickness_INITIAL);
store.setWinterSnowSurface(winter_snow_thickness_INITIAL);
// SET FIXED ELEVATION SURFACE FOR LAPSE RATE CALCULATIONS
double elevation_fixed[][] = store.getElevation();
store.setElevationFixedSurface(elevation_fixed);
// Begin loop through monthly file
while (iterator0.hasNext()) {
//System.out.println("Snow depth being tested: MINUS 0.5");
System.out.println("Elevation surface uploaded");
double elevation[][] = store.getElevation();
store.setElevationSize(elevation);
double Elevation_size[][] = store.getElevationSize();
double elevationFIXED[][] = store.getElevationFixedSurface();
System.out.println("Thickness surface uploaded");
double glacier_thickness[][] = store.getThickness(); //Only called once; following this, loops must use the updated thickness and elevation variables
double glacier_thickness_temp[][] = glacier_thickness; // This gets a copy of glacier_thickness
store.setThickness_intermediary(glacier_thickness_temp); // This sets the copy of thickness, making a clone of it (i.e. it can't be affcted if you alter the "glacier_thickness" object
double glacier_thickness_intermediary[][] = store.getThickness_intermediary(); //This gets the "clone" - so this will remain an unaltered thickness layer throughout the loop (unlike "glacierThickness[][]")
double summer_snow_thickness[][] = store.getSummerSnowSurface(); // An empty array in the first iteration of this loop
double winter_snow_thickness[][] = store.getWinterSnowSurface(); // An empty array in the first iteration of this loop
//double WinterSnow_interpolation[][];
double temp_winter_snow_layer[][] = new double[elevation.length][elevation[0].length];
//Slope variables
double Slope_Surface[][] = new double[Elevation_size.length][Elevation_size[0].length];
double slopeA, slopeB, slopeC, slopeD, slopeE, slopeF, slopeG, slopeH, slopeI;
double slope_dzdy, slope_dzdx;
double slopeDegree;
//Aspect variables
double aspectSurface[][] = new double[Elevation_size.length][Elevation_size[0].length];
double aspectA, aspectB, aspectC, aspectD, aspectE, aspectF, aspectG, aspectH, aspectI;
double aspect_dzdy, aspect_dzdx;
double aspect_pre;
double aspectDegree;
//Bulk flux variables
double cTa;
double psi = 0;
double lapsed_Ta;
double lapsed_temp[][] = new double[Elevation_size.length][Elevation_size[0].length];
double psi_surface[][] = new double[Elevation_size.length][Elevation_size[0].length];
//Q calculation variables
double albedo_instance = 0.0;
double Q_daily_grid[][] = new double[Elevation_size.length][Elevation_size[0].length];
double Q_monthly_grid[][] = new double[Elevation_size.length][Elevation_size[0].length];
double I_for_Q;
double psi_for_Q;
double Q, Q_daily, Q_monthly;
double Q_counter = 0;
double Q_total = 0;
double mean_Q_m2;
double mean_Q_5_x_m2;
double cell_area = 25.0;
//Radiation variables
double slope[][], aspect[][], slope_RAD[][], aspect_RAD[][],
surfaceRadiationSurface[][];
//double hillshade[][] = null;
double hillshade_midnight[][] = null;
double hillshade_6am[][] = null;
double hillshade_noon[][] = null;
double hillshade_6pm[][] = null;
double tau;
double azimuth_midnight_radians, zenith_midnight_radians; //Midnight variables
double azimuth_6am_radians, zenith_6am_radians; //6am variables
double azimuth_noon_radians, zenith_noon_radians; //noon variables
double azimuth_6pm_radians, zenith_6pm_radians; //6pm variables
double surface_Radiation = 0.0;
double surface_Radiation_midnight;
double surface_Radiation_6am;
double surface_Radiation_noon;
double surface_Radiation_6pm;
//Melt calculation variables
double adjustment_counter = 0;
double thickness_adjustment_total = 0;
double volume_adjustment_total = 0;
double ice_thickness_surface_adjustment[][] = new double[Elevation_size.length][Elevation_size[0].length];
double ice_thickness_change_surface[][] = new double[Elevation_size.length][Elevation_size[0].length];
double summer_snow_surface_change[][] = new double[Elevation_size.length][Elevation_size[0].length];
double winter_snow_surface_change[][] = new double[Elevation_size.length][Elevation_size[0].length];
double latent_heat_of_fusion = 334000;
double energy_for_total_summer_snow_melt;
double energy_for_total_winter_snow_melt;
double ice_mass;
double snow_mass;
double energy_for_total_melt;
double Q_available;
//Counters (zeroed at the beginning of each loop)
double Radiation_counter = 0;
double Radiation_total = 0;
double Psi_counter = 0;
double Psi_total = 0;
double Lapsed_temp_counter = 0;
double Lapsed_temp_total = 0;
double Snowfall_counter = 0;
double Snowfall_total = 0;
//Winter precip. variables
// Iterator<Integer> iterator6 = store.getYearFile_WinterPrecip().iterator();
// Iterator<Double> iterator7 = store.get_Winter_PrecipFile().iterator();
// Iterator<Double> iterator8 = store.get_Winter_MonthFile().iterator();
// int year_winter_precip = iterator6.next();
// double snow_thickness_winter_precip = iterator7.next();
// double month_winter_precip = iterator8.next();
int month = (int) iterator0.next();
int year = (int) iterator1.next();
double temp = iterator2.next();
store.setTemp(temp);
double precip = iterator3.next(); // This is the daily total precipitation in metres - check the input data file with the raw if you are unsure
double precip_season = iterator4.next();
System.out.println(month + "/" + year);
System.out.println("Temp: " + temp);
System.out.println("Precipitation (m): " + precip);
System.out.println("Precipitation season: " + precip_season);
/*
* Precipitation algorithm
*/
//**************Summer precipitation**************
// REMEMBER: when dividing precipitation by snow density, do not
// use the value in kg m^3 (e.g. 900.0 kg m^3). You must instead
// use that value divided by 100 (e.g. 0.9). In this way, where
// the threshold is not met rainfall at the cell is equal to the
// AWS (i.e. measured rainfall/1) To divide the emasured
// rainfall by water density (1000.0 kg m^3) would give very
// warped results!
if (precip_season == 1.0) {
System.out.println("Summer precipitation");
/*
* Lapse rate calculater
*/
for (int i = 0; i < elevationFIXED.length; i++) {
for (int j = 0; j < elevationFIXED[i].length; j++) {
double lapse_intermediary = elevationFIXED[i][j];
if (lapse_intermediary != NODATA_value) {
lapsed_temp[i][j] = (double) LapseRate(lapse_intermediary, temp);
} else if (lapse_intermediary == NODATA_value) {
lapsed_temp[i][j] = (int) NODATA_value;
}
}
}
store.setLapsedTempSurface(lapsed_temp);
/*
* Populate summer snow thickness layer
*/
System.out.println("Precip. value for use in summer precip. algorithm: " + precip + " m");
System.out.println("AWS temp. value for use in summer precip. algorithm: " + temp + "°C");
System.out.println("Summer snow density value for use in summer precip. algorithm: " + summer_snow_density);
for (int i = 0; i < summer_snow_thickness.length; i++) {
for (int j = 0; j < summer_snow_thickness[i].length; j++) {
if (((lapsed_temp[i][j] != NODATA_value) && (precip != NODATA_value)) && ((precip != 0) && (lapsed_temp[i][j] <= snow_threshold))) // If less than or equal to threshold, snow amount is equal to precip * fresh snow density
{
summer_snow_thickness[i][j] += (precip / (summer_snow_density / 100)); // Increase the value of the existing cell by new snow fall
store.setSummerSnowSurface(summer_snow_thickness);
} else if (((lapsed_temp[i][j] != NODATA_value) && (precip != NODATA_value)) && (lapsed_temp[i][j] > snow_threshold)) // This simulates rain which flows off the surface
{
summer_snow_thickness[i][j] += 0; // Increase the value of the existing cell by nothing (could just do nothing...)
store.setSummerSnowSurface(summer_snow_thickness);
} else if ((lapsed_temp[i][j] != NODATA_value) && (precip == NODATA_value)) // There are some instances where the AWS didn't work so this is pertinent
{
summer_snow_thickness[i][j] += 0;
store.setSummerSnowSurface(summer_snow_thickness);
} else if (lapsed_temp[i][j] == NODATA_value) {
summer_snow_thickness[i][j] = NODATA_value;
store.setSummerSnowSurface(summer_snow_thickness);
}
}
}
//store.setSummerSnowSurface(summer_snow_thickness);
} //**************Winter precipitation**************
//else if (((precip_season == 0.0) && (year == year_winter_precip)) && (month == month_winter_precip)) {
else if (precip_season == 0.0) {
System.out.println("Winter precipitation");
int year_winter_precip = 0;
double snow_thickness_winter_precip = 0.0;
double month_winter_precip = 0.0;
double winter_depth_test = 0.0;
//int year_winter_precip = iterator6.next();
//double snow_thickness_winter_precip = iterator7.next();
//double month_winter_precip = iterator8.next();
//int year_winter_precip = 2008;
//double snow_thickness_winter_precip = 2.567;
//double month_winter_precip = 7;
if (((month == 1) | (month == 2)) | ((month == 3) | (month == 4)) | (month == 5)) {
System.out.println("Use month count of year");
// Loop through winter_precip_list
for (int i = 0; i < store.getYearFile_WinterPrecip().size(); i++) {
int test_year = store.getYearFile_WinterPrecip().get(i);
winter_depth_test = store.get_Winter_PrecipFile().get(i);
double test_month = store.get_Winter_MonthFile().get(i);
// System.out.println("Start test loop (1)");
// System.out.println("test_year: " + test_year);
// System.out.println("winter_depth_test: " + winter_depth_test);
// System.out.println("test_month: " + test_month);
// System.out.println("End test loop (1)");
if (year == test_year) {
System.out.println("Bazinga years equal");
System.out.println("Year of main loop: " + year);
System.out.println("Year in winter precip. loop: " + test_year);
//snow_thickness_winter_precip = (winter_depth_test - 0.5); // SENSITIVITY
snow_thickness_winter_precip = winter_depth_test;
month_winter_precip = test_month;
System.out.println("winter_depth_test: " + winter_depth_test);
System.out.println("month_winter_precip: " + month_winter_precip);
}
else
{
// Do nothing so loop again
}
}
} else if (((month == 9) | (month == 10)) | ((month == 11) | (month == 12))) {
System.out.println("Use month count of following year");
// Loop through winter_precip_list
for (int i = 0; i < store.getYearFile_WinterPrecip().size(); i++) {
int test_year = store.getYearFile_WinterPrecip().get(i);
winter_depth_test = store.get_Winter_PrecipFile().get(i);
double test_month = store.get_Winter_MonthFile().get(i);
// System.out.println("Start test loop (2)");
// System.out.println("test_year: " + test_year);
// System.out.println("winter_depth_test: " + winter_depth_test);
// System.out.println("test_month: " + test_month);
// System.out.println("End test loop (2)");
if ((year + 1) == test_year) {
System.out.println("Bazinga year +1");
System.out.println("Year of main loop: " + year);
System.out.println("Year in winter precip. loop: " + test_year);
// snow_thickness_winter_precip = (winter_depth_test - 0.5); // SENSITIVITY TEST
snow_thickness_winter_precip = winter_depth_test;
month_winter_precip = test_month;
System.out.println("winter_depth_test: " + winter_depth_test);
System.out.println("month_winter_precip: " + month_winter_precip);
}
else
{
// Do nothing so loop again
}
}
}
System.out.println("Out of while loops now");
System.out.println("snow_thickness_winter_precip: " + snow_thickness_winter_precip);
System.out.println("month_winter_precip: " + month_winter_precip);
//(1) Zeros the snow thickness surface (summer snow at the end of
//summer is assumed to be a part of the winter snow pack that was
//measured in the field at the end of march and is therefore already
//accounted for in the daily winter snowfall algorithm
//(1b) [Possible addition] Maybe zero the winter snow pack....
for (int i = 0; i < summer_snow_thickness.length; i++) {
for (int j = 0; j < summer_snow_thickness[i].length; j++) {
if (summer_snow_thickness[i][j] != NODATA_value) {
summer_snow_thickness[i][j] = 0.0;
store.setSummerSnowSurface(summer_snow_thickness);
} else if (summer_snow_thickness[i][j] == NODATA_value) {
summer_snow_thickness[i][j] = NODATA_value;
store.setSummerSnowSurface(summer_snow_thickness);
}
}
}
//(2) Calculate mean monthly winter snowfall
//double snow_to_accumulate = (snow_thickness_winter_precip/month_winter_precip);
System.out.println("Main model loop: " + month + "/" + year);
System.out.println("Winter precip: " + month_winter_precip + "/" + year_winter_precip);
System.out.println("Total snow thickness:" + snow_thickness_winter_precip);
//System.out.println("Mean snow thickness:" + snow_to_accumulate);
//(3) Distribute monthly snow across surface as a function
// of elevation using:
// [y = -28.39 + 0.05252x - 0.00002181x^2] * snow_to_accumulate
// where x is elevation
//
// NOTE: IF ELEVATION DISTRIBUTED SNOW THICKNESS IS LESS
// THAN 1.0M, IT IS SET TO 1.0M
for (int i = 0; i < winter_snow_thickness.length; i++) {
for (int j = 0; j < winter_snow_thickness[i].length; j++) {
double y = 0.0;
if (winter_snow_thickness[i][j] != NODATA_value) {
double elev_instance_x = elevationFIXED[i][j];
double regressmean_yearmean_diff = (2.854751 - snow_thickness_winter_precip);
// 2.854751 is the mean on which the regression
// is based - the difference between this mean
// and the year specific mean is required to
// correct the regression to the year to which
// it is applied
//
// Essentially, 2.854751 is the mean snow
// thickness for 2010/2011
double snow_thickness_limit = (-28.39 + (0.05252 * 964.331943)) - (0.00002181 * (964.331943 * 964.331943)) - regressmean_yearmean_diff;
// where snow thickness values fall below
// predicted snow depth as calculated for the
// minimum elevation (964.3m) from which the
// regression curve was created (with the
// addition/subtraction of the difference in
// means), snow thickness will be set to this
// calculated value. In implementing this
// method, snow thickness values will have a
// finite limit.
if(regressmean_yearmean_diff >= 0) // i.e. ANS < Glacier mean
{
// Add on the mean diffs to correct the regression to the new mean
y = (-28.39 + (0.05252 * elev_instance_x)) - (0.00002181 * (elev_instance_x * elev_instance_x)) - regressmean_yearmean_diff;
}
else if(regressmean_yearmean_diff < 0) // i.e. ANS > Glacier mean
{
// Removes the minus sign
regressmean_yearmean_diff = (regressmean_yearmean_diff * -1);
// Add on the mean diffs to correct the regression to the new mean
y = (-28.39 + (0.05252 * elev_instance_x)) - (0.00002181 * (elev_instance_x * elev_instance_x)) + regressmean_yearmean_diff;
}
//double elev_dependent_snow_acummulation = y;
if (y >= 1.0) {
// Prevents exceeding winter snow thickness total at a given elevation.
//
// NOTE: the cap is the total measured snowfall lapsed up to the elevation
// i.e. (snow_thickness_winter_precip*y)
// and NOT "elev_dependent_snow_acummulation" ITSELF (this is just a mean addition)
//
// This caps snow in a similar way to zeroing any previous season
// winter snow at the beginning of a new winter season.
if(winter_snow_thickness[i][j] < y)
{
winter_snow_thickness[i][j] += (y/month_winter_precip); // If less than the elevation corrected total, add on a monthly portion of the total
store.setWinterSnowSurface(winter_snow_thickness);
}
else if(winter_snow_thickness[i][j] > y)
{
winter_snow_thickness[i][j] = y; // If it's going to be greater than the elevation corrected total, it equals the total
store.setWinterSnowSurface(winter_snow_thickness);
}
}
else if (y < snow_thickness_limit)
{
winter_snow_thickness[i][j] += (snow_thickness_limit/month_winter_precip); // Adds a monthly portion of snow_thickness_limit (according to number of winter months)
store.setWinterSnowSurface(winter_snow_thickness);
}
else if (y <= 0.0)
{
winter_snow_thickness[i][j] += (snow_thickness_limit/month_winter_precip); // Adds a monthly portion of snow_thickness_limit (according to number of winter months)
store.setWinterSnowSurface(winter_snow_thickness);
}
store.setWinterSnowSurface(winter_snow_thickness);
} else if (winter_snow_thickness[i][j] == NODATA_value) {
winter_snow_thickness[i][j] = NODATA_value;
store.setWinterSnowSurface(winter_snow_thickness);
}
}
}
}
/**
* Loops through the WinterSnowSurface layer and calculates mean
* total accumulated thickness on a given day
*/
double winter_snow_thickness_total = 0; // Has to be done here. If set as 0 outide the loop the total will grow forever
double winter_snow_thickness_counter = 0; // Has to be done here. If set as 0 outide the loop the total will grow forever
for (int i = 0; i < winter_snow_thickness.length; i++) {
for (int j = 0; j < winter_snow_thickness[i].length; j++) {
if (winter_snow_thickness[i][j] != NODATA_value) {
//System.out.println("Winter snow cells: " + winter_snow_thickness[i][j]);
double winter_snow_thickness_instance = winter_snow_thickness[i][j];
winter_snow_thickness_total += winter_snow_thickness_instance; // Accumulates all summer snow thickness changes
winter_snow_thickness_counter++; // Counts instances of summer snow thickness where != NODATA_value
} else if (winter_snow_thickness[i][j] == NODATA_value) {
//do nothing
}
}
}
System.out.println("Mean accumulated winter snowfall at this point: " + winter_snow_thickness_total / winter_snow_thickness_counter + "m");
store.setWinterSnowThickness(winter_snow_thickness);
if (save_arrays == 1) {
/**
* This bit will open a save box to save the monthly psi
* surface as an ASCII, using the coordinates of the
* originally opened up elevation surface
*
*/
File f_summer_precip = new File("F:/Melt_modelling/Historical_model_outputs_Elev_Fixed/summer_precip_" + month + "_" + year + ".txt");
DecimalFormat df_summer_precip = new DecimalFormat("#.####");
try {
BufferedWriter bw_summer_precip = new BufferedWriter(new FileWriter(f_summer_precip));
bw_summer_precip.write("ncols" + " " + store.getOriginalNcols());
bw_summer_precip.write(System.getProperty("line.separator"));
bw_summer_precip.write("nrows" + " " + store.getOriginalNrows());
bw_summer_precip.write(System.getProperty("line.separator"));
bw_summer_precip.write("xllcorner" + " " + store.getOriginalXllcorner());
bw_summer_precip.write(System.getProperty("line.separator"));
bw_summer_precip.write("yllcorner" + " " + store.getOriginalYllcorner());
bw_summer_precip.write(System.getProperty("line.separator"));
bw_summer_precip.write("cellsize" + " " + store.getOriginalCellsize());
bw_summer_precip.write(System.getProperty("line.separator"));
bw_summer_precip.write("NODATA_value" + " " + "-9999");
bw_summer_precip.write(System.getProperty("line.separator"));
/**
* Write out the array data
*
*/
String tempStr = "";
for (int a = 0; a < summer_snow_thickness.length; a++) {
for (int b = 0; b < summer_snow_thickness[a].length; b++) {
if (summer_snow_thickness[a][b] == NODATA_value) {
bw_summer_precip.write("-9999 ");
} else {
bw_summer_precip.write(df_summer_precip.format(summer_snow_thickness[a][b]) + " ");
}
}
bw_summer_precip.newLine();
}
bw_summer_precip.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Summer snow thickness surface for " + month + "/" + year + " saved: " + f_summer_precip.getAbsolutePath());
} else {
// Do not save arrays
}
if (save_arrays == 1) {
/**
* This bit will open a save box to save the monthly psi
* surface as an ASCII, using the coordinates of the
* originally opened up elevation surface
*
*/
File f_winter_precip = new File("F:/Melt_modelling/Historical_model_outputs_Elev_Fixed/winter_precip_" + month + "_" + year + ".txt");
DecimalFormat df_winter_precip = new DecimalFormat("#.####");
try {
BufferedWriter bw_winter_precip = new BufferedWriter(new FileWriter(f_winter_precip));
bw_winter_precip.write("ncols" + " " + store.getOriginalNcols());
bw_winter_precip.write(System.getProperty("line.separator"));
bw_winter_precip.write("nrows" + " " + store.getOriginalNrows());
bw_winter_precip.write(System.getProperty("line.separator"));
bw_winter_precip.write("xllcorner" + " " + store.getOriginalXllcorner());
bw_winter_precip.write(System.getProperty("line.separator"));
bw_winter_precip.write("yllcorner" + " " + store.getOriginalYllcorner());
bw_winter_precip.write(System.getProperty("line.separator"));
bw_winter_precip.write("cellsize" + " " + store.getOriginalCellsize());
bw_winter_precip.write(System.getProperty("line.separator"));
bw_winter_precip.write("NODATA_value" + " " + "-9999");
bw_winter_precip.write(System.getProperty("line.separator"));
/**
* Write out the array data
*
*/
String tempStr = "";
for (int a = 0; a < winter_snow_thickness.length; a++) {
for (int b = 0; b < winter_snow_thickness[a].length; b++) {
if (winter_snow_thickness[a][b] == NODATA_value) {
bw_winter_precip.write("-9999 ");
} else {
bw_winter_precip.write(df_winter_precip.format(winter_snow_thickness[a][b]) + " ");
}
}
bw_winter_precip.newLine();
}
bw_winter_precip.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Winter snow thickness surface for " + month + "/" + year + " saved: " + f_winter_precip.getAbsolutePath());
} else {
// Do not save arrays
}
/*
* Slope calculation
*/
for (int i = 0; i < elevation.length; i++) {
for (int j = 0; j < elevation[i].length; j++) {
if (elevation[i][j] != NODATA_value) {
// Try/catch blocks exist in case of "out of bounds exceptions"
// which are likely when running the neighborhood searches at the
// array edges - this will be called upon less when using the
// larger arrays populated with No_Data (i.e. -9999.0) values
//
// These assign the values to letters A-I, according to positions
// within the array assuming the structure of:
// A B C
// D E F
// G H I
try {
if ((elevation[i - 1][j - 1] != NODATA_value)) {
slopeA = elevation[i - 1][j - 1];
} else {
slopeA = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe0) {
slopeA = elevation[i][j];
}
try {
if ((elevation[i - 1][j] != NODATA_value)) {
slopeB = elevation[i - 1][j];
} else {
slopeB = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe1) {
slopeB = elevation[i][j];
}
try {
if ((elevation[i - 1][j + 1] != NODATA_value)) {
slopeC = elevation[i - 1][j + 1];
} else {
//error1 = ("C fail");//
slopeC = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe2) {
//error1 = ("C fail catch"); //
slopeC = elevation[i][j];
}
try {
if ((elevation[i][j - 1] != NODATA_value)) {
slopeD = elevation[i][j - 1];
} else {
slopeD = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe3) {
slopeD = elevation[i][j];
}
try {
if ((elevation[i][j] != NODATA_value)) {
slopeE = elevation[i][j];
} else {
slopeE = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe4) {
slopeE = elevation[i][j];
}
try {
if ((elevation[i][j + 1] != NODATA_value)) {
slopeF = elevation[i][j + 1];
} else {
slopeF = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe5) {
slopeF = elevation[i][j];
}
try {
if ((elevation[i + 1][j - 1] != NODATA_value)) {
slopeG = elevation[i + 1][j - 1];
} else {
slopeG = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe6) {
slopeG = elevation[i][j];
}
try {
if ((elevation[i + 1][j] != NODATA_value)) {
slopeH = elevation[i + 1][j];
} else {
slopeH = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe7) {
slopeH = elevation[i][j];
}
try {
if ((elevation[i + 1][j + 1] != NODATA_value)) {
slopeI = elevation[i + 1][j + 1];
} else {
slopeI = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe8) {
slopeI = elevation[i][j];
}
slope_dzdx = (((slopeC + (2 * slopeF) + slopeI) - (slopeA + (2 * slopeD) + slopeG)) / (8 * 5));
slope_dzdy = (((slopeG + (2 * slopeH) + slopeI) - (slopeA + (2 * slopeB) + slopeC)) / (8 * 5));
slopeDegree = Math.atan(Math.sqrt((Math.pow(slope_dzdx, 2)
+ Math.pow(slope_dzdy, 2)))) * (180 / Math.PI);
Slope_Surface[i][j] = slopeDegree;
} else if (elevation[i][j] == NODATA_value) {
Slope_Surface[i][j] = NODATA_value;
}
}
}
store.setSlope(Slope_Surface);
//System.out.println("Slope calculated");
/*
* Aspect calculation
*/
for (int i = 0; i < elevation.length; i++) {
for (int j = 0; j < elevation[i].length; j++) {
if (elevation[i][j] != NODATA_value) {
// Try/catch blocks exist in case of "out of bounds exceptions"
// which are likely when running the neighborhood searches at the
// array edges - this will be called upon less when using the
// larger arrays populated with No_Data (i.e. -9999.0) values
//
// These assign the values to letters A-I, according to positions
// within the array assuming the structure of:
// A B C
// D E F
// G H I
try {
if ((elevation[i - 1][j - 1] != NODATA_value)) {
aspectA = elevation[i - 1][j - 1];
} else {
aspectA = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe0) {
aspectA = elevation[i][j];
}
try {
if ((elevation[i - 1][j] != NODATA_value)) {
aspectB = elevation[i - 1][j];
} else {
aspectB = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe1) {
aspectB = elevation[i][j];
}
try {
if ((elevation[i - 1][j + 1] != NODATA_value)) {
aspectC = elevation[i - 1][j + 1];
} else {
//error1 = ("C fail");//
aspectC = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe2) {
//error1 = ("C fail catch"); //
aspectC = elevation[i][j];
}
try {
if ((elevation[i][j - 1] != NODATA_value)) {
aspectD = elevation[i][j - 1];
} else {
aspectD = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe3) {
aspectD = elevation[i][j];
}
try {
if ((elevation[i][j] != NODATA_value)) {
aspectE = elevation[i][j];
} else {
aspectE = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe4) {
aspectE = elevation[i][j];
}
try {
if ((elevation[i][j + 1] != NODATA_value)) {
aspectF = elevation[i][j + 1];
} else {
aspectF = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe5) {
aspectF = elevation[i][j];
}
try {
if ((elevation[i + 1][j - 1] != NODATA_value)) {
aspectG = elevation[i + 1][j - 1];
} else {
aspectG = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe6) {
aspectG = elevation[i][j];
}
try {
if ((elevation[i + 1][j] != NODATA_value)) {
aspectH = elevation[i + 1][j];
} else {
aspectH = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe7) {
aspectH = elevation[i][j];
}
try {
if ((elevation[i + 1][j + 1] != NODATA_value)) {
aspectI = elevation[i + 1][j + 1];
} else {
aspectI = elevation[i][j];
}
} catch (ArrayIndexOutOfBoundsException aiobe8) {
aspectI = elevation[i][j];
}
// Breaks down the aspect algorithm into a few different steps
aspect_dzdx = (((aspectC + (2 * aspectF) + aspectI) - (aspectA + (2 * aspectD) + aspectG)) / (8));
aspect_dzdy = (((aspectG + (2 * aspectH) + aspectI) - (aspectA + (2 * aspectB) + aspectC)) / (8));
aspect_pre = ((180 / Math.PI) * Math.atan2(aspect_dzdy, -aspect_dzdx));
// Insert if loop to convert aspect to compass direction (degrees)
if (aspect_pre < 0) {
aspectDegree = (90.0 - aspect_pre);
} else if (aspect_pre > 90.0) {
aspectDegree = (360.0 - aspect_pre + 90.0);
} else {
aspectDegree = (90.0 - aspect_pre);
}
// Sets the aspect value in the appropriate position in the
// aspectSurface array
aspectSurface[i][j] = aspectDegree;
} else {
aspectSurface[i][j] = NODATA_value;
}
}
}
store.setAspect(aspectSurface);
/*
* Bulk flux calculation
*/
System.out.println("Temp value used in bulk flux equation: " + temp);
for (int i = 0; i < elevationFIXED.length; i++) {
for (int j = 0; j < elevationFIXED[i].length; j++) {
double Elevation_for_bulk_flux = elevationFIXED[i][j];
if (Elevation_for_bulk_flux != NODATA_value) {
lapsed_temp[i][j] = (double) LapseRate(Elevation_for_bulk_flux, temp);
lapsed_Ta = lapsed_temp[i][j];
// Calculate value of psi [INTEGRATE THIS INTO ABOVE LOOP]
if (lapsed_Ta >= T_tip) {
cTa = (c * lapsed_Ta);
psi = psi_min + cTa;
psi_surface[i][j] = psi;
} else if (lapsed_Ta < T_tip) {
psi = psi_min;
psi_surface[i][j] = psi;
}
} else if (Elevation_for_bulk_flux == NODATA_value) {
lapsed_temp[i][j] = (int) NODATA_value;
psi = NODATA_value;
psi_surface[i][j] = NODATA_value;
}
store.setPsi(psi);
store.setPsiSurface(psi_surface);
store.setLapsedTempSurface(lapsed_temp);
}
}
System.out.println("Bulk flux surface created for " + month + "/" + year);
if (save_arrays == 1) {
/**
* This bit will open a save box to save the monthly psi
* surface as an ASCII, using the coordinates of the
* originally opened up elevation surface
*
*/
File f_monthly_psi = new File("F:/Melt_modelling/Historical_model_outputs_Elev_Fixed/monthly_psi_" + month + "_" + year + ".txt");
DecimalFormat df_monthly_psi = new DecimalFormat("#.####");
try {
BufferedWriter bw_monthly_psi = new BufferedWriter(new FileWriter(f_monthly_psi));
bw_monthly_psi.write("ncols" + " " + store.getOriginalNcols());
bw_monthly_psi.write(System.getProperty("line.separator"));
bw_monthly_psi.write("nrows" + " " + store.getOriginalNrows());
bw_monthly_psi.write(System.getProperty("line.separator"));
bw_monthly_psi.write("xllcorner" + " " + store.getOriginalXllcorner());
bw_monthly_psi.write(System.getProperty("line.separator"));
bw_monthly_psi.write("yllcorner" + " " + store.getOriginalYllcorner());
bw_monthly_psi.write(System.getProperty("line.separator"));
bw_monthly_psi.write("cellsize" + " " + store.getOriginalCellsize());
bw_monthly_psi.write(System.getProperty("line.separator"));
bw_monthly_psi.write("NODATA_value" + " " + "-9999");
bw_monthly_psi.write(System.getProperty("line.separator"));
/**
* Write out the array data
*
*/
String tempStr = "";
for (int a = 0; a < psi_surface.length; a++) {
for (int b = 0; b < psi_surface[a].length; b++) {
if (psi_surface[a][b] == NODATA_value) {
bw_monthly_psi.write("-9999 ");
} else {
bw_monthly_psi.write(df_monthly_psi.format(psi_surface[a][b]) + " ");
}
}
bw_monthly_psi.newLine();
}
bw_monthly_psi.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Monthly radiation surface for " + month + "/" + year + " saved: " + f_monthly_psi.getAbsolutePath());
} else {
// Do not save arrays
}
/**
* Hillshade and slope/aspect radian conversion - preliminary to
* the radiation algorithm
*/
if (month == 1.0) {
//hillshade = store.getHillshade_Jan();
hillshade_midnight = store.getHillshade_Jan_midnight();
hillshade_6am = store.getHillshade_Jan_6am();
hillshade_noon = store.getHillshade_Jan_noon();
hillshade_6pm = store.getHillshade_Jan_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
//System.out.println("January hillshade uploaded into model");
//System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("January hillshade not uploaded");
}
} else if (month == 2.0) {
//hillshade = store.getHillshade_Feb();
hillshade_midnight = store.getHillshade_Feb_midnight();
hillshade_6am = store.getHillshade_Feb_6am();
hillshade_noon = store.getHillshade_Feb_noon();
hillshade_6pm = store.getHillshade_Feb_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
//System.out.println("February hillshade uploaded into model");
//System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("February hillshade not uploaded");
}
} else if (month == 3.0) {
//hillshade = store.getHillshade_March();
hillshade_midnight = store.getHillshade_March_midnight();
hillshade_6am = store.getHillshade_March_6am();
hillshade_noon = store.getHillshade_March_noon();
hillshade_6pm = store.getHillshade_March_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("March hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("March hillshade not uploaded");
}
} else if (month == 4.0) {
//hillshade = store.getHillshade_April();
hillshade_midnight = store.getHillshade_April_midnight();
hillshade_6am = store.getHillshade_April_6am();
hillshade_noon = store.getHillshade_April_noon();
hillshade_6pm = store.getHillshade_April_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("April hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("April hillshade not uploaded");
}
} else if (month == 5.0) {
//hillshade = store.getHillshade_May();
hillshade_midnight = store.getHillshade_May_midnight();
hillshade_6am = store.getHillshade_May_6am();
hillshade_noon = store.getHillshade_May_noon();
hillshade_6pm = store.getHillshade_May_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("May hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("May hillshade not uploaded");
}
} else if (month == 6.0) {
//hillshade = store.getHillshade_June();
hillshade_midnight = store.getHillshade_June_midnight();
hillshade_6am = store.getHillshade_June_6am();
hillshade_noon = store.getHillshade_June_noon();
hillshade_6pm = store.getHillshade_June_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("June hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("June hillshade not uploaded");
}
} else if (month == 7.0) {
//hillshade = store.getHillshade_July();
hillshade_midnight = store.getHillshade_July_midnight();
hillshade_6am = store.getHillshade_July_6am();
hillshade_noon = store.getHillshade_July_noon();
hillshade_6pm = store.getHillshade_July_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("July hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("July hillshade not uploaded");
}
} else if (month == 8.0) {
//hillshade = store.getHillshade_August();
hillshade_midnight = store.getHillshade_August_midnight();
hillshade_6am = store.getHillshade_August_6am();
hillshade_noon = store.getHillshade_August_noon();
hillshade_6pm = store.getHillshade_August_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("August hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("August hillshade not uploaded");
}
} else if (month == 9.0) {
//hillshade = store.getHillshade_Sept();
hillshade_midnight = store.getHillshade_Sept_midnight();
hillshade_6am = store.getHillshade_Sept_6am();
hillshade_noon = store.getHillshade_Sept_noon();
hillshade_6pm = store.getHillshade_Sept_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("September hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("September hillshade not uploaded");
}
} else if (month == 10.0) {
//hillshade = store.getHillshade_Oct();
hillshade_midnight = store.getHillshade_Oct_midnight();
hillshade_6am = store.getHillshade_Oct_6am();
hillshade_noon = store.getHillshade_Oct_noon();
hillshade_6pm = store.getHillshade_Oct_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("October hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("October hillshade not uploaded");
}
} else if (month == 11.0) {
//hillshade = store.getHillshade_Nov();
hillshade_midnight = store.getHillshade_Nov_midnight();
hillshade_6am = store.getHillshade_Nov_6am();
hillshade_noon = store.getHillshade_Nov_noon();
hillshade_6pm = store.getHillshade_Nov_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("November hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("November hillshade not uploaded");
}
} else if (month == 12.0) {
//hillshade = store.getHillshade_Dec();
hillshade_midnight = store.getHillshade_Dec_midnight();
hillshade_6am = store.getHillshade_Dec_6am();
hillshade_noon = store.getHillshade_Dec_noon();
hillshade_6pm = store.getHillshade_Dec_6pm();
if (hillshade_midnight != null | hillshade_6am != null | hillshade_noon != null | hillshade_6pm != null) {
// System.out.println("December hillshade uploaded into model");
// System.out.println("Month: " + month);
} else if (hillshade_midnight == null | hillshade_6am == null | hillshade_noon == null | hillshade_6pm == null) {
System.out.println("December hillshade not uploaded");
}
}
//Gets the calculated slope and aspect surfaces
slope = store.getSlope(); // slope surface array
aspect = store.getAspect(); // aspect surface array
slope_RAD = new double[slope.length][slope[0].length];
aspect_RAD = new double[slope.length][slope[0].length];
//Converts the slope and aspect surfaces to radians
for (int a = 0; a < Slope_Surface.length; a++) {
for (int b = 0; b < Slope_Surface[a].length; b++) {
if (slope[a][b] != NODATA_value) {
double slope_initial_value = Slope_Surface[a][b];
double slope_radians = Math.toRadians(slope_initial_value);
slope_RAD[a][b] = slope_radians;
} else {
slope_RAD[a][b] = NODATA_value;
}
if (aspectSurface[a][b] != NODATA_value) {
double aspect_initial_value = aspectSurface[a][b];
double aspect_radians = Math.toRadians(aspect_initial_value);
aspect_RAD[a][b] = aspect_radians;
} else {
aspect_RAD[a][b] = NODATA_value;
}
}
}
//System.out.println("Just before radiation loop");
/**
* Internal Radiation loop: during each month loop, this daily
* radiation loop is instigated.
*
* This loop first accesses all of the lists created upon upload
* of the radiation input file. Where the month and year values
* from the radiation lists match the month and year of the
* overall monthly time step loop (starting somewhere up above
* and in which this secondary iteration loop exists), radiation
* calculations are carried out for each day. The mean daily
* radiation amount is calculated and totaled within the array
* (i.e. each loop, the current loops mean daily radiation is
* summed with the last value present at the same position in
* the array). At the end of the radiation loop, the cells of
* the array are divided by the number of days (which is
* represented by the loop counter of radiation loop, to give a
* monthly mean.
*
* Required prior to loop initiation: - Radiation loop counter
* to be set to 0 - MonthlyRadiation total to be set to 0
*
*/
double radiation_loop_counter = 0;
double monthlyRadiationTotal = 0;
surfaceRadiationSurface = new double[elevation.length][elevation[0].length];
// Read in radiation iterators
// Implement Rdaiation code
// When month_radiation == month and year_radiation == year, get next using the day as the iterator
Iterator<Integer> iteratora = store.getDayFile_Radiation().iterator();
Iterator<Integer> iteratorb = store.getMonthFile_Radiation().iterator();
Iterator<Integer> iteratorc = store.getYearFile_Radiation().iterator();
Iterator<Double> iteratord = store.getTOA_midnight_list().iterator();
Iterator<Double> iteratore = store.getZenith_midnight_list().iterator();
Iterator<Double> iteratorf = store.getAzimuth_midnight_list().iterator();
Iterator<Double> iteratorg = store.getTOA_6am_list().iterator();
Iterator<Double> iteratorh = store.getZenith_6am_list().iterator();
Iterator<Double> iteratori = store.getAzimuth_6am_list().iterator();
Iterator<Double> iteratorj = store.getTOA_noon_list().iterator();
Iterator<Double> iteratork = store.getZenith_noon_list().iterator();
Iterator<Double> iteratorl = store.getAzimuth_noon_list().iterator();
Iterator<Double> iteratorm = store.getTOA_6pm_list().iterator();
Iterator<Double> iteratorn = store.getZenith_6pm_list().iterator();
Iterator<Double> iteratoro = store.getAzimuth_6pm_list().iterator();
//Melt algorithm check counters
int summersnow_hit = 0;
int nosummersnow_hit = 0;
int summersnow_wintersnow_hit = 0;
int summersnow_no_wintersnow_hit = 0;
int summersnow_wintersnow_ice = 0;
//int summersnow_no_wintersnow_ice = 0;
int no_summersnow_wintersnow_hit = 0;
int no_summersnow_no_wintersnow_hit = 0;
int no_summersnow_wintersnow_ice = 0;
tau = store.getTauEstimate();
System.out.println("Tau being utilised: " + tau);
while (iteratora.hasNext()) {
int day_radiation = iteratora.next();
int month_radiation = iteratorb.next();
int year_radiation = iteratorc.next();
double TOA_midnight = iteratord.next();
double zenith_midnight = iteratore.next();
double azimuth_midnight = iteratorf.next();
double TOA_6am = iteratorg.next();
double zenith_6am = iteratorh.next();
double azimuth_6am = iteratori.next();
double TOA_noon = iteratorj.next();
double zenith_noon = iteratork.next();
double azimuth_noon = iteratorl.next();
double TOA_6pm = iteratorm.next();
double zenith_6pm = iteratorn.next();
double azimuth_6pm = iteratoro.next();
if ((month_radiation == month) && (year_radiation == year)) {
//System.out.println("Radiation algorithm reached (" + month_radiation + "/" + year_radiation + ")");
radiation_loop_counter++;
//System.out.println("Rad loop number: " + radiation_loop_counter);
//surfaceRadiationSurface = new double[elevation.length][elevation[0].length];
// tau = store.getTauEstimate();
// System.out.println("Tau being utilised: " + tau);
for (int i = 0; i < slope_RAD.length; i++) {
for (int j = 0; j < slope_RAD[i].length; j++) {
surface_Radiation_midnight = 0;
surface_Radiation_6am = 0;
surface_Radiation_noon = 0;
surface_Radiation_6pm = 0;
//******************************************************************
// Midnight radiation calculation
//******************************************************************
// These would be taken from lists in the full
azimuth_midnight_radians = Math.toRadians(azimuth_midnight); // model but for this run just use a single
zenith_midnight_radians = Math.toRadians(zenith_midnight); // value i.e. read in a one line input met
// data file
// Start looping through surfaces and implement equation - this would be
// nested in an array list loop eventually
// slope_RAD[i][j] = aspect_RAD[i][j] = hillshade[i][j];
double loop_slope1 = slope_RAD[i][j];
double loop_aspect1 = aspect_RAD[i][j];
double loop_hillshade_midnight = hillshade_midnight[i][j]; // If you want to account for topog. shading
// double loop_hillshade = 1.0; // Use to set clear sky conditions (i.e. no topog. shading)
if (((loop_slope1 != NODATA_value) & (loop_aspect1 != NODATA_value)) & (loop_hillshade_midnight != NODATA_value)) {
if (zenith_midnight <= 84.0) { // Prevents development of rogue values from discontinuity between zenith/azimuth/TOA at low sun altitudes - note that this referes to the zenith in degrees
//************** MODIFIED SURFACE RADIATION EQUATION
// surface_Radiation_midnight = ((100-loop_hillshade1)/100) * (((Math.cos(zenith_midnight_radians)*Math.cos(loop_slope1))
//surface_Radiation_midnight = (1) * (((Math.cos(zenith_midnight_radians)*Math.cos(loop_slope1))
surface_Radiation_midnight = (loop_hillshade_midnight / 255.0) * (((Math.cos(zenith_midnight_radians) * Math.cos(loop_slope1))
+ (Math.sin(zenith_midnight_radians) * Math.sin(loop_slope1) * Math.cos(azimuth_midnight_radians - loop_aspect1)))
* TOA_midnight * Math.exp(-tau / Math.cos(zenith_midnight_radians)));
// System.out.println("Midnight surface rad: " + surface_Radiation_midnight);
} else if (zenith_midnight > 84.0) {
surface_Radiation_midnight = 0.0;
//System.out.println("Noon surface rad: " + surface_Radiation_noon);
}
}
//******************************************************************
// 6am radiation calculation
//******************************************************************
// These would be taken from lists in the full
azimuth_6am_radians = Math.toRadians(azimuth_6am); // model but for this run just use a single
zenith_6am_radians = Math.toRadians(zenith_6am); // value i.e. read in a one line input met
// data file
//System.out.println("Azimuth 6am (rad) = " + azimuth_6am_radians);
//System.out.println("Zenith 6am (rad) = " + zenith_6am_radians);
//slope_RAD[i][j] = aspect_RAD[i][j] = hillshade[i][j];
double loop_slope2 = slope_RAD[i][j];
double loop_aspect2 = aspect_RAD[i][j];
double loop_hillshade_6am = hillshade_6am[i][j]; // If you want to account for topog. shading
// double loop_hillshade = 1.0; // Use to set clearsky conditions (i.e. no topog. shading)
if (((loop_slope2 != NODATA_value) & (loop_aspect2 != NODATA_value)) & (loop_hillshade_6am != NODATA_value)) {
if (zenith_6am <= 84.0) { // Prevents development of rogue values from discontinuity between zenith/azimuth/TOA at low sun altitudes - note that this referes to the zenith in degrees
//************** MODIFIED SURFACE RADIATION EQUATION
// surface_Radiation_6am = ((100-loop_hillshade2)/100) * (((Math.cos(zenith_6am_radians)*Math.cos(loop_slope2))
//surface_Radiation_6am = (1) * (((Math.cos(zenith_6am_radians)*Math.cos(loop_slope2))
surface_Radiation_6am = (loop_hillshade_6am / 255.0) * (((Math.cos(zenith_6am_radians) * Math.cos(loop_slope2))
+ (Math.sin(zenith_6am_radians) * Math.sin(loop_slope2) * Math.cos(azimuth_6am_radians - loop_aspect2)))
* TOA_6am * Math.exp(-tau / Math.cos(zenith_6am_radians)));
//System.out.println("6am surface rad: " + surface_Radiation_6am);
} else if (zenith_6am > 84.0) {
surface_Radiation_6am = 0.0;
//System.out.println("Noon surface rad: " + surface_Radiation_noon);
}
}
//******************************************************************
// noon radiation calculation
//******************************************************************
// These would be taken from lists in the full
azimuth_noon_radians = Math.toRadians(azimuth_noon); // model but for this run just use a single
zenith_noon_radians = Math.toRadians(zenith_noon); // value i.e. read in a one line input met
// data file
//System.out.println("Azimuth noon (rad) = " + azimuth_noon_radians);
//System.out.println("Zenith noon (rad) = " + zenith_noon_radians);
//slope_RAD[i][j] = aspect_RAD[i][j] = hillshade[i][j];
double loop_slope3 = slope_RAD[i][j];
double loop_aspect3 = aspect_RAD[i][j];
double loop_hillshade_noon = hillshade_noon[i][j]; // If you want to account for topog. shading
// double loop_hillshade = 1.0; // Use to set clearsky conditions (i.e. no topog. shading)
if (((loop_slope3 != NODATA_value) & (loop_aspect3 != NODATA_value)) & (loop_hillshade_noon != NODATA_value)) {
if (zenith_noon <= 84.0) { // Prevents development of rogue values from discontinuity between zenith/azimuth/TOA at low sun altitudes - note that this referes to the zenith in degrees
//************** MODIFIED SURFACE RADIATION EQUATION
// surface_Radiation_noon = ((100-loop_hillshade3)/100) * (((Math.cos(zenith_noon_radians)*Math.cos(loop_slope3))
//surface_Radiation_noon = (1) * (((Math.cos(zenith_noon_radians)*Math.cos(loop_slope3))
surface_Radiation_noon = (loop_hillshade_noon / 255.0) * (((Math.cos(zenith_noon_radians) * Math.cos(loop_slope3))
+ (Math.sin(zenith_noon_radians) * Math.sin(loop_slope3) * Math.cos(azimuth_noon_radians - loop_aspect3)))
* TOA_noon * Math.exp(-tau / Math.cos(zenith_noon_radians)));
//System.out.println("Noon surface rad: " + surface_Radiation_noon);
} else if (zenith_noon > 84.0) {
surface_Radiation_noon = 0.0;
//System.out.println("Noon surface rad: " + surface_Radiation_noon);
}
}
//******************************************************************
// 6pm radiation calculation
//******************************************************************
// These would be taken from lists in the full
azimuth_6pm_radians = Math.toRadians(azimuth_6pm); // model but for this run just use a single
zenith_6pm_radians = Math.toRadians(zenith_6pm); // value i.e. read in a one line input met
// data file
//System.out.println("Azimuth 6pm (rad) = " + azimuth_6pm_radians);
//System.out.println("Zenith 6pm (rad) = " + zenith_6pm_radians);
// slope_RAD[i][j] = aspect_RAD[i][j] = hillshade[i][j];
double loop_slope4 = slope_RAD[i][j];
double loop_aspect4 = aspect_RAD[i][j];
double loop_hillshade_6pm = hillshade_6pm[i][j]; // If you want to account for topog. shading
// double loop_hillshade = 1.0; // Use to set clearsky conditions (i.e. no topog. shading)
if (((loop_slope4 != NODATA_value) & (loop_aspect4 != NODATA_value)) & (loop_hillshade_6pm != NODATA_value)) {
if (zenith_6pm <= 84.0) { // Prevents development of rogue values from discontinuity between zenith/azimuth/TOA at low sun altitudes - note that this referes to the zenith in degrees
//************** MODIFIED SURFACE RADIATION EQUATION
//surface_Radiation_6pm = (1) * (((Math.cos(zenith_6pm_radians)*Math.cos(loop_slope4))
surface_Radiation_6pm = (loop_hillshade_6pm / 255.0) * (((Math.cos(zenith_6pm_radians) * Math.cos(loop_slope4))
+ (Math.sin(zenith_6pm_radians) * Math.sin(loop_slope4) * Math.cos(azimuth_6pm_radians - loop_aspect4)))
* TOA_6pm * Math.exp(-tau / Math.cos(zenith_6pm_radians)));
//System.out.println("6pm surface rad: " + surface_Radiation_6pm);
} else if (zenith_6pm > 84.0) {
surface_Radiation_6pm = 0.0;
//System.out.println("Noon surface rad: " + surface_Radiation_noon);
}
// Need to total surface_radiation_[time_interval] up for each loop and to create daily mean radiation
//monthlyRadiationTotal += dailyRadiationMean;
}
//***************************** Create radiation surface ****************************************************
if ((elevation[i][j] == NODATA_value)) {
// System.out.println("No data populated for rad");
surfaceRadiationSurface[i][j] = NODATA_value;
store.setSurfaceRadiationSurface(surfaceRadiationSurface);
// System.out.println("surface_rad NODATA_value populated");
} else if ((elevation[i][j] != NODATA_value) & ((surface_Radiation_midnight != NODATA_value) & (surface_Radiation_6am != NODATA_value)) & ((surface_Radiation_noon != NODATA_value) & (surface_Radiation_6pm != NODATA_value))) {
//surface_Radiation += ((surface_Radiation_midnight + surface_Radiation_6am + surface_Radiation_noon + surface_Radiation_6pm) / 4.0);
surfaceRadiationSurface[i][j] += ((surface_Radiation_midnight + surface_Radiation_6am + surface_Radiation_noon + surface_Radiation_6pm) / 4.0);
//System.out.println("Surface radiation [accum] calc: " + surfaceRadiationSurface[i][j]);
//double surfRadinstance = ((surface_Radiation_midnight + surface_Radiation_6am + surface_Radiation_noon + surface_Radiation_6pm) / 4.0);
//System.out.println("Surface radiation [instance] calc: " + surfRadinstance);
if (surfaceRadiationSurface[i][j] >= 0.000001) {
// System.out.println("Rad >= 0.000001 populated");
//surfaceRaditionSurface[i][j] = surfaceRadiationSurface[i][j];
store.setSurfaceRadiationSurface(surfaceRadiationSurface);
} else if ((surfaceRadiationSurface[i][j] < 0.000001) & (surfaceRadiationSurface[i][j] != NODATA_value)) {
// System.out.println("Rad < 0.000001 populated");
surfaceRadiationSurface[i][j] = 0.0;
store.setSurfaceRadiationSurface(surfaceRadiationSurface);
}
}
}
}
}
}
System.out.println("Radiation loop counter: " + radiation_loop_counter);
/**
* Calculating monthly mean surface radiation surface. Loops
* through set surfaceRadiationSurface, dividing each cell by
* the number of days in the prior radiation loop. *
*
*/
double daily_surfaceRadiationSurface[][] = store.getSurfaceRadiationSurface();// Gets the SurfaceRadiationSurface array which consisits of monthly totals (total of daily mean values)
double meanMonthlyRadiation = 0;
if (daily_surfaceRadiationSurface != null) {
System.out.println("Calculating monthly mean surface radiation surface");
double raw_rad_total = 0;
double meanrad_total = 0;
double rad_cellcount = 0;
//meanMonthlyRadiation = monthlyRadiationTotal / radiation_loop_counter;
//double meanMonthlyRadiation_surface [][] = new double[][];
for (int i = 0; i < daily_surfaceRadiationSurface.length; i++) {
for (int j = 0; j < daily_surfaceRadiationSurface[i].length; j++) {
if (daily_surfaceRadiationSurface[i][j] == NODATA_value) {
//macht nichts
} else if (daily_surfaceRadiationSurface[i][j] != NODATA_value) {
raw_rad_total += daily_surfaceRadiationSurface[i][j];
double dailyrad_instance = daily_surfaceRadiationSurface[i][j];
meanMonthlyRadiation = dailyrad_instance / radiation_loop_counter;
daily_surfaceRadiationSurface[i][j] = meanMonthlyRadiation;
store.setSurfaceRadiationSurface(daily_surfaceRadiationSurface);
meanrad_total += meanMonthlyRadiation; // This mean is for the whole grid (i.e. this is not a mean monthly cell value (requires the result to be divided by number of cells))
rad_cellcount++;
}
}
}
//System.out.println("cell count: " + rad_cellcount);
//System.out.println("Raw raditaion total: " + raw_rad_total);
//System.out.println("raditaion total: " + meanrad_total);
System.out.println("Mean radiation for " + month + "/" + year + ": " + (meanrad_total / rad_cellcount));
//System.out.println("End of radiation loop reached - go back to start of main monthly loop");
if (save_arrays == 1) {
/**
* This bit will open a save box to save the mean
* radiation surface as an ASCII, using the coordinates
* of the originally opened up elevation surface
*
*/
File f_monthly_rad = new File("F:/Melt_modelling/Historical_model_outputs_Elev_Fixed/mean_monthly_rad_" + month + "_" + year + ".txt");
DecimalFormat df_monthly_rad = new DecimalFormat("#.####");
try {
BufferedWriter bw_monthly_rad = new BufferedWriter(new FileWriter(f_monthly_rad));
bw_monthly_rad.write("ncols" + " " + store.getOriginalNcols());
bw_monthly_rad.write(System.getProperty("line.separator"));
bw_monthly_rad.write("nrows" + " " + store.getOriginalNrows());
bw_monthly_rad.write(System.getProperty("line.separator"));
bw_monthly_rad.write("xllcorner" + " " + store.getOriginalXllcorner());
bw_monthly_rad.write(System.getProperty("line.separator"));
bw_monthly_rad.write("yllcorner" + " " + store.getOriginalYllcorner());
bw_monthly_rad.write(System.getProperty("line.separator"));
bw_monthly_rad.write("cellsize" + " " + store.getOriginalCellsize());
bw_monthly_rad.write(System.getProperty("line.separator"));
bw_monthly_rad.write("NODATA_value" + " " + "-9999");
bw_monthly_rad.write(System.getProperty("line.separator"));
/**
* Write out the array data
*
*/
String tempStr = "";
for (int a = 0; a < daily_surfaceRadiationSurface.length; a++) {
for (int b = 0; b < daily_surfaceRadiationSurface[a].length; b++) {
if (daily_surfaceRadiationSurface[a][b] == NODATA_value) {
bw_monthly_rad.write("-9999 ");
} else {
bw_monthly_rad.write(df_monthly_rad.format(daily_surfaceRadiationSurface[a][b]) + " ");
}
}
bw_monthly_rad.newLine();
}
bw_monthly_rad.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Monthly radiation surface for " + month + "/" + year + "saved: " + f_monthly_rad.getAbsolutePath());
} else {
// Do not save arrays
}
/*
* Q calculation
*/
// double[][] Q_daily_grid = new double[elevation.length][elevation[0].length];
// double I_for_Q;
// double psi_for_Q;
// double Q, Q_daily;
// double Q, Q_daily, mean_Q;
// double Q_counter = 0;
for (int i = 0; i < elevation.length; i++) {
for (int j = 0; j < elevation[i].length; j++) {
if ((summer_snow_thickness[i][j] != NODATA_value) && (summer_snow_thickness[i][j] > 0.0)) {
albedo_instance = snow_albedo;
} else if ((winter_snow_thickness[i][j] != NODATA_value) && (winter_snow_thickness[i][j] > 0.0)) {
albedo_instance = snow_albedo;
} else {
albedo_instance = ice_albedo;
}
//albedo_instance = 0.5;
I_for_Q = store.getSurfaceRadiationSurface()[i][j];
psi_for_Q = store.getPsiSurface()[i][j];
if ((I_for_Q != NODATA_value) & (psi_for_Q != NODATA_value)) {
Q = ((1 - albedo_instance) * I_for_Q) + psi_for_Q; //<<<----- This gives a value of Q per m^2 - the actual cell area (5m x 5m) or full months time has not been considered yet
Q_daily = (Q * 86400) * cell_area; // Multiplies Q value by the number of seconds in a day and scales it up to the cell area (so if a 5m x 5m cell, multiply Q by 25)
Q_monthly = Q_daily * radiation_loop_counter; // The radiation loop counter accounts for the number of days in the month, specific to year and month
//System.out.println("Q daily: " + Q_daily);
//Q_daily_grid[i][j] = Q_daily; // Sets the Q_daily value in the Q_daily_grid
Q_monthly_grid[i][j] = Q_monthly; // Sets the Q_monthly value in the Q_monthly_grid
Q_counter++; // Counts instances of Q where != NODATA_value
//Q_total += Q_daily; // Total value of scaled up Q for a day through each full model loop
Q_total += Q_monthly; // Total value of scaled up Q for a month through each full model loop
} else if ((I_for_Q == NODATA_value) | (psi_for_Q == NODATA_value)) {
Q_monthly_grid[i][j] = NODATA_value;
}
store.setQmonthlySurface(Q_monthly_grid);
}
}
mean_Q_5_x_m2 = Q_total / Q_counter; //<<---- Mean energy for a 5m x 5m cell (so units are W x 5m^-2)
mean_Q_m2 = (Q_total / Q_counter) / 25.0; //<<<---- Mean energy for a 1m x 1m cell (so units are Wm^-2)
System.out.println("Q calculated: " + mean_Q_5_x_m2 + " W x 5m^-2"); //<<---- Mean energy for a 5m x 5m cell (so units are W x 5m^-2)
System.out.println("Q calculated: " + mean_Q_m2 + " W x m^-2"); //<<<---- Mean energy for a 1m x 1m cell (so units are Wm^-2)
/**
* This bit will open a save box to save the Q surface layer
* as an ASCII, using the coordinates of the originally
* opened up elevation surface. This is the MONTHLY surface
* (i.e. not in Wm^-2 (or per second)
*/
if ((save_arrays == 1)|(save_arrays == 4)) {
// File f_Q_monthly = new File("F:/Melt_modelling/Historical_model_outputs/Q_monthly_" + (int) month + "." + (int) year + ".txt");
File f_Q_monthly = new File("C:/Users/Chris/Desktop/19261943/Historical_model_outputs_Elev_Fixed/Q_monthly_" + (int) month + "." + (int) year + ".txt");
// //File f_Q_monthly = new File("F:/Melt_modelling/Historical_model_outputs_snow_thickness_m05/Q_monthly_" + (int) month + "." + (int) year + ".txt");
DecimalFormat df_Q_monthly = new DecimalFormat("#.####");
//
try {
BufferedWriter bw_Q_monthly = new BufferedWriter(new FileWriter(f_Q_monthly));
bw_Q_monthly.write("ncols" + " " + store.getOriginalNcols());
bw_Q_monthly.write(System.getProperty("line.separator"));
bw_Q_monthly.write("nrows" + " " + store.getOriginalNrows());
bw_Q_monthly.write(System.getProperty("line.separator"));
bw_Q_monthly.write("xllcorner" + " " + store.getOriginalXllcorner());
bw_Q_monthly.write(System.getProperty("line.separator"));
bw_Q_monthly.write("yllcorner" + " " + store.getOriginalYllcorner());
bw_Q_monthly.write(System.getProperty("line.separator"));
bw_Q_monthly.write("cellsize" + " " + store.getOriginalCellsize());
bw_Q_monthly.write(System.getProperty("line.separator"));
bw_Q_monthly.write("NODATA_value" + " " + "-9999");
bw_Q_monthly.write(System.getProperty("line.separator"));
/**
* Write out the array data
*
*/
//String tempStr = "";
for (int a = 0; a < Q_monthly_grid.length; a++) {
for (int b = 0; b < Q_monthly_grid[a].length; b++) {
if (Q_monthly_grid[a][b] == NODATA_value) {
bw_Q_monthly.write("-9999 ");
} else {
bw_Q_monthly.write(df_Q_monthly.format(Q_monthly_grid[a][b]) + " ");
}
}
bw_Q_monthly.newLine();
}
bw_Q_monthly.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Q [monthly] surface: " + f_Q_monthly.getAbsolutePath());
} else {
// Do not save array
}
/**
* Surface melting.
*
* Melts through the summer snow surface, then the winter
* surface and then the ice surface. Accounts for remaining
* Q, where Q available > Q required to melt. In this way,
* energy is conserved and used on the next layer that can
* be melted.
*/
for (int i = 0; i < summer_snow_thickness.length; i++) {
for (int j = 0; j < summer_snow_thickness[i].length; j++) {
double Q_for_melt = Q_monthly_grid[i][j];
double glacier_thickness_instance = glacier_thickness[i][j];
double winter_snow_surface_instance = winter_snow_thickness[i][j];
double summer_snow_surface_instance = summer_snow_thickness[i][j];
double summer_snow_surface_change_instance = summer_snow_surface_change[i][j];
double winter_snow_surface_change_instance = winter_snow_surface_change[i][j];
//double ice_thickness_change_surface_instance = ice_thickness_change_surface[i][j];
double ice_thickness_change = ice_thickness_change_surface[i][j];
// First loop - when there is energy, positive thickness values and Q is a positive number
if (((summer_snow_surface_instance != NODATA_value) && (Q_for_melt != NODATA_value)) && ((summer_snow_surface_instance > 0.0) && (Q_for_melt > 0.0))) {
summersnow_hit++;
double summer_snow_volume = summer_snow_surface_instance * cell_area;
double summer_snow_mass = summer_snow_volume * summer_snow_density;
energy_for_total_summer_snow_melt = summer_snow_mass * latent_heat_of_fusion;
summer_snow_surface_change_instance = (Q_for_melt / energy_for_total_summer_snow_melt) * summer_snow_surface_instance; // Calculates a ratio of available melt to required melt and multiplies by thickness to make the appropriate reduction
summer_snow_surface_change[i][j] = summer_snow_surface_change_instance; // Populates thickness change grid - this may allow for more change than is possible considering the actual thickness surface hence the next step
// Calculates the remaining energy available (i.e. used in instances where there is more energy available than there is snow to melt)
if ((energy_for_total_summer_snow_melt - Q_for_melt) < 0.0) // A negative value is indicative of Q_for_melt > Q required so gives you the remainding energy
{
Q_for_melt = (Q_for_melt - energy_for_total_summer_snow_melt); // Inverts the negative value to make the remainding energy positive
} else {
Q_for_melt = 0.0;
}
// Now deal with WINTER snow
// If snow thickness is positive and there is energy
if (((winter_snow_surface_instance != NODATA_value) && (Q_for_melt != NODATA_value)) && ((winter_snow_surface_instance > 0.0) && (Q_for_melt > 0.0))) {
summersnow_wintersnow_hit++;
double winter_snow_volume = winter_snow_surface_instance * cell_area;
double winter_snow_mass = winter_snow_volume * (winter_snow_density * snow_wind_stripping_factor);
// The snow stripping factor in effect
// reduces the amount of snow present - this
// replicates the effect wind would have in
// removing the snow, not asa function of
// melting
energy_for_total_winter_snow_melt = winter_snow_mass * latent_heat_of_fusion;
winter_snow_surface_change_instance = (Q_for_melt / energy_for_total_winter_snow_melt) * winter_snow_surface_instance; // Calculates a ratio of available melt to required melt and multiplies by thickness to make the appropriate reduction
winter_snow_surface_change[i][j] = winter_snow_surface_change_instance; // Populates thickness change grid - this may allow for more change than is possible considering the actual thickness surface hence the next step
// Calculates the remaining energy available (i.e. used in instances where there is more energy available than there is snow to melt)
if ((energy_for_total_winter_snow_melt - Q_for_melt) < 0.0) // A negative value is indicative of Q_for_melt > Q required so gives you the remainding energy
{
Q_for_melt = (Q_for_melt - energy_for_total_winter_snow_melt); // Inverts the negative value to make the remainding energy positive
} else {
Q_for_melt = 0.0;
}
} // If snow thickness is equal to 0 or there is no energy
else if ((winter_snow_surface_instance == 0.0) | (Q_for_melt <= 0.0)) // Required so that if winter_snow_surface is already zero or there is no energy, then nothing is done
{
summersnow_no_wintersnow_hit++;
winter_snow_surface_change_instance = 0.0;
winter_snow_surface_change[i][j] = 0.0;
} // If snow thickness is equal to NODATA_value or there is no energy
else if ((winter_snow_surface_instance == NODATA_value) | (Q_for_melt == NODATA_value)) {
winter_snow_surface_change[i][j] = NODATA_value;
}
// Deal with ICE
if (((glacier_thickness_instance != NODATA_value) && (Q_for_melt != NODATA_value)) && ((glacier_thickness_instance > 0.0) && (Q_for_melt > 0.0))) {
//double thickness = glacier_thickness_instance;
summersnow_wintersnow_ice++;
double ice_volume = glacier_thickness_instance * cell_area;
ice_mass = ice_volume * ice_density;
energy_for_total_melt = ice_mass * latent_heat_of_fusion;
ice_thickness_change = (Q_for_melt / energy_for_total_melt) * glacier_thickness_instance; // Calculates a ratio of available melt to required melt and multiplies by thickness to make the appropriate reduction
ice_thickness_change_surface[i][j] = ice_thickness_change; // Populates thickness change grid - this may allow for more change than is possible considering the actual thickness surface hence the next step
// Calculates the remaining energy available (i.e. used in instances where there is more energy available than there is snow to melt)
if ((energy_for_total_melt - Q_for_melt) < 0.0) // A negative value is indicative of Q_for_melt > Q required so gives you the remainding energy
{
Q_for_melt = (Q_for_melt - energy_for_total_melt); // Inverts the negative value to make the remainding energy positive
} else {
Q_for_melt = 0.0;
}
} // If ice thickness is equal to 0 or there is no energy
else if ((glacier_thickness_instance == 0.0) | (Q_for_melt <= 0.0)) // Required so that if winter_snow_surface is already zero or there is no energy, then nothing is done
{
ice_thickness_change = 0.0;
ice_thickness_change_surface[i][j] = 0.0;
} // If ice thickness is equal to NODATA_value or there is no energy
else if ((glacier_thickness_instance == NODATA_value) | (Q_for_melt == NODATA_value)) {
ice_thickness_change_surface[i][j] = NODATA_value;
}
} // Second loop - when there is energy, but summer snow thickness values are 0 -> for winter snow, thickness values > 0 and energy is positive
else if (((summer_snow_surface_instance != NODATA_value) && (Q_for_melt != NODATA_value)) && ((summer_snow_surface_instance == 0.0) && (Q_for_melt > 0.0))) {
nosummersnow_hit++;
//summer_snow_surface_instance = 0.0;
summer_snow_surface_change_instance = 0.0;
summer_snow_surface_change[i][j] = summer_snow_surface_change_instance;
// Now deal with WINTER snow
// If snow thickness is positive and there is energy
if ((winter_snow_surface_instance != NODATA_value) && (Q_for_melt != NODATA_value) && (winter_snow_surface_instance > 0.0) && (Q_for_melt > 0.0)) {
no_summersnow_wintersnow_hit++;
double winter_snow_volume = winter_snow_surface_instance * cell_area;
double winter_snow_mass = winter_snow_volume * (winter_snow_density * snow_wind_stripping_factor);
// The snow stripping factor in effect
// reduces the amount of snow present - this
// replicates the effect wind would have in
// removing the snow, not asa function of
// melting
energy_for_total_winter_snow_melt = winter_snow_mass * latent_heat_of_fusion;
winter_snow_surface_change_instance = (Q_for_melt / energy_for_total_winter_snow_melt) * winter_snow_surface_instance; // Calculates a ratio of available melt to required melt and multiplies by thickness to make the appropriate reduction
winter_snow_surface_change[i][j] = winter_snow_surface_change_instance; // Populates thickness change grid - this may allow for more change than is possible considering the actual thickness surface hence the next step
// Calculates the remaining energy available (i.e. used in instances where there is more energy available than there is snow to melt)
if ((energy_for_total_winter_snow_melt - Q_for_melt) < 0.0) // A negative value is indicative of Q_for_melt > Q required so gives you the remainding energy
{
Q_for_melt = (Q_for_melt - energy_for_total_winter_snow_melt); // Inverts the negative value to make the remainding energy positive
} else {
Q_for_melt = 0.0;
}
} // If snow thickness is equal to 0 or there is no energy
else if ((winter_snow_surface_instance == 0.0) | (Q_for_melt <= 0.0)) // Required so that if winter_snow_surface is already zero or there is no energy, then nothing is done
{
no_summersnow_no_wintersnow_hit++;
winter_snow_surface_change_instance = 0.0;
winter_snow_surface_change[i][j] = 0.0;
} // If snow thickness is equal to NODATA_value or there is no energy
else if ((winter_snow_surface_instance == NODATA_value) | (Q_for_melt == NODATA_value)) {
winter_snow_surface_change[i][j] = NODATA_value;
}
// Deal with ICE
if (((glacier_thickness_instance != NODATA_value) && (Q_for_melt != NODATA_value)) && ((glacier_thickness_instance > 0.0) && (Q_for_melt > 0.0))) {
//double thickness = glacier_thickness_instance;
no_summersnow_wintersnow_ice++;
double ice_volume = glacier_thickness_instance * cell_area;
ice_mass = ice_volume * ice_density;
energy_for_total_melt = ice_mass * latent_heat_of_fusion;
ice_thickness_change = (Q_for_melt / energy_for_total_melt) * glacier_thickness_instance; // Calculates a ratio of available melt to required melt and multiplies by thickness to make the appropriate reduction
ice_thickness_change_surface[i][j] = ice_thickness_change; // Populates thickness change grid - this may allow for more change than is possible considering the actual thickness surface hence the next step
// Calculates the remaining energy available (i.e. used in instances where there is more energy available than there is snow to melt)
if ((energy_for_total_melt - Q_for_melt) < 0) // A negative value is indicative of Q_for_melt > Q required so gives you the remainding energy
{
Q_for_melt = (energy_for_total_melt - Q_for_melt) * -1; // Inverts the negative value to make the remainding energy positive
} else {
Q_for_melt = 0.0;
}
} // If ice thickness is equal to 0 or there is no energy
else if ((glacier_thickness_instance == 0) | (Q_for_melt <= 0)) // Required so that if winter_snow_surface is already zero or there is no energy, then nothing is done
{
ice_thickness_change = 0.0;
ice_thickness_change_surface[i][j] = 0.0;
} // If ice thickness is equal to NODATA_value or there is no energy
else if ((glacier_thickness_instance == NODATA_value) | (Q_for_melt == NODATA_value)) {
ice_thickness_change_surface[i][j] = NODATA_value;
}
}
// Update surfaces
//Update summer snow thickness
if ((summer_snow_surface_change[i][j] != NODATA_value) && (summer_snow_thickness[i][j] != NODATA_value)) {
if ((summer_snow_thickness[i][j] - summer_snow_surface_change[i][j]) >= 0.0) {
summer_snow_thickness[i][j] = summer_snow_thickness[i][j] - summer_snow_surface_change[i][j];
} else if ((summer_snow_thickness[i][j] - summer_snow_surface_change[i][j]) < 0.0) {
summer_snow_thickness[i][j] = 0.0;
} else if ((summer_snow_surface_change[i][j] == NODATA_value) | (summer_snow_thickness[i][j] == NODATA_value)) {
summer_snow_thickness[i][j] = NODATA_value;
}
}
store.setSummerSnowSurface(summer_snow_thickness);
//Update winter snow thickness
if ((winter_snow_surface_change[i][j] != NODATA_value) && (winter_snow_thickness[i][j] != NODATA_value)) {
if ((winter_snow_thickness[i][j] - winter_snow_surface_change[i][j]) >= 0.0) {
winter_snow_thickness[i][j] = winter_snow_thickness[i][j] - winter_snow_surface_change[i][j];
} else if ((winter_snow_thickness[i][j] - winter_snow_surface_change[i][j]) < 0.0) {
winter_snow_thickness[i][j] = 0.0;
} else if ((winter_snow_surface_change[i][j] == NODATA_value) | (winter_snow_thickness[i][j] == NODATA_value)) {
winter_snow_thickness[i][j] = NODATA_value;
}
}
store.setWinterSnowSurface(winter_snow_thickness);
//Update glacier ice thickness
if ((ice_thickness_change_surface[i][j] != NODATA_value) && (glacier_thickness[i][j] != NODATA_value)) {
if ((glacier_thickness[i][j] - ice_thickness_change_surface[i][j]) >= 0.0) {
glacier_thickness[i][j] = glacier_thickness[i][j] - ice_thickness_change_surface[i][j];
} else if ((glacier_thickness[i][j] - ice_thickness_change_surface[i][j]) < 0.0) {
glacier_thickness[i][j] = 0.0;
} else if ((ice_thickness_change_surface[i][j] == NODATA_value) | (glacier_thickness[i][j] == NODATA_value)) {
glacier_thickness[i][j] = NODATA_value;
}
}
//store.setThickness(glacier_thickness);
// summer_snow_thickness[i][j] = summer_snow_thickness[i][j] - summer_snow_surface_change[i][j];
// winter_snow_thickness[i][j] = winter_snow_thickness[i][j] - winter_snow_surface_change[i][j];
// glacier_thickness[i][j] = glacier_thickness[i][j] - ice_thickness_change_surface[i][j];
store.setSummerSnowSurface(summer_snow_thickness);
store.setWinterSnowSurface(winter_snow_thickness);
store.setThickness(glacier_thickness);
}
}
//*********************************************************************************************************************************************************
/**
* Loops through ice_thickness_surface_adjustment and
* populates it with values equal to
* glacier_thickness_intermediary - glacier_thickness. The
* output of this is a correct calculation of actual surface
* melt).
*
*/
for (int i = 0; i < ice_thickness_surface_adjustment.length; i++) {
for (int j = 0; j < ice_thickness_surface_adjustment[i].length; j++) {
if ((glacier_thickness[i][j] == NODATA_value) | (glacier_thickness_intermediary[i][j] == NODATA_value)) {
ice_thickness_surface_adjustment[i][j] = NODATA_value;
} else if ((glacier_thickness[i][j] != NODATA_value) & (glacier_thickness_intermediary[i][j] != NODATA_value)) {
ice_thickness_surface_adjustment[i][j] = glacier_thickness_intermediary[i][j] - glacier_thickness[i][j];
// Accumulation of adjustment values to give daily mean melt
double thickness_adjustment_instance = ice_thickness_surface_adjustment[i][j];
thickness_adjustment_total += thickness_adjustment_instance; // Accumulates all thickness change
adjustment_counter++; // Counts instances of glacier thickness where != NODATA_value
double ice_volume_adjustment = thickness_adjustment_instance * cell_area;
volume_adjustment_total += ice_volume_adjustment; // Accumulates all thickness change
}
}
}
DecimalFormat df_mean_melt = new DecimalFormat("0.00");
double Daily_mean_ice_thickness_change = thickness_adjustment_total / adjustment_counter;
double Daily_mean_ice_volume_change = volume_adjustment_total / adjustment_counter;
//System.out.println("Daily mean thickness change: " + df_mean_melt.format(Daily_mean_ice_thickness_change) + "m");
//System.out.println("Daily mean volume change: " + Daily_mean_ice_volume_change + "m^3");
/**
* Updates elevation surface and re-sets it for use at the
* top of the loop
*
*/
for (int i = 0; i < elevation.length; i++) {
for (int j = 0; j < elevation[i].length; j++) {
if ((elevation[i][j] != NODATA_value) & (ice_thickness_surface_adjustment[i][j] != NODATA_value)) {
elevation[i][j] = elevation[i][j] - ice_thickness_surface_adjustment[i][j];
} else if ((elevation[i][j] == NODATA_value) | (ice_thickness_surface_adjustment[i][j] == NODATA_value)) {
elevation[i][j] = NODATA_value;
}
}
}
store.setElevation(elevation);
elevation = store.getElevation();
/**
* This bit will open a save box to save the updated
* thickness layer as an ASCII, using the coordinates of the
* originally opened up elevation surface
*
*/
if (save_arrays == 1) {
File f_glacier_thickness = new File("F:/Melt_modelling/Historical_model_outputs_Elev_Fixed/updated_thickness_" + (int) month + "." + (int) year + ".txt");
DecimalFormat df_glacier_thickness = new DecimalFormat("#.####");
try {
BufferedWriter bw_glacier_thickness = new BufferedWriter(new FileWriter(f_glacier_thickness));
bw_glacier_thickness.write("ncols" + " " + store.getOriginalNcols());
bw_glacier_thickness.write(System.getProperty("line.separator"));
bw_glacier_thickness.write("nrows" + " " + store.getOriginalNrows());
bw_glacier_thickness.write(System.getProperty("line.separator"));
bw_glacier_thickness.write("xllcorner" + " " + store.getOriginalXllcorner());
bw_glacier_thickness.write(System.getProperty("line.separator"));
bw_glacier_thickness.write("yllcorner" + " " + store.getOriginalYllcorner());
bw_glacier_thickness.write(System.getProperty("line.separator"));
bw_glacier_thickness.write("cellsize" + " " + store.getOriginalCellsize());
bw_glacier_thickness.write(System.getProperty("line.separator"));
bw_glacier_thickness.write("NODATA_value" + " " + "-9999");
bw_glacier_thickness.write(System.getProperty("line.separator"));
/**
* Write out the array data
*
*/
//String tempStr = "";
for (int a = 0; a < glacier_thickness.length; a++) {
for (int b = 0; b < glacier_thickness[a].length; b++) {
if (glacier_thickness[a][b] == NODATA_value) {
bw_glacier_thickness.write("-9999 ");
} else {
bw_glacier_thickness.write(df_glacier_thickness.format(glacier_thickness[a][b]) + " ");
}
}
bw_glacier_thickness.newLine();
}
bw_glacier_thickness.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Glacier_thickness: " + f_glacier_thickness.getAbsolutePath());
} else {
// Do not save array
}
/**
* This bit will open a save box to save the updated
* elevation layer as an ASCII, using the coordinates of the
* originally opened up elevation surface
*
*/
if (save_arrays == 1) {
File f_elevation_update = new File("F:/Melt_modelling/Historical_model_outputs_Elev_Fixed/updated_elevation_" + (int) month + "." + (int) year + ".txt");
DecimalFormat df_elevation_update = new DecimalFormat("#.####");
try {
BufferedWriter bw_elevation_update = new BufferedWriter(new FileWriter(f_elevation_update));
bw_elevation_update.write("ncols" + " " + store.getOriginalNcols());
bw_elevation_update.write(System.getProperty("line.separator"));
bw_elevation_update.write("nrows" + " " + store.getOriginalNrows());
bw_elevation_update.write(System.getProperty("line.separator"));
bw_elevation_update.write("xllcorner" + " " + store.getOriginalXllcorner());
bw_elevation_update.write(System.getProperty("line.separator"));
bw_elevation_update.write("yllcorner" + " " + store.getOriginalYllcorner());
bw_elevation_update.write(System.getProperty("line.separator"));
bw_elevation_update.write("cellsize" + " " + store.getOriginalCellsize());
bw_elevation_update.write(System.getProperty("line.separator"));
bw_elevation_update.write("NODATA_value" + " " + "-9999");
bw_elevation_update.write(System.getProperty("line.separator"));
/**
* Write out the array data
*
*/
//String tempStr = "";
for (int a = 0; a < elevation.length; a++) {
for (int b = 0; b < elevation[a].length; b++) {
if (Q_daily_grid[a][b] == NODATA_value) {
bw_elevation_update.write("-9999 ");
} else {
bw_elevation_update.write(df_elevation_update.format(elevation[a][b]) + " ");
}
}
bw_elevation_update.newLine();
}
bw_elevation_update.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Updated elevation: " + f_elevation_update.getAbsolutePath());
} else {
// Do not save array
}
/*
* Deals with inputs for the stats file. Sorts out loop
* counting and also loops through the radiation, psi and
* lapse rate surfaces to calculate mean values for the
* stats file
*/
Loop_counter++;
for (int i = 0; i < surfaceRadiationSurface.length; i++) {
for (int j = 0; j < surfaceRadiationSurface[i].length; j++) {
if (surfaceRadiationSurface[i][j] != NODATA_value) {
double Radiation_instance = surfaceRadiationSurface[i][j];
Radiation_total += Radiation_instance;
Radiation_counter++;
} else {
}
if (psi_surface[i][j] != NODATA_value) {
double Psi_instance = psi_surface[i][j];
Psi_total += Psi_instance;
Psi_counter++;
} else {
}
if (lapsed_temp[i][j] != NODATA_value) {
double Lapsed_temp_instance = lapsed_temp[i][j];
Lapsed_temp_total += Lapsed_temp_instance;
Lapsed_temp_counter++;
} else {
}
}
}
//Sort other values
bw_stats.write(Loop_counter + ", " + month + ", " + year + ", " + Radiation_total / Radiation_counter
+ ", " + Psi_total / Psi_counter + ", " + mean_Q_m2 / radiation_loop_counter + ", " + Lapsed_temp_total / Lapsed_temp_counter + ", " + "N/A"
+ ", " + thickness_adjustment_total / adjustment_counter + ", "
+ volume_adjustment_total / adjustment_counter);
bw_stats.newLine();
} // If there is no surfaceRadiationSurface (i.e. if the month and temp list extends to a period where there are no solar geometry values
// e.g. if the main met input fle starts march 1920 but the radiation file doesn't start until march 1926, then surfaceRadiationSurface
// would be null for all runs until march 1926
else {
System.out.println("No radiation surface - main input and radiation input must be starting at different dates");
}
//}
System.out.println("summersnow_hit: " + summersnow_hit);
System.out.println("nosummersnow_hit: " + nosummersnow_hit);
System.out.println("summersnow_wintersnow_hit: " + summersnow_wintersnow_hit);
System.out.println("summersnow_no_wintersnow_hit: " + summersnow_no_wintersnow_hit);
System.out.println("summersnow_wintersnow_ice: " + summersnow_wintersnow_ice);
System.out.println("no_summersnow_wintersnow_hit: " + no_summersnow_wintersnow_hit);
System.out.println("no_summersnow_no_wintersnow_hit: " + no_summersnow_no_wintersnow_hit);
System.out.println("no_summersnow_wintersnow_ice: " + no_summersnow_wintersnow_ice);
/**
* This bit will open a save box to save the slope
* layer as an ASCII, using the coordinates of the originally
* opened up elevation surface
*
*/
if (save_arrays == 3) {
File f_Slope_Surface = new File("F:/Melt_modelling/Historical_model_outputs_Elev_Fixed/slope_" + (int) month + "." + (int) year + ".txt");
DecimalFormat df_Slope_Surface = new DecimalFormat("#.####");
try {
BufferedWriter bw_Slope_Surface = new BufferedWriter(new FileWriter(f_Slope_Surface));
bw_Slope_Surface.write("ncols" + " " + store.getOriginalNcols());
bw_Slope_Surface.write(System.getProperty("line.separator"));
bw_Slope_Surface.write("nrows" + " " + store.getOriginalNrows());
bw_Slope_Surface.write(System.getProperty("line.separator"));
bw_Slope_Surface.write("xllcorner" + " " + store.getOriginalXllcorner());
bw_Slope_Surface.write(System.getProperty("line.separator"));
bw_Slope_Surface.write("yllcorner" + " " + store.getOriginalYllcorner());
bw_Slope_Surface.write(System.getProperty("line.separator"));
bw_Slope_Surface.write("cellsize" + " " + store.getOriginalCellsize());
bw_Slope_Surface.write(System.getProperty("line.separator"));
bw_Slope_Surface.write("NODATA_value" + " " + "-9999");
bw_Slope_Surface.write(System.getProperty("line.separator"));
/**
* Write out the array data
*
*/
//String tempStr = "";
for (int a = 0; a < Slope_Surface.length; a++) {
for (int b = 0; b < Slope_Surface[a].length; b++) {
if (Slope_Surface[a][b] == NODATA_value) {
bw_Slope_Surface.write("-9999 ");
} else {
bw_Slope_Surface.write(df_Slope_Surface.format(Slope_Surface[a][b]) + " ");
}
}
bw_Slope_Surface.newLine();
}
bw_Slope_Surface.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Slope check: " + f_Slope_Surface.getAbsolutePath());
} else {
// Do not save array
}
/**
* This bit will open a save box to save the aspect
* layer as an ASCII, using the coordinates of the originally
* opened up elevation surface
*
*/
if (save_arrays == 3) {
File f_aspectSurface = new File("F:/Melt_modelling/Historical_model_outputs_Elev_Fixed/aspect_" + (int) month + "." + (int) year + ".txt");
DecimalFormat df_aspectSurface = new DecimalFormat("#.####");
try {
BufferedWriter bw_aspectSurface = new BufferedWriter(new FileWriter(f_aspectSurface));
bw_aspectSurface.write("ncols" + " " + store.getOriginalNcols());
bw_aspectSurface.write(System.getProperty("line.separator"));
bw_aspectSurface.write("nrows" + " " + store.getOriginalNrows());
bw_aspectSurface.write(System.getProperty("line.separator"));
bw_aspectSurface.write("xllcorner" + " " + store.getOriginalXllcorner());
bw_aspectSurface.write(System.getProperty("line.separator"));
bw_aspectSurface.write("yllcorner" + " " + store.getOriginalYllcorner());
bw_aspectSurface.write(System.getProperty("line.separator"));
bw_aspectSurface.write("cellsize" + " " + store.getOriginalCellsize());
bw_aspectSurface.write(System.getProperty("line.separator"));
bw_aspectSurface.write("NODATA_value" + " " + "-9999");
bw_aspectSurface.write(System.getProperty("line.separator"));
/**
* Write out the array data
*
*/
//String tempStr = "";
for (int a = 0; a < aspectSurface.length; a++) {
for (int b = 0; b < aspectSurface[a].length; b++) {
if (aspectSurface[a][b] == NODATA_value) {
bw_aspectSurface.write("-9999 ");
} else {
bw_aspectSurface.write(df_aspectSurface.format(aspectSurface[a][b]) + " ");
}
}
bw_aspectSurface.newLine();
}
bw_aspectSurface.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Aspect check: " + f_aspectSurface.getAbsolutePath());
} else {
// Do not save array
}
}
bw_stats.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* This calculates the temperature at a point as a function of elevation
* relative to the temperature from a meteorological station of known
* elevation - the lapse rate value used is 0.0065 which is between the
* generic environmental lapse rate values of 0.006 and 0.007°C/m
* (Ballantyne, 2002)
*
*/
public double LapseRate(double elevation, double BaseTemp) {
double BaseElevation = 800.0; // Elevation of meteorological station
//double BaseTemp = store.getTemp(); // Temperature at meteorological station (needs to come from within the loop)
double equalizedElevation = elevation - BaseElevation; // Calculates height difference between met station and pooint of interest
// double pseudoTemp = equalizedElevation * 0.0065; // SENSITIVITY TEST
double pseudoTemp = equalizedElevation * 0.0065; // Calculates temperature (celcius - increase/decrease) lapse difference
// according to equalizedElevation
double lapseRate = BaseTemp - pseudoTemp; // Calculates temperature at point of interested with a lapse rate correction
return lapseRate;
}
}
| gpl-2.0 |
yeKcim/warmux | old/warmux-11.04/build/android/src/Video.java | 10783 | // This string is autogenerated by ChangeAppSettings.sh, do not change spaces amount
package org.warmux;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.os.Environment;
import java.io.File;
import android.widget.TextView;
import java.lang.Thread;
import java.util.concurrent.locks.ReentrantLock;
import android.os.Build;
import java.lang.reflect.Method;
import java.util.LinkedList;
abstract class DifferentTouchInput
{
public static DifferentTouchInput getInstance()
{
boolean multiTouchAvailable1 = false;
boolean multiTouchAvailable2 = false;
// Not checking for getX(int), getY(int) etc 'cause I'm lazy
Method methods [] = MotionEvent.class.getDeclaredMethods();
for(Method m: methods)
{
if( m.getName().equals("getPointerCount") )
multiTouchAvailable1 = true;
if( m.getName().equals("getPointerId") )
multiTouchAvailable2 = true;
}
if (multiTouchAvailable1 && multiTouchAvailable2)
return MultiTouchInput.Holder.sInstance;
else
return SingleTouchInput.Holder.sInstance;
}
public abstract void process(final MotionEvent event);
private static class SingleTouchInput extends DifferentTouchInput
{
private static class Holder
{
private static final SingleTouchInput sInstance = new SingleTouchInput();
}
public void process(final MotionEvent event)
{
int action = -1;
if( event.getAction() == MotionEvent.ACTION_DOWN )
action = 0;
if( event.getAction() == MotionEvent.ACTION_UP )
action = 1;
if( event.getAction() == MotionEvent.ACTION_MOVE )
action = 2;
if ( action >= 0 )
DemoGLSurfaceView.nativeMouse( (int)event.getX(), (int)event.getY(), action, 0,
(int)(event.getPressure() * 1000.0),
(int)(event.getSize() * 1000.0) );
}
}
private static class MultiTouchInput extends DifferentTouchInput
{
private static final int touchEventMax = 16; // Max multitouch pointers
private class touchEvent
{
public boolean down = false;
public int x = 0;
public int y = 0;
public int pressure = 0;
public int size = 0;
}
private touchEvent touchEvents[];
MultiTouchInput()
{
touchEvents = new touchEvent[touchEventMax];
for( int i = 0; i < touchEventMax; i++ )
touchEvents[i] = new touchEvent();
}
private static class Holder
{
private static final MultiTouchInput sInstance = new MultiTouchInput();
}
public void process(final MotionEvent event)
{
int action = -1;
if( event.getAction() == MotionEvent.ACTION_UP )
{
action = 1;
for( int i = 0; i < touchEventMax; i++ )
{
if( touchEvents[i].down )
{
touchEvents[i].down = false;
DemoGLSurfaceView.nativeMouse( touchEvents[i].x, touchEvents[i].y, action, i, touchEvents[i].pressure, touchEvents[i].size );
}
}
}
if( event.getAction() == MotionEvent.ACTION_DOWN )
{
action = 0;
for( int i = 0; i < event.getPointerCount(); i++ )
{
int id = event.getPointerId(i);
if( id >= touchEventMax )
id = touchEventMax-1;
touchEvents[id].down = true;
touchEvents[id].x = (int)event.getX(i);
touchEvents[id].y = (int)event.getY(i);
touchEvents[id].pressure = (int)(event.getPressure(i) * 1000.0);
touchEvents[id].size = (int)(event.getSize(i) * 1000.0);
DemoGLSurfaceView.nativeMouse( touchEvents[i].x, touchEvents[i].y, action, id, touchEvents[i].pressure, touchEvents[i].size );
}
}
if( event.getAction() == MotionEvent.ACTION_MOVE )
{
for( int i = 0; i < touchEventMax; i++ )
{
int ii;
for( ii = 0; ii < event.getPointerCount(); ii++ )
{
if( i == event.getPointerId(ii) )
break;
}
if( ii >= event.getPointerCount() )
{
// Up event
if( touchEvents[i].down )
{
action = 1;
touchEvents[i].down = false;
DemoGLSurfaceView.nativeMouse( touchEvents[i].x, touchEvents[i].y, action, i, touchEvents[i].pressure, touchEvents[i].size );
}
}
else
{
int id = event.getPointerId(ii);
if( id >= touchEventMax )
id = touchEventMax-1;
if( touchEvents[id].down )
action = 2;
else
action = 0;
touchEvents[id].down = true;
touchEvents[id].x = (int)event.getX(i);
touchEvents[id].y = (int)event.getY(i);
touchEvents[id].pressure = (int)(event.getPressure(i) * 1000.0);
touchEvents[id].size = (int)(event.getSize(i) * 1000.0);
DemoGLSurfaceView.nativeMouse( touchEvents[i].x, touchEvents[i].y, action, id, touchEvents[i].pressure, touchEvents[i].size );
}
}
}
}
}
}
class DemoRenderer extends GLSurfaceView_SDL.Renderer {
public DemoRenderer(MainActivity _context)
{
context = _context;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
System.out.println("libSDL: DemoRenderer.onSurfaceCreated(): paused " + mPaused + " mFirstTimeStart " + mFirstTimeStart );
mGlSurfaceCreated = true;
if( ! mPaused && ! mFirstTimeStart )
nativeGlContextRecreated();
mFirstTimeStart = false;
}
public void onSurfaceChanged(GL10 gl, int w, int h) {
nativeResize(w, h, Globals.KeepAspectRatio ? 1 : 0);
}
public void onSurfaceDestroyed() {
mGlSurfaceCreated = false;
mGlContextLost = true;
nativeGlContextLost();
};
public void onDrawFrame(GL10 gl) {
nativeInitJavaCallbacks();
// Make main thread priority lower so audio thread won't get underrun
// Thread.currentThread().setPriority((Thread.currentThread().getPriority() + Thread.MIN_PRIORITY)/2);
mGlContextLost = false;
String libs[] = { "application", "sdl_main" };
try
{
for(String l : libs)
{
System.loadLibrary(l);
}
}
catch ( UnsatisfiedLinkError e )
{
for(String l : libs)
{
String libname = System.mapLibraryName(l);
File libpath = new File(context.getCacheDir(), libname);
System.out.println("libSDL: loading lib " + libpath.getPath());
System.load(libpath.getPath());
libpath.delete();
}
}
Settings.Apply(context);
accelerometer = new AccelerometerReader(context);
URLDownloader tmp = new URLDownloader();
// Tweak video thread priority, if user selected big audio buffer
if(Globals.AudioBufferConfig >= 2)
Thread.currentThread().setPriority( (Thread.NORM_PRIORITY + Thread.MIN_PRIORITY) / 2 ); // Lower than normal
nativeInit( Globals.DataDir,
Globals.CommandLine,
( Globals.SwVideoMode && Globals.MultiThreadedVideo ) ? 1 : 0 ); // Calls main() and never returns, hehe - we'll call eglSwapBuffers() from native code
System.exit(0); // The main() returns here - I don't bother with deinit stuff, just terminate process
}
public int swapBuffers() // Called from native code
{
synchronized(this) {
this.notify();
}
if( ! super.SwapBuffers() && Globals.NonBlockingSwapBuffers )
return 0;
if(mGlContextLost) {
mGlContextLost = false;
Settings.SetupTouchscreenKeyboardGraphics(context); // Reload on-screen buttons graphics
}
return 1;
}
public void showScreenKeyboard(final String oldText, int sendBackspace) // Called from native code
{
class Callback implements Runnable
{
public MainActivity parent;
public String oldText;
public boolean sendBackspace;
public void run()
{
parent.showScreenKeyboard(oldText, sendBackspace);
}
}
Callback cb = new Callback();
cb.parent = context;
cb.oldText = oldText;
cb.sendBackspace = (sendBackspace != 0);
context.runOnUiThread(cb);
}
public void exitApp() {
nativeDone();
};
private native void nativeInitJavaCallbacks();
private native void nativeInit(String CurrentPath, String CommandLine, int multiThreadedVideo);
private native void nativeResize(int w, int h, int keepAspectRatio);
private native void nativeDone();
private native void nativeGlContextLost();
public native void nativeGlContextRecreated();
public static native void nativeTextInput( int ascii, int unicode );
public static native void nativeTextInputFinished();
private MainActivity context = null;
private AccelerometerReader accelerometer = null;
private EGL10 mEgl = null;
private EGLDisplay mEglDisplay = null;
private EGLSurface mEglSurface = null;
private EGLContext mEglContext = null;
private boolean mGlContextLost = false;
public boolean mGlSurfaceCreated = false;
public boolean mPaused = false;
private boolean mFirstTimeStart = true;
}
class DemoGLSurfaceView extends GLSurfaceView_SDL {
public DemoGLSurfaceView(MainActivity context) {
super(context);
mParent = context;
touchInput = DifferentTouchInput.getInstance();
setEGLConfigChooser(Globals.NeedDepthBuffer);
mRenderer = new DemoRenderer(context);
setRenderer(mRenderer);
}
@Override
public boolean onTouchEvent(final MotionEvent event)
{
touchInput.process(event);
// Wait a bit, and try to synchronize to app framerate, or event thread will eat all CPU and we'll lose FPS
if( event.getAction() == MotionEvent.ACTION_MOVE ) {
synchronized(mRenderer) {
try {
mRenderer.wait(300L);
} catch (InterruptedException e) { }
}
}
return true;
};
public void exitApp() {
mRenderer.exitApp();
};
@Override
public void onPause() {
super.onPause();
mRenderer.mPaused = true;
};
public boolean isPaused() {
return mRenderer.mPaused;
}
@Override
public void onResume() {
super.onResume();
mRenderer.mPaused = false;
System.out.println("libSDL: DemoGLSurfaceView.onResume(): mRenderer.mGlSurfaceCreated " + mRenderer.mGlSurfaceCreated + " mRenderer.mPaused " + mRenderer.mPaused);
if( mRenderer.mGlSurfaceCreated && ! mRenderer.mPaused || Globals.NonBlockingSwapBuffers )
mRenderer.nativeGlContextRecreated();
};
@Override
public boolean onKeyDown(int keyCode, final KeyEvent event) {
nativeKey( keyCode, 1 );
return true;
}
@Override
public boolean onKeyUp(int keyCode, final KeyEvent event) {
nativeKey( keyCode, 0 );
return true;
}
DemoRenderer mRenderer;
MainActivity mParent;
DifferentTouchInput touchInput = null;
public static native void nativeMouse( int x, int y, int action, int pointerId, int pressure, int radius );
public static native void nativeKey( int keyCode, int down );
public static native void initJavaCallbacks();
}
| gpl-2.0 |
jchalco/Ate | sistema/sistema-ejb/src/java/bc/FacturaVentaFacade.java | 633 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package bc;
import be.FacturaVenta;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author argos
*/
@Stateless
public class FacturaVentaFacade extends AbstractFacade<FacturaVenta> implements FacturaVentaFacadeLocal {
@PersistenceContext(unitName = "sistema-ejbPU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
public FacturaVentaFacade() {
super(FacturaVenta.class);
}
}
| gpl-2.0 |
dmacvicar/spacewalk | java/code/src/com/redhat/rhn/frontend/xmlrpc/test/BaseHandlerTestCase.java | 2245 | /**
* 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.frontend.xmlrpc.test;
import com.redhat.rhn.domain.org.Org;
import com.redhat.rhn.domain.role.Role;
import com.redhat.rhn.domain.role.RoleFactory;
import com.redhat.rhn.domain.user.User;
import com.redhat.rhn.testing.RhnBaseTestCase;
import com.redhat.rhn.testing.TestUtils;
import com.redhat.rhn.testing.UserTestUtils;
public class BaseHandlerTestCase extends RhnBaseTestCase {
/*
* admin - Org Admin
* regular - retgular user
* adminKey/regularKey - session keys for respective users
*/
protected User admin;
protected User regular;
protected String adminKey;
protected String regularKey;
public void setUp() throws Exception {
super.setUp();
admin = UserTestUtils.createUserInOrgOne();
admin.addPermanentRole(RoleFactory.ORG_ADMIN);
TestUtils.saveAndFlush(admin);
regular = UserTestUtils.createUser("testUser2", admin.getOrg().getId());
regular.removePermanentRole(RoleFactory.ORG_ADMIN);
assertTrue(admin.hasRole(RoleFactory.ORG_ADMIN));
assertTrue(!regular.hasRole(RoleFactory.ORG_ADMIN));
//setup session keys
adminKey = XmlRpcTestUtils.getSessionKey(admin);
regularKey = XmlRpcTestUtils.getSessionKey(regular);
//make sure the test org has the channel admin role
Org org = admin.getOrg();
org.addRole(RoleFactory.CHANNEL_ADMIN);
org.addRole(RoleFactory.SYSTEM_GROUP_ADMIN);
}
protected void addRole(User user, Role role) {
user.getOrg().addRole(role);
user.addPermanentRole(role);
}
}
| gpl-2.0 |
Teameeting/Teameeting-MsgServer | MsgServerClientSdk/SdkMsgClientAndroid/sdkmsgclient/src/main/java/org/dync/teameeting/sdkmsgclient/msgs/MSMessage.java | 2772 | package org.dync.teameeting.sdkmsgclient.msgs;
/**
* Created by hp on 7/10/16.
*/
public final class MSMessage {
private String content = null;
private String extra = null;
private String msgId = null;
private String toId = null;
private String fromId = null;
private String groupId = null;
private String nickName = null;
private String uiconUrl = null;
private String cash = null;
private String wishcont = null;
private String toNickName = null;
private int millSec = 0;//send second
private int msgType = 0;
private int flag = 0;
private int push = 0;
public MSMessage() {
}
public int getPush() {
return push;
}
public void setPush(int push) {
this.push = push;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
public String getExtra() {
return extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
public String getMsgId() {
return msgId;
}
public void setMsgId(String msgId) {
this.msgId = msgId;
}
public String getToId() {
return toId;
}
public void setToId(String toId) {
this.toId = toId;
}
public String getFromId() {
return fromId;
}
public void setFromId(String fromId) {
this.fromId = fromId;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getUiconUrl() {
return uiconUrl;
}
public void setUiconUrl(String uiconUrl) {
this.uiconUrl = uiconUrl;
}
public String getCash() {
return cash;
}
public void setCash(String cash) {
this.cash = cash;
}
public String getWishcont() {
return wishcont;
}
public void setWishcont(String wishcont) {
this.wishcont = wishcont;
}
public int getMillSec() {
return millSec;
}
public void setMillSec(int millSec) {
this.millSec = millSec;
}
public int getMsgType() {
return msgType;
}
public void setMsgType(int msgType) {
this.msgType = msgType;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getToNickName() { return toNickName; }
public void setToNickName(String toNickName) { this.toNickName = toNickName; }
}
| gpl-2.0 |
DigitalLabApp/Gramy | Telegram-master/TMessagesProj/src/main/java/org/telegram/ui/Cells/SharedMediaSectionCell.java | 1665 | /*
* This is the source code of Telegram for Android v. 3.x.x
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2016.
*/
package org.telegram.ui.Cells;
import android.content.Context;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.LocaleController;
import org.telegram.ui.Components.LayoutHelper;
public class SharedMediaSectionCell extends FrameLayout {
private TextView textView;
public SharedMediaSectionCell(Context context) {
super(context);
textView = new TextView(getContext());
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
textView.setTypeface(AndroidUtilities.getTypeface(ApplicationLoader.applicationTypeFace)); //Hossein
textView.setTextColor(0xff212121);
textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 13, 0, 13, 0));
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(40), MeasureSpec.EXACTLY));
}
public void setText(String text) {
textView.setText(text);
}
}
| gpl-2.0 |
dhaowoods/preclinical-clerkship-information-system | src/main/java/id/ac/ums/fkg/panum/model/master/MMahasiswa.java | 4042 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package id.ac.ums.fkg.panum.model.master;
import dawud.perawatan;
import id.ac.ums.fkg.panum.model.transaksi.TrKelompokMahasiswa;
import id.ac.ums.fkg.panum.model.transaksi.TrMahasiswaJurnal;
import id.ac.ums.fkg.panum.model.transaksi.TrMahasiswaPinjamAlat;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.ColumnResult;
import javax.persistence.ConstructorResult;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.NamedNativeQuery;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.SqlResultSetMapping;
import org.eclipse.persistence.annotations.CascadeOnDelete;
/**
*
* @author Dawud
*/
@Entity
@DiscriminatorValue("mahasiswa")
@SqlResultSetMapping(
name = "GolonganTerakhir",
classes = {
@ConstructorResult(
targetClass = perawatan.class,
columns = {
@ColumnResult(name = "kat", type = String.class),
@ColumnResult(name = "tggl", type = Date.class),
@ColumnResult(name = "sudah", type = Boolean.class),
@ColumnResult(name = "nama", type = String.class),
@ColumnResult(name = "pembimbing", type = String.class)
}
)
})
@NamedNativeQuery(name = "ajipku",
query = "select x.nama1 as kat, y.tanggaldiagnosa as tggl, if (y.id is "
+ "null, 0,1) as sudah, x.nama2 as nama, if(y.namalengkap is null, '-', y.namalengkap) as pembimbing from (SELECT j.id, l.nama as nama1, "
+ "j.nama as nama2 FROM mperawatan j, eperawatanwajib k, etema l where j.id=k.perawatan_id AND l.id=j.kategoriperawatan_id) x LEFT JOIN "
+ "(SELECT d.id, a.TANGGALDIAGNOSA, d.NAMA, e.NAMALENGKAP FROM trdiagnosa a, trdiagnosaperawatan c,mperawatan d, mmanusia e WHERE "
+ "a.DOSEN_ID = e.ID AND a.ID = c.DIAGNOSA_ID AND c.PERAWATAN_ID = d.ID AND a.PERIODEPANUM = ? AND a.KELOMPOK_ID = ?) y ON (x.id = y.id) ORDER BY y.tanggaldiagnosa, x.nama1, x.nama2",
resultSetMapping = "GolonganTerakhir")
@NamedQuery(name = "mmahasiswa.all", query = "SELECT a FROM MMahasiswa a INNER JOIN a.kelompokList b ORDER BY b.kelompok.nama, a.namaLengkap")
public class MMahasiswa extends MManusia {
@OneToMany(orphanRemoval = true, cascade = {CascadeType.ALL}, mappedBy = "mahasiswa")
@CascadeOnDelete
private List<TrMahasiswaJurnal> jurnalList;
@OneToMany(orphanRemoval = true, cascade = {CascadeType.ALL}, mappedBy = "mahasiswa")
@CascadeOnDelete
private List<TrMahasiswaPinjamAlat> mhsPinjamAlatList;
@OneToMany(orphanRemoval = true, cascade = {CascadeType.ALL}, mappedBy = "mahasiswa")
@CascadeOnDelete
private List<TrKelompokMahasiswa> kelompokList;
public MMahasiswa() {
}
public String getNim() {
return getUserName();
}
public void setNim(String username) {
String oldUsername = this.getUserName();
this.setUserName(username);
changeSupport.firePropertyChange("nim", oldUsername, username);
}
public List<TrMahasiswaJurnal> getJurnalList() {
return jurnalList;
}
public void setJurnalList(List<TrMahasiswaJurnal> jurnalList) {
this.jurnalList = jurnalList;
}
public List<TrKelompokMahasiswa> getKelompokList() {
return kelompokList;
}
public void setKelompokList(List<TrKelompokMahasiswa> kelompokList) {
this.kelompokList = kelompokList;
}
public List<TrMahasiswaPinjamAlat> getMhsPinjamAlatList() {
return mhsPinjamAlatList;
}
public void setMhsPinjamAlatList(List<TrMahasiswaPinjamAlat> mhsPinjamAlatList) {
this.mhsPinjamAlatList = mhsPinjamAlatList;
}
}
| gpl-2.0 |
bharcode/MachineLearning | CustomMahout/core/src/main/java/org/apache/mahout/math/hadoop/stochasticsvd/qr/QRLastStep.java | 4114 | /**
* 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.mahout.math.hadoop.stochasticsvd.qr;
import java.io.Closeable;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import org.apache.commons.lang3.Validate;
import org.apache.mahout.common.iterator.CopyConstructorIterator;
import org.apache.mahout.math.DenseVector;
import org.apache.mahout.math.Vector;
import org.apache.mahout.math.VectorWritable;
import org.apache.mahout.math.hadoop.stochasticsvd.DenseBlockWritable;
import org.apache.mahout.math.UpperTriangular;
import com.google.common.collect.Lists;
/**
* Second/last step of QR iterations. Takes input of qtHats and rHats and
* provides iterator to pull ready rows of final Q.
*
*/
public class QRLastStep implements Closeable, Iterator<Vector> {
private final Iterator<DenseBlockWritable> qHatInput;
private final List<UpperTriangular> mRs = Lists.newArrayList();
private final int blockNum;
private double[][] mQt;
private int cnt;
private int r;
private int kp;
private Vector qRow;
/**
*
* @param qHatInput
* the Q-Hat input that was output in the first step
* @param rHatInput
* all RHat outputs int the group in order of groups
* @param blockNum
* our RHat number in the group
* @throws IOException
*/
public QRLastStep(Iterator<DenseBlockWritable> qHatInput,
Iterator<VectorWritable> rHatInput,
int blockNum) {
this.blockNum = blockNum;
this.qHatInput = qHatInput;
/*
* in this implementation we actually preload all Rs into memory to make R
* sequence modifications more efficient.
*/
int block = 0;
while (rHatInput.hasNext()) {
Vector value = rHatInput.next().get();
if (block < blockNum && block > 0) {
GivensThinSolver.mergeR(mRs.get(0), new UpperTriangular(value));
} else {
mRs.add(new UpperTriangular(value));
}
block++;
}
}
private boolean loadNextQt() {
boolean more = qHatInput.hasNext();
if (!more) {
return false;
}
DenseBlockWritable v = qHatInput.next();
mQt =
GivensThinSolver
.computeQtHat(v.getBlock(),
blockNum == 0 ? 0 : 1,
new CopyConstructorIterator<UpperTriangular>(mRs
.iterator()));
r = mQt[0].length;
kp = mQt.length;
if (qRow == null) {
qRow = new DenseVector(kp);
}
return true;
}
@Override
public boolean hasNext() {
if (mQt != null && cnt == r) {
mQt = null;
}
boolean result = true;
if (mQt == null) {
result = loadNextQt();
cnt = 0;
}
return result;
}
@Override
public Vector next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Validate.isTrue(hasNext(), "Q input overrun");
/*
* because Q blocks are initially stored in inverse order
*/
int qRowIndex = r - cnt - 1;
for (int j = 0; j < kp; j++) {
qRow.setQuick(j, mQt[j][qRowIndex]);
}
cnt++;
return qRow;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void close() throws IOException {
mQt = null;
mRs.clear();
}
}
| gpl-2.0 |
smarr/Truffle | compiler/src/org.graalvm.compiler.jtt/src/org/graalvm/compiler/jtt/bytecode/BC_d2f.java | 1717 | /*
* 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. 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 org.graalvm.compiler.jtt.bytecode;
import org.junit.Test;
import org.graalvm.compiler.jtt.JTTTest;
/*
*/
public class BC_d2f extends JTTTest {
public static float test(double d) {
return (float) d;
}
@Test
public void run0() throws Throwable {
runTest("test", 0.0d);
}
@Test
public void run1() throws Throwable {
runTest("test", 1.0d);
}
@Test
public void run2() throws Throwable {
runTest("test", -1.06d);
}
}
| gpl-2.0 |
AcademicTorrents/AcademicTorrents-Downloader | vuze/com/aelitis/azureus/ui/common/table/TableView.java | 8860 | /**
* Copyright (C) 2007 Aelitis, All Rights Reserved.
*
* 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.
*
* AELITIS, SAS au capital de 63.529,40 euros
* 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
*
*/
package com.aelitis.azureus.ui.common.table;
import java.util.List;
import org.gudy.azureus2.core3.util.AEDiagnosticsEvidenceGenerator;
import org.gudy.azureus2.plugins.ui.tables.TableColumn;
import org.gudy.azureus2.plugins.ui.tables.TableRow;
/**
* @author TuxPaper
* @created Feb 2, 2007
*
*/
public interface TableView<DATASOURCETYPE>
extends AEDiagnosticsEvidenceGenerator
{
/**
* @param listener
*/
void addCountChangeListener(TableCountChangeListener listener);
/** Adds a dataSource to the table as a new row. If the data source is
* already added, a new row will not be added. This function runs
* asynchronously, so the rows creation is not guaranteed directly after
* calling this function.
*
* You can't add datasources until the table is initialized
*
* @param dataSource data source to add to the table
*/
void addDataSource(DATASOURCETYPE dataSource);
/**
* Add a list of dataSources to the table. The array passed in may be
* modified, so make sure you don't need it afterwards.
*
* You can't add datasources until the table is initialized
*
* @param dataSources
*/
void addDataSources(DATASOURCETYPE[] dataSources);
void addLifeCycleListener(TableLifeCycleListener l);
void addRefreshListener(TableRefreshListener l, boolean trigger);
/**
* @param listener
* @param bFireSelection
*/
void addSelectionListener(TableSelectionListener listener, boolean trigger);
/**
* The data set that this table represents has been changed. This is not
* for listening on changes to data sources changing within the table
*
* @param l
* @param trigger
*/
void addTableDataSourceChangedListener(TableDataSourceChangedListener l,
boolean trigger);
/**
* Send Selected rows to the clipboard in a SpreadSheet friendly format
* (tab/cr delimited)
*/
void clipboardSelected();
/**
* Invalidate all the cells in a column
*
* @param sColumnName Name of column to invalidate
*/
void columnInvalidate(String sColumnName);
/**
* @param tableColumn
*/
void columnInvalidate(TableColumnCore tableColumn);
void delete();
/**
* Retrieve a list of <pre>TableCell</pre>s, in the last sorted order.
* The order will not be of the supplied cell's sort unless the table
* has been sorted by that column previously.
* <p>
* ie. You can sort on the 5th column, and retrieve the cells for the
* 3rd column, but they will be in order of the 5th columns sort.
*
* @param sColumnName Which column cell's to return. This does not sort
* the array on the column.
* @return array of cells
*/
TableCellCore[] getColumnCells(String columnName);
/**
* @return not sorted
*/
List<DATASOURCETYPE> getDataSources();
/**
* @note May not necessarily return DATASOURCETYPE if table has subrows
*/
Object getFirstSelectedDataSource();
/**
* @return
*/
String getPropertiesPrefix();
/**
* Get the row associated with a datasource
* @param dataSource a reference to a core Datasource object
* (not a plugin datasource object)
* @return The row, or null
*/
TableRowCore getRow(DATASOURCETYPE dataSource);
/** Get all the rows for this table, in the order they are displayed
*
* @return a list of TableRowSWT objects in the order the user sees them
*/
TableRowCore[] getRows();
/** Returns an array of all selected Data Sources. Null data sources are
* ommitted.
*
* @return an array containing the selected data sources
*
* @note May not necessarily return DATASOURCETYPE if table has subrows
*/
List<Object> getSelectedDataSources();
/**
* Returns an array of all selected Data Sources. Null data sources are
* ommitted.
*
* @param bCoreDataSource
* @return an array containing the selected data sources
*/
Object[] getSelectedDataSources(boolean bCoreDataSource);
/**
* Returns an array of all selected TableRowSWT. Null data sources are
* ommitted.
*
* @return an array containing the selected data sources
*/
TableRowCore[] getSelectedRows();
/**
* @return
*/
TableColumnCore getSortColumn();
/**
* @return
*/
boolean isDisposed();
/**
* Process the queue of datasources to be added and removed
*
*/
void processDataSourceQueue();
/**
* @param bForceSort
*/
void refreshTable(boolean bForceSort);
/**
* Remove all the data sources (table rows) from the table.
*/
void removeAllTableRows();
/**
* @param dataSource
*/
void removeDataSource(DATASOURCETYPE dataSource);
/**
* @param l
*/
void removeTableDataSourceChangedListener(TableDataSourceChangedListener l);
/** For every row source, run the code provided by the specified
* parameter.
*
* @param runner Code to run for each row/datasource
*/
void runForAllRows(TableGroupRowRunner runner);
/** For every row source, run the code provided by the specified
* parameter.
*
* @param runner Code to run for each row/datasource
*/
void runForAllRows(TableGroupRowVisibilityRunner runner);
/**
* @param runner
*/
void runForSelectedRows(TableGroupRowRunner runner);
/**
* Does not fire off selection events
*/
void selectAll();
/**
* @param enableTabViews
*/
void setEnableTabViews(boolean enableTabViews, boolean expandByDefault, String[] restrictToIDs );
void setFocus();
/**
* @param newDataSource
*/
void setParentDataSource(Object newDataSource);
Object getParentDataSource();
/**
* @param iHeight
*/
void setRowDefaultHeight(int iHeight);
void setSelectedRows(TableRowCore[] rows);
/**
* @param bIncludeQueue
* @return
*/
int size(boolean bIncludeQueue);
/**
* @return
*/
TableRowCore getFocusedRow();
/**
* @return
*/
String getTableID();
/**
* @param x
* @param y
* @return
*/
TableRowCore getRow(int x, int y);
/**
* @param dataSource
* @return
*/
boolean dataSourceExists(DATASOURCETYPE dataSource);
/**
* @return
*/
TableColumnCore[] getVisibleColumns();
/**
* @param dataSources
*/
void removeDataSources(DATASOURCETYPE[] dataSources);
/**
* @return
*
* @since 3.0.0.7
*/
int getSelectedRowsSize();
/**
* @param row
* @return
*
* @since 3.0.0.7
*/
int indexOf(TableRowCore row);
/**
* @param row
* @return
*
* @since 3.0.4.3
*/
boolean isRowVisible(TableRowCore row);
/**
* @return
*
* @since 3.0.4.3
*/
TableCellCore getTableCellWithCursor();
/**
* Retrieves the row that has the cursor over it
*
* @return null if mouse isn't over a row
*
* @since 3.0.4.3
*/
TableRowCore getTableRowWithCursor();
/**
* @return
*
* @since 3.0.4.3
*/
int getRowDefaultHeight();
boolean isColumnVisible(TableColumn column);
/**
* @param position
* @return
*
* @since 3.0.4.3
*/
TableRowCore getRow(int position);
/**
* @return
*
* @since 3.1.1.1
*/
Class getDataSourceType();
/**
* @param columnName
* @return
*
* @since 3.1.1.1
*/
TableColumn getTableColumn(String columnName);
void setEnabled(boolean enable);
boolean canHaveSubItems();
/**
* @param tableRowImpl
* @return
*
* @since 4.4.0.5
*/
boolean isSelected(TableRow row);
boolean isUnfilteredDataSourceAdded(Object ds);
/**
* @param visible
*
* @since 4.6.0.5
*/
void setHeaderVisible(boolean visible);
/**
* @return
*
* @since 4.6.0.5
*/
boolean getHeaderVisible();
/**
*
*
* @since 4.6.0.5
*/
void processDataSourceQueueSync();
/**
*
*
* @since 4.6.0.5
*/
int getMaxItemShown();
/**
* @param newIndex
*
* @since 4.6.0.5
*/
void setMaxItemShown(int newIndex);
int getRowCount();
void resetLastSortedOn();
TableColumnCore[] getAllColumns();
void removeCountChangeListener(TableCountChangeListener l);
void addExpansionChangeListener(TableExpansionChangeListener listener);
void removeExpansionChangeListener(TableExpansionChangeListener listener);
}
| gpl-2.0 |
russellcameronthomas/MultiLab | src/main/java/edu/gmu/cds/multilab/processes/Abstraction.java | 325 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.gmu.cds.multilab.processes;
/**
*
* @author Russell Thomas
*/
public class Abstraction extends ImplementationProcess {
}
| gpl-2.0 |
VytautasBoznis/l2.skilas.lt | aCis_datapack/data/scripts/quests/Q112_WalkOfFate/Q112_WalkOfFate.java | 2552 | /*
* 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 quests.Q112_WalkOfFate;
import net.sf.l2j.gameserver.model.actor.L2Npc;
import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance;
import net.sf.l2j.gameserver.model.quest.Quest;
import net.sf.l2j.gameserver.model.quest.QuestState;
public class Q112_WalkOfFate extends Quest
{
private static final String qn = "Q112_WalkOfFate";
// NPCs
private static final int LIVINA = 30572;
private static final int KARUDA = 32017;
// Rewards
private static final int ENCHANT_D = 956;
public Q112_WalkOfFate()
{
super(112, qn, "Walk of Fate");
addStartNpc(LIVINA);
addTalkId(LIVINA, KARUDA);
}
@Override
public String onAdvEvent(String event, L2Npc npc, L2PcInstance player)
{
String htmltext = event;
QuestState st = player.getQuestState(qn);
if (st == null)
return htmltext;
if (event.equalsIgnoreCase("30572-02.htm"))
{
st.setState(STATE_STARTED);
st.set("cond", "1");
st.playSound(QuestState.SOUND_ACCEPT);
}
else if (event.equalsIgnoreCase("32017-02.htm"))
{
st.giveItems(ENCHANT_D, 1);
st.rewardItems(57, 4665);
st.playSound(QuestState.SOUND_FINISH);
st.exitQuest(false);
}
return htmltext;
}
@Override
public String onTalk(L2Npc npc, L2PcInstance player)
{
QuestState st = player.getQuestState(qn);
String htmltext = getNoQuestMsg();
if (st == null)
return htmltext;
switch (st.getState())
{
case STATE_CREATED:
htmltext = (player.getLevel() < 20) ? "30572-00.htm" : "30572-01.htm";
break;
case STATE_STARTED:
switch (npc.getNpcId())
{
case LIVINA:
htmltext = "30572-03.htm";
break;
case KARUDA:
htmltext = "32017-01.htm";
break;
}
break;
case STATE_COMPLETED:
htmltext = getAlreadyCompletedMsg();
break;
}
return htmltext;
}
public static void main(String[] args)
{
new Q112_WalkOfFate();
}
} | gpl-2.0 |
AcademicTorrents/AcademicTorrents-Downloader | vuze/com/aelitis/net/udp/mc/MCGroupFactory.java | 1488 | /*
* Created on 05-Jan-2006
* Created by Paul Gardner
* Copyright (C) 2006 Aelitis, All Rights Reserved.
*
* 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.
*
* AELITIS, SAS au capital de 46,603.30 euros
* 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
*
*/
package com.aelitis.net.udp.mc;
import com.aelitis.net.udp.mc.impl.MCGroupImpl;
public class
MCGroupFactory
{
public static MCGroup
getSingleton(
MCGroupAdapter adapter,
String group_address,
int group_port,
int control_port,
String[] selected_interfaces )
throws MCGroupException
{
return( MCGroupImpl.getSingleton( adapter, group_address, group_port, control_port, selected_interfaces ));
}
public static void
setSuspended(
boolean suspended )
{
MCGroupImpl.setSuspended( suspended );
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/src/share/classes/java/io/PipedReader.java | 12501 | /*
* Copyright 1996-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 java.io;
/**
* Piped character-input streams.
*
* @author Mark Reinhold
* @since JDK1.1
*/
public class PipedReader extends Reader {
boolean closedByWriter = false;
boolean closedByReader = false;
boolean connected = false;
/* REMIND: identification of the read and write sides needs to be
more sophisticated. Either using thread groups (but what about
pipes within a thread?) or using finalization (but it may be a
long time until the next GC). */
Thread readSide;
Thread writeSide;
/**
* The size of the pipe's circular input buffer.
*/
private static final int DEFAULT_PIPE_SIZE = 1024;
/**
* The circular buffer into which incoming data is placed.
*/
char buffer[];
/**
* The index of the position in the circular buffer at which the
* next character of data will be stored when received from the connected
* piped writer. <code>in<0</code> implies the buffer is empty,
* <code>in==out</code> implies the buffer is full
*/
int in = -1;
/**
* The index of the position in the circular buffer at which the next
* character of data will be read by this piped reader.
*/
int out = 0;
/**
* Creates a <code>PipedReader</code> so
* that it is connected to the piped writer
* <code>src</code>. Data written to <code>src</code>
* will then be available as input from this stream.
*
* @param src the stream to connect to.
* @exception IOException if an I/O error occurs.
*/
public PipedReader(PipedWriter src) throws IOException {
this(src, DEFAULT_PIPE_SIZE);
}
/**
* Creates a <code>PipedReader</code> so that it is connected
* to the piped writer <code>src</code> and uses the specified
* pipe size for the pipe's buffer. Data written to <code>src</code>
* will then be available as input from this stream.
* @param src the stream to connect to.
* @param pipeSize the size of the pipe's buffer.
* @exception IOException if an I/O error occurs.
* @exception IllegalArgumentException if <code>pipeSize <= 0</code>.
* @since 1.6
*/
public PipedReader(PipedWriter src, int pipeSize) throws IOException {
initPipe(pipeSize);
connect(src);
}
/**
* Creates a <code>PipedReader</code> so
* that it is not yet {@linkplain #connect(java.io.PipedWriter)
* connected}. It must be {@linkplain java.io.PipedWriter#connect(
* java.io.PipedReader) connected} to a <code>PipedWriter</code>
* before being used.
*/
public PipedReader() {
initPipe(DEFAULT_PIPE_SIZE);
}
/**
* Creates a <code>PipedReader</code> so that it is not yet
* {@link #connect(java.io.PipedWriter) connected} and uses
* the specified pipe size for the pipe's buffer.
* It must be {@linkplain java.io.PipedWriter#connect(
* java.io.PipedReader) connected} to a <code>PipedWriter</code>
* before being used.
*
* @param pipeSize the size of the pipe's buffer.
* @exception IllegalArgumentException if <code>pipeSize <= 0</code>.
* @since 1.6
*/
public PipedReader(int pipeSize) {
initPipe(pipeSize);
}
private void initPipe(int pipeSize) {
if (pipeSize <= 0) {
throw new IllegalArgumentException("Pipe size <= 0");
}
buffer = new char[pipeSize];
}
/**
* Causes this piped reader to be connected
* to the piped writer <code>src</code>.
* If this object is already connected to some
* other piped writer, an <code>IOException</code>
* is thrown.
* <p>
* If <code>src</code> is an
* unconnected piped writer and <code>snk</code>
* is an unconnected piped reader, they
* may be connected by either the call:
* <p>
* <pre><code>snk.connect(src)</code> </pre>
* <p>
* or the call:
* <p>
* <pre><code>src.connect(snk)</code> </pre>
* <p>
* The two
* calls have the same effect.
*
* @param src The piped writer to connect to.
* @exception IOException if an I/O error occurs.
*/
public void connect(PipedWriter src) throws IOException {
src.connect(this);
}
/**
* Receives a char of data. This method will block if no input is
* available.
*/
synchronized void receive(int c) throws IOException {
if (!connected) {
throw new IOException("Pipe not connected");
} else if (closedByWriter || closedByReader) {
throw new IOException("Pipe closed");
} else if (readSide != null && !readSide.isAlive()) {
throw new IOException("Read end dead");
}
writeSide = Thread.currentThread();
while (in == out) {
if ((readSide != null) && !readSide.isAlive()) {
throw new IOException("Pipe broken");
}
/* full: kick any waiting readers */
notifyAll();
try {
wait(1000);
} catch (InterruptedException ex) {
throw new java.io.InterruptedIOException();
}
}
if (in < 0) {
in = 0;
out = 0;
}
buffer[in++] = (char) c;
if (in >= buffer.length) {
in = 0;
}
}
/**
* Receives data into an array of characters. This method will
* block until some input is available.
*/
synchronized void receive(char c[], int off, int len) throws IOException {
while (--len >= 0) {
receive(c[off++]);
}
}
/**
* Notifies all waiting threads that the last character of data has been
* received.
*/
synchronized void receivedLast() {
closedByWriter = true;
notifyAll();
}
/**
* Reads the next character of data from this piped stream.
* If no character is available because the end of the stream
* has been reached, the value <code>-1</code> is returned.
* This method blocks until input data is available, the end of
* the stream is detected, or an exception is thrown.
*
* @return the next character of data, or <code>-1</code> if the end of the
* stream is reached.
* @exception IOException if the pipe is
* <a href=PipedInputStream.html#BROKEN> <code>broken</code></a>,
* {@link #connect(java.io.PipedWriter) unconnected}, closed,
* or an I/O error occurs.
*/
public synchronized int read() throws IOException {
if (!connected) {
throw new IOException("Pipe not connected");
} else if (closedByReader) {
throw new IOException("Pipe closed");
} else if (writeSide != null && !writeSide.isAlive()
&& !closedByWriter && (in < 0)) {
throw new IOException("Write end dead");
}
readSide = Thread.currentThread();
int trials = 2;
while (in < 0) {
if (closedByWriter) {
/* closed by writer, return EOF */
return -1;
}
if ((writeSide != null) && (!writeSide.isAlive()) && (--trials < 0)) {
throw new IOException("Pipe broken");
}
/* might be a writer waiting */
notifyAll();
try {
wait(1000);
} catch (InterruptedException ex) {
throw new java.io.InterruptedIOException();
}
}
int ret = buffer[out++];
if (out >= buffer.length) {
out = 0;
}
if (in == out) {
/* now empty */
in = -1;
}
return ret;
}
/**
* Reads up to <code>len</code> characters of data from this piped
* stream into an array of characters. Less than <code>len</code> characters
* will be read if the end of the data stream is reached or if
* <code>len</code> exceeds the pipe's buffer size. This method
* blocks until at least one character of input is available.
*
* @param cbuf the buffer into which the data is read.
* @param off the start offset of the data.
* @param len the maximum number of characters read.
* @return the total number of characters read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the stream has been reached.
* @exception IOException if the pipe is
* <a href=PipedInputStream.html#BROKEN> <code>broken</code></a>,
* {@link #connect(java.io.PipedWriter) unconnected}, closed,
* or an I/O error occurs.
*/
public synchronized int read(char cbuf[], int off, int len) throws IOException {
if (!connected) {
throw new IOException("Pipe not connected");
} else if (closedByReader) {
throw new IOException("Pipe closed");
} else if (writeSide != null && !writeSide.isAlive()
&& !closedByWriter && (in < 0)) {
throw new IOException("Write end dead");
}
if ((off < 0) || (off > cbuf.length) || (len < 0) ||
((off + len) > cbuf.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
/* possibly wait on the first character */
int c = read();
if (c < 0) {
return -1;
}
cbuf[off] = (char)c;
int rlen = 1;
while ((in >= 0) && (--len > 0)) {
cbuf[off + rlen] = buffer[out++];
rlen++;
if (out >= buffer.length) {
out = 0;
}
if (in == out) {
/* now empty */
in = -1;
}
}
return rlen;
}
/**
* Tell whether this stream is ready to be read. A piped character
* stream is ready if the circular buffer is not empty.
*
* @exception IOException if the pipe is
* <a href=PipedInputStream.html#BROKEN> <code>broken</code></a>,
* {@link #connect(java.io.PipedWriter) unconnected}, or closed.
*/
public synchronized boolean ready() throws IOException {
if (!connected) {
throw new IOException("Pipe not connected");
} else if (closedByReader) {
throw new IOException("Pipe closed");
} else if (writeSide != null && !writeSide.isAlive()
&& !closedByWriter && (in < 0)) {
throw new IOException("Write end dead");
}
if (in < 0) {
return false;
} else {
return true;
}
}
/**
* Closes this piped stream and releases any system resources
* associated with the stream.
*
* @exception IOException if an I/O error occurs.
*/
public void close() throws IOException {
in = -1;
closedByReader = true;
}
}
| gpl-2.0 |
rac021/blazegraph_1_5_3_cluster_2_nodes | bigdata/src/java/com/bigdata/relation/rule/eval/AbstractJoinNexusFactory.java | 8893 | /**
Copyright (C) SYSTAP, LLC 2006-2015. All rights reserved.
Contact:
SYSTAP, LLC
2501 Calvert ST NW #106
Washington, DC 20008
licenses@systap.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; version 2 of the License.
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
*/
/*
* Created on Aug 20, 2010
*/
package com.bigdata.relation.rule.eval;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Properties;
import java.util.WeakHashMap;
import org.apache.log4j.Logger;
import com.bigdata.bop.IBindingSet;
import com.bigdata.bop.joinGraph.IEvaluationPlan;
import com.bigdata.bop.joinGraph.IEvaluationPlanFactory;
import com.bigdata.journal.IIndexManager;
import com.bigdata.relation.IMutableRelation;
import com.bigdata.relation.accesspath.IBuffer;
import com.bigdata.relation.accesspath.IElementFilter;
import com.bigdata.relation.rule.IRule;
/**
* Base implementation for {@link IJoinNexusFactory}.
*
* @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a>
* @version $Id$
*/
abstract public class AbstractJoinNexusFactory implements IJoinNexusFactory {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final transient Logger log = Logger.getLogger(AbstractJoinNexusFactory.class);
private final ActionEnum action;
private final long writeTimestamp;
private /*final*/ long readTimestamp;
private final Properties properties;
private final int solutionFlags;
// @todo should be generic as IElementFilter<ISolution<?>>
private final IElementFilter<?> solutionFilter;
private final IEvaluationPlanFactory evaluationPlanFactory;
private final IRuleTaskFactory defaultRuleTaskFactory;
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
// sb.append("{ ruleContext=" + ruleContext);
sb.append("{ action=" + action);
sb.append(", writeTime=" + writeTimestamp);
sb.append(", readTime=" + readTimestamp);
sb.append(", properties=" + properties);
sb.append(", solutionFlags=" + solutionFlags);
sb.append(", solutionFilter="
+ (solutionFilter == null ? "N/A" : solutionFilter.getClass().getName()));
sb.append(", planFactory=" + evaluationPlanFactory.getClass().getName());
sb.append(", defaultRuleTaskFactory="
+ defaultRuleTaskFactory.getClass().getName());
// allow extension by derived classes.
toString(sb);
sb.append("}");
return sb.toString();
}
/**
* Allows extension of {@link #toString()} by derived classes.
*
* @param sb
*/
protected void toString(final StringBuilder sb) {
}
/**
*
* @param action
* Indicates whether this is a Query, Insert, or Delete
* operation.
* @param writeTimestamp
* The timestamp of the relation view(s) using to write on the
* {@link IMutableRelation}s (ignored if you are not execution
* mutation programs).
* @param readTimestamp
* The timestamp of the relation view(s) used to read from the
* access paths.
* @param solutionFlags
* Flags controlling the behavior of
* {@link #newSolution(IRule, IBindingSet)}.
* @param solutionFilter
* An optional filter that will be applied to keep matching
* elements out of the {@link IBuffer} for Query or Mutation
* operations.
* @param evaluationPlanFactory
* The factory used to generate {@link IEvaluationPlan}s for
* {@link IRule}s.
* @param defaultRuleTaskFactory
* The factory that will be used to generate the
* {@link IStepTask} to execute an {@link IRule} unless the
* {@link IRule} explicitly specifies a factory object using
* {@link IRule#getTaskFactory()}.
*/
protected AbstractJoinNexusFactory(//
final ActionEnum action,//
final long writeTimestamp,//
final long readTimestamp,//
final Properties properties,//
final int solutionFlags, //
final IElementFilter<?> solutionFilter,//
final IEvaluationPlanFactory evaluationPlanFactory,//
final IRuleTaskFactory defaultRuleTaskFactory
) {
if (action == null)
throw new IllegalArgumentException();
if (evaluationPlanFactory == null)
throw new IllegalArgumentException();
this.action = action;
this.writeTimestamp = writeTimestamp;
this.readTimestamp = readTimestamp;
this.properties = properties;
this.solutionFlags = solutionFlags;
this.solutionFilter = solutionFilter;
this.evaluationPlanFactory = evaluationPlanFactory;
this.defaultRuleTaskFactory = defaultRuleTaskFactory;
joinNexusCache = new WeakHashMap<IIndexManager, WeakReference<IJoinNexus>>();
}
// @todo assumes one "central" relation (e.g., SPORelation)?
public IJoinNexus newInstance(final IIndexManager indexManager) {
if (indexManager == null)
throw new IllegalArgumentException();
synchronized (joinNexusCache) {
final WeakReference<IJoinNexus> ref = joinNexusCache
.get(indexManager);
IJoinNexus joinNexus = ref == null ? null : ref.get();
if (joinNexus == null) {
joinNexus = newJoinNexus(indexManager);
joinNexusCache.put(indexManager, new WeakReference<IJoinNexus>(
joinNexus));
}
return joinNexus;
}
}
/**
* Factory for {@link IJoinNexus} instances used by
* {@link #newInstance(IIndexManager)} as past of its singleton pattern.
*/
abstract protected IJoinNexus newJoinNexus(IIndexManager indexManager);
private transient WeakHashMap<IIndexManager, WeakReference<IJoinNexus>> joinNexusCache;
final public ActionEnum getAction() {
return action;
}
final public Properties getProperties() {
return properties;
}
final public long getReadTimestamp() {
return readTimestamp;
}
final public void setReadTimestamp(final long readTimestamp) {
if (this.readTimestamp == readTimestamp) {
// NOP.
return;
}
synchronized(joinNexusCache) {
// discard cache since advancing the readTimestamp.
joinNexusCache.clear();
this.readTimestamp = readTimestamp;
if(log.isInfoEnabled())
log.info("readTimestamp: "+readTimestamp);
}
}
final public long getWriteTimestamp() {
return writeTimestamp;
}
final public int getSolutionFlags() {
return solutionFlags;
}
final public IElementFilter<?> getSolutionFilter() {
return solutionFilter;
}
final public IEvaluationPlanFactory getEvaluationPlanFactory() {
return evaluationPlanFactory;
}
final public IRuleTaskFactory getDefaultRuleTaskFactory() {
return defaultRuleTaskFactory;
}
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException {
/*
* Note: Must be explicitly allocated when de-serialized.
*/
joinNexusCache = new WeakHashMap<IIndexManager, WeakReference<IJoinNexus>>();
in.defaultReadObject();
}
}
| gpl-2.0 |
person594/cs153 | assignment4/wci/intermediate/PascalValueType.java | 699 | package wci.intermediate;
public class PascalValueType
{
public PascalValueType() {
}
public boolean equals(Object other) {
return other == this;
}
//all the atomic types simply exist as singletons
//they have no defining properties apart from their uniqueness
//most compound types are built recursively from these, except enums
//and ranges, which are weird
public static PascalValueType REAL = new PascalValueType();
public static PascalIntegralType INTEGER = (PascalIntegralType) new PascalValueType();
public static PascalIntegralType CHAR = (PascalIntegralType) new PascalValueType();
public static PascalIntegralType BOOLEAN = (PascalIntegralType) new PascalValueType();
}
| gpl-2.0 |
mzed/wekimini | src/wekimini/kadenze/KadenzeAssignment.java | 18570 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package wekimini.kadenze;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author rebecca
*/
public class KadenzeAssignment {
private static final Logger logger = Logger.getLogger(KadenzeAssignment.class.getName());
public static KadenzeAssignmentType getAssignment(int p, int p2) {
if (p == 1 && p2 == 1) {
return KadenzeAssignmentType.ASSIGNMENT1;
} else if (p == 2 && p2 == 1) {
return KadenzeAssignmentType.ASSIGNMENT2_PART1A;
} else if (p == 2 && p2 == 2) {
return KadenzeAssignmentType.ASSIGNMENT2_PART1B;
} else if (p == 2 && p2 == 3) {
return KadenzeAssignmentType.ASSIGNMENT2_PART1C;
} else if (p == 2 && p2 == 4) {
return KadenzeAssignmentType.ASSIGNMENT2_PART1D;
} else if (p == 2 && p2 == 5) {
return KadenzeAssignmentType.ASSIGNMENT2_PART2;
} else if (p == 2 && p2 == 6) {
return KadenzeAssignmentType.ASSIGNMENT2_PART3A;
} else if (p == 2 && p2 == 7) {
return KadenzeAssignmentType.ASSIGNMENT2_PART3B;
} else if (p == 3 && p2 == 1) {
return KadenzeAssignmentType.ASSIGNMENT3_PART1A;
} else if (p == 3 && p2 == 2) {
return KadenzeAssignmentType.ASSIGNMENT3_PART1B;
} else if (p == 3 && p2 == 3) {
return KadenzeAssignmentType.ASSIGNMENT3_PART1C;
} else if (p == 3 && p2 == 4) {
return KadenzeAssignmentType.ASSIGNMENT3_PART2;
} else if (p == 3 && p2 == 5) {
return KadenzeAssignmentType.ASSIGNMENT3_PART3A;
} else if (p == 3 && p2 == 6) {
return KadenzeAssignmentType.ASSIGNMENT3_PART3B;
} else if (p == 4 && p2 == 1) {
return KadenzeAssignmentType.ASSIGNMENT4_PART1A;
} else if (p == 4 && p2 == 2) {
return KadenzeAssignmentType.ASSIGNMENT4_PART1B;
} else if (p == 4 && p2 == 3) {
return KadenzeAssignmentType.ASSIGNMENT4_PART1C;
} else if (p == 4 && p2 == 4) {
return KadenzeAssignmentType.ASSIGNMENT4_PART2;
} else if (p == 6 && p2 == 1) {
return KadenzeAssignmentType.ASSIGNMENT6_PART1;
} else if (p == 6 && p2 == 2) {
return KadenzeAssignmentType.ASSIGNMENT6_PART2;
} else if (p == 7) {
return KadenzeAssignmentType.ASSIGNMENT7;
} else {
logger.log(Level.WARNING, "NO ASSIGNMENT FOUND FOR " + p + "," + p2);
return KadenzeAssignmentType.NONE;
}
}
public enum KadenzeAssignmentType {
NONE,
ASSIGNMENT1,
ASSIGNMENT2_PART1A,
ASSIGNMENT2_PART1B,
ASSIGNMENT2_PART1C,
ASSIGNMENT2_PART1D,
ASSIGNMENT2_PART2,
ASSIGNMENT2_PART3A,
ASSIGNMENT2_PART3B,
ASSIGNMENT3_PART1A,
ASSIGNMENT3_PART1B,
ASSIGNMENT3_PART1C,
ASSIGNMENT3_PART2,
ASSIGNMENT3_PART3A,
ASSIGNMENT3_PART3B,
ASSIGNMENT4_PART1A,
ASSIGNMENT4_PART1B,
ASSIGNMENT4_PART1C,
ASSIGNMENT4_PART2,
ASSIGNMENT6_PART1,
ASSIGNMENT6_PART2,
ASSIGNMENT7
}
public static int getAssignmentNumber(KadenzeAssignmentType t) {
if (t == KadenzeAssignmentType.NONE) {
return -1;
} else if (t == KadenzeAssignmentType.ASSIGNMENT1) {
return 1;
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1A) {
return 2;
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1B) {
return 2;
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1C) {
return 2;
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1D) {
return 2;
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART2) {
return 2;
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART3A) {
return 2;
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART3B) {
return 2;
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1A) {
return 3;
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1B) {
return 3;
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1C) {
return 3;
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART2) {
return 3;
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART3A) {
return 3;
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART3B) {
return 3;
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1A) {
return 4;
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1B) {
return 4;
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1C) {
return 4;
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART2) {
return 4;
} else if (t == KadenzeAssignmentType.ASSIGNMENT6_PART1) {
return 6;
} else if (t == KadenzeAssignmentType.ASSIGNMENT6_PART2) {
return 6;
} else if (t == KadenzeAssignmentType.ASSIGNMENT7) {
return 7;
} else {
System.out.println("ERROR NO ASSIGNMENT NUMBER FOUND");
return -1;
}
}
public static int getAssignmentSubPart(KadenzeAssignmentType t) {
if (t == KadenzeAssignmentType.NONE) {
return -1;
} else if (t == KadenzeAssignmentType.ASSIGNMENT1) {
return -1;
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1A) {
return 1;
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1B) {
return 2;
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1C) {
return 3;
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1D) {
return 4;
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART2) {
return 5;
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART3A) {
return 6;
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART3B) {
return 7;
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1A) {
return 1;
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1B) {
return 2;
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1C) {
return 3;
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART2) {
return 4;
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART3A) {
return 5;
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART3B) {
return 6;
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1A) {
return 1;
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1B) {
return 2;
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1C) {
return 3;
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART2) {
return 4;
}else if (t == KadenzeAssignmentType.ASSIGNMENT6_PART1) {
return 1;
} else if (t == KadenzeAssignmentType.ASSIGNMENT6_PART2) {
return 2;
} else if (t == KadenzeAssignmentType.ASSIGNMENT7) {
return 1;
} else {
System.out.println("ERROR NO ASSIGNMENT NUMBER FOUND");
return -1;
}
}
public static String getAssignmentLogfilename(KadenzeAssignmentType t) {
if (t == KadenzeAssignmentType.NONE) {
return "tmp.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT1) {
return "assignment1.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1A) {
return "assignment2_1A.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1B) {
return "assignment2_1B.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1C) {
return "assignment2_1C.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1D) {
return "assignment2_1D.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART2) {
return "assignment2_2.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART3A) {
return "assignment2_3A.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART3B) {
return "assignment2_3B.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1A) {
return "assignment3_1A.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1B) {
return "assignment3_1B.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1C) {
return "assignment3_1C.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART2) {
return "assignment3_2.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART3A) {
return "assignment3_3A.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART3B) {
return "assignment3_3B.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1A) {
return "assignment4_1A.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1B) {
return "assignment4_1B.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1C) {
return "assignment4_1C.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART2) {
return "assignment4_2.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT6_PART1) {
return "assignment6_1.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT6_PART2) {
return "assignment6_2.txt";
} else if (t == KadenzeAssignmentType.ASSIGNMENT7) {
return "assignment7_1.txt";
} else {
System.out.println("ERROR NO ASSIGNMENT NUMBER FOUND");
return "tmp.txt";
}
}
public static String getReadableName(KadenzeAssignmentType t) {
if (t == KadenzeAssignmentType.NONE) {
return "No assignment";
} else if (t == KadenzeAssignmentType.ASSIGNMENT1) {
return "Assignment 1, Part 1";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1A) {
return "Assignment 2, Part 1A";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1B) {
return "Assignment 2, Part 1B";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1C) {
return "Assignment 2, Part 1C";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1D) {
return "Assignment 2, Part 1D";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART2) {
return "Assignment 2, Part 2";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART3A) {
return "Assignment 2, Part 3A";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART3B) {
return "Assignment 2, Part 3B";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1A) {
return "Assignment 3, Part 1A";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1B) {
return "Assignment 3, Part 1B";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1C) {
return "Assignment 3, Part 1C";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART2) {
return "Assignment 3, Part 2";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART3A) {
return "Assignment 3, Part 3A";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART3B) {
return "Assignment 3, Part 3B";
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1A) {
return "Assignment 4, Part 1A";
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1B) {
return "Assignment 4, Part 1B";
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1C) {
return "Assignment 4, Part 1C";
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART2) {
return "Assignment 4, Part 2";
} else if (t == KadenzeAssignmentType.ASSIGNMENT6_PART1) {
return "Assignment 6, Part 1";
} else if (t == KadenzeAssignmentType.ASSIGNMENT6_PART2) {
return "Assignment 6, Part 2";
} else if (t == KadenzeAssignmentType.ASSIGNMENT7) {
return "Assignment 7";
} else {
System.out.println("ERROR NO ASSIGNMENT NUMBER FOUND");
return "";
}
}
public static String getLogDirectory(KadenzeAssignmentType t) {
if (t == KadenzeAssignmentType.NONE) {
return "";
} else if (t == KadenzeAssignmentType.ASSIGNMENT1) {
return "assignment1";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1A) {
return "assignment2" + File.separator + "assignment2_1A";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1B) {
return "assignment2" + File.separator + "assignment2_1B";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1C) {
return "assignment2" + File.separator + "assignment2_1C";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1D) {
return "assignment2" + File.separator + "assignment2_1D";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART2) {
return "assignment2" + File.separator + "assignment2_2";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART3A) {
return "assignment2" + File.separator + "assignment2_3A";
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART3B) {
return "assignment2" + File.separator + "assignment2_3B";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1A) {
return "assignment3" + File.separator + "assignment3_1A";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1B) {
return "assignment3" + File.separator + "assignment3_1B";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1C) {
return "assignment3" + File.separator + "assignment3_1C";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART2) {
return "assignment3" + File.separator + "assignment3_2";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART3A) {
return "assignment3" + File.separator + "assignment3_3A";
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART3B) {
return "assignment3" + File.separator + "assignment3_3B";
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1A) {
return "assignment4" + File.separator + "assignment4_1A";
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1B) {
return "assignment4" + File.separator + "assignment4_1B";
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1C) {
return "assignment4" + File.separator + "assignment4_1C";
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART2) {
return "assignment4" + File.separator + "assignment4_2";
} else if (t == KadenzeAssignmentType.ASSIGNMENT6_PART1) {
return "assignment6" + File.separator + "assignment6_1";
} else if (t == KadenzeAssignmentType.ASSIGNMENT6_PART2) {
return "assignment6" + File.separator + "assignment6_2";
} else if (t == KadenzeAssignmentType.ASSIGNMENT7) {
return "assignment7" + File.separator + "assignment7";
} else {
System.out.println("ERROR NO ASSIGNMENT NUMBER FOUND");
return "";
}
}
public static KadenzeLogger getLoggerForAssignmentType(KadenzeAssignmentType t) throws Exception {
if (t == KadenzeAssignmentType.NONE) {
return new NoLogger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT1) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1A) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1B) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1C) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART1D) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART2) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART3A) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT2_PART3B) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1A) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1B) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART1C) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART2) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART3A) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT3_PART3B) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1A) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1B) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART1C) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT4_PART2) {
return new Assignment12Logger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT6_PART1) {
return new AssignmentFinalLogger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT6_PART2) {
return new AssignmentFinalLogger();
} else if (t == KadenzeAssignmentType.ASSIGNMENT7) {
return new AssignmentFinalLogger();
} else {
throw new Exception("No logger for this assignment!");
}
}
}
| gpl-2.0 |
wordpress-mobile/WordPress-Stores-Android | fluxc/src/main/java/org/wordpress/android/fluxc/module/AppContextModule.java | 425 | package org.wordpress.android.fluxc.module;
import android.content.Context;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
@Module
public class AppContextModule {
private final Context mAppContext;
public AppContextModule(Context appContext) {
mAppContext = appContext;
}
@Singleton
@Provides
Context providesContext() {
return mAppContext;
}
}
| gpl-2.0 |
ikantech/xmppsupport_v2 | src/com/kenai/jbosh/ServiceLib.java | 5749 | /*
* Copyright 2009 Mike Cumings
*
* 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.kenai.jbosh;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Utility library for use in loading services using the Jar Service Provider
* Interface (Jar SPI). This can be replaced once the minimum java rev moves
* beyond Java 5.
*/
final class ServiceLib {
/**
* Logger.
*/
private static final Logger LOG = Logger.getLogger(ServiceLib.class
.getName());
// /////////////////////////////////////////////////////////////////////////
// Package-private methods:
/**
* Prevent construction.
*/
private ServiceLib() {
// Empty
}
// /////////////////////////////////////////////////////////////////////////
// Package-private methods:
/**
* Probe for and select an implementation of the specified service type by
* using the a modified Jar SPI mechanism. Modified in that the system
* properties will be checked to see if there is a value set for the naem of
* the class to be loaded. If so, that value is treated as the class name of
* the first implementation class to be attempted to be loaded. This
* provides a (unsupported) mechanism to insert other implementations. Note
* that the supported mechanism is by properly ordering the classpath.
*
* @return service instance
* @throws IllegalStateException
* is no service implementations could be instantiated
*/
static <T> T loadService(Class<T> ofType) {
List<String> implClasses = loadServicesImplementations(ofType);
for (String implClass : implClasses) {
T result = attemptLoad(ofType, implClass);
if (result != null) {
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("Selected " + ofType.getSimpleName()
+ " implementation: " + result.getClass().getName());
}
return result;
}
}
throw (new IllegalStateException("Could not load " + ofType.getName()
+ " implementation"));
}
// /////////////////////////////////////////////////////////////////////////
// Private methods:
/**
* Generates a list of implementation class names by using the Jar SPI
* technique. The order in which the class names occur in the service
* manifest is significant.
*
* @return list of all declared implementation class names
*/
private static List<String> loadServicesImplementations(final Class ofClass) {
List<String> result = new ArrayList<String>();
// Allow a sysprop to specify the first candidate
String override = System.getProperty(ofClass.getName());
if (override != null) {
result.add(override);
}
ClassLoader loader = ServiceLib.class.getClassLoader();
URL url = loader.getResource("META-INF/services/" + ofClass.getName());
InputStream inStream = null;
InputStreamReader reader = null;
BufferedReader bReader = null;
try {
inStream = url.openStream();
reader = new InputStreamReader(inStream);
bReader = new BufferedReader(reader);
String line;
while ((line = bReader.readLine()) != null) {
if (!line.matches("\\s*(#.*)?")) {
// not a comment or blank line
result.add(line.trim());
}
}
} catch (IOException iox) {
LOG.log(Level.WARNING,
"Could not load services descriptor: " + url.toString(),
iox);
} finally {
finalClose(bReader);
finalClose(reader);
finalClose(inStream);
}
return result;
}
/**
* Attempts to load the specified implementation class. Attempts will fail
* if - for example - the implementation depends on a class not found on the
* classpath.
*
* @param className
* implementation class to attempt to load
* @return service instance, or {@code null} if the instance could not be
* loaded
*/
private static <T> T attemptLoad(final Class<T> ofClass,
final String className) {
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("Attempting service load: " + className);
}
Level level;
Exception thrown;
try {
Class clazz = Class.forName(className);
if (!ofClass.isAssignableFrom(clazz)) {
if (LOG.isLoggable(Level.WARNING)) {
LOG.warning(clazz.getName() + " is not assignable to "
+ ofClass.getName());
}
return null;
}
return ofClass.cast(clazz.newInstance());
} catch (ClassNotFoundException ex) {
level = Level.FINEST;
thrown = ex;
} catch (InstantiationException ex) {
level = Level.WARNING;
thrown = ex;
} catch (IllegalAccessException ex) {
level = Level.WARNING;
thrown = ex;
}
LOG.log(level, "Could not load " + ofClass.getSimpleName()
+ " instance: " + className, thrown);
return null;
}
/**
* Check and close a closeable object, trapping and ignoring any exception
* that might result.
*
* @param closeMe
* the thing to close
*/
private static void finalClose(final Closeable closeMe) {
if (closeMe != null) {
try {
closeMe.close();
} catch (IOException iox) {
LOG.log(Level.FINEST, "Could not close: " + closeMe, iox);
}
}
}
}
| gpl-2.0 |
md-5/jdk10 | test/langtools/jdk/javadoc/doclet/testSimpleTagInherit/TestSimpleTagInherit.java | 2308 | /*
* Copyright (c) 2013, 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.
*/
/*
* @test
* @bug 8008768 8026567
* @summary Using {@inheritDoc} in simple tag defined via -tag fails
* @library ../../lib
* @modules jdk.javadoc/jdk.javadoc.internal.tool
* @build javadoc.tester.*
* @run main TestSimpleTagInherit
*/
import javadoc.tester.JavadocTester;
public class TestSimpleTagInherit extends JavadocTester {
//Javadoc arguments.
private static final String[] ARGS = new String[] {
};
//Input for string search tests.
private static final String[][] TEST = {
{ }
};
public static void main(String... args) throws Exception {
TestSimpleTagInherit tester = new TestSimpleTagInherit();
tester.runTests();
}
@Test
public void test() {
javadoc("-d", "out",
"-sourcepath", testSrc,
"-tag", "custom:optcm:<em>Custom:</em>",
"p");
checkExit(Exit.OK);
checkOutput("p/TestClass.html", true,
"<dt><span class=\"simpleTagLabel\"><em>Custom:</em></span></dt>\n"
+ "<dd>doc for BaseClass class</dd>",
"<dt><span class=\"simpleTagLabel\"><em>Custom:</em></span></dt>\n"
+ "<dd>doc for BaseClass method</dd>");
}
}
| gpl-2.0 |
dwango/quercus | src/main/java/com/caucho/quercus/program/Function.java | 12073 | /*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.program;
import com.caucho.quercus.Location;
import com.caucho.quercus.QuercusException;
import com.caucho.quercus.env.Env;
import com.caucho.quercus.env.EnvVar;
import com.caucho.quercus.env.EnvVarImpl;
import com.caucho.quercus.env.NullThisValue;
import com.caucho.quercus.env.NullValue;
import com.caucho.quercus.env.StringValue;
import com.caucho.quercus.env.QuercusClass;
import com.caucho.quercus.env.UnsetValue;
import com.caucho.quercus.env.Value;
import com.caucho.quercus.env.Var;
import com.caucho.quercus.expr.Expr;
import com.caucho.quercus.expr.ExprFactory;
import com.caucho.quercus.expr.ParamRequiredExpr;
import com.caucho.quercus.function.AbstractFunction;
import com.caucho.quercus.statement.*;
import com.caucho.util.L10N;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
/**
* Represents sequence of statements.
*/
public class Function extends AbstractFunction {
private static final Logger log = Logger.getLogger(Function.class.getName());
private static final L10N L = new L10N(Function.class);
protected final FunctionInfo _info;
protected final boolean _isReturnsReference;
protected final String _name;
protected final Arg []_args;
protected final Statement _statement;
protected boolean _hasReturn;
protected String _comment;
protected Arg []_closureUseArgs;
Function(Location location,
String name,
FunctionInfo info,
Arg []args,
Statement []statements)
{
super(location);
_name = name.intern();
_info = info;
_info.setFunction(this);
_isReturnsReference = info.isReturnsReference();
_args = args;
_statement = new BlockStatement(location, statements);
setGlobal(info.isPageStatic());
setClosure(info.isClosure());
_isStatic = true;
}
public Function(ExprFactory exprFactory,
Location location,
String name,
FunctionInfo info,
Arg []args,
Statement []statements)
{
super(location);
_name = name.intern();
_info = info;
_info.setFunction(this);
_isReturnsReference = info.isReturnsReference();
_args = new Arg[args.length];
System.arraycopy(args, 0, _args, 0, args.length);
_statement = exprFactory.createBlock(location, statements);
setGlobal(info.isPageStatic());
setClosure(info.isClosure());
_isStatic = true;
}
/**
* Returns the name.
*/
public String getName()
{
return _name;
}
/*
* Returns the declaring class
*/
@Override
public ClassDef getDeclaringClass()
{
return _info.getDeclaringClass();
}
public FunctionInfo getInfo()
{
return _info;
}
protected boolean isMethod()
{
return getDeclaringClassName() != null;
}
/*
* Returns the declaring class
*/
@Override
public String getDeclaringClassName()
{
ClassDef declaringClass = _info.getDeclaringClass();
if (declaringClass != null)
return declaringClass.getName();
else
return null;
}
/**
* Returns the args.
*/
public Arg []getArgs()
{
return _args;
}
/**
* Returns the args.
*/
public Arg []getClosureUseArgs()
{
return _closureUseArgs;
}
/**
* Returns the args.
*/
public void setClosureUseArgs(Arg []useArgs)
{
_closureUseArgs = useArgs;
}
public boolean isObjectMethod()
{
return false;
}
/**
* True for a returns reference.
*/
public boolean isReturnsReference()
{
return _isReturnsReference;
}
/**
* Sets the documentation for this function.
*/
public void setComment(String comment)
{
_comment = comment;
}
/**
* Returns the documentation for this function.
*/
@Override
public String getComment()
{
return _comment;
}
public Value execute(Env env)
{
return null;
}
/**
* Evaluates a function's argument, handling ref vs non-ref
*/
@Override
public Value []evalArguments(Env env, Expr fun, Expr []args)
{
Value []values = new Value[args.length];
for (int i = 0; i < args.length; i++) {
Arg arg = null;
if (i < _args.length)
arg = _args[i];
if (arg == null)
values[i] = args[i].eval(env).copy();
else if (arg.isReference())
values[i] = args[i].evalVar(env);
else {
// php/0d04
values[i] = args[i].eval(env);
}
}
return values;
}
public Value call(Env env, Expr []args)
{
return callImpl(env, args, false);
}
public Value callCopy(Env env, Expr []args)
{
return callImpl(env, args, false);
}
public Value callRef(Env env, Expr []args)
{
return callImpl(env, args, true);
}
private Value callImpl(Env env, Expr []args, boolean isRef)
{
HashMap<StringValue,EnvVar> map = new HashMap<StringValue,EnvVar>();
Value []values = new Value[args.length];
for (int i = 0; i < args.length; i++) {
Arg arg = null;
if (i < _args.length) {
arg = _args[i];
}
if (arg == null) {
values[i] = args[i].eval(env).copy();
}
else if (arg.isReference()) {
values[i] = args[i].evalVar(env);
map.put(arg.getName(), new EnvVarImpl(values[i].toLocalVarDeclAsRef()));
}
else {
// php/0d04
values[i] = args[i].eval(env);
Var var = values[i].toVar();
map.put(arg.getName(), new EnvVarImpl(var));
values[i] = var.toValue();
}
}
for (int i = args.length; i < _args.length; i++) {
Arg arg = _args[i];
Expr defaultExpr = arg.getDefault();
if (defaultExpr == null)
return env.error("expected default expression");
else if (arg.isReference())
map.put(arg.getName(),
new EnvVarImpl(defaultExpr.evalVar(env).toVar()));
else {
map.put(arg.getName(),
new EnvVarImpl(defaultExpr.eval(env).copy().toVar()));
}
}
Map<StringValue,EnvVar> oldMap = env.pushEnv(map);
Value []oldArgs = env.setFunctionArgs(values); // php/0476
Value oldThis;
if (isStatic()) {
// php/0967
oldThis = env.setThis(env.getCallingClass());
}
else
oldThis = env.getThis();
try {
Value value = _statement.execute(env);
if (value != null)
return value;
else if (_info.isReturnsReference())
return new Var();
else
return NullValue.NULL;
/*
else if (_isReturnsReference && isRef)
return value;
else
return value.copyReturn();
*/
} finally {
env.restoreFunctionArgs(oldArgs);
env.popEnv(oldMap);
env.setThis(oldThis);
}
}
@Override
public Value call(Env env, Value []args)
{
return callImpl(env, args, false, null, null);
}
@Override
public Value callCopy(Env env, Value []args)
{
return callImpl(env, args, false, null, null).copy();
}
@Override
public Value callRef(Env env, Value []args)
{
return callImpl(env, args, true, null, null);
}
public Value callImpl(Env env, Value []args, boolean isRef,
Arg []useParams, Value []useArgs)
{
HashMap<StringValue,EnvVar> map = new HashMap<StringValue,EnvVar>(8);
if (useParams != null) {
for (int i = 0; i < useParams.length; i++) {
map.put(useParams[i].getName(), new EnvVarImpl(useArgs[i].toVar()));
}
}
for (int i = 0; i < args.length; i++) {
Arg arg = null;
if (i < _args.length) {
arg = _args[i];
}
if (arg == null) {
}
else if (arg.isReference()) {
map.put(arg.getName(), new EnvVarImpl(args[i].toLocalVarDeclAsRef()));
}
else {
// XXX: php/1708, toVar() may be doing another copy()
Var var = args[i].toLocalVar();
if (arg.getExpectedClass() != null
&& arg.getDefault() instanceof ParamRequiredExpr) {
env.checkTypeHint(var,
arg.getExpectedClass(),
arg.getName().toString(),
getName());
}
// quercus/0d04
map.put(arg.getName(), new EnvVarImpl(var));
}
}
for (int i = args.length; i < _args.length; i++) {
Arg arg = _args[i];
Expr defaultExpr = arg.getDefault();
try {
if (defaultExpr == null)
return env.error("expected default expression");
else if (arg.isReference())
map.put(arg.getName(), new EnvVarImpl(defaultExpr.evalVar(env).toVar()));
else {
map.put(arg.getName(), new EnvVarImpl(defaultExpr.eval(env).toLocalVar()));
}
} catch (Exception e) {
throw new QuercusException(getName() + ":arg(" + arg.getName() + ") "
+ e.getMessage(), e);
}
}
Map<StringValue,EnvVar> oldMap = env.pushEnv(map);
Value []oldArgs = env.setFunctionArgs(args);
Value oldThis;
if (_info.isMethod()) {
oldThis = env.getThis();
}
else {
// php/0967, php/091i
oldThis = env.setThis(NullThisValue.NULL);
}
try {
Value value = _statement.execute(env);
if (value == null) {
if (_isReturnsReference)
return new Var();
else
return NullValue.NULL;
}
else if (_isReturnsReference)
return value;
else
return value.toValue().copy();
} finally {
env.restoreFunctionArgs(oldArgs);
env.popEnv(oldMap);
env.setThis(oldThis);
}
}
//
// method
//
@Override
public Value callMethod(Env env,
QuercusClass qClass,
Value qThis,
Value[] args)
{
if (isStatic())
qThis = qClass;
Value oldThis = env.setThis(qThis);
QuercusClass oldClass = env.setCallingClass(qClass);
try {
return callImpl(env, args, false, null, null);
} finally {
env.setThis(oldThis);
env.setCallingClass(oldClass);
}
}
@Override
public Value callMethodRef(Env env,
QuercusClass qClass,
Value qThis,
Value[] args)
{
Value oldThis = env.setThis(qThis);
QuercusClass oldClass = env.setCallingClass(qClass);
try {
return callImpl(env, args, true, null, null);
} finally {
env.setThis(oldThis);
env.setCallingClass(oldClass);
}
}
private boolean isVariableArgs()
{
return _info.isVariableArgs() || _args.length > 5;
}
private boolean isVariableMap()
{
// return _info.isVariableVar();
// php/3254
return _info.isUsesSymbolTable() || _info.isVariableVar();
}
public String toString()
{
return getClass().getSimpleName() + "[" + _name + "]";
}
}
| gpl-2.0 |
ariesteam/thinklab | plugins/org.integratedmodelling.thinklab.corescience/src/org/integratedmodelling/corescience/implementations/observations/Aggregator.java | 2642 | /**
* Copyright 2011 The ARIES Consortium (http://www.ariesonline.org) and
* www.integratedmodelling.org.
This file is part of Thinklab.
Thinklab 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.
Thinklab 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 Thinklab. If not, see <http://www.gnu.org/licenses/>.
*/
package org.integratedmodelling.corescience.implementations.observations;
import org.integratedmodelling.corescience.interfaces.IContext;
import org.integratedmodelling.corescience.interfaces.IObservationContext;
import org.integratedmodelling.corescience.interfaces.internal.ContextTransformingObservation;
import org.integratedmodelling.thinklab.exception.ThinklabException;
import org.integratedmodelling.thinklab.interfaces.applications.ISession;
import org.integratedmodelling.thinklab.interfaces.knowledge.IConcept;
import org.integratedmodelling.thinklab.interfaces.knowledge.IInstance;
/**
* A transformer observation that will aggregate along one or more dimensions, collapsing
* the context appropriately.
*
* @author Ferdinando
*
*/
public class Aggregator extends Observation implements ContextTransformingObservation {
// public so it can be set using reflection
public IConcept[] dimensions = null;
@Override
public IContext getTransformedContext(IObservationContext context)
throws ThinklabException {
if (dimensions == null) {
return context.collapse(null);
}
IContext ctx = context;
for (IConcept c : dimensions)
ctx = ctx.collapse(c);
return ctx;
}
@Override
public IConcept getTransformedObservationClass() {
// TODO Auto-generated method stub
return null;
}
@Override
public IContext transform(IObservationContext sourceObs, ISession session,
IContext context) throws ThinklabException {
// TODO create new observations with the aggregated states of the
// source obs
return null;
}
@Override
public void initialize(IInstance i) throws ThinklabException {
// TODO get dimensions and aggregation hints if any, or use reflection from
// aggregation model
super.initialize(i);
}
}
| gpl-3.0 |
doglover129/GriefLog | src/tk/blackwolf12333/grieflog/data/block/BlockWorldEditChangeData.java | 3708 | package tk.blackwolf12333.grieflog.data.block;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import tk.blackwolf12333.grieflog.rollback.Rollback;
import tk.blackwolf12333.grieflog.rollback.Undo;
import tk.blackwolf12333.grieflog.utils.logging.Events;
public class BlockWorldEditChangeData extends BaseBlockData {
String changedTo;
byte changedToData;
public BlockWorldEditChangeData(Block b, String player, String changedFromType, byte changedFromData, String changedTo, byte changedToData) {
putBlock(b);
this.blockType = changedFromType;
this.blockData = changedFromData;
this.changedTo = changedTo;
this.changedToData = changedToData;
this.xyz = this.blockX + ", " + this.blockY + ", " + this.blockZ;
this.playerName = player;
this.event = Events.WORLDEDIT.getEventName();
}
public BlockWorldEditChangeData(Block b, String player, UUID playerUUID, String changedFromType, byte changedFromData, String changedTo, byte changedToData) {
this(b, player, changedFromType, changedFromData, changedTo, changedToData);
this.playerUUID = playerUUID;
}
public BlockWorldEditChangeData(String time, int x, int y, int z, String world, String player, String changedFromType, byte changedFromData, String changedTo, byte changedToData) {
this.time = time;
this.blockX = x;
this.blockY = y;
this.blockZ = z;
this.worldName = world;
this.blockType = changedFromType;
this.blockData = changedFromData;
this.changedTo = changedTo;
this.changedToData = changedToData;
this.playerName = player;
this.xyz = this.blockX + ", " + this.blockY + ", " + this.blockZ;
this.event = Events.WORLDEDIT.getEventName();
}
public BlockWorldEditChangeData(String time, int x, int y, int z, String world, String player, UUID playerUUID, String changedFromType, byte changedFromData, String changedTo, byte changedToData) {
this(time, x, y, z, world, player, changedFromType, changedFromData, changedTo, changedToData);
this.playerUUID = playerUUID;
}
@Override
public void rollback(Rollback rollback) {
Location loc = new Location(Bukkit.getWorld(worldName), this.blockX, this.blockY, this.blockZ);
if(this.changedTo != Material.AIR.toString()) {
int materialID = Material.getMaterial(blockType).getId();
this.setBlockFast(loc, materialID, blockData);
} else {
int materialID = Material.getMaterial(this.changedTo).getId();
this.setBlockFast(loc, materialID, changedToData);
}
rollback.chunks.add(loc.getChunk());
}
@Override
public void undo(Undo undo) {
Location loc = new Location(Bukkit.getWorld(worldName), this.blockX, this.blockY, this.blockZ);
if(this.changedTo != Material.AIR.toString()) {
int materialID = Material.getMaterial(this.changedTo).getId();
this.setBlockFast(loc, materialID, changedToData);
} else {
int materialID = Material.getMaterial(blockType).getId();
this.setBlockFast(loc, materialID, blockData);
}
undo.chunks.add(loc.getChunk());
}
@Override
public String toString() {
if(time != null) {
return this.time + " " + this.event + " By: " + this.playerName + " from: " + this.blockType + ":" + this.blockData + " to: " + this.changedTo + ":" + this.changedToData + " at: " + this.xyz + " in: " + this.worldName;
}
return " " + this.event + " By: " + this.playerName + ":" + playerUUID.toString() + " from: " + this.blockType + ":" + this.blockData + " to: " + this.changedTo + ":" + this.changedToData + " at: " + this.xyz + " in: " + this.worldName;
}
@Override
public String getMinimal() {
return this.time + " " + this.playerName + " made a change here with WorldEdit.";
}
}
| gpl-3.0 |
jachness/blockcalls | app/src/main/java/com/jachness/blockcalls/db/AppProvider.java | 1071 | /*
* Copyright (C) 2017 Jonatan Cheiro Anriquez
*
* This file is part of Block Calls.
*
* Block Calls 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.
*
* Block Calls 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 Block Calls. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jachness.blockcalls.db;
import android.content.ContentProvider;
/**
* Created by jachness on 21/10/2016.
*/
public abstract class AppProvider extends ContentProvider {
DBHelper dbHelper;
@Override
public boolean onCreate() {
dbHelper = new DBHelper(getContext());
return true;
}
}
| gpl-3.0 |
covers1624/ForestryLegacy | forestry_common/core/forestry/plugins/PluginForestryCore.java | 40978 | /*******************************************************************************
* Copyright (c) 2011-2014 SirSengir.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl-3.0.txt
*
* Various Contributors including, but not limited to:
* SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges
******************************************************************************/
package forestry.plugins;
import java.util.ArrayList;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.command.ICommand;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.item.crafting.IRecipe;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.oredict.OreDictionary;
import cpw.mods.fml.common.IFuelHandler;
import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage;
import cpw.mods.fml.common.network.IGuiHandler;
import cpw.mods.fml.common.registry.GameRegistry;
import forestry.api.circuits.ChipsetManager;
import forestry.api.core.IOreDictionaryHandler;
import forestry.api.core.ISaveEventHandler;
import forestry.api.core.PluginInfo;
import forestry.api.core.Tabs;
import forestry.api.genetics.AlleleManager;
import forestry.core.CommandForestry;
import forestry.core.CreativeTabForestry;
import forestry.core.GameMode;
import forestry.core.SaveEventHandlerCore;
import forestry.core.circuits.CircuitRegistry;
import forestry.core.circuits.ItemCircuitBoard;
import forestry.core.circuits.ItemSolderingIron;
import forestry.core.config.Config;
import forestry.core.config.Defaults;
import forestry.core.config.ForestryBlock;
import forestry.core.config.ForestryItem;
import forestry.core.gadgets.BlockBase;
import forestry.core.gadgets.MachineAnalyzer;
import forestry.core.gadgets.MachineDefinition;
import forestry.core.genetics.Allele;
import forestry.core.genetics.AlleleRegistry;
import forestry.core.items.ItemAssemblyKit;
import forestry.core.items.ItemCrated;
import forestry.core.items.ItemForestry;
import forestry.core.items.ItemForestryBlock;
import forestry.core.items.ItemForestryPickaxe;
import forestry.core.items.ItemForestryShovel;
import forestry.core.items.ItemFruit;
import forestry.core.items.ItemLiquidContainer;
import forestry.core.items.ItemLiquids;
import forestry.core.items.ItemMisc;
import forestry.core.items.ItemOverlay;
import forestry.core.items.ItemOverlay.OverlayInfo;
import forestry.core.items.ItemPipette;
import forestry.core.items.ItemWrench;
import forestry.core.proxy.Proxies;
import forestry.core.utils.ShapedRecipeCustom;
@PluginInfo(pluginID = "Core", name = "Core", author = "SirSengir", url = Defaults.URL, description = "Core mechanics for Forestry. Required by all other plugins.")
public class PluginForestryCore extends NativePlugin implements IFuelHandler {
public static MachineDefinition definitionAnalyzer;
@Override
public void preInit() {
super.preInit();
int blockid = Config.getOrCreateBlockIdProperty("core", Defaults.ID_BLOCK_CORE);
definitionAnalyzer = new MachineDefinition(blockid, Defaults.DEFINITION_ANALYZER_META, "forestry.Analyzer", MachineAnalyzer.class,
PluginForestryApiculture.proxy.getRendererAnalyzer(Defaults.TEXTURE_PATH_BLOCKS + "/analyzer_"),
getAnalyzerRecipes(blockid, Defaults.DEFINITION_ANALYZER_META));
ForestryBlock.core = new BlockBase(blockid,
Material.iron, new MachineDefinition[] { definitionAnalyzer }, true).setBlockName("for.core");
Item.itemsList[ForestryBlock.core.blockID] = null;
Item.itemsList[ForestryBlock.core.blockID] = new ItemForestryBlock(ForestryBlock.core.blockID - 256, "for.core");
ChipsetManager.solderManager = new ItemSolderingIron.SolderManager();
CircuitRegistry circuitRegistry = new CircuitRegistry();
ChipsetManager.circuitRegistry = circuitRegistry;
circuitRegistry.initialize();
AlleleRegistry alleleRegistry = new AlleleRegistry();
AlleleManager.alleleRegistry = alleleRegistry;
alleleRegistry.initialize();
Allele.initialize();
GameRegistry.registerFuelHandler(this);
}
public void doInit() {
super.doInit();
definitionAnalyzer.register();
}
@Override
public void postInit() {
super.postInit();
}
@Override
public boolean isAvailable() {
return true;
}
@Override
public String getDescription() {
return "Core";
}
@Override
public IGuiHandler getGuiHandler() {
return null;
}
@Override
public ISaveEventHandler getSaveEventHandler() {
return new SaveEventHandlerCore();
}
@Override
protected void registerPackages() {
}
@Override
protected void registerItems() {
// / FERTILIZERS
ForestryItem.fertilizerBio = (new ItemForestry(Config.getOrCreateItemIdProperty("fertilizerBio", Defaults.ID_ITEM_FERTILIZER_BIO)))
.setItemName("fertilizerBio").setIconIndex(19);
ForestryItem.fertilizerCompound = (new ItemForestry(Config.getOrCreateItemIdProperty("fertilizerCompound", Defaults.ID_ITEM_FERTILIZER_COMPOUND)))
.setItemName("fertilizerCompound").setIconIndex(1);
// / GEMS
ForestryItem.apatite = (new ItemForestry(Config.getOrCreateItemIdProperty("apatite", Defaults.ID_ITEM_APATITE))).setItemName("apatite").setIconIndex(0);
OreDictionary.registerOre("gemApatite", new ItemStack(ForestryItem.apatite));
// / INGOTS
Item copper = (new ItemForestry(Config.getOrCreateItemIdProperty("ingotCopper", Defaults.ID_ITEM_COPPER))).setItemName("ingotCopper").setIconIndex(3);
ForestryItem.ingotCopper = new ItemStack(copper);
FurnaceRecipes.smelting().addSmelting(ForestryBlock.resources.blockID, 1, ForestryItem.ingotCopper, 0.5f);
Item tin = (new ItemForestry(Config.getOrCreateItemIdProperty("ingotTin", Defaults.ID_ITEM_TIN))).setItemName("ingotTin").setIconIndex(2);
ForestryItem.ingotTin = new ItemStack(tin);
FurnaceRecipes.smelting().addSmelting(ForestryBlock.resources.blockID, 2, ForestryItem.ingotTin, 0.5f);
Item bronze = (new ItemForestry(Config.getOrCreateItemIdProperty("ingotBronze", Defaults.ID_ITEM_BRONZE))).setItemName("ingotBronze").setIconIndex(4);
ForestryItem.ingotBronze = new ItemStack(bronze);
OreDictionary.registerOre("ingotCopper", ForestryItem.ingotCopper);
OreDictionary.registerOre("ingotTin", ForestryItem.ingotTin);
OreDictionary.registerOre("ingotBronze", ForestryItem.ingotBronze);
// / TOOLS
ForestryItem.wrench = (new ItemWrench(Config.getOrCreateItemIdProperty("wrench", Defaults.ID_ITEM_WRENCH))).setItemName("wrench").setIconIndex(6);
ForestryItem.pipette = new ItemPipette(Config.getOrCreateItemIdProperty("pipette", Defaults.ID_ITEM_PIPETTE)).setItemName("pipette").setIconIndex(20)
.setFull3D();
// / MACHINES
ForestryItem.sturdyCasing = (new ItemForestry(Config.getOrCreateItemIdProperty("sturdyMachine", Defaults.ID_ITEM_STURDY_CASING)))
.setItemName("sturdyMachine").setIconIndex(9);
ForestryItem.hardenedCasing = (new ItemForestry(Config.getOrCreateItemIdProperty("hardenedMachine", Defaults.ID_ITEM_HARDENED_MACHINE)))
.setItemName("hardenedMachine").setIconIndex(39);
ForestryItem.impregnatedCasing = (new ItemForestry(Config.getOrCreateItemIdProperty("impregnatedCasing", Defaults.ID_ITEM_IMPREGNATED_CASING)))
.setItemName("impregnatedCasing").setIconIndex(61);
ForestryItem.craftingMaterial = new ItemMisc(Config.getOrCreateItemIdProperty("craftingMaterial", Defaults.ID_ITEM_CRAFTING))
.setItemName("craftingMaterial");
// / DISCONTINUED
// ForestryItem.vialEmpty = (new
// ItemForestry(Config.getOrCreateIntProperty("vialEmpty",
// Config.CATEGORY_ITEM, Defaults.ID_ITEM_VIAL_EMPTY)))
// .setItemName("vialEmpty").setIconIndex(10);
ForestryItem.vialCatalyst = (new ItemForestry(Config.getOrCreateItemIdProperty("vialCatalyst", Defaults.ID_ITEM_VIAL_CATALYST))).setItemName(
"vialCatalyst").setIconIndex(58);
// / PEAT PRODUCTION
ForestryItem.peat = (new ItemForestry(Config.getOrCreateItemIdProperty("peat", Defaults.ID_ITEM_PEAT))).setItemName("peat").setIconIndex(16);
OreDictionary.registerOre("brickPeat", new ItemStack(ForestryItem.peat));
ForestryItem.ash = (new ItemForestry(Config.getOrCreateItemIdProperty("ash", Defaults.ID_ITEM_ASH))).setItemName("ash").setIconIndex(17);
OreDictionary.registerOre("dustAsh", new ItemStack(ForestryItem.ash));
Proxies.common.addSmelting(new ItemStack(ForestryItem.peat), new ItemStack(ForestryItem.ash));
ForestryItem.bituminousPeat = new ItemForestry(Config.getOrCreateItemIdProperty("bituminousPeat", Defaults.ID_ITEM_BITUMINOUS_PEAT))
.setItemName("bituminousPeat").setIconIndex(59);
// / GEARS
ForestryItem.gearBronze = (new ItemForestry(Config.getOrCreateItemIdProperty("gearBronze", Defaults.ID_ITEM_BRONZE_GEAR))).setItemName("gearBronze")
.setIconIndex(7);
OreDictionary.registerOre("gearBronze", new ItemStack(ForestryItem.gearBronze));
ForestryItem.gearCopper = (new ItemForestry(Config.getOrCreateItemIdProperty("gearCopper", Defaults.ID_ITEM_COPPER_GEAR))).setItemName("gearCopper")
.setIconIndex(18);
OreDictionary.registerOre("gearCopper", new ItemStack(ForestryItem.gearCopper));
ForestryItem.gearTin = (new ItemForestry(Config.getOrCreateItemIdProperty("gearTin", Defaults.ID_ITEM_TIN_GEAR))).setItemName("gearTin")
.setIconIndex(38);
OreDictionary.registerOre("gearTin", new ItemStack(ForestryItem.gearTin));
// / CIRCUIT BOARDS
ForestryItem.circuitboards = new ItemCircuitBoard(Config.getOrCreateItemIdProperty("chipsets", Defaults.ID_ITEM_CHIPSETS)).setItemName("chipsets");
ForestryItem.solderingIron = new ItemSolderingIron(Config.getOrCreateItemIdProperty("solderingIron", Defaults.ID_ITEM_SOLDERING_IRON)).setIconIndex(11)
.setItemName("solderingIron");
ForestryItem.tubes = new ItemOverlay(Config.getOrCreateItemIdProperty("thermionicTubes", Defaults.ID_ITEM_THERMIONIC_TUBES), CreativeTabForestry.tabForestry,
new OverlayInfo[] { new OverlayInfo("ex-0", 0xffffff, 0xe3b78e), new OverlayInfo("ex-1", 0xffffff, 0xe1eef4),
new OverlayInfo("ex-2", 0xffffff, 0xddc276), new OverlayInfo("ex-3", 0xffffff, 0xd8d8d8), new OverlayInfo("ex-4", 0xffffff, 0xffff8b),
new OverlayInfo("ex-5", 0xffffff, 0x7bd1b8), new OverlayInfo("ex-6", 0xffffff, 0x866bc0), new OverlayInfo("ex-7", 0xfff87e, 0xd96600),
new OverlayInfo("ex-8", 0xffffff, 0x444444), new OverlayInfo("ex-9", 0xffffff, 0xbfffdd), new OverlayInfo("ex-10", 0xffffff, 0x68ccee),
new OverlayInfo("ex-11", 0xffffff, 0x1c57c6)}).setIcons(41, 42).setItemName("thermionicTubes");
// / CRATES AND CARTONS
ForestryItem.carton = (new ItemForestry(Config.getOrCreateItemIdProperty("carton", Defaults.ID_ITEM_CARTON))).setItemName("carton").setIconIndex(24);
ForestryItem.crate = (new ItemForestry(Config.getOrCreateItemIdProperty("crate", Defaults.ID_ITEM_CRATE))).setItemName("crate").setIconIndex(32);
// / CRAFTING CARPENTER
ForestryItem.stickImpregnated = (new ItemForestry(Config.getOrCreateItemIdProperty("oakStick", Defaults.ID_ITEM_OAKSTICK))).setItemName("oakStick")
.setIconIndex(25);
ForestryItem.woodPulp = (new ItemForestry(Config.getOrCreateItemIdProperty("woodPulp", Defaults.ID_ITEM_WOODPULP))).setItemName("woodPulp")
.setIconIndex(33);
OreDictionary.registerOre("pulpWood", new ItemStack(ForestryItem.woodPulp));
// / RECLAMATION
ForestryItem.brokenBronzePickaxe = (new ItemForestry(Config.getOrCreateItemIdProperty("brokenBronzePickaxe", Defaults.ID_ITEM_PICKAXE_BRONZE_BROKEN)))
.setItemName("brokenBronzePickaxe").setIconIndex(28);
ForestryItem.brokenBronzeShovel = (new ItemForestry(Config.getOrCreateItemIdProperty("brokenBronzeShovel", Defaults.ID_ITEM_SHOVEL_BRONZE_BROKEN)))
.setItemName("brokenBronzeShovel").setIconIndex(31);
// / TOOLS
ForestryItem.bronzePickaxe = (new ItemForestryPickaxe(Config.getOrCreateItemIdProperty("bronzePickaxe", Defaults.ID_ITEM_PICKAXE_BRONZE),
new ItemStack(ForestryItem.brokenBronzePickaxe))).setItemName("bronzePickaxe").setIconIndex(27);
MinecraftForge.setToolClass(ForestryItem.bronzePickaxe, "pickaxe", 3);
MinecraftForge.EVENT_BUS.register(ForestryItem.bronzePickaxe);
ForestryItem.bronzeShovel = (new ItemForestryShovel(Config.getOrCreateItemIdProperty("bronzeShovel", Defaults.ID_ITEM_SHOVEL_BRONZE), new ItemStack(
ForestryItem.brokenBronzeShovel))).setItemName("bronzeShovel").setIconIndex(30);
MinecraftForge.setToolClass(ForestryItem.bronzeShovel, "shovel", 3);
MinecraftForge.EVENT_BUS.register(ForestryItem.bronzeShovel);
// / ASSEMBLY KITS
ForestryItem.kitShovel = (new ItemAssemblyKit(Config.getOrCreateItemIdProperty("kitShovel", Defaults.ID_ITEM_TOOLKIT_SHOVEL), new ItemStack(
ForestryItem.bronzeShovel))).setItemName("kitShovel").setIconIndex(29);
ForestryItem.kitPickaxe = (new ItemAssemblyKit(Config.getOrCreateItemIdProperty("kitPickaxe", Defaults.ID_ITEM_TOOLKIT_PICKAXE), new ItemStack(
ForestryItem.bronzePickaxe))).setItemName("kitPickaxe").setIconIndex(26);
// / MOISTENER RESOURCES
ForestryItem.mouldyWheat = (new ItemForestry(Config.getOrCreateItemIdProperty("mouldyWheat", Defaults.ID_ITEM_WHEAT_MOULDY)))
.setItemName("mouldyWheat").setIconIndex(35);
ForestryItem.decayingWheat = (new ItemForestry(Config.getOrCreateItemIdProperty("decayingWheat", Defaults.ID_ITEM_WHEAT_DECAYING))).setItemName(
"decayingWheat").setIconIndex(36);
ForestryItem.mulch = (new ItemForestry(Config.getOrCreateItemIdProperty("mulch", Defaults.ID_ITEM_MULCH))).setItemName("mulch").setIconIndex(34);
// / RAINMAKER SUBSTRATES
ForestryItem.iodineCharge = (new ItemForestry(Config.getOrCreateItemIdProperty("iodineCapsule", Defaults.ID_ITEM_IODINE_CAPSULE)))
.setItemName("iodineCapsule").setIconIndex(40);
ForestryItem.phosphor = (new ItemForestry(Config.getOrCreateItemIdProperty("phosphor", Defaults.ID_ITEM_PHOSPHOR))).setItemName("phosphor")
.setIconIndex(78);
// / BEE RESOURCES
ForestryItem.beeswax = (new ItemForestry(Config.getOrCreateItemIdProperty("beeswax", Defaults.ID_ITEM_BEESWAX))).setItemName("beeswax")
.setIconIndex(44).setCreativeTab(Tabs.tabApiculture);
OreDictionary.registerOre("itemBeeswax", new ItemStack(ForestryItem.beeswax));
ForestryItem.refractoryWax = (new ItemForestry(Config.getOrCreateItemIdProperty("refractoryWax", Defaults.ID_ITEM_REFRACTORY_WAX)))
.setItemName("refractoryWax").setIconIndex(79);
// FRUITS
ForestryItem.fruits = new ItemFruit(Config.getOrCreateItemIdProperty("fruits", Defaults.ID_ITEM_FRUITS))
.setItemName("fruits");
// / EMPTY LIQUID CONTAINERS
ForestryItem.waxCapsule = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("waxCapsule", Defaults.ID_ITEM_WAX_CAPSULE), 1))
.setItemName("waxCapsule");
ForestryItem.canEmpty = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("canEmpty", Defaults.ID_ITEM_CAN_EMPTY), 0)).setItemName("canEmpty");
ForestryItem.refractoryEmpty = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("refractoryEmpty", Defaults.ID_ITEM_REFRACTORY_EMPTY), 7))
.setItemName("refractoryEmpty");
// / BUCKETS
ForestryItem.bucketBiomass = (new ItemForestry(Config.getOrCreateItemIdProperty("bucketBiomass", Defaults.ID_ITEM_BUCKET_BIOMASS)))
.setItemName("bucketBiomass").setIconIndex(8).setContainerItem(Item.bucketEmpty).setMaxStackSize(1);
ForestryItem.bucketBiofuel = (new ItemForestry(Config.getOrCreateItemIdProperty("bucketBiofuel", Defaults.ID_ITEM_BUCKET_BIOFUEL)))
.setItemName("bucketBiofuel").setIconIndex(14).setContainerItem(Item.bucketEmpty).setMaxStackSize(1);
// / WAX CAPSULES
ForestryItem.waxCapsuleWater = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("waxCapsuleWater", Defaults.ID_ITEM_WAX_CAPSULE_WATER), 17))
.setItemName("waxCapsuleWater");
ForestryItem.waxCapsuleBiomass = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("waxCapsuleBiomass", Defaults.ID_ITEM_WAX_CAPSULE_BIOMASS),
33)).setItemName("waxCapsuleBiomass");
ForestryItem.waxCapsuleBiofuel = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("waxCapsuleBiofuel", Defaults.ID_ITEM_WAX_CAPSULE_BIOFUEL),
49)).setItemName("waxCapsuleBiofuel");
ForestryItem.waxCapsuleOil = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("waxCapsuleOil", Defaults.ID_ITEM_WAX_CAPSULE_OIL), 97))
.setItemName("waxCapsuleOil");
ForestryItem.waxCapsuleFuel = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("waxCapsuleFuel", Defaults.ID_ITEM_WAX_CAPSULE_FUEL), 113))
.setItemName("waxCapsuleFuel");
ForestryItem.waxCapsuleSeedOil = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("waxCapsuleSeedOil", Defaults.ID_ITEM_WAX_CAPSULE_SEED_OIL),
145)).setItemName("waxCapsuleSeedOil");
ForestryItem.waxCapsuleHoney = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("waxCapsuleHoney", Defaults.ID_ITEM_WAX_CAPSULE_HONEY), 161))
.setDrink(Defaults.FOOD_HONEY_HEAL, Defaults.FOOD_HONEY_SATURATION).setItemName("waxCapsuleHoney");
ForestryItem.waxCapsuleJuice = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("waxCapsuleJuice", Defaults.ID_ITEM_WAX_CAPSULE_JUICE), 177))
.setDrink(Defaults.FOOD_JUICE_HEAL, Defaults.FOOD_JUICE_SATURATION).setItemName("waxCapsuleJuice");
ForestryItem.waxCapsuleIce = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("waxCapsuleIce", Defaults.ID_ITEM_WAX_CAPSULE_ICE), 193))
.setItemName("waxCapsuleIce");
// / CANS
ForestryItem.canWater = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("waterCan", Defaults.ID_ITEM_WATERCAN), 16)).setItemName("waterCan");
ForestryItem.canBiomass = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("biomassCan", Defaults.ID_ITEM_BIOMASSCAN), 32))
.setItemName("biomassCan");
ForestryItem.canBiofuel = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("biofuelCan", Defaults.ID_ITEM_BIOFUELCAN), 48))
.setItemName("biofuelCan");
ForestryItem.canOil = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("canOil", Defaults.ID_ITEM_CAN_OIL), 96)).setItemName("canOil");
ForestryItem.canFuel = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("canFuel", Defaults.ID_ITEM_CAN_FUEL), 112)).setItemName("canFuel");
ForestryItem.canLava = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("canLava", Defaults.ID_ITEM_CAN_LAVA), 128)).setItemName("canLava");
ForestryItem.canSeedOil = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("canSeedOil", Defaults.ID_ITEM_CAN_SEED_OIL), 144))
.setItemName("canSeedOil");
ForestryItem.canHoney = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("canHoney", Defaults.ID_ITEM_CAN_HONEY), 160)).setDrink(
Defaults.FOOD_HONEY_HEAL, Defaults.FOOD_HONEY_SATURATION).setItemName("canHoney");
ForestryItem.canJuice = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("canJuice", Defaults.ID_ITEM_CAN_JUICE), 176)).setDrink(
Defaults.FOOD_JUICE_HEAL, Defaults.FOOD_JUICE_SATURATION).setItemName("canJuice");
ForestryItem.canIce = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("canIce", Defaults.ID_ITEM_CAN_ICE), 192)).setItemName("canIce");
// / REFRACTORY CAPSULES
ForestryItem.refractoryWater = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("refractoryWater", Defaults.ID_ITEM_REFRACTORY_WATER), 23))
.setItemName("refractoryWater");
ForestryItem.refractoryBiomass = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("refractoryBiomass", Defaults.ID_ITEM_REFRACTORY_BIOMASS),
39)).setItemName("refractoryBiomass");
ForestryItem.refractoryBiofuel = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("refractoryBiofuel", Defaults.ID_ITEM_REFRACTORY_BIOFUEL),
55)).setItemName("refractoryBiofuel");
ForestryItem.refractoryOil = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("refractoryOil", Defaults.ID_ITEM_REFRACTORY_OIL), 103))
.setItemName("refractoryOil");
ForestryItem.refractoryFuel = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("refractoryFuel", Defaults.ID_ITEM_REFRACTORY_FUEL), 119))
.setItemName("refractoryFuel");
ForestryItem.refractoryLava = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("refractoryLava", Defaults.ID_ITEM_REFRACTORY_LAVA), 135))
.setItemName("refractoryLava");
ForestryItem.refractorySeedOil = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("refractorySeedOil", Defaults.ID_ITEM_REFRACTORY_SEED_OIL),
151)).setItemName("refractorySeedOil");
ForestryItem.refractoryHoney = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("refractoryHoney", Defaults.ID_ITEM_REFRACTORY_HONEY), 167))
.setDrink(Defaults.FOOD_HONEY_HEAL, Defaults.FOOD_HONEY_SATURATION).setItemName("refractoryHoney");
ForestryItem.refractoryJuice = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("refractoryJuice", Defaults.ID_ITEM_REFRACTORY_JUICE), 183))
.setDrink(Defaults.FOOD_JUICE_HEAL, Defaults.FOOD_JUICE_SATURATION).setItemName("refractoryJuice");
ForestryItem.refractoryIce = (new ItemLiquidContainer(Config.getOrCreateItemIdProperty("refractoryIce", Defaults.ID_ITEM_REFRACTORY_ICE), 199))
.setItemName("refractoryIce");
// / LIQUIDS
ForestryItem.liquidMilk = (new ItemLiquids(Config.getOrCreateItemIdProperty("liquidMilk", Defaults.ID_ITEM_MILK))).setItemName("liquidMilk")
.setIconIndex(15);
ForestryItem.liquidBiofuel = (new ItemLiquids(Config.getOrCreateItemIdProperty("bioFuel", Defaults.ID_ITEM_BIOFUEL))).setItemName("bioFuel")
.setIconIndex(12);
ForestryItem.liquidBiomass = (new ItemLiquids(Config.getOrCreateItemIdProperty("bioMass", Defaults.ID_ITEM_BIOMASS))).setItemName("bioMass")
.setIconIndex(13);
ForestryItem.liquidSeedOil = (new ItemLiquids(Config.getOrCreateItemIdProperty("liquidSeedOil", Defaults.ID_ITEM_SEED_OIL))).setItemName(
"liquidSeedOil").setIconIndex(74);
ForestryItem.liquidJuice = (new ItemLiquids(Config.getOrCreateItemIdProperty("appleJuice", Defaults.ID_ITEM_APPLE_JUICE))).setItemName("appleJuice")
.setIconIndex(75);
ForestryItem.liquidHoney = (new ItemLiquids(Config.getOrCreateItemIdProperty("liquidHoney", Defaults.ID_ITEM_LIQUIDS))).setItemName("liquidHoney")
.setIconIndex(76);
ForestryItem.liquidMead = (new ItemLiquids(Config.getOrCreateItemIdProperty("liquidMead", Defaults.ID_ITEM_MEAD))).setItemName("liquidMead")
.setIconIndex(77);
ForestryItem.liquidGlass = (new ItemLiquids(Config.getOrCreateItemIdProperty("liquidGlass", Defaults.ID_ITEM_MOLTEN_GLASS))).setItemName("liquidGlass")
.setIconIndex(49);
ForestryItem.liquidIce = (new ItemLiquids(Config.getOrCreateItemIdProperty("liquidIce", Defaults.ID_ITEM_CRUSHED_ICE))).setItemName("liquidIce")
.setIconIndex(73);
// / CRATES
ForestryItem.cratedWood = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedWood", Defaults.ID_ITEM_CRATED_WOOD), new ItemStack(
Block.wood))).setItemName("cratedWood").setIconIndex(1);
ForestryItem.cratedCobblestone = (ItemCrated) (new ItemCrated(
Config.getOrCreateItemIdProperty("cratedCobblestone", Defaults.ID_ITEM_CRATED_COBBLESTONE), new ItemStack(Block.cobblestone))).setItemName(
"cratedCobblestone").setIconIndex(2);
ForestryItem.cratedDirt = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedDirt", Defaults.ID_ITEM_CRATED_DIRT), new ItemStack(
Block.dirt))).setItemName("cratedDirt").setIconIndex(3);
ForestryItem.cratedStone = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedStone", Defaults.ID_ITEM_CRATED_STONE), new ItemStack(
Block.stone))).setItemName("cratedStone").setIconIndex(4);
ForestryItem.cratedBrick = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedBrick", Defaults.ID_ITEM_CRATED_BRICK), new ItemStack(
Block.brick))).setItemName("cratedBrick").setIconIndex(5);
ForestryItem.cratedCacti = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedCacti", Defaults.ID_ITEM_CRATED_CACTI), new ItemStack(
Block.cactus))).setItemName("cratedCacti").setIconIndex(6);
ForestryItem.cratedSand = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedSand", Defaults.ID_ITEM_CRATED_SAND), new ItemStack(
Block.sand))).setItemName("cratedSand").setIconIndex(7);
ForestryItem.cratedObsidian = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedObsidian", Defaults.ID_ITEM_CRATED_OBSIDIAN),
new ItemStack(Block.obsidian))).setItemName("cratedObsidian").setIconIndex(8);
ForestryItem.cratedNetherrack = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedNetherrack", Defaults.ID_ITEM_CRATED_NETHERRACK),
new ItemStack(Block.netherrack))).setItemName("cratedNetherrack").setIconIndex(9);
ForestryItem.cratedSoulsand = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedSoulsand", Defaults.ID_ITEM_CRATED_SOULSAND),
new ItemStack(Block.slowSand))).setItemName("cratedSoulsand").setIconIndex(10);
ForestryItem.cratedSandstone = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedSandstone", Defaults.ID_ITEM_CRATED_SANDSTONE),
new ItemStack(Block.sandStone))).setItemName("cratedSandstone").setIconIndex(11);
ForestryItem.cratedBogearth = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedBogearth", Defaults.ID_ITEM_CRATED_BOGEARTH),
new ItemStack(ForestryBlock.soil, 1, 1))).setItemName("cratedBogearth").setIconIndex(12);
ForestryItem.cratedHumus = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedHumus", Defaults.ID_ITEM_CRATED_HUMUS), new ItemStack(
ForestryBlock.soil, 1, 0))).setItemName("cratedHumus").setIconIndex(13);
ForestryItem.cratedNetherbrick = (ItemCrated) (new ItemCrated(
Config.getOrCreateItemIdProperty("cratedNetherbrick", Defaults.ID_ITEM_CRATED_NETHERBRICK), new ItemStack(Block.netherBrick))).setItemName(
"cratedNetherbrick").setIconIndex(14);
ForestryItem.cratedPeat = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedPeat", Defaults.ID_ITEM_CRATED_PEAT), new ItemStack(
ForestryItem.peat))).setItemName("cratedPeat").setIconIndex(17);
ForestryItem.cratedApatite = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedApatite", Defaults.ID_ITEM_CRATED_APATITE),
new ItemStack(ForestryItem.apatite))).setItemName("cratedApatite").setIconIndex(18);
ForestryItem.cratedFertilizer = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedFertilizer", Defaults.ID_ITEM_CRATED_FERTILIZER),
new ItemStack(ForestryItem.fertilizerCompound))).setItemName("cratedFertilizer").setIconIndex(19);
ForestryItem.cratedTin = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedTin", Defaults.ID_ITEM_CRATED_TIN), ForestryItem.ingotTin))
.setItemName("cratedTin").setIconIndex(20);
ForestryItem.cratedCopper = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedCopper", Defaults.ID_ITEM_CRATED_COPPER),
ForestryItem.ingotCopper)).setItemName("cratedCopper").setIconIndex(21);
ForestryItem.cratedBronze = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedBronze", Defaults.ID_ITEM_CRATED_BRONZE),
ForestryItem.ingotBronze)).setItemName("cratedBronze").setIconIndex(22);
ForestryItem.cratedWheat = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedWheat", Defaults.ID_ITEM_CRATED_WHEAT), new ItemStack(
Item.wheat))).setItemName("cratedWheat").setIconIndex(23);
ForestryItem.cratedMycelium = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedMycelium", Defaults.ID_ITEM_CRATED_MYCELIUM),
new ItemStack(Block.mycelium))).setItemName("cratedMycelium").setIconIndex(15);
ForestryItem.cratedMulch = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedMulch", Defaults.ID_ITEM_CRATED_MULCH), new ItemStack(
ForestryItem.mulch))).setItemName("cratedMulch").setIconIndex(24);
ForestryItem.cratedSilver = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedSilver", Defaults.ID_ITEM_CRATED_SILVER)))
.setItemName("cratedSilver").setIconIndex(25);
ForestryItem.cratedBrass = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedBrass", Defaults.ID_ITEM_CRATED_BRASS))).setItemName(
"cratedBrass").setIconIndex(26);
ForestryItem.cratedNikolite = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedNikolite", Defaults.ID_ITEM_CRATED_NIKOLITE)))
.setItemName("cratedNikolite").setIconIndex(27);
ForestryItem.cratedCookies = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedCookies", Defaults.ID_ITEM_CRATED_COOKIES),
new ItemStack(Item.cookie))).setItemName("cratedCookies").setIconIndex(28);
ForestryItem.cratedRedstone = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedRedstone", Defaults.ID_ITEM_CRATED_REDSTONE),
new ItemStack(Item.redstone))).setItemName("cratedRedstone").setIconIndex(36);
ForestryItem.cratedLapis = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedLapis", Defaults.ID_ITEM_CRATED_LAPIS), new ItemStack(
Item.dyePowder, 1, 4))).setItemName("cratedLapis").setIconIndex(37);
ForestryItem.cratedReeds = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedReeds", Defaults.ID_ITEM_CRATED_REEDS), new ItemStack(
Item.reed))).setItemName("cratedReeds").setIconIndex(38);
ForestryItem.cratedClay = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedClay", Defaults.ID_ITEM_CRATED_CLAY), new ItemStack(
Item.clay))).setItemName("cratedClay").setIconIndex(39);
ForestryItem.cratedGlowstone = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedGlowstone", Defaults.ID_ITEM_CRATED_GLOWSTONE),
new ItemStack(Item.lightStoneDust))).setItemName("cratedGlowstone").setIconIndex(40);
ForestryItem.cratedApples = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedApples", Defaults.ID_ITEM_CRATED_APPLES),
new ItemStack(Item.appleRed))).setItemName("cratedApples").setIconIndex(41);
ForestryItem.cratedNetherwart = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedNetherwart", Defaults.ID_ITEM_CRATED_NETHERWART),
new ItemStack(Item.netherStalkSeeds))).setItemName("cratedNetherwart").setIconIndex(42);
ForestryItem.cratedResin = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedResin", Defaults.ID_ITEM_CRATED_RESIN))).setItemName(
"cratedResin").setIconIndex(43);
ForestryItem.cratedRubber = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedRubber", Defaults.ID_ITEM_CRATED_RUBBER)))
.setItemName("cratedRubber").setIconIndex(44);
ForestryItem.cratedScrap = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedScrap", Defaults.ID_ITEM_CRATED_SCRAP))).setItemName(
"cratedScrap").setIconIndex(45);
ForestryItem.cratedUUM = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedUUM", Defaults.ID_ITEM_CRATED_UUM))).setItemName(
"cratedUUM").setIconIndex(46);
ForestryItem.cratedPhosphor = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedPhosphor", Defaults.ID_ITEM_CRATED_PHOSPHOR),
new ItemStack(ForestryItem.phosphor))).setItemName("cratedPhosphor").setIconIndex(52);
ForestryItem.cratedAsh = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedAsh", Defaults.ID_ITEM_CRATED_ASH), new ItemStack(
ForestryItem.ash))).setItemName("cratedAsh").setIconIndex(53);
ForestryItem.cratedCharcoal = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedCharcoal", Defaults.ID_ITEM_CRATED_CHARCOAL),
new ItemStack(Item.coal, 1, 1))).setItemName("cratedCharcoal").setIconIndex(54);
ForestryItem.cratedGravel = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedGravel", Defaults.ID_ITEM_CRATED_GRAVEL),
new ItemStack(Block.gravel))).setItemName("cratedGravel").setIconIndex(55);
ForestryItem.cratedCoal = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedCoal", Defaults.ID_ITEM_CRATED_COAL), new ItemStack(
Item.coal, 1, 0))).setItemName("cratedCoal").setIconIndex(54);
ForestryItem.cratedSeeds = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedSeeds", Defaults.ID_ITEM_CRATED_SEEDS), new ItemStack(
Item.seeds))).setItemName("cratedSeeds").setIconIndex(56);
ForestryItem.cratedSaplings = (ItemCrated) (new ItemCrated(Config.getOrCreateItemIdProperty("cratedSaplings", Defaults.ID_ITEM_CRATED_SAPLINGS),
new ItemStack(Block.sapling))).setItemName("cratedSaplings").setIconIndex(57);
}
@Override
protected void registerBackpackItems() {
}
@Override
protected void registerCrates() {
}
@Override
protected void registerRecipes() {
// / BRONZE INGOTS
if (Config.craftingBronzeEnabled) {
Proxies.common.addRecipe(new ItemStack(ForestryItem.ingotBronze.itemID, 4, ForestryItem.ingotBronze.getItemDamage()), new Object[] { "##", "#X",
Character.valueOf('#'), "ingotCopper", Character.valueOf('X'), "ingotTin" });
}
// / STURDY MACHINE
Proxies.common.addRecipe(new ItemStack(ForestryItem.sturdyCasing, 1), new Object[] { "###", "# #", "###", Character.valueOf('#'), "ingotBronze" });
// / EMPTY CANS
Proxies.common.addRecipe(GameMode.getGameMode().getRecipeCanOutput(), new Object[] { " # ", "# #", Character.valueOf('#'), "ingotTin" });
// / GEARS
if (PluginBuildCraft.stoneGear != null) {
Proxies.common.addRecipe(new ItemStack(ForestryItem.gearBronze, 1), new Object[] { " # ", "#Y#", " # ", Character.valueOf('#'), "ingotBronze",
Character.valueOf('Y'), PluginBuildCraft.stoneGear });
Proxies.common.addRecipe(new ItemStack(ForestryItem.gearCopper, 1), new Object[] { " # ", "#Y#", " # ", Character.valueOf('#'), "ingotCopper",
Character.valueOf('Y'), PluginBuildCraft.stoneGear });
Proxies.common.addRecipe(new ItemStack(ForestryItem.gearTin, 1),
new Object[] { " # ", "#Y#", " # ", Character.valueOf('#'), "ingotTin", Character.valueOf('Y'), PluginBuildCraft.stoneGear });
} else {
Proxies.common.addRecipe(new ItemStack(ForestryItem.gearBronze, 1), new Object[] { " # ", "#X#", " # ", Character.valueOf('#'), "ingotBronze",
Character.valueOf('X'), "ingotCopper" });
Proxies.common.addRecipe(new ItemStack(ForestryItem.gearCopper, 1), new Object[] { " # ", "#X#", " # ", Character.valueOf('#'), "ingotCopper",
Character.valueOf('X'), "ingotCopper" });
Proxies.common.addRecipe(new ItemStack(ForestryItem.gearTin, 1),
new Object[] { " # ", "#X#", " # ", Character.valueOf('#'), "ingotTin", Character.valueOf('X'), "ingotCopper" });
}
// / SURVIVALIST TOOLS
Proxies.common.addRecipe(new ItemStack(ForestryItem.bronzePickaxe), new Object[] { " X ", " X ", "###", '#', "ingotBronze", 'X', "stickWood" });
Proxies.common.addRecipe(new ItemStack(ForestryItem.bronzeShovel), new Object[] { " X ", " X ", " # ", '#', "ingotBronze", 'X', "stickWood" });
Proxies.common.addShapelessRecipe(new ItemStack(ForestryItem.kitPickaxe), new Object[] { ForestryItem.bronzePickaxe, ForestryItem.carton });
Proxies.common.addShapelessRecipe(new ItemStack(ForestryItem.kitShovel), new Object[] { ForestryItem.bronzeShovel, ForestryItem.carton });
// / WRENCH
Proxies.common.addRecipe(new ItemStack(ForestryItem.wrench, 1), new Object[] { "# #", " # ", " # ", Character.valueOf('#'), "ingotBronze" });
// Manure and Fertilizer
if (GameMode.getGameMode().getRecipeCompostOutputWheat().stackSize > 0) {
Proxies.common.addRecipe(GameMode.getGameMode().getRecipeCompostOutputWheat(), new Object[] { " X ", "X#X", " X ", Character.valueOf('#'),
Block.dirt, Character.valueOf('X'), Item.wheat });
}
if (GameMode.getGameMode().getRecipeCompostOutputAsh().stackSize > 0) {
Proxies.common.addRecipe(GameMode.getGameMode().getRecipeCompostOutputAsh(), new Object[] { " X ", "X#X", " X ", Character.valueOf('#'),
Block.dirt, Character.valueOf('X'), "dustAsh" });
}
if (GameMode.getGameMode().getRecipeFertilizerOutputApatite().stackSize > 0) {
Proxies.common.addRecipe(GameMode.getGameMode().getRecipeFertilizerOutputApatite(), new Object[] { " # ", " X ", " # ", Character.valueOf('#'),
Block.sand, Character.valueOf('X'), ForestryItem.apatite });
}
if (GameMode.getGameMode().getRecipeFertilizerOutputAsh().stackSize > 0) {
Proxies.common.addRecipe(GameMode.getGameMode().getRecipeFertilizerOutputAsh(), new Object[] { "###", "#X#", "###", '#', "dustAsh", 'X', ForestryItem.apatite });
}
// Humus
if (GameMode.getGameMode().getRecipeHumusOutputCompost().stackSize > 0) {
Proxies.common.addRecipe(GameMode.getGameMode().getRecipeHumusOutputCompost(),
new Object[] { "###", "#X#", "###", Character.valueOf('#'), Block.dirt, Character.valueOf('X'), ForestryItem.fertilizerBio });
}
if (GameMode.getGameMode().getRecipeHumusOutputFertilizer().stackSize > 0) {
Proxies.common.addRecipe(GameMode.getGameMode().getRecipeHumusOutputFertilizer(),
new Object[] { "###", "#X#", "###", Character.valueOf('#'), Block.dirt, Character.valueOf('X'), ForestryItem.fertilizerCompound });
}
// Bog earth
if (GameMode.getGameMode().getRecipeBogEarthOutputBucket().stackSize > 0) {
Proxies.common.addRecipe(GameMode.getGameMode().getRecipeBogEarthOutputBucket(), new Object[] { "#Y#", "YXY", "#Y#", Character.valueOf('#'),
Block.dirt, Character.valueOf('X'), Item.bucketWater, Character.valueOf('Y'), Block.sand });
}
if (GameMode.getGameMode().getRecipeBogEarthOutputCans().stackSize > 0) {
Proxies.common.addRecipe(GameMode.getGameMode().getRecipeBogEarthOutputCans(), new Object[] { "#Y#", "YXY", "#Y#", Character.valueOf('#'),
Block.dirt, Character.valueOf('X'), ForestryItem.canWater, Character.valueOf('Y'), Block.sand });
Proxies.common.addRecipe(GameMode.getGameMode().getRecipeBogEarthOutputCans(), new Object[] { "#Y#", "YXY", "#Y#", Character.valueOf('#'),
Block.dirt, Character.valueOf('X'), ForestryItem.waxCapsuleWater, Character.valueOf('Y'), Block.sand });
Proxies.common.addRecipe(GameMode.getGameMode().getRecipeBogEarthOutputCans(), new Object[] { "#Y#", "YXY", "#Y#", Character.valueOf('#'),
Block.dirt, Character.valueOf('X'), ForestryItem.refractoryWater, Character.valueOf('Y'), Block.sand });
}
// Vials and catalyst
Proxies.common.addRecipe(new ItemStack(ForestryItem.vialCatalyst, 3), new Object[] { "###", "YXY", Character.valueOf('#'), ForestryItem.waxCapsule,
Character.valueOf('X'), Item.bone, Character.valueOf('Y'), ForestryItem.fertilizerCompound });
Proxies.common.addRecipe(new ItemStack(ForestryItem.vialCatalyst, 3), new Object[] { "###", "YXY", Character.valueOf('#'), ForestryItem.canEmpty,
Character.valueOf('X'), Item.bone, Character.valueOf('Y'), ForestryItem.fertilizerCompound });
// Crafting Material
Proxies.common.addRecipe(new ItemStack(Item.silk), new Object[] { "#", "#", "#", Character.valueOf('#'),
new ItemStack(ForestryItem.craftingMaterial, 1, 2) });
// / Pipette
Proxies.common.addRecipe(new ItemStack(ForestryItem.pipette),
new Object[] { " #", " X ", "X ", Character.valueOf('X'), Block.thinGlass, Character.valueOf('#'), new ItemStack(Block.cloth, 1, -1) });
}
@Override
public IOreDictionaryHandler getDictionaryHandler() {
return null;
}
@Override
public ICommand[] getConsoleCommands() {
return new ICommand[] { new CommandForestry() };
}
@Override
public int getBurnTime(ItemStack fuel) {
if (fuel != null && fuel.itemID == ForestryItem.peat.itemID)
return 2000;
if (fuel != null && fuel.itemID == ForestryItem.bituminousPeat.itemID)
return 4200;
return 0;
}
@Override
public boolean processIMCMessage(IMCMessage message) {
if(message.key.equals("securityViolation")) {
Config.invalidFingerprint = true;
}
return false;
}
/* PACKAGE DEFINITION */
public static IRecipe[] getAnalyzerRecipes(int blockid, int meta) {
ArrayList<IRecipe> recipes = new ArrayList<IRecipe>();
if(ForestryItem.beealyzer != null)
recipes.add(ShapedRecipeCustom.createShapedRecipe(new Object[] { "XTX", " Y ", "X X", Character.valueOf('Y'), ForestryItem.sturdyCasing, Character.valueOf('T'),
ForestryItem.beealyzer, Character.valueOf('X'), "ingotBronze" },
new ItemStack(blockid, 1, meta)
));
if(ForestryItem.treealyzer != null)
recipes.add(ShapedRecipeCustom.createShapedRecipe(new Object[] { "XTX", " Y ", "X X", Character.valueOf('Y'), ForestryItem.sturdyCasing, Character.valueOf('T'),
ForestryItem.treealyzer, Character.valueOf('X'), "ingotBronze" },
new ItemStack(blockid, 1, meta)
));
return recipes.toArray(new IRecipe[0]);
}
}
| gpl-3.0 |
czy920/DCOPSolver | DCOPSolver/src/com/cqu/util/DialogUtil.java | 2615 | package com.cqu.util;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
public class DialogUtil {
/**
* 过滤文件的类型放在fileTypes数组中,比如{".jpg", ".png", ".bmp"},或者{".*"}
* @param fileTypes
* @return
*/
public static File dialogOpenFile(final String[] fileTypes, String title, String defaultDir)
{
JFileChooser jfileChooser=new JFileChooser();
jfileChooser.setDialogTitle(title);
jfileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
if(defaultDir!=null&&defaultDir.length()>0)
{
jfileChooser.setCurrentDirectory(new File(defaultDir));
}
jfileChooser.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
// TODO Auto-generated method stub
String desc="";
for(int i=0;i<fileTypes.length;i++)
{
desc+=fileTypes[i]+";";
}
return desc;
}
@Override
public boolean accept(File file) {
// TODO Auto-generated method stub
if(file.isDirectory()==true)
{
return true;
}
String fileName=file.getName().toLowerCase();
if(fileTypes[0].equals(".*")==true)
{
return true;
}
for(int i=0;i<fileTypes.length;i++)
{
if(fileName.endsWith(fileTypes[i])==true)
{
return true;
}
}
return false;
}
});
if(jfileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
return jfileChooser.getSelectedFile();
}
return null;
}
public static File dialogOpenDir(String title, String defaultDir)
{
JFileChooser jfileChooser=new JFileChooser();
jfileChooser.setDialogTitle(title);
if(defaultDir!=null&&defaultDir.length()>0)
{
jfileChooser.setCurrentDirectory(new File(defaultDir));
}
jfileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = jfileChooser.showOpenDialog(jfileChooser);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
return jfileChooser.getSelectedFile();
}
return null;
}
public static void dialogWaring(String message)
{
JOptionPane.showMessageDialog(null, message, "Warning", JOptionPane.WARNING_MESSAGE);
}
public static void dialogError(String message)
{
JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE);
}
public static void dialogInformation(String message)
{
JOptionPane.showMessageDialog(null, message, "Information", JOptionPane.INFORMATION_MESSAGE);
}
}
| gpl-3.0 |
triplea-game/triplea | game-app/game-core/src/main/java/games/strategy/engine/framework/startup/ui/PlayerSelectorRow.java | 8646 | package games.strategy.engine.framework.startup.ui;
import games.strategy.engine.data.GamePlayer;
import games.strategy.engine.data.properties.GameProperties;
import games.strategy.engine.framework.startup.launcher.local.PlayerCountrySelection;
import games.strategy.triplea.Constants;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
/**
* Represents a player selection row worth of data, during initial setup this is a row where a
* player can choose to play a country, set it to AI, etc.
*/
public class PlayerSelectorRow implements PlayerCountrySelection {
private final JCheckBox enabledCheckBox;
private final String playerName;
private final GamePlayer player;
private final JComboBox<String> playerTypes;
private final JComponent incomePercentage;
private final JLabel incomePercentageLabel;
private final JComponent puIncomeBonus;
private final JLabel puIncomeBonusLabel;
private boolean enabled = true;
private final JLabel name;
private JButton alliances;
private final Collection<String> disableable;
private final SetupPanel parent;
private final PlayerTypes playerTypesProvider;
PlayerSelectorRow(
final List<PlayerSelectorRow> playerRows,
final GamePlayer player,
final Map<String, String> reloadSelections,
final Collection<String> disableable,
final Map<String, Boolean> playersEnablementListing,
final Collection<String> playerAlliances,
final SetupPanel parent,
final GameProperties gameProperties,
final PlayerTypes playerTypes) {
this.disableable = disableable;
this.parent = parent;
playerName = player.getName();
this.player = player;
name = new JLabel(playerName + ":");
this.playerTypesProvider = playerTypes;
enabledCheckBox = new JCheckBox();
final ActionListener disablePlayerActionListener =
new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
if (enabledCheckBox.isSelected()) {
enabled = true;
// the 1st in the list should be human
PlayerSelectorRow.this.playerTypes.setSelectedItem(PlayerTypes.HUMAN_PLAYER);
} else {
enabled = false;
// the 2nd in the list should be Weak AI
PlayerSelectorRow.this.playerTypes.setSelectedItem(PlayerTypes.WEAK_AI);
}
setWidgetActivation();
}
};
enabledCheckBox.addActionListener(disablePlayerActionListener);
enabledCheckBox.setSelected(playersEnablementListing.get(playerName));
enabledCheckBox.setEnabled(disableable.contains(playerName));
this.playerTypes = new JComboBox<>(this.playerTypesProvider.getAvailablePlayerLabels());
String previousSelection = reloadSelections.get(playerName);
if (previousSelection.equalsIgnoreCase("Client")) {
previousSelection = PlayerTypes.HUMAN_PLAYER.getLabel();
}
if (List.of(this.playerTypesProvider.getAvailablePlayerLabels()).contains(previousSelection)) {
this.playerTypes.setSelectedItem(previousSelection);
} else {
setDefaultPlayerType();
}
alliances = null;
if (!playerAlliances.contains(playerName)) {
final String alliancesLabelText = playerAlliances.toString();
alliances = new JButton(alliancesLabelText);
alliances.setToolTipText("Click to play " + alliancesLabelText);
alliances.addActionListener(
e ->
playerRows.stream()
.filter(
row ->
row.alliances != null
&& row.alliances.getText().equals(alliancesLabelText))
.forEach(row -> row.setPlayerType(PlayerTypes.HUMAN_PLAYER.getLabel())));
}
incomePercentage =
gameProperties
.getPlayerProperty(Constants.getIncomePercentageFor(player))
.getEditorComponent();
incomePercentageLabel = new JLabel("%");
puIncomeBonus =
gameProperties.getPlayerProperty(Constants.getPuIncomeBonus(player)).getEditorComponent();
puIncomeBonusLabel = new JLabel("PUs");
setWidgetActivation();
}
void layout(final int row, final Container container) {
int gridx = 0;
if (!disableable.isEmpty()) {
container.add(
enabledCheckBox,
new GridBagConstraints(
gridx++,
row,
1,
1,
0,
0,
GridBagConstraints.WEST,
GridBagConstraints.NONE,
new Insets(0, 5, 5, 0),
0,
0));
}
container.add(
name,
new GridBagConstraints(
gridx++,
row,
1,
1,
0,
0,
GridBagConstraints.WEST,
GridBagConstraints.NONE,
new Insets(0, 5, 5, 0),
0,
0));
container.add(
playerTypes,
new GridBagConstraints(
gridx++,
row,
1,
1,
0,
0,
GridBagConstraints.WEST,
GridBagConstraints.NONE,
new Insets(0, 5, 5, 0),
0,
0));
if (alliances != null) {
container.add(
alliances,
new GridBagConstraints(
gridx,
row,
1,
1,
0,
0,
GridBagConstraints.WEST,
GridBagConstraints.NONE,
new Insets(0, 7, 5, 5),
0,
0));
}
gridx++;
container.add(
incomePercentage,
new GridBagConstraints(
gridx++,
row,
1,
1,
0,
0,
GridBagConstraints.WEST,
GridBagConstraints.NONE,
new Insets(0, 20, 2, 0),
0,
0));
container.add(
incomePercentageLabel,
new GridBagConstraints(
gridx++,
row,
1,
1,
0,
0,
GridBagConstraints.WEST,
GridBagConstraints.NONE,
new Insets(0, 5, 5, 5),
0,
0));
container.add(
puIncomeBonus,
new GridBagConstraints(
gridx++,
row,
1,
1,
0,
0,
GridBagConstraints.WEST,
GridBagConstraints.NONE,
new Insets(0, 20, 2, 0),
0,
0));
container.add(
puIncomeBonusLabel,
new GridBagConstraints(
gridx,
row,
1,
1,
0,
0,
GridBagConstraints.WEST,
GridBagConstraints.NONE,
new Insets(0, 5, 5, 5),
0,
0));
}
void setResourceModifiersVisible(final boolean isVisible) {
incomePercentage.setVisible(isVisible);
incomePercentageLabel.setVisible(isVisible);
puIncomeBonus.setVisible(isVisible);
puIncomeBonusLabel.setVisible(isVisible);
}
void setPlayerType(final String playerType) {
if (enabled && !player.isHidden()) {
playerTypes.setSelectedItem(playerType);
}
}
void setDefaultPlayerType() {
if (player.isDefaultTypeAi()) {
playerTypes.setSelectedItem(PlayerTypes.PRO_AI.getLabel());
} else if (player.isDefaultTypeDoesNothing()) {
playerTypes.setSelectedItem(PlayerTypes.DOES_NOTHING_PLAYER_LABEL);
} else {
playerTypes.setSelectedItem(PlayerTypes.HUMAN_PLAYER.getLabel());
}
}
@Override
public String getPlayerName() {
return playerName;
}
@Override
public PlayerTypes.Type getPlayerType() {
return this.playerTypesProvider.fromLabel(String.valueOf(this.playerTypes.getSelectedItem()));
}
@Override
public boolean isPlayerEnabled() {
return enabledCheckBox.isSelected();
}
private void setWidgetActivation() {
name.setEnabled(enabled);
if (alliances != null) {
alliances.setEnabled(enabled);
}
enabledCheckBox.setEnabled(disableable.contains(playerName));
incomePercentage.setEnabled(enabled);
puIncomeBonus.setEnabled(enabled);
parent.fireListener();
}
}
| gpl-3.0 |
syslover33/ctank | java/android-sdk-linux_r24.4.1_src/sources/android-23/com/android/internal/telephony/cdma/CdmaMmiCode.java | 13222 | /*
* Copyright (C) 2006 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.internal.telephony.cdma;
import android.content.Context;
import com.android.internal.telephony.CommandException;
import com.android.internal.telephony.uicc.UiccCardApplication;
import com.android.internal.telephony.uicc.IccCardApplicationStatus.AppState;
import com.android.internal.telephony.MmiCode;
import com.android.internal.telephony.Phone;
import android.os.AsyncResult;
import android.os.Handler;
import android.os.Message;
import android.telephony.Rlog;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
* This class can handle Puk code Mmi
*
* {@hide}
*
*/
public final class CdmaMmiCode extends Handler implements MmiCode {
static final String LOG_TAG = "CdmaMmiCode";
// Constants
// From TS 22.030 6.5.2
static final String ACTION_REGISTER = "**";
// Supplementary Service codes for PIN/PIN2/PUK/PUK2 from TS 22.030 Annex B
static final String SC_PIN = "04";
static final String SC_PIN2 = "042";
static final String SC_PUK = "05";
static final String SC_PUK2 = "052";
// Event Constant
static final int EVENT_SET_COMPLETE = 1;
// Instance Variables
CDMAPhone mPhone;
Context mContext;
UiccCardApplication mUiccApplication;
String mAction; // ACTION_REGISTER
String mSc; // Service Code
String mSia, mSib, mSic; // Service Info a,b,c
String mPoundString; // Entire MMI string up to and including #
String mDialingNumber;
String mPwd; // For password registration
State mState = State.PENDING;
CharSequence mMessage;
// Class Variables
static Pattern sPatternSuppService = Pattern.compile(
"((\\*|#|\\*#|\\*\\*|##)(\\d{2,3})(\\*([^*#]*)(\\*([^*#]*)(\\*([^*#]*)(\\*([^*#]*))?)?)?)?#)(.*)");
/* 1 2 3 4 5 6 7 8 9 10 11 12
1 = Full string up to and including #
2 = action
3 = service code
5 = SIA
7 = SIB
9 = SIC
10 = dialing number
*/
static final int MATCH_GROUP_POUND_STRING = 1;
static final int MATCH_GROUP_ACTION = 2;
static final int MATCH_GROUP_SERVICE_CODE = 3;
static final int MATCH_GROUP_SIA = 5;
static final int MATCH_GROUP_SIB = 7;
static final int MATCH_GROUP_SIC = 9;
static final int MATCH_GROUP_PWD_CONFIRM = 11;
static final int MATCH_GROUP_DIALING_NUMBER = 12;
// Public Class methods
/**
* Check if provided string contains Mmi code in it and create corresponding
* Mmi if it does
*/
public static CdmaMmiCode
newFromDialString(String dialString, CDMAPhone phone, UiccCardApplication app) {
Matcher m;
CdmaMmiCode ret = null;
m = sPatternSuppService.matcher(dialString);
// Is this formatted like a standard supplementary service code?
if (m.matches()) {
ret = new CdmaMmiCode(phone,app);
ret.mPoundString = makeEmptyNull(m.group(MATCH_GROUP_POUND_STRING));
ret.mAction = makeEmptyNull(m.group(MATCH_GROUP_ACTION));
ret.mSc = makeEmptyNull(m.group(MATCH_GROUP_SERVICE_CODE));
ret.mSia = makeEmptyNull(m.group(MATCH_GROUP_SIA));
ret.mSib = makeEmptyNull(m.group(MATCH_GROUP_SIB));
ret.mSic = makeEmptyNull(m.group(MATCH_GROUP_SIC));
ret.mPwd = makeEmptyNull(m.group(MATCH_GROUP_PWD_CONFIRM));
ret.mDialingNumber = makeEmptyNull(m.group(MATCH_GROUP_DIALING_NUMBER));
}
return ret;
}
// Private Class methods
/** make empty strings be null.
* Regexp returns empty strings for empty groups
*/
private static String
makeEmptyNull (String s) {
if (s != null && s.length() == 0) return null;
return s;
}
// Constructor
CdmaMmiCode (CDMAPhone phone, UiccCardApplication app) {
super(phone.getHandler().getLooper());
mPhone = phone;
mContext = phone.getContext();
mUiccApplication = app;
}
// MmiCode implementation
@Override
public State
getState() {
return mState;
}
@Override
public CharSequence
getMessage() {
return mMessage;
}
public Phone
getPhone() {
return ((Phone) mPhone);
}
// inherited javadoc suffices
@Override
public void
cancel() {
// Complete or failed cannot be cancelled
if (mState == State.COMPLETE || mState == State.FAILED) {
return;
}
mState = State.CANCELLED;
mPhone.onMMIDone (this);
}
@Override
public boolean isCancelable() {
return false;
}
// Instance Methods
/**
* @return true if the Service Code is PIN/PIN2/PUK/PUK2-related
*/
boolean isPinPukCommand() {
return mSc != null && (mSc.equals(SC_PIN) || mSc.equals(SC_PIN2)
|| mSc.equals(SC_PUK) || mSc.equals(SC_PUK2));
}
boolean isRegister() {
return mAction != null && mAction.equals(ACTION_REGISTER);
}
@Override
public boolean isUssdRequest() {
Rlog.w(LOG_TAG, "isUssdRequest is not implemented in CdmaMmiCode");
return false;
}
/** Process a MMI PUK code */
void
processCode() {
try {
if (isPinPukCommand()) {
// TODO: This is the same as the code in GsmMmiCode.java,
// MmiCode should be an abstract or base class and this and
// other common variables and code should be promoted.
// sia = old PIN or PUK
// sib = new PIN
// sic = new PIN
String oldPinOrPuk = mSia;
String newPinOrPuk = mSib;
int pinLen = newPinOrPuk.length();
if (isRegister()) {
if (!newPinOrPuk.equals(mSic)) {
// password mismatch; return error
handlePasswordError(com.android.internal.R.string.mismatchPin);
} else if (pinLen < 4 || pinLen > 8 ) {
// invalid length
handlePasswordError(com.android.internal.R.string.invalidPin);
} else if (mSc.equals(SC_PIN)
&& mUiccApplication != null
&& mUiccApplication.getState() == AppState.APPSTATE_PUK) {
// Sim is puk-locked
handlePasswordError(com.android.internal.R.string.needPuk);
} else if (mUiccApplication != null) {
Rlog.d(LOG_TAG, "process mmi service code using UiccApp sc=" + mSc);
// We have an app and the pre-checks are OK
if (mSc.equals(SC_PIN)) {
mUiccApplication.changeIccLockPassword(oldPinOrPuk, newPinOrPuk,
obtainMessage(EVENT_SET_COMPLETE, this));
} else if (mSc.equals(SC_PIN2)) {
mUiccApplication.changeIccFdnPassword(oldPinOrPuk, newPinOrPuk,
obtainMessage(EVENT_SET_COMPLETE, this));
} else if (mSc.equals(SC_PUK)) {
mUiccApplication.supplyPuk(oldPinOrPuk, newPinOrPuk,
obtainMessage(EVENT_SET_COMPLETE, this));
} else if (mSc.equals(SC_PUK2)) {
mUiccApplication.supplyPuk2(oldPinOrPuk, newPinOrPuk,
obtainMessage(EVENT_SET_COMPLETE, this));
} else {
throw new RuntimeException("Unsupported service code=" + mSc);
}
} else {
throw new RuntimeException("No application mUiccApplicaiton is null");
}
} else {
throw new RuntimeException ("Ivalid register/action=" + mAction);
}
}
} catch (RuntimeException exc) {
mState = State.FAILED;
mMessage = mContext.getText(com.android.internal.R.string.mmiError);
mPhone.onMMIDone(this);
}
}
private void handlePasswordError(int res) {
mState = State.FAILED;
StringBuilder sb = new StringBuilder(getScString());
sb.append("\n");
sb.append(mContext.getText(res));
mMessage = sb;
mPhone.onMMIDone(this);
}
@Override
public void
handleMessage (Message msg) {
AsyncResult ar;
if (msg.what == EVENT_SET_COMPLETE) {
ar = (AsyncResult) (msg.obj);
onSetComplete(msg, ar);
} else {
Rlog.e(LOG_TAG, "Unexpected reply");
}
}
// Private instance methods
private CharSequence getScString() {
if (mSc != null) {
if (isPinPukCommand()) {
return mContext.getText(com.android.internal.R.string.PinMmi);
}
}
return "";
}
private void
onSetComplete(Message msg, AsyncResult ar){
StringBuilder sb = new StringBuilder(getScString());
sb.append("\n");
if (ar.exception != null) {
mState = State.FAILED;
if (ar.exception instanceof CommandException) {
CommandException.Error err = ((CommandException)(ar.exception)).getCommandError();
if (err == CommandException.Error.PASSWORD_INCORRECT) {
if (isPinPukCommand()) {
// look specifically for the PUK commands and adjust
// the message accordingly.
if (mSc.equals(SC_PUK) || mSc.equals(SC_PUK2)) {
sb.append(mContext.getText(
com.android.internal.R.string.badPuk));
} else {
sb.append(mContext.getText(
com.android.internal.R.string.badPin));
}
// Get the No. of retries remaining to unlock PUK/PUK2
int attemptsRemaining = msg.arg1;
if (attemptsRemaining <= 0) {
Rlog.d(LOG_TAG, "onSetComplete: PUK locked,"
+ " cancel as lock screen will handle this");
mState = State.CANCELLED;
} else if (attemptsRemaining > 0) {
Rlog.d(LOG_TAG, "onSetComplete: attemptsRemaining="+attemptsRemaining);
sb.append(mContext.getResources().getQuantityString(
com.android.internal.R.plurals.pinpuk_attempts,
attemptsRemaining, attemptsRemaining));
}
} else {
sb.append(mContext.getText(
com.android.internal.R.string.passwordIncorrect));
}
} else if (err == CommandException.Error.SIM_PUK2) {
sb.append(mContext.getText(
com.android.internal.R.string.badPin));
sb.append("\n");
sb.append(mContext.getText(
com.android.internal.R.string.needPuk2));
} else if (err == CommandException.Error.REQUEST_NOT_SUPPORTED) {
if (mSc.equals(SC_PIN)) {
sb.append(mContext.getText(com.android.internal.R.string.enablePin));
}
} else {
sb.append(mContext.getText(
com.android.internal.R.string.mmiError));
}
} else {
sb.append(mContext.getText(
com.android.internal.R.string.mmiError));
}
} else if (isRegister()) {
mState = State.COMPLETE;
sb.append(mContext.getText(
com.android.internal.R.string.serviceRegistered));
} else {
mState = State.FAILED;
sb.append(mContext.getText(
com.android.internal.R.string.mmiError));
}
mMessage = sb;
mPhone.onMMIDone(this);
}
}
| gpl-3.0 |
RaysaOliveira/cloudsim-plus | cloudsim-plus/src/main/java/org/cloudsimplus/builders/tables/HtmlTableBuilder.java | 2308 | /*
* CloudSim Plus: A modern, highly-extensible and easier-to-use Framework for
* Modeling and Simulation of Cloud Computing Infrastructures and Services.
* http://cloudsimplus.org
*
* Copyright (C) 2015-2016 Universidade da Beira Interior (UBI, Portugal) and
* the Instituto Federal de Educação Ciência e Tecnologia do Tocantins (IFTO, Brazil).
*
* This file is part of CloudSim Plus.
*
* CloudSim Plus 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.
*
* CloudSim Plus 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 CloudSim Plus. If not, see <http://www.gnu.org/licenses/>.
*/
package org.cloudsimplus.builders.tables;
import org.cloudbus.cloudsim.util.Log;
/**
* A generator of HTML tables.
*
* @author Manoel Campos da Silva Filho
* @since CloudSim Plus 1.0
*/
public class HtmlTableBuilder extends AbstractTableBuilder {
public HtmlTableBuilder() {
super();
}
/**
* Creates an TableBuilder
* @param title Title of the table
*/
public HtmlTableBuilder(final String title) {
super(title);
}
@Override
protected void printTableOpening() {
Log.printLine("\n<table>");
}
@Override
protected void printTitle() {
Log.printFormatted(" <caption>%s</caption>\n", getTitle());
}
@Override
protected void printRowOpening() {
Log.printLine(" <tr>");
}
@Override
protected void printRowClosing() {
Log.printLine("\n </tr>");
}
@Override
protected void printTableClosing() {
Log.printLine("</table>\n");
}
@Override
public TableColumn addColumn(int index, String columnTitle) {
final TableColumn col = new HtmlTableColumn(this, columnTitle);
getColumns().add(index, col);
return col;
}
}
| gpl-3.0 |
lionelliang/zorka | zorka-core/src/main/java/com/jitlogic/zorka/core/spy/Tracer.java | 5443 | /**
* Copyright 2012-2015 Rafal Lewczuk <rafal.lewczuk@jitlogic.com>
* <p/>
* This 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.
* <p/>
* This software 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.
* <p/>
* You should have received a copy of the GNU General Public License
* along with this software. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jitlogic.zorka.core.spy;
import com.jitlogic.zorka.common.ZorkaService;
import com.jitlogic.zorka.common.ZorkaSubmitter;
import com.jitlogic.zorka.common.tracedata.SymbolRegistry;
import com.jitlogic.zorka.common.tracedata.SymbolicRecord;
import com.jitlogic.zorka.common.util.ZorkaAsyncThread;
import com.jitlogic.zorka.common.util.ZorkaUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
/**
* Groups all tracer engine components and global settings.
*
* @author rafal.lewczuk@jitlogic.com
*/
public class Tracer implements ZorkaSubmitter<SymbolicRecord>, ZorkaService {
/**
* Minimum default method execution time required to attach method to trace.
*/
private static long minMethodTime = 250000;
/**
* Maximum number of records inside trace
*/
private static int maxTraceRecords = 4096;
private AtomicReference<List<ZorkaSubmitter<SymbolicRecord>>> outputs
= new AtomicReference<List<ZorkaSubmitter<SymbolicRecord>>>(new ArrayList<ZorkaSubmitter<SymbolicRecord>>());
/**
* Defines which classes and methods should be traced.
*/
private SpyMatcherSet matcherSet;
/**
* Symbol registry containing names of all symbols tracer knows about.
*/
private SymbolRegistry symbolRegistry;
/**
* If true, methods instrumented by SPY will also be traced by default.
*/
private boolean traceSpyMethods = true;
public static long getMinMethodTime() {
return minMethodTime;
}
public static void setMinMethodTime(long methodTime) {
minMethodTime = methodTime;
}
public static int getMaxTraceRecords() {
return maxTraceRecords;
}
public static void setMaxTraceRecords(int traceSize) {
maxTraceRecords = traceSize;
}
public boolean isTraceSpyMethods() {
return traceSpyMethods;
}
public void setTraceSpyMethods(boolean traceSpyMethods) {
this.traceSpyMethods = traceSpyMethods;
}
/**
* Thread local serving trace builder objects for application threads
*/
private ThreadLocal<TraceBuilder> localHandlers =
new ThreadLocal<TraceBuilder>() {
public TraceBuilder initialValue() {
return new TraceBuilder(Tracer.this, symbolRegistry);
}
};
public Tracer(SpyMatcherSet matcherSet, SymbolRegistry symbolRegistry) {
this.matcherSet = matcherSet;
this.symbolRegistry = symbolRegistry;
}
/**
* Returns trace even handler receiving events from local application thread.
*
* @return trace event handler (trace builder object)
*/
public TraceBuilder getHandler() {
return localHandlers.get();
}
/**
* Adds new matcher that includes (or excludes) classes and method to be traced.
*
* @param matcher spy matcher to be added
*/
public void include(SpyMatcher matcher) {
matcherSet = matcherSet.include(matcher);
}
public SpyMatcherSet clearMatchers() {
SpyMatcherSet ret = matcherSet;
matcherSet = new SpyMatcherSet();
return ret;
}
@Override
public boolean submit(SymbolicRecord record) {
boolean submitted = false;
for (ZorkaSubmitter<SymbolicRecord> output : outputs.get()) {
submitted |= output.submit(record);
}
return submitted;
}
@Override
public synchronized void shutdown() {
List<ZorkaSubmitter<SymbolicRecord>> old = outputs.get();
outputs.set(new ArrayList<ZorkaSubmitter<SymbolicRecord>>());
for (ZorkaSubmitter<SymbolicRecord> output : old) {
if (output instanceof ZorkaService) {
((ZorkaService)output).shutdown();
}
}
if (old.size() > 0) {
ZorkaUtil.sleep(100);
}
}
/**
* Sets output trace event handler tracer will submit completed traces to.
* Note that submit() method of supplied handler is called from application
* threads, so it must be thread safe.
*
* @param output trace event handler
*/
public synchronized void addOutput(ZorkaSubmitter<SymbolicRecord> output) {
List<ZorkaSubmitter<SymbolicRecord>> newOutputs = new ArrayList<ZorkaSubmitter<SymbolicRecord>>();
newOutputs.addAll(outputs.get());
newOutputs.add(output);
outputs.set(newOutputs);
}
public SpyMatcherSet getMatcherSet() {
return matcherSet;
}
public void setMatcherSet(SpyMatcherSet matcherSet) {
this.matcherSet = matcherSet;
}
}
| gpl-3.0 |
tinda/tps-one-simulator | src/test/StationaryMovement.java | 1168 | /*
* Copyright 2008 TKK/ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package test;
import core.Coord;
import movement.MovementModel;
import movement.Path;
/**
* A dummy stationary "movement" model where nodes do not move for testing
* purposes
*/
public class StationaryMovement extends MovementModel {
private Coord loc;
public StationaryMovement(Coord location) {
if (location == null) {
this.loc = new Coord(0, 0);
} else {
this.loc = location;
}
}
/**
* Returns the only location of this movement model
*
* @return the only location of this movement model
*/
@Override
public Coord getInitialLocation() {
return loc;
}
@Override
public boolean isActive() {
return true;
}
/**
* Returns a single coordinate path (using the only possible coordinate)
*
* @return a single coordinate path
*/
@Override
public Path getPath() {
Path p = new Path(0);
p.addWaypoint(loc);
return p;
}
@Override
public double nextPathAvailable() {
return Double.MAX_VALUE; // no new paths available
}
@Override
public StationaryMovement replicate() {
return new StationaryMovement(loc);
}
}
| gpl-3.0 |
acmyonghua/eucalyptus | clc/modules/msgs/src/main/java/com/eucalyptus/ws/handlers/http/NioHttpDecoder.java | 21535 | /*************************************************************************
* Copyright 2009-2012 Eucalyptus Systems, 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; version 3 of the License.
*
* 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/.
*
* Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta
* CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need
* additional information or have any questions.
*
* This file may incorporate work covered under the following copyright
* and permission notice:
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Regents of the University of California
* All rights reserved.
*
* Redistribution and use of this software 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE. USERS OF THIS SOFTWARE ACKNOWLEDGE
* THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE LICENSED MATERIAL,
* COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS SOFTWARE,
* AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING
* IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA,
* SANTA BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY,
* WHICH IN THE REGENTS' DISCRETION MAY INCLUDE, WITHOUT LIMITATION,
* REPLACEMENT OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO
* IDENTIFIED, OR WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT
* NEEDED TO COMPLY WITH ANY SUCH LICENSES OR RIGHTS.
*
* This file may incorporate work covered under the following copyright
* and permission notice:
*
* JBoss, Home of Professional Open Source
*
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @author tags. See the COPYRIGHT.txt in the distribution for a
* full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
************************************************************************/
package com.eucalyptus.ws.handlers.http;
import java.util.List;
import org.apache.log4j.Logger;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.handler.codec.frame.TooLongFrameException;
import org.jboss.netty.handler.codec.http.DefaultHttpChunk;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpMessage;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.jboss.netty.handler.codec.replay.ReplayingDecoder;
import com.eucalyptus.context.Context;
import com.eucalyptus.context.Contexts;
import com.eucalyptus.context.NoSuchContextException;
import com.eucalyptus.http.MappingHttpRequest;
import com.eucalyptus.records.Logs;
import com.eucalyptus.ws.StackConfiguration;
public class NioHttpDecoder extends ReplayingDecoder<NioHttpDecoder.State> {
private final int maxInitialLineLength;
private final int maxHeaderSize;
private final int maxChunkSize;
protected volatile HttpMessage message;
private volatile ChannelBuffer content;
private volatile long chunkSize;
private int headerSize;
protected enum State {
SKIP_CONTROL_CHARS,
READ_INITIAL,
READ_HEADER,
READ_VARIABLE_LENGTH_CONTENT,
READ_VARIABLE_LENGTH_CONTENT_AS_CHUNKS,
READ_FIXED_LENGTH_CONTENT,
READ_FIXED_LENGTH_CONTENT_AS_CHUNKS,
READ_CHUNK_SIZE,
READ_CHUNKED_CONTENT,
READ_CHUNKED_CONTENT_AS_CHUNKS,
READ_CHUNK_DELIMITER,
READ_CHUNK_FOOTER;
}
public NioHttpDecoder( ) {
this( StackConfiguration.HTTP_MAX_INITIAL_LINE_BYTES, StackConfiguration.HTTP_MAX_HEADER_BYTES, StackConfiguration.HTTP_MAX_CHUNK_BYTES );
}
protected NioHttpDecoder( int maxInitialLineLength, int maxHeaderSize, int maxChunkSize ) {
super( State.SKIP_CONTROL_CHARS, true );
if ( maxInitialLineLength <= 0 ) { throw new IllegalArgumentException( "maxInitialLineLength must be a positive integer: " + maxInitialLineLength ); }
if ( maxHeaderSize <= 0 ) { throw new IllegalArgumentException( "maxHeaderSize must be a positive integer: " + maxChunkSize ); }
if ( maxChunkSize < 0 ) { throw new IllegalArgumentException( "maxChunkSize must be a positive integer: " + maxChunkSize ); }
this.maxInitialLineLength = maxInitialLineLength;
this.maxHeaderSize = maxHeaderSize;
this.maxChunkSize = maxChunkSize;
}
@Override
protected Object decode( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, State state ) throws Exception {
switch ( state ) {
case SKIP_CONTROL_CHARS: {
try {
skipControlCharacters( buffer );
checkpoint( State.READ_INITIAL );
} finally {
checkpoint( );
}
}
case READ_INITIAL: {
String[] initialLine = splitInitialLine( HttpUtils.readLine( buffer, maxInitialLineLength ) );
if ( initialLine.length < 3 ) {
checkpoint( State.SKIP_CONTROL_CHARS );
return null;
}
MappingHttpRequest newMessage = new MappingHttpRequest( HttpVersion.valueOf( initialLine[2] ), HttpMethod.valueOf( initialLine[0] ), initialLine[1] );
Contexts.create( newMessage, ctx.getChannel( ) );
message = newMessage;
checkpoint( State.READ_HEADER );
}
case READ_HEADER: {
State nextState = readHeaders( buffer );
checkpoint( nextState );
if ( nextState == State.READ_CHUNK_SIZE ) {
return message;
} else if ( nextState == State.SKIP_CONTROL_CHARS ) {
message.removeHeader( HttpHeaders.Names.CONTENT_LENGTH );
message.removeHeader( HttpHeaders.Names.TRANSFER_ENCODING );
return message;
} else {
long contentLength = message.getContentLength( -1 );
if ( contentLength == 0 || contentLength == -1 && isDecodingRequest( ) ) {
content = ChannelBuffers.EMPTY_BUFFER;
return reset( );
}
switch ( nextState ) {
case READ_FIXED_LENGTH_CONTENT:
if ( contentLength > maxChunkSize ) {
checkpoint( State.READ_FIXED_LENGTH_CONTENT_AS_CHUNKS );
message.addHeader( HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED );
chunkSize = message.getContentLength( -1 );
return message;
}
break;
case READ_VARIABLE_LENGTH_CONTENT:
if ( buffer.readableBytes( ) > maxChunkSize ) {
checkpoint( State.READ_VARIABLE_LENGTH_CONTENT_AS_CHUNKS );
message.addHeader( HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED );
return message;
}
break;
}
}
return null;
}
case READ_VARIABLE_LENGTH_CONTENT: {
if ( content == null ) {
content = ChannelBuffers.dynamicBuffer( channel.getConfig( ).getBufferFactory( ) );
}
// this will cause a replay error until the channel is closed where this
// will read what's left in the buffer
content.writeBytes( buffer.readBytes( buffer.readableBytes( ) ) );
return reset( );
}
case READ_VARIABLE_LENGTH_CONTENT_AS_CHUNKS: {
// Keep reading data as a chunk until the end of connection is reached.
int chunkSize = Math.min( maxChunkSize, buffer.readableBytes( ) );
HttpChunk chunk = new DefaultHttpChunk( buffer.readBytes( chunkSize ) );
if ( !buffer.readable( ) ) {
// Reached to the end of the connection.
reset( );
if ( !chunk.isLast( ) ) {
// Append the last chunk.
return new Object[] { chunk, HttpChunk.LAST_CHUNK };
}
}
return chunk;
}
case READ_FIXED_LENGTH_CONTENT: {
// we have a content-length so we just read the correct number of bytes
readFixedLengthContent( buffer );
return reset( );
}
case READ_FIXED_LENGTH_CONTENT_AS_CHUNKS: {
long chunkSize = this.chunkSize;
HttpChunk chunk;
if ( chunkSize > maxChunkSize ) {
chunk = new DefaultHttpChunk( buffer.readBytes( maxChunkSize ) );
chunkSize -= maxChunkSize;
} else {
assert chunkSize <= Integer.MAX_VALUE;
chunk = new DefaultHttpChunk( buffer.readBytes( ( int ) chunkSize ) );
chunkSize = 0;
}
this.chunkSize = chunkSize;
if ( chunkSize == 0 ) {
// Read all content.
reset( );
if ( !chunk.isLast( ) ) {
// Append the last chunk.
return new Object[] { chunk, HttpChunk.LAST_CHUNK };
}
}
return chunk;
}
/**
* everything else after this point takes care of reading chunked
* content. basically, read chunk size,
* read chunk, read and ignore the CRLF and repeat until 0
*/
case READ_CHUNK_SIZE: {
String line = HttpUtils.readLine( buffer, maxInitialLineLength );
int chunkSize = getChunkSize( line );
this.chunkSize = chunkSize;
if ( chunkSize == 0 ) {
checkpoint( State.READ_CHUNK_FOOTER );
return null;
} else if ( chunkSize > maxChunkSize ) {
// A chunk is too large. Split them into multiple chunks again.
checkpoint( State.READ_CHUNKED_CONTENT_AS_CHUNKS );
} else {
checkpoint( State.READ_CHUNKED_CONTENT );
}
}
case READ_CHUNKED_CONTENT: {
assert chunkSize <= Integer.MAX_VALUE;
HttpChunk chunk = new DefaultHttpChunk( buffer.readBytes( ( int ) chunkSize ) );
checkpoint( State.READ_CHUNK_DELIMITER );
return chunk;
}
case READ_CHUNKED_CONTENT_AS_CHUNKS: {
long chunkSize = this.chunkSize;
HttpChunk chunk;
if ( chunkSize > maxChunkSize ) {
chunk = new DefaultHttpChunk( buffer.readBytes( maxChunkSize ) );
chunkSize -= maxChunkSize;
} else {
assert chunkSize <= Integer.MAX_VALUE;
chunk = new DefaultHttpChunk( buffer.readBytes( ( int ) chunkSize ) );
chunkSize = 0;
}
this.chunkSize = chunkSize;
if ( chunkSize == 0 ) {
// Read all content.
checkpoint( State.READ_CHUNK_DELIMITER );
}
if ( !chunk.isLast( ) ) { return chunk; }
}
case READ_CHUNK_DELIMITER: {
for ( ;; ) {
byte next = buffer.readByte( );
if ( next == HttpUtils.CR ) {
if ( buffer.readByte( ) == HttpUtils.LF ) {
checkpoint( State.READ_CHUNK_SIZE );
return null;
}
} else if ( next == HttpUtils.LF ) {
checkpoint( State.READ_CHUNK_SIZE );
return null;
}
}
}
case READ_CHUNK_FOOTER: {
// Skip the footer; does anyone use it?
try {
if ( !skipLine( buffer ) ) {
if ( maxChunkSize == 0 ) {
// Chunked encoding disabled.
return reset( );
} else {
reset( );
// The last chunk, which is empty
return HttpChunk.LAST_CHUNK;
}
}
} finally {
checkpoint( );
}
return null;
}
default: {
throw new Error( "Shouldn't reach here." );
}
}
}
@Override
public void channelClosed( final ChannelHandlerContext ctx,
final ChannelStateEvent channelStateEvent ) throws Exception {
try {
final Channel channel = ctx.getChannel();
if ( channel != null ) {
final Context context = Contexts.lookup( channel );
Contexts.clear( context );
}
} catch ( NoSuchContextException e ) {
// nothing to clean up
}
super.channelClosed( ctx, channelStateEvent );
}
private boolean isDecodingRequest( ) {
return true;
}
protected boolean isContentAlwaysEmpty( HttpMessage msg ) {
if ( msg instanceof HttpResponse ) {
HttpResponse res = ( HttpResponse ) msg;
int code = res.getStatus( ).getCode( );
if ( code < 200 ) { return true; }
switch ( code ) {
case 204:
case 205:
case 304:
return true;
}
}
return false;
}
private Object reset( ) {
HttpMessage message = this.message;
ChannelBuffer content = this.content;
if ( content != null ) {
message.setContent( content );
this.content = null;
}
this.message = null;
checkpoint( State.SKIP_CONTROL_CHARS );
return message;
}
private void skipControlCharacters( ChannelBuffer buffer ) {
for ( ;; ) {
char c = ( char ) buffer.readUnsignedByte( );
if ( !Character.isISOControl( c ) && !Character.isWhitespace( c ) ) {
buffer.readerIndex( buffer.readerIndex( ) - 1 );
break;
}
}
}
private void readFixedLengthContent( ChannelBuffer buffer ) {
long length = message.getContentLength( -1 );
assert length <= Integer.MAX_VALUE;
if ( content == null ) {
content = buffer.readBytes( ( int ) length );
} else {
content.writeBytes( buffer.readBytes( ( int ) length ) );
}
}
private State readHeaders( ChannelBuffer buffer ) throws TooLongFrameException {
headerSize = 0;
final HttpMessage message = this.message;
String line = readHeader( buffer );
String lastHeader = null;
if ( line.length( ) != 0 ) {
message.clearHeaders( );
do {
char firstChar = line.charAt( 0 );
if ( lastHeader != null && ( firstChar == ' ' || firstChar == '\t' ) ) {
List<String> current = message.getHeaders( lastHeader );
int lastPos = current.size( ) - 1;
String newString = current.get( lastPos ) + line.trim( );
current.set( lastPos, newString );
} else {
String[] header = splitHeader( line );
message.addHeader( header[0], header[1] );
lastHeader = header[0];
}
line = readHeader( buffer );
} while ( line.length( ) != 0 );
}
State nextState;
if ( isContentAlwaysEmpty( message ) ) {
nextState = State.SKIP_CONTROL_CHARS;
} else if ( message.isChunked( ) ) {
nextState = State.READ_CHUNK_SIZE;
} else if ( message.getContentLength( -1 ) >= 0 ) {
nextState = State.READ_FIXED_LENGTH_CONTENT;
} else {
nextState = State.READ_VARIABLE_LENGTH_CONTENT;
}
return nextState;
}
private String readHeader( ChannelBuffer buffer ) throws TooLongFrameException {
StringBuilder sb = new StringBuilder( 64 );
int headerSize = this.headerSize;
loop: for ( ;; ) {
char nextByte = ( char ) buffer.readByte( );
headerSize++;
switch ( nextByte ) {
case HttpUtils.CR:
nextByte = ( char ) buffer.readByte( );
headerSize++;
if ( nextByte == HttpUtils.LF ) {
break loop;
}
break;
case HttpUtils.LF:
break loop;
}
// Abort decoding if the header part is too large.
if ( headerSize >= maxHeaderSize ) { throw new TooLongFrameException( "HTTP header is larger than " + maxHeaderSize + " bytes." );
}
sb.append( nextByte );
}
this.headerSize = headerSize;
return sb.toString( );
}
private int getChunkSize( String hex ) {
final Logger logger = Logs.exhaust();
if ( logger.isTraceEnabled() )
logger.trace( "Chunk Size Hex to parse:" + hex );
hex = hex.replaceAll( "\\W", "" ).trim( );
for ( int i = 0; i < hex.length( ); i++ ) {
char c = hex.charAt( i );
if ( c == ';' || Character.isWhitespace( c ) || Character.isISOControl( c ) ) {
hex = hex.substring( 0, i );
break;
}
}
if ( logger.isTraceEnabled() )
logger.trace( "Chunk Size in Hex:" + hex );
return Integer.parseInt( hex, 16 );
}
/**
* Returns {@code true} if only if the skipped line was not empty.
* Please note that an empty line is also skipped, while {@code} false is
* returned.
*/
private boolean skipLine( ChannelBuffer buffer ) {
int lineLength = 0;
while ( true ) {
byte nextByte = buffer.readByte( );
if ( nextByte == HttpUtils.CR ) {
nextByte = buffer.readByte( );
if ( nextByte == HttpUtils.LF ) { return lineLength != 0; }
} else if ( nextByte == HttpUtils.LF ) {
return lineLength != 0;
} else if ( !Character.isWhitespace( ( char ) nextByte ) ) {
lineLength++;
}
}
}
private String[] splitInitialLine( String sb ) {
int aStart;
int aEnd;
int bStart;
int bEnd;
int cStart;
int cEnd;
aStart = findNonWhitespace( sb, 0 );
aEnd = findWhitespace( sb, aStart );
bStart = findNonWhitespace( sb, aEnd );
bEnd = findWhitespace( sb, bStart );
cStart = findNonWhitespace( sb, bEnd );
cEnd = findEndOfString( sb );
return new String[] { sb.substring( aStart, aEnd ), sb.substring( bStart, bEnd ), sb.substring( cStart, cEnd ) };
}
private String[] splitHeader( String sb ) {
int nameStart;
int nameEnd;
int colonEnd;
int valueStart;
int valueEnd;
nameStart = findNonWhitespace( sb, 0 );
for ( nameEnd = nameStart; nameEnd < sb.length( ); nameEnd++ ) {
char ch = sb.charAt( nameEnd );
if ( ch == ':' || Character.isWhitespace( ch ) ) {
break;
}
}
for ( colonEnd = nameEnd; colonEnd < sb.length( ); colonEnd++ ) {
if ( sb.charAt( colonEnd ) == ':' ) {
colonEnd++;
break;
}
}
valueStart = findNonWhitespace( sb, colonEnd );
valueEnd = findEndOfString( sb );
valueStart = valueStart > valueEnd ? valueEnd : valueStart;
return new String[] { sb.substring( nameStart, nameEnd ), sb.substring( valueStart, valueEnd ) };
}
private int findNonWhitespace( String sb, int offset ) {
int result;
for ( result = offset; result < sb.length( ); result++ ) {
if ( !Character.isWhitespace( sb.charAt( result ) ) ) {
break;
}
}
return result;
}
private int findWhitespace( String sb, int offset ) {
int result;
for ( result = offset; result < sb.length( ); result++ ) {
if ( Character.isWhitespace( sb.charAt( result ) ) ) {
break;
}
}
return result;
}
private int findEndOfString( String sb ) {
int result;
for ( result = sb.length( ); result > 0; result-- ) {
if ( !Character.isWhitespace( sb.charAt( result - 1 ) ) ) {
break;
}
}
return result;
}
}
| gpl-3.0 |
pemulis/Zones | src/org/anhonesteffort/polygons/map/GoogleGeometryFactory.java | 3214 | package org.anhonesteffort.polygons.map;
import java.util.ArrayList;
import org.anhonesteffort.polygons.geometry.TaggedPoint;
import org.anhonesteffort.polygons.geometry.TaggedPolygon;
import android.location.Location;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolygonOptions;
public class GoogleGeometryFactory {
public static MarkerOptions buildMarkerOptions(TaggedPoint point) {
MarkerOptions marker = new MarkerOptions();
LatLng position = new LatLng(point.getY(), point.getX());
marker.position(position);
marker.snippet(Integer.toString(point.getID()));
return marker;
}
public static LatLng buildLatLng(TaggedPoint point) {
return new LatLng(point.getY(), point.getX());
}
public static PolygonOptions buildPolygonOptions(TaggedPolygon<TaggedPoint> polygonRecord) {
PolygonOptions polygonOptions = new PolygonOptions();
for(TaggedPoint point : polygonRecord.getPoints())
polygonOptions.add(buildLatLng(point));
return polygonOptions;
}
public static TaggedPoint buildTaggedPoint(LatLng point) {
TaggedPoint newPoint = new TaggedPoint(-1, point.longitude, point.latitude);
return newPoint;
}
public static TaggedPoint buildTaggedPoint(MarkerOptions marker) {
TaggedPoint newPoint = new TaggedPoint(Integer.parseInt(marker.getSnippet()),
marker.getPosition().longitude,
marker.getPosition().latitude);
return newPoint;
}
public static TaggedPoint buildTaggedPoint(Marker marker) {
TaggedPoint newPoint = new TaggedPoint(Integer.parseInt(marker.getSnippet()),
marker.getPosition().longitude,
marker.getPosition().latitude);
return newPoint;
}
public static TaggedPoint buildTaggedPoint(Location point) {
TaggedPoint newPoint = new TaggedPoint(-1, point.getLongitude(), point.getLatitude());
return newPoint;
}
public static TaggedPolygon<TaggedPoint> buildTaggedPolygon(PolygonOptions polygonOptions) {
TaggedPolygon<TaggedPoint> polygon = new TaggedPolygon<TaggedPoint>(-1, "", new ArrayList<TaggedPoint>());
for(LatLng point : polygonOptions.getPoints()) {
polygon.getPoints().add(buildTaggedPoint(point));
}
return polygon;
}
public static TaggedPolygon<TaggedPoint> buildTaggedPolygon(LatLngBounds bounds) {
TaggedPolygon<TaggedPoint> polygon = new TaggedPolygon<TaggedPoint>(-1, "", new ArrayList<TaggedPoint>());
polygon.getPoints().add(buildTaggedPoint(bounds.northeast));
polygon.getPoints().add(buildTaggedPoint(new LatLng(bounds.southwest.latitude, bounds.northeast.longitude)));
polygon.getPoints().add(buildTaggedPoint(bounds.southwest));
polygon.getPoints().add(buildTaggedPoint(new LatLng(bounds.northeast.latitude, bounds.southwest.longitude)));
return polygon;
}
}
| gpl-3.0 |
TeamUbercube/ubercube | src/main/java/fr/veridiangames/client/main/Timer.java | 1055 | /*
* Copyright (C) 2016 Team Ubercube
*
* This file is part of Ubercube.
*
* Ubercube 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.
*
* Ubercube 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 Ubercube. If not, see http://www.gnu.org/licenses/.
*/
package fr.veridiangames.client.main;
/**
* Created by Marccspro on 9 f�vr. 2016.
*/
public class Timer
{
long startTime;
public Timer()
{
reset();
}
public void reset()
{
startTime = System.nanoTime();
}
public double getElapsed()
{
return System.nanoTime() - startTime;
}
} | gpl-3.0 |
gstreamer-java/gir2java | generated-src/generated/gstreamer10/gst/GstPresetInterface.java | 1249 |
package generated.gstreamer10.gst;
import generated.gobject20.gobject.GTypeInterface;
import org.bridj.BridJ;
import org.bridj.Pointer;
import org.bridj.StructObject;
import org.bridj.ann.Field;
import org.bridj.ann.Library;
@Library("gstreamer-1.0")
public class GstPresetInterface
extends StructObject
{
static {
BridJ.register();
}
public GstPresetInterface() {
super();
}
public GstPresetInterface(Pointer pointer) {
super(pointer);
}
@Field(0)
public GTypeInterface gstpresetinterface_field_parent() {
return this.io.getNativeObjectField(this, 0);
}
@Field(0)
public GstPresetInterface gstpresetinterface_field_parent(GTypeInterface gstpresetinterface_field_parent) {
this.io.setNativeObjectField(this, 0, gstpresetinterface_field_parent);
return this;
}
@Field(1)
private Pointer gstpresetinterface_field__gst_reserved() {
return this.io.getPointerField(this, 1);
}
@Field(1)
private GstPresetInterface gstpresetinterface_field__gst_reserved(Pointer gstpresetinterface_field__gst_reserved) {
this.io.setPointerField(this, 1, gstpresetinterface_field__gst_reserved);
return this;
}
}
| gpl-3.0 |
craftercms/test-suite | src/test/java/org/craftercms/studio/test/utils/UIElementsPropertiesManager.java | 1516 | /*
* Copyright (C) 2007-2019 Crafter Software Corporation. All Rights Reserved.
*
* 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 org.craftercms.studio.test.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class UIElementsPropertiesManager {
Properties sharedUIElementsLocators;
public UIElementsPropertiesManager(String filePath) {
sharedUIElementsLocators = new Properties();
try {
sharedUIElementsLocators.load(new FileInputStream(filePath));
} catch (IOException e) {
e.printStackTrace();
}
}
public Properties getSharedUIElementsLocators() {
return sharedUIElementsLocators;
}
public void setSharedUIElementsLocators(Properties sharedUIElementsLocators) {
this.sharedUIElementsLocators = sharedUIElementsLocators;
}
public Properties getSharedDataOfExecutionLocators() {
return sharedUIElementsLocators;
}
}
| gpl-3.0 |
Gnafu/OpenSDI-Manager2 | src/modules/filemanager/src/main/java/it/geosolutions/opensdi2/ftp/user/BaseAuthoritiesProvider.java | 923 | package it.geosolutions.opensdi2.ftp.user;
import java.util.List;
import org.apache.ftpserver.ftplet.Authority;
/**
* Base Implementation of authorities provider that can
* keep static authorities valid for all the users.
* @author Lorenzo Natali, GeoSolutions
*
*/
public class BaseAuthoritiesProvider implements AuthoritiesProvider {
List<Authority> authorities;
String homeDirectory;
public List<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(List<Authority> authorities) {
this.authorities = authorities;
}
public String getHomeDirectory() {
return homeDirectory;
}
public void setHomeDirectory(String homeDirectory) {
this.homeDirectory = homeDirectory;
}
@Override
public List<Authority> getAuthorities(Object userName) {
return authorities;
}
@Override
public String getHomeDirectory(Object userName) {
return homeDirectory;
}
}
| gpl-3.0 |
YinYanfei/CadalWorkspace | jcdl_searchLucene/src/cn/cadal/entity/Cpainting.java | 2822 | package cn.cadal.entity;
// Generated 2006-4-10 20:48:27 by Hibernate Tools 3.1.0 beta1JBIDERC2
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
@Table(name = "PaintingInfo")
public class Cpainting implements java.io.Serializable {
// Fields
private Integer paintingNO;
private String paintingName;
private String author;
private String location;
private String appearance;
private String description;
private String filepath;
private Integer filesize;
// Constructors
/** default constructor */
public Cpainting() {
}
/** minimal constructor */
public Cpainting(Integer paintingNO) {
this.paintingNO = paintingNO;
}
/** full constructor */
public Cpainting(Integer paintingNO, String paintingName, String author,
String location, String appearance, String description,
String filepath, Integer filesize) {
this.paintingNO = paintingNO;
this.paintingName = paintingName;
this.author = author;
this.location = location;
this.appearance = appearance;
this.description = description;
this.filepath = filepath;
this.filesize = filesize;
}
// Property accessors
@Id
@Column (name="sID")
public Integer getPaintingNO() {
return this.paintingNO;
}
public void setPaintingNO(Integer paintingNO) {
this.paintingNO = paintingNO;
}
@Column (name="PName", length=100)
public String getPaintingName() {
return this.paintingName;
}
public void setPaintingName(String paintingName) {
this.paintingName = paintingName;
}
@Column (name="Author", length=3000)
public String getAuthor() {
return this.author;
}
public void setAuthor(String author) {
this.author = author;
}
@Column (name="Location", length=150)
public String getLocation() {
return this.location;
}
public void setLocation(String location) {
this.location = location;
}
@Column (name="SpeSize", length=3000)
public String getAppearance() {
return this.appearance;
}
public void setAppearance(String appearance) {
this.appearance = appearance;
}
@Column (name="Description", length=300)
@Lob
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
@Column (name="FilePath", length=150)
public String getFilepath() {
return this.filepath;
}
public void setFilepath(String filepath) {
this.filepath = filepath;
}
@Column (name="FileSize")
public Integer getFilesize() {
return this.filesize;
}
public void setFilesize(Integer filesize) {
this.filesize = filesize;
}
}
| gpl-3.0 |
MrKickkiller/BuildcraftAdditions2 | src/main/java/buildcraftAdditions/blocks/BlockKineticEnergyBufferTier1.java | 4475 | package buildcraftAdditions.blocks;
import java.util.List;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.IIcon;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.Explosion;
import net.minecraft.world.World;
import buildcraftAdditions.BuildcraftAdditions;
import buildcraftAdditions.reference.Variables;
import buildcraftAdditions.tileEntities.Bases.TileKineticEnergyBufferBase;
import buildcraftAdditions.tileEntities.TileKineticEnergyBufferTier1;
import buildcraftAdditions.utils.EnumPriority;
import buildcraftAdditions.utils.EnumSideStatus;
import buildcraftAdditions.utils.RenderUtils;
import buildcraftAdditions.utils.SideConfiguration;
/**
* Copyright (c) 2014, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Buildcraft Additions is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class BlockKineticEnergyBufferTier1 extends BlockContainer {
public IIcon icons[];
public BlockKineticEnergyBufferTier1() {
super(Material.iron);
this.setResistance(2f);
this.setHardness(2f);
this.setHarvestLevel(null, 0);
}
@Override
public void registerBlockIcons(IIconRegister register) {
icons = new IIcon[10];
for (int teller = 0; teller < 9; teller++) {
icons[teller] = RenderUtils.registerIcon(register, "kineticEnergyBuffer" + teller);
}
icons[9] = RenderUtils.registerIcon(register, "kineticEnergyBufferCreative");
}
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int meta, float hitX, float hitY, float hitZ) {
if (world.getTileEntity(x, y, z) instanceof TileKineticEnergyBufferBase)
player.openGui(BuildcraftAdditions.instance, Variables.Gui.KEB, world, x, y, z);
return true;
}
@Override
public IIcon getIcon(int side, int meta) {
if (meta > 9)
return icons[8];
return icons[meta];
}
@Override
public void onBlockDestroyedByExplosion(World world, int x, int y, int z, Explosion explosion) {
TileEntity tileEntity = world.getTileEntity(x, y, z);
if (tileEntity instanceof TileKineticEnergyBufferBase)
((TileKineticEnergyBufferBase) tileEntity).byeBye();
}
@Override
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entity, ItemStack stack) {
if (stack.stackTagCompound != null) {
stack.stackTagCompound.setInteger("x", x);
stack.stackTagCompound.setInteger("y", y);
stack.stackTagCompound.setInteger("z", z);
world.getTileEntity(x, y, z).readFromNBT(stack.stackTagCompound);
}
if (entity instanceof EntityPlayer) {
TileEntity tileEntity = world.getTileEntity(x, y, z);
if (tileEntity instanceof TileKineticEnergyBufferBase)
((TileKineticEnergyBufferBase) tileEntity).setOwner(((EntityPlayer) entity).getDisplayName());
}
}
@Override
public TileEntity createNewTileEntity(World world, int meta) {
return new TileKineticEnergyBufferTier1();
}
public ItemStack createCreativeKEB() {
ItemStack stack = new ItemStack(this, 1, 9);
stack.stackTagCompound = new NBTTagCompound();
stack.stackTagCompound.setBoolean("creative", true);
stack.stackTagCompound.setInteger("energy", 3000000);
stack.stackTagCompound.setInteger("maxEnergy", 3000000);
stack.stackTagCompound.setInteger("maxInput", 30000);
stack.stackTagCompound.setInteger("maxOutput", 30000);
SideConfiguration configuration = new SideConfiguration();
configuration.setAllStatus(EnumSideStatus.OUTPUT);
configuration.setAllPriority(EnumPriority.NORMAL);
configuration.writeToNBT(stack.stackTagCompound);
return stack;
}
@Override
public void getSubBlocks(Item item, CreativeTabs tab, List list) {
super.getSubBlocks(item, tab, list);
list.add(createCreativeKEB());
}
@Override
public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) {
if (world.getBlockMetadata(x, y, z) == 9) {
return createCreativeKEB();
}
return super.getPickBlock(target, world, x, y, z);
}
}
| gpl-3.0 |
Severed-Infinity/technium | build/tmp/recompileMc/sources/net/minecraftforge/client/IClientCommand.java | 1411 | /*
* Minecraft Forge
* Copyright (c) 2016.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation version 2.1
* of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.client;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
/**
* Client-side commands can implement this interface to allow additional control over when the command may be used.
*/
public interface IClientCommand extends ICommand
{
/**
* Determine whether this command can be used without the "/" prefix. By default this is true.
* @param sender the command sender
* @param message the message, without potential prefix
* @return true to allow the usage of this command without the prefix
*/
boolean allowUsageWithoutPrefix(ICommandSender sender, String message);
} | gpl-3.0 |
gstreamer-java/gir2java | generated-src/generated/gio20/gio/GApplicationCommandLinePrivate.java | 114 |
package generated.gio20.gio;
/**
* Opaque type
*
*/
public interface GApplicationCommandLinePrivate {
}
| gpl-3.0 |
drugis/addis | application/src/test/java/org/drugis/addis/entities/DoseUnitTest.java | 4536 | /*
* This file is part of ADDIS (Aggregate Data Drug Information System).
* ADDIS is distributed from http://drugis.org/.
* Copyright © 2009 Gert van Valkenhoef, Tommi Tervonen.
* Copyright © 2010 Gert van Valkenhoef, Tommi Tervonen, Tijs Zwinkels,
* Maarten Jacobs, Hanno Koeslag, Florin Schimbinschi, Ahmad Kamal, Daniel
* Reid.
* Copyright © 2011 Gert van Valkenhoef, Ahmad Kamal, Daniel Reid, Florin
* Schimbinschi.
* Copyright © 2012 Gert van Valkenhoef, Daniel Reid, Joël Kuiper, Wouter
* Reckman.
* Copyright © 2013 Gert van Valkenhoef, Joël Kuiper.
*
* 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 org.drugis.addis.entities;
import static org.drugis.addis.entities.AssertEntityEquals.assertEntityEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import java.util.Collections;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import org.apache.commons.math3.util.Precision;
import org.drugis.addis.ExampleData;
import org.drugis.addis.util.EntityUtil;
import org.drugis.common.JUnitUtil;
import org.junit.Before;
import org.junit.Test;
public class DoseUnitTest {
private DoseUnit d_mgDay;
private DoseUnit d_kgHr;
private Unit d_gram;
private Unit d_meter;
@Before
public void setUp() {
d_gram = new Unit("gram", "g");
d_meter = new Unit("meter", "m");
d_mgDay = DoseUnit.createMilliGramsPerDay().clone();
d_kgHr = ExampleData.KILOGRAMS_PER_HOUR.clone();
}
@Test
public void testEquals() {
assertFalse(d_mgDay.equals(d_kgHr));
assertEntityEquals(d_mgDay, d_mgDay);
DoseUnit du = new DoseUnit(new Unit("gram", "gg"), ScaleModifier.MILLI, EntityUtil.createDuration("P1D"));
DoseUnit du2 = new DoseUnit(new Unit("gram", "gg"), ScaleModifier.MILLI, EntityUtil.createDuration("P1D"));
assertEntityEquals(du, du2);
assertEquals(d_mgDay, du);
assertFalse(d_mgDay.deepEquals(du));
}
@Test
public void testEvents() {
JUnitUtil.testSetter(d_mgDay, DoseUnit.PROPERTY_UNIT, d_gram, d_meter);
JUnitUtil.testSetter(d_mgDay, DoseUnit.PROPERTY_SCALE_MODIFIER, ScaleModifier.MILLI, ScaleModifier.KILO);
JUnitUtil.testSetter(d_mgDay, DoseUnit.PROPERTY_PER_TIME, EntityUtil.createDuration("P1D"), EntityUtil.createDuration("PT1H"));
}
@Test
public void testClone() throws DatatypeConfigurationException {
DoseUnit cloned = d_mgDay.clone();
assertEntityEquals(d_mgDay, cloned);
assertNotSame(d_mgDay, cloned);
cloned.setScaleModifier(ScaleModifier.KILO);
JUnitUtil.assertNotEquals(d_mgDay.getScaleModifier(), cloned.getScaleModifier());
cloned.setScaleModifier(ScaleModifier.MILLI);
assertEquals(d_mgDay.getScaleModifier(), cloned.getScaleModifier());
cloned.setUnit(new Unit("nonsense", "ns"));
JUnitUtil.assertNotEquals(d_mgDay.getUnit(), cloned.getUnit());
cloned.setUnit(d_mgDay.getUnit());
assertEquals(d_mgDay.getUnit(), cloned.getUnit());
cloned.setPerTime(DatatypeFactory.newInstance().newDuration("P2D"));
JUnitUtil.assertNotEquals(d_mgDay.getPerTime(), cloned.getPerTime());
cloned.setPerTime(d_mgDay.getPerTime());
assertEquals(d_mgDay.getPerTime(), cloned.getPerTime());
}
@Test
public void testConvert() {
assertEquals(0.0001, DoseUnit.convert(2400, DoseUnit.createMilliGramsPerDay(), ExampleData.KILOGRAMS_PER_HOUR), Precision.EPSILON);
DoseUnit gHour = new DoseUnit(new Unit("gram", "g"), ScaleModifier.UNIT, EntityUtil.createDuration("PT1H"));
assertEquals(240000, DoseUnit.convert(10, gHour, DoseUnit.createMilliGramsPerDay()), Precision.EPSILON);
}
@Test
public void testDependencies() {
assertEquals(Collections.singleton(d_gram), d_mgDay.getDependencies());
assertEquals(Collections.singleton(d_gram), d_kgHr.getDependencies());
d_mgDay.setUnit(d_meter);
assertEquals(Collections.singleton(d_meter), d_mgDay.getDependencies());
}
}
| gpl-3.0 |
wangwl/SOAPgaeaDevelopment4.0 | src/main/java/org/bgi/flexlab/gaea/tools/mapreduce/realigner/FixmateMapper.java | 3173 | /*******************************************************************************
* Copyright (c) 2017, BGI-Shenzhen
*
* 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 org.bgi.flexlab.gaea.tools.mapreduce.realigner;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMRecord;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.bgi.flexlab.gaea.data.mapreduce.input.header.SamHdfsFileHeader;
import org.bgi.flexlab.gaea.data.mapreduce.writable.SamRecordWritable;
import org.bgi.flexlab.gaea.data.structure.bam.GaeaSamRecord;
import org.bgi.flexlab.gaea.framework.tools.mapreduce.PairEndAggregatorMapper;
import org.bgi.flexlab.gaea.tools.recalibrator.report.RecalibratorReport;
public class FixmateMapper extends PairEndAggregatorMapper {
private final String DefaultReadGroup = "UK";
private String RG;
private SAMFileHeader header = null;
private Text readID = new Text();
private RealignerExtendOptions option = new RealignerExtendOptions();
private RecalibratorReport report = null;
private SamRecordWritable writable = new SamRecordWritable();
@Override
public void setup(Context context) {
Configuration conf = context.getConfiguration();
header = SamHdfsFileHeader.getHeader(conf);
option.getOptionsFromHadoopConf(conf);
if (option.isRecalibration()) {
String input = conf.get(Realigner.RECALIBRATOR_REPORT_TABLE_NAME);
if (input == null)
throw new RuntimeException("bqsr report table is null!!!");
RecalibratorOptions bqsrOption = option.getBqsrOptions();
report = new RecalibratorReport(input, header, 0,
bqsrOption.PRESERVE_QSCORES_LESS_THAN);
}
}
protected Writable getKey(Writable keyin, Writable valuein) {
if(!option.isRealignment())
return NullWritable.get();
SAMRecord record = ((SamRecordWritable) valuein).get();
GaeaSamRecord sam = new GaeaSamRecord(header, record);
RG = (String) sam.getAttribute("RG");
if (RG == null)
RG = DefaultReadGroup;
readID.set(RG + ":" + sam.getReadName());
return readID;
}
protected Writable getValue(Writable value) {
if (!option.isRecalibration())
return value;
if (value instanceof SamRecordWritable) {
SamRecordWritable temp = (SamRecordWritable) value;
GaeaSamRecord sam = new GaeaSamRecord(header, temp.get());
report.readRecalibrator(sam);
writable.set(sam);
return writable;
}
return value;
}
}
| gpl-3.0 |
obiba/mica2 | mica-core/src/main/java/org/obiba/mica/core/domain/Membership.java | 977 | /*
* Copyright (c) 2018 OBiBa. 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.mica.core.domain;
import java.io.Serializable;
public class Membership implements Serializable {
public final static String INVESTIGATOR = "investigator";
public final static String CONTACT = "contact";
private Person person;
private String role;
public Membership() {
}
public Membership(Person person, String role) {
this.person = person;
this.role = role;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
| gpl-3.0 |
kazoompa/opal | opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/magma/importvariables/TableCompareVariablePanel.java | 2931 | /*
* Copyright (c) 2021 OBiBa. 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.opal.web.gwt.app.client.magma.importvariables;
import org.obiba.opal.web.gwt.app.client.i18n.Translations;
import org.obiba.opal.web.gwt.app.client.magma.AttributesTable;
import org.obiba.opal.web.gwt.app.client.magma.CategoriesTable;
import org.obiba.opal.web.gwt.app.client.ui.NavTabsPanel;
import org.obiba.opal.web.gwt.app.client.ui.PropertiesTable;
import org.obiba.opal.web.gwt.app.client.ui.Table;
import org.obiba.opal.web.model.client.magma.VariableDto;
import com.github.gwtbootstrap.client.ui.SimplePager;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Panel;
/**
*
*/
public class TableCompareVariablePanel extends FlowPanel {
private static final Translations translations = GWT.create(Translations.class);
private final VariableDto variableDto;
public TableCompareVariablePanel(VariableDto variableDto) {
this.variableDto = variableDto;
add(initProperties());
add(initTabs());
}
private PropertiesTable initProperties() {
PropertiesTable properties = new PropertiesTable();
properties.setKeyStyleNames("span2");
properties.setValueStyleNames("span8");
properties.addProperty(translations.entityTypeLabel(), variableDto.getEntityType());
properties.addProperty(translations.referencedEntityTypeLabel(), variableDto.getReferencedEntityType(), 1);
properties.addProperty(translations.valueTypeLabel(), variableDto.getValueType());
properties.addProperty(translations.mimeTypeLabel(), variableDto.getMimeType(), 1);
properties.addProperty(translations.repeatableLabel(),
variableDto.getIsRepeatable() ? translations.yesLabel() : translations.noLabel());
properties.addProperty(translations.occurrenceGroupLabel(), variableDto.getOccurrenceGroup(), 1);
properties.addProperty(translations.unitLabel(), variableDto.getUnit(), 0, 2);
return properties;
}
private NavTabsPanel initTabs() {
NavTabsPanel tabs = new NavTabsPanel();
tabs.addStyleName("top-margin");
tabs.add(initTablePanel(new CategoriesTable(variableDto)), translations.categoriesLabel());
tabs.add(initTablePanel(new AttributesTable(variableDto)), translations.attributesLabel());
return tabs;
}
private Panel initTablePanel(Table<?> table) {
FlowPanel panel = new FlowPanel();
SimplePager pager = new SimplePager();
pager.setDisplay(table);
pager.addStyleName("pull-right");
panel.add(pager);
table.addStyleName("pull-left");
table.setWidth("100%");
panel.add(table);
return panel;
}
}
| gpl-3.0 |
Shappiro/GEOFRAME | PROJECTS/oms3.proj.richards1d/src/JAVA/parallelcolt-code/test/cern/colt/matrix/tdouble/algo/solver/DoubleIRDiagonalTest.java | 450 | package cern.colt.matrix.tdouble.algo.solver;
import cern.colt.matrix.tdouble.algo.solver.preconditioner.DoubleDiagonal;
/**
* Test of DoubleIR with diagonal preconditioner
*/
public class DoubleIRDiagonalTest extends DoubleGMRESTest {
public DoubleIRDiagonalTest(String arg0) {
super(arg0);
}
protected void createSolver() throws Exception {
super.createSolver();
M = new DoubleDiagonal(A.rows());
}
}
| gpl-3.0 |
Belxjander/Bread | src/main/Constants.java | 943 | package main;
import java.text.DecimalFormat;
import math.geom2d.Point2D;
import math.geom3d.Point3D;
import math.geom3d.Vector3D;
public class Constants {
static public final Point3D farPoint = new Point3D(0,0,1e9);
static public final Point2D far2D = new Point2D(0,1e9);
static public final Point3D origin = new Point3D(0,0,0);
static public final Vector3D xplus = new Vector3D(1,0,0);
static public final Vector3D xminus = new Vector3D(-1,0,0);
static public final Vector3D yplus = new Vector3D(0,1,0);
static public final Vector3D yminus = new Vector3D(0,-1,0);
static public final Vector3D zplus = new Vector3D(0,0,1);
static public final Vector3D zminus = new Vector3D(0,0,-1);
static public final double tol = 1e-4;
static public DecimalFormat ext = new DecimalFormat("#.#####"); //Extrusion
static public DecimalFormat xyz = new DecimalFormat("#.###"); //Position
static public Vector3D zero = new Vector3D(0,0,0);
}
| gpl-3.0 |
Noterik/lou2 | src/org/springfield/lou/application/components/types/external/ExternalSubscriberManager.java | 3814 | /*
* ExternalSubscriberManager.java
*
* Copyright (c) 2012 Noterik B.V.
*
* This file is part of Lou, related to the Noterik Springfield project.
*
* Lou 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.
*
* Lou 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 Lou. If not, see <http://www.gnu.org/licenses/>.
*/
package org.springfield.lou.application.components.types.external;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.springfield.lou.application.Html5Application;
import org.springfield.lou.application.components.BasicComponent;
/**
* ExternalSubscriberManager
*
* @author Daniel Ockeloen
* @copyright Copyright: Noterik B.V. 2012
* @package org.springfield.lou.application.components.types.external
*
*/
public class ExternalSubscriberManager {
private HashMap<String, ExternalSubscriber> subscribtions;
private Html5Application application;
private String component;
public ExternalSubscriberManager(Html5Application application, String component){
this.subscribtions = new HashMap<String, ExternalSubscriber>();
this.application = application;
this.component = component;
}
public void addSubsctiption(HashMap<String, String[]> properties){
System.out.println("adding external subscriber");
String url = properties.get("subscribe")[0];
List<String> events = Arrays.asList(properties.get("events")[0].split(","));
ExternalSubscriber es = null;
if(properties.containsKey("class")){
Object o;
try {
String classname = "org.springfield.lou.application.components.types.external."+properties.get("class")[0];
o = Class.forName(classname).getConstructor(Html5Application.class, String.class, String.class, List.class).newInstance(application, url, component, events);
es = (ExternalSubscriber)o;
((BasicComponent)this.application.getComponentManager().getComponent(component)).addObserver(es);
} catch (Exception e) {
e.printStackTrace();
}
}
else{
es = new ExternalSubscriber(application, url, component, events);
((BasicComponent)this.application.getComponentManager().getComponent(component)).addObserver(es);
}
if(this.subscribtions.containsKey(url))
((BasicComponent)this.application.getComponentManager().getComponent(this.subscribtions.get(url).getSubscribedComponentName())).deleteObserver(this.getExternalSubscriber(url));
this.subscribtions.put(url, es);
}
public void addSubsctiption(String url, List<String> events){
System.out.println("adding external subscriber" + url);
if(this.subscribtions.containsKey(url))
((BasicComponent)this.application.getComponentManager().getComponent(this.subscribtions.get(url).getSubscribedComponentName())).deleteObserver(this.getExternalSubscriber(url));
this.subscribtions.put(url, new ExternalSubscriber(application, url, component, events));
}
public void addSubscription(ExternalSubscriber subscriber){
this.subscribtions.put(subscriber.getUrl(), subscriber);
((BasicComponent)this.application.getComponentManager().getComponent(component)).addObserver(subscriber);
}
public ExternalSubscriber getExternalSubscriber(String name){
return this.subscribtions.get(name);
}
public void remove(String name){
this.subscribtions.remove(name);
}
public HashMap<String, ExternalSubscriber> getMap(){
return this.subscribtions;
}
}
| gpl-3.0 |
ther12k/android-client | phone/src/com/voiceblue/phone/widgets/contactbadge/OverlayedImageView.java | 1905 | /**
* Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
* This file is part of CSipSimple.
*
* CSipSimple 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.
* If you own a pjsip commercial license you can also redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License
* as an android library.
*
* CSipSimple 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 CSipSimple. If not, see <http://www.gnu.org/licenses/>.
*/
package com.voiceblue.phone.widgets.contactbadge;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.ImageView;
public class OverlayedImageView extends ImageView {
private QuickContactBadge topBadge;
public OverlayedImageView(Context context) {
this(context, null, 0, null);
}
public OverlayedImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0, null);
}
public OverlayedImageView(Context context, AttributeSet attrs, int defStyle) {
this(context, attrs, defStyle, null);
}
public OverlayedImageView(Context context, AttributeSet attrs, int defStyle,
QuickContactBadge topBadge) {
super(context, attrs, defStyle);
this.topBadge = topBadge;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
topBadge.overlay(canvas, this);
}
}
| gpl-3.0 |
MrKickkiller/BuildcraftAdditions2 | src/main/java/buildcraftAdditions/tileEntities/TileRefinery.java | 12536 | package buildcraftAdditions.tileEntities;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTankInfo;
import net.minecraftforge.fluids.IFluidHandler;
import cofh.api.energy.IEnergyReceiver;
import buildcraft.api.transport.IPipeConnection;
import buildcraft.api.transport.IPipeTile;
import buildcraftAdditions.BuildcraftAdditions;
import buildcraftAdditions.api.recipe.BCARecipeManager;
import buildcraftAdditions.api.recipe.refinery.IRefineryRecipe;
import buildcraftAdditions.multiBlocks.IMultiBlockTile;
import buildcraftAdditions.reference.Variables;
import buildcraftAdditions.tileEntities.Bases.TileBase;
import buildcraftAdditions.utils.ITankHolder;
import buildcraftAdditions.utils.Location;
import buildcraftAdditions.utils.MultiBlockData;
import buildcraftAdditions.utils.RotationUtils;
import buildcraftAdditions.utils.Tank;
import io.netty.buffer.ByteBuf;
/**
* Copyright (c) 2014, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Buildcraft Additions is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class TileRefinery extends TileBase implements IMultiBlockTile, IFluidHandler, IEnergyReceiver, ITankHolder, IPipeConnection {
public int energy, maxEnergy, currentHeat, requiredHeat, energyCost, heatTimer, lastRequiredHeat;
public boolean init, valve, isCooling, moved;
public TileRefinery master;
private Tank input = new Tank(3000, this, "Input");
private Tank output = new Tank(3000, this, "Output");
private FluidStack outputFluidStack;
private FluidStack inputFluidStack;
private MultiBlockData data = new MultiBlockData().setPatern(Variables.Paterns.REFINERY);
public TileRefinery() {
maxEnergy = 50000;
init = false;
lastRequiredHeat = 20;
currentHeat = 20;
}
public void updateEntity() {
super.updateEntity();
if (worldObj.isRemote)
return;
if (data.moved) {
data.afterMoveCheck(worldObj);
worldObj.scheduleBlockUpdate(xCoord, yCoord, zCoord, worldObj.getBlock(xCoord, yCoord, zCoord), 80);
}
if (input.getFluid() != null && input.getFluid().amount <= 0)
input.setFluid(null);
if (output.getFluid() != null && output.getFluid().amount <= 0)
output.setFluid(null);
if (input.getFluid() == null)
updateRecipe();
updateHeat();
if (!data.isMaster)
return;
energyCost = (input.getFluid() == null || isCooling || energy < (int) (50 + (50 * ((double) currentHeat / 100)))) ? 0 : (int) (50 + (50 * ((double) currentHeat / 100)));
energy -= energyCost;
if (currentHeat < requiredHeat) {
return;
}
if (energyCost == 0 || input.isEmpty() || output.isFull() || !input.getFluid().isFluidEqual(inputFluidStack) || input.getFluidAmount() < inputFluidStack.amount || (!output.isEmpty() && !output.getFluid().isFluidEqual(outputFluidStack)) || output.getCapacity() - output.getFluidAmount() < outputFluidStack.amount)
return;
input.drain(inputFluidStack.amount, true);
output.fill(outputFluidStack, true);
}
private void updateHeat() {
if (worldObj.isRemote)
return;
if (heatTimer == 0) {
if ((currentHeat > requiredHeat || (energy < energyCost || energyCost == 0)) && currentHeat > 20) {
currentHeat--;
isCooling = true;
}
if (currentHeat < requiredHeat && (energy >= energyCost && energyCost != 0)) {
currentHeat++;
isCooling = false;
}
heatTimer = 10;
}
if (currentHeat == 20)
isCooling = false;
heatTimer -= 1;
}
private void updateRecipe() {
if (!input.isEmpty()) {
IRefineryRecipe recipe = BCARecipeManager.refinery.getRecipe(input.getFluid());
requiredHeat = recipe.getRequiredHeat();
lastRequiredHeat = requiredHeat;
outputFluidStack = recipe.getOutput();
inputFluidStack = recipe.getInput();
} else {
requiredHeat = 0;
}
}
@Override
public void makeMaster(int rotationIndex) {
data.isMaster = true;
data.partOfMultiBlock = true;
data.rotationIndex = rotationIndex;
}
public void findMaster() {
TileEntity entity = worldObj.getTileEntity(data.masterX, data.masterY, data.masterZ);
if (entity instanceof TileRefinery) {
master = (TileRefinery) entity;
}
if (master == null || !master.data.isMaster) {
master = null;
invalidateMultiblock();
}
}
@Override
public void invalidateMultiblock() {
if (isMaster())
data.patern.destroyMultiblock(worldObj, xCoord, yCoord, zCoord, data.rotationIndex);
else
data.patern.destroyMultiblock(worldObj, data.masterX, data.masterY, data.masterZ, data.rotationIndex);
}
private void emptyTanks() {
if (input.getFluid() == null || input.getFluid().amount < 1000 || input.getFluidType() == null)
return;
ForgeDirection[] directions = RotationUtils.rotateDirections(new ForgeDirection[]{ForgeDirection.NORTH, ForgeDirection.EAST, ForgeDirection.UP}, data.rotationIndex);
Location location = new Location(this);
location.move(directions);
while (input.getFluid().amount > 1000) {
if (input.getFluidType().getBlock() != null)
location.setBlock(input.getFluidType().getBlock());
input.drain(1000, true);
location.move(RotationUtils.rotatateDirection(ForgeDirection.NORTH, data.rotationIndex));
}
location.move(RotationUtils.rotatateDirection(ForgeDirection.NORTH, data.rotationIndex));
if (output.getFluid() == null || output.getFluid().amount < 1000 || output.getFluidType() == null)
return;
while (output.getFluid().amount > 1000) {
location.setBlock(output.getFluidType().getBlock());
output.drain(1000, true);
location.move(RotationUtils.rotatateDirection(ForgeDirection.NORTH, data.rotationIndex));
}
}
@Override
public boolean onBlockActivated(EntityPlayer player) {
if (data.isMaster) {
sync();
if (!worldObj.isRemote) {
player.openGui(BuildcraftAdditions.instance, Variables.Gui.REFINERY, worldObj, xCoord, yCoord, zCoord);
}
return true;
}
if (data.partOfMultiBlock) {
if (master == null)
findMaster();
if (master != null)
return master.onBlockActivated(player);
}
return false;
}
@Override
public void readFromNBT(NBTTagCompound tag) {
super.readFromNBT(tag);
valve = tag.getBoolean("valve");
energy = tag.getInteger("energy");
currentHeat = tag.getInteger("currentHeat");
requiredHeat = tag.getInteger("requiredHeat");
lastRequiredHeat = tag.getInteger("lastRequiredHeat");
data.readFromNBT(tag);
if (tag.hasKey("input", Constants.NBT.TAG_COMPOUND))
input.readFromNBT(tag.getCompoundTag("input"));
if (tag.hasKey("output", Constants.NBT.TAG_COMPOUND))
output.readFromNBT(tag.getCompoundTag("output"));
updateRecipe();
}
@Override
public void writeToNBT(NBTTagCompound tag) {
super.writeToNBT(tag);
data.writeToNBT(tag);
tag.setBoolean("valve", valve);
tag.setInteger("energy", energy);
tag.setInteger("currentHeat", currentHeat);
tag.setInteger("requiredHeat", requiredHeat);
tag.setInteger("lastRequiredHeat", lastRequiredHeat);
tag.setTag("input", input.writeToNBT(new NBTTagCompound()));
tag.setTag("output", output.writeToNBT(new NBTTagCompound()));
}
@Override
public void formMultiblock(int masterX, int masterY, int masterZ, int rotationIndex) {
data.formMultiBlock(masterX, masterY, masterZ, rotationIndex);
sync();
}
@Override
public void invalidateBlock() {
if (data.isMaster)
emptyTanks();
worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, 0, 2);
worldObj.scheduleBlockUpdate(xCoord, yCoord, zCoord, worldObj.getBlock(xCoord, yCoord, zCoord), 80);
input.setFluid(null);
output.setFluid(null);
requiredHeat = 0;
data.invalidate();
sync();
}
@Override
public void moved(ForgeDirection direction) {
data.onMove(direction);
master = null;
}
@Override
public int getMasterX() {
return data.masterX;
}
@Override
public int getMasterY() {
return data.masterY;
}
@Override
public int getMasterZ() {
return data.masterZ;
}
@Override
public int getRotationIndex() {
return data.rotationIndex;
}
@Override
public boolean isMaster() {
return data.isMaster;
}
@Override
public boolean isPartOfMultiblock() {
return data.partOfMultiBlock;
}
@Override
public void setMasterX(int masterX) {
data.masterX = masterX;
}
@Override
public void setMasterY(int masterY) {
data.masterY = masterY;
}
@Override
public void setMasterZ(int masterZ) {
data.masterZ = masterZ;
}
@Override
public void setIsMaster(boolean isMaster) {
data.isMaster = isMaster;
}
@Override
public void setPartOfMultiBlock(boolean partOfMultiBlock) {
data.partOfMultiBlock = partOfMultiBlock;
}
@Override
public void setRotationIndex(int rotationIndex) {
data.rotationIndex = rotationIndex;
}
@Override
public int fill(ForgeDirection from, FluidStack resource, boolean doFill) {
if (!valve)
return 0;
if (master == null)
findMaster();
if (master != null)
return master.realFill(resource, doFill);
return 0;
}
public int realFill(FluidStack resource, boolean doFill) {
int result = input.fill(resource, doFill);
updateRecipe();
return result;
}
@Override
public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) {
return null;
}
@Override
public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) {
if (!valve)
return null;
if (master == null)
findMaster();
if (master != null)
return master.realDrain(maxDrain, doDrain);
return null;
}
public FluidStack realDrain(int maxDrain, boolean doDrain) {
FluidStack result = output.drain(maxDrain, doDrain);
updateRecipe();
return result;
}
@Override
public boolean canFill(ForgeDirection from, Fluid fluid) {
return data.partOfMultiBlock && valve;
}
@Override
public boolean canDrain(ForgeDirection from, Fluid fluid) {
return data.partOfMultiBlock && valve;
}
@Override
public FluidTankInfo[] getTankInfo(ForgeDirection from) {
if (!valve)
return null;
if (master == null)
findMaster();
if (master != null)
return master.realGetTankInfo();
return new FluidTankInfo[]{new FluidTankInfo(input), new FluidTankInfo(output)};
}
public FluidTankInfo[] realGetTankInfo() {
return new FluidTankInfo[]{new FluidTankInfo(input), new FluidTankInfo(output)};
}
@Override
public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) {
if (data.isMaster) {
int recieved = maxReceive;
if (recieved > maxEnergy - energy)
recieved = maxEnergy - energy;
if (!simulate)
energy += recieved;
return recieved;
} else {
if (master == null)
findMaster();
if (master != null)
return master.receiveEnergy(from, maxReceive, simulate);
}
return 0;
}
@Override
public int getEnergyStored(ForgeDirection from) {
if (data.isMaster)
return energy;
else {
if (master == null)
findMaster();
if (master != null)
return master.getEnergyStored(from);
}
return 0;
}
@Override
public int getMaxEnergyStored(ForgeDirection from) {
if (data.isMaster)
return maxEnergy;
else {
if (master == null)
findMaster();
if (master != null)
return master.getMaxEnergyStored(from);
}
return 0;
}
@Override
public boolean canConnectEnergy(ForgeDirection from) {
return true;
}
@Override
public Tank[] getTanks() {
return new Tank[]{input, output};
}
@Override
public ByteBuf writeToByteBuff(ByteBuf buf) {
buf.writeBoolean(valve);
buf.writeInt(currentHeat);
buf.writeInt(lastRequiredHeat);
buf.writeInt(energyCost);
buf.writeInt(requiredHeat);
input.writeToByteBuff(buf);
output.writeToByteBuff(buf);
data.writeToByteBuff(buf);
return buf;
}
@Override
public ByteBuf readFromByteBuff(ByteBuf buf) {
valve = buf.readBoolean();
currentHeat = buf.readInt();
lastRequiredHeat = buf.readInt();
energyCost = buf.readInt();
requiredHeat = buf.readInt();
buf = input.readFromByteBuff(buf);
buf = output.readFromByteBuff(buf);
data.readFromByteBuff(buf);
return buf;
}
@Override
public ConnectOverride overridePipeConnection(IPipeTile.PipeType type, ForgeDirection with) {
return valve && type == IPipeTile.PipeType.FLUID ? ConnectOverride.CONNECT : ConnectOverride.DISCONNECT;
}
}
| gpl-3.0 |
nishanttotla/predator | cpachecker/src/org/sosy_lab/cpachecker/cpa/validvars/ValidVarsTransferRelation.java | 4400 | /*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2014 Dirk Beyer
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.cpa.validvars;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.sosy_lab.cpachecker.cfa.ast.c.CDeclaration;
import org.sosy_lab.cpachecker.cfa.ast.c.CVariableDeclaration;
import org.sosy_lab.cpachecker.cfa.model.CFAEdge;
import org.sosy_lab.cpachecker.cfa.model.FunctionEntryNode;
import org.sosy_lab.cpachecker.cfa.model.FunctionExitNode;
import org.sosy_lab.cpachecker.cfa.model.MultiEdge;
import org.sosy_lab.cpachecker.cfa.model.c.CDeclarationEdge;
import org.sosy_lab.cpachecker.core.defaults.SingleEdgeTransferRelation;
import org.sosy_lab.cpachecker.core.interfaces.AbstractState;
import org.sosy_lab.cpachecker.core.interfaces.Precision;
import org.sosy_lab.cpachecker.exceptions.CPATransferException;
import com.google.common.collect.ImmutableSet;
public class ValidVarsTransferRelation extends SingleEdgeTransferRelation {
@Override
public Collection<? extends AbstractState> getAbstractSuccessorsForEdge(
AbstractState pState, Precision pPrecision, CFAEdge pCfaEdge)
throws CPATransferException, InterruptedException {
ValidVarsState state = (ValidVarsState)pState;
ValidVars validVariables = state.getValidVariables();
switch (pCfaEdge.getEdgeType()) {
case MultiEdge:
Collection<AbstractState> predecessors, successors;
predecessors = Collections.singleton(pState);
for (CFAEdge edge: ((MultiEdge)pCfaEdge).getEdges()) {
successors = new ArrayList<>();
for (AbstractState predState: predecessors) {
successors.addAll(getAbstractSuccessorsForEdge(predState, pPrecision, edge));
}
predecessors = successors;
}
return predecessors;
case BlankEdge:
if (pCfaEdge.getDescription().equals("Function start dummy edge") && !(pCfaEdge.getPredecessor() instanceof FunctionEntryNode)) {
validVariables = validVariables.extendLocalVarsFunctionCall(pCfaEdge.getSuccessor().getFunctionName(),
ImmutableSet.<String> of());
}
if(pCfaEdge.getSuccessor() instanceof FunctionExitNode) {
validVariables = validVariables.removeVarsOfFunction(pCfaEdge.getPredecessor().getFunctionName());
}
break;
case FunctionCallEdge:
validVariables = validVariables.extendLocalVarsFunctionCall(pCfaEdge.getSuccessor().getFunctionName(),
((FunctionEntryNode) pCfaEdge.getSuccessor()).getFunctionParameterNames());
break;
case DeclarationEdge:
CDeclaration declaration = ((CDeclarationEdge) pCfaEdge).getDeclaration();
if (declaration instanceof CVariableDeclaration) {
if (declaration.isGlobal()) {
validVariables = validVariables.extendGlobalVars(declaration.getName());
} else {
validVariables =
validVariables.extendLocalVars(pCfaEdge.getPredecessor().getFunctionName(), declaration.getName());
}
}
break;
case ReturnStatementEdge:
validVariables = validVariables.removeVarsOfFunction(pCfaEdge.getPredecessor().getFunctionName());
break;
default:
break;
}
if (state.getValidVariables() == validVariables) {
return Collections.singleton(state);
}
return Collections.singleton(new ValidVarsState(validVariables));
}
@Override
public Collection<? extends AbstractState> strengthen(AbstractState pState, List<AbstractState> pOtherStates,
CFAEdge pCfaEdge, Precision pPrecision) throws CPATransferException, InterruptedException {
return null;
}
}
| gpl-3.0 |
dejan-brkic/studio | src/main/java/org/craftercms/studio/api/v1/service/deployment/DeploymentHistoryProvider.java | 1803 | /*
* Crafter Studio Web-content authoring solution
* Copyright (C) 2007-2017 Crafter Software Corporation.
*
* 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 org.craftercms.studio.api.v1.service.deployment;
import org.craftercms.studio.api.v1.dal.DeploymentSyncHistory;
import org.craftercms.studio.api.v1.util.filter.DmFilterWrapper;
import java.time.ZonedDateTime;
import java.util.List;
public interface DeploymentHistoryProvider {
/**
* Get deployment history for given site
*
* @param site site id
* @param fromDate date from
* @param toDate date to
* @param dmFilterWrapper
*@param filterType filter items by type
* @param numberOfItems number of items in result set @return
*/
List<DeploymentSyncHistory> getDeploymentHistory(String site, ZonedDateTime fromDate, ZonedDateTime toDate, DmFilterWrapper dmFilterWrapper, String filterType, int numberOfItems);
/**
* Get last deployment date time for given site and path
*
* @param site site id
* @param path path
* @return last deployment date or null if never deployed
*/
ZonedDateTime getLastDeploymentDate(String site, String path);
}
| gpl-3.0 |
makinacorpus/vtm | vtm-web/src/org/oscim/gdx/emu/org/oscim/utils/ThreadUtils.java | 194 | package org.oscim.utils;
public class ThreadUtils {
public static void assertMainThread() {
}
public static boolean isMainThread() {
return true;
}
public static void init() {
}
}
| gpl-3.0 |
84rrsk/TRG | src/main/java/ditl/graphs/cli/MovementToPresence.java | 2741 | /*******************************************************************************
* This file is part of DITL. *
* *
* Copyright (C) 2011-2012 John Whitbeck <john@whitbeck.fr> *
* *
* DITL 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. *
* *
* DITL 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 ditl.graphs.cli;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.ParseException;
import ditl.cli.App;
import ditl.cli.ConvertApp;
import ditl.graphs.MovementToPresenceConverter;
import ditl.graphs.MovementTrace;
import ditl.graphs.PresenceTrace;
@App.Cli(pkg = "graphs", cmd = "movement-to-presence", alias = "m2p")
public class MovementToPresence extends ConvertApp {
private final GraphOptions.CliParser graph_options = new GraphOptions.CliParser(GraphOptions.MOVEMENT, GraphOptions.PRESENCE);
@Override
protected void initOptions() {
super.initOptions();
graph_options.setOptions(options);
}
@Override
protected void parseArgs(CommandLine cli, String[] args)
throws ParseException, ArrayIndexOutOfBoundsException,
HelpException {
super.parseArgs(cli, args);
graph_options.parse(cli);
}
@Override
protected void run() throws Exception {
final MovementTrace movement = orig_store.getTrace(graph_options.get(GraphOptions.MOVEMENT));
final PresenceTrace presence = dest_store.newTrace(graph_options.get(GraphOptions.PRESENCE), PresenceTrace.class, force);
new MovementToPresenceConverter(presence, movement).convert();
}
}
| gpl-3.0 |
schwabdidier/GazePlay | gazeplay-games/src/main/java/net/gazeplay/games/goosegame/RepeatSquare.java | 449 | package net.gazeplay.games.goosegame;
import net.gazeplay.components.Position;
public class RepeatSquare extends Square {
public RepeatSquare(int number, Position pawnPosition, Square previousSquare, GooseGame game) {
super(number, pawnPosition, previousSquare, game);
}
@Override
protected void pawnStays(Pawn pawn) {
pawn.move(pawn.getLastThrowResult());
game.showMessage("Repeat last throw!");
}
}
| gpl-3.0 |
PFgimenez/thesis | src/recommandation/parser/ParserProcess.java | 1681 | /* (C) Copyright 2017, Gimenez Pierre-François
*
* 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 recommandation.parser;
/**
* A small parser
* @author Pierre-François Gimenez
*
*/
public class ParserProcess
{
private String[] args;
private Integer index;
private boolean verbose;
public boolean hasNext()
{
return index < args.length;
}
@Override
public ParserProcess clone()
{
return new ParserProcess(args, verbose, index);
}
public String read()
{
String out = args[index++];
if(verbose)
{
StackTraceElement elem = Thread.currentThread().getStackTrace()[2];
System.out.println("Lecture par "+elem.getClassName().substring(elem.getClassName().lastIndexOf(".") + 1) + ":" + elem.getLineNumber() + " (" + Thread.currentThread().getName()+") > "+out);
}
return out;
}
public ParserProcess(String[] args, boolean verbose)
{
this(args, verbose, 0);
}
private ParserProcess(String[] args, boolean verbose, int index)
{
this.verbose = verbose;
this.args = args;
this.index = index;
}
}
| gpl-3.0 |
k0smik0/FaCRI | Analyzer/faci/src/analyzer/net/iubris/faci/analyzer/graphstream/NoZeroDegree.java | 1884 | /*******************************************************************************
* Copyleft (c) 2015, "Massimiliano Leone - <maximilianus@gmail.com> - https://plus.google.com/+MassimilianoLeone"
* This file (NoZeroDegree.java) is part of facri.
*
* NoZeroDegree.java 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.
*
* NoZeroDegree.java 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 . If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package net.iubris.faci.analyzer.graphstream;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.graphstream.graph.Graph;
import org.graphstream.graph.Node;
public class NoZeroDegree {
public static int removeZeroDegreeNodes(Graph graph) {
AtomicInteger removed = new AtomicInteger(0);
Stream<Node> stream = StreamSupport.stream(graph.spliterator(), true);
stream.forEach(node -> {
if (node.getDegree()==0) {
graph.removeNode(node);
removed.incrementAndGet();
}
});
/*Iterator<Node> iterator = graph.iterator();
while (iterator.hasNext()) {
Node node = iterator.next();
if (node.getDegree()==0) {
// try {
iterator.remove();
removed.incrementAndGet();
// } catch(NullPointerException npe) {}
}
}*/
return removed.get();
}
}
| gpl-3.0 |
jokereactive/SpeakerCounter | src/de/fau/cs/jstk/io/FrameReader.java | 2957 | /*
Copyright (c) 2009-2011
Speech Group at Informatik 5, Univ. Erlangen-Nuremberg, GERMANY
Korbinian Riedhammer
Tobias Bocklet
This file is part of the Java Speech Toolkit (JSTK).
The JSTK 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.
The JSTK 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 the JSTK. If not, see <http://www.gnu.org/licenses/>.
*/
package de.fau.cs.jstk.io;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Reader;
/**
* Read Frames from the given Reader
* @author sikoried
*
*/
public class FrameReader implements FrameSource {
/** line number reader to read from */
private LineNumberReader lnr = null;
/** peek the first line */
private String peek = null;
/** input frame dimension */
private int fd = 0;
/** first line to read */
private double [] first = null;
/**
* Initialize a new FrameReader using the given reader.
* @param rd
* @throws IOException
*/
public FrameReader(Reader rd) throws IOException {
if (rd instanceof LineNumberReader)
lnr = (LineNumberReader) rd;
else
lnr = new LineNumberReader(rd);
// read first line
if ((peek = lnr.readLine()) == null)
throw new IOException("no line to read!");
String [] split = peek.trim().split("\\s+");
fd = split.length;
first = new double [fd];
try {
for (int i = 0; i < fd; ++i)
first[i] = Double.parseDouble(split[i]);
} catch (NumberFormatException e) {
throw new IOException("line " + lnr.getLineNumber() + ": invalid number format");
}
}
/**
* Read the next Frame from the Reader
*/
public boolean read(double [] buf) throws IOException {
if (first != null) {
if (buf.length != fd)
throw new IOException("Wrong buffer size on read()");
System.arraycopy(first, 0, buf, 0, fd);
first = null;
} else {
String l = lnr.readLine();
if (l == null)
return false;
String [] split = l.trim().split("\\s+");
if (split.length != fd)
throw new IOException("line " + lnr.getLineNumber() + ": invalid number of features");
try {
for (int i = 0; i < fd; ++i)
buf[i] = Double.parseDouble(split[i]);
} catch (NumberFormatException e) {
throw new IOException("line " + lnr.getLineNumber() + ": invalid number format");
}
}
return true;
}
/**
* Get the input frame size
*/
public int getFrameSize() {
return fd;
}
/**
* Get the underlying source
* @return null for FrameReaders
*/
public FrameSource getSource() {
return null;
}
}
| gpl-3.0 |
dested/Spoke-in-Craftbook | oldsrc/commonrefactor/com/sk89q/craftbook/blockbag/CompoundBlockBag.java | 2576 | package com.sk89q.craftbook.blockbag;
// $Id$
/*
* CraftBook
* Copyright (C) 2010 sk89q <http://www.sk89q.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/>.
*/
import java.util.List;
import com.sk89q.craftbook.access.WorldInterface;
import com.sk89q.craftbook.util.Vector;
/**
* A collection of block bags.
*
* @author Lymia
*/
public class CompoundBlockBag extends BlockBag {
private List<BlockBag> sources;
/**
* Construct the instance.
*
* @param bags
*/
public CompoundBlockBag(List<BlockBag> bags) {
this.sources = bags;
}
/**
* Store a block.
*
* @param id
*/
public void storeBlock(int id) throws BlockBagException {
for (BlockBag b : sources)
try {
b.storeBlock(id);
return;
} catch (OutOfSpaceException e) {
}
throw new OutOfSpaceException(id);
}
/**
* Get a block.
*
* @param id
*/
public void fetchBlock(int id) throws BlockBagException {
for (BlockBag b : sources)
try {
b.fetchBlock(id);
return;
} catch (OutOfBlocksException e) {
}
throw new OutOfBlocksException(id);
}
/**
* Adds a position to be used a source.
*
* @param pos
* @return
*/
public void addSingleSourcePosition(WorldInterface w, Vector pos) {
for (BlockBag b : sources)
b.addSingleSourcePosition(w, pos);
}
/**
* Adds a position to be used a source.
*
* @param pos
* @return
*/
public void addSourcePosition(WorldInterface w, Vector pos) {
for (BlockBag b : sources)
b.addSourcePosition(w, pos);
}
/**
* Return the list of missing blocks.
*
* @return
*/
public void flushChanges() {
for (BlockBag b : sources)
b.flushChanges();
}
}
| gpl-3.0 |
haslam22/IMDBSql | src/test/java/SelectorsTest.java | 2870 | import org.jsoup.nodes.Document;
import org.junit.Test;
import org.jsoup.*;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import static org.junit.Assert.*;
/*
* JUnit tests for IMDB CSS selectors
*/
public class SelectorsTest {
IMDBTitle title;
public SelectorsTest() {
try {
Document htmlDocument = Jsoup.connect("http://www.imdb.com/title/tt0137523").get();
this.title = new IMDBDocument(htmlDocument).createTitle();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testTitleSelectors() {
assertEquals("title ID should match", "0137523", title.getID());
assertEquals("title should match", "Fight Club", title.getName());
assertEquals("title type should match", "Movie", title.getType());
assertTrue("title year should match", title.getReleaseDate().contains("1999"));
assertEquals("title duration should match", "2h 19min", title.getDuration());
assertFalse("title classification should not be empty", title.getClassification().isEmpty());
assertFalse("title summary should not be empty", title.getSummary().isEmpty());
assertFalse("title poster should not be empty", title.getPoster().isEmpty());
assertTrue("title genre should match", title.getGenres().contains("Drama"));
}
@Test
public void testPeopleSelectors() {
List<IMDBPerson> people = title.getPeople();
HashSet<String> expected = new HashSet<String>();
expected.add("David Fincher");
expected.add("Chuck Palahniuk");
expected.add("Jim Uhls");
expected.add("Brad Pitt");
expected.add("Edward Norton");
expected.add("Meat Loaf");
expected.add("Zach Grenier");
expected.add("Richmond Arquette");
expected.add("David Andrews");
expected.add("George Maguire");
expected.add("Eugenie Bondurant");
expected.add("Helena Bonham Carter");
expected.add("Christina Cabot");
expected.add("Sydney 'Big Dawg' Colston");
expected.add("Rachel Singer");
expected.add("Christie Cronenweth");
expected.add("Tim DeZarn");
expected.add("Ezra Buzzington");
for(IMDBPerson person : people) {
assertTrue("person name should be in the expected map", expected.contains(person.getName()));
assertTrue("person ID length should be 7", person.getID().length() == 7);
for (char c : person.getID().toCharArray())
{
assertTrue("person ID should only contain digits", Character.isDigit(c));
}
assertTrue("person profession should be actor, director or writer",
person.getProfession().matches("actor|director|creator"));
}
}
}
| gpl-3.0 |
seadas/beam | beam-gpf/src/main/java/org/esa/beam/framework/gpf/ui/DefaultAppContext.java | 3805 | /*
* Copyright (C) 2010 Brockmann Consult GmbH (info@brockmann-consult.de)
*
* 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 org.esa.beam.framework.gpf.ui;
import org.esa.beam.framework.datamodel.Product;
import org.esa.beam.framework.datamodel.ProductManager;
import org.esa.beam.framework.ui.AppContext;
import org.esa.beam.framework.ui.application.ApplicationPage;
import org.esa.beam.framework.ui.product.ProductSceneView;
import org.esa.beam.util.PropertyMap;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.Window;
/**
* This trivial implementation of the {@link org.esa.beam.framework.ui.AppContext} class
* is only for testing.
*/
public class DefaultAppContext implements AppContext {
private Window applicationWindow;
private String applicationName;
private ProductManager productManager;
private Product selectedProduct;
private PropertyMap preferences;
private ProductSceneView selectedSceneView;
public DefaultAppContext(String applicationName) {
this(applicationName,
new JFrame(applicationName),
new ProductManager(),
new PropertyMap());
}
public DefaultAppContext(String applicationName,
Window applicationWindow,
ProductManager productManager,
PropertyMap preferences) {
this.applicationWindow = applicationWindow;
this.applicationName = applicationName;
this.productManager = productManager;
this.preferences = preferences;
}
@Override
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
@Override
public Window getApplicationWindow() {
return applicationWindow;
}
@Override
public ApplicationPage getApplicationPage() {
return null;
}
public void setApplicationWindow(Window applicationWindow) {
this.applicationWindow = applicationWindow;
}
@Override
public PropertyMap getPreferences() {
return preferences;
}
public void setPreferences(PropertyMap preferences) {
this.preferences = preferences;
}
@Override
public ProductManager getProductManager() {
return productManager;
}
public void setProductManager(ProductManager productManager) {
this.productManager = productManager;
}
@Override
public Product getSelectedProduct() {
return selectedProduct;
}
public void setSelectedProduct(Product selectedProduct) {
this.selectedProduct = selectedProduct;
}
@Override
public void handleError(String message, Throwable t) {
if (t != null) {
t.printStackTrace();
}
JOptionPane.showMessageDialog(getApplicationWindow(), message);
}
@Override
public ProductSceneView getSelectedProductSceneView() {
return selectedSceneView;
}
public void setSelectedSceneView(ProductSceneView selectedView) {
this.selectedSceneView = selectedView;
}
}
| gpl-3.0 |
squaregoldfish/QuinCe | WebApp/src/uk/ac/exeter/QuinCe/data/Dataset/QC/RoutineFlag.java | 2250 | package uk.ac.exeter.QuinCe.data.Dataset.QC;
import uk.ac.exeter.QuinCe.data.Dataset.QC.DataReduction.DataReductionQCRoutinesConfiguration;
import uk.ac.exeter.QuinCe.data.Dataset.QC.SensorValues.QCRoutinesConfiguration;
public class RoutineFlag extends Flag {
/**
* The routine that generated this flag
*/
protected final String routineName;
/**
* The value required by the routine
*/
private final String requiredValue;
/**
* The actual value
*/
private final String actualValue;
public RoutineFlag(Routine routine, Flag flag, String requiredValue,
String actualValue) {
super(flag);
this.routineName = routine.getName();
this.requiredValue = requiredValue;
this.actualValue = actualValue;
}
/**
* Get a concrete instance of the Routine that generated this flag.
*
* @return The Routine instance.
*/
protected Routine getRoutineInstance() throws RoutineException {
Routine result;
String[] routineNameParts = routineName.split("\\.");
switch (routineNameParts[0]) {
case "SensorValues": {
result = QCRoutinesConfiguration.getRoutine(routineName);
break;
}
case "DataReduction": {
result = DataReductionQCRoutinesConfiguration.getRoutine(routineName);
break;
}
default: {
throw new RoutineException(
"Cannot determine routine type " + routineNameParts[0]);
}
}
return result;
}
public String getRoutineName() {
return routineName;
}
/**
* Get the short message for the routine attached to this flag
*
* @return The message
* @throws RoutineException
* If the message cannot be retrieved
*/
public String getShortMessage() throws RoutineException {
return getRoutineInstance().getShortMessage();
}
/**
* Get the short message for the routine attached to this flag
*
* @return The message
* @throws RoutineException
* If the message cannot be retrieved
*/
public String getLongMessage() throws RoutineException {
return getRoutineInstance().getLongMessage(this);
}
public String getRequiredValue() {
return requiredValue;
}
public String getActualValue() {
return actualValue;
}
}
| gpl-3.0 |
DivineCooperation/bco.dal | lib/src/main/java/org/openbase/bco/dal/lib/layer/unit/UnitDataFilteredObservable.java | 6450 | package org.openbase.bco.dal.lib.layer.unit;
/*-
* #%L
* BCO DAL Library
* %%
* Copyright (C) 2014 - 2021 openbase.org
* %%
* This program 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 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
import com.google.protobuf.Descriptors;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Message;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.openbase.bco.dal.lib.layer.service.Services;
import org.openbase.jul.exception.CouldNotPerformException;
import org.openbase.jul.exception.NotAvailableException;
import org.openbase.jul.extension.protobuf.ProtoBufBuilderProcessor;
import org.openbase.jul.extension.protobuf.processing.ProtoBufFieldProcessor;
import org.openbase.jul.pattern.AbstractObservable;
import org.openbase.jul.pattern.provider.DataProvider;
import org.openbase.type.domotic.service.ServiceDescriptionType.ServiceDescription;
import org.openbase.type.domotic.service.ServiceTemplateType.ServiceTemplate.ServiceType;
import org.openbase.type.domotic.service.ServiceTempusTypeType.ServiceTempusType.ServiceTempus;
import org.openbase.type.domotic.unit.UnitTemplateType.UnitTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author <a href="mailto:thuxohl@techfak.uni-bielefeld.de">Tamino Huxohl</a>
* @param <M>
*/
public class UnitDataFilteredObservable<M extends Message> extends AbstractObservable<DataProvider<M>, M> {
private static final Logger LOGGER = LoggerFactory.getLogger(UnitDataFilteredObservable.class);
private static final String FIELD_NAME_ALIAS = "alias";
private static final String FIELD_NAME_ID = "id";
private static final String FIELD_NAME_TRANSACTION_ID = "transaction_id";
private static final String FIELD_NAME_AGGREGATED_VALUE_COVERAGE = "aggregated_value_coverage";
private final DataProvider<M> unit;
private final ServiceTempus serviceTempus;
private final Set<String> fieldsToKeep;
private UnitTemplate unitTemplate;
public UnitDataFilteredObservable(final DataProvider<M> dataProvider, final ServiceTempus serviceTempus) {
this(dataProvider, serviceTempus, null);
}
public UnitDataFilteredObservable(final DataProvider<M> dataProvider, final ServiceTempus serviceTempus, final UnitTemplate unitTemplate) {
super(dataProvider);
this.unit = dataProvider;
this.serviceTempus = serviceTempus;
this.setHashGenerator((M value) -> removeUnwantedServiceTempusAndIdFields(value.toBuilder()).build().hashCode());
this.fieldsToKeep = new HashSet<>();
this.unitTemplate = unitTemplate;
if (unitTemplate != null) {
updateFieldsToKeep();
}
}
public Set<String> getFieldsToKeep() {
return Collections.unmodifiableSet(fieldsToKeep);
}
@Override
public void waitForValue(long timeout, TimeUnit timeUnit) throws CouldNotPerformException, InterruptedException {
unit.waitForData();
}
@Override
public M getValue() throws NotAvailableException {
return unit.getData();
}
@Override
public boolean isValueAvailable() {
return unit.isDataAvailable();
}
@Override
public Future<M> getValueFuture() {
return unit.getDataFuture();
}
private synchronized void updateFieldsToKeep() {
if(serviceTempus == ServiceTempus.UNKNOWN) {
return;
}
fieldsToKeep.clear();
Set<ServiceType> serviceTypeSet = new HashSet<>();
for (ServiceDescription serviceDescription : unitTemplate.getServiceDescriptionList()) {
if (!serviceTypeSet.contains(serviceDescription.getServiceType())) {
serviceTypeSet.add(serviceDescription.getServiceType());
fieldsToKeep.add(Services.getServiceFieldName(serviceDescription.getServiceType(), serviceTempus));
}
}
}
public void updateToUnitTemplateChange(UnitTemplate unitTemplate) {
this.unitTemplate = unitTemplate;
updateFieldsToKeep();
}
private synchronized Message.Builder removeUnwantedServiceTempusAndIdFields(final Message.Builder builder) {
// if unknown keep everything
if(serviceTempus == ServiceTempus.UNKNOWN) {
return builder;
}
// filter tempus
Descriptors.Descriptor descriptorForType = builder.getDescriptorForType();
for (FieldDescriptor field : descriptorForType.getFields()) {
if (field.getType() == FieldDescriptor.Type.MESSAGE) {
if (!fieldsToKeep.contains(field.getName())) {
builder.clearField(field);
} else {
Message.Builder fieldBuilder = builder.getFieldBuilder(field);
for (FieldDescriptor fieldDescriptor : fieldBuilder.getDescriptorForType().getFields()) {
if (fieldDescriptor.getName().equals(FIELD_NAME_AGGREGATED_VALUE_COVERAGE)) {
fieldBuilder.clearField(fieldDescriptor);
}
}
}
} else {
switch (field.getName()) {
case FIELD_NAME_ALIAS:
case FIELD_NAME_ID:
builder.clearField(field);
break;
case FIELD_NAME_TRANSACTION_ID:
if (serviceTempus != ServiceTempus.CURRENT) builder.clearField(field);
break;
}
}
}
// LOGGER.trace("For {} let pass Fields[{}]: {}", serviceTempus.name(), fieldsToKeep.toString(), builder.build());
return builder;
}
}
| gpl-3.0 |
marvec/engine | lumeer-core/src/test/java/io/lumeer/core/util/UtilsTest.java | 714 | package io.lumeer.core.util;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class UtilsTest {
@Test
public void isCodeSafe() {
assertThat(Utils.isCodeSafe("abc")).isTrue();
assertThat(Utils.isCodeSafe("abc/das")).isFalse();
}
@Test
public void testQueryParamEncoding() {
assertThat(Utils.encodeQueryParam("{\"s\":[{\"c\":\"5d24b3632ec57b390456ed06\"}]}"))
.isEqualTo("eyJzIjpbeyJjIjoiNWQyNGIzNjMyZWM1N2IzOTA0NTZlZDA2In1dfQc809164d");
assertThat(Utils.decodeQueryParam("eyJzIjpbeyJjIjoiNWQyNGIzNjMyZWM1N2IzOTA0NTZlZDA2In1dfQc809164d"))
.isEqualTo("{\"s\":[{\"c\":\"5d24b3632ec57b390456ed06\"}]}");
}
}
| gpl-3.0 |
Abnaxos/pegdown-doclet | core/src/main/java/ch/raffael/mddoclet/core/options/ReflectedOptions.java | 3891 | package ch.raffael.mddoclet.core.options;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;
import ch.raffael.mddoclet.core.util.ReflectionException;
/**
* Provides the tools to scan objects/methods for the {@link OptionConsumer @Option}
* annotation and return option processors or descriptors for it.
*
* @author Raffael Herzog
*/
public final class ReflectedOptions {
private ReflectedOptions() {
throw new AssertionError("Utility class: " + getClass().getName());
}
public static List<OptionDescriptor> descriptorsForObject(Object target) {
List<OptionDescriptor> descriptors = new ArrayList<>();
for (Method method : target.getClass().getMethods()) {
if (method.isAnnotationPresent(OptionConsumer.class)) {
descriptors.add(descriptorForMethod(target, method));
}
}
return descriptors;
}
public static OptionDescriptor descriptorForMethod(Object target, Method method) {
OptionConsumer annotation = method.getAnnotation(OptionConsumer.class);
if (annotation == null) {
throw new IllegalArgumentException("Method " + method + " not annotated with @" + OptionConsumer.class.getSimpleName());
}
return OptionDescriptor.builder()
.names(annotation.names())
.description(annotation.description())
.parameters(annotation.parameters())
.argumentCount(method.getParameterCount())
.processor(processorForMethod(target, method))
.build();
}
public static OptionProcessor processorForMethod(Object target, Method method) {
List<ArgumentConverter<?>> converters = new ArrayList<>(method.getParameterCount());
for (Parameter parameter : method.getParameters()) {
ArgumentConverter<?> converter;
OptionConsumer.Converter converterAnnotation = parameter.getAnnotation(OptionConsumer.Converter.class);
if (converterAnnotation != null) {
try {
converter = converterAnnotation.value().newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new ReflectionException("Error instantiating converter for parameter " + parameter + " method " + method);
}
} else {
converter = StandardArgumentConverters.forType(parameter.getParameterizedType());
if (converter == null) {
throw new ReflectionException("No argument converter found for parameter " + parameter.getName() + " of " + method);
}
}
converters.add(converter);
}
return (name, arguments) -> {
if (arguments.size() != converters.size()) {
throw new InvalidOptionArgumentsException("Unexpected argument count: " + arguments.size() + "!=" + converters.size() + "(expeted)");
}
Object[] methodArguments = new Object[arguments.size()];
for (int i = 0; i < arguments.size(); i++) {
methodArguments[i] = converters.get(i).convert(arguments.get(i));
}
try {
method.invoke(target, methodArguments);
} catch (IllegalAccessException e) {
throw new ArgumentsProcessingException(e);
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof InvalidOptionArgumentsException) {
throw (InvalidOptionArgumentsException)e.getTargetException();
} else {
throw new ArgumentsProcessingException(e);
}
}
};
}
}
| gpl-3.0 |
borboton13/sisk13 | src/main/com/encens/khipus/framework/action/QueryDataModel.java | 12884 | package com.encens.khipus.framework.action;
import com.encens.khipus.model.BaseModel;
import com.encens.khipus.util.FormatUtils;
import com.encens.khipus.util.ListEntityManagerName;
import com.encens.khipus.util.query.QueryUtils;
import org.ajax4jsf.model.DataVisitor;
import org.ajax4jsf.model.Range;
import org.ajax4jsf.model.SequenceRange;
import org.ajax4jsf.model.SerializableDataModel;
import org.jboss.seam.Component;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Base DataModel to be used in View DataTables.
* It allows to define a sorting property and its order type.
* It allows to bind the page for the datascroller, if there's one bind to it
* It browse the data in a paged fashion.
* It's recommended to use this databmodel binded to a component with page scope.
*
* @author
* @version $Id: BaseDataModel.java 2008-8-20 16:26:26 $
*/
public abstract class QueryDataModel<ID, T extends BaseModel> extends SerializableDataModel {
/**
* To configure the entity manager with which execute the Entity query.
* <p/>
* The default value its 'listEntityManager'
*/
private String entityManagerName = ListEntityManagerName.DEFAULT_LIST.getName();
private ID currentId;
private boolean detached = false;
private List<ID> wrappedKeys = null;
private final Map<ID, T> wrappedData = new HashMap<ID, T>();
private Integer rowCount;
private int numberOfRows;
private int numberOfRowsDisplayed;
private int rowIndex;
protected String sortProperty;
private String currentSortProperties = null;
protected boolean sortAsc = true;
private int page = 1;
private Class<T> entityClass;
private Class<ID> idClass;
//TODO: improve this, entityQuery does not require to be serialized , it must be transient, but making it transient gives unexpected results when searching
private EntityQuery<T> entityQuery;
private String ejbql = null;
private List<String> restrictions = new ArrayList<String>(0);
private T criteria;
private Map<Integer, Boolean> selectedValue = new HashMap<Integer, Boolean>();
private Map<Integer, Map<ID, Boolean>> selectedList = new HashMap<Integer, Map<ID, Boolean>>();
public Long getCount() {
initEntityQuery();
postInitEntityQuery(entityQuery);
entityQuery.setOrder(getOrder());
return entityQuery.getResultCount();
}
public List<T> getList(Integer firstRow, Integer maxResults) {
initEntityQuery();
postInitEntityQuery(entityQuery);
setNumberOfRows(maxResults);
entityQuery.setOrder(getOrder());
entityQuery.setFirstResult(firstRow);
entityQuery.setMaxResults(maxResults);
return entityQuery.getResultList();
}
private void initEntityQuery() {
if (entityQuery == null) {
entityQuery = new EntityQuery<T>();
entityQuery.setEjbql(getEjbql());
entityQuery.setRestrictionExpressionStrings(getRestrictions());
criteria = createInstance();
}
entityQuery.setEntityManager(getEntityManager());
}
protected void postInitEntityQuery(EntityQuery entityQuery) {
}
public List<T> getResultList() {
initEntityQuery();
postInitEntityQuery(entityQuery);
entityQuery.setOrder(getOrder());
return entityQuery.getResultList();
}
private String getOrder() {
if (getSortProperty() != null) {
String currentOrder = isSortAsc() ? " ASC" : " DESC";
currentSortProperties = getSortProperty().replaceAll(" ", "").replaceAll(",", currentOrder + ",") + currentOrder;
}
return currentSortProperties;
}
public String getEjbql() {
return ejbql;
}
public List<String> getRestrictions() {
return restrictions;
}
public T getCriteria() {
return criteria;
}
public void setCriteria(T criteria) {
this.criteria = criteria;
}
public void search() {
if (entityQuery != null) {
entityQuery.refresh();
}
setPage(1);
clearAllSelection();
}
public void clear() {
setCriteria(createInstance());
clearAllSelection();
updateAndSearch();
}
public void updateAndSearch() {
update();
search();
}
public void reset() {
updateAndSearch();
}
public T createInstance() {
if (getEntityClass() != null) {
try {
criteria = getEntityClass().newInstance();
return criteria;
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
return null;
}
}
@SuppressWarnings({"unchecked"})
public Class<T> getEntityClass() {
if (entityClass == null) {
Type type = getClass().getGenericSuperclass();
if (type instanceof ParameterizedType) {
ParameterizedType paramType = (ParameterizedType) type;
entityClass = (Class<T>) paramType.getActualTypeArguments()[1];
} else {
throw new IllegalArgumentException("Could not guess entity class by reflection");
}
}
return entityClass;
}
@SuppressWarnings({"unchecked"})
public Class<ID> getIdClass() {
if (idClass == null) {
Type type = getClass().getGenericSuperclass();
if (type instanceof ParameterizedType) {
ParameterizedType paramType = (ParameterizedType) type;
idClass = (Class<ID>) paramType.getActualTypeArguments()[0];
} else {
throw new IllegalArgumentException("Could not guess id class by reflection");
}
}
return idClass;
}
public void walk(FacesContext facesContext, DataVisitor dataVisitor, Range range, Object argument) throws IOException {
if (detached) {
for (ID key : wrappedKeys) {
setRowKey(key);
dataVisitor.process(facesContext, key, argument);
}
} else {
int firstRow = ((SequenceRange) range).getFirstRow();
int numberOfRows = ((SequenceRange) range).getRows();
wrappedKeys = new ArrayList<ID>();
for (T instance : getList(firstRow, numberOfRows)) {
wrappedKeys.add(getId(instance));
wrappedData.put(getId(instance), instance);
dataVisitor.process(facesContext, getId(instance), argument);
}
}
setNumberOfRowsDisplayed(wrappedKeys.size());
}
@Override
public SerializableDataModel getSerializableModel(Range range) {
if (wrappedKeys != null) {
detached = true;
return this;
}
return null;
}
@SuppressWarnings("unchecked")
public ID getId(T row) {
return (ID) row.getId();
}
public void update() {
rowCount = null;
detached = false;
}
public boolean isRowAvailable() {
if (currentId == null) {
return false;
} else if (wrappedKeys.contains(currentId)) {
return true;
} else if (wrappedData.keySet().contains(currentId)) {
return true;
}
return false;
}
public Object getRowData() {
if (currentId == null) {
return null;
} else {
return wrappedData.get(currentId);
}
}
public int getRowCount() {
if (rowCount == null) {
rowCount = getCount().intValue();
}
return rowCount;
}
public int getNumberOfRows() {
return numberOfRows;
}
public void setNumberOfRows(int numberOfRows) {
this.numberOfRows = numberOfRows;
}
public int getNumberOfRowsDisplayed() {
return numberOfRowsDisplayed;
}
public void setNumberOfRowsDisplayed(int numberOfRowsDisplayed) {
this.numberOfRowsDisplayed = numberOfRowsDisplayed;
}
public Integer getCurrentRows() {
if (getRowCount() > getNumberOfRows() && (getPage() * getNumberOfRows()) <= getRowCount() && getPage() * getNumberOfRows() > 0) {
return getPage() * getNumberOfRows();
}
return getRowCount();
}
public String getRangeRowsString() {
Integer currentRows = getCurrentRows();
if (currentRows != null && currentRows > 0) {
return FormatUtils.removePoint(((getNumberOfRowsDisplayed() > 0 ? currentRows - getNumberOfRowsDisplayed() : 0) + 1) + " - " + currentRows);
}
return "0";
}
public String getRowCountString() {
return FormatUtils.removePoint("" + getRowCount());
}
@SuppressWarnings({"unchecked"})
public void setRowKey(Object key) {
this.currentId = (ID) key;
}
public Object getRowKey() {
return currentId;
}
public int getRowIndex() {
return rowIndex;
}
public void setRowIndex(int rowIndex) {
this.rowIndex = rowIndex;
}
public Object getWrappedData() {
throw new UnsupportedOperationException();
}
public void setWrappedData(Object o) {
throw new UnsupportedOperationException();
}
public String getSortProperty() {
return sortProperty;
}
public void setSortProperty(String sortProperty) {
if (this.sortProperty != null) {
setSortAsc(!this.sortProperty.equals(sortProperty) || !isSortAsc());
}
this.sortProperty = sortProperty;
}
public boolean isSortAsc() {
return sortAsc;
}
public void setSortAsc(boolean sortAsc) {
this.sortAsc = sortAsc;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
protected EntityManager getEntityManager() {
return (EntityManager) Component.getInstance(entityManagerName);
}
public Map<Integer, Boolean> getSelectedValue() {
return selectedValue;
}
public void setSelectedValue(Map<Integer, Boolean> selectedValue) {
this.selectedValue = selectedValue;
}
public Map<Integer, Map<ID, Boolean>> getSelectedList() {
if (selectedList.get(getPage()) == null) {
selectedList.put(getPage(), new HashMap<ID, Boolean>());
}
return selectedList;
}
public void setSelectedList(Map<Integer, Map<ID, Boolean>> selectedList) {
this.selectedList = selectedList;
}
@SuppressWarnings({"unchecked"})
public List<T> getSelectedObjectList() {
List<T> currentSelectionList = new ArrayList<T>();
if (!getIdClass().isLocalClass()) {
List<ID> currentIdSelectionList = getSelectedIdList();
if (!currentIdSelectionList.isEmpty()) {
currentSelectionList = QueryUtils.selectAllIn(getEntityManager(), getEntityClass(), currentIdSelectionList).getResultList();
}
} else {
for (Map.Entry<Integer, Map<ID, Boolean>> mainEntrySelection : getSelectedList().entrySet()) {
for (Map.Entry<ID, Boolean> selectEntry : mainEntrySelection.getValue().entrySet()) {
if (selectEntry.getValue()) {
currentSelectionList.add(getEntityManager().find(getEntityClass(), selectEntry.getKey()));
}
}
}
}
return currentSelectionList;
}
public List<ID> getSelectedIdList() {
List<ID> currentSelectionList = new ArrayList<ID>();
for (Map.Entry<Integer, Map<ID, Boolean>> mainEntrySelection : getSelectedList().entrySet()) {
for (Map.Entry<ID, Boolean> selectEntry : mainEntrySelection.getValue().entrySet()) {
if (selectEntry.getValue()) {
currentSelectionList.add(selectEntry.getKey());
}
}
}
return currentSelectionList;
}
public void selectAll() {
for (Map.Entry<ID, Boolean> selectEntry : getSelectedList().get(getPage()).entrySet()) {
selectEntry.setValue(getSelectedValue().get(getPage()));
}
}
public void clearAllSelection() {
getSelectedValue().clear();
getSelectedList().clear();
}
public String getEntityManagerName() {
return entityManagerName;
}
public void setEntityManagerName(String entityManagerName) {
this.entityManagerName = entityManagerName;
}
} | gpl-3.0 |
Scrik/Cauldron-1 | eclipse/cauldron/src/main/java/net/minecraft/inventory/InventoryEnderChest.java | 3609 | package net.minecraft.inventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntityEnderChest;
// CraftBukkit start
import java.util.List;
import org.bukkit.craftbukkit.entity.CraftHumanEntity;
import org.bukkit.entity.HumanEntity;
// CraftBukkit end
public class InventoryEnderChest extends InventoryBasic
{
private TileEntityEnderChest associatedChest;
// CraftBukkit start
public List<HumanEntity> transaction = new java.util.ArrayList<HumanEntity>();
public org.bukkit.entity.Player player;
private int maxStack = MAX_STACK;
public ItemStack[] getContents()
{
return this.inventoryContents;
}
public void onOpen(CraftHumanEntity who)
{
transaction.add(who);
}
public void onClose(CraftHumanEntity who)
{
transaction.remove(who);
}
public List<HumanEntity> getViewers()
{
return transaction;
}
public org.bukkit.inventory.InventoryHolder getOwner()
{
return this.player;
}
public void setMaxStackSize(int size)
{
maxStack = size;
}
/**
* Returns the maximum stack size for a inventory slot. Seems to always be 64, possibly will be extended. *Isn't
* this more of a set than a get?*
*/
public int getInventoryStackLimit()
{
return maxStack;
}
// CraftBukkit end
private static final String __OBFID = "CL_00001759";
public InventoryEnderChest()
{
super("container.enderchest", false, 27);
}
public void func_146031_a(TileEntityEnderChest p_146031_1_)
{
this.associatedChest = p_146031_1_;
}
public void loadInventoryFromNBT(NBTTagList p_70486_1_)
{
int i;
for (i = 0; i < this.getSizeInventory(); ++i)
{
this.setInventorySlotContents(i, (ItemStack)null);
}
for (i = 0; i < p_70486_1_.tagCount(); ++i)
{
NBTTagCompound nbttagcompound = p_70486_1_.getCompoundTagAt(i);
int j = nbttagcompound.getByte("Slot") & 255;
if (j >= 0 && j < this.getSizeInventory())
{
this.setInventorySlotContents(j, ItemStack.loadItemStackFromNBT(nbttagcompound));
}
}
}
public NBTTagList saveInventoryToNBT()
{
NBTTagList nbttaglist = new NBTTagList();
for (int i = 0; i < this.getSizeInventory(); ++i)
{
ItemStack itemstack = this.getStackInSlot(i);
if (itemstack != null)
{
NBTTagCompound nbttagcompound = new NBTTagCompound();
nbttagcompound.setByte("Slot", (byte)i);
itemstack.writeToNBT(nbttagcompound);
nbttaglist.appendTag(nbttagcompound);
}
}
return nbttaglist;
}
public boolean isUseableByPlayer(EntityPlayer p_70300_1_)
{
return this.associatedChest != null && !this.associatedChest.func_145971_a(p_70300_1_) ? false : super.isUseableByPlayer(p_70300_1_);
}
public void openInventory()
{
if (this.associatedChest != null)
{
this.associatedChest.func_145969_a();
}
super.openInventory();
}
public void closeInventory()
{
if (this.associatedChest != null)
{
this.associatedChest.func_145970_b();
}
super.closeInventory();
this.associatedChest = null;
}
} | gpl-3.0 |
juergenchrist/smtinterpol | SMTInterpol/src/de/uni_freiburg/informatik/ultimate/smtinterpol/model/BoolSortInterpretation.java | 1440 | /*
* Copyright (C) 2014 University of Freiburg
*
* This file is part of SMTInterpol.
*
* SMTInterpol 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.
*
* SMTInterpol 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 SMTInterpol. If not, see <http://www.gnu.org/licenses/>.
*/
package de.uni_freiburg.informatik.ultimate.smtinterpol.model;
import de.uni_freiburg.informatik.ultimate.logic.Sort;
import de.uni_freiburg.informatik.ultimate.logic.Term;
import de.uni_freiburg.informatik.ultimate.logic.Theory;
public class BoolSortInterpretation implements SortInterpretation {
@Override
public Term toSMTLIB(final Theory t, final Sort sort) {
throw new InternalError("Should never be called");
}
@Override
public Term extendFresh(final Sort sort) {
throw new InternalError("Three-valued Bool?");
}
@Override
public Term getModelValue(final int idx, final Sort sort) {
return idx == 0 ? sort.getTheory().mFalse : sort.getTheory().mTrue;
}
}
| gpl-3.0 |
adithyaphilip/open-keychain | OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/pgp/UncachedKeyringTest.java | 6490 | /*
* Copyright (C) 2014 Dominik Schürmann <dominik@dominikschuermann.de>
* Copyright (C) 2014 Vincent Breitmoser <v.breitmoser@mugenguild.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 org.sufficientlysecure.keychain.pgp;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.shadows.ShadowLog;
import org.spongycastle.bcpg.sig.KeyFlags;
import org.sufficientlysecure.keychain.operations.results.PgpEditKeyResult;
import org.sufficientlysecure.keychain.pgp.UncachedKeyRing.IteratorWithIOThrow;
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
import org.sufficientlysecure.keychain.service.SaveKeyringParcel;
import org.sufficientlysecure.keychain.service.SaveKeyringParcel.Algorithm;
import org.sufficientlysecure.keychain.service.SaveKeyringParcel.ChangeUnlockParcel;
import org.sufficientlysecure.keychain.util.Passphrase;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Random;
@RunWith(RobolectricTestRunner.class)
@org.robolectric.annotation.Config(emulateSdk = 18) // Robolectric doesn't yet support 19
public class UncachedKeyringTest {
static UncachedKeyRing staticRing, staticPubRing;
UncachedKeyRing ring, pubRing;
@BeforeClass
public static void setUpOnce() throws Exception {
ShadowLog.stream = System.out;
SaveKeyringParcel parcel = new SaveKeyringParcel();
parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd(
Algorithm.RSA, 1024, null, KeyFlags.CERTIFY_OTHER, 0L));
parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd(
Algorithm.RSA, 1024, null, KeyFlags.SIGN_DATA, 0L));
parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd(
Algorithm.RSA, 1024, null, KeyFlags.ENCRYPT_COMMS, 0L));
parcel.mAddUserIds.add("twi");
parcel.mAddUserIds.add("pink");
{
Random r = new Random();
int type = r.nextInt(110)+1;
byte[] data = new byte[r.nextInt(2000)];
new Random().nextBytes(data);
WrappedUserAttribute uat = WrappedUserAttribute.fromSubpacket(type, data);
parcel.mAddUserAttribute.add(uat);
}
// passphrase is tested in PgpKeyOperationTest, just use empty here
parcel.mNewUnlock = new ChangeUnlockParcel(new Passphrase());
PgpKeyOperation op = new PgpKeyOperation(null);
PgpEditKeyResult result = op.createSecretKeyRing(parcel);
staticRing = result.getRing();
staticPubRing = staticRing.extractPublicKeyRing();
Assert.assertNotNull("initial test key creation must succeed", staticRing);
// we sleep here for a second, to make sure all new certificates have different timestamps
Thread.sleep(1000);
}
@Before
public void setUp() throws Exception {
// show Log.x messages in system.out
ShadowLog.stream = System.out;
ring = staticRing;
pubRing = staticPubRing;
}
@Test(expected = UnsupportedOperationException.class)
public void testPublicKeyItRemove() throws Exception {
Iterator<UncachedPublicKey> it = ring.getPublicKeys();
it.remove();
}
@Test(expected = PgpGeneralException.class)
public void testDecodeFromEmpty() throws Exception {
UncachedKeyRing.decodeFromData(new byte[0]);
}
@Test
public void testArmorIdentity() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ring.encodeArmored(out, "OpenKeychain");
Assert.assertArrayEquals("armor encoded and decoded ring should be identical to original",
ring.getEncoded(),
UncachedKeyRing.decodeFromData(out.toByteArray()).getEncoded());
}
@Test(expected = PgpGeneralException.class)
public void testDecodeEncodeMulti() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
// encode secret and public ring in here
ring.encodeArmored(out, "OpenKeychain");
pubRing.encodeArmored(out, "OpenKeychain");
IteratorWithIOThrow<UncachedKeyRing> it =
UncachedKeyRing.fromStream(new ByteArrayInputStream(out.toByteArray()));
Assert.assertTrue("there should be two rings in the stream", it.hasNext());
Assert.assertArrayEquals("first ring should be the first we put in",
ring.getEncoded(), it.next().getEncoded());
Assert.assertTrue("there should be two rings in the stream", it.hasNext());
Assert.assertArrayEquals("second ring should be the second we put in",
pubRing.getEncoded(), it.next().getEncoded());
Assert.assertFalse("there should be two rings in the stream", it.hasNext());
// this should fail with PgpGeneralException, since it expects exactly one ring
UncachedKeyRing.decodeFromData(out.toByteArray());
}
@Test(expected = RuntimeException.class)
public void testPublicExtractPublic() throws Exception {
// can't do this, either!
pubRing.extractPublicKeyRing();
}
@Test(expected = IOException.class)
public void testBrokenVersionCert() throws Throwable {
// this is a test for one of the patches we use on top of stock bouncycastle, which
// returns an IOException rather than a RuntimeException in case of a bad certificate
// version byte
readRingFromResource("/test-keys/broken_cert_version.asc");
}
UncachedKeyRing readRingFromResource(String name) throws Throwable {
return UncachedKeyRing.fromStream(UncachedKeyringTest.class.getResourceAsStream(name)).next();
}
}
| gpl-3.0 |
servinglynk/hmis-lynk-open-source | hmis-base-model/src/main/java/com/servinglynk/hmis/warehouse/base/dao/AccountConsentDao.java | 637 | package com.servinglynk.hmis.warehouse.base.dao;
import java.util.List;
import java.util.UUID;
import com.servinglynk.hmis.warehouse.model.base.AccountConsentEntity;
public interface AccountConsentDao {
AccountConsentEntity create(AccountConsentEntity consent);
AccountConsentEntity findByAccountIdAndTrustedAppId(UUID accountId, UUID trustedAppId);
AccountConsentEntity updateAccountConsent(AccountConsentEntity consent);
void deleteAccountConsent(AccountConsentEntity consent);
AccountConsentEntity findByToken(String consentToken);
List<AccountConsentEntity> findByAccountIdAndConsented(UUID id, boolean consented);
}
| mpl-2.0 |
mark47/OESandbox | app/src/us/mn/state/health/lims/testmanagement/action/TestVerificationNewbornUpdateAction.java | 21370 | /**
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations under
* the License.
*
* The Original Code is OpenELIS code.
*
* Copyright (C) The Minnesota Department of Health. All Rights Reserved.
*/
package us.mn.state.health.lims.testmanagement.action;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionRedirect;
import org.hibernate.Transaction;
import us.mn.state.health.lims.action.dao.ActionDAO;
import us.mn.state.health.lims.action.daoimpl.ActionDAOImpl;
import us.mn.state.health.lims.action.valueholder.Action;
import us.mn.state.health.lims.analysis.dao.AnalysisDAO;
import us.mn.state.health.lims.analysis.daoimpl.AnalysisDAOImpl;
import us.mn.state.health.lims.analysis.valueholder.Analysis;
import us.mn.state.health.lims.analysisqaevent.dao.AnalysisQaEventDAO;
import us.mn.state.health.lims.analysisqaevent.daoimpl.AnalysisQaEventDAOImpl;
import us.mn.state.health.lims.analysisqaevent.valueholder.AnalysisQaEvent;
import us.mn.state.health.lims.analysisqaeventaction.dao.AnalysisQaEventActionDAO;
import us.mn.state.health.lims.analysisqaeventaction.daoimpl.AnalysisQaEventActionDAOImpl;
import us.mn.state.health.lims.analysisqaeventaction.valueholder.AnalysisQaEventAction;
import us.mn.state.health.lims.common.action.BaseAction;
import us.mn.state.health.lims.common.action.BaseActionForm;
import us.mn.state.health.lims.common.exception.LIMSDuplicateRecordException;
import us.mn.state.health.lims.common.exception.LIMSRuntimeException;
import us.mn.state.health.lims.common.log.LogEvent;
import us.mn.state.health.lims.common.util.DateUtil;
import us.mn.state.health.lims.common.util.StringUtil;
import us.mn.state.health.lims.common.util.SystemConfiguration;
import us.mn.state.health.lims.common.util.resources.ResourceLocator;
import us.mn.state.health.lims.common.util.validator.ActionError;
import us.mn.state.health.lims.hibernate.HibernateUtil;
import us.mn.state.health.lims.login.valueholder.UserSessionData;
import us.mn.state.health.lims.qaevent.dao.QaEventDAO;
import us.mn.state.health.lims.qaevent.daoimpl.QaEventDAOImpl;
import us.mn.state.health.lims.qaevent.valueholder.QaEvent;
import us.mn.state.health.lims.sample.dao.SampleDAO;
import us.mn.state.health.lims.sample.daoimpl.SampleDAOImpl;
import us.mn.state.health.lims.sample.valueholder.Sample;
import us.mn.state.health.lims.sampleitem.dao.SampleItemDAO;
import us.mn.state.health.lims.sampleitem.daoimpl.SampleItemDAOImpl;
import us.mn.state.health.lims.sampleitem.valueholder.SampleItem;
import us.mn.state.health.lims.sampleorganization.dao.SampleOrganizationDAO;
import us.mn.state.health.lims.sampleorganization.daoimpl.SampleOrganizationDAOImpl;
import us.mn.state.health.lims.sampleorganization.valueholder.SampleOrganization;
import us.mn.state.health.lims.systemuser.dao.SystemUserDAO;
import us.mn.state.health.lims.systemuser.daoimpl.SystemUserDAOImpl;
import us.mn.state.health.lims.systemuser.valueholder.SystemUser;
import us.mn.state.health.lims.test.dao.TestDAO;
import us.mn.state.health.lims.test.daoimpl.TestDAOImpl;
import us.mn.state.health.lims.test.valueholder.Test;
import us.mn.state.health.lims.typeofsample.valueholder.TypeOfSample;
public class TestVerificationNewbornUpdateAction extends BaseAction {
protected ActionForward performAction(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
String forward = FWD_SUCCESS;
BaseActionForm dynaForm = (BaseActionForm) form;
Sample sample = new Sample();
SampleItem sampleItem = new SampleItem();
TypeOfSample typeOfSample = new TypeOfSample();
SampleOrganization sampleOrganization = new SampleOrganization();
String accessionNumber = (String) dynaForm.get("accessionNumber");
String stringOfTestIds = (String) dynaForm.get("selectedTestIds");
// set current date for validation of dates
Date today = Calendar.getInstance().getTime();
Locale locale = (Locale) request.getSession().getAttribute(
"org.apache.struts.action.LOCALE");
String dateAsText = DateUtil.formatDateAsText(today, locale);
Transaction tx = HibernateUtil.getSession().beginTransaction();
try {
SampleDAO sampleDAO = new SampleDAOImpl();
sample.setAccessionNumber(accessionNumber);
sampleDAO.getSampleByAccessionNumber(sample);
SampleItemDAO sampleItemDAO = new SampleItemDAOImpl();
AnalysisDAO analysisDAO = new AnalysisDAOImpl();
AnalysisQaEventDAO analysisQaEventDAO = new AnalysisQaEventDAOImpl();
AnalysisQaEventActionDAO analysisQaEventActionDAO = new AnalysisQaEventActionDAOImpl();
QaEventDAO qaEventDAO = new QaEventDAOImpl();
ActionDAO actionDAO = new ActionDAOImpl();
SampleOrganizationDAO sampleOrganizationDAO = new SampleOrganizationDAOImpl();
// bugzilla 1773 need to store sample not sampleId for use in
// sorting
sampleItem.setSample(sample);
sampleItemDAO.getDataBySample(sampleItem);
String[] listOfTestIds = stringOfTestIds.split(SystemConfiguration
.getInstance().getDefaultIdSeparator(), -1);
// bugzilla 1926 insert logging - get sysUserId from login module
UserSessionData usd = (UserSessionData)request.getSession().getAttribute(USER_SESSION_DATA);
String sysUserId = String.valueOf(usd.getSystemUserId());
//bugzilla 2481, 2496 Action Owner
SystemUser systemUser = new SystemUser();
systemUser.setId(sysUserId);
SystemUserDAO systemUserDAO = new SystemUserDAOImpl();
systemUserDAO.getData(systemUser);
for (int i = 0; i < listOfTestIds.length; i++) {
if (!StringUtil.isNullorNill(listOfTestIds[i])) {
Analysis analysis = new Analysis();
Test test = new Test();
String testId = (String) listOfTestIds[i];
test.setId(testId);
TestDAO testDAO = new TestDAOImpl();
testDAO.getData(test);
analysis.setTest(test);
analysis.setSampleItem(sampleItem);
analysis.setAnalysisType("TEST");
analysis.setStatus(SystemConfiguration.getInstance()
.getAnalysisStatusAssigned());
// bugzilla 1942
analysis.setIsReportable(test.getIsReportable());
// bugzilla 1926 insert logging - get sysUserId from login
// module
analysis.setSysUserId(sysUserId);
//bugzilla 2064
analysis.setRevision(SystemConfiguration.getInstance().getAnalysisDefaultRevision());
//bugzilla 2013 added duplicateCheck parameter
analysisDAO.insertData(analysis, true);
if (i == 1) {
if (!StringUtil.isNullorNill(sample.getStatus())
&& sample.getStatus().equals(
SystemConfiguration.getInstance()
.getSampleStatusReleased())) {
// bugzilla 1942: if sample status WAS released set
// it
// back to HSE2 complete
sample.setStatus(SystemConfiguration.getInstance()
.getSampleStatusEntry2Complete());
// bugzilla 1942 remove released date since we are
// returning to HSE2 completed status
sample.setReleasedDateForDisplay(null);
// bugzilla 1926 insert audit logging - get
// sysUserId
// from login module
sample.setSysUserId(sysUserId);
sampleDAO.updateData(sample);
}
}
}
}
// bugzilla 2028 qa event logic needs to be executed for new and
// existing analyses for this sample
// ADDITIONAL REQUIREMENT ADDED 8/30: only for HSE2 Completed Status (see bugzilla 2032)
boolean isSampleStatusReadyForQaEvent = false;
if (!StringUtil.isNullorNill(sample.getStatus()) && (sample.getStatus().equals(SystemConfiguration.getInstance().getSampleStatusReleased()))
|| sample.getStatus().equals(SystemConfiguration.getInstance().getSampleStatusEntry2Complete())) {
isSampleStatusReadyForQaEvent = true;
}
if (isSampleStatusReadyForQaEvent) {
// bugzilla 2028 need additional information for qa events
typeOfSample = sampleItem.getTypeOfSample();
sampleOrganization.setSampleId(sample.getId());
sampleOrganizationDAO.getDataBySample(sampleOrganization);
String submitterNumber = null;
if (sampleOrganization != null && sampleOrganization.getOrganization() != null) {
submitterNumber = sampleOrganization.getOrganization()
.getId();
}
//bugzilla 2227
List allAnalysesForSample = analysisDAO
.getMaxRevisionAnalysesBySample(sampleItem);
// bugzilla 2028 get the possible qa events
QaEvent qaEventForNoCollectionDate = new QaEvent();
qaEventForNoCollectionDate.setQaEventName(SystemConfiguration
.getInstance().getQaEventCodeForRequestNoCollectionDate());
qaEventForNoCollectionDate = qaEventDAO
.getQaEventByName(qaEventForNoCollectionDate);
QaEvent qaEventForNoSampleType = new QaEvent();
qaEventForNoSampleType.setQaEventName(SystemConfiguration
.getInstance().getQaEventCodeForRequestNoSampleType());
qaEventForNoSampleType = qaEventDAO
.getQaEventByName(qaEventForNoSampleType);
QaEvent qaEventForUnknownSubmitter = new QaEvent();
qaEventForUnknownSubmitter.setQaEventName(SystemConfiguration
.getInstance().getQaEventCodeForRequestUnknownSubmitter());
qaEventForUnknownSubmitter = qaEventDAO
.getQaEventByName(qaEventForUnknownSubmitter);
// end bugzilla 2028
// bugzilla 2028 get the possible qa event actions
Action actionForNoCollectionDate = new Action();
actionForNoCollectionDate.setCode(SystemConfiguration.getInstance()
.getQaEventActionCodeForRequestNoCollectionDate());
actionForNoCollectionDate = actionDAO
.getActionByCode(actionForNoCollectionDate);
Action actionForNoSampleType = new Action();
actionForNoSampleType.setCode(SystemConfiguration.getInstance()
.getQaEventActionCodeForRequestNoSampleType());
actionForNoSampleType = actionDAO
.getActionByCode(actionForNoSampleType);
Action actionForUnknownSubmitter = new Action();
actionForUnknownSubmitter.setCode(SystemConfiguration.getInstance()
.getQaEventActionCodeForRequestUnknownSubmitter());
actionForUnknownSubmitter = actionDAO
.getActionByCode(actionForUnknownSubmitter);
// end bugzilla 2028
for (int i = 0; i < allAnalysesForSample.size(); i++) {
Analysis analysis = (Analysis) allAnalysesForSample.get(i);
// bugzilla 2028 QA_EVENT COLLECTIONDATE
if (sample.getCollectionDate() == null) {
AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForNoCollectionDate);
analysisQaEvent = analysisQaEventDAO
.getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);
if (analysisQaEvent == null) {
analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForNoCollectionDate);
analysisQaEvent.setCompletedDate(null);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.insertData(analysisQaEvent);
} else {
if (analysisQaEvent.getCompletedDate() != null) {
analysisQaEvent.setCompletedDate(null);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.updateData(analysisQaEvent);
}
}
} else {
AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForNoCollectionDate);
analysisQaEvent = analysisQaEventDAO
.getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);
// if we don't find a record in ANALYSIS_QAEVENT (or
// completed date is not null) then this is already
// fixed
if (analysisQaEvent != null
&& analysisQaEvent.getCompletedDate() == null) {
AnalysisQaEventAction analysisQaEventAction = new AnalysisQaEventAction();
analysisQaEventAction
.setAnalysisQaEvent(analysisQaEvent);
analysisQaEventAction
.setAction(actionForNoCollectionDate);
analysisQaEventAction = analysisQaEventActionDAO
.getAnalysisQaEventActionByAnalysisQaEventAndAction(analysisQaEventAction);
// if we found a record in ANALYSIS_QAEVENT_ACTION
// then this has been fixed
if (analysisQaEventAction == null) {
// insert a record in ANALYSIS_QAEVENT_ACTION
AnalysisQaEventAction analQaEventAction = new AnalysisQaEventAction();
analQaEventAction
.setAnalysisQaEvent(analysisQaEvent);
analQaEventAction
.setAction(actionForNoCollectionDate);
analQaEventAction
.setCreatedDateForDisplay(dateAsText);
analQaEventAction.setSysUserId(sysUserId);
//bugzilla 2496
analQaEventAction.setSystemUser(systemUser);
analysisQaEventActionDAO
.insertData(analQaEventAction);
}
// update the found
// ANALYSIS_QAEVENT.COMPLETED_DATE with current
// date stamp
analysisQaEvent
.setCompletedDateForDisplay(dateAsText);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.updateData(analysisQaEvent);
}
}
// bugzilla 2028 QA_EVENT SAMPLETYPE
if (typeOfSample.getDescription().equals(SAMPLE_TYPE_NOT_GIVEN)) {
AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForNoSampleType);
analysisQaEvent = analysisQaEventDAO
.getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);
if (analysisQaEvent == null) {
analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForNoSampleType);
analysisQaEvent.setCompletedDate(null);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.insertData(analysisQaEvent);
} else {
if (analysisQaEvent.getCompletedDate() != null) {
analysisQaEvent.setCompletedDate(null);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.updateData(analysisQaEvent);
}
}
} else {
AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForNoSampleType);
analysisQaEvent = analysisQaEventDAO
.getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);
// if we don't find a record in ANALYSIS_QAEVENT (or
// completed date is not null) then this is already
// fixed
if (analysisQaEvent != null
&& analysisQaEvent.getCompletedDate() == null) {
AnalysisQaEventAction analysisQaEventAction = new AnalysisQaEventAction();
analysisQaEventAction
.setAnalysisQaEvent(analysisQaEvent);
analysisQaEventAction
.setAction(actionForNoSampleType);
analysisQaEventAction = analysisQaEventActionDAO
.getAnalysisQaEventActionByAnalysisQaEventAndAction(analysisQaEventAction);
// if we found a record in ANALYSIS_QAEVENT_ACTION
// then this has been fixed
if (analysisQaEventAction == null) {
// insert a record in ANALYSIS_QAEVENT_ACTION
AnalysisQaEventAction analQaEventAction = new AnalysisQaEventAction();
analQaEventAction
.setAnalysisQaEvent(analysisQaEvent);
analQaEventAction
.setAction(actionForNoSampleType);
analQaEventAction
.setCreatedDateForDisplay(dateAsText);
analQaEventAction.setSysUserId(sysUserId);
//bugzilla 2496
analQaEventAction.setSystemUser(systemUser);
analysisQaEventActionDAO
.insertData(analQaEventAction);
}
// update the found
// ANALYSIS_QAEVENT.COMPLETED_DATE with current
// date stamp
analysisQaEvent
.setCompletedDateForDisplay(dateAsText);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.updateData(analysisQaEvent);
}
}
// bugzilla 2028 QA_EVENT UNKNOWN SUBMITTER
if (!StringUtil.isNullorNill(submitterNumber) && submitterNumber.equals(SystemConfiguration.getInstance()
.getUnknownSubmitterNumberForQaEvent())) {
AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForUnknownSubmitter);
analysisQaEvent = analysisQaEventDAO
.getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);
if (analysisQaEvent == null) {
analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForUnknownSubmitter);
analysisQaEvent.setCompletedDate(null);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.insertData(analysisQaEvent);
} else {
if (analysisQaEvent.getCompletedDate() != null) {
analysisQaEvent.setCompletedDate(null);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.updateData(analysisQaEvent);
}
}
} else {
AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
analysisQaEvent.setAnalysis(analysis);
analysisQaEvent.setQaEvent(qaEventForUnknownSubmitter);
analysisQaEvent = analysisQaEventDAO
.getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);
// if we don't find a record in ANALYSIS_QAEVENT (or
// completed date is not null) then this is already
// fixed
if (analysisQaEvent != null
&& analysisQaEvent.getCompletedDate() == null) {
AnalysisQaEventAction analysisQaEventAction = new AnalysisQaEventAction();
analysisQaEventAction
.setAnalysisQaEvent(analysisQaEvent);
analysisQaEventAction
.setAction(actionForUnknownSubmitter);
analysisQaEventAction = analysisQaEventActionDAO
.getAnalysisQaEventActionByAnalysisQaEventAndAction(analysisQaEventAction);
// if we found a record in ANALYSIS_QAEVENT_ACTION
// then this has been fixed
if (analysisQaEventAction == null) {
// insert a record in ANALYSIS_QAEVENT_ACTION
AnalysisQaEventAction analQaEventAction = new AnalysisQaEventAction();
analQaEventAction
.setAnalysisQaEvent(analysisQaEvent);
analQaEventAction
.setAction(actionForUnknownSubmitter);
analQaEventAction
.setCreatedDateForDisplay(dateAsText);
analQaEventAction.setSysUserId(sysUserId);
//bugzilla 2496
analQaEventAction.setSystemUser(systemUser);
analysisQaEventActionDAO
.insertData(analQaEventAction);
}
// update the found
// ANALYSIS_QAEVENT.COMPLETED_DATE with current
// date stamp
analysisQaEvent
.setCompletedDateForDisplay(dateAsText);
analysisQaEvent.setSysUserId(sysUserId);
analysisQaEventDAO.updateData(analysisQaEvent);
}
}
}
}
tx.commit();
} catch (LIMSRuntimeException lre) {
//bugzilla 2154
LogEvent.logError("TestVerificationUpdateAction","performAction()",lre.toString());
tx.rollback();
ActionMessages errors = new ActionMessages();
ActionError error = null;
if (lre.getException() instanceof org.hibernate.StaleObjectStateException) {
error = new ActionError("errors.OptimisticLockException", null,
null);
} else {
//bugzilla 2013 added duplicateCheck parameter
if (lre.getException() instanceof LIMSDuplicateRecordException) {
String messageKey = "analysis.analysis";
String msg = ResourceLocator.getInstance()
.getMessageResources().getMessage(locale,
messageKey);
error = new ActionError("errors.DuplicateRecord",
msg, null);
} else {
error = new ActionError("errors.UpdateException", null,
null);
}
}
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
saveErrors(request, errors);
request.setAttribute(Globals.ERROR_KEY, errors);
request.setAttribute(ALLOW_EDITS_KEY, "false");
return mapping.findForward(FWD_FAIL);
} finally {
HibernateUtil.closeSession();
}
return getForward(mapping.findForward(forward));
}
protected String getPageTitleKey() {
return "testmanagement.newborn.title";
}
protected String getPageSubtitleKey() {
return "testmanagement.newborn.title";
}
protected ActionForward getForward(ActionForward forward) {
ActionRedirect redirect = new ActionRedirect(forward);
return redirect;
}
} | mpl-2.0 |
aborg0/RapidMiner-Unuk | src/liblinear/FeatureNode.java | 1168 | /*
* RapidMiner
*
* Copyright (C) 2001-2013 by Rapid-I and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapid-i.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package liblinear;
public class FeatureNode {
public final int index;
public final double value;
public FeatureNode( final int index, final double value ) {
if ( index < 1 ) throw new IllegalArgumentException("index must be >= 1");
this.index = index;
this.value = value;
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/RefMan/vo/domain/ReportsRequiredForPrintingVoAssembler.java | 20851 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5589.25814)
* WARNING: DO NOT MODIFY the content of this file
* Generated on 12/10/2015, 13:25
*
*/
package ims.RefMan.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Rory Fitzpatrick
*/
public class ReportsRequiredForPrintingVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.RefMan.vo.ReportsRequiredForPrintingVo copy(ims.RefMan.vo.ReportsRequiredForPrintingVo valueObjectDest, ims.RefMan.vo.ReportsRequiredForPrintingVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_ReportsRequiredForPrinting(valueObjectSrc.getID_ReportsRequiredForPrinting());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// PrintedDate
valueObjectDest.setPrintedDate(valueObjectSrc.getPrintedDate());
// PrintedBy
valueObjectDest.setPrintedBy(valueObjectSrc.getPrintedBy());
// ReportsRequired
valueObjectDest.setReportsRequired(valueObjectSrc.getReportsRequired());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #createReportsRequiredForPrintingVoCollectionFromReportsRequiredForPrinting(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.RefMan.domain.objects.ReportsRequiredForPrinting objects.
*/
public static ims.RefMan.vo.ReportsRequiredForPrintingVoCollection createReportsRequiredForPrintingVoCollectionFromReportsRequiredForPrinting(java.util.Set domainObjectSet)
{
return createReportsRequiredForPrintingVoCollectionFromReportsRequiredForPrinting(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.RefMan.domain.objects.ReportsRequiredForPrinting objects.
*/
public static ims.RefMan.vo.ReportsRequiredForPrintingVoCollection createReportsRequiredForPrintingVoCollectionFromReportsRequiredForPrinting(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.RefMan.vo.ReportsRequiredForPrintingVoCollection voList = new ims.RefMan.vo.ReportsRequiredForPrintingVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.RefMan.domain.objects.ReportsRequiredForPrinting domainObject = (ims.RefMan.domain.objects.ReportsRequiredForPrinting) iterator.next();
ims.RefMan.vo.ReportsRequiredForPrintingVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.RefMan.domain.objects.ReportsRequiredForPrinting objects.
*/
public static ims.RefMan.vo.ReportsRequiredForPrintingVoCollection createReportsRequiredForPrintingVoCollectionFromReportsRequiredForPrinting(java.util.List domainObjectList)
{
return createReportsRequiredForPrintingVoCollectionFromReportsRequiredForPrinting(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.RefMan.domain.objects.ReportsRequiredForPrinting objects.
*/
public static ims.RefMan.vo.ReportsRequiredForPrintingVoCollection createReportsRequiredForPrintingVoCollectionFromReportsRequiredForPrinting(DomainObjectMap map, java.util.List domainObjectList)
{
ims.RefMan.vo.ReportsRequiredForPrintingVoCollection voList = new ims.RefMan.vo.ReportsRequiredForPrintingVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.RefMan.domain.objects.ReportsRequiredForPrinting domainObject = (ims.RefMan.domain.objects.ReportsRequiredForPrinting) domainObjectList.get(i);
ims.RefMan.vo.ReportsRequiredForPrintingVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.RefMan.domain.objects.ReportsRequiredForPrinting set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set extractReportsRequiredForPrintingSet(ims.domain.ILightweightDomainFactory domainFactory, ims.RefMan.vo.ReportsRequiredForPrintingVoCollection voCollection)
{
return extractReportsRequiredForPrintingSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractReportsRequiredForPrintingSet(ims.domain.ILightweightDomainFactory domainFactory, ims.RefMan.vo.ReportsRequiredForPrintingVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.RefMan.vo.ReportsRequiredForPrintingVo vo = voCollection.get(i);
ims.RefMan.domain.objects.ReportsRequiredForPrinting domainObject = ReportsRequiredForPrintingVoAssembler.extractReportsRequiredForPrinting(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.RefMan.domain.objects.ReportsRequiredForPrinting list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List extractReportsRequiredForPrintingList(ims.domain.ILightweightDomainFactory domainFactory, ims.RefMan.vo.ReportsRequiredForPrintingVoCollection voCollection)
{
return extractReportsRequiredForPrintingList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractReportsRequiredForPrintingList(ims.domain.ILightweightDomainFactory domainFactory, ims.RefMan.vo.ReportsRequiredForPrintingVoCollection voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.RefMan.vo.ReportsRequiredForPrintingVo vo = voCollection.get(i);
ims.RefMan.domain.objects.ReportsRequiredForPrinting domainObject = ReportsRequiredForPrintingVoAssembler.extractReportsRequiredForPrinting(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.RefMan.domain.objects.ReportsRequiredForPrinting object.
* @param domainObject ims.RefMan.domain.objects.ReportsRequiredForPrinting
*/
public static ims.RefMan.vo.ReportsRequiredForPrintingVo create(ims.RefMan.domain.objects.ReportsRequiredForPrinting domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.RefMan.domain.objects.ReportsRequiredForPrinting object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.RefMan.vo.ReportsRequiredForPrintingVo create(DomainObjectMap map, ims.RefMan.domain.objects.ReportsRequiredForPrinting domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.RefMan.vo.ReportsRequiredForPrintingVo valueObject = (ims.RefMan.vo.ReportsRequiredForPrintingVo) map.getValueObject(domainObject, ims.RefMan.vo.ReportsRequiredForPrintingVo.class);
if ( null == valueObject )
{
valueObject = new ims.RefMan.vo.ReportsRequiredForPrintingVo(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.RefMan.domain.objects.ReportsRequiredForPrinting
*/
public static ims.RefMan.vo.ReportsRequiredForPrintingVo insert(ims.RefMan.vo.ReportsRequiredForPrintingVo valueObject, ims.RefMan.domain.objects.ReportsRequiredForPrinting domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.RefMan.domain.objects.ReportsRequiredForPrinting
*/
public static ims.RefMan.vo.ReportsRequiredForPrintingVo insert(DomainObjectMap map, ims.RefMan.vo.ReportsRequiredForPrintingVo valueObject, ims.RefMan.domain.objects.ReportsRequiredForPrinting domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_ReportsRequiredForPrinting(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// PrintedDate
java.util.Date PrintedDate = domainObject.getPrintedDate();
if ( null != PrintedDate )
{
valueObject.setPrintedDate(new ims.framework.utils.DateTime(PrintedDate) );
}
// PrintedBy
if (domainObject.getPrintedBy() != null)
{
if(domainObject.getPrintedBy() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already.
{
HibernateProxy p = (HibernateProxy) domainObject.getPrintedBy();
int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString());
valueObject.setPrintedBy(new ims.core.resource.people.vo.MemberOfStaffRefVo(id, -1));
}
else
{
valueObject.setPrintedBy(new ims.core.resource.people.vo.MemberOfStaffRefVo(domainObject.getPrintedBy().getId(), domainObject.getPrintedBy().getVersion()));
}
}
// ReportsRequired
ims.domain.lookups.LookupInstance instance3 = domainObject.getReportsRequired();
if ( null != instance3 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance3.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance3.getImage().getImageId(), instance3.getImage().getImagePath());
}
color = instance3.getColor();
if (color != null)
color.getValue();
ims.RefMan.vo.lookups.ReportNoteType voLookup3 = new ims.RefMan.vo.lookups.ReportNoteType(instance3.getId(),instance3.getText(), instance3.isActive(), null, img, color);
ims.RefMan.vo.lookups.ReportNoteType parentVoLookup3 = voLookup3;
ims.domain.lookups.LookupInstance parent3 = instance3.getParent();
while (parent3 != null)
{
if (parent3.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent3.getImage().getImageId(), parent3.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent3.getColor();
if (color != null)
color.getValue();
parentVoLookup3.setParent(new ims.RefMan.vo.lookups.ReportNoteType(parent3.getId(),parent3.getText(), parent3.isActive(), null, img, color));
parentVoLookup3 = parentVoLookup3.getParent();
parent3 = parent3.getParent();
}
valueObject.setReportsRequired(voLookup3);
}
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.RefMan.domain.objects.ReportsRequiredForPrinting extractReportsRequiredForPrinting(ims.domain.ILightweightDomainFactory domainFactory, ims.RefMan.vo.ReportsRequiredForPrintingVo valueObject)
{
return extractReportsRequiredForPrinting(domainFactory, valueObject, new HashMap());
}
public static ims.RefMan.domain.objects.ReportsRequiredForPrinting extractReportsRequiredForPrinting(ims.domain.ILightweightDomainFactory domainFactory, ims.RefMan.vo.ReportsRequiredForPrintingVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_ReportsRequiredForPrinting();
ims.RefMan.domain.objects.ReportsRequiredForPrinting domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.RefMan.domain.objects.ReportsRequiredForPrinting)domMap.get(valueObject);
}
// ims.RefMan.vo.ReportsRequiredForPrintingVo ID_ReportsRequiredForPrinting field is unknown
domainObject = new ims.RefMan.domain.objects.ReportsRequiredForPrinting();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_ReportsRequiredForPrinting());
if (domMap.get(key) != null)
{
return (ims.RefMan.domain.objects.ReportsRequiredForPrinting)domMap.get(key);
}
domainObject = (ims.RefMan.domain.objects.ReportsRequiredForPrinting) domainFactory.getDomainObject(ims.RefMan.domain.objects.ReportsRequiredForPrinting.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.getVersion_ReportsRequiredForPrinting());
ims.framework.utils.DateTime dateTime1 = valueObject.getPrintedDate();
java.util.Date value1 = null;
if ( dateTime1 != null )
{
value1 = dateTime1.getJavaDate();
}
domainObject.setPrintedDate(value1);
ims.core.resource.people.domain.objects.MemberOfStaff value2 = null;
if ( null != valueObject.getPrintedBy() )
{
if (valueObject.getPrintedBy().getBoId() == null)
{
if (domMap.get(valueObject.getPrintedBy()) != null)
{
value2 = (ims.core.resource.people.domain.objects.MemberOfStaff)domMap.get(valueObject.getPrintedBy());
}
}
else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field
{
value2 = domainObject.getPrintedBy();
}
else
{
value2 = (ims.core.resource.people.domain.objects.MemberOfStaff)domainFactory.getDomainObject(ims.core.resource.people.domain.objects.MemberOfStaff.class, valueObject.getPrintedBy().getBoId());
}
}
domainObject.setPrintedBy(value2);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value3 = null;
if ( null != valueObject.getReportsRequired() )
{
value3 =
domainFactory.getLookupInstance(valueObject.getReportsRequired().getID());
}
domainObject.setReportsRequired(value3);
return domainObject;
}
}
| agpl-3.0 |
heliumv/restapi | src/com/heliumv/factory/loader/ItemLoaderStockinfoSummary.java | 5122 | /*******************************************************************************
* HELIUM V, Open Source ERP software for sustained success
* at small and medium-sized enterprises.
* Copyright (C) 2004 - 2014 HELIUM V IT-Solutions GmbH
*
* 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 theLicense, or
* (at your option) any later version.
*
* According to sec. 7 of the GNU Affero General Public License, version 3,
* the terms of the AGPL are supplemented with the following terms:
*
* "HELIUM V" and "HELIUM 5" are registered trademarks of
* HELIUM V IT-Solutions GmbH. The licensing of the program under the
* AGPL does not imply a trademark license. Therefore any rights, title and
* interest in our trademarks remain entirely with us. If you want to propagate
* modified versions of the Program under the name "HELIUM V" or "HELIUM 5",
* you may only do so if you have a written permission by HELIUM V IT-Solutions
* GmbH (to acquire a permission please contact HELIUM V IT-Solutions
* at trademark@heliumv.com).
*
* 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/>.
*
* Contact: developers@heliumv.com
******************************************************************************/
package com.heliumv.factory.loader;
import java.rmi.RemoteException;
import javax.naming.NamingException;
import org.springframework.beans.factory.annotation.Autowired;
import com.heliumv.api.item.ItemEntryInternal;
import com.heliumv.api.item.StockAmountInfoEntry;
import com.heliumv.factory.IFehlmengeCall;
import com.heliumv.factory.ILagerCall;
import com.heliumv.factory.IReservierungCall;
import com.lp.server.artikel.service.ArtikelDto;
public class ItemLoaderStockinfoSummary implements IItemLoaderAttribute {
@Autowired
private ILagerCall lagerCall ;
@Autowired
private IReservierungCall reservierungCall ;
@Autowired
private IFehlmengeCall fehlmengeCall ;
@Override
public ItemEntryInternal load(ItemEntryInternal entry, ArtikelDto artikelDto) {
try {
StockAmountInfoEntry infoEntry = new StockAmountInfoEntry() ;
infoEntry.setStockAmount(lagerCall.getLagerstandAllerLagerEinesMandanten(
artikelDto.getIId(), false));
// BigDecimal paternoster = lagerCall.getPaternosterLagerstand(artikelDto.getIId());
infoEntry.setReservedAmount(reservierungCall
.getAnzahlReservierungen(artikelDto.getIId()));
infoEntry.setMissingAmount(fehlmengeCall
.getAnzahlFehlmengeEinesArtikels(artikelDto.getIId()));
infoEntry.setAvailableAmount(
infoEntry.getStockAmount().subtract(infoEntry.getReservedAmount())
.subtract(infoEntry.getMissingAmount())) ;
entry.setStockAmount(infoEntry.getAvailableAmount());
entry.setStockAmountInfo(infoEntry) ;
} catch(RemoteException e) {
} catch(NamingException e) {
}
return entry ;
}
/*
BigDecimal infertigung = DelegateFactory
.getInstance()
.getFertigungDelegate()
.getAnzahlInFertigung(
internalFrameArtikel.getArtikelDto().getIId());
wkvfInfertigung.setValue(Helper.formatZahl(infertigung, 2,
LPMain.getTheClient().getLocUi()));
BigDecimal bestellt = DelegateFactory
.getInstance()
.getArtikelbestelltDelegate()
.getAnzahlBestellt(
internalFrameArtikel.getArtikelDto().getIId());
wkvfBestellt.setValue(Helper.formatZahl(bestellt, 2, LPMain
.getTheClient().getLocUi()));
BigDecimal rahmenres = DelegateFactory
.getInstance()
.getReservierungDelegate()
.getAnzahlRahmenreservierungen(
internalFrameArtikel.getArtikelDto().getIId());
wkvfRahmenreserviert.setValue(Helper.formatZahl(rahmenres, 2,
LPMain.getTheClient().getLocUi()));
BigDecimal rahmenbestellt = null;
Hashtable<?, ?> htAnzahlRahmenbestellt = DelegateFactory
.getInstance()
.getArtikelbestelltDelegate()
.getAnzahlRahmenbestellt(
internalFrameArtikel.getArtikelDto().getIId());
if (htAnzahlRahmenbestellt
.containsKey(ArtikelbestelltFac.KEY_RAHMENBESTELLT_ANZAHL)) {
rahmenbestellt = (BigDecimal) htAnzahlRahmenbestellt
.get(ArtikelbestelltFac.KEY_RAHMENBESTELLT_ANZAHL);
wkvfRahmenbestellt.setValue(Helper
.formatZahl(rahmenbestellt, 2, LPMain
.getTheClient().getLocUi()));
}
BigDecimal rahmenbedarf = DelegateFactory
.getInstance()
.getRahmenbedarfeDelegate()
.getSummeAllerRahmenbedarfeEinesArtikels(
internalFrameArtikel.getArtikelDto().getIId());
wkvfRahmenbedarf.setValue(Helper.formatZahl(rahmenbedarf, 2,
LPMain.getTheClient().getLocUi()));
*
*/
}
| agpl-3.0 |
aborg0/RapidMiner-Unuk | src/com/rapidminer/operator/util/annotations/ExtractAnnotation.java | 4998 | /*
* RapidMiner
*
* Copyright (C) 2001-2013 by Rapid-I and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapid-i.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.util.annotations;
import java.util.List;
import com.rapidminer.MacroHandler;
import com.rapidminer.operator.Annotations;
import com.rapidminer.operator.IOObject;
import com.rapidminer.operator.Operator;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.UserError;
import com.rapidminer.operator.ports.InputPort;
import com.rapidminer.operator.ports.OutputPort;
import com.rapidminer.parameter.ParameterType;
import com.rapidminer.parameter.ParameterTypeBoolean;
import com.rapidminer.parameter.ParameterTypeString;
import com.rapidminer.parameter.conditions.BooleanParameterCondition;
/**
* @author Marius Helf
*
*/
public class ExtractAnnotation extends Operator {
private InputPort inputPort = getInputPorts().createPort("object", IOObject.class);
private OutputPort outputPort = getOutputPorts().createPort("object");
public static final String PARAMETER_MACRO_NAME = "macro";
public static final String PARAMETER_ANNOTATION = "annotation";
public static final String PARAMETER_EXTRACT_ALL = "extract_all";
public static final String PARAMETER_NAME_PREFIX = "name_prefix";
private static final String PARAMETER_FAIL_ON_MISSING = "fail_on_missing";
/**
* @param description
*/
public ExtractAnnotation(OperatorDescription description) {
super(description);
getTransformer().addPassThroughRule(inputPort, outputPort);
}
@Override
public void doWork() throws OperatorException {
IOObject data = inputPort.getData(IOObject.class);
Annotations annotations = data.getAnnotations();
MacroHandler macroHandler = getProcess().getMacroHandler();
if (getParameterAsBoolean(PARAMETER_EXTRACT_ALL)) {
String prefix = getParameterAsString(PARAMETER_NAME_PREFIX);
if (prefix == null) {
prefix = "";
}
for (String annotation : annotations.getDefinedAnnotationNames()) {
String macroName = prefix + annotation;
String value = annotations.getAnnotation(annotation);
macroHandler.addMacro(macroName, value);
}
} else {
String macroName = getParameterAsString(PARAMETER_MACRO_NAME);
String annotation = getParameterAsString(PARAMETER_ANNOTATION);
String value = annotations.getAnnotation(annotation);
if (value == null) {
if (getParameterAsBoolean(PARAMETER_FAIL_ON_MISSING)) {
throw new UserError(this, "annotations.annotation_not_exist", annotation);
} else {
value = "";
}
}
macroHandler.addMacro(macroName, value);
}
outputPort.deliver(inputPort.getData(IOObject.class));
}
@Override
public List<ParameterType> getParameterTypes() {
List<ParameterType> types = super.getParameterTypes();
ParameterType extractAll = new ParameterTypeBoolean(PARAMETER_EXTRACT_ALL, "If checked, all annotations are extracted to macros named the same as the annotations. Optionally, you can define a name prefix which is prepended to the macro names", false, true);
types.add(extractAll);
ParameterType type;
type = new ParameterTypeString(PARAMETER_MACRO_NAME, "Defines the name of the created macro", true, false);
type.registerDependencyCondition(new BooleanParameterCondition(this, PARAMETER_EXTRACT_ALL, true, false));
types.add(type);
type = new ParameterTypeString(PARAMETER_ANNOTATION, "The name of the annotation to be extracted", true, false);
type.registerDependencyCondition(new BooleanParameterCondition(this, PARAMETER_EXTRACT_ALL, true, false));
types.add(type);
type = new ParameterTypeBoolean(PARAMETER_FAIL_ON_MISSING, "If checked, the operator breaks if the specified annotation can't be found; if unchecked, in that case an empty macro will be created.", true, true);
type.registerDependencyCondition(new BooleanParameterCondition(this, PARAMETER_EXTRACT_ALL, false, false));
types.add(type);
type = new ParameterTypeString(PARAMETER_NAME_PREFIX, "A prefix which is prepended to all macro names", true, true);
type.registerDependencyCondition(new BooleanParameterCondition(this, PARAMETER_EXTRACT_ALL, false, true));
types.add(type);
return types;
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/RefMan/src/ims/refman/forms/electivelistdetails/AccessLogic.java | 2550 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Cristian Belciug using IMS Development Environment (version 1.80 build 5465.13953)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
package ims.RefMan.forms.electivelistdetails;
import java.io.Serializable;
public final class AccessLogic extends BaseAccessLogic implements Serializable
{
private static final long serialVersionUID = 1L;
public boolean isAccessible()
{
if(!super.isAccessible())
return false;
// TODO: Add your conditions here.
return true;
}
public boolean isReadOnly()
{
if(super.isReadOnly())
return true;
// TODO: Add your conditions here.
return false;
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/core/vo/CDSCriticalCareVoCollection.java | 8694 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.vo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import ims.framework.enumerations.SortOrder;
/**
* Linked to core.cds.CDSCriticalCareDetails business object (ID: 1104100005).
*/
public class CDSCriticalCareVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<CDSCriticalCareVo>
{
private static final long serialVersionUID = 1L;
private ArrayList<CDSCriticalCareVo> col = new ArrayList<CDSCriticalCareVo>();
public String getBoClassName()
{
return "ims.core.cds.domain.objects.CDSCriticalCareDetails";
}
public boolean add(CDSCriticalCareVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
return this.col.add(value);
}
return false;
}
public boolean add(int index, CDSCriticalCareVo value)
{
if(value == null)
return false;
if(this.col.indexOf(value) < 0)
{
this.col.add(index, value);
return true;
}
return false;
}
public void clear()
{
this.col.clear();
}
public void remove(int index)
{
this.col.remove(index);
}
public int size()
{
return this.col.size();
}
public int indexOf(CDSCriticalCareVo instance)
{
return col.indexOf(instance);
}
public CDSCriticalCareVo get(int index)
{
return this.col.get(index);
}
public boolean set(int index, CDSCriticalCareVo value)
{
if(value == null)
return false;
this.col.set(index, value);
return true;
}
public void remove(CDSCriticalCareVo instance)
{
if(instance != null)
{
int index = indexOf(instance);
if(index >= 0)
remove(index);
}
}
public boolean contains(CDSCriticalCareVo instance)
{
return indexOf(instance) >= 0;
}
public Object clone()
{
CDSCriticalCareVoCollection clone = new CDSCriticalCareVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
if(this.col.get(x) != null)
clone.col.add((CDSCriticalCareVo)this.col.get(x).clone());
else
clone.col.add(null);
}
return clone;
}
public boolean isValidated()
{
for(int x = 0; x < col.size(); x++)
if(!this.col.get(x).isValidated())
return false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(col.size() == 0)
return null;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
for(int x = 0; x < col.size(); x++)
{
String[] listOfOtherErrors = this.col.get(x).validate();
if(listOfOtherErrors != null)
{
for(int y = 0; y < listOfOtherErrors.length; y++)
{
listOfErrors.add(listOfOtherErrors[y]);
}
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
return null;
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
return result;
}
public CDSCriticalCareVoCollection sort()
{
return sort(SortOrder.ASCENDING);
}
public CDSCriticalCareVoCollection sort(boolean caseInsensitive)
{
return sort(SortOrder.ASCENDING, caseInsensitive);
}
public CDSCriticalCareVoCollection sort(SortOrder order)
{
return sort(new CDSCriticalCareVoComparator(order));
}
public CDSCriticalCareVoCollection sort(SortOrder order, boolean caseInsensitive)
{
return sort(new CDSCriticalCareVoComparator(order, caseInsensitive));
}
@SuppressWarnings("unchecked")
public CDSCriticalCareVoCollection sort(Comparator comparator)
{
Collections.sort(col, comparator);
return this;
}
public ims.core.cds.vo.CDSCriticalCareDetailsRefVoCollection toRefVoCollection()
{
ims.core.cds.vo.CDSCriticalCareDetailsRefVoCollection result = new ims.core.cds.vo.CDSCriticalCareDetailsRefVoCollection();
for(int x = 0; x < this.col.size(); x++)
{
result.add(this.col.get(x));
}
return result;
}
public CDSCriticalCareVo[] toArray()
{
CDSCriticalCareVo[] arr = new CDSCriticalCareVo[col.size()];
col.toArray(arr);
return arr;
}
public Iterator<CDSCriticalCareVo> iterator()
{
return col.iterator();
}
@Override
protected ArrayList getTypedCollection()
{
return col;
}
private class CDSCriticalCareVoComparator implements Comparator
{
private int direction = 1;
private boolean caseInsensitive = true;
public CDSCriticalCareVoComparator()
{
this(SortOrder.ASCENDING);
}
public CDSCriticalCareVoComparator(SortOrder order)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
}
public CDSCriticalCareVoComparator(SortOrder order, boolean caseInsensitive)
{
if (order == SortOrder.DESCENDING)
{
direction = -1;
}
this.caseInsensitive = caseInsensitive;
}
public int compare(Object obj1, Object obj2)
{
CDSCriticalCareVo voObj1 = (CDSCriticalCareVo)obj1;
CDSCriticalCareVo voObj2 = (CDSCriticalCareVo)obj2;
return direction*(voObj1.compareTo(voObj2, this.caseInsensitive));
}
public boolean equals(Object obj)
{
return false;
}
}
public ims.core.vo.beans.CDSCriticalCareVoBean[] getBeanCollection()
{
return getBeanCollectionArray();
}
public ims.core.vo.beans.CDSCriticalCareVoBean[] getBeanCollectionArray()
{
ims.core.vo.beans.CDSCriticalCareVoBean[] result = new ims.core.vo.beans.CDSCriticalCareVoBean[col.size()];
for(int i = 0; i < col.size(); i++)
{
CDSCriticalCareVo vo = ((CDSCriticalCareVo)col.get(i));
result[i] = (ims.core.vo.beans.CDSCriticalCareVoBean)vo.getBean();
}
return result;
}
public static CDSCriticalCareVoCollection buildFromBeanCollection(java.util.Collection beans)
{
CDSCriticalCareVoCollection coll = new CDSCriticalCareVoCollection();
if(beans == null)
return coll;
java.util.Iterator iter = beans.iterator();
while (iter.hasNext())
{
coll.add(((ims.core.vo.beans.CDSCriticalCareVoBean)iter.next()).buildVo());
}
return coll;
}
public static CDSCriticalCareVoCollection buildFromBeanCollection(ims.core.vo.beans.CDSCriticalCareVoBean[] beans)
{
CDSCriticalCareVoCollection coll = new CDSCriticalCareVoCollection();
if(beans == null)
return coll;
for(int x = 0; x < beans.length; x++)
{
coll.add(beans[x].buildVo());
}
return coll;
}
}
| agpl-3.0 |
auroreallibe/Silverpeas-Core | core-library/src/main/java/org/silverpeas/core/contribution/converter/DocumentFormatConversion.java | 3661 | /*
* Copyright (C) 2000 - 2016 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 received 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.core.contribution.converter;
import org.silverpeas.core.contribution.converter.option.FilterOption;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
/**
* This interface defines the ability to convert a document in a given format into a specified
* another format. An object with a such property should implement this interface. A converter
* takes
* into account a specific format of documents and provides the capability to convert it into
* another format. It can support only a subset of available conversions in Silverpeas.
*/
public interface DocumentFormatConversion {
/**
* Converts the specified document in the specified format. The format should be supported by the
* converter. If an error occurs while converting the specified file, then a runtime exception
* DocumentFormatConversionException is thrown.
* @param source the document to convert.
* @param inFormat the format into which the document has to be converted.
* @param options additional options such as "PageRange"
* @return the file with the converted document.
*/
File convert(File source, DocumentFormat inFormat, FilterOption... options);
/**
* Converts the specified document in the specified format. The format should be supported by the
* converter. If an error occurs while converting the specified file, then a runtime exception
* DocumentFormatConversionException is thrown.
* @param source the document to convert.
* @param destination the converted document.
* @param inFormat the format into which the document has to be converted.
* @return the destination file.
*/
File convert(File source, File destination, DocumentFormat inFormat, FilterOption... options);
/**
* Converts the specified inputstream/format in the specified outputstream/format.
* @param source the source stream to convert.
* @param inFormat the format from which the document has to be converted.
* @param destination the converted stream.
* @param outFormat the format into which the document has to be converted.
*/
void convert(InputStream source, DocumentFormat inFormat, OutputStream destination,
DocumentFormat outFormat, FilterOption... options);
/**
* Gets the formats of documents supported by the converter.
* @return an array with the different formats into which the object implementing this interface
* can convert a document.
*/
DocumentFormat[] getSupportedFormats();
}
| agpl-3.0 |
VietOpenCPS/opencps | portlets/opencps-portlet/docroot/WEB-INF/src/org/opencps/processmgt/portlet/ProcessOrderMenuPortlet.java | 5899 | /**
* OpenCPS is the open source Core Public Services software
* Copyright (C) 2016-present OpenCPS community
*
* 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
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package org.opencps.processmgt.portlet;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletModeException;
import javax.portlet.PortletRequest;
import javax.portlet.PortletURL;
import javax.portlet.WindowStateException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.opencps.processmgt.model.ProcessStep;
import org.opencps.processmgt.service.ProcessOrderLocalServiceUtil;
import org.opencps.processmgt.util.ProcessOrderUtils;
// import org.opencps.processmgt.util.ProcessOrderUtils;
import org.opencps.util.WebKeys;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.portlet.LiferayPortletMode;
import com.liferay.portal.kernel.portlet.LiferayWindowState;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.HtmlUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.model.User;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.PortletURLFactoryUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
/**
* @author khoavd
*/
public class ProcessOrderMenuPortlet extends MVCPortlet {
private Log _log = LogFactoryUtil
.getLog(ProcessOrderMenuPortlet.class);
public void menuAction(
ActionRequest actionRequest, ActionResponse actionResponse)
throws PortalException, SystemException, WindowStateException,
PortletModeException, IOException {
String mvcPath = ParamUtil
.getString(actionRequest, "mvcPath");
String active = ParamUtil
.getString(actionRequest, WebKeys.MENU_ACTIVE);
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest
.getAttribute(WebKeys.THEME_DISPLAY);
PortletURL renderUrl = PortletURLFactoryUtil
.create(actionRequest, themeDisplay
.getPortletDisplay().getId(), themeDisplay
.getPlid(),
PortletRequest.RENDER_PHASE);
renderUrl
.setWindowState(LiferayWindowState.NORMAL);
renderUrl
.setPortletMode(LiferayPortletMode.VIEW);
renderUrl
.setParameter("mvcPath", mvcPath);
HttpServletRequest httpRequest = PortalUtil
.getHttpServletRequest(actionRequest);
httpRequest
.getSession().invalidate();
httpRequest
.getSession().setAttribute(WebKeys.MENU_ACTIVE, active);
actionResponse
.sendRedirect(renderUrl
.toString());
}
public void menuCounterAction(
ActionRequest actionRequest, ActionResponse actionResponse)
throws PortalException, SystemException {
Map<String, String> par = new HashMap<String, String>();
User user = PortalUtil
.getUser(actionRequest);
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest
.getAttribute(WebKeys.THEME_DISPLAY);
long groupId = themeDisplay
.getScopeGroupId();
// now read your parameters, e.g. like this:
// long someParameter = ParamUtil.getLong(request, "someParameter");
List<ProcessStep> list = ProcessOrderUtils
.getProcessSteps(groupId, user
.getRoleIds());
long counterVal = 1;
for (ProcessStep item : list) {
counterVal = ProcessOrderLocalServiceUtil.countProcessOrder(0l, item.getProcessStepId(), 0, 0);
par.put("badge_" + item.getProcessStepId(), String.valueOf(counterVal));
counterVal = ProcessOrderLocalServiceUtil
.countProcessOrder(0l, item
.getProcessStepId(), themeDisplay.getUserId(), 0);
par
.put("badge_" + item
.getProcessStepId(), String
.valueOf(counterVal));
}
ajaxReturn(actionRequest, actionResponse, par);
}
private void ajaxReturn(
ActionRequest actionRequest, ActionResponse actionResponse,
Map<String, String> par) {
try {
HttpServletResponse httpResponse = PortalUtil
.getHttpServletResponse(actionResponse);
httpResponse
.setContentType("text");
JSONObject payloadJSON = JSONFactoryUtil
.createJSONObject();
for (Map.Entry<String, String> entry : par
.entrySet()) {
payloadJSON
.put(entry
.getKey(), HtmlUtil
.escape(entry
.getValue()));
}
httpResponse
.getWriter().print(payloadJSON
.toString());
httpResponse
.flushBuffer();
SessionMessages
.add(actionRequest, PortalUtil
.getPortletId(actionRequest) +
SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE);
SessionMessages
.add(actionRequest, PortalUtil
.getPortletId(actionRequest) +
SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_SUCCESS_MESSAGE);
}
catch (Exception e) {
_log.error(e);
}
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/scheduling/vo/SessionServiceProcedureConsultantVo.java | 8605 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.scheduling.vo;
public class SessionServiceProcedureConsultantVo extends ims.vo.ValueObject implements ims.vo.ImsCloneable, Comparable
{
private static final long serialVersionUID = 1L;
public SessionServiceProcedureConsultantVo()
{
}
public SessionServiceProcedureConsultantVo(ims.scheduling.vo.beans.SessionServiceProcedureConsultantVoBean bean)
{
this.service = bean.getService() == null ? null : bean.getService().buildVo();
this.procedure = bean.getProcedure() == null ? null : bean.getProcedure().buildVo();
this.consultant = bean.getConsultant() == null ? null : bean.getConsultant().buildVo();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.scheduling.vo.beans.SessionServiceProcedureConsultantVoBean bean)
{
this.service = bean.getService() == null ? null : bean.getService().buildVo(map);
this.procedure = bean.getProcedure() == null ? null : bean.getProcedure().buildVo(map);
this.consultant = bean.getConsultant() == null ? null : bean.getConsultant().buildVo(map);
}
public ims.vo.ValueObjectBean getBean()
{
return this.getBean(new ims.vo.ValueObjectBeanMap());
}
public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map)
{
ims.scheduling.vo.beans.SessionServiceProcedureConsultantVoBean bean = null;
if(map != null)
bean = (ims.scheduling.vo.beans.SessionServiceProcedureConsultantVoBean)map.getValueObjectBean(this);
if (bean == null)
{
bean = new ims.scheduling.vo.beans.SessionServiceProcedureConsultantVoBean();
map.addValueObjectBean(this, bean);
bean.populate(map, this);
}
return bean;
}
public boolean getServiceIsNotNull()
{
return this.service != null;
}
public ims.core.vo.ServiceLiteVo getService()
{
return this.service;
}
public void setService(ims.core.vo.ServiceLiteVo value)
{
this.isValidated = false;
this.service = value;
}
public boolean getProcedureIsNotNull()
{
return this.procedure != null;
}
public ims.core.vo.ProcedureLiteVo getProcedure()
{
return this.procedure;
}
public void setProcedure(ims.core.vo.ProcedureLiteVo value)
{
this.isValidated = false;
this.procedure = value;
}
public boolean getConsultantIsNotNull()
{
return this.consultant != null;
}
public ims.core.vo.HcpLiteVo getConsultant()
{
return this.consultant;
}
public void setConsultant(ims.core.vo.HcpLiteVo value)
{
this.isValidated = false;
this.consultant = value;
}
public final String getIItemText()
{
return toString();
}
public final Integer getBoId()
{
return null;
}
public final String getBoClassName()
{
return null;
}
public boolean equals(Object obj)
{
if(obj == null)
return false;
if(!(obj instanceof SessionServiceProcedureConsultantVo))
return false;
SessionServiceProcedureConsultantVo compareObj = (SessionServiceProcedureConsultantVo)obj;
if(this.getService() == null && compareObj.getService() != null)
return false;
if(this.getService() != null && compareObj.getService() == null)
return false;
if(this.getService() != null && compareObj.getService() != null)
return this.getService().equals(compareObj.getService());
return super.equals(obj);
}
public boolean isValidated()
{
if(this.isBusy)
return true;
this.isBusy = true;
if(!this.isValidated)
{
this.isBusy = false;
return false;
}
this.isBusy = false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(this.isBusy)
return null;
this.isBusy = true;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
{
this.isBusy = false;
this.isValidated = true;
return null;
}
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
this.isBusy = false;
this.isValidated = false;
return result;
}
public Object clone()
{
if(this.isBusy)
return this;
this.isBusy = true;
SessionServiceProcedureConsultantVo clone = new SessionServiceProcedureConsultantVo();
if(this.service == null)
clone.service = null;
else
clone.service = (ims.core.vo.ServiceLiteVo)this.service.clone();
if(this.procedure == null)
clone.procedure = null;
else
clone.procedure = (ims.core.vo.ProcedureLiteVo)this.procedure.clone();
if(this.consultant == null)
clone.consultant = null;
else
clone.consultant = (ims.core.vo.HcpLiteVo)this.consultant.clone();
clone.isValidated = this.isValidated;
this.isBusy = false;
return clone;
}
public int compareTo(Object obj)
{
return compareTo(obj, true);
}
public int compareTo(Object obj, boolean caseInsensitive)
{
if (obj == null)
{
return -1;
}
if(caseInsensitive); // this is to avoid eclipse warning only.
if (!(SessionServiceProcedureConsultantVo.class.isAssignableFrom(obj.getClass())))
{
throw new ClassCastException("A SessionServiceProcedureConsultantVo object cannot be compared an Object of type " + obj.getClass().getName());
}
SessionServiceProcedureConsultantVo compareObj = (SessionServiceProcedureConsultantVo)obj;
int retVal = 0;
if (retVal == 0)
{
if(this.getService() == null && compareObj.getService() != null)
return -1;
if(this.getService() != null && compareObj.getService() == null)
return 1;
if(this.getService() != null && compareObj.getService() != null)
retVal = this.getService().compareTo(compareObj.getService());
}
return retVal;
}
public synchronized static int generateValueObjectUniqueID()
{
return ims.vo.ValueObject.generateUniqueID();
}
public int countFieldsWithValue()
{
int count = 0;
if(this.service != null)
count++;
if(this.procedure != null)
count++;
if(this.consultant != null)
count++;
return count;
}
public int countValueObjectFields()
{
return 3;
}
protected ims.core.vo.ServiceLiteVo service;
protected ims.core.vo.ProcedureLiteVo procedure;
protected ims.core.vo.HcpLiteVo consultant;
private boolean isValidated = false;
private boolean isBusy = false;
}
| agpl-3.0 |
bitsquare/bitsquare | core/src/main/java/bisq/core/btc/wallet/NonBsqCoinSelector.java | 2815 | /*
* This file is part of Bisq.
*
* Bisq 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.
*
* Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.core.btc.wallet;
import bisq.core.dao.state.DaoStateService;
import bisq.core.dao.state.model.blockchain.TxOutputKey;
import bisq.core.user.Preferences;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionConfidence;
import org.bitcoinj.core.TransactionOutput;
import javax.inject.Inject;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
/**
* We use a specialized version of the CoinSelector based on the DefaultCoinSelector implementation.
* We lookup for spendable outputs which matches our address of our address.
*/
@Slf4j
public class NonBsqCoinSelector extends BisqDefaultCoinSelector {
private DaoStateService daoStateService;
@Setter
private Preferences preferences;
@Inject
public NonBsqCoinSelector(DaoStateService daoStateService) {
super(false);
this.daoStateService = daoStateService;
}
@Override
protected boolean isTxOutputSpendable(TransactionOutput output) {
// output.getParentTransaction() cannot be null as it is checked in calling method
Transaction parentTransaction = output.getParentTransaction();
if (parentTransaction == null)
return false;
// It is important to not allow pending txs as otherwise unconfirmed BSQ txs would be considered nonBSQ as
// below outputIsNotInBsqState would be true.
if (parentTransaction.getConfidence().getConfidenceType() != TransactionConfidence.ConfidenceType.BUILDING)
return false;
TxOutputKey key = new TxOutputKey(parentTransaction.getTxId().toString(), output.getIndex());
// It might be that we received BTC in a non-BSQ tx so that will not be stored in out state and not found.
// So we consider any txOutput which is not in the state as BTC output.
return !daoStateService.existsTxOutput(key) || daoStateService.isRejectedIssuanceOutput(key);
}
// Prevent usage of dust attack utxos
@Override
protected boolean isDustAttackUtxo(TransactionOutput output) {
return output.getValue().value < preferences.getIgnoreDustThreshold();
}
}
| agpl-3.0 |
MetaWebDesign/Editor | Editor_MWD.diagram/src/Metawebdesign/metawebdesign/diagram/part/MetaWebDesignDiagramActionBarContributor.java | 1026 | package Metawebdesign.metawebdesign.diagram.part;
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramActionBarContributor;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
/**
* @generated
*/
public class MetaWebDesignDiagramActionBarContributor extends
DiagramActionBarContributor {
/**
* @generated
*/
protected Class getEditorClass() {
return Metawebdesign.metawebdesign.diagram.part.MetaWebDesignDiagramEditor.class;
}
/**
* @generated
*/
protected String getEditorId() {
return Metawebdesign.metawebdesign.diagram.part.MetaWebDesignDiagramEditor.ID;
}
/**
* @generated
*/
public void init(IActionBars bars, IWorkbenchPage page) {
super.init(bars, page);
// print preview
IMenuManager fileMenu = bars.getMenuManager().findMenuUsingPath(
IWorkbenchActionConstants.M_FILE);
assert fileMenu != null;
fileMenu.remove("pageSetupAction"); //$NON-NLS-1$
}
}
| agpl-3.0 |
gortiz/mongowp | mongowp-core/src/main/java/com/torodb/mongowp/exceptions/NoReplicationEnabledException.java | 1051 | /*
* Copyright 2014 8Kdata Technology
*
* 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.torodb.mongowp.exceptions;
import com.torodb.mongowp.ErrorCode;
/**
*
*/
public class NoReplicationEnabledException extends MongoException {
private static final long serialVersionUID = -31440686092347454L;
public NoReplicationEnabledException() {
super(ErrorCode.NO_REPLICATION_ENABLED);
}
public NoReplicationEnabledException(String customMessage) {
super(customMessage, ErrorCode.NO_REPLICATION_ENABLED);
}
}
| agpl-3.0 |
aihua/opennms | opennms-services/src/main/java/org/opennms/netmgt/poller/jmx/PollerdMBean.java | 2719 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2002-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.poller.jmx;
import org.opennms.netmgt.daemon.BaseOnmsMBean;
/**
* <p>PollerdMBean interface.</p>
*
* @author ranger
* @version $Id: $
*/
public interface PollerdMBean extends BaseOnmsMBean {
/**
* Returns the number of polls that have been executed so far (counter).
*
* @return the number of polls that have been executed
*/
public long getNumPolls();
/**
* @return The number of currently active poller threads
*/
public long getActiveThreads();
/**
* @return The cumulative number of polling tasks scheduled since poller startup
*/
public long getTasksTotal();
/**
* @return The cumulative number of polling tasks completed since poller startup
*/
public long getTasksCompleted();
/**
* @return The ratio of completed to scheduled polling tasks since poller startup
*/
public double getTaskCompletionRatio();
/**
*
* @return The largest size of the poller thread pool since poller startup
*/
public long getPeakPoolThreads();
/**
* @return The maximum number of threads allowed in the poller's thread pool
*/
public long getMaxPoolThreads();
/**
* @return The number of pending tasks on our ExecutorService
*/
public long getTaskQueuePendingCount();
/**
* @return The number of open slots on our ExecutorService queue.
*/
public long getTaskQueueRemainingCapacity();
}
| agpl-3.0 |
IMS-MAXIMS/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/core/vo/PatientHomeSituationVo.java | 28732 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.vo;
/**
* Linked to clinical.PatientHomeSituation business object (ID: 1072100065).
*/
public class PatientHomeSituationVo extends ims.clinical.vo.PatientHomeSituationRefVo implements ims.vo.ImsCloneable, Comparable
{
private static final long serialVersionUID = 1L;
public PatientHomeSituationVo()
{
}
public PatientHomeSituationVo(Integer id, int version)
{
super(id, version);
}
public PatientHomeSituationVo(ims.core.vo.beans.PatientHomeSituationVoBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.carecontext = bean.getCareContext() == null ? null : new ims.core.admin.vo.CareContextRefVo(new Integer(bean.getCareContext().getId()), bean.getCareContext().getVersion());
this.clinicalcontact = bean.getClinicalContact() == null ? null : new ims.core.admin.vo.ClinicalContactRefVo(new Integer(bean.getClinicalContact().getId()), bean.getClinicalContact().getVersion());
this.accomtype = bean.getAccomType() == null ? null : ims.clinical.vo.lookups.HSAccomType.buildLookup(bean.getAccomType());
this.accomtypeother = bean.getAccomTypeOther();
this.ownership = bean.getOwnership() == null ? null : ims.clinical.vo.lookups.HSOwnership.buildLookup(bean.getOwnership());
this.supervisedby = bean.getSupervisedBy() == null ? null : ims.clinical.vo.lookups.HSSupervisedBy.buildLookup(bean.getSupervisedBy());
this.supervisename = bean.getSuperviseName();
this.superviseaddress = bean.getSuperviseAddress();
this.supervisephoneno = bean.getSupervisePhoneNo();
this.floorlevel = bean.getFloorLevel() == null ? null : ims.clinical.vo.lookups.HSFloorLevel.buildLookup(bean.getFloorLevel());
this.lift = bean.getLift() == null ? null : ims.clinical.vo.lookups.HSLift.buildLookup(bean.getLift());
this.stairs = bean.getStairs() == null ? null : ims.clinical.vo.lookups.HSStairs.buildLookup(bean.getStairs());
this.stairslift = bean.getStairsLift();
this.rails = bean.getRails() == null ? null : ims.clinical.vo.lookups.HSRails.buildLookup(bean.getRails());
this.railside = bean.getRailSide() == null ? null : ims.clinical.vo.lookups.HSRailsSide.buildLookup(bean.getRailSide());
this.bathroom = bean.getBathroom();
this.bathroomlocation = bean.getBathroomLocation() == null ? null : ims.clinical.vo.lookups.HSBathroomLocation.buildLookup(bean.getBathroomLocation());
this.toilet = bean.getToilet();
this.toiletlocation = bean.getToiletLocation() == null ? null : ims.clinical.vo.lookups.HSToiletLocation.buildLookup(bean.getToiletLocation());
this.shower = bean.getShower();
this.showerlocation = bean.getShowerLocation() == null ? null : ims.clinical.vo.lookups.HSShowerLocation.buildLookup(bean.getShowerLocation());
this.housekeys = bean.getHouseKeys();
this.spareset = bean.getSpareSet();
this.authoringinformation = bean.getAuthoringInformation() == null ? null : bean.getAuthoringInformation().buildVo();
this.liveswith = bean.getLivesWith() == null ? null : ims.core.vo.lookups.LivesWith.buildLookup(bean.getLivesWith());
this.liveswithdetails = bean.getLivesWithDetails();
this.fittocareforpatient = bean.getFitToCareForPatient() == null ? null : ims.core.vo.lookups.YesNoUnknown.buildLookup(bean.getFitToCareForPatient());
this.fittotakehome = bean.getFitToTakeHome() == null ? null : ims.core.vo.lookups.YesNoUnknown.buildLookup(bean.getFitToTakeHome());
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.core.vo.beans.PatientHomeSituationVoBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.carecontext = bean.getCareContext() == null ? null : new ims.core.admin.vo.CareContextRefVo(new Integer(bean.getCareContext().getId()), bean.getCareContext().getVersion());
this.clinicalcontact = bean.getClinicalContact() == null ? null : new ims.core.admin.vo.ClinicalContactRefVo(new Integer(bean.getClinicalContact().getId()), bean.getClinicalContact().getVersion());
this.accomtype = bean.getAccomType() == null ? null : ims.clinical.vo.lookups.HSAccomType.buildLookup(bean.getAccomType());
this.accomtypeother = bean.getAccomTypeOther();
this.ownership = bean.getOwnership() == null ? null : ims.clinical.vo.lookups.HSOwnership.buildLookup(bean.getOwnership());
this.supervisedby = bean.getSupervisedBy() == null ? null : ims.clinical.vo.lookups.HSSupervisedBy.buildLookup(bean.getSupervisedBy());
this.supervisename = bean.getSuperviseName();
this.superviseaddress = bean.getSuperviseAddress();
this.supervisephoneno = bean.getSupervisePhoneNo();
this.floorlevel = bean.getFloorLevel() == null ? null : ims.clinical.vo.lookups.HSFloorLevel.buildLookup(bean.getFloorLevel());
this.lift = bean.getLift() == null ? null : ims.clinical.vo.lookups.HSLift.buildLookup(bean.getLift());
this.stairs = bean.getStairs() == null ? null : ims.clinical.vo.lookups.HSStairs.buildLookup(bean.getStairs());
this.stairslift = bean.getStairsLift();
this.rails = bean.getRails() == null ? null : ims.clinical.vo.lookups.HSRails.buildLookup(bean.getRails());
this.railside = bean.getRailSide() == null ? null : ims.clinical.vo.lookups.HSRailsSide.buildLookup(bean.getRailSide());
this.bathroom = bean.getBathroom();
this.bathroomlocation = bean.getBathroomLocation() == null ? null : ims.clinical.vo.lookups.HSBathroomLocation.buildLookup(bean.getBathroomLocation());
this.toilet = bean.getToilet();
this.toiletlocation = bean.getToiletLocation() == null ? null : ims.clinical.vo.lookups.HSToiletLocation.buildLookup(bean.getToiletLocation());
this.shower = bean.getShower();
this.showerlocation = bean.getShowerLocation() == null ? null : ims.clinical.vo.lookups.HSShowerLocation.buildLookup(bean.getShowerLocation());
this.housekeys = bean.getHouseKeys();
this.spareset = bean.getSpareSet();
this.authoringinformation = bean.getAuthoringInformation() == null ? null : bean.getAuthoringInformation().buildVo(map);
this.liveswith = bean.getLivesWith() == null ? null : ims.core.vo.lookups.LivesWith.buildLookup(bean.getLivesWith());
this.liveswithdetails = bean.getLivesWithDetails();
this.fittocareforpatient = bean.getFitToCareForPatient() == null ? null : ims.core.vo.lookups.YesNoUnknown.buildLookup(bean.getFitToCareForPatient());
this.fittotakehome = bean.getFitToTakeHome() == null ? null : ims.core.vo.lookups.YesNoUnknown.buildLookup(bean.getFitToTakeHome());
}
public ims.vo.ValueObjectBean getBean()
{
return this.getBean(new ims.vo.ValueObjectBeanMap());
}
public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map)
{
ims.core.vo.beans.PatientHomeSituationVoBean bean = null;
if(map != null)
bean = (ims.core.vo.beans.PatientHomeSituationVoBean)map.getValueObjectBean(this);
if (bean == null)
{
bean = new ims.core.vo.beans.PatientHomeSituationVoBean();
map.addValueObjectBean(this, bean);
bean.populate(map, this);
}
return bean;
}
public Object getFieldValueByFieldName(String fieldName)
{
if(fieldName == null)
throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name");
fieldName = fieldName.toUpperCase();
if(fieldName.equals("CARECONTEXT"))
return getCareContext();
if(fieldName.equals("CLINICALCONTACT"))
return getClinicalContact();
if(fieldName.equals("ACCOMTYPE"))
return getAccomType();
if(fieldName.equals("ACCOMTYPEOTHER"))
return getAccomTypeOther();
if(fieldName.equals("OWNERSHIP"))
return getOwnership();
if(fieldName.equals("SUPERVISEDBY"))
return getSupervisedBy();
if(fieldName.equals("SUPERVISENAME"))
return getSuperviseName();
if(fieldName.equals("SUPERVISEADDRESS"))
return getSuperviseAddress();
if(fieldName.equals("SUPERVISEPHONENO"))
return getSupervisePhoneNo();
if(fieldName.equals("FLOORLEVEL"))
return getFloorLevel();
if(fieldName.equals("LIFT"))
return getLift();
if(fieldName.equals("STAIRS"))
return getStairs();
if(fieldName.equals("STAIRSLIFT"))
return getStairsLift();
if(fieldName.equals("RAILS"))
return getRails();
if(fieldName.equals("RAILSIDE"))
return getRailSide();
if(fieldName.equals("BATHROOM"))
return getBathroom();
if(fieldName.equals("BATHROOMLOCATION"))
return getBathroomLocation();
if(fieldName.equals("TOILET"))
return getToilet();
if(fieldName.equals("TOILETLOCATION"))
return getToiletLocation();
if(fieldName.equals("SHOWER"))
return getShower();
if(fieldName.equals("SHOWERLOCATION"))
return getShowerLocation();
if(fieldName.equals("HOUSEKEYS"))
return getHouseKeys();
if(fieldName.equals("SPARESET"))
return getSpareSet();
if(fieldName.equals("AUTHORINGINFORMATION"))
return getAuthoringInformation();
if(fieldName.equals("LIVESWITH"))
return getLivesWith();
if(fieldName.equals("LIVESWITHDETAILS"))
return getLivesWithDetails();
if(fieldName.equals("FITTOCAREFORPATIENT"))
return getFitToCareForPatient();
if(fieldName.equals("FITTOTAKEHOME"))
return getFitToTakeHome();
return super.getFieldValueByFieldName(fieldName);
}
public boolean getCareContextIsNotNull()
{
return this.carecontext != null;
}
public ims.core.admin.vo.CareContextRefVo getCareContext()
{
return this.carecontext;
}
public void setCareContext(ims.core.admin.vo.CareContextRefVo value)
{
this.isValidated = false;
this.carecontext = value;
}
public boolean getClinicalContactIsNotNull()
{
return this.clinicalcontact != null;
}
public ims.core.admin.vo.ClinicalContactRefVo getClinicalContact()
{
return this.clinicalcontact;
}
public void setClinicalContact(ims.core.admin.vo.ClinicalContactRefVo value)
{
this.isValidated = false;
this.clinicalcontact = value;
}
public boolean getAccomTypeIsNotNull()
{
return this.accomtype != null;
}
public ims.clinical.vo.lookups.HSAccomType getAccomType()
{
return this.accomtype;
}
public void setAccomType(ims.clinical.vo.lookups.HSAccomType value)
{
this.isValidated = false;
this.accomtype = value;
}
public boolean getAccomTypeOtherIsNotNull()
{
return this.accomtypeother != null;
}
public String getAccomTypeOther()
{
return this.accomtypeother;
}
public static int getAccomTypeOtherMaxLength()
{
return 255;
}
public void setAccomTypeOther(String value)
{
this.isValidated = false;
this.accomtypeother = value;
}
public boolean getOwnershipIsNotNull()
{
return this.ownership != null;
}
public ims.clinical.vo.lookups.HSOwnership getOwnership()
{
return this.ownership;
}
public void setOwnership(ims.clinical.vo.lookups.HSOwnership value)
{
this.isValidated = false;
this.ownership = value;
}
public boolean getSupervisedByIsNotNull()
{
return this.supervisedby != null;
}
public ims.clinical.vo.lookups.HSSupervisedBy getSupervisedBy()
{
return this.supervisedby;
}
public void setSupervisedBy(ims.clinical.vo.lookups.HSSupervisedBy value)
{
this.isValidated = false;
this.supervisedby = value;
}
public boolean getSuperviseNameIsNotNull()
{
return this.supervisename != null;
}
public String getSuperviseName()
{
return this.supervisename;
}
public static int getSuperviseNameMaxLength()
{
return 255;
}
public void setSuperviseName(String value)
{
this.isValidated = false;
this.supervisename = value;
}
public boolean getSuperviseAddressIsNotNull()
{
return this.superviseaddress != null;
}
public String getSuperviseAddress()
{
return this.superviseaddress;
}
public static int getSuperviseAddressMaxLength()
{
return 255;
}
public void setSuperviseAddress(String value)
{
this.isValidated = false;
this.superviseaddress = value;
}
public boolean getSupervisePhoneNoIsNotNull()
{
return this.supervisephoneno != null;
}
public String getSupervisePhoneNo()
{
return this.supervisephoneno;
}
public static int getSupervisePhoneNoMaxLength()
{
return 255;
}
public void setSupervisePhoneNo(String value)
{
this.isValidated = false;
this.supervisephoneno = value;
}
public boolean getFloorLevelIsNotNull()
{
return this.floorlevel != null;
}
public ims.clinical.vo.lookups.HSFloorLevel getFloorLevel()
{
return this.floorlevel;
}
public void setFloorLevel(ims.clinical.vo.lookups.HSFloorLevel value)
{
this.isValidated = false;
this.floorlevel = value;
}
public boolean getLiftIsNotNull()
{
return this.lift != null;
}
public ims.clinical.vo.lookups.HSLift getLift()
{
return this.lift;
}
public void setLift(ims.clinical.vo.lookups.HSLift value)
{
this.isValidated = false;
this.lift = value;
}
public boolean getStairsIsNotNull()
{
return this.stairs != null;
}
public ims.clinical.vo.lookups.HSStairs getStairs()
{
return this.stairs;
}
public void setStairs(ims.clinical.vo.lookups.HSStairs value)
{
this.isValidated = false;
this.stairs = value;
}
public boolean getStairsLiftIsNotNull()
{
return this.stairslift != null;
}
public String getStairsLift()
{
return this.stairslift;
}
public static int getStairsLiftMaxLength()
{
return 255;
}
public void setStairsLift(String value)
{
this.isValidated = false;
this.stairslift = value;
}
public boolean getRailsIsNotNull()
{
return this.rails != null;
}
public ims.clinical.vo.lookups.HSRails getRails()
{
return this.rails;
}
public void setRails(ims.clinical.vo.lookups.HSRails value)
{
this.isValidated = false;
this.rails = value;
}
public boolean getRailSideIsNotNull()
{
return this.railside != null;
}
public ims.clinical.vo.lookups.HSRailsSide getRailSide()
{
return this.railside;
}
public void setRailSide(ims.clinical.vo.lookups.HSRailsSide value)
{
this.isValidated = false;
this.railside = value;
}
public boolean getBathroomIsNotNull()
{
return this.bathroom != null;
}
public String getBathroom()
{
return this.bathroom;
}
public static int getBathroomMaxLength()
{
return 255;
}
public void setBathroom(String value)
{
this.isValidated = false;
this.bathroom = value;
}
public boolean getBathroomLocationIsNotNull()
{
return this.bathroomlocation != null;
}
public ims.clinical.vo.lookups.HSBathroomLocation getBathroomLocation()
{
return this.bathroomlocation;
}
public void setBathroomLocation(ims.clinical.vo.lookups.HSBathroomLocation value)
{
this.isValidated = false;
this.bathroomlocation = value;
}
public boolean getToiletIsNotNull()
{
return this.toilet != null;
}
public String getToilet()
{
return this.toilet;
}
public static int getToiletMaxLength()
{
return 255;
}
public void setToilet(String value)
{
this.isValidated = false;
this.toilet = value;
}
public boolean getToiletLocationIsNotNull()
{
return this.toiletlocation != null;
}
public ims.clinical.vo.lookups.HSToiletLocation getToiletLocation()
{
return this.toiletlocation;
}
public void setToiletLocation(ims.clinical.vo.lookups.HSToiletLocation value)
{
this.isValidated = false;
this.toiletlocation = value;
}
public boolean getShowerIsNotNull()
{
return this.shower != null;
}
public String getShower()
{
return this.shower;
}
public static int getShowerMaxLength()
{
return 255;
}
public void setShower(String value)
{
this.isValidated = false;
this.shower = value;
}
public boolean getShowerLocationIsNotNull()
{
return this.showerlocation != null;
}
public ims.clinical.vo.lookups.HSShowerLocation getShowerLocation()
{
return this.showerlocation;
}
public void setShowerLocation(ims.clinical.vo.lookups.HSShowerLocation value)
{
this.isValidated = false;
this.showerlocation = value;
}
public boolean getHouseKeysIsNotNull()
{
return this.housekeys != null;
}
public String getHouseKeys()
{
return this.housekeys;
}
public static int getHouseKeysMaxLength()
{
return 255;
}
public void setHouseKeys(String value)
{
this.isValidated = false;
this.housekeys = value;
}
public boolean getSpareSetIsNotNull()
{
return this.spareset != null;
}
public String getSpareSet()
{
return this.spareset;
}
public static int getSpareSetMaxLength()
{
return 255;
}
public void setSpareSet(String value)
{
this.isValidated = false;
this.spareset = value;
}
public boolean getAuthoringInformationIsNotNull()
{
return this.authoringinformation != null;
}
public ims.core.vo.AuthoringInformationVo getAuthoringInformation()
{
return this.authoringinformation;
}
public void setAuthoringInformation(ims.core.vo.AuthoringInformationVo value)
{
this.isValidated = false;
this.authoringinformation = value;
}
public boolean getLivesWithIsNotNull()
{
return this.liveswith != null;
}
public ims.core.vo.lookups.LivesWith getLivesWith()
{
return this.liveswith;
}
public void setLivesWith(ims.core.vo.lookups.LivesWith value)
{
this.isValidated = false;
this.liveswith = value;
}
public boolean getLivesWithDetailsIsNotNull()
{
return this.liveswithdetails != null;
}
public String getLivesWithDetails()
{
return this.liveswithdetails;
}
public static int getLivesWithDetailsMaxLength()
{
return 255;
}
public void setLivesWithDetails(String value)
{
this.isValidated = false;
this.liveswithdetails = value;
}
public boolean getFitToCareForPatientIsNotNull()
{
return this.fittocareforpatient != null;
}
public ims.core.vo.lookups.YesNoUnknown getFitToCareForPatient()
{
return this.fittocareforpatient;
}
public void setFitToCareForPatient(ims.core.vo.lookups.YesNoUnknown value)
{
this.isValidated = false;
this.fittocareforpatient = value;
}
public boolean getFitToTakeHomeIsNotNull()
{
return this.fittotakehome != null;
}
public ims.core.vo.lookups.YesNoUnknown getFitToTakeHome()
{
return this.fittotakehome;
}
public void setFitToTakeHome(ims.core.vo.lookups.YesNoUnknown value)
{
this.isValidated = false;
this.fittotakehome = value;
}
public boolean isValidated()
{
if(this.isBusy)
return true;
this.isBusy = true;
if(!this.isValidated)
{
this.isBusy = false;
return false;
}
if(this.authoringinformation != null)
{
if(!this.authoringinformation.isValidated())
{
this.isBusy = false;
return false;
}
}
this.isBusy = false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(this.isBusy)
return null;
this.isBusy = true;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
if(this.carecontext == null)
listOfErrors.add("CareContext is mandatory");
if(this.authoringinformation != null)
{
String[] listOfOtherErrors = this.authoringinformation.validate();
if(listOfOtherErrors != null)
{
for(int x = 0; x < listOfOtherErrors.length; x++)
{
listOfErrors.add(listOfOtherErrors[x]);
}
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
{
this.isBusy = false;
this.isValidated = true;
return null;
}
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
this.isBusy = false;
this.isValidated = false;
return result;
}
public void clearIDAndVersion()
{
this.id = null;
this.version = 0;
}
public Object clone()
{
if(this.isBusy)
return this;
this.isBusy = true;
PatientHomeSituationVo clone = new PatientHomeSituationVo(this.id, this.version);
clone.carecontext = this.carecontext;
clone.clinicalcontact = this.clinicalcontact;
if(this.accomtype == null)
clone.accomtype = null;
else
clone.accomtype = (ims.clinical.vo.lookups.HSAccomType)this.accomtype.clone();
clone.accomtypeother = this.accomtypeother;
if(this.ownership == null)
clone.ownership = null;
else
clone.ownership = (ims.clinical.vo.lookups.HSOwnership)this.ownership.clone();
if(this.supervisedby == null)
clone.supervisedby = null;
else
clone.supervisedby = (ims.clinical.vo.lookups.HSSupervisedBy)this.supervisedby.clone();
clone.supervisename = this.supervisename;
clone.superviseaddress = this.superviseaddress;
clone.supervisephoneno = this.supervisephoneno;
if(this.floorlevel == null)
clone.floorlevel = null;
else
clone.floorlevel = (ims.clinical.vo.lookups.HSFloorLevel)this.floorlevel.clone();
if(this.lift == null)
clone.lift = null;
else
clone.lift = (ims.clinical.vo.lookups.HSLift)this.lift.clone();
if(this.stairs == null)
clone.stairs = null;
else
clone.stairs = (ims.clinical.vo.lookups.HSStairs)this.stairs.clone();
clone.stairslift = this.stairslift;
if(this.rails == null)
clone.rails = null;
else
clone.rails = (ims.clinical.vo.lookups.HSRails)this.rails.clone();
if(this.railside == null)
clone.railside = null;
else
clone.railside = (ims.clinical.vo.lookups.HSRailsSide)this.railside.clone();
clone.bathroom = this.bathroom;
if(this.bathroomlocation == null)
clone.bathroomlocation = null;
else
clone.bathroomlocation = (ims.clinical.vo.lookups.HSBathroomLocation)this.bathroomlocation.clone();
clone.toilet = this.toilet;
if(this.toiletlocation == null)
clone.toiletlocation = null;
else
clone.toiletlocation = (ims.clinical.vo.lookups.HSToiletLocation)this.toiletlocation.clone();
clone.shower = this.shower;
if(this.showerlocation == null)
clone.showerlocation = null;
else
clone.showerlocation = (ims.clinical.vo.lookups.HSShowerLocation)this.showerlocation.clone();
clone.housekeys = this.housekeys;
clone.spareset = this.spareset;
if(this.authoringinformation == null)
clone.authoringinformation = null;
else
clone.authoringinformation = (ims.core.vo.AuthoringInformationVo)this.authoringinformation.clone();
if(this.liveswith == null)
clone.liveswith = null;
else
clone.liveswith = (ims.core.vo.lookups.LivesWith)this.liveswith.clone();
clone.liveswithdetails = this.liveswithdetails;
if(this.fittocareforpatient == null)
clone.fittocareforpatient = null;
else
clone.fittocareforpatient = (ims.core.vo.lookups.YesNoUnknown)this.fittocareforpatient.clone();
if(this.fittotakehome == null)
clone.fittotakehome = null;
else
clone.fittotakehome = (ims.core.vo.lookups.YesNoUnknown)this.fittotakehome.clone();
clone.isValidated = this.isValidated;
this.isBusy = false;
return clone;
}
public int compareTo(Object obj)
{
return compareTo(obj, true);
}
public int compareTo(Object obj, boolean caseInsensitive)
{
if (obj == null)
{
return -1;
}
if(caseInsensitive); // this is to avoid eclipse warning only.
if (!(PatientHomeSituationVo.class.isAssignableFrom(obj.getClass())))
{
throw new ClassCastException("A PatientHomeSituationVo object cannot be compared an Object of type " + obj.getClass().getName());
}
if (this.id == null)
return 1;
if (((PatientHomeSituationVo)obj).getBoId() == null)
return -1;
return this.id.compareTo(((PatientHomeSituationVo)obj).getBoId());
}
public synchronized static int generateValueObjectUniqueID()
{
return ims.vo.ValueObject.generateUniqueID();
}
public int countFieldsWithValue()
{
int count = 0;
if(this.accomtype != null)
count++;
if(this.accomtypeother != null)
count++;
if(this.ownership != null)
count++;
if(this.supervisedby != null)
count++;
if(this.supervisename != null)
count++;
if(this.superviseaddress != null)
count++;
if(this.supervisephoneno != null)
count++;
if(this.floorlevel != null)
count++;
if(this.lift != null)
count++;
if(this.stairs != null)
count++;
if(this.stairslift != null)
count++;
if(this.rails != null)
count++;
if(this.railside != null)
count++;
if(this.bathroom != null)
count++;
if(this.bathroomlocation != null)
count++;
if(this.toilet != null)
count++;
if(this.toiletlocation != null)
count++;
if(this.shower != null)
count++;
if(this.showerlocation != null)
count++;
if(this.housekeys != null)
count++;
if(this.spareset != null)
count++;
if(this.liveswith != null)
count++;
if(this.liveswithdetails != null)
count++;
if(this.fittocareforpatient != null)
count++;
if(this.fittotakehome != null)
count++;
return count;
}
public int countValueObjectFields()
{
return 25;
}
protected ims.core.admin.vo.CareContextRefVo carecontext;
protected ims.core.admin.vo.ClinicalContactRefVo clinicalcontact;
protected ims.clinical.vo.lookups.HSAccomType accomtype;
protected String accomtypeother;
protected ims.clinical.vo.lookups.HSOwnership ownership;
protected ims.clinical.vo.lookups.HSSupervisedBy supervisedby;
protected String supervisename;
protected String superviseaddress;
protected String supervisephoneno;
protected ims.clinical.vo.lookups.HSFloorLevel floorlevel;
protected ims.clinical.vo.lookups.HSLift lift;
protected ims.clinical.vo.lookups.HSStairs stairs;
protected String stairslift;
protected ims.clinical.vo.lookups.HSRails rails;
protected ims.clinical.vo.lookups.HSRailsSide railside;
protected String bathroom;
protected ims.clinical.vo.lookups.HSBathroomLocation bathroomlocation;
protected String toilet;
protected ims.clinical.vo.lookups.HSToiletLocation toiletlocation;
protected String shower;
protected ims.clinical.vo.lookups.HSShowerLocation showerlocation;
protected String housekeys;
protected String spareset;
protected ims.core.vo.AuthoringInformationVo authoringinformation;
protected ims.core.vo.lookups.LivesWith liveswith;
protected String liveswithdetails;
protected ims.core.vo.lookups.YesNoUnknown fittocareforpatient;
protected ims.core.vo.lookups.YesNoUnknown fittotakehome;
private boolean isValidated = false;
private boolean isBusy = false;
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/ocrr/vo/SpecimenNameVo.java | 16242 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.ocrr.vo;
/**
* Linked to OCRR.OrderingResults.OrderSpecimen business object (ID: 1070100010).
*/
public class SpecimenNameVo extends ims.ocrr.orderingresults.vo.OrderSpecimenRefVo implements ims.vo.ImsCloneable, Comparable, ims.vo.interfaces.IOrderSpecimen
{
private static final long serialVersionUID = 1L;
public SpecimenNameVo()
{
}
public SpecimenNameVo(Integer id, int version)
{
super(id, version);
}
public SpecimenNameVo(ims.ocrr.vo.beans.SpecimenNameVoBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.specimensource = bean.getSpecimenSource() == null ? null : ims.ocrr.vo.lookups.SpecimenType.buildLookup(bean.getSpecimenSource());
if(bean.getPathResult() != null)
{
this.pathresult = new ims.ocrr.orderingresults.vo.PathResultDetailsRefVoCollection();
for(int pathresult_i = 0; pathresult_i < bean.getPathResult().length; pathresult_i++)
{
this.pathresult.add(new ims.ocrr.orderingresults.vo.PathResultDetailsRefVo(new Integer(bean.getPathResult()[pathresult_i].getId()), bean.getPathResult()[pathresult_i].getVersion()));
}
}
this.colldatetimefiller = bean.getCollDateTimeFiller() == null ? null : bean.getCollDateTimeFiller().buildDateTime();
this.fillerordnum = bean.getFillerOrdNum();
this.receiveddatetime = bean.getReceivedDateTime() == null ? null : bean.getReceivedDateTime().buildDateTime();
this.coltimefillersupplied = bean.getColTimeFillerSupplied();
this.receivedtimesupplied = bean.getReceivedTimeSupplied();
this.dftspecimenresulted = bean.getDftSpecimenResulted() == null ? null : bean.getDftSpecimenResulted().buildDateTime();
this.dftspecimenresultedtimesupplied = bean.getDftSpecimenResultedTimeSupplied();
this.sitecd = bean.getSiteCd() == null ? null : ims.ocrr.vo.lookups.SpecimenSite.buildLookup(bean.getSiteCd());
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.ocrr.vo.beans.SpecimenNameVoBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.specimensource = bean.getSpecimenSource() == null ? null : ims.ocrr.vo.lookups.SpecimenType.buildLookup(bean.getSpecimenSource());
if(bean.getPathResult() != null)
{
this.pathresult = new ims.ocrr.orderingresults.vo.PathResultDetailsRefVoCollection();
for(int pathresult_i = 0; pathresult_i < bean.getPathResult().length; pathresult_i++)
{
this.pathresult.add(new ims.ocrr.orderingresults.vo.PathResultDetailsRefVo(new Integer(bean.getPathResult()[pathresult_i].getId()), bean.getPathResult()[pathresult_i].getVersion()));
}
}
this.colldatetimefiller = bean.getCollDateTimeFiller() == null ? null : bean.getCollDateTimeFiller().buildDateTime();
this.fillerordnum = bean.getFillerOrdNum();
this.receiveddatetime = bean.getReceivedDateTime() == null ? null : bean.getReceivedDateTime().buildDateTime();
this.coltimefillersupplied = bean.getColTimeFillerSupplied();
this.receivedtimesupplied = bean.getReceivedTimeSupplied();
this.dftspecimenresulted = bean.getDftSpecimenResulted() == null ? null : bean.getDftSpecimenResulted().buildDateTime();
this.dftspecimenresultedtimesupplied = bean.getDftSpecimenResultedTimeSupplied();
this.sitecd = bean.getSiteCd() == null ? null : ims.ocrr.vo.lookups.SpecimenSite.buildLookup(bean.getSiteCd());
}
public ims.vo.ValueObjectBean getBean()
{
return this.getBean(new ims.vo.ValueObjectBeanMap());
}
public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map)
{
ims.ocrr.vo.beans.SpecimenNameVoBean bean = null;
if(map != null)
bean = (ims.ocrr.vo.beans.SpecimenNameVoBean)map.getValueObjectBean(this);
if (bean == null)
{
bean = new ims.ocrr.vo.beans.SpecimenNameVoBean();
map.addValueObjectBean(this, bean);
bean.populate(map, this);
}
return bean;
}
public Object getFieldValueByFieldName(String fieldName)
{
if(fieldName == null)
throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name");
fieldName = fieldName.toUpperCase();
if(fieldName.equals("SPECIMENSOURCE"))
return getSpecimenSource();
if(fieldName.equals("PATHRESULT"))
return getPathResult();
if(fieldName.equals("COLLDATETIMEFILLER"))
return getCollDateTimeFiller();
if(fieldName.equals("FILLERORDNUM"))
return getFillerOrdNum();
if(fieldName.equals("RECEIVEDDATETIME"))
return getReceivedDateTime();
if(fieldName.equals("COLTIMEFILLERSUPPLIED"))
return getColTimeFillerSupplied();
if(fieldName.equals("RECEIVEDTIMESUPPLIED"))
return getReceivedTimeSupplied();
if(fieldName.equals("DFTSPECIMENRESULTED"))
return getDftSpecimenResulted();
if(fieldName.equals("DFTSPECIMENRESULTEDTIMESUPPLIED"))
return getDftSpecimenResultedTimeSupplied();
if(fieldName.equals("SITECD"))
return getSiteCd();
return super.getFieldValueByFieldName(fieldName);
}
public boolean getSpecimenSourceIsNotNull()
{
return this.specimensource != null;
}
public ims.ocrr.vo.lookups.SpecimenType getSpecimenSource()
{
return this.specimensource;
}
public void setSpecimenSource(ims.ocrr.vo.lookups.SpecimenType value)
{
this.isValidated = false;
this.specimensource = value;
}
public boolean getPathResultIsNotNull()
{
return this.pathresult != null;
}
public ims.ocrr.orderingresults.vo.PathResultDetailsRefVoCollection getPathResult()
{
return this.pathresult;
}
public void setPathResult(ims.ocrr.orderingresults.vo.PathResultDetailsRefVoCollection value)
{
this.isValidated = false;
this.pathresult = value;
}
public boolean getCollDateTimeFillerIsNotNull()
{
return this.colldatetimefiller != null;
}
public ims.framework.utils.DateTime getCollDateTimeFiller()
{
return this.colldatetimefiller;
}
public void setCollDateTimeFiller(ims.framework.utils.DateTime value)
{
this.isValidated = false;
this.colldatetimefiller = value;
}
public boolean getFillerOrdNumIsNotNull()
{
return this.fillerordnum != null;
}
public String getFillerOrdNum()
{
return this.fillerordnum;
}
public static int getFillerOrdNumMaxLength()
{
return 20;
}
public void setFillerOrdNum(String value)
{
this.isValidated = false;
this.fillerordnum = value;
}
public boolean getReceivedDateTimeIsNotNull()
{
return this.receiveddatetime != null;
}
public ims.framework.utils.DateTime getReceivedDateTime()
{
return this.receiveddatetime;
}
public void setReceivedDateTime(ims.framework.utils.DateTime value)
{
this.isValidated = false;
this.receiveddatetime = value;
}
public boolean getColTimeFillerSuppliedIsNotNull()
{
return this.coltimefillersupplied != null;
}
public Boolean getColTimeFillerSupplied()
{
return this.coltimefillersupplied;
}
public void setColTimeFillerSupplied(Boolean value)
{
this.isValidated = false;
this.coltimefillersupplied = value;
}
public boolean getReceivedTimeSuppliedIsNotNull()
{
return this.receivedtimesupplied != null;
}
public Boolean getReceivedTimeSupplied()
{
return this.receivedtimesupplied;
}
public void setReceivedTimeSupplied(Boolean value)
{
this.isValidated = false;
this.receivedtimesupplied = value;
}
public boolean getDftSpecimenResultedIsNotNull()
{
return this.dftspecimenresulted != null;
}
public ims.framework.utils.DateTime getDftSpecimenResulted()
{
return this.dftspecimenresulted;
}
public void setDftSpecimenResulted(ims.framework.utils.DateTime value)
{
this.isValidated = false;
this.dftspecimenresulted = value;
}
public boolean getDftSpecimenResultedTimeSuppliedIsNotNull()
{
return this.dftspecimenresultedtimesupplied != null;
}
public Boolean getDftSpecimenResultedTimeSupplied()
{
return this.dftspecimenresultedtimesupplied;
}
public void setDftSpecimenResultedTimeSupplied(Boolean value)
{
this.isValidated = false;
this.dftspecimenresultedtimesupplied = value;
}
public boolean getSiteCdIsNotNull()
{
return this.sitecd != null;
}
public ims.ocrr.vo.lookups.SpecimenSite getSiteCd()
{
return this.sitecd;
}
public void setSiteCd(ims.ocrr.vo.lookups.SpecimenSite value)
{
this.isValidated = false;
this.sitecd = value;
}
/**
* IOrderSpecimen interface methods
*/
public String getIOrderSpecimenSource()
{
if(this.specimensource != null)
return this.specimensource.getText();
return null;
}
public Integer getIOrderSpecimenId()
{
return this.id;
}
public ims.framework.utils.DateTime getIOrderSpecimenCollectionDateTime()
{
return this.colldatetimefiller;
}
public ims.framework.utils.DateTime getIOrderSpecimenReceivedDateTime()
{
return this.receiveddatetime;
}
public String getIOrderSpecimenFillerOrdNum()
{
return this.fillerordnum;
}
public Boolean getIOrderSpecimenCollectionTimeSupplied()
{
return this.coltimefillersupplied;
}
public Boolean getIOrderSpecimenReceivedTimeSupplied()
{
return this.receivedtimesupplied;
}
public ims.framework.utils.DateTime getIOrderSpecimenResultedDate()
{
return this.dftspecimenresulted;
}
public Boolean getIOrderSpecimenResultedTimeSupplied()
{
return this.dftspecimenresultedtimesupplied;
}
public boolean isValidated()
{
if(this.isBusy)
return true;
this.isBusy = true;
if(!this.isValidated)
{
this.isBusy = false;
return false;
}
this.isBusy = false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(this.isBusy)
return null;
this.isBusy = true;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
if(this.specimensource == null)
listOfErrors.add("SpecimenSource is mandatory");
if(this.fillerordnum != null)
if(this.fillerordnum.length() > 20)
listOfErrors.add("The length of the field [fillerordnum] in the value object [ims.ocrr.vo.SpecimenNameVo] is too big. It should be less or equal to 20");
int errorCount = listOfErrors.size();
if(errorCount == 0)
{
this.isBusy = false;
this.isValidated = true;
return null;
}
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
this.isBusy = false;
this.isValidated = false;
return result;
}
public void clearIDAndVersion()
{
this.id = null;
this.version = 0;
}
public Object clone()
{
if(this.isBusy)
return this;
this.isBusy = true;
SpecimenNameVo clone = new SpecimenNameVo(this.id, this.version);
if(this.specimensource == null)
clone.specimensource = null;
else
clone.specimensource = (ims.ocrr.vo.lookups.SpecimenType)this.specimensource.clone();
clone.pathresult = this.pathresult;
if(this.colldatetimefiller == null)
clone.colldatetimefiller = null;
else
clone.colldatetimefiller = (ims.framework.utils.DateTime)this.colldatetimefiller.clone();
clone.fillerordnum = this.fillerordnum;
if(this.receiveddatetime == null)
clone.receiveddatetime = null;
else
clone.receiveddatetime = (ims.framework.utils.DateTime)this.receiveddatetime.clone();
clone.coltimefillersupplied = this.coltimefillersupplied;
clone.receivedtimesupplied = this.receivedtimesupplied;
if(this.dftspecimenresulted == null)
clone.dftspecimenresulted = null;
else
clone.dftspecimenresulted = (ims.framework.utils.DateTime)this.dftspecimenresulted.clone();
clone.dftspecimenresultedtimesupplied = this.dftspecimenresultedtimesupplied;
if(this.sitecd == null)
clone.sitecd = null;
else
clone.sitecd = (ims.ocrr.vo.lookups.SpecimenSite)this.sitecd.clone();
clone.isValidated = this.isValidated;
this.isBusy = false;
return clone;
}
public int compareTo(Object obj)
{
return compareTo(obj, true);
}
public int compareTo(Object obj, boolean caseInsensitive)
{
if (obj == null)
{
return -1;
}
if(caseInsensitive); // this is to avoid eclipse warning only.
if (!(SpecimenNameVo.class.isAssignableFrom(obj.getClass())))
{
throw new ClassCastException("A SpecimenNameVo object cannot be compared an Object of type " + obj.getClass().getName());
}
if (this.id == null)
return 1;
if (((SpecimenNameVo)obj).getBoId() == null)
return -1;
return this.id.compareTo(((SpecimenNameVo)obj).getBoId());
}
public synchronized static int generateValueObjectUniqueID()
{
return ims.vo.ValueObject.generateUniqueID();
}
public int countFieldsWithValue()
{
int count = 0;
if(this.specimensource != null)
count++;
if(this.pathresult != null)
count++;
if(this.colldatetimefiller != null)
count++;
if(this.fillerordnum != null)
count++;
if(this.receiveddatetime != null)
count++;
if(this.coltimefillersupplied != null)
count++;
if(this.receivedtimesupplied != null)
count++;
if(this.dftspecimenresulted != null)
count++;
if(this.dftspecimenresultedtimesupplied != null)
count++;
if(this.sitecd != null)
count++;
return count;
}
public int countValueObjectFields()
{
return 10;
}
protected ims.ocrr.vo.lookups.SpecimenType specimensource;
protected ims.ocrr.orderingresults.vo.PathResultDetailsRefVoCollection pathresult;
protected ims.framework.utils.DateTime colldatetimefiller;
protected String fillerordnum;
protected ims.framework.utils.DateTime receiveddatetime;
protected Boolean coltimefillersupplied;
protected Boolean receivedtimesupplied;
protected ims.framework.utils.DateTime dftspecimenresulted;
protected Boolean dftspecimenresultedtimesupplied;
protected ims.ocrr.vo.lookups.SpecimenSite sitecd;
private boolean isValidated = false;
private boolean isBusy = false;
}
| agpl-3.0 |
erdincay/ejb | src/com/lp/server/artikel/fastlanereader/generated/FLRArtikelgruppe.java | 5006 | /*******************************************************************************
* HELIUM V, Open Source ERP software for sustained success
* at small and medium-sized enterprises.
* Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH
*
* 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 theLicense, or
* (at your option) any later version.
*
* According to sec. 7 of the GNU Affero General Public License, version 3,
* the terms of the AGPL are supplemented with the following terms:
*
* "HELIUM V" and "HELIUM 5" are registered trademarks of
* HELIUM V IT-Solutions GmbH. The licensing of the program under the
* AGPL does not imply a trademark license. Therefore any rights, title and
* interest in our trademarks remain entirely with us. If you want to propagate
* modified versions of the Program under the name "HELIUM V" or "HELIUM 5",
* you may only do so if you have a written permission by HELIUM V IT-Solutions
* GmbH (to acquire a permission please contact HELIUM V IT-Solutions
* at trademark@heliumv.com).
*
* 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/>.
*
* Contact: developers@heliumv.com
*******************************************************************************/
package com.lp.server.artikel.fastlanereader.generated;
import java.io.Serializable;
import java.util.Set;
import org.apache.commons.lang.builder.ToStringBuilder;
import com.lp.server.finanz.fastlanereader.generated.FLRFinanzKonto;
/** @author Hibernate CodeGenerator */
public class FLRArtikelgruppe implements Serializable {
/** identifier field */
private Integer i_id;
/** nullable persistent field */
private String c_nr;
/** nullable persistent field */
private Integer artgru_i_id;
/** persistent field */
private String mandant_c_nr;
/** nullable persistent field */
private com.lp.server.artikel.fastlanereader.generated.FLRArtikelgruppe flrartikelgruppe;
/** nullable persistent field */
private FLRFinanzKonto flrkonto;
/** persistent field */
private Set artikelgruppesprset;
/** full constructor */
public FLRArtikelgruppe(String c_nr, Integer artgru_i_id, String mandant_c_nr, com.lp.server.artikel.fastlanereader.generated.FLRArtikelgruppe flrartikelgruppe, FLRFinanzKonto flrkonto, Set artikelgruppesprset) {
this.c_nr = c_nr;
this.artgru_i_id = artgru_i_id;
this.mandant_c_nr = mandant_c_nr;
this.flrartikelgruppe = flrartikelgruppe;
this.flrkonto = flrkonto;
this.artikelgruppesprset = artikelgruppesprset;
}
/** default constructor */
public FLRArtikelgruppe() {
}
/** minimal constructor */
public FLRArtikelgruppe(String mandant_c_nr, Set artikelgruppesprset) {
this.mandant_c_nr = mandant_c_nr;
this.artikelgruppesprset = artikelgruppesprset;
}
public FLRArtikelgruppe(Integer i_id, Integer artgru_i_id) {
this.i_id = i_id;
this.artgru_i_id = artgru_i_id;
}
public Integer getI_id() {
return this.i_id;
}
public void setI_id(Integer i_id) {
this.i_id = i_id;
}
public String getC_nr() {
return this.c_nr;
}
public void setC_nr(String c_nr) {
this.c_nr = c_nr;
}
public Integer getArtgru_i_id() {
return this.artgru_i_id;
}
public void setArtgru_i_id(Integer artgru_i_id) {
this.artgru_i_id = artgru_i_id;
}
public String getMandant_c_nr() {
return this.mandant_c_nr;
}
public void setMandant_c_nr(String mandant_c_nr) {
this.mandant_c_nr = mandant_c_nr;
}
public com.lp.server.artikel.fastlanereader.generated.FLRArtikelgruppe getFlrartikelgruppe() {
return this.flrartikelgruppe;
}
public void setFlrartikelgruppe(com.lp.server.artikel.fastlanereader.generated.FLRArtikelgruppe flrartikelgruppe) {
this.flrartikelgruppe = flrartikelgruppe;
}
public FLRFinanzKonto getFlrkonto() {
return this.flrkonto;
}
public void setFlrkonto(FLRFinanzKonto flrkonto) {
this.flrkonto = flrkonto;
}
public Set getArtikelgruppesprset() {
return this.artikelgruppesprset;
}
public void setArtikelgruppesprset(Set artikelgruppesprset) {
this.artikelgruppesprset = artikelgruppesprset;
}
public String toString() {
return new ToStringBuilder(this)
.append("i_id", getI_id())
.toString();
}
}
| agpl-3.0 |