code
stringlengths 5
1.04M
| repo_name
stringlengths 7
108
| path
stringlengths 6
299
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 5
1.04M
|
---|---|---|---|---|---|
package com.changhewl.hotel.mq.model;
import java.util.TimeZone;
import lombok.Data;
import com.changhewl.hotel.util.AliasUtil;
import com.changhewl.hotel.util.DateUtil;
import com.changhewl.hotel.util.XstreamUtil;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.basic.DateConverter;
import com.thoughtworks.xstream.io.xml.KXml2Driver;
/**
* 控制对象
* @Title: ContrlModel.java
* @Package com.changhewl.hotel.mq.model
* @Description: TODO(用一句话描述该文件做什么)
* @author 丁江磊
* @date 2015年5月9日 下午10:28:38
* @version V1.0
*/
@Data
public class ContrlModel implements Cloneable {
public static final XStream xstream = new XStream(new KXml2Driver());
/** 业务类型 */
private BusiType busiType;
/** 业务名称 */
private String serverName;
static {
AliasUtil.aliasFieldUseUpperCase(ContrlModel.class, xstream);
xstream.registerConverter(new DateConverter(DateUtil.dateFormatStr1, null, TimeZone.getDefault()));
xstream.alias("CONTRLMODEL", ContrlModel.class);
xstream.setMode(XStream.NO_REFERENCES);
}
public String toXML() {
return XstreamUtil.toXML(this, xstream);
}
public void setBusiType(BusiType busiType) {
this.busiType = busiType;
this.serverName = busiType.getServerName();
}
@Override
public ContrlModel clone() throws CloneNotSupportedException {
return (ContrlModel) super.clone();
}
}
| dingding77/smartHotel | src/main/java/com/changhewl/hotel/mq/model/ContrlModel.java | Java | gpl-2.0 | 1,426 |
package org.janelia.alignment.match;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.janelia.alignment.ArgbRenderer;
import org.janelia.alignment.RenderParameters;
import org.janelia.alignment.Utils;
import org.janelia.alignment.spec.Bounds;
import org.janelia.alignment.spec.TileBounds;
import org.janelia.alignment.spec.TileBoundsRTree;
import org.janelia.alignment.spec.TileSpec;
import org.janelia.alignment.util.ImageProcessorCache;
import org.janelia.alignment.util.RenderWebServiceUrls;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Information about overlapping same layer tile clusters that can be rendered for review.
*
* @author Eric Trautman
*/
public class ClusterOverlapProblem {
public static List<ClusterOverlapProblem> findOverlapProblems(final Double originalZ,
final List<List<TileBounds>> clusterBoundsLists) {
final List<ClusterOverlapProblem> overlapProblems = new ArrayList<>();
final List<TileBoundsRTree> clusterBoundsTrees = new ArrayList<>(clusterBoundsLists.size());
for (int i = 0; i < clusterBoundsLists.size(); i++) {
clusterBoundsTrees.add(new TileBoundsRTree((double) i, clusterBoundsLists.get(i)));
}
ClusterOverlapProblem overlapProblem;
for (int clusterIndex = 0; clusterIndex < clusterBoundsLists.size(); clusterIndex++) {
final TileBoundsRTree boundsRTree = clusterBoundsTrees.get(clusterIndex);
for (int otherClusterIndex = clusterIndex + 1;
otherClusterIndex < clusterBoundsTrees.size();
otherClusterIndex++) {
overlapProblem = null;
for (final TileBounds tileBounds : clusterBoundsLists.get(otherClusterIndex)) {
final List<TileBounds> intersectingTiles = boundsRTree.findTilesInBox(tileBounds.getMinX(),
tileBounds.getMinY(),
tileBounds.getMaxX(),
tileBounds.getMaxY());
if (intersectingTiles.size() > 0) {
if (overlapProblem == null) {
overlapProblem = new ClusterOverlapProblem(originalZ,
tileBounds,
intersectingTiles);
} else {
overlapProblem.addProblem(tileBounds, intersectingTiles);
}
}
}
if (overlapProblem != null) {
overlapProblems.add(overlapProblem);
}
}
}
return overlapProblems;
}
public static RenderParameters getScaledRenderParametersForBounds(final RenderWebServiceUrls renderWebServiceUrls,
final String stackName,
final Double z,
final Bounds bounds,
final int maxHeightOrWidth) {
final int maxHeight = Math.min(maxHeightOrWidth, (int) bounds.getDeltaY());
final int maxWidth = Math.min(maxHeightOrWidth, (int) bounds.getDeltaX());
final double scaleX = maxWidth / bounds.getDeltaX();
final double scaleY = maxHeight / bounds.getDeltaY();
final double scale = Math.min(scaleX, scaleY);
final String urlString = renderWebServiceUrls.getRenderParametersUrlString(stackName,
bounds.getMinX(),
bounds.getMinY(),
z,
(int) bounds.getDeltaX(),
(int) bounds.getDeltaY(),
scale,
null);
return RenderParameters.loadFromUrl(urlString);
}
public static void drawClusterBounds(final BufferedImage targetImage,
final RenderParameters renderParameters,
final Collection<TileBounds> clusterTileBounds,
final Color color) {
final Graphics2D targetGraphics = targetImage.createGraphics();
targetGraphics.setFont(ROW_COLUMN_FONT);
clusterTileBounds.forEach(tb -> drawTileBounds(targetGraphics, renderParameters, tb, color));
targetGraphics.dispose();
}
public static String getTileIdListJson(final Collection<String> tileIds) {
final StringBuilder json = new StringBuilder();
tileIds.stream().sorted().forEach(tileId -> {
if (json.length() > 0) {
json.append(",\n");
}
json.append('"').append(tileId).append('"');
});
return "[\n" + json + "\n]";
}
private final Double originalZ;
private final Double z;
private final Map<String, TileBounds> tileIdToBounds;
private final Double intersectingZ;
private final Map<String, TileBounds> intersectingTileIdToBounds;
private final List<String> problemDetailsList;
private String problemName;
private File problemImageFile;
private ClusterOverlapProblem(final Double originalZ,
final TileBounds tileBounds,
final List<TileBounds> intersectingTileBoundsList) {
this.originalZ = originalZ;
this.z = tileBounds.getZ();
this.tileIdToBounds = new HashMap<>();
this.intersectingZ = intersectingTileBoundsList.get(0).getZ();
this.intersectingTileIdToBounds = new HashMap<>();
this.problemDetailsList = new ArrayList<>();
this.problemName = null;
this.problemImageFile = null;
addProblem(tileBounds, intersectingTileBoundsList);
}
private void addProblem(final TileBounds tileBounds,
final List<TileBounds> intersectingTileBoundsList) {
this.tileIdToBounds.put(tileBounds.getTileId(), tileBounds);
final List<String> intersectingTileIds = new ArrayList<>();
intersectingTileBoundsList.forEach(tb -> {
intersectingTileIdToBounds.put(tb.getTileId(), tb);
intersectingTileIds.add(tb.getTileId());
});
final String details = "cluster overlap: z " + z + " tile " + tileBounds.getTileId() +
" overlaps z " + intersectingZ + " tile(s) " + intersectingTileIds;
this.problemDetailsList.add(details);
}
public void logProblemDetails() {
problemDetailsList.forEach(LOG::warn);
if (problemImageFile != null) {
LOG.warn("cluster overlap image saved to {}\n", problemImageFile);
}
}
public void render(final RenderWebServiceUrls renderWebServiceUrls,
final String stackName,
final File toDirectory) {
final List<Bounds> allBounds = new ArrayList<>(intersectingTileIdToBounds.values());
allBounds.addAll(tileIdToBounds.values());
@SuppressWarnings("OptionalGetWithoutIsPresent")
final Bounds problemBounds = allBounds.stream().reduce(Bounds::union).get();
final RenderParameters parameters = getParameters(renderWebServiceUrls, stackName, problemBounds);
final RenderParameters otherParameters = getParameters(renderWebServiceUrls, stackName, problemBounds);
for (final TileSpec tileSpec : otherParameters.getTileSpecs()) {
parameters.addTileSpec(tileSpec);
}
final BufferedImage targetImage = parameters.openTargetImage();
ArgbRenderer.render(parameters, targetImage, ImageProcessorCache.DISABLED_CACHE);
drawClusterBounds(targetImage, parameters, intersectingTileIdToBounds.values(), Color.GREEN);
drawClusterBounds(targetImage, parameters, tileIdToBounds.values(), Color.RED);
this.problemName = String.format("problem_overlap_%s_z%1.0f_gz%1.0f_rz%1.0f_x%d_y%d",
stackName, originalZ, intersectingZ, z,
(int) parameters.getX(), (int) parameters.getY());
this.problemImageFile = new File(toDirectory, problemName + ".jpg").getAbsoluteFile();
try {
Utils.saveImage(targetImage, this.problemImageFile, false, 0.85f);
} catch (final IOException e) {
LOG.error("failed to save data for " + problemName, e);
}
}
public String toJson() {
final String greenIdJson = getTileIdListJson(intersectingTileIdToBounds.keySet());
final String redIdJson = getTileIdListJson(tileIdToBounds.keySet());
return "{\n" +
" \"problemName\": \"" + problemName + "\",\n" +
" \"greenTileIds\": " + greenIdJson + ",\n" +
" \"redTileIds\": " + redIdJson + "\n" +
"}";
}
public ClusterOverlapBounds getBounds() {
return new ClusterOverlapBounds(z,
intersectingTileIdToBounds.values(),
tileIdToBounds.values());
}
private RenderParameters getParameters(final RenderWebServiceUrls renderWebServiceUrls,
final String stackName,
final Bounds intersectingBounds) {
return getScaledRenderParametersForBounds(renderWebServiceUrls,
stackName,
originalZ,
intersectingBounds,
800);
}
private static final Logger LOG = LoggerFactory.getLogger(ClusterOverlapProblem.class);
private static final Font ROW_COLUMN_FONT = new Font(Font.MONOSPACED, Font.PLAIN, 16);
private static void drawTileBounds(final Graphics2D targetGraphics,
final RenderParameters renderParameters,
final TileBounds tileBounds,
final Color color) {
targetGraphics.setStroke(new BasicStroke(2));
targetGraphics.setColor(color);
final int x = (int) ((tileBounds.getMinX() - renderParameters.getX()) * renderParameters.getScale());
final int y = (int) ((tileBounds.getMinY() - renderParameters.getY()) * renderParameters.getScale());
final int width = (int) (tileBounds.getDeltaX() * renderParameters.getScale());
final int height = (int) (tileBounds.getDeltaY() * renderParameters.getScale());
// HACK: draw row and column label for FAFB style tileIds
final String tileId = tileBounds.getTileId();
final int firstDot = tileId.indexOf('.');
if (firstDot > 6) {
final String rowAndColumn = tileId.substring(firstDot - 6, firstDot);
targetGraphics.drawString(rowAndColumn, (x + 10), (y + 20));
}
targetGraphics.drawRect(x, y, width, height);
}
}
| saalfeldlab/render | render-app/src/main/java/org/janelia/alignment/match/ClusterOverlapProblem.java | Java | gpl-2.0 | 12,214 |
package com.ecotravel.controller;
import java.io.IOException;
import java.net.URISyntaxException;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import com.ecotravel.enums.PersonType;
import com.ecotravel.model.Driver;
import com.ecotravel.model.Passenger;
import com.ecotravel.model.Person;
import com.ecotravel.model.Profile;
import com.ecotravel.service.MailSender;
import com.ecotravel.service.RegisterService;
import com.ecotravel.utils.AuthenticationUtils;
@Stateless
@Path("register")
public class RegisterController {
@Inject
private RegisterService regService;
@Inject
private MailSender mailSender;
@GET
@Produces("application/json")
public void index(@Context HttpServletRequest request, @Context HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = null;
rd = request.getRequestDispatcher("/register.jsp");
rd.forward(request, response);
}
@POST
@Consumes("application/x-www-form-urlencoded")
@Produces("application/json")
public void post(@Context HttpServletRequest request, @Context HttpServletResponse response,
@FormParam(value="username") String username,
@FormParam(value="password") String password,
@FormParam(value="confirm_password") String password2,
@FormParam(value="email") String email,
@FormParam(value="personType") PersonType type,
@FormParam(value="telephone") String telephone,
@FormParam(value="name") String name,
@FormParam(value="birthYear") int birthYear) throws ServletException, IOException{
RequestDispatcher rd = null;
if (!password.equals(password2)) {
request.setAttribute("confirm_error_msg", "Password mismatch!");
rd = request.getRequestDispatcher("/register.jsp");
} else {
if(regService.doesPersonExists(username)){
request.setAttribute("confirm_error_msg", "This username is already taken!");
rd = request.getRequestDispatcher("/register.jsp");
}
else{
Person person = null;
if (type == PersonType.DRIVER) {
person = new Driver();
} else {
person = new Passenger();
}
person.setBirthYear(birthYear);
person.setName(name);
person.setTelephone(telephone);
Profile profile = new Profile();
profile.setEmail(email);
String hashedPassword = AuthenticationUtils.getHashedPassword(password);
profile.setPassword(hashedPassword);
profile.setUsername(username);
regService.register(profile, person);
// rd = request.getRequestDispatcher("/login.jsp");
response.sendRedirect(request.getContextPath());
return;
}
}
rd.forward(request, response);
}
@Path("/forgottenPassword")
public void forgottenPassword(@Context HttpServletRequest request, @Context HttpServletResponse response) throws ServletException, IOException, URISyntaxException {
RequestDispatcher rd = null;
rd = request.getRequestDispatcher("/forgottenPassword.jsp");
rd.forward(request, response);
}
@POST
@Path("/resetPassword")
public void resetPassword(@Context HttpServletRequest request, @Context HttpServletResponse response,
@FormParam(value="username") String username) throws ServletException, IOException, URISyntaxException {
RequestDispatcher rd = null;
if(username == null){
return;
}
mailSender.sendMessage(username);
response.sendRedirect(request.getContextPath());
}
}
| pankrator/Roadtrip | Roadtrip/src/main/java/com/ecotravel/controller/RegisterController.java | Java | gpl-2.0 | 3,777 |
package org.jalgo.module.kmp.gui.component;
import java.awt.Dimension;
import java.awt.Cursor;
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JButton;
import javax.swing.ScrollPaneConstants;
import org.jalgo.module.kmp.gui.event.PhaseTwoScreenListener;
import org.jalgo.module.kmp.gui.GUIConstants;
import org.jalgo.main.util.Messages;
/**
* This is the dialog for loading a searchtext.
*
* @author Danilo Lisske
*/
public class SearchTextLoadDialog extends JDialog {
private static final long serialVersionUID = 5735872302716708982L;
private PhaseTwoScreenListener listener;
private JTextPane tasearchtext;
/**
* The constructor of the searchtext loading dialog.
*
* @param l2 the <code>PhaseTwoScreenListener</code>
*/
public SearchTextLoadDialog(PhaseTwoScreenListener l2) {
listener = l2;
setTitle(Messages.getString("kmp","STLD.Title"));
setSize(240,190);
setFont(GUIConstants.SCREEN_FONT);
setLayout(new GridBagLayout());
setResizable(false);
addWindowFocusListener(listener);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
JLabel lbsearchtext = new JLabel(Messages.getString("kmp","STLD.Label_searchtext") + ":");
lbsearchtext.setFont(getFont());
add(lbsearchtext,c);
c.gridx = 1;
c.insets = new Insets(4,4,4,4);
c.anchor = GridBagConstraints.EAST;
JButton btopenfc = new JButton(Messages.getString("kmp","STLD.Button_load"));
btopenfc.setActionCommand("stfilechooser");
btopenfc.addActionListener(listener);
btopenfc.setFont(getFont());
add(btopenfc,c);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 2;
c.insets = new Insets(0,0,0,0);
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
tasearchtext = new JTextPane();
tasearchtext.setPreferredSize(new Dimension(190,60));
tasearchtext.setFont(getFont());
JScrollPane scrollPane = new JScrollPane(tasearchtext,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setCursor(new Cursor(Cursor.TEXT_CURSOR));
add(scrollPane,c);
c.gridy = 2;
c.insets = new Insets(4,4,4,4);
JPanel buttonPane = new JPanel(new BorderLayout());
JButton btapply = new JButton(Messages.getString("kmp","STLD.Button_apply"));
btapply.setActionCommand("setsearchtext");
btapply.addActionListener(listener);
btapply.setFont(getFont());
buttonPane.add(btapply,BorderLayout.CENTER);
JButton btcancel = new JButton(Messages.getString("kmp","STLD.Button_cancel"));
btcancel.setActionCommand("cancelsearchtext");
btcancel.addActionListener(listener);
btcancel.setFont(getFont());
buttonPane.add(btcancel,BorderLayout.EAST);
add(buttonPane,c);
}
/**
* Returns the searchtext.
*
* @return the searchtext
*/
public String getTaSearchText() {
return tasearchtext.getText();
}
/**
* Sets the searchtext to the input area of this dialog.
*
* @param s the searchtext
*/
public void setTaSearchText(String s) {
tasearchtext.setText(s);
}
} | jurkov/j-algo-mod | src/org/jalgo/module/kmp/gui/component/SearchTextLoadDialog.java | Java | gpl-2.0 | 3,296 |
package com.numhero.client.mvp.task;
import com.google.gwt.i18n.client.Messages;
import static com.google.gwt.i18n.client.LocalizableResource.*;
@GeneratedFrom("com/numhero/client/mvp/task/TaskPanel.ui.xml")
@DefaultLocale("en")
@GenerateKeys("com.google.gwt.i18n.rebind.keygen.MD5KeyGenerator")
@Generate(
format = {"com.google.gwt.i18n.rebind.format.PropertiesFormat", },
fileName = "TaskPanel",
locales = {"default", }
)
public interface TaskPanelTaskUiBinderImplGenMessages extends Messages {
@DefaultMessage("Name")
@Key("task.name")
String message1();
@DefaultMessage("Description")
@Key("task.description")
String message2();
@DefaultMessage("Client")
@Key("invoice.client.supplier")
String message3();
@DefaultMessage("Created")
@Key("task.created")
String message4();
@DefaultMessage("Rate")
@Key("task.rate")
String message5();
@DefaultMessage("Billable")
@Key("task.billable")
String message6();
@DefaultMessage("Time Unit")
@Key("task.timeunit")
String message7();
@DefaultMessage("Time Entry Unit")
@Key("task.timeentryunit")
String message8();
@DefaultMessage("State")
@Key("task.state")
String message9();
@DefaultMessage("Add Staff")
@Key("task.add.staff")
String message10();
@DefaultMessage("Save")
@Key("task.save")
String message11();
@DefaultMessage("Cancel")
@Key("task.cancel")
String message12();
}
| midaboghetich/netnumero | gen/com/numhero/client/mvp/task/TaskPanelTaskUiBinderImplGenMessages.java | Java | gpl-2.0 | 1,416 |
package ir.telgeram.Adel;
import java.io.Serializable;
public class Zangooleh implements Serializable
{
public Integer Id;
public String Title;
public String Content;
public String Link;
public String ImageUrl;
public String ButtonText;
public String Time;
}
| mhossein27/Telgeram | TMessagesProj/src/main/java/ir/telgeram/Adel/Zangooleh.java | Java | gpl-2.0 | 274 |
/*
* Copyright (c) 2018, 2022, 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.hotspot;
import static jdk.vm.ci.runtime.JVMCI.getRuntime;
import static jdk.vm.ci.services.Services.IS_IN_NATIVE_IMAGE;
import static org.graalvm.compiler.hotspot.HotSpotReplacementsImpl.isGraalClass;
import static org.graalvm.compiler.nodes.graphbuilderconf.IntrinsicContext.CompilationContext.INLINE_AFTER_PARSING;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import org.graalvm.collections.UnmodifiableEconomicMap;
import org.graalvm.compiler.api.replacements.SnippetReflectionProvider;
import org.graalvm.compiler.api.runtime.GraalJVMCICompiler;
import org.graalvm.compiler.api.runtime.GraalRuntime;
import org.graalvm.compiler.bytecode.BytecodeProvider;
import org.graalvm.compiler.bytecode.ResolvedJavaMethodBytecode;
import org.graalvm.compiler.core.common.type.Stamp;
import org.graalvm.compiler.core.common.type.StampPair;
import org.graalvm.compiler.core.common.type.SymbolicJVMCIReference;
import org.graalvm.compiler.debug.DebugContext;
import org.graalvm.compiler.debug.GraalError;
import org.graalvm.compiler.graph.NodeClass;
import org.graalvm.compiler.nodeinfo.Verbosity;
import org.graalvm.compiler.nodes.ConstantNode;
import org.graalvm.compiler.nodes.EncodedGraph;
import org.graalvm.compiler.nodes.StructuredGraph;
import org.graalvm.compiler.nodes.ValueNode;
import org.graalvm.compiler.nodes.graphbuilderconf.InlineInvokePlugin;
import org.graalvm.compiler.nodes.graphbuilderconf.IntrinsicContext;
import org.graalvm.compiler.nodes.graphbuilderconf.ParameterPlugin;
import org.graalvm.compiler.nodes.java.MethodCallTargetNode;
import org.graalvm.compiler.nodes.spi.SnippetParameterInfo;
import org.graalvm.compiler.options.OptionValues;
import org.graalvm.compiler.phases.util.Providers;
import org.graalvm.compiler.replacements.ConstantBindingParameterPlugin;
import org.graalvm.compiler.replacements.PEGraphDecoder;
import org.graalvm.compiler.replacements.PartialIntrinsicCallTargetNode;
import jdk.vm.ci.meta.JavaConstant;
import jdk.vm.ci.meta.JavaKind;
import jdk.vm.ci.meta.MetaAccessProvider;
import jdk.vm.ci.meta.ResolvedJavaField;
import jdk.vm.ci.meta.ResolvedJavaMethod;
import jdk.vm.ci.meta.ResolvedJavaType;
import jdk.vm.ci.meta.UnresolvedJavaField;
import jdk.vm.ci.meta.UnresolvedJavaMethod;
import jdk.vm.ci.meta.UnresolvedJavaType;
public class EncodedSnippets {
abstract static class GraphData {
int startOffset;
String originalMethod;
SnippetParameterInfo info;
GraphData(int startOffset, String originalMethod, SnippetParameterInfo info) {
this.startOffset = startOffset;
this.originalMethod = originalMethod;
this.info = info;
}
/**
* Record the data for an encoded graph. Most graphs are from static methods and can only
* have a single instantiation but snippets might come for a non-static method and rely on
* the type of the receiver to devirtualize invokes. In that case each pair of method and
* receiver represents a potentially different instantiation and these are linked into a
* chain of {@link VirtualGraphData VirtualGraphDatas}.
*
* @param startOffset offset of the encoded graph
* @param originalMethod method parsed for the graph
* @param snippetParameterInfo parameter information for snippets
* @param receiverClass static type of the receiver for non-virtual methods
* @param existingGraph a previous encoding of this same graph
*/
public static GraphData create(int startOffset, String originalMethod, SnippetParameterInfo snippetParameterInfo, Class<?> receiverClass, GraphData existingGraph) {
if (receiverClass == null) {
assert existingGraph == null : originalMethod;
return new StaticGraphData(startOffset, originalMethod, snippetParameterInfo);
} else {
return new VirtualGraphData(startOffset, originalMethod, snippetParameterInfo, receiverClass, (VirtualGraphData) existingGraph);
}
}
/**
* Return the proper starting offset based on the actual receiver type of the instantiation
* which may be null.
*/
abstract int getStartOffset(Class<?> receiverClass);
}
/**
* Graph data for a snippet or method substitution defined by a static method.
*/
static class StaticGraphData extends GraphData {
StaticGraphData(int startOffset, String originalMethod, SnippetParameterInfo info) {
super(startOffset, originalMethod, info);
}
@Override
int getStartOffset(Class<?> receiverClass) {
assert receiverClass == null;
return startOffset;
}
}
/**
* Graph data for a snippet defined by a virtual method. Method substitutions can't be virtual.
*/
static class VirtualGraphData extends GraphData {
private final Class<?> receiverClass;
private final VirtualGraphData next;
VirtualGraphData(int startOffset, String originalMethod, SnippetParameterInfo info, Class<?> receiverClass, VirtualGraphData next) {
super(startOffset, originalMethod, info);
this.receiverClass = receiverClass;
this.next = next;
}
@Override
int getStartOffset(Class<?> aClass) {
VirtualGraphData start = this;
while (start != null) {
if (start.receiverClass == aClass) {
return start.startOffset;
}
start = start.next;
}
throw GraalError.shouldNotReachHere("missing receiver type " + aClass);
}
}
private final byte[] snippetEncoding;
private final Object[] snippetObjects;
private final NodeClass<?>[] snippetNodeClasses;
private final UnmodifiableEconomicMap<String, GraphData> graphDatas;
private final Map<Class<?>, SnippetResolvedJavaType> snippetTypes;
EncodedSnippets(byte[] snippetEncoding, Object[] snippetObjects, NodeClass<?>[] snippetNodeClasses, UnmodifiableEconomicMap<String, GraphData> graphDatas,
Map<Class<?>, SnippetResolvedJavaType> snippetTypes) {
this.snippetEncoding = snippetEncoding;
this.snippetObjects = snippetObjects;
this.snippetNodeClasses = snippetNodeClasses;
this.graphDatas = graphDatas;
this.snippetTypes = snippetTypes;
}
public NodeClass<?>[] getSnippetNodeClasses() {
return snippetNodeClasses;
}
ResolvedJavaType lookupSnippetType(Class<?> clazz) {
SnippetResolvedJavaType type = snippetTypes.get(clazz);
if (type == null && isGraalClass(clazz)) {
throw new GraalError("Missing graal class " + clazz);
}
return type;
}
public void visitImmutable(Consumer<Object> visitor) {
visitor.accept(snippetEncoding);
visitor.accept(snippetNodeClasses);
visitor.accept(graphDatas);
}
/**
* Generate a String name for a method including all type information. Used as a symbolic key
* for lookup.
*/
public static String methodKey(ResolvedJavaMethod method) {
return method.format("%H.%n(%P)");
}
StructuredGraph getEncodedSnippet(ResolvedJavaMethod method, ResolvedJavaMethod original, HotSpotReplacementsImpl replacements, Object[] args, StructuredGraph.AllowAssumptions allowAssumptions,
OptionValues options) {
GraphData data = null;
if (graphDatas != null) {
data = graphDatas.get(methodKey(method));
}
if (data == null) {
if (IS_IN_NATIVE_IMAGE) {
throw GraalError.shouldNotReachHere("snippet not found: " + method.format("%H.%n(%p)"));
} else {
return null;
}
}
Class<?> receiverClass = null;
if (!method.isStatic()) {
assert args != null && args[0] != null : "must have a receiver";
receiverClass = args[0].getClass();
}
int startOffset = data.getStartOffset(receiverClass);
ResolvedJavaType declaringClass = method.getDeclaringClass();
if (declaringClass instanceof SnippetResolvedJavaType) {
declaringClass = replacements.getProviders().getMetaAccess().lookupJavaType(Object.class);
}
SymbolicEncodedGraph encodedGraph = new SymbolicEncodedGraph(snippetEncoding, startOffset, snippetObjects, snippetNodeClasses, data.originalMethod, declaringClass);
return decodeSnippetGraph(encodedGraph, method, original, replacements, args, allowAssumptions, options, IS_IN_NATIVE_IMAGE);
}
public SnippetParameterInfo getSnippetParameterInfo(ResolvedJavaMethod method) {
GraphData data = null;
if (graphDatas != null) {
data = graphDatas.get(methodKey(method));
}
assert data != null : method + " " + methodKey(method);
SnippetParameterInfo info = data.info;
assert info != null;
return info;
}
public boolean isSnippet(ResolvedJavaMethod method) {
GraphData data = null;
if (graphDatas != null) {
data = graphDatas.get(methodKey(method));
}
return data != null && data.info != null;
}
static class LibGraalSnippetReflectionProvider implements SnippetReflectionProvider {
final SnippetReflectionProvider delegate;
LibGraalSnippetReflectionProvider(SnippetReflectionProvider delegate) {
this.delegate = delegate;
}
@Override
public JavaConstant forObject(Object object) {
return new SnippetObjectConstant(object);
}
@Override
public <T> T asObject(Class<T> type, JavaConstant constant) {
return delegate.asObject(type, constant);
}
@Override
public JavaConstant forBoxed(JavaKind kind, Object value) {
if (kind == JavaKind.Object) {
return forObject(value);
}
return delegate.forBoxed(kind, value);
}
@Override
public <T> T getInjectedNodeIntrinsicParameter(Class<T> type) {
return delegate.getInjectedNodeIntrinsicParameter(type);
}
@Override
public Class<?> originalClass(ResolvedJavaType type) {
return delegate.originalClass(type);
}
}
@SuppressWarnings("try")
static StructuredGraph decodeSnippetGraph(SymbolicEncodedGraph encodedGraph, ResolvedJavaMethod method, ResolvedJavaMethod original, HotSpotReplacementsImpl replacements, Object[] args,
StructuredGraph.AllowAssumptions allowAssumptions, OptionValues options, boolean mustSucceed) {
Providers providers = replacements.getProviders();
ParameterPlugin parameterPlugin = null;
if (args != null) {
MetaAccessProvider meta = HotSpotReplacementsImpl.noticeTypes(providers.getMetaAccess());
SnippetReflectionProvider snippetReflection = replacements.snippetReflection;
if (IS_IN_NATIVE_IMAGE) {
snippetReflection = new LibGraalSnippetReflectionProvider(snippetReflection);
}
parameterPlugin = new ConstantBindingParameterPlugin(args, meta, snippetReflection);
}
try (DebugContext debug = replacements.openDebugContext("LibGraal", method, options)) {
// @formatter:off
boolean isSubstitution = true;
StructuredGraph result = new StructuredGraph.Builder(options, debug, allowAssumptions)
.method(method)
.trackNodeSourcePosition(encodedGraph.trackNodeSourcePosition())
.setIsSubstitution(isSubstitution)
.build();
// @formatter:on
try (DebugContext.Scope scope = debug.scope("LibGraal.DecodeSnippet", result)) {
PEGraphDecoder graphDecoder = new SubstitutionGraphDecoder(providers, result, replacements, parameterPlugin, method, INLINE_AFTER_PARSING, encodedGraph, mustSucceed);
graphDecoder.decode(method, isSubstitution, encodedGraph.trackNodeSourcePosition());
postDecode(debug, result, original);
assert result.verify();
return result;
} catch (Throwable t) {
throw debug.handle(t);
}
}
}
private static void postDecode(DebugContext debug, StructuredGraph result, ResolvedJavaMethod original) {
debug.dump(DebugContext.VERBOSE_LEVEL, result, "Before PartialIntrinsicCallTargetNode replacement");
for (PartialIntrinsicCallTargetNode partial : result.getNodes(PartialIntrinsicCallTargetNode.TYPE)) {
// Ensure the orignal method matches
assert partial.checkName(original);
ValueNode[] arguments = partial.arguments().toArray(new ValueNode[partial.arguments().size()]);
MethodCallTargetNode target = result.add(new MethodCallTargetNode(partial.invokeKind(), original,
arguments, partial.returnStamp(), null));
partial.replaceAndDelete(target);
}
debug.dump(DebugContext.VERBOSE_LEVEL, result, "After decoding");
for (ValueNode n : result.getNodes().filter(ValueNode.class)) {
if (n instanceof ConstantNode) {
ConstantNode constant = (ConstantNode) n;
if (constant.asConstant() instanceof SnippetObjectConstant) {
throw new InternalError(n.toString(Verbosity.Debugger));
}
}
}
}
static class SubstitutionGraphDecoder extends PEGraphDecoder {
private final ResolvedJavaMethod method;
private final EncodedGraph encodedGraph;
private final IntrinsicContext intrinsic;
private final boolean mustSucceed;
SubstitutionGraphDecoder(Providers providers, StructuredGraph result, HotSpotReplacementsImpl replacements, ParameterPlugin parameterPlugin, ResolvedJavaMethod method,
IntrinsicContext.CompilationContext context, EncodedGraph encodedGraph, boolean mustSucceed) {
super(providers.getCodeCache().getTarget().arch, result, providers, null,
replacements.getGraphBuilderPlugins().getInvocationPlugins(), new InlineInvokePlugin[0], parameterPlugin,
null, null, null, new ConcurrentHashMap<>(), new ConcurrentHashMap<>(), false);
this.method = method;
this.encodedGraph = encodedGraph;
this.mustSucceed = mustSucceed;
this.intrinsic = new IntrinsicContext(method, null, replacements.getDefaultReplacementBytecodeProvider(), context, false);
}
@Override
protected EncodedGraph lookupEncodedGraph(ResolvedJavaMethod lookupMethod,
BytecodeProvider intrinsicBytecodeProvider,
boolean isSubstitution,
boolean trackNodeSourcePosition) {
if (lookupMethod.equals(method)) {
return encodedGraph;
} else {
throw GraalError.shouldNotReachHere(method.format("%H.%n(%p)"));
}
}
@Override
public IntrinsicContext getIntrinsic() {
return intrinsic;
}
@Override
protected boolean pluginReplacementMustSucceed() {
return mustSucceed;
}
}
static class SymbolicEncodedGraph extends EncodedGraph {
private final ResolvedJavaType[] accessingClasses;
private final String originalMethod;
SymbolicEncodedGraph(byte[] encoding, int startOffset, Object[] objects, NodeClass<?>[] types, String originalMethod, ResolvedJavaType... accessingClasses) {
super(encoding, startOffset, objects, types, null, null, false, false);
this.accessingClasses = accessingClasses;
this.originalMethod = originalMethod;
}
SymbolicEncodedGraph(EncodedGraph encodedGraph, ResolvedJavaType declaringClass, String originalMethod) {
this(encodedGraph.getEncoding(), encodedGraph.getStartOffset(), encodedGraph.getObjects(), encodedGraph.getNodeClasses(),
originalMethod, declaringClass);
}
@Override
public Object getObject(int i) {
Object o = objects[i];
Object replacement = null;
Throwable error = null;
if (o instanceof SymbolicJVMCIReference) {
for (ResolvedJavaType type : accessingClasses) {
try {
replacement = ((SymbolicJVMCIReference<?>) o).resolve(type);
if (replacement != null) {
break;
}
} catch (NoClassDefFoundError e) {
error = e;
}
}
} else if (o instanceof UnresolvedJavaType) {
for (ResolvedJavaType type : accessingClasses) {
try {
replacement = ((UnresolvedJavaType) o).resolve(type);
if (replacement != null) {
break;
}
} catch (NoClassDefFoundError e) {
error = e;
}
}
} else if (o instanceof UnresolvedJavaMethod) {
throw new InternalError(o.toString());
} else if (o instanceof UnresolvedJavaField) {
for (ResolvedJavaType type : accessingClasses) {
try {
replacement = ((UnresolvedJavaField) o).resolve(type);
if (replacement != null) {
break;
}
} catch (NoClassDefFoundError e) {
error = e;
}
}
} else if (o instanceof GraalCapability) {
replacement = ((GraalCapability) o).resolve(((GraalJVMCICompiler) getRuntime().getCompiler()).getGraalRuntime());
} else {
return o;
}
if (replacement != null) {
objects[i] = o = replacement;
} else {
throw new GraalError(error, "Can't resolve %s", o);
}
return o;
}
@Override
public boolean isCallToOriginal(ResolvedJavaMethod callTarget) {
if (originalMethod != null && originalMethod.equals(EncodedSnippets.methodKey(callTarget))) {
return true;
}
return super.isCallToOriginal(callTarget);
}
}
/**
* Symbolic reference to an object which can be retrieved from
* {@link GraalRuntime#getCapability(Class)}.
*/
static class GraalCapability {
final Class<?> capabilityClass;
GraalCapability(Class<?> capabilityClass) {
this.capabilityClass = capabilityClass;
}
public Object resolve(GraalRuntime runtime) {
Object capability = runtime.getCapability(this.capabilityClass);
if (capability != null) {
assert capability.getClass() == capabilityClass;
return capability;
}
throw new InternalError(this.capabilityClass.getName());
}
@Override
public String toString() {
return "GraalCapability{" +
"capabilityClass=" + capabilityClass +
'}';
}
}
static class SymbolicResolvedJavaMethod implements SymbolicJVMCIReference<ResolvedJavaMethod> {
final UnresolvedJavaType type;
final String methodName;
final String signature;
SymbolicResolvedJavaMethod(UnresolvedJavaType type, String methodName, String signature) {
this.type = type;
this.methodName = methodName;
this.signature = signature;
}
@Override
public String toString() {
return "SymbolicResolvedJavaMethod{" +
"declaringType='" + type.getName() + '\'' +
", methodName='" + methodName + '\'' +
", signature='" + signature + '\'' +
'}';
}
@Override
public ResolvedJavaMethod resolve(ResolvedJavaType accessingClass) {
ResolvedJavaType resolvedType = type.resolve(accessingClass);
if (resolvedType == null) {
throw new NoClassDefFoundError("Can't resolve " + type.getName() + " with " + accessingClass.getName());
}
for (ResolvedJavaMethod method : methodName.equals("<init>") ? resolvedType.getDeclaredConstructors() : resolvedType.getDeclaredMethods()) {
if (method.getName().equals(methodName) && method.getSignature().toMethodDescriptor().equals(signature)) {
return method;
}
}
throw new NoClassDefFoundError("Can't resolve " + type.getName() + " with " + accessingClass.getName());
}
}
static class SymbolicResolvedJavaField implements SymbolicJVMCIReference<ResolvedJavaField> {
final UnresolvedJavaType declaringType;
final String name;
final UnresolvedJavaType signature;
private final boolean isStatic;
SymbolicResolvedJavaField(UnresolvedJavaType declaringType, String name, UnresolvedJavaType signature, boolean isStatic) {
this.declaringType = declaringType;
this.name = name;
this.signature = signature;
this.isStatic = isStatic;
}
@Override
public ResolvedJavaField resolve(ResolvedJavaType accessingClass) {
ResolvedJavaType resolvedType = declaringType.resolve(accessingClass);
if (resolvedType == null) {
throw new NoClassDefFoundError("Can't resolve " + declaringType.getName() + " with " + accessingClass.getName());
}
ResolvedJavaType resolvedFieldType = signature.resolve(accessingClass);
if (resolvedFieldType == null) {
throw new NoClassDefFoundError("Can't resolve " + signature.getName() + " with " + accessingClass.getName());
}
ResolvedJavaField[] fields = isStatic ? resolvedType.getStaticFields() : resolvedType.getInstanceFields(true);
for (ResolvedJavaField field : fields) {
if (field.getName().equals(name)) {
if (field.getType().equals(resolvedFieldType)) {
return field;
}
}
}
throw new InternalError("Could not resolve " + this + " in context of " + accessingClass.toJavaName());
}
@Override
public String toString() {
return "SymbolicResolvedJavaField{" +
signature.getName() + ' ' +
declaringType.getName() + '.' +
name +
'}';
}
}
static class SymbolicResolvedJavaMethodBytecode implements SymbolicJVMCIReference<ResolvedJavaMethodBytecode> {
SymbolicResolvedJavaMethod method;
SymbolicResolvedJavaMethodBytecode(SymbolicResolvedJavaMethod method) {
this.method = method;
}
@Override
public ResolvedJavaMethodBytecode resolve(ResolvedJavaType accessingClass) {
return new ResolvedJavaMethodBytecode(method.resolve(accessingClass));
}
@Override
public String toString() {
return "SymbolicResolvedJavaMethodBytecode{" +
"method=" + method +
'}';
}
}
static class SymbolicStampPair implements SymbolicJVMCIReference<StampPair> {
final Object trustedStamp;
final Object uncheckedStamp;
SymbolicStampPair(Object trustedStamp, Object uncheckedStamp) {
this.trustedStamp = trustedStamp;
this.uncheckedStamp = uncheckedStamp;
}
@Override
public StampPair resolve(ResolvedJavaType accessingClass) {
return StampPair.create(resolveStamp(accessingClass, trustedStamp), resolveStamp(accessingClass, uncheckedStamp));
}
@Override
public String toString() {
return "SymbolicStampPair{" +
"trustedStamp=" + trustedStamp +
", uncheckedStamp=" + uncheckedStamp +
'}';
}
private static Stamp resolveStamp(ResolvedJavaType accessingClass, Object stamp) {
if (stamp == null) {
return null;
}
if (stamp instanceof Stamp) {
return (Stamp) stamp;
}
return (Stamp) ((SymbolicJVMCIReference<?>) stamp).resolve(accessingClass);
}
}
}
| smarr/Truffle | compiler/src/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/EncodedSnippets.java | Java | gpl-2.0 | 26,614 |
package es.uned.dia.jcsombria.softwarelinks.utils;
import java.io.IOException;
import java.io.StringReader;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class ConfigurationModel {
// XML Node labels for saving the state of the elements
private static final String XML_NODE_LABEL_MATLAB = "rpcmatlab";
private static final String XML_NODE_LABEL_SERVER = "server";
private static final String XML_NODE_LABEL_PORT = "port";
// private static final String XML_NODE_LABEL_PATH = "path";
private static final String XML_NODE_LABEL_LINKS = "links";
private static final String XML_NODE_LABEL_ROW = "row";
private static final String XML_NODE_LABEL_TRANSPORT = "transport";
private static final String XML_NODE_LABEL_LABVIEW = "matlab";
private static final String XML_NODE_LABEL_MODEL = "model";
private static final String XML_NODE_LABEL_GET = "get";
private static final String XML_NODE_LABEL_SET = "set";
private static final String XML_NODE_LABEL_MODE = "mode";
private String mode;
private String server;
private String port;
private String protocol;
private Vector<Vector<Object>> data;
public void setData(Vector<Vector<Object>> data) {
this.data = data;
}
public void setMode(String mode) {
switch(mode.toLowerCase()) {
case "local":
case "remote":
this.mode = mode.toLowerCase();
break;
default:
}
}
public void setServer(String server, String port, String protocol) {
this.server = server;
if (server.length() <= 0) {
this.server = "localhost";
}
this.port = port;
if(port.length() <= 0) {
this.port = "2055";
}
if("tcp".equalsIgnoreCase(protocol) || "http".equalsIgnoreCase(protocol)) {
this.protocol = protocol.toLowerCase();
}
}
public String getURL() {
return protocol + "://" + server + ":" + port;
}
public Vector<Vector<Object>> getDataVector() {
return data;
}
public Object[][] getData() {
Object[][] dataAsMatrix = new Object[data.size()][];
int i = 0;
for(Vector<Object> row : data) {
dataAsMatrix[i++] = row.toArray();
}
return dataAsMatrix;
}
public String getServer() {
return server;
}
public String getPort() {
return port;
}
public String getProtocol() {
return protocol;
}
public String getMode() {
return mode;
}
public void restore(String state) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
InputSource is = new InputSource(new StringReader(state));
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
// Server configuration
String server = doc.getElementsByTagName(XML_NODE_LABEL_SERVER).item(0).getTextContent();
String port = doc.getElementsByTagName(XML_NODE_LABEL_PORT).item(0).getTextContent();
String transport = doc.getElementsByTagName(XML_NODE_LABEL_TRANSPORT).item(0).getTextContent();
String mode = doc.getElementsByTagName(XML_NODE_LABEL_MODE).item(0).getTextContent();
setServer(server, port, transport);
setMode(mode);
// The links between matlab variables and ejs variables
Node links = doc.getElementsByTagName(XML_NODE_LABEL_LINKS).item(0);
if (links != null) {
NodeList linksList = links.getChildNodes();
int i = 0;
Node node = linksList.item(0);
setData(new Vector<Vector<Object>>());
while(node != null) {
if(node.getNodeName() == XML_NODE_LABEL_ROW) {
Object[] row = new Object[4];
Node next = node.getFirstChild();
while(next != null) {
String value = next.getTextContent();
switch(next.getNodeName()) {
case XML_NODE_LABEL_LABVIEW:
row[0] = value;
break;
case XML_NODE_LABEL_MODEL:
row[1] = value;
break;
case XML_NODE_LABEL_GET:
row[2] = Boolean.valueOf(value);
break;
case XML_NODE_LABEL_SET:
row[3] = Boolean.valueOf(value);
break;
}
next = next.getNextSibling();
}
data.add(arrayToVector(row));
}
node = linksList.item(++i);
}
}
} catch (ParserConfigurationException | SAXException | IOException e) {
System.err.println("Error al restaurar el estado del elemento.");
}
}
private Vector<Object> arrayToVector(Object[] array) {
Vector<Object> toReturn = new Vector<>();
for(Object item : array) {
toReturn.add(item);
}
return toReturn;
}
public String dump() {
String result = "<" + XML_NODE_LABEL_MATLAB + ">" +
"<" + XML_NODE_LABEL_SERVER + ">" + server + "</" + XML_NODE_LABEL_SERVER + ">" +
"<" + XML_NODE_LABEL_PORT + ">" + port + "</" + XML_NODE_LABEL_PORT + ">" +
"<" + XML_NODE_LABEL_TRANSPORT + ">" + protocol + "</" + XML_NODE_LABEL_TRANSPORT + ">" +
"<" + XML_NODE_LABEL_MODE + ">" + mode + "</" + XML_NODE_LABEL_MODE + ">";
if(data != null) {
result += "<" + XML_NODE_LABEL_LINKS + ">";
Iterable<Vector<Object>> links = (Iterable<Vector<Object>>)this.data;
for(Vector<Object> v : links) {
result += "<" + XML_NODE_LABEL_ROW + ">" +
"<" + XML_NODE_LABEL_LABVIEW + ">" + v.elementAt(0) + "</" + XML_NODE_LABEL_LABVIEW + ">" +
"<" + XML_NODE_LABEL_MODEL + ">" + v.elementAt(1) + "</" + XML_NODE_LABEL_MODEL + ">" +
"<" + XML_NODE_LABEL_GET + ">" + v.elementAt(2) + "</" + XML_NODE_LABEL_GET + ">" +
"<" + XML_NODE_LABEL_SET + ">" + v.elementAt(3) + "</" + XML_NODE_LABEL_SET + ">" +
"</" + XML_NODE_LABEL_ROW + ">" + "\n";
}
result += "</" + XML_NODE_LABEL_LINKS + ">";
}
result += "</" + XML_NODE_LABEL_MATLAB + ">";
return result;
}
} | jcsombria/softwarelinks-ejs-matlabconnector | rip-matlab-client/src/es/uned/dia/jcsombria/softwarelinks/utils/ConfigurationModel.java | Java | gpl-2.0 | 5,821 |
/*
* Node.java
*
* Created on 19.10.2005, 22:27
* Copyright (c) 2005-2008, Eugene Stahov (evgs), http://bombus-im.org
*
* 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.
*
* You can also redistribute and/or modify this program under the
* terms of the Psi License, specified in the accompanied COPYING
* file, as published by the Psi Project; either dated January 1st,
* 2005, 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
//#ifdef SERVICE_DISCOVERY
package disco;
import images.RosterIcons;
import ui.IconTextElement;
/**
*
* @author EvgS
*/
public class Node extends IconTextElement{
private String node;
private String name;
private String discoJid;
public int getImageIndex() { return RosterIcons.ICON_COLLAPSED_INDEX; }
/** Creates a new instance of Item */
public Node(String name, String jid, String node) {
super((name!=null)? name:node, RosterIcons.getInstance(), -1);
this.name=name;
this.node=node;
this.discoJid = jid;
}
public String getName() { return name; }
public String getNode() { return node; }
public String getTipString() { return discoJid; }
}
//#endif
| Tishka17/qd-fork | src/disco/Node.java | Java | gpl-2.0 | 1,831 |
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package it.ilnaufrago.myapp;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class id {
public static final int password=0x7f060001;
public static final int result=0x7f060002;
public static final int username=0x7f060000;
}
public static final class layout {
public static final int main=0x7f030000;
public static final int page=0x7f030001;
}
public static final class string {
public static final int app_name=0x7f040001;
public static final int ciao=0x7f040002;
public static final int hello=0x7f040000;
}
public static final class style {
public static final int AppTheme=0x7f050000;
}
}
| algedi/HelloAndroid | gen/it/ilnaufrago/myapp/R.java | Java | gpl-2.0 | 1,018 |
package de.mixedfx.test;
import de.mixedfx.inspector.Inspector;
import de.mixedfx.ts3.TS3LocalInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import java.io.IOException;
/**
* Created by Jerry on 09.10.2015.
*/
@ComponentScan(basePackages = "de.mixedfx.ts3")
public class TS3Tester_cdi {
@Autowired
private TS3LocalInstance instance;
public void listen() throws IOException {
// Register for TS3 events
instance.setOnEvent(event -> System.err.println(event));
Inspector.runNowAsDaemon(() -> {
while (true) {
System.out.println("Waiting for TS3 to start!");
try {
boolean pluginEnabled = instance.start();
if (!pluginEnabled) {
System.out.println("In TS3 ClientQuery plugin must be enabled!");
break; // Stop this
}
} catch (IOException e) {
System.out.println("An unknown exception occurred!");
e.printStackTrace();
}
System.out.println("TS3 was closed!");
}
});
instance.waitForReadyness();
System.err.println("Read schandlerid: " + instance.getSchandlerID());
System.err.println("Read clients: " + instance.getClients());
}
public static void main(String[] args) throws InterruptedException, IOException {
System.out.println("START");
ApplicationContext context = new AnnotationConfigApplicationContext(TS3Tester_cdi.class);
context.getBean(TS3Tester_cdi.class).listen();
System.out.println("Close application in 100 seconds.");
Thread.sleep(100000);
System.out.println("STOP");
}
}
| Jerry0022/MixedFX | mixedfx-ts3/src/test/java/de/mixedfx/test/TS3Tester_cdi.java | Java | gpl-2.0 | 1,995 |
/*******************************************************************************
* Copyright (c) 2012 Harrison Chapman.
*
* This file is part of Reverb.
*
* Reverb 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.
*
* Reverb 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 Reverb. If not, see <http://www.gnu.org/licenses/>.
*
* Contributors:
* Harrison Chapman - initial API and implementation
******************************************************************************/
package com.harrcharr.pulse;
import java.util.HashMap;
public abstract class JNIObject {
private long mPointer;
private static HashMap<Long, JNIObject> ptrTable = new HashMap<Long, JNIObject>();
protected JNIObject(long ptr) {
mPointer = ptr;
addToTable();
}
protected void finalize() {
purge();
}
/*
* Delete object being pointed to, remove self from pointer table
*/
public synchronized void purge() {
ptrTable.remove(new Long(mPointer));
}
public static JNIObject getByPointer(long ptr) {
return getByPointer(new Long(ptr));
}
public static JNIObject getByPointer(Long ptr) {
return ptrTable.get(ptr);
}
protected void addToTable() {
ptrTable.put(new Long(mPointer), this);
}
public long getPointer() {
return mPointer;
}
}
| hchapman/libpulse-android | src/main/java/com/harrcharr/pulse/JNIObject.java | Java | gpl-2.0 | 1,764 |
package net.pms.remote;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import net.pms.PMS;
import net.pms.configuration.FormatConfiguration;
import net.pms.configuration.RendererConfiguration;
import net.pms.configuration.WebRender;
import net.pms.dlna.*;
import net.pms.encoders.FFMpegVideo;
import net.pms.encoders.FFmpegAudio;
import net.pms.encoders.FFmpegWebVideo;
import net.pms.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("restriction")
public class RemoteMediaHandler implements HttpHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RemoteMediaHandler.class);
private RemoteWeb parent;
private String path;
private RendererConfiguration renderer;
private boolean flash;
public RemoteMediaHandler(RemoteWeb parent) {
this(parent, "media/", null);
}
public RemoteMediaHandler(RemoteWeb parent, boolean flash) {
this(parent, "fmedia/", null);
this.flash = flash;
}
public RemoteMediaHandler(RemoteWeb parent, String path, RendererConfiguration renderer) {
this.flash = false;
this.parent = parent;
this.path = path;
this.renderer = renderer;
}
@Override
public void handle(HttpExchange httpExchange) throws IOException {
if (RemoteUtil.deny(httpExchange)) {
throw new IOException("Access denied");
}
RootFolder root = parent.getRoot(RemoteUtil.userName(httpExchange), httpExchange);
if (root == null) {
throw new IOException("Unknown root");
}
Headers h = httpExchange.getRequestHeaders();
for (String h1 : h.keySet()) {
LOGGER.debug("key " + h1 + "=" + h.get(h1));
}
String id = RemoteUtil.getId(path, httpExchange);
id = RemoteUtil.strip(id);
RendererConfiguration defaultRenderer = renderer;
if (renderer == null) {
defaultRenderer = root.getDefaultRenderer();
}
DLNAResource resource = root.getDLNAResource(id, defaultRenderer);
if (resource == null) {
// another error
LOGGER.debug("media unkonwn");
throw new IOException("Bad id");
}
if (!resource.isCodeValid(resource)) {
LOGGER.debug("coded object with invalid code");
throw new IOException("Bad code");
}
DLNAMediaSubtitle sid = null;
String mimeType = root.getDefaultRenderer().getMimeType(resource.mimeType(), resource.getMedia());
//DLNAResource dlna = res.get(0);
WebRender renderer = (WebRender) defaultRenderer;
DLNAMediaInfo media = resource.getMedia();
if (media == null) {
media = new DLNAMediaInfo();
resource.setMedia(media);
}
if (mimeType.equals(FormatConfiguration.MIMETYPE_AUTO) && media.getMimeType() != null) {
mimeType = media.getMimeType();
}
int code = 200;
resource.setDefaultRenderer(defaultRenderer);
if (resource.getFormat().isVideo()) {
if (flash) {
mimeType = "video/flash";
} else if (!RemoteUtil.directmime(mimeType) || RemoteUtil.transMp4(mimeType, media)) {
mimeType = renderer != null ? renderer.getVideoMimeType() : RemoteUtil.transMime();
if (FileUtil.isUrl(resource.getSystemName())) {
resource.setPlayer(new FFmpegWebVideo());
} else if (!(resource instanceof DVDISOTitle)) {
resource.setPlayer(new FFMpegVideo());
}
//code = 206;
}
if (
PMS.getConfiguration().getWebSubs() &&
resource.getMediaSubtitle() != null &&
resource.getMediaSubtitle().isExternal()
) {
// fetched on the side
sid = resource.getMediaSubtitle();
resource.setMediaSubtitle(null);
}
}
if (!RemoteUtil.directmime(mimeType) && resource.getFormat().isAudio()) {
resource.setPlayer(new FFmpegAudio());
code = 206;
}
media.setMimeType(mimeType);
Range.Byte range = RemoteUtil.parseRange(httpExchange.getRequestHeaders(), resource.length());
LOGGER.debug("Sending {} with mime type {} to {}", resource, mimeType, renderer);
InputStream in = resource.getInputStream(range, root.getDefaultRenderer());
if(range.getEnd() == 0) {
// For web resources actual length may be unknown until we open the stream
range.setEnd(resource.length());
}
Headers headers = httpExchange.getResponseHeaders();
headers.add("Content-Type", mimeType);
headers.add("Accept-Ranges", "bytes");
long end = range.getEnd();
long start = range.getStart();
String rStr = start + "-" + end + "/*" ;
headers.add("Content-Range", "bytes " + rStr);
if (start != 0) {
code = 206;
}
headers.add("Server", PMS.get().getServerName());
headers.add("Connection", "keep-alive");
httpExchange.sendResponseHeaders(code, 0);
OutputStream os = httpExchange.getResponseBody();
if (renderer != null) {
renderer.start(resource);
}
if (sid != null) {
resource.setMediaSubtitle(sid);
}
RemoteUtil.dump(in, os, renderer);
}
}
| Sami32/UniversalMediaServer | src/main/java/net/pms/remote/RemoteMediaHandler.java | Java | gpl-2.0 | 4,852 |
package net.minecraft.world;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.world.WorldProvider;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.biome.WorldChunkManagerHell;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.ChunkProviderEnd;
public class WorldProviderEnd extends WorldProvider {
private static final String __OBFID = "CL_00000389";
public void func_76572_b() {
this.field_76578_c = new WorldChunkManagerHell(BiomeGenBase.field_76779_k, 0.0F);
this.field_76574_g = 1;
this.field_76576_e = true;
}
public IChunkProvider func_76555_c() {
return new ChunkProviderEnd(this.field_76579_a, this.field_76579_a.func_72905_C());
}
public float func_76563_a(long p_76563_1_, float p_76563_3_) {
return 0.0F;
}
public boolean func_76567_e() {
return false;
}
public boolean func_76569_d() {
return false;
}
public boolean func_76566_a(int p_76566_1_, int p_76566_2_) {
return this.field_76579_a.func_147474_b(p_76566_1_, p_76566_2_).func_149688_o().func_76230_c();
}
public ChunkCoordinates func_76554_h() {
return new ChunkCoordinates(100, 50, 0);
}
public int func_76557_i() {
return 50;
}
public String func_80007_l() {
return "The End";
}
}
| mviitanen/marsmod | mcp/temp/src/minecraft_server/net/minecraft/world/WorldProviderEnd.java | Java | gpl-2.0 | 1,371 |
/*
* 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 org.mathison.hits.key;
import com.hazelcast.core.PartitionAware;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.DataSerializable;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;
/**
*
* @author Daryl
*/
public class NodeMapKey implements PartitionAware<String>, DataSerializable {
//UUID
private String uuid;
private String URI;
public NodeMapKey(String uuid, String URI) {
this.uuid = uuid;
this.URI = URI;
}
public NodeMapKey(String URI) {
this.uuid = UUID.randomUUID().toString();
this.URI = URI;
}
private NodeMapKey() {}
public String getUuid() {
return uuid;
}
public String getURI() {
return URI;
}
@Override
public String getPartitionKey() {
return uuid;
}
@Override
public void writeData(ObjectDataOutput odo) throws IOException {
odo.writeUTF(uuid);
odo.writeUTF(URI);
}
@Override
public void readData(ObjectDataInput odi) throws IOException {
uuid = odi.readUTF();
URI = odi.readUTF();
}
@Override
public int hashCode() {
int hash = 7;
hash = 61 * hash + Objects.hashCode(this.uuid);
hash = 61 * hash + Objects.hashCode(this.URI);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final NodeMapKey other = (NodeMapKey) obj;
if (!Objects.equals(this.uuid, other.uuid)) {
return false;
}
if (!Objects.equals(this.URI, other.URI)) {
return false;
}
return true;
}
}
| darylmathison/hits-search-database | HitsDatabase/src/org/mathison/hits/key/NodeMapKey.java | Java | gpl-2.0 | 2,145 |
/*
* Java Statistics. A java library providing power/sample size estimation for
* the general linear model.
*
* Copyright (C) 2010 Regents of the University of Colorado.
*
* 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 edu.cudenver.bios.power.test.general;
import java.text.DecimalFormat;
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.LUDecomposition;
import org.apache.commons.math3.linear.RealMatrix;
import edu.cudenver.bios.matrix.DesignEssenceMatrix;
import edu.cudenver.bios.matrix.FixedRandomMatrix;
import edu.cudenver.bios.matrix.MatrixUtils;
import edu.cudenver.bios.matrix.RandomColumnMetaData;
import edu.cudenver.bios.matrix.RowMetaData;
import edu.cudenver.bios.power.PowerException;
import edu.cudenver.bios.power.glmm.NonCentralityDistribution;
import edu.cudenver.bios.power.glmm.GLMMTestFactory.Test;
import edu.cudenver.bios.power.parameters.GLMMPowerParameters;
import edu.cudenver.bios.power.parameters.GLMMPowerParameters.PowerMethod;
import junit.framework.TestCase;
/**
* Non-automated test of non-centrality distribution. Manually compared against
* Glueck & Muller 2003 implementation in SAS/IML
* @author Sarah Kreidler
*
*/
public class TestNonCentralityDistribution extends TestCase
{
private static final int SIMULATION_SIZE = 10000;
private static final double UNIT_TEST_ALPHA = 0.01;
private static final double MEAN = 9.75;
private static final double VARIANCE = 1.0;
private static final double[] ALPHA_LIST = {0.05};
private static final double[] BETA_SCALE_LIST = {1};
private static final double[] SIGMA_SCALE_LIST = {1};
private static final int[] SAMPLE_SIZE_LIST = {5};
private DecimalFormat Number = new DecimalFormat("#0.0000000000");
public void testApproximateNonCentralCDF()
{
GLMMPowerParameters params = buildValidMultivariateRandomInputs();
double betaScale = params.getBetaScaleList().get(0);
double sigmaScale = params.getSigmaScaleList().get(0);
int perGroupN = params.getSampleSizeList().get(0);
Test test = params.getTestList().get(0);
// Test test, RealMatrix F, RealMatrix FtFinverse, int N,
// FixedRandomMatrix CFixedRand, RealMatrix U,
// RealMatrix thetaNull, RealMatrix beta,
// RealMatrix sigmaError, RealMatrix sigmaG, boolean exact
try {
NonCentralityDistribution ncd =
new NonCentralityDistribution(test, params.getDesignEssence(),
null,
perGroupN,
params.getBetweenSubjectContrast(),
params.getWithinSubjectContrast(),
params.getTheta(),
params.getBeta().scalarMultiply(betaScale, true),
params.getSigmaError().scalarMultiply(sigmaScale),
params.getSigmaGaussianRandom(),
false);
for(double crit = 1; crit < 15; crit++)
{
double prob = ncd.cdf(crit);
System.out.println("Critical Value: " + crit + " prob: " + Number.format(prob));
}
} catch (PowerException e) {
System.err.println("CDF failed: [" + e.getErrorCode() +
"]" + e.getMessage());
}
}
public void testApproximateNonCentralInverseCDF()
{
GLMMPowerParameters params = buildValidMultivariateRandomInputs();
double betaScale = params.getBetaScaleList().get(0);
double sigmaScale = params.getSigmaScaleList().get(0);
int perGroupN = params.getSampleSizeList().get(0);
Test test = params.getTestList().get(0);
try {
NonCentralityDistribution ncd =
new NonCentralityDistribution(test, params.getDesignEssence(),
null,
perGroupN,
params.getBetweenSubjectContrast(),
params.getWithinSubjectContrast(),
params.getTheta(),
params.getBeta().scalarMultiply(betaScale, true),
params.getSigmaError().scalarMultiply(sigmaScale),
params.getSigmaGaussianRandom(),
false);
for(double w = 0.10; w < 1.05; w += 0.1)
{
double nonCentralityParam = ncd.inverseCDF(w);
System.out.println("Quantile: " + Number.format(w) +
" inverseCDF: " + Number.format(nonCentralityParam));
}
} catch (PowerException e) {
System.err.println("Simulation failed: [" + e.getErrorCode() +
"]" + e.getMessage());
}
}
/**
* Builds matrices for a multivariate GLM with a baseline covariate
*/
private GLMMPowerParameters buildValidMultivariateRandomInputs()
{
GLMMPowerParameters params = new GLMMPowerParameters();
// add power methods
//for(PowerMethod method: PowerMethod.values()) params.addPowerMethod(method);
params.addPowerMethod(PowerMethod.CONDITIONAL_POWER);
params.addPowerMethod(PowerMethod.QUANTILE_POWER);
params.addQuantile(0.25);
params.addQuantile(0.5);
params.addQuantile(0.75);
// add tests - only HL andUNIREP value for random case
params.addTest(Test.HOTELLING_LAWLEY_TRACE);
//params.addTest(GLMMPowerParameters.Test.UNIREP);
// add alpha values
for(double alpha: ALPHA_LIST) params.addAlpha(alpha);
int P = 3;
int Q = 3;
// create design matrix
params.setDesignEssence(org.apache.commons.math3.linear.MatrixUtils.createRealIdentityMatrix(Q));
// add sample size multipliers
for(int sampleSize: SAMPLE_SIZE_LIST) params.addSampleSize(sampleSize);
// build sigma G matrix
double[][] sigmaG = {{1}};
params.setSigmaGaussianRandom(new Array2DRowRealMatrix(sigmaG));
// build sigma Y matrix
double rho = 0.4;
double [][] sigmaY = {{1,0},{0,1}};
params.setSigmaOutcome(new Array2DRowRealMatrix(sigmaY));
// build sigma YG
double rhoYG = 0.8;
double [][] sigmaYG = {{0.9},{0}};
params.setSigmaOutcomeGaussianRandom(new Array2DRowRealMatrix(sigmaYG));
// add sigma scale values
for(double sigmaScale: SIGMA_SCALE_LIST) params.addSigmaScale(sigmaScale);
// build beta matrix
double [][] beta = {{1,0},{0,0},{0,0}};
double [][] betaRandom = {{0.9,0}};
params.setBeta(new FixedRandomMatrix(beta, betaRandom, false));
// add beta scale values
for(double betaScale: BETA_SCALE_LIST) params.addBetaScale(betaScale);
// build theta null matrix
double [][] theta0 = {{0,0},{0,0}};
params.setTheta(new Array2DRowRealMatrix(theta0));
// build between subject contrast
double [][] between = {{1,-1,0},{1,0,-1}};
double[][] betweenRandom = {{1},{1}};
params.setBetweenSubjectContrast(new FixedRandomMatrix(between, betweenRandom, true));
// build within subject contrast
double [][] within = {{1,0},{0,1}};
params.setWithinSubjectContrast(new Array2DRowRealMatrix(within));
// set the sigma error matrix to [sigmaY - sigmaYG * sigmaG-1 * sigmaGY]
RealMatrix sigmaGY = params.getSigmaOutcomeGaussianRandom().transpose();
RealMatrix sigmaGInverse = new LUDecomposition(params.getSigmaGaussianRandom()).getSolver().getInverse();
params.setSigmaError(params.getSigmaOutcome().subtract(params.getSigmaOutcomeGaussianRandom().multiply(sigmaGInverse.multiply(sigmaGY))));
return params;
}
}
| SampleSizeShop/JavaStatistics | src/edu/cudenver/bios/power/test/general/TestNonCentralityDistribution.java | Java | gpl-2.0 | 8,632 |
/*
* Copyright (c) 1999, 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. 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 mono.debugger.request;
/**
* Thrown to indicate that the requested event cannot be modified
* because it is enabled. Filters can be added only to disabled
* event requests.
* Also thrown if an operation is attempted on a deleted request.
* See {@link EventRequestManager#deleteEventRequest(EventRequest)}
*
* @author Robert Field
* @since 1.3
*/
public class InvalidRequestStateException extends RuntimeException {
private static final long serialVersionUID = -3774632428543322148L;
public InvalidRequestStateException()
{
super();
}
public InvalidRequestStateException(String s)
{
super(s);
}
}
| consulo/mono-soft-debugging | src/main/java/mono/debugger/request/InvalidRequestStateException.java | Java | gpl-2.0 | 1,874 |
package br.com.msystem.db.bo;
import java.io.Serializable;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import br.com.msystem.db.dao.InterfaceDao;
@Service
@Transactional
public abstract class AbstractBo<T> implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2462393380275995367L;
@Autowired
private InterfaceDao<T> dao;
public T buscar(Serializable id) {
return dao.buscar(id);
}
public void excluir(Serializable id) {
dao.excluir(id);
}
public T salvar(T entity) {
return dao.salvar(entity);
}
public List<T> executeNamedQuery(String namedQuery, Object... parameters) {
return dao.executeNamedQuery(namedQuery, parameters);
}
public List<T> listAll() {
return dao.listAll();
}
}
| samaanfilho/agenda | src/java/dbProject/src/br/com/msystem/db/bo/AbstractBo.java | Java | gpl-2.0 | 977 |
/*
* 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 net.sf.l2j.gameserver.serverpackets;
import net.sf.l2j.gameserver.model.actor.instance.L2StaticObjectInstance;
public class StaticObject extends L2GameServerPacket
{
private static final String _S__99_StaticObjectPacket = "[S] 99 StaticObjectPacket";
private final L2StaticObjectInstance _staticObject;
/**
* [S]0x99 StaticObjectPacket dd
* @param StaticObject
*/
public StaticObject(L2StaticObjectInstance StaticObject)
{
_staticObject = StaticObject; // staticObjectId
}
@Override
protected final void writeImpl()
{
writeC(0x99);
writeD(_staticObject.getStaticObjectId()); // staticObjectId
writeD(_staticObject.getObjectId()); // objectId
}
@Override
public String getType()
{
return _S__99_StaticObjectPacket;
}
}
| oonym/l2InterludeServer | L2J_Server/java/net/sf/l2j/gameserver/serverpackets/StaticObject.java | Java | gpl-2.0 | 1,463 |
/*
* This is the source code of Telegram for Android v. 1.3.2.
* 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.
*/
package org.telegram.ui;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.ui.Views.ActionBar.ActionBarLayer;
import org.telegram.ui.Views.ActionBar.ActionBarMenu;
import org.telegram.ui.Views.BackupImageView;
import org.telegram.ui.Views.ActionBar.BaseFragment;
import org.telegram.ui.Views.PinnedHeaderListView;
import org.telegram.ui.Views.SectionedBaseAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
public class GroupCreateActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate {
public static class XImageSpan extends ImageSpan {
public int uid;
public XImageSpan(Drawable d, int verticalAlignment) {
super(d, verticalAlignment);
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
if (fm == null) {
fm = new Paint.FontMetricsInt();
}
int sz = super.getSize(paint, text, start, end, fm);
int offset = Utilities.dp(6);
int w = (fm.bottom - fm.top) / 2;
fm.top = -w - offset;
fm.bottom = w - offset;
fm.ascent = -w - offset;
fm.leading = 0;
fm.descent = w - offset;
return sz;
}
}
private SectionedBaseAdapter listViewAdapter;
private PinnedHeaderListView listView;
private TextView emptyTextView;
private EditText userSelectEditText;
private boolean ignoreChange = false;
private HashMap<Integer, XImageSpan> selectedContacts = new HashMap<Integer, XImageSpan>();
private ArrayList<XImageSpan> allSpans = new ArrayList<XImageSpan>();
private boolean searchWas;
private boolean searching;
private Timer searchTimer;
public ArrayList<TLRPC.User> searchResult;
public ArrayList<CharSequence> searchResultNames;
private CharSequence changeString;
private int beforeChangeIndex;
private final static int done_button = 1;
@Override
public boolean onFragmentCreate() {
NotificationCenter.getInstance().addObserver(this, MessagesController.contactsDidLoaded);
NotificationCenter.getInstance().addObserver(this, MessagesController.updateInterfaces);
NotificationCenter.getInstance().addObserver(this, MessagesController.chatDidCreated);
return super.onFragmentCreate();
}
@Override
public void onFragmentDestroy() {
super.onFragmentDestroy();
NotificationCenter.getInstance().removeObserver(this, MessagesController.contactsDidLoaded);
NotificationCenter.getInstance().removeObserver(this, MessagesController.updateInterfaces);
NotificationCenter.getInstance().removeObserver(this, MessagesController.chatDidCreated);
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
if (fragmentView == null) {
actionBarLayer.setDisplayHomeAsUpEnabled(true, R.drawable.ic_ab_back);
actionBarLayer.setBackOverlay(R.layout.updating_state_layout);
actionBarLayer.setTitle(LocaleController.getString("NewGroup", R.string.NewGroup));
actionBarLayer.setSubtitle(String.format("%d/200 %s", selectedContacts.size(), LocaleController.getString("Members", R.string.Members)));
actionBarLayer.setActionBarMenuOnItemClick(new ActionBarLayer.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
finishFragment();
} else if (id == done_button) {
if (!selectedContacts.isEmpty()) {
ArrayList<Integer> result = new ArrayList<Integer>();
result.addAll(selectedContacts.keySet());
Bundle args = new Bundle();
args.putIntegerArrayList("result", result);
presentFragment(new GroupCreateFinalActivity(args));
}
}
}
});
ActionBarMenu menu = actionBarLayer.createMenu();
View doneItem = menu.addItemResource(done_button, R.layout.group_create_done_layout);
TextView doneTextView = (TextView)doneItem.findViewById(R.id.done_button);
doneTextView.setText(LocaleController.getString("Next", R.string.Next));
searching = false;
searchWas = false;
fragmentView = inflater.inflate(R.layout.group_create_layout, container, false);
emptyTextView = (TextView)fragmentView.findViewById(R.id.searchEmptyView);
emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts));
userSelectEditText = (EditText)fragmentView.findViewById(R.id.bubble_input_text);
userSelectEditText.setHint(LocaleController.getString("SendMessageTo", R.string.SendMessageTo));
if (Build.VERSION.SDK_INT >= 11) {
userSelectEditText.setTextIsSelectable(false);
}
userSelectEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
if (!ignoreChange) {
beforeChangeIndex = userSelectEditText.getSelectionStart();
changeString = new SpannableString(charSequence);
}
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void afterTextChanged(Editable editable) {
if (!ignoreChange) {
boolean search = false;
int afterChangeIndex = userSelectEditText.getSelectionEnd();
if (editable.toString().length() < changeString.toString().length()) {
String deletedString = "";
try {
deletedString = changeString.toString().substring(afterChangeIndex, beforeChangeIndex);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
if (deletedString.length() > 0) {
if (searching && searchWas) {
search = true;
}
Spannable span = userSelectEditText.getText();
for (int a = 0; a < allSpans.size(); a++) {
XImageSpan sp = allSpans.get(a);
if (span.getSpanStart(sp) == -1) {
allSpans.remove(sp);
selectedContacts.remove(sp.uid);
}
}
actionBarLayer.setSubtitle(String.format("%d/200 %s", selectedContacts.size(), LocaleController.getString("Members", R.string.Members)));
listView.invalidateViews();
} else {
search = true;
}
} else {
search = true;
}
if (search) {
String text = userSelectEditText.getText().toString().replace("<", "");
if (text.length() != 0) {
searchDialogs(text);
searching = true;
searchWas = true;
emptyTextView.setText(LocaleController.getString("NoResult", R.string.NoResult));
listViewAdapter.notifyDataSetChanged();
} else {
searchResult = null;
searchResultNames = null;
searching = false;
searchWas = false;
emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts));
listViewAdapter.notifyDataSetChanged();
}
}
}
}
});
listView = (PinnedHeaderListView)fragmentView.findViewById(R.id.listView);
listView.setEmptyView(emptyTextView);
listView.setVerticalScrollBarEnabled(false);
listView.setAdapter(listViewAdapter = new ListAdapter(getParentActivity()));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TLRPC.User user;
int section = listViewAdapter.getSectionForPosition(i);
int row = listViewAdapter.getPositionInSectionForPosition(i);
if (searching && searchWas) {
user = searchResult.get(row);
} else {
ArrayList<TLRPC.TL_contact> arr = ContactsController.getInstance().usersSectionsDict.get(ContactsController.getInstance().sortedUsersSectionsArray.get(section));
user = MessagesController.getInstance().users.get(arr.get(row).user_id);
listView.invalidateViews();
}
if (selectedContacts.containsKey(user.id)) {
XImageSpan span = selectedContacts.get(user.id);
selectedContacts.remove(user.id);
SpannableStringBuilder text = new SpannableStringBuilder(userSelectEditText.getText());
text.delete(text.getSpanStart(span), text.getSpanEnd(span));
allSpans.remove(span);
ignoreChange = true;
userSelectEditText.setText(text);
userSelectEditText.setSelection(text.length());
ignoreChange = false;
} else {
if (selectedContacts.size() == 200) {
return;
}
ignoreChange = true;
XImageSpan span = createAndPutChipForUser(user);
span.uid = user.id;
ignoreChange = false;
}
actionBarLayer.setSubtitle(String.format("%d/200 %s", selectedContacts.size(), LocaleController.getString("Members", R.string.Members)));
if (searching || searchWas) {
searching = false;
searchWas = false;
emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts));
ignoreChange = true;
SpannableStringBuilder ssb = new SpannableStringBuilder("");
for (ImageSpan sp : allSpans) {
ssb.append("<<");
ssb.setSpan(sp, ssb.length() - 2, ssb.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
}
userSelectEditText.setText(ssb);
userSelectEditText.setSelection(ssb.length());
ignoreChange = false;
listViewAdapter.notifyDataSetChanged();
} else {
listView.invalidateViews();
}
}
});
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
if (i == SCROLL_STATE_TOUCH_SCROLL) {
Utilities.hideKeyboard(userSelectEditText);
}
}
@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
} else {
ViewGroup parent = (ViewGroup)fragmentView.getParent();
if (parent != null) {
parent.removeView(fragmentView);
}
}
return fragmentView;
}
public XImageSpan createAndPutChipForUser(TLRPC.User user) {
LayoutInflater lf = (LayoutInflater)ApplicationLoader.applicationContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View textView = lf.inflate(R.layout.group_create_bubble, null);
TextView text = (TextView)textView.findViewById(R.id.bubble_text_view);
String name = Utilities.formatName(user.first_name, user.last_name);
if (name.length() == 0 && user.phone != null && user.phone.length() != 0) {
name = PhoneFormat.getInstance().format("+" + user.phone);
}
text.setText(name + ", ");
int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
textView.measure(spec, spec);
textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());
Bitmap b = Bitmap.createBitmap(textView.getWidth(), textView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(b);
canvas.translate(-textView.getScrollX(), -textView.getScrollY());
textView.draw(canvas);
textView.setDrawingCacheEnabled(true);
Bitmap cacheBmp = textView.getDrawingCache();
Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);
textView.destroyDrawingCache();
final BitmapDrawable bmpDrawable = new BitmapDrawable(b);
bmpDrawable.setBounds(0, 0, b.getWidth(), b.getHeight());
SpannableStringBuilder ssb = new SpannableStringBuilder("");
XImageSpan span = new XImageSpan(bmpDrawable, ImageSpan.ALIGN_BASELINE);
allSpans.add(span);
selectedContacts.put(user.id, span);
for (ImageSpan sp : allSpans) {
ssb.append("<<");
ssb.setSpan(sp, ssb.length() - 2, ssb.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
}
userSelectEditText.setText(ssb);
userSelectEditText.setSelection(ssb.length());
return span;
}
public void searchDialogs(final String query) {
if (query == null) {
searchResult = null;
searchResultNames = null;
} else {
try {
if (searchTimer != null) {
searchTimer.cancel();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
searchTimer = new Timer();
searchTimer.schedule(new TimerTask() {
@Override
public void run() {
try {
searchTimer.cancel();
searchTimer = null;
} catch (Exception e) {
FileLog.e("tmessages", e);
}
processSearch(query);
}
}, 100, 300);
}
}
private void processSearch(final String query) {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
final ArrayList<TLRPC.TL_contact> contactsCopy = new ArrayList<TLRPC.TL_contact>();
contactsCopy.addAll(ContactsController.getInstance().contacts);
Utilities.searchQueue.postRunnable(new Runnable() {
@Override
public void run() {
if (query.length() == 0) {
updateSearchResults(new ArrayList<TLRPC.User>(), new ArrayList<CharSequence>());
return;
}
long time = System.currentTimeMillis();
ArrayList<TLRPC.User> resultArray = new ArrayList<TLRPC.User>();
ArrayList<CharSequence> resultArrayNames = new ArrayList<CharSequence>();
String q = query.toLowerCase();
for (TLRPC.TL_contact contact : contactsCopy) {
TLRPC.User user = MessagesController.getInstance().users.get(contact.user_id);
if (user.first_name.toLowerCase().startsWith(q) || user.last_name.toLowerCase().startsWith(q)) {
if (user.id == UserConfig.getClientUserId()) {
continue;
}
resultArrayNames.add(Utilities.generateSearchName(user.first_name, user.last_name, q));
resultArray.add(user);
}
}
updateSearchResults(resultArray, resultArrayNames);
}
});
}
});
}
private void updateSearchResults(final ArrayList<TLRPC.User> users, final ArrayList<CharSequence> names) {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
searchResult = users;
searchResultNames = names;
listViewAdapter.notifyDataSetChanged();
}
});
}
@Override
public void didReceivedNotification(int id, Object... args) {
if (id == MessagesController.contactsDidLoaded) {
if (listViewAdapter != null) {
listViewAdapter.notifyDataSetChanged();
}
} else if (id == MessagesController.updateInterfaces) {
int mask = (Integer)args[0];
if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0 || (mask & MessagesController.UPDATE_MASK_STATUS) != 0) {
if (listView != null) {
listView.invalidateViews();
}
}
} else if (id == MessagesController.chatDidCreated) {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
removeSelfFromStack();
}
});
}
}
private class ListAdapter extends SectionedBaseAdapter {
private Context mContext;
public ListAdapter(Context context) {
mContext = context;
}
@Override
public Object getItem(int section, int position) {
return null;
}
@Override
public long getItemId(int section, int position) {
return 0;
}
@Override
public int getSectionCount() {
if (searching && searchWas) {
return searchResult == null || searchResult.isEmpty() ? 0 : 1;
}
return ContactsController.getInstance().sortedUsersSectionsArray.size();
}
@Override
public int getCountForSection(int section) {
if (searching && searchWas) {
return searchResult == null ? 0 : searchResult.size();
}
ArrayList<TLRPC.TL_contact> arr = ContactsController.getInstance().usersSectionsDict.get(ContactsController.getInstance().sortedUsersSectionsArray.get(section));
return arr.size();
}
@Override
public View getItemView(int section, int position, View convertView, ViewGroup parent) {
TLRPC.User user;
int size;
if (searchWas && searching) {
user = MessagesController.getInstance().users.get(searchResult.get(position).id);
size = searchResult.size();
} else {
ArrayList<TLRPC.TL_contact> arr = ContactsController.getInstance().usersSectionsDict.get(ContactsController.getInstance().sortedUsersSectionsArray.get(section));
user = MessagesController.getInstance().users.get(arr.get(position).user_id);
size = arr.size();
}
if (convertView == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.group_create_row_layout, parent, false);
}
ContactListRowHolder holder = (ContactListRowHolder)convertView.getTag();
if (holder == null) {
holder = new ContactListRowHolder(convertView);
convertView.setTag(holder);
}
ImageView checkButton = (ImageView)convertView.findViewById(R.id.settings_row_check_button);
if (selectedContacts.containsKey(user.id)) {
checkButton.setImageResource(R.drawable.btn_check_on_holo_light);
} else {
checkButton.setImageResource(R.drawable.btn_check_off_holo_light);
}
View divider = convertView.findViewById(R.id.settings_row_divider);
if (position == size - 1) {
divider.setVisibility(View.INVISIBLE);
} else {
divider.setVisibility(View.VISIBLE);
}
if (searchWas && searching) {
holder.nameTextView.setText(searchResultNames.get(position));
} else {
String name = Utilities.formatName(user.first_name, user.last_name);
if (name.length() == 0) {
if (user.phone != null && user.phone.length() != 0) {
name = PhoneFormat.getInstance().format("+" + user.phone);
} else {
name = LocaleController.getString("HiddenName", R.string.HiddenName);
}
}
holder.nameTextView.setText(name);
}
TLRPC.FileLocation photo = null;
if (user.photo != null) {
photo = user.photo.photo_small;
}
int placeHolderId = Utilities.getUserAvatarForId(user.id);
holder.avatarImage.setImage(photo, "50_50", placeHolderId);
holder.messageTextView.setText(LocaleController.formatUserStatus(user));
if (user.status != null && user.status.expires > ConnectionsManager.getInstance().getCurrentTime()) {
holder.messageTextView.setTextColor(0xff357aa8);
} else {
holder.messageTextView.setTextColor(0xff808080);
}
return convertView;
}
@Override
public int getItemViewType(int section, int position) {
return 0;
}
@Override
public int getItemViewTypeCount() {
return 1;
}
@Override
public int getSectionHeaderViewType(int section) {
return 0;
}
@Override
public int getSectionHeaderViewTypeCount() {
return 1;
}
@Override
public View getSectionHeaderView(int section, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.settings_section_layout, parent, false);
convertView.setBackgroundColor(0xffffffff);
}
TextView textView = (TextView)convertView.findViewById(R.id.settings_section_text);
if (searching && searchWas) {
textView.setText(LocaleController.getString("AllContacts", R.string.AllContacts));
} else {
textView.setText(ContactsController.getInstance().sortedUsersSectionsArray.get(section));
}
return convertView;
}
}
public static class ContactListRowHolder {
public BackupImageView avatarImage;
public TextView messageTextView;
public TextView nameTextView;
public ContactListRowHolder(View view) {
messageTextView = (TextView)view.findViewById(R.id.messages_list_row_message);
nameTextView = (TextView)view.findViewById(R.id.messages_list_row_name);
avatarImage = (BackupImageView)view.findViewById(R.id.messages_list_row_avatar);
}
}
}
| cbedoy/WAYGRAM | TMessagesProj/src/main/java/org/telegram/ui/GroupCreateActivity.java | Java | gpl-2.0 | 26,430 |
/*
* Copyright (c) 2012-2013 Open Source Community - <http://www.peerfact.org>
* Copyright (c) 2011-2012 University of Paderborn - UPB
* Copyright (c) 2005-2011 KOM - Multimedia Communications Lab
*
* This file is part of PeerfactSim.KOM.
*
* PeerfactSim.KOM 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
* any later version.
*
* PeerfactSim.KOM 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 PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.peerfact.impl.overlay.informationdissemination.mercury;
import java.awt.Point;
import java.math.BigInteger;
import java.util.List;
import org.apache.log4j.Logger;
import org.peerfact.api.overlay.OverlayID;
import org.peerfact.impl.service.publishsubscribe.mercury.MercuryListener;
import org.peerfact.impl.service.publishsubscribe.mercury.attribute.IMercuryAttribute;
import org.peerfact.impl.service.publishsubscribe.mercury.messages.MercuryPayload;
import org.peerfact.impl.util.logging.SimLogger;
/**
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
* This part of the Simulator is not maintained in the current version of
* PeerfactSim.KOM. There is no intention of the authors to fix this
* circumstances, since the changes needed are huge compared to overall benefit.
*
* If you want it to work correctly, you are free to make the specific changes
* and provide it to the community.
* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!
*
* The implementation of the {@link MercuryListener} for IDO Mercury.
*
* @author Christoph Muenker <[email protected]>
* @version 01/28/2011
*
*/
public class MercuryIDOListener implements MercuryListener {
/**
* The logger for this class
*/
final static Logger log = SimLogger.getLogger(MercuryIDOListener.class);
/**
* The mercury ido node, which has this listener created.
*/
private MercuryIDONode node;
/**
* Creates an Listener and set the Mercury IDO node.
*
* @param node
* The node, which has this Listener create.
*/
public MercuryIDOListener(MercuryIDONode node) {
this.node = node;
}
@Override
public void notificationReceived(MercuryPayload payload,
List<IMercuryAttribute> attributes) {
if (payload instanceof MercuryIDOPayload) {
MercuryIDOPayload mPayload = (MercuryIDOPayload) payload;
// take x and y from the payload.
Integer x = null;
Integer y = null;
for (IMercuryAttribute attr : attributes) {
if (attr.getName().equals("x")) {
x = (Integer) attr.getValue();
}
if (attr.getName().equals("y")) {
y = (Integer) attr.getValue();
}
}
if (x == null || y == null) {
log.error("x or y are not in payload! Abort the notification handling");
return;
}
Point position = new Point(x, y);
int aoi = mPayload.getAoi();
OverlayID<BigInteger> id = mPayload.getId();
// store the received information
node.getStorage().addNodeInfo(
new MercuryNodeInfo(position, aoi, id));
}
}
}
| flyroom/PeerfactSimKOM_Clone | src/org/peerfact/impl/overlay/informationdissemination/mercury/MercuryIDOListener.java | Java | gpl-2.0 | 3,456 |
package aku.IO.XML;
import akgl.Units.GLTypes.Extensions.UI.Sprites.SlicedSprite;
import akgl.Units.GLTypes.Extensions.UI.Text.TextLabel;
import akgl.Units.GLTypes.GLObject;
import aku.AncientKemetRegistry;
import aku.IO.XML.UIComponents.XMLComponentHandler;
import aku.IO.XML.XMLHelpers.RootHelper;
import aku.IO.XML.XMLHelpers.VectorParsing;
import java.net.URL;
import java.util.List;
import javax.xml.parsers.*;
import org.w3c.dom.*;
/**
* @author Robert Kollar
*/
public class XMLLoader {
public static GLObject loadCompositionFromKXML(String filename) throws Exception {
//Get the DOM Builder Factory
DocumentBuilderFactory factory
= DocumentBuilderFactory.newInstance();
//Get the DOM Builder
DocumentBuilder builder = factory.newDocumentBuilder();
//Load and Parse the XML document
//document contains the complete XML as a Tree.
Document document
= builder.parse(new URL(AncientKemetRegistry.getDataHost() + "xml/" + filename + ".xml").openStream());
//Iterating through the nodes and extracting the data.
return parseNode(document.getDocumentElement());
}
public static GLObject parseNode(Node node) {
GLObject glo = new GLObject(null);
/*
* parse atributes
*/
//tranforms
if (node.hasAttributes()) {
Node position = node.getAttributes().getNamedItem("pos");
Node scale = node.getAttributes().getNamedItem("scale");
if (position != null) {
glo.getTransform().getLocalPosition().set(VectorParsing.parseVec3(position));
}
if (scale != null) {
glo.getTransform().getScale().set(VectorParsing.parseVec3(scale));
}
}
//use helpers for the rest
switch (node.getNodeName()) {
case "root":
RootHelper.parseRoot(glo, node);
break;
default:
XMLComponentHandler.loadComponentToObject(glo, node);
}
/*
* parse children
*/
if (node.hasChildNodes()) {
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
if (!nodeList.item(i).getNodeName().equalsIgnoreCase("#text")) {
GLObject child = parseNode(nodeList.item(i));
child.setParent(glo);
}
}
}
return glo;
}
}
| AncientKemet/Ancient-Kemet-Utility | aku/IO/XML/XMLLoader.java | Java | gpl-2.0 | 2,543 |
package org.totalboumboum.ai.v201112.ais._simplet.v1.criterion;
/*
* Total Boum Boum
* Copyright 2008-2014 Vincent Labatut
*
* This file is part of Total Boum Boum.
*
* Total Boum Boum 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.
*
* Total Boum Boum 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 Total Boum Boum. If not, see <http://www.gnu.org/licenses/>.
*
*/
import org.totalboumboum.ai.v201112.ais._simplet.v1.CommonTools;
import org.totalboumboum.ai.v201112.ais._simplet.v1.Simplet;
import org.totalboumboum.ai.v201112.adapter.agent.AiUtilityCriterionInteger;
import org.totalboumboum.ai.v201112.adapter.communication.StopRequestException;
import org.totalboumboum.ai.v201112.adapter.data.AiTile;
/**
* Cette classe représente le critère de menace envers l'adversaire.
* Il est entier : la valeur comprise entre 1 et {@value #THREAT_LIMIT}
* représente la distance entre la case et la cible.
*
* @author Vincent Labatut
*/
@SuppressWarnings("deprecation")
public class CriterionThreat extends AiUtilityCriterionInteger
{ /** Nom de ce critère */
public static final String NAME = "THREAT";
/**
* Crée un nouveau critère entier.
*
* @param ai
* L'agent concerné.
*
* @throws StopRequestException
* Au cas où le moteur demande la terminaison de l'agent.
*/
public CriterionThreat(Simplet ai) throws StopRequestException
{ // init nom
super(NAME,1,THREAT_LIMIT);
ai.checkInterruption();
// init agent
this.ai = ai;
}
/////////////////////////////////////////////////////////////////
// ARTIFICIAL INTELLIGENCE /////////////////////////////////////
/////////////////////////////////////////////////////////////////
/** L'agent associé au traitement */
protected Simplet ai;
/////////////////////////////////////////////////////////////////
// PROCESS /////////////////////////////////////
/////////////////////////////////////////////////////////////////
/** Valeur maximale pour ce critère */
public static final int THREAT_LIMIT = 4;
@Override
public Integer processValue(AiTile tile) throws StopRequestException
{ ai.checkInterruption();
CommonTools commonTools = ai.commonTools;
// on récupère la distance à la cible : plus c'est prêt, mieux c'est
// (-> très mauvaise stratégie !)
int distance = commonTools.getDistanceToTarget(tile);
// on ne veut quand même pas être sur le joueur, ça c'est très mauvais
if(distance<1)
distance = THREAT_LIMIT;
// si on est trop loin, ça ne fait plus de différence
else if(distance>THREAT_LIMIT)
distance = THREAT_LIMIT;
int result = THREAT_LIMIT - distance + 1;
return result;
}
}
| vlabatut/totalboumboum | resources/ai/org/totalboumboum/ai/v201112/ais/_simplet/v1/criterion/CriterionThreat.java | Java | gpl-2.0 | 3,227 |
/*
* Copyright (C) 2017 即时通讯网(52im.net) & Jack Jiang.
* The MobileIMSDK_X_netty (MobileIMSDK v3.x Netty版) Project.
* All rights reserved.
*
* > Github地址: https://github.com/JackJiang2011/MobileIMSDK
* > 文档地址: http://www.52im.net/forum-89-1.html
* > 即时通讯技术社区:http://www.52im.net/
* > 即时通讯技术交流群:320837163 (http://www.52im.net/topic-qqgroup.html)
*
* "即时通讯网(52im.net) - 即时通讯开发者社区!" 推荐开源工程。
*
* PKeepAlive.java at 2017-12-9 11:24:33, code by Jack Jiang.
* You can contact author with [email protected] or [email protected].
*/
package net.openmob.mobileimsdk.server.protocal.c;
public class PKeepAlive
{
}
| suxinde2009/MobileIMSDK | src_all/libs_src/MobileIMSDKServerX_netty_Open/src/net/openmob/mobileimsdk/server/protocal/c/PKeepAlive.java | Java | gpl-2.0 | 748 |
/*
* Copyright (C) 2002-2013 Michael Koch ([email protected])
*
* This file is part of JGloss.
*
* JGloss 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.
*
* JGloss 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 JGloss; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
*/
package jgloss.ui;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.KeyStroke;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.HyperlinkEvent;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Element;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import jgloss.ui.util.UIUtilities;
/**
* Allow keyboard navigation of links in a <code>JEditorPane</code> showing HTML content.
* <p>
* There is already similar functionality built into the HTML editor kit, but the default
* keyboard keys are impractical, the implemetation does not work well and the corresponding
* actions are not documented, so I decided to roll my own implementation.
* </p>
*
* @author Michael Koch
*/
public class HyperlinkKeyNavigator implements DocumentListener, PropertyChangeListener {
private static final Logger LOGGER = Logger.getLogger(HyperlinkKeyNavigator.class.getPackage().getName());
protected Element currentElement;
protected Object highlightTag;
protected JEditorPane editor;
protected HTMLDocument document;
protected MoveLinkAction nextLinkAction;
protected MoveLinkAction previousLinkAction;
protected ActivateLinkAction activateLinkAction;
protected DefaultHighlighter.DefaultHighlightPainter highlightPainter;
public HyperlinkKeyNavigator() {
this(Color.CYAN);
}
public HyperlinkKeyNavigator(Color highlightColor) {
createHighlightPainter(highlightColor);
nextLinkAction = new MoveLinkAction("nextLinkAction", false,
KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));
previousLinkAction = new MoveLinkAction("previousLinkAction", true,
KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0));
activateLinkAction = new ActivateLinkAction("activateLinkAction",
KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0));
}
public void setTargetEditor(JEditorPane _editor) {
if (editor == _editor) {
return;
}
if (editor != null) {
editor.removePropertyChangeListener(this);
editor.setInputMap(JComponent.WHEN_FOCUSED, editor.getInputMap().getParent());
editor.setActionMap(editor.getActionMap().getParent());
}
if (document != null) {
document.removeDocumentListener(this);
document = null;
}
if (_editor != null) {
_editor.addPropertyChangeListener(this);
InputMap inputmap = new InputMap();
inputmap.put((KeyStroke) nextLinkAction.getValue(Action.ACCELERATOR_KEY),
nextLinkAction.getValue(Action.NAME));
inputmap.put((KeyStroke) previousLinkAction.getValue(Action.ACCELERATOR_KEY),
previousLinkAction.getValue(Action.NAME));
inputmap.put((KeyStroke) activateLinkAction.getValue(Action.ACCELERATOR_KEY),
activateLinkAction.getValue(Action.NAME));
inputmap.setParent(_editor.getInputMap());
_editor.setInputMap(JComponent.WHEN_FOCUSED, inputmap);
ActionMap actionmap = new ActionMap();
actionmap.put(nextLinkAction.getValue(Action.NAME), nextLinkAction);
actionmap.put(previousLinkAction.getValue(Action.NAME), previousLinkAction);
actionmap.put(activateLinkAction.getValue(Action.NAME), activateLinkAction);
actionmap.setParent(_editor.getActionMap());
_editor.setActionMap(actionmap);
try {
document = (HTMLDocument) _editor.getDocument();
document.addDocumentListener(this);
resetSelection();
} catch (ClassCastException ex) {
document = null;
}
}
editor = _editor;
}
public void setHighlightColor(Color highlightColor) {
createHighlightPainter(highlightColor);
}
public Color getHighlightColor() {
return highlightPainter.getColor();
}
protected void createHighlightPainter(Color highlightColor) {
highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(highlightColor);
}
protected void setHighlight(int startOffset, int endOffset) {
try {
if (highlightTag != null) {
editor.getHighlighter().changeHighlight(highlightTag, startOffset, endOffset);
}
else {
highlightTag = editor.getHighlighter().addHighlight(startOffset, endOffset,
highlightPainter);
}
} catch (BadLocationException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
}
}
protected void removeHighlight() {
if (highlightTag != null) {
editor.getHighlighter().removeHighlight(highlightTag);
highlightTag = null;
}
}
@Override
public void propertyChange(PropertyChangeEvent event) {
if (event.getPropertyName().equalsIgnoreCase("document")) {
if (document != null) {
document.removeDocumentListener(this);
}
try {
document = (HTMLDocument) editor.getDocument();
document.addDocumentListener(this);
} catch (ClassCastException ex) {
document = null;
}
resetSelection();
}
}
@Override
public void changedUpdate(DocumentEvent e) {
if (currentElement == null ||
currentElement.getStartOffset()<=e.getOffset()+e.getLength() &&
currentElement.getEndOffset()>=e.getOffset()) {
// changed area intersects current element
resetSelection();
}
}
@Override
public void insertUpdate(DocumentEvent e) {
if (currentElement == null) {
resetSelection();
}
}
@Override
public void removeUpdate(DocumentEvent e) {
if (currentElement!=null &&
currentElement.getStartOffset()<=e.getOffset()+e.getLength() &&
currentElement.getEndOffset()>=e.getOffset()) {
// changed area intersects current element
resetSelection();
}
}
protected void resetSelection() {
removeHighlight();
currentElement = null;
// select the first link element
nextLinkAction.moveLink(editor, document);
}
/**
* Searches the first <code>a href</code> element after the given position.
*
* @return the element, or <code>null</code> if there is no such element.
*/
protected Element getFirstLinkAfter(int position, Element elem) {
if (elem.isLeaf()) {
AttributeSet att = elem.getAttributes();
if (elem.getStartOffset() >= position &&
att.isDefined(HTML.Tag.A) &&
((AttributeSet) att.getAttribute(HTML.Tag.A)).isDefined
(HTML.Attribute.HREF)) {
return elem; // element is first link after given position
}
}
else { // recurse over children
for (int i=0; i<elem.getElementCount(); i++) {
Element child = elem.getElement(i);
if (child.getEndOffset() > position) {
Element out = getFirstLinkAfter(position, child);
if (out != null) {
return out;
}
}
}
}
// No link element found in this recursion step
return null;
}
/**
* Searches the first <code>a href</code> element after the given position.
*
* @return the element, or <code>null</code> if there is no such element.
*/
protected Element getFirstLinkBefore(int position, Element elem) {
if (elem.isLeaf()) {
AttributeSet att = elem.getAttributes();
if (elem.getEndOffset() <= position &&
att.isDefined(HTML.Tag.A) &&
((AttributeSet) att.getAttribute(HTML.Tag.A)).isDefined
(HTML.Attribute.HREF)) {
return elem; // element is first link after given position
}
}
else { // recurse over children
for (int i=elem.getElementCount()-1; i>=0; i--) {
Element child = elem.getElement(i);
if (child.getStartOffset() < position) {
Element out = getFirstLinkBefore(position, child);
if (out != null) {
return out;
}
}
}
}
// No link element found in this recursion step
return null;
}
protected class MoveLinkAction extends AbstractAction {
private static final long serialVersionUID = 1L;
protected boolean backwards;
protected MoveLinkAction(String name, boolean _backwards, KeyStroke acceleratorKey) {
super(name);
this.backwards = _backwards;
putValue(ACCELERATOR_KEY, acceleratorKey);
}
@Override
public void actionPerformed(ActionEvent event) {
if (event.getSource()==editor && document!=null) {
moveLink(editor, document);
}
}
public void moveLink(JEditorPane editor, HTMLDocument doc) {
Element nextHref = null;
doc.readLock();
try {
if (backwards) {
if (currentElement != null) {
nextHref = getFirstLinkBefore(currentElement.getStartOffset(),
doc.getDefaultRootElement());
}
if (nextHref == null) {
// no current element, or no further link after current link element
// finds the current link element again if it is the only link in the
// document
nextHref = getFirstLinkBefore(doc.getLength(), doc.getDefaultRootElement());
}
}
else {
if (currentElement != null) {
nextHref = getFirstLinkAfter(currentElement.getEndOffset(),
doc.getDefaultRootElement());
}
if (nextHref == null) {
// no current element, or no further link after current link element
// finds the current link element again if it is the only link in the
// document
nextHref = getFirstLinkAfter(0, doc.getDefaultRootElement());
}
}
} finally {
doc.readUnlock();
}
if (nextHref != null) {
currentElement = nextHref;
setHighlight(currentElement.getStartOffset(), currentElement.getEndOffset());
UIUtilities.makeVisible(editor, currentElement.getStartOffset(),
currentElement.getEndOffset());
activateLinkAction.setEnabled(true);
}
else {
// no href element in document
removeHighlight();
currentElement = null;
activateLinkAction.setEnabled(false);
}
}
}
protected class ActivateLinkAction extends AbstractAction {
private static final long serialVersionUID = 1L;
protected ActivateLinkAction(String name, KeyStroke acceleratorKey) {
super(name);
putValue(ACCELERATOR_KEY, acceleratorKey);
}
@Override
public void actionPerformed(ActionEvent event) {
if (event.getSource()==editor && document!=null) {
activateLink();
}
}
public void activateLink() {
if (currentElement == null) {
return;
}
String currentURL = (String) ((AttributeSet) currentElement.getAttributes().getAttribute
(HTML.Tag.A)).getAttribute(HTML.Attribute.HREF);
URL parsedURL = null;
try {
parsedURL = new URL(currentURL);
} catch (MalformedURLException ex) {}
editor.fireHyperlinkUpdate(new HyperlinkEvent(editor, HyperlinkEvent.EventType.ACTIVATED,
parsedURL, currentURL, currentElement));
}
}
} // class HyperlinkKeyNavigator
| tensberg/jgloss-mirror | jdictionary/src/main/java/jgloss/ui/HyperlinkKeyNavigator.java | Java | gpl-2.0 | 14,181 |
package com.googry.android.gradproj.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.googry.android.gradproj.R;
import com.googry.android.gradproj.data.Exhibition;
import com.googry.android.gradproj.data.ExhibitionCheckIn;
import com.googry.android.gradproj.data.ExhibitionDataManager;
public class ExhibitionCheckInAdapter extends ArrayAdapter<ExhibitionCheckIn> {
private ArrayList<ExhibitionCheckIn> alExCheckIn;
private Context mContext;
private ArrayList<Exhibition> alExhibition;
public ExhibitionCheckInAdapter(Context context, int resource,
ArrayList<ExhibitionCheckIn> objects) {
super(context, resource, objects);
alExCheckIn = objects;
mContext = context;
alExhibition = ExhibitionDataManager.getInstance().getAlExhibition();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row_exhibitioncheckinlist, null);
}
ExhibitionCheckIn ehCheckIn = alExCheckIn.get(position);
Exhibition exhibition = alExhibition.get(alExCheckIn.get(position)
.getIndex() - 1);
if (ehCheckIn != null) {
TextView tv_productName = (TextView) v
.findViewById(R.id.tv_productName);
TextView tv_teamName = (TextView) v.findViewById(R.id.tv_teamName);
TextView tv_teamMember = (TextView) v
.findViewById(R.id.tv_teamMember);
TextView tv_checkInTime = (TextView) v
.findViewById(R.id.tv_checkInTime);
if (tv_productName != null) {
tv_productName.setText(exhibition.getProductName());
}
if (tv_teamName != null) {
tv_teamName.setText(mContext.getString(R.string.str_teamName)
+ " : " + exhibition.getTeamName());
}
if (tv_teamMember != null) {
tv_teamMember.setText(mContext.getString(R.string.str_member)
+ " : " + exhibition.getMember());
}
if (tv_checkInTime != null) {
tv_checkInTime.setText(ehCheckIn.getCheckIn());
}
}
return v;
}
}
| imsukmin/SmartExhibition | app/SmartExhibition/src/com/googry/android/gradproj/adapter/ExhibitionCheckInAdapter.java | Java | gpl-2.0 | 2,306 |
package com.datastructures.orderedbinarytree;
public class Node {
private Node leftNode, rightNode;
private int data;
public Node(int data) {
this.data = data;
leftNode = rightNode = null;
}
public void setLeftNode(Node leftNode) {
this.leftNode = leftNode;
}
public void setRightNode(Node rightNode) {
this.rightNode = rightNode;
}
public void setData(int data) {
this.data = data;
}
public Node getLeftNode() {
return leftNode;
}
public Node getRightNode() {
return rightNode;
}
public int getData() {
return data;
}
}
| Piski/VariousSmallProjects | Exercises/Exercises/src/com/datastructures/orderedbinarytree/Node.java | Java | gpl-2.0 | 562 |
/*
* TclTagger.java
*
* Copyright (C) 2002 Peter Graves
* $Id: TclTagger.java,v 1.1.1.1 2002/09/24 16:08:47 piso Exp $
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.armedbear.j;
import gnu.regexp.RE;
import gnu.regexp.REMatch;
import gnu.regexp.UncheckedRE;
import java.util.ArrayList;
public final class TclTagger extends Tagger {
private static final RE procRE = new UncheckedRE("^proc\\s+(\\S+)");
public TclTagger(SystemBuffer buffer) {
super(buffer);
}
public void run() {
ArrayList tags = new ArrayList();
Line line = buffer.getFirstLine();
while (line != null) {
String s = line.trim();
if (s != null) {
REMatch match;
if (s.startsWith("proc"))
match = procRE.getMatch(s);
else
match = null;
if (match != null) {
String name = s.substring(match.getSubStartIndex(1), match.getSubEndIndex(1));
tags.add(new LocalTag(name, line));
}
}
line = line.next();
}
buffer.setTags(tags);
}
}
| logicmoo/jrelisp-abcl-ws | src/org/armedbear/j/TclTagger.java | Java | gpl-2.0 | 1,653 |
package org.opennms.gwt.web.ui.asset.client.view;
public class AssetNodePageImpl_AssetNodePageUiBinderImpl_TemplateImpl implements org.opennms.gwt.web.ui.asset.client.view.AssetNodePageImpl_AssetNodePageUiBinderImpl.Template {
public com.google.gwt.safehtml.shared.SafeHtml html7(java.lang.String arg0) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<h3> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span> </h3>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
public com.google.gwt.safehtml.shared.SafeHtml html14(java.lang.String arg0,java.lang.String arg1,java.lang.String arg2,java.lang.String arg3,java.lang.String arg4,java.lang.String arg5,java.lang.String arg6,java.lang.String arg7,java.lang.String arg8,java.lang.String arg9,java.lang.String arg10,java.lang.String arg11) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg1));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg2));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg3));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg4));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg5));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg6));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg7));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg8));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg9));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg10));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg11));
sb.append("'></span>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
public com.google.gwt.safehtml.shared.SafeHtml html6(java.lang.String arg0,java.lang.String arg1,java.lang.String arg2,java.lang.String arg3,java.lang.String arg4,java.lang.String arg5,java.lang.String arg6,java.lang.String arg7) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg1));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg2));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg3));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg4));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg5));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg6));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg7));
sb.append("'></span>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
public com.google.gwt.safehtml.shared.SafeHtml html8(java.lang.String arg0,java.lang.String arg1,java.lang.String arg2,java.lang.String arg3,java.lang.String arg4,java.lang.String arg5,java.lang.String arg6,java.lang.String arg7,java.lang.String arg8,java.lang.String arg9,java.lang.String arg10,java.lang.String arg11,java.lang.String arg12,java.lang.String arg13,java.lang.String arg14,java.lang.String arg15,java.lang.String arg16) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg1));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg2));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg3));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg4));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg5));
sb.append("'></span> <br> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg6));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg7));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg8));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg9));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg10));
sb.append("'></span> <br> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg11));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg12));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg13));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg14));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg15));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg16));
sb.append("'></span>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
public com.google.gwt.safehtml.shared.SafeHtml html17(java.lang.String arg0,java.lang.String arg1,java.lang.String arg2,java.lang.String arg3) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg1));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg2));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg3));
sb.append("'></span>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
public com.google.gwt.safehtml.shared.SafeHtml html1(java.lang.String arg0) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<h3> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span> </h3>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
public com.google.gwt.safehtml.shared.SafeHtml html4(java.lang.String arg0,java.lang.String arg1,java.lang.String arg2,java.lang.String arg3) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg1));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg2));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg3));
sb.append("'></span>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
public com.google.gwt.safehtml.shared.SafeHtml html15(java.lang.String arg0) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<h3> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span> </h3>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
public com.google.gwt.safehtml.shared.SafeHtml html2(java.lang.String arg0,java.lang.String arg1,java.lang.String arg2,java.lang.String arg3,java.lang.String arg4) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg1));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg2));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg3));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg4));
sb.append("'></span>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
public com.google.gwt.safehtml.shared.SafeHtml html3(java.lang.String arg0) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<h3> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span> </h3>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
public com.google.gwt.safehtml.shared.SafeHtml html5(java.lang.String arg0) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<h3> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span> </h3>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
public com.google.gwt.safehtml.shared.SafeHtml html10(java.lang.String arg0,java.lang.String arg1,java.lang.String arg2,java.lang.String arg3,java.lang.String arg4,java.lang.String arg5,java.lang.String arg6,java.lang.String arg7,java.lang.String arg8) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg1));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg2));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg3));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg4));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg5));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg6));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg7));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg8));
sb.append("'></span>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
public com.google.gwt.safehtml.shared.SafeHtml html13(java.lang.String arg0) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<h3> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span> </h3>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
public com.google.gwt.safehtml.shared.SafeHtml html9(java.lang.String arg0) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<h3> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span> </h3>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
public com.google.gwt.safehtml.shared.SafeHtml html12(java.lang.String arg0,java.lang.String arg1,java.lang.String arg2,java.lang.String arg3,java.lang.String arg4,java.lang.String arg5) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg1));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg2));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg3));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg4));
sb.append("'></span> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg5));
sb.append("'></span>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
public com.google.gwt.safehtml.shared.SafeHtml html11(java.lang.String arg0) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<h3> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span> </h3>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
public com.google.gwt.safehtml.shared.SafeHtml html18(java.lang.String arg0,java.lang.String arg1,java.lang.String arg2) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<h2> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span> </h2> <p> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg1));
sb.append("'></span> </p> <span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg2));
sb.append("'></span>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
public com.google.gwt.safehtml.shared.SafeHtml html16(java.lang.String arg0) {
StringBuilder sb = new java.lang.StringBuilder();
sb.append("<span id='");
sb.append(com.google.gwt.safehtml.shared.SafeHtmlUtils.htmlEscape(arg0));
sb.append("'></span>");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
}
| vishwaAbhinav/OpenNMS | opennms-webapp/target/.generated/org/opennms/gwt/web/ui/asset/client/view/AssetNodePageImpl_AssetNodePageUiBinderImpl_TemplateImpl.java | Java | gpl-2.0 | 14,658 |
package com.ifhz.core.po;
import java.util.Date;
/**
* 类描述
* User: yangjian
*/
public class DeviceInfo {
private Long deviceId;
private String deviceCode;
private Long groupId;
private Long channelId;
private String active;
private Date createTime;
private Date updateTime;
private String deviceCodeCondition;
private String channelNameCondition;
private String groupName;
private String channelName;
public String getChannelNameCondition() {
return channelNameCondition;
}
public void setChannelNameCondition(String channelNameCondition) {
this.channelNameCondition = channelNameCondition;
}
public String getDeviceCodeCondition() {
return deviceCodeCondition;
}
public void setDeviceCodeCondition(String deviceCodeCondition) {
this.deviceCodeCondition = deviceCodeCondition;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getChannelName() {
return channelName;
}
public void setChannelName(String channelName) {
this.channelName = channelName;
}
public Long getDeviceId() {
return deviceId;
}
public void setDeviceId(Long deviceId) {
this.deviceId = deviceId;
}
public String getDeviceCode() {
return deviceCode;
}
public void setDeviceCode(String deviceCode) {
this.deviceCode = deviceCode;
}
public Long getGroupId() {
return groupId;
}
public void setGroupId(Long groupId) {
this.groupId = groupId;
}
public Long getChannelId() {
return channelId;
}
public void setChannelId(Long channelId) {
this.channelId = channelId;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("DeviceInfo{");
sb.append("deviceId=").append(deviceId);
sb.append(", deviceCode='").append(deviceCode).append('\'');
sb.append(", groupId=").append(groupId);
sb.append(", channelId=").append(channelId);
sb.append(", active='").append(active).append('\'');
sb.append(", createTime=").append(createTime);
sb.append(", updateTime=").append(updateTime);
sb.append(", deviceCodeCondition='").append(deviceCodeCondition).append('\'');
sb.append(", groupName='").append(groupName).append('\'');
sb.append(", channelName='").append(channelName).append('\'');
sb.append('}');
return sb.toString();
}
}
| cgxu1122/cmsmng | core/src/main/java/com/ifhz/core/po/DeviceInfo.java | Java | gpl-2.0 | 3,106 |
package com.hanvon.sulupen.sync;
import android.content.Context;
public class SyncInfo {
public final static int HVN_DELETE_TAGS = 1;
public final static int HVN_DELETE_FILES = 2;
public final static int HVN_UPLOAD_FILE = 3;
public final static int HVN_UPLOAD_TAGS = 4;
public final static int HVN_FILES_LIST = 5;
public final static int HVN_DOWN_SING_FILE = 6;
public final static int HVN_TAGS_LIST = 7;
public final static int HVN_DOWN_FILES = 8;
public final static int HVN_GET_SYSTEM_TIME = 9;
//public final static String HvnIpUrl = "http://dpi.hanvon.com/rt/ap/v1/";
public final static String HvnIpUrl = "http://cloud.hwyun.com/dws-cloud/rt/ap/v1/";
public final static String HvnDeleteTagsUrl = HvnIpUrl + "app/note/delTag";
public final static String HvnDeleteFilesUrl = HvnIpUrl + "app/note/delContent";
public final static String HvnUploadTagsUrl = HvnIpUrl + "app/note/uploadtags";
public final static String HvnUploadFileUrl = HvnIpUrl + "store/upload";
public final static String HvnFilesListUrl = HvnIpUrl + "app/note/contentlist";
public final static String HvnTagsListUrl = HvnIpUrl + "app/note/taglist";
// public final static String HvnDOWNSingFileUrl = "http://dpi.hanvon.com/pub/file/singledownload.do?input=";
// public final static String HvnDOWNFilesUrl = "http://dpi.hanvon.com/pub/file/download.do?input=";
public final static String HvnDOWNSingFileUrl = "http://cloud.hwyun.com/dws-cloud/pub/file/singledownload.do?input=";
public final static String HvnDOWNFilesUrl = "http://cloud.hwyun.com/dws-cloud/pub/file/download.do?input=";
public final static String HvnGetSystemTimeUrl = HvnIpUrl + "/pub/std/getSystemTime";
//下载解压文件根目录
public static final String DOWN_ZIP_DIR = "/data/data/com.hanvon.sulupen/down/";
//下载解析的图片文件
public static final String DOWN_PHOTO_DIR = "/data/data/com.hanvon.sulupen/users/";
public static int uploadTotal = 0;
public static String HvnSystemCurTime = "";
public static String HvnOldSynchroTime = "";
public static int downZipCount = 0;
public static int NoNeedDownNoteBooks = 0;
public static int NeedDownNoteBooks = 0;
public final static String SHOWDIOGSIGN = "com.hanvon.sulupen.showdiog";
public final static String DIMISSDIOGSIGN = "com.hanvon.sulupen.dimissdiog";
public final static String SYNCPROCESSEXCEPTION = "com.hanvon.sulupen.exception";
public static Context mContext = null;
public synchronized static void setNoNeedDownNoteBooks(){
NoNeedDownNoteBooks++;
}
public synchronized static void setNeedDownNoteBooks(){
NeedDownNoteBooks++;
}
public synchronized static int getNoNeedDownNoteBooks(){
return NoNeedDownNoteBooks;
}
public synchronized static int getNeedDownNoteBooks(){
return NeedDownNoteBooks;
}
public synchronized static void ClearNoNeedDownNoteBooks(){
NoNeedDownNoteBooks = 0;
}
public synchronized static void ClearNeedDownNoteBooks(){
NeedDownNoteBooks = 0;
}
}
| baiheng222/SuluPen | src/com/hanvon/sulupen/sync/SyncInfo.java | Java | gpl-2.0 | 3,192 |
/*
* Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.crypto.provider;
import java.io.*;
import java.security.*;
import javax.crypto.*;
final class SealedObjectForKeyProtector extends SealedObject {
static final long serialVersionUID = -3650226485480866989L;
SealedObjectForKeyProtector(Serializable object, Cipher c)
throws IOException, IllegalBlockSizeException {
super(object, c);
}
SealedObjectForKeyProtector(SealedObject so) {
super(so);
}
AlgorithmParameters getParameters() {
AlgorithmParameters params = null;
if (super.encodedParams != null) {
try {
params = AlgorithmParameters.getInstance("PBE", "SunJCE");
params.init(super.encodedParams);
} catch (NoSuchProviderException nspe) {
// eat.
} catch (NoSuchAlgorithmException nsae) {
//eat.
} catch (IOException ioe) {
//eat.
}
}
return params;
}
}
| karianna/jdk8_tl | jdk/src/share/classes/com/sun/crypto/provider/SealedObjectForKeyProtector.java | Java | gpl-2.0 | 2,219 |
package cs.ualberta.ca.tunein;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import cs.ualberta.ca.tunein.network.BitmapJsonConverter;
import cs.ualberta.ca.tunein.network.ElasticSearchOperations;
import cs.ualberta.ca.tunein.network.ElasticSearchOperationsInterface;
/**
* Controller
* CacheController Class:
* This controller is used to modify the cache list of
* a user. The main objective of the class is adding,
* removing, saving and loading from the cache singleton
* class.
*/
public class CacheController {
public final static String SAVE_FILE = "cache.sav";
private Cache saves;
private Gson GSON;
/**
* CacheController constructor that assigns
* the cache class to be modified
*/
public CacheController()
{
saves = Cache.getInstance();
constructGson();
}
/**
* This method adds a saved comment to the cache list.
* The max size of the list is 20 comments before the
* removal of the last comment (first in first out style)
* @param cntxt The context of the application.
* @param comment The comment that is saved
*/
public void addToCache(Context cntxt, Comment comment)
{
if(!(saves.cacheIDs.contains(comment.getElasticID())))
{
ElasticSearchOperationsInterface eso = new ElasticSearchOperations();
//get the saved comment's replies
eso.getReplyReplies(comment, comment.getElasticID(), cntxt);
//add new saved comment to beginning of list
saves.cacheIDs.add(0, comment.getElasticID());
saves.cacheList.add(0, comment);
//remove last element if cache gets too large
if(saves.cacheIDs.size() > 20)
{
removeFromCache(cntxt);
}
saveCache(cntxt);
CharSequence text = "Saved!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(cntxt, text, duration);
toast.show();
}
else
{
CharSequence text = "Already Saved.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(cntxt, text, duration);
toast.show();
}
}
/**
* Method to remove a saved comment from the cache,
* remove comment when cache gets too full.
* Use first in first out style of removing.
* @param cntxt The context of the application
* @param comment The comment to be removed
*/
public void removeFromCache(Context cntxt)
{
saves.cacheIDs.remove(saves.cacheIDs.size()-1);
saves.cacheList.remove(saves.cacheList.size()-1);
}
/**
* Method to check if comment is currently in the cache.
* @param comment The comment to be checked
* @return The result of the check
*/
public boolean inCache(Comment comment)
{
if(saves.cacheIDs.contains(comment.getElasticID()))
{
return true;
}
else
{
return false;
}
}
/**
* Method to save the saved comments (cache) to a file.
* @param cntxt The application context.
*/
private void saveCache(Context cntxt)
{
Type cacheType = new TypeToken<Cache>(){}.getType();
String jsonString = GSON.toJson(saves, cacheType);
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(cntxt.openFileOutput(SAVE_FILE, Context.MODE_PRIVATE));
outputStreamWriter.write(jsonString);
outputStreamWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Method to load the saved comments (cache) from a file.
* @param cntxt The application context
*/
public void loadCache(Context cntxt)
{
File file = cntxt.getFileStreamPath(SAVE_FILE);
saves.cacheIDs = new ArrayList<String>();
saves.cacheList = new ArrayList<Comment>();
if(file.exists())
{
String jsonString = "";
try {
InputStream inputStream = cntxt.openFileInput(SAVE_FILE);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
jsonString = stringBuilder.toString();
}
Type cacheType = new TypeToken<Cache>(){}.getType();
saves.setInstance((Cache) GSON.fromJson(jsonString, cacheType));
}
catch (FileNotFoundException e) {
Log.e("FAV:", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("FAV:", "Can not read file: " + e.toString());
}
}
}
/**
* Constructs a Gson with a custom serializer / desserializer registered for
* Bitmaps.
*/
private void constructGson() {
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Bitmap.class, new BitmapJsonConverter());
GSON = builder.create();
}
}
| CMPUT301W14T3/Group-Project | src/cs/ualberta/ca/tunein/CacheController.java | Java | gpl-2.0 | 5,308 |
/*
* Copyright (C) 2013-2014 Zhang Rui <[email protected]>
*
* 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 tv.danmaku.ijk.media.player;
import android.annotation.TargetApi;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.view.Surface;
import android.view.SurfaceHolder;
import java.io.FileDescriptor;
import java.io.IOException;
import java.util.Map;
import tv.danmaku.ijk.media.player.misc.IMediaDataSource;
import tv.danmaku.ijk.media.player.misc.ITrackInfo;
public interface IMediaPlayer {
/*
* Do not change these values without updating their counterparts in native
*/
int MEDIA_INFO_UNKNOWN = 1;
int MEDIA_INFO_STARTED_AS_NEXT = 2;
int MEDIA_INFO_VIDEO_RENDERING_START = 3;
int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
int MEDIA_INFO_BUFFERING_START = 701;
int MEDIA_INFO_BUFFERING_END = 702;
int MEDIA_INFO_NETWORK_BANDWIDTH = 703;
int MEDIA_INFO_BAD_INTERLEAVING = 800;
int MEDIA_INFO_NOT_SEEKABLE = 801;
int MEDIA_INFO_METADATA_UPDATE = 802;
int MEDIA_INFO_TIMED_TEXT_ERROR = 900;
int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901;
int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902;
int MEDIA_INFO_VIDEO_ROTATION_CHANGED = 10001;
int MEDIA_INFO_AUDIO_RENDERING_START = 10002;
int MEDIA_ERROR_UNKNOWN = 1;
int MEDIA_ERROR_SERVER_DIED = 100;
int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
int MEDIA_ERROR_IO = -1004;
int MEDIA_ERROR_MALFORMED = -1007;
int MEDIA_ERROR_UNSUPPORTED = -1010;
int MEDIA_ERROR_TIMED_OUT = -110;
void setDisplay(SurfaceHolder sh);
void setDataSource(Context context, Uri uri)
throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
void setDataSource(Context context, Uri uri, Map<String, String> headers)
throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
void setDataSource(FileDescriptor fd)
throws IOException, IllegalArgumentException, IllegalStateException;
void setDataSource(String path)
throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
String getDataSource();
void prepareAsync() throws IllegalStateException;
void start() throws IllegalStateException;
void stop() throws IllegalStateException;
void pause() throws IllegalStateException;
void setScreenOnWhilePlaying(boolean screenOn);
int getVideoWidth();
int getVideoHeight();
boolean isPlaying();
void seekTo(long msec) throws IllegalStateException;
long getCurrentPosition();
long getDuration();
void release();
void reset();
void setVolume(float leftVolume, float rightVolume);
int getAudioSessionId();
MediaInfo getMediaInfo();
@SuppressWarnings("EmptyMethod")
@Deprecated
void setLogEnabled(boolean enable);
@Deprecated
boolean isPlayable();
void setOnPreparedListener(OnPreparedListener listener);
void setOnCompletionListener(OnCompletionListener listener);
void setOnBufferingUpdateListener(
OnBufferingUpdateListener listener);
void setOnSeekCompleteListener(
OnSeekCompleteListener listener);
void setOnVideoSizeChangedListener(
OnVideoSizeChangedListener listener);
void setOnErrorListener(OnErrorListener listener);
void setOnInfoListener(OnInfoListener listener);
void setOnVideoOpenListener(OnVideoOpenListener listener);
/*--------------------
* Listeners
*/
interface OnPreparedListener {
void onPrepared(IMediaPlayer mp);
}
interface OnCompletionListener {
void onCompletion(IMediaPlayer mp);
}
interface OnBufferingUpdateListener {
void onBufferingUpdate(IMediaPlayer mp, int percent);
}
interface OnSeekCompleteListener {
void onSeekComplete(IMediaPlayer mp);
}
interface OnVideoSizeChangedListener {
void onVideoSizeChanged(IMediaPlayer mp, int width, int height,
int sar_num, int sar_den);
}
interface OnErrorListener {
boolean onError(IMediaPlayer mp, int what, int extra);
}
interface OnInfoListener {
boolean onInfo(IMediaPlayer mp, int what, int extra);
}
interface OnVideoOpenListener {
void onOpen(IMediaPlayer mp, boolean success);
}
/*--------------------
* Optional
*/
void setAudioStreamType(int streamtype);
@Deprecated
void setKeepInBackground(boolean keepInBackground);
int getVideoSarNum();
int getVideoSarDen();
@Deprecated
void setWakeMode(Context context, int mode);
void setLooping(boolean looping);
boolean isLooping();
/*--------------------
* AndroidMediaPlayer: JELLY_BEAN
*/
ITrackInfo[] getTrackInfo();
/*--------------------
* AndroidMediaPlayer: ICE_CREAM_SANDWICH:
*/
void setSurface(Surface surface);
/*--------------------
* AndroidMediaPlayer: M:
*/
void setDataSource(IMediaDataSource mediaDataSource);
}
| LittleKey/ijkplayer | android/ijkplayer/ijkplayer-java/src/main/java/tv/danmaku/ijk/media/player/IMediaPlayer.java | Java | gpl-2.0 | 5,739 |
package com.thexfactor117.levels.leveling;
import com.thexfactor117.levels.config.Config;
import com.thexfactor117.levels.util.NBTHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemAxe;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting;
/**
*
* @author TheXFactor117
*
*/
public class Experience
{
/**
* Levels up the current weapon/armor to the next level, assuming it is not at max level.
* @param player
* @param stack
*/
public static void levelUp(EntityPlayer player, ItemStack stack)
{
NBTTagCompound nbt = stack.getTagCompound();
if (nbt != null)
{
while (Experience.getLevel(nbt) < Config.maxLevel && Experience.getExperience(nbt) >= Experience.getNextLevelExperience(Experience.getLevel(nbt)))
{
Experience.setLevel(nbt, Experience.getLevel(nbt) + 1); // increase level by one
Experience.setAttributeTokens(nbt, Experience.getAttributeTokens(nbt) + 1);
player.sendMessage(new TextComponentString(stack.getDisplayName() + TextFormatting.GRAY + " has leveled up to level " + TextFormatting.GOLD + Experience.getLevel(nbt) + TextFormatting.GRAY + "!"));
if (stack.getItem() instanceof ItemSword || stack.getItem() instanceof ItemAxe)
{
// update damage and attack speed values
NBTTagList taglist = nbt.getTagList("AttributeModifiers", 10); // retrieves our custom Attribute Modifier implementation
NBTTagCompound damageNbt = taglist.getCompoundTagAt(0);
NBTTagCompound speedNbt = taglist.getCompoundTagAt(1);
double newDamage = damageNbt.getDouble("Amount") + ((damageNbt.getDouble("Amount") * nbt.getDouble("Multiplier")) / 2);
double newSpeed = speedNbt.getDouble("Amount") - ((speedNbt.getDouble("Amount") * nbt.getDouble("Multiplier")) / 2);
damageNbt.setDouble("Amount", newDamage);
speedNbt.setDouble("Amount", newSpeed);
}
else if (stack.getItem() instanceof ItemArmor)
{
// update armor and armor toughness values
NBTTagList taglist = nbt.getTagList("AttributeModifiers", 10); // retrieves our custom Attribute Modifier implementation
NBTTagCompound armorNbt = taglist.getCompoundTagAt(0);
NBTTagCompound toughnessNbt = taglist.getCompoundTagAt(1);
double newArmor = armorNbt.getDouble("Amount") + ((armorNbt.getDouble("Amount") * nbt.getDouble("Multiplier")) / 2);
double newToughness = toughnessNbt.getDouble("Amount") - ((toughnessNbt.getDouble("Amount") * nbt.getDouble("Multiplier")) / 2);
armorNbt.setDouble("Amount", newArmor);
toughnessNbt.setDouble("Amount", newToughness);
}
NBTHelper.saveStackNBT(stack, nbt);
}
}
}
/**
* Returns the level of the current weapon/armor.
* @param nbt
* @return
*/
public static int getLevel(NBTTagCompound nbt)
{
return nbt != null ? nbt.getInteger("LEVEL") : 1;
}
/**
* Sets the level of the current weapon/armor.
* @param nbt
* @param level
*/
public static void setLevel(NBTTagCompound nbt, int level)
{
if (nbt != null)
{
if (level > 0)
nbt.setInteger("LEVEL", level);
else
nbt.removeTag("LEVEL");
}
}
/**
* Returns the experience of the current weapon/armor.
* @param nbt
* @return
*/
public static int getExperience(NBTTagCompound nbt)
{
return nbt != null ? nbt.getInteger("EXPERIENCE") : 1;
}
/**
* Sets the experience of the current weapon/armor.
* @param nbt
* @param level
*/
public static void setExperience(NBTTagCompound nbt, int experience)
{
if (nbt != null)
{
if (experience > 0)
nbt.setInteger("EXPERIENCE", experience);
else
nbt.removeTag("EXPERIENCE");
}
}
/**
* Sets the amount of Attribute Tokens the specific NBT tag has.
* @param nbt
* @param tokens
*/
public static void setAttributeTokens(NBTTagCompound nbt, int tokens)
{
if (nbt != null)
{
if (tokens > 0)
nbt.setInteger("TOKENS", tokens);
else
nbt.removeTag("TOKENS");
}
}
/**
* Returns how many Attribute Tokens the specific NBT tag has.
* @param nbt
* @return
*/
public static int getAttributeTokens(NBTTagCompound nbt)
{
return nbt != null ? nbt.getInteger("TOKENS") : 0;
}
/**
* Returns the amount of experience to level up.
* @param currentLevel
* @return
*/
public static int getNextLevelExperience(int currentLevel)
{
return (int) Math.pow(currentLevel, Config.expExponent) * Config.expMultiplier;
}
}
| TheXFactor117/Levels | src/main/java/com/thexfactor117/levels/leveling/Experience.java | Java | gpl-2.0 | 4,659 |
package soot.JastAddJ;
import java.util.HashSet;import java.util.LinkedHashSet;import java.io.File;import java.util.*;import beaver.*;import java.util.ArrayList;import java.util.zip.*;import java.io.*;import java.io.FileNotFoundException;import java.util.Collection;import soot.*;import soot.util.*;import soot.jimple.*;import soot.coffi.ClassFile;import soot.coffi.method_info;import soot.coffi.CONSTANT_Utf8_info;import soot.coffi.CoffiMethodSource;
public class ConstructorDecl extends BodyDecl implements Cloneable {
public void flushCache() {
super.flushCache();
accessibleFrom_TypeDecl_values = null;
isDAafter_Variable_values = null;
isDUafter_Variable_values = null;
throwsException_TypeDecl_values = null;
name_computed = false;
name_value = null;
signature_computed = false;
signature_value = null;
sameSignature_ConstructorDecl_values = null;
moreSpecificThan_ConstructorDecl_values = null;
parameterDeclaration_String_values = null;
circularThisInvocation_ConstructorDecl_values = null;
sourceConstructorDecl_computed = false;
sourceConstructorDecl_value = null;
sootMethod_computed = false;
sootMethod_value = null;
sootRef_computed = false;
sootRef_value = null;
localNumOfFirstParameter_computed = false;
offsetFirstEnclosingVariable_computed = false;
handlesException_TypeDecl_values = null;
}
@SuppressWarnings({"unchecked", "cast"}) public ConstructorDecl clone() throws CloneNotSupportedException {
ConstructorDecl node = (ConstructorDecl)super.clone();
node.accessibleFrom_TypeDecl_values = null;
node.isDAafter_Variable_values = null;
node.isDUafter_Variable_values = null;
node.throwsException_TypeDecl_values = null;
node.name_computed = false;
node.name_value = null;
node.signature_computed = false;
node.signature_value = null;
node.sameSignature_ConstructorDecl_values = null;
node.moreSpecificThan_ConstructorDecl_values = null;
node.parameterDeclaration_String_values = null;
node.circularThisInvocation_ConstructorDecl_values = null;
node.sourceConstructorDecl_computed = false;
node.sourceConstructorDecl_value = null;
node.sootMethod_computed = false;
node.sootMethod_value = null;
node.sootRef_computed = false;
node.sootRef_value = null;
node.localNumOfFirstParameter_computed = false;
node.offsetFirstEnclosingVariable_computed = false;
node.handlesException_TypeDecl_values = null;
node.in$Circle(false);
node.is$Final(false);
return node;
}
@SuppressWarnings({"unchecked", "cast"}) public ConstructorDecl copy() {
try {
ConstructorDecl node = (ConstructorDecl)clone();
if(children != null) node.children = (ASTNode[])children.clone();
return node;
} catch (CloneNotSupportedException e) {
}
System.err.println("Error: Could not clone node of type " + getClass().getName() + "!");
return null;
}
@SuppressWarnings({"unchecked", "cast"}) public ConstructorDecl fullCopy() {
ConstructorDecl res = (ConstructorDecl)copy();
for(int i = 0; i < getNumChildNoTransform(); i++) {
ASTNode node = getChildNoTransform(i);
if(node != null) node = node.fullCopy();
res.setChild(node, i);
}
return res;
}
// Declared in LookupConstructor.jrag at line 163
public boolean applicable(List argList) {
if(getNumParameter() != argList.getNumChild())
return false;
for(int i = 0; i < getNumParameter(); i++) {
TypeDecl arg = ((Expr)argList.getChild(i)).type();
TypeDecl parameter = getParameter(i).type();
if(!arg.instanceOf(parameter)) {
return false;
}
}
return true;
}
// Declared in Modifiers.jrag at line 108
public void checkModifiers() {
super.checkModifiers();
}
// Declared in NameCheck.jrag at line 68
public void nameCheck() {
super.nameCheck();
// 8.8
if(!hostType().name().equals(name()))
error("constructor " + name() +" does not have the same name as the simple name of the host class " + hostType().name());
// 8.8.2
if(hostType().lookupConstructor(this) != this)
error("constructor with signature " + signature() + " is multiply declared in type " + hostType().typeName());
if(circularThisInvocation(this))
error("The constructor " + signature() + " may not directly or indirectly invoke itself");
}
// Declared in PrettyPrint.jadd at line 135
public void toString(StringBuffer s) {
s.append(indent());
getModifiers().toString(s);
s.append(name() + "(");
if(getNumParameter() > 0) {
getParameter(0).toString(s);
for(int i = 1; i < getNumParameter(); i++) {
s.append(", ");
getParameter(i).toString(s);
}
}
s.append(")");
if(getNumException() > 0) {
s.append(" throws ");
getException(0).toString(s);
for(int i = 1; i < getNumException(); i++) {
s.append(", ");
getException(i).toString(s);
}
}
s.append(" {\n");
indent++;
if(hasConstructorInvocation()) {
s.append(indent());
getConstructorInvocation().toString(s);
}
for(int i = 0; i < getBlock().getNumStmt(); i++) {
s.append(indent());
getBlock().getStmt(i).toString(s);
}
indent--;
s.append(indent());
s.append("}\n");
}
// Declared in TypeCheck.jrag at line 424
public void typeCheck() {
// 8.8.4 (8.4.4)
TypeDecl exceptionType = typeThrowable();
for(int i = 0; i < getNumException(); i++) {
TypeDecl typeDecl = getException(i).type();
if(!typeDecl.instanceOf(exceptionType))
error(signature() + " throws non throwable type " + typeDecl.fullName());
}
}
// Declared in Enums.jrag at line 135
protected void transformEnumConstructors() {
// add implicit super constructor access since we are traversing
// without doing rewrites
if(!hasConstructorInvocation()) {
setConstructorInvocation(
new ExprStmt(
new SuperConstructorAccess("super", new List())
)
);
}
super.transformEnumConstructors();
getParameterList().insertChild(
new ParameterDeclaration(new TypeAccess("java.lang", "String"), "@p0"),
0
);
getParameterList().insertChild(
new ParameterDeclaration(new TypeAccess("int"), "@p1"),
1
);
}
// Declared in Generics.jrag at line 1072
public BodyDecl p(Parameterization parTypeDecl) {
ConstructorDecl c = new ConstructorDeclSubstituted(
(Modifiers)getModifiers().fullCopy(),
getID(),
getParameterList().substitute(parTypeDecl),
getExceptionList().substitute(parTypeDecl),
new Opt(),
new Block(),
this
);
return c;
}
// Declared in InnerClasses.jrag at line 436
// add val$name as parameters to the constructor
protected boolean addEnclosingVariables = true;
// Declared in InnerClasses.jrag at line 437
public void addEnclosingVariables() {
if(!addEnclosingVariables) return;
addEnclosingVariables = false;
hostType().addEnclosingVariables();
for(Iterator iter = hostType().enclosingVariables().iterator(); iter.hasNext(); ) {
Variable v = (Variable)iter.next();
getParameterList().add(new ParameterDeclaration(v.type(), "val$" + v.name()));
}
}
// Declared in InnerClasses.jrag at line 471
public ConstructorDecl createAccessor() {
ConstructorDecl c = (ConstructorDecl)hostType().getAccessor(this, "constructor");
if(c != null) return c;
// make sure enclosing varibles are added as parameters prior to building accessor
addEnclosingVariables();
Modifiers modifiers = new Modifiers(new List());
modifiers.addModifier(new Modifier("synthetic"));
modifiers.addModifier(new Modifier("public"));
List parameters = createAccessorParameters();
// add all parameters as arguments except for the dummy parameter
List args = new List();
for(int i = 0; i < parameters.getNumChildNoTransform() - 1; i++)
args.add(new VarAccess(((ParameterDeclaration)parameters.getChildNoTransform(i)).name()));
ConstructorAccess access = new ConstructorAccess("this", args);
access.addEnclosingVariables = false;
c = new ConstructorDecl(
modifiers,
name(),
parameters,
(List)getExceptionList().fullCopy(),
new Opt(
new ExprStmt(
access
)
),
new Block(
new List().add(new ReturnStmt(new Opt()))
)
);
c = hostType().addConstructor(c);
c.addEnclosingVariables = false;
hostType().addAccessor(this, "constructor", c);
return c;
}
// Declared in InnerClasses.jrag at line 511
protected List createAccessorParameters() {
List parameters = new List();
for (int i=0; i<getNumParameter(); i++)
parameters.add(new ParameterDeclaration(getParameter(i).type(), getParameter(i).name()));
parameters.add(new ParameterDeclaration(createAnonymousJavaTypeDecl().createBoundAccess(), ("p" + getNumParameter())));
return parameters;
}
// Declared in InnerClasses.jrag at line 519
protected TypeDecl createAnonymousJavaTypeDecl() {
ClassDecl classDecl =
new ClassDecl(
new Modifiers(new List().add(new Modifier("synthetic"))),
"" + hostType().nextAnonymousIndex(),
new Opt(),
new List(),
new List()
);
classDecl = hostType().addMemberClass(classDecl);
hostType().addNestedType(classDecl);
return classDecl;
}
// Declared in Transformations.jrag at line 119
public void transformation() {
// this$val as fields and constructor parameters
addEnclosingVariables();
super.transformation();
}
// Declared in EmitJimple.jrag at line 229
public void jimplify1phase2() {
String name = "<init>";
ArrayList parameters = new ArrayList();
ArrayList paramnames = new ArrayList();
// this$0
TypeDecl typeDecl = hostType();
if(typeDecl.needsEnclosing())
parameters.add(typeDecl.enclosingType().getSootType());
if(typeDecl.needsSuperEnclosing()) {
TypeDecl superClass = ((ClassDecl)typeDecl).superclass();
parameters.add(superClass.enclosingType().getSootType());
}
// args
for(int i = 0; i < getNumParameter(); i++) {
parameters.add(getParameter(i).type().getSootType());
paramnames.add(getParameter(i).name());
}
soot.Type returnType = soot.VoidType.v();
int modifiers = sootTypeModifiers();
ArrayList throwtypes = new ArrayList();
for(int i = 0; i < getNumException(); i++)
throwtypes.add(getException(i).type().getSootClassDecl());
String signature = SootMethod.getSubSignature(name, parameters, returnType);
if(!hostType().getSootClassDecl().declaresMethod(signature)) {
SootMethod m = new SootMethod(name, parameters, returnType, modifiers, throwtypes);
hostType().getSootClassDecl().addMethod(m);
m.addTag(new soot.tagkit.ParamNamesTag(paramnames));
sootMethod = m;
}
addAttributes();
}
// Declared in EmitJimple.jrag at line 287
public SootMethod sootMethod;
// Declared in AnnotationsCodegen.jrag at line 57
public void addAttributes() {
super.addAttributes();
ArrayList c = new ArrayList();
getModifiers().addRuntimeVisibleAnnotationsAttribute(c);
getModifiers().addRuntimeInvisibleAnnotationsAttribute(c);
addRuntimeVisibleParameterAnnotationsAttribute(c);
addRuntimeInvisibleParameterAnnotationsAttribute(c);
addSourceLevelParameterAnnotationsAttribute(c);
getModifiers().addSourceOnlyAnnotations(c);
for(Iterator iter = c.iterator(); iter.hasNext(); ) {
soot.tagkit.Tag tag = (soot.tagkit.Tag)iter.next();
sootMethod.addTag(tag);
}
}
// Declared in AnnotationsCodegen.jrag at line 185
public void addRuntimeVisibleParameterAnnotationsAttribute(Collection c) {
boolean foundVisibleAnnotations = false;
Collection annotations = new ArrayList(getNumParameter());
for(int i = 0; i < getNumParameter(); i++) {
Collection a = getParameter(i).getModifiers().runtimeVisibleAnnotations();
if(!a.isEmpty()) foundVisibleAnnotations = true;
soot.tagkit.VisibilityAnnotationTag tag = new soot.tagkit.VisibilityAnnotationTag(soot.tagkit.AnnotationConstants.RUNTIME_VISIBLE);
for(Iterator iter = a.iterator(); iter.hasNext(); ) {
Annotation annotation = (Annotation)iter.next();
ArrayList elements = new ArrayList(1);
annotation.appendAsAttributeTo(elements);
tag.addAnnotation((soot.tagkit.AnnotationTag)elements.get(0));
}
annotations.add(tag);
}
if(foundVisibleAnnotations) {
soot.tagkit.VisibilityParameterAnnotationTag tag = new soot.tagkit.VisibilityParameterAnnotationTag(annotations.size(), soot.tagkit.AnnotationConstants.RUNTIME_VISIBLE);
for(Iterator iter = annotations.iterator(); iter.hasNext(); ) {
tag.addVisibilityAnnotation((soot.tagkit.VisibilityAnnotationTag)iter.next());
}
c.add(tag);
}
}
// Declared in AnnotationsCodegen.jrag at line 241
public void addRuntimeInvisibleParameterAnnotationsAttribute(Collection c) {
boolean foundVisibleAnnotations = false;
Collection annotations = new ArrayList(getNumParameter());
for(int i = 0; i < getNumParameter(); i++) {
Collection a = getParameter(i).getModifiers().runtimeInvisibleAnnotations();
if(!a.isEmpty()) foundVisibleAnnotations = true;
soot.tagkit.VisibilityAnnotationTag tag = new soot.tagkit.VisibilityAnnotationTag(soot.tagkit.AnnotationConstants.RUNTIME_INVISIBLE);
for(Iterator iter = a.iterator(); iter.hasNext(); ) {
Annotation annotation = (Annotation)iter.next();
ArrayList elements = new ArrayList(1);
annotation.appendAsAttributeTo(elements);
tag.addAnnotation((soot.tagkit.AnnotationTag)elements.get(0));
}
annotations.add(tag);
}
if(foundVisibleAnnotations) {
soot.tagkit.VisibilityParameterAnnotationTag tag = new soot.tagkit.VisibilityParameterAnnotationTag(annotations.size(), soot.tagkit.AnnotationConstants.RUNTIME_INVISIBLE);
for(Iterator iter = annotations.iterator(); iter.hasNext(); ) {
tag.addVisibilityAnnotation((soot.tagkit.VisibilityAnnotationTag)iter.next());
}
c.add(tag);
}
}
// Declared in AnnotationsCodegen.jrag at line 280
public void addSourceLevelParameterAnnotationsAttribute(Collection c) {
boolean foundVisibleAnnotations = false;
Collection annotations = new ArrayList(getNumParameter());
for(int i = 0; i < getNumParameter(); i++) {
getParameter(i).getModifiers().addSourceOnlyAnnotations(c);
}
}
// Declared in java.ast at line 3
// Declared in java.ast line 72
public ConstructorDecl() {
super();
setChild(new List(), 1);
setChild(new List(), 2);
setChild(new Opt(), 3);
}
// Declared in java.ast at line 13
// Declared in java.ast line 72
public ConstructorDecl(Modifiers p0, String p1, List<ParameterDeclaration> p2, List<Access> p3, Opt<Stmt> p4, Block p5) {
setChild(p0, 0);
setID(p1);
setChild(p2, 1);
setChild(p3, 2);
setChild(p4, 3);
setChild(p5, 4);
}
// Declared in java.ast at line 23
// Declared in java.ast line 72
public ConstructorDecl(Modifiers p0, beaver.Symbol p1, List<ParameterDeclaration> p2, List<Access> p3, Opt<Stmt> p4, Block p5) {
setChild(p0, 0);
setID(p1);
setChild(p2, 1);
setChild(p3, 2);
setChild(p4, 3);
setChild(p5, 4);
}
// Declared in java.ast at line 32
protected int numChildren() {
return 5;
}
// Declared in java.ast at line 35
public boolean mayHaveRewrite() { return true; }
// Declared in java.ast at line 2
// Declared in java.ast line 72
public void setModifiers(Modifiers node) {
setChild(node, 0);
}
// Declared in java.ast at line 5
public Modifiers getModifiers() {
return (Modifiers)getChild(0);
}
// Declared in java.ast at line 9
public Modifiers getModifiersNoTransform() {
return (Modifiers)getChildNoTransform(0);
}
// Declared in java.ast at line 2
// Declared in java.ast line 72
protected String tokenString_ID;
// Declared in java.ast at line 3
public void setID(String value) {
tokenString_ID = value;
}
// Declared in java.ast at line 6
public int IDstart;
// Declared in java.ast at line 7
public int IDend;
// Declared in java.ast at line 8
public void setID(beaver.Symbol symbol) {
if(symbol.value != null && !(symbol.value instanceof String))
throw new UnsupportedOperationException("setID is only valid for String lexemes");
tokenString_ID = (String)symbol.value;
IDstart = symbol.getStart();
IDend = symbol.getEnd();
}
// Declared in java.ast at line 15
public String getID() {
return tokenString_ID != null ? tokenString_ID : "";
}
// Declared in java.ast at line 2
// Declared in java.ast line 72
public void setParameterList(List<ParameterDeclaration> list) {
setChild(list, 1);
}
// Declared in java.ast at line 6
private int getNumParameter = 0;
// Declared in java.ast at line 7
public int getNumParameter() {
return getParameterList().getNumChild();
}
// Declared in java.ast at line 11
@SuppressWarnings({"unchecked", "cast"}) public ParameterDeclaration getParameter(int i) {
return (ParameterDeclaration)getParameterList().getChild(i);
}
// Declared in java.ast at line 15
public void addParameter(ParameterDeclaration node) {
List<ParameterDeclaration> list = getParameterList();
list.addChild(node);
}
// Declared in java.ast at line 20
public void setParameter(ParameterDeclaration node, int i) {
List<ParameterDeclaration> list = getParameterList();
list.setChild(node, i);
}
// Declared in java.ast at line 24
public List<ParameterDeclaration> getParameters() {
return getParameterList();
}
// Declared in java.ast at line 27
public List<ParameterDeclaration> getParametersNoTransform() {
return getParameterListNoTransform();
}
// Declared in java.ast at line 31
@SuppressWarnings({"unchecked", "cast"}) public List<ParameterDeclaration> getParameterList() {
return (List<ParameterDeclaration>)getChild(1);
}
// Declared in java.ast at line 35
@SuppressWarnings({"unchecked", "cast"}) public List<ParameterDeclaration> getParameterListNoTransform() {
return (List<ParameterDeclaration>)getChildNoTransform(1);
}
// Declared in java.ast at line 2
// Declared in java.ast line 72
public void setExceptionList(List<Access> list) {
setChild(list, 2);
}
// Declared in java.ast at line 6
private int getNumException = 0;
// Declared in java.ast at line 7
public int getNumException() {
return getExceptionList().getNumChild();
}
// Declared in java.ast at line 11
@SuppressWarnings({"unchecked", "cast"}) public Access getException(int i) {
return (Access)getExceptionList().getChild(i);
}
// Declared in java.ast at line 15
public void addException(Access node) {
List<Access> list = getExceptionList();
list.addChild(node);
}
// Declared in java.ast at line 20
public void setException(Access node, int i) {
List<Access> list = getExceptionList();
list.setChild(node, i);
}
// Declared in java.ast at line 24
public List<Access> getExceptions() {
return getExceptionList();
}
// Declared in java.ast at line 27
public List<Access> getExceptionsNoTransform() {
return getExceptionListNoTransform();
}
// Declared in java.ast at line 31
@SuppressWarnings({"unchecked", "cast"}) public List<Access> getExceptionList() {
return (List<Access>)getChild(2);
}
// Declared in java.ast at line 35
@SuppressWarnings({"unchecked", "cast"}) public List<Access> getExceptionListNoTransform() {
return (List<Access>)getChildNoTransform(2);
}
// Declared in java.ast at line 2
// Declared in java.ast line 72
public void setConstructorInvocationOpt(Opt<Stmt> opt) {
setChild(opt, 3);
}
// Declared in java.ast at line 6
public boolean hasConstructorInvocation() {
return getConstructorInvocationOpt().getNumChild() != 0;
}
// Declared in java.ast at line 10
@SuppressWarnings({"unchecked", "cast"}) public Stmt getConstructorInvocation() {
return (Stmt)getConstructorInvocationOpt().getChild(0);
}
// Declared in java.ast at line 14
public void setConstructorInvocation(Stmt node) {
getConstructorInvocationOpt().setChild(node, 0);
}
// Declared in java.ast at line 17
@SuppressWarnings({"unchecked", "cast"}) public Opt<Stmt> getConstructorInvocationOpt() {
return (Opt<Stmt>)getChild(3);
}
// Declared in java.ast at line 21
@SuppressWarnings({"unchecked", "cast"}) public Opt<Stmt> getConstructorInvocationOptNoTransform() {
return (Opt<Stmt>)getChildNoTransform(3);
}
// Declared in java.ast at line 2
// Declared in java.ast line 72
public void setBlock(Block node) {
setChild(node, 4);
}
// Declared in java.ast at line 5
public Block getBlock() {
return (Block)getChild(4);
}
// Declared in java.ast at line 9
public Block getBlockNoTransform() {
return (Block)getChildNoTransform(4);
}
// Declared in EmitJimpleRefinements.jrag at line 120
public void jimplify2() {
if(!generate() || sootMethod().hasActiveBody() ||
(sootMethod().getSource() != null && (sootMethod().getSource() instanceof soot.coffi.CoffiMethodSource)) ) return;
JimpleBody body = Jimple.v().newBody(sootMethod());
sootMethod().setActiveBody(body);
Body b = new Body(hostType(), body, this);
b.setLine(this);
for(int i = 0; i < getNumParameter(); i++)
getParameter(i).jimplify2(b);
boolean needsInit = true;
if(hasConstructorInvocation()) {
getConstructorInvocation().jimplify2(b);
Stmt stmt = getConstructorInvocation();
if(stmt instanceof ExprStmt) {
ExprStmt exprStmt = (ExprStmt)stmt;
Expr expr = exprStmt.getExpr();
if(!expr.isSuperConstructorAccess())
needsInit = false;
}
}
if(hostType().needsEnclosing()) {
TypeDecl type = hostType().enclosingType();
b.add(Jimple.v().newAssignStmt(
Jimple.v().newInstanceFieldRef(
b.emitThis(hostType()),
hostType().getSootField("this$0", type).makeRef()
),
asLocal(b, Jimple.v().newParameterRef(type.getSootType(), 0))
));
}
for(Iterator iter = hostType().enclosingVariables().iterator(); iter.hasNext(); ) {
Variable v = (Variable)iter.next();
ParameterDeclaration p = (ParameterDeclaration)parameterDeclaration("val$" + v.name()).iterator().next();
b.add(Jimple.v().newAssignStmt(
Jimple.v().newInstanceFieldRef(
b.emitThis(hostType()),
Scene.v().makeFieldRef(hostType().getSootClassDecl(), "val$" + v.name(), v.type().getSootType(), false)
//hostType().getSootClassDecl().getField("val$" + v.name(), v.type().getSootType()).makeRef()
),
p.local
));
}
if(needsInit) {
TypeDecl typeDecl = hostType();
for(int i = 0; i < typeDecl.getNumBodyDecl(); i++) {
BodyDecl bodyDecl = typeDecl.getBodyDecl(i);
if(bodyDecl instanceof FieldDeclaration && bodyDecl.generate()) {
FieldDeclaration f = (FieldDeclaration)bodyDecl;
if(!f.isStatic() && f.hasInit()) {
soot.Local base = b.emitThis(hostType());
Local l = asLocal(b,
f.getInit().type().emitCastTo(b, f.getInit(), f.type()), // AssignConversion
f.type().getSootType()
);
b.setLine(f);
b.add(Jimple.v().newAssignStmt(
Jimple.v().newInstanceFieldRef(base, f.sootRef()),
l
));
}
}
else if(bodyDecl instanceof InstanceInitializer && bodyDecl.generate()) {
bodyDecl.jimplify2(b);
}
}
}
getBlock().jimplify2(b);
b.add(Jimple.v().newReturnVoidStmt());
}
// Declared in LookupConstructor.jrag at line 155
private boolean refined_LookupConstructor_moreSpecificThan_ConstructorDecl(ConstructorDecl m)
{
for(int i = 0; i < getNumParameter(); i++) {
if(!getParameter(i).type().instanceOf(m.getParameter(i).type()))
return false;
}
return true;
}
protected java.util.Map accessibleFrom_TypeDecl_values;
// Declared in AccessControl.jrag at line 94
@SuppressWarnings({"unchecked", "cast"}) public boolean accessibleFrom(TypeDecl type) {
Object _parameters = type;
if(accessibleFrom_TypeDecl_values == null) accessibleFrom_TypeDecl_values = new java.util.HashMap(4);
if(accessibleFrom_TypeDecl_values.containsKey(_parameters))
return ((Boolean)accessibleFrom_TypeDecl_values.get(_parameters)).booleanValue();
int num = boundariesCrossed;
boolean isFinal = this.is$Final();
boolean accessibleFrom_TypeDecl_value = accessibleFrom_compute(type);
if(isFinal && num == boundariesCrossed)
accessibleFrom_TypeDecl_values.put(_parameters, Boolean.valueOf(accessibleFrom_TypeDecl_value));
return accessibleFrom_TypeDecl_value;
}
private boolean accessibleFrom_compute(TypeDecl type) {
if(!hostType().accessibleFrom(type))
return false;
else if(isPublic())
return true;
else if(isProtected()) {
return true;
}
else if(isPrivate()) {
return hostType().topLevelType() == type.topLevelType();
}
else
return hostPackage().equals(type.hostPackage());
}
// Declared in DefiniteAssignment.jrag at line 297
@SuppressWarnings({"unchecked", "cast"}) public boolean isDAafter(Variable v) {
Object _parameters = v;
if(isDAafter_Variable_values == null) isDAafter_Variable_values = new java.util.HashMap(4);
if(isDAafter_Variable_values.containsKey(_parameters))
return ((Boolean)isDAafter_Variable_values.get(_parameters)).booleanValue();
int num = boundariesCrossed;
boolean isFinal = this.is$Final();
boolean isDAafter_Variable_value = isDAafter_compute(v);
if(isFinal && num == boundariesCrossed)
isDAafter_Variable_values.put(_parameters, Boolean.valueOf(isDAafter_Variable_value));
return isDAafter_Variable_value;
}
private boolean isDAafter_compute(Variable v) { return getBlock().isDAafter(v) && getBlock().checkReturnDA(v); }
// Declared in DefiniteAssignment.jrag at line 753
@SuppressWarnings({"unchecked", "cast"}) public boolean isDUafter(Variable v) {
Object _parameters = v;
if(isDUafter_Variable_values == null) isDUafter_Variable_values = new java.util.HashMap(4);
if(isDUafter_Variable_values.containsKey(_parameters))
return ((Boolean)isDUafter_Variable_values.get(_parameters)).booleanValue();
int num = boundariesCrossed;
boolean isFinal = this.is$Final();
boolean isDUafter_Variable_value = isDUafter_compute(v);
if(isFinal && num == boundariesCrossed)
isDUafter_Variable_values.put(_parameters, Boolean.valueOf(isDUafter_Variable_value));
return isDUafter_Variable_value;
}
private boolean isDUafter_compute(Variable v) { return getBlock().isDUafter(v) && getBlock().checkReturnDU(v); }
protected java.util.Map throwsException_TypeDecl_values;
// Declared in ExceptionHandling.jrag at line 136
@SuppressWarnings({"unchecked", "cast"}) public boolean throwsException(TypeDecl exceptionType) {
Object _parameters = exceptionType;
if(throwsException_TypeDecl_values == null) throwsException_TypeDecl_values = new java.util.HashMap(4);
if(throwsException_TypeDecl_values.containsKey(_parameters))
return ((Boolean)throwsException_TypeDecl_values.get(_parameters)).booleanValue();
int num = boundariesCrossed;
boolean isFinal = this.is$Final();
boolean throwsException_TypeDecl_value = throwsException_compute(exceptionType);
if(isFinal && num == boundariesCrossed)
throwsException_TypeDecl_values.put(_parameters, Boolean.valueOf(throwsException_TypeDecl_value));
return throwsException_TypeDecl_value;
}
private boolean throwsException_compute(TypeDecl exceptionType) {
for(int i = 0; i < getNumException(); i++)
if(exceptionType.instanceOf(getException(i).type()))
return true;
return false;
}
protected boolean name_computed = false;
protected String name_value;
// Declared in LookupConstructor.jrag at line 129
@SuppressWarnings({"unchecked", "cast"}) public String name() {
if(name_computed)
return name_value;
int num = boundariesCrossed;
boolean isFinal = this.is$Final();
name_value = name_compute();
if(isFinal && num == boundariesCrossed)
name_computed = true;
return name_value;
}
private String name_compute() { return getID(); }
protected boolean signature_computed = false;
protected String signature_value;
// Declared in LookupConstructor.jrag at line 131
@SuppressWarnings({"unchecked", "cast"}) public String signature() {
if(signature_computed)
return signature_value;
int num = boundariesCrossed;
boolean isFinal = this.is$Final();
signature_value = signature_compute();
if(isFinal && num == boundariesCrossed)
signature_computed = true;
return signature_value;
}
private String signature_compute() {
StringBuffer s = new StringBuffer();
s.append(name() + "(");
for(int i = 0; i < getNumParameter(); i++) {
s.append(getParameter(i));
if(i != getNumParameter() - 1)
s.append(", ");
}
s.append(")");
return s.toString();
}
protected java.util.Map sameSignature_ConstructorDecl_values;
// Declared in LookupConstructor.jrag at line 144
@SuppressWarnings({"unchecked", "cast"}) public boolean sameSignature(ConstructorDecl c) {
Object _parameters = c;
if(sameSignature_ConstructorDecl_values == null) sameSignature_ConstructorDecl_values = new java.util.HashMap(4);
if(sameSignature_ConstructorDecl_values.containsKey(_parameters))
return ((Boolean)sameSignature_ConstructorDecl_values.get(_parameters)).booleanValue();
int num = boundariesCrossed;
boolean isFinal = this.is$Final();
boolean sameSignature_ConstructorDecl_value = sameSignature_compute(c);
if(isFinal && num == boundariesCrossed)
sameSignature_ConstructorDecl_values.put(_parameters, Boolean.valueOf(sameSignature_ConstructorDecl_value));
return sameSignature_ConstructorDecl_value;
}
private boolean sameSignature_compute(ConstructorDecl c) {
if(!name().equals(c.name()))
return false;
if(c.getNumParameter() != getNumParameter())
return false;
for(int i = 0; i < getNumParameter(); i++)
if(!c.getParameter(i).type().equals(getParameter(i).type()))
return false;
return true;
}
protected java.util.Map moreSpecificThan_ConstructorDecl_values;
// Declared in MethodSignature.jrag at line 153
@SuppressWarnings({"unchecked", "cast"}) public boolean moreSpecificThan(ConstructorDecl m) {
Object _parameters = m;
if(moreSpecificThan_ConstructorDecl_values == null) moreSpecificThan_ConstructorDecl_values = new java.util.HashMap(4);
if(moreSpecificThan_ConstructorDecl_values.containsKey(_parameters))
return ((Boolean)moreSpecificThan_ConstructorDecl_values.get(_parameters)).booleanValue();
int num = boundariesCrossed;
boolean isFinal = this.is$Final();
boolean moreSpecificThan_ConstructorDecl_value = moreSpecificThan_compute(m);
if(isFinal && num == boundariesCrossed)
moreSpecificThan_ConstructorDecl_values.put(_parameters, Boolean.valueOf(moreSpecificThan_ConstructorDecl_value));
return moreSpecificThan_ConstructorDecl_value;
}
private boolean moreSpecificThan_compute(ConstructorDecl m) {
if(!isVariableArity() && !m.isVariableArity())
return refined_LookupConstructor_moreSpecificThan_ConstructorDecl(m);
int num = Math.max(getNumParameter(), m.getNumParameter());
for(int i = 0; i < num; i++) {
TypeDecl t1 = i < getNumParameter() - 1 ? getParameter(i).type() : getParameter(getNumParameter()-1).type().componentType();
TypeDecl t2 = i < m.getNumParameter() - 1 ? m.getParameter(i).type() : m.getParameter(m.getNumParameter()-1).type().componentType();
if(!t1.instanceOf(t2))
return false;
}
return true;
}
protected java.util.Map parameterDeclaration_String_values;
// Declared in LookupVariable.jrag at line 105
@SuppressWarnings({"unchecked", "cast"}) public SimpleSet parameterDeclaration(String name) {
Object _parameters = name;
if(parameterDeclaration_String_values == null) parameterDeclaration_String_values = new java.util.HashMap(4);
if(parameterDeclaration_String_values.containsKey(_parameters))
return (SimpleSet)parameterDeclaration_String_values.get(_parameters);
int num = boundariesCrossed;
boolean isFinal = this.is$Final();
SimpleSet parameterDeclaration_String_value = parameterDeclaration_compute(name);
if(isFinal && num == boundariesCrossed)
parameterDeclaration_String_values.put(_parameters, parameterDeclaration_String_value);
return parameterDeclaration_String_value;
}
private SimpleSet parameterDeclaration_compute(String name) {
for(int i = 0; i < getNumParameter(); i++)
if(getParameter(i).name().equals(name))
return (ParameterDeclaration)getParameter(i);
return SimpleSet.emptySet;
}
// Declared in Modifiers.jrag at line 215
@SuppressWarnings({"unchecked", "cast"}) public boolean isSynthetic() {
boolean isSynthetic_value = isSynthetic_compute();
return isSynthetic_value;
}
private boolean isSynthetic_compute() { return getModifiers().isSynthetic(); }
// Declared in Modifiers.jrag at line 233
@SuppressWarnings({"unchecked", "cast"}) public boolean isPublic() {
boolean isPublic_value = isPublic_compute();
return isPublic_value;
}
private boolean isPublic_compute() { return getModifiers().isPublic(); }
// Declared in Modifiers.jrag at line 234
@SuppressWarnings({"unchecked", "cast"}) public boolean isPrivate() {
boolean isPrivate_value = isPrivate_compute();
return isPrivate_value;
}
private boolean isPrivate_compute() { return getModifiers().isPrivate(); }
// Declared in Modifiers.jrag at line 235
@SuppressWarnings({"unchecked", "cast"}) public boolean isProtected() {
boolean isProtected_value = isProtected_compute();
return isProtected_value;
}
private boolean isProtected_compute() { return getModifiers().isProtected(); }
protected java.util.Map circularThisInvocation_ConstructorDecl_values;
// Declared in NameCheck.jrag at line 83
@SuppressWarnings({"unchecked", "cast"}) public boolean circularThisInvocation(ConstructorDecl decl) {
Object _parameters = decl;
if(circularThisInvocation_ConstructorDecl_values == null) circularThisInvocation_ConstructorDecl_values = new java.util.HashMap(4);
if(circularThisInvocation_ConstructorDecl_values.containsKey(_parameters))
return ((Boolean)circularThisInvocation_ConstructorDecl_values.get(_parameters)).booleanValue();
int num = boundariesCrossed;
boolean isFinal = this.is$Final();
boolean circularThisInvocation_ConstructorDecl_value = circularThisInvocation_compute(decl);
if(isFinal && num == boundariesCrossed)
circularThisInvocation_ConstructorDecl_values.put(_parameters, Boolean.valueOf(circularThisInvocation_ConstructorDecl_value));
return circularThisInvocation_ConstructorDecl_value;
}
private boolean circularThisInvocation_compute(ConstructorDecl decl) {
if(hasConstructorInvocation()) {
Expr e = ((ExprStmt)getConstructorInvocation()).getExpr();
if(e instanceof ConstructorAccess) {
ConstructorDecl constructorDecl = ((ConstructorAccess)e).decl();
if(constructorDecl == decl)
return true;
return constructorDecl.circularThisInvocation(decl);
}
}
return false;
}
// Declared in TypeAnalysis.jrag at line 268
@SuppressWarnings({"unchecked", "cast"}) public TypeDecl type() {
TypeDecl type_value = type_compute();
return type_value;
}
private TypeDecl type_compute() { return unknownType(); }
// Declared in TypeAnalysis.jrag at line 274
@SuppressWarnings({"unchecked", "cast"}) public boolean isVoid() {
boolean isVoid_value = isVoid_compute();
return isVoid_value;
}
private boolean isVoid_compute() { return true; }
// Declared in Annotations.jrag at line 286
@SuppressWarnings({"unchecked", "cast"}) public boolean hasAnnotationSuppressWarnings(String s) {
boolean hasAnnotationSuppressWarnings_String_value = hasAnnotationSuppressWarnings_compute(s);
return hasAnnotationSuppressWarnings_String_value;
}
private boolean hasAnnotationSuppressWarnings_compute(String s) { return getModifiers().hasAnnotationSuppressWarnings(s); }
// Declared in Annotations.jrag at line 324
@SuppressWarnings({"unchecked", "cast"}) public boolean isDeprecated() {
boolean isDeprecated_value = isDeprecated_compute();
return isDeprecated_value;
}
private boolean isDeprecated_compute() { return getModifiers().hasDeprecatedAnnotation(); }
protected boolean sourceConstructorDecl_computed = false;
protected ConstructorDecl sourceConstructorDecl_value;
// Declared in Generics.jrag at line 1303
@SuppressWarnings({"unchecked", "cast"}) public ConstructorDecl sourceConstructorDecl() {
if(sourceConstructorDecl_computed)
return sourceConstructorDecl_value;
int num = boundariesCrossed;
boolean isFinal = this.is$Final();
sourceConstructorDecl_value = sourceConstructorDecl_compute();
if(isFinal && num == boundariesCrossed)
sourceConstructorDecl_computed = true;
return sourceConstructorDecl_value;
}
private ConstructorDecl sourceConstructorDecl_compute() { return this; }
// Declared in MethodSignature.jrag at line 175
@SuppressWarnings({"unchecked", "cast"}) public boolean applicableBySubtyping(List argList) {
boolean applicableBySubtyping_List_value = applicableBySubtyping_compute(argList);
return applicableBySubtyping_List_value;
}
private boolean applicableBySubtyping_compute(List argList) {
if(getNumParameter() != argList.getNumChild())
return false;
for(int i = 0; i < getNumParameter(); i++) {
TypeDecl arg = ((Expr)argList.getChild(i)).type();
if(!arg.instanceOf(getParameter(i).type()))
return false;
}
return true;
}
// Declared in MethodSignature.jrag at line 195
@SuppressWarnings({"unchecked", "cast"}) public boolean applicableByMethodInvocationConversion(List argList) {
boolean applicableByMethodInvocationConversion_List_value = applicableByMethodInvocationConversion_compute(argList);
return applicableByMethodInvocationConversion_List_value;
}
private boolean applicableByMethodInvocationConversion_compute(List argList) {
if(getNumParameter() != argList.getNumChild())
return false;
for(int i = 0; i < getNumParameter(); i++) {
TypeDecl arg = ((Expr)argList.getChild(i)).type();
if(!arg.methodInvocationConversionTo(getParameter(i).type()))
return false;
}
return true;
}
// Declared in MethodSignature.jrag at line 216
@SuppressWarnings({"unchecked", "cast"}) public boolean applicableVariableArity(List argList) {
boolean applicableVariableArity_List_value = applicableVariableArity_compute(argList);
return applicableVariableArity_List_value;
}
private boolean applicableVariableArity_compute(List argList) {
for(int i = 0; i < getNumParameter() - 1; i++) {
TypeDecl arg = ((Expr)argList.getChild(i)).type();
if(!arg.methodInvocationConversionTo(getParameter(i).type()))
return false;
}
for(int i = getNumParameter() - 1; i < argList.getNumChild(); i++) {
TypeDecl arg = ((Expr)argList.getChild(i)).type();
if(!arg.methodInvocationConversionTo(lastParameter().type().componentType()))
return false;
}
return true;
}
// Declared in MethodSignature.jrag at line 303
@SuppressWarnings({"unchecked", "cast"}) public boolean potentiallyApplicable(List argList) {
boolean potentiallyApplicable_List_value = potentiallyApplicable_compute(argList);
return potentiallyApplicable_List_value;
}
private boolean potentiallyApplicable_compute(List argList) {
if(isVariableArity() && !(argList.getNumChild() >= arity()-1))
return false;
if(!isVariableArity() && !(arity() == argList.getNumChild()))
return false;
return true;
}
// Declared in MethodSignature.jrag at line 310
@SuppressWarnings({"unchecked", "cast"}) public int arity() {
int arity_value = arity_compute();
return arity_value;
}
private int arity_compute() { return getNumParameter(); }
// Declared in VariableArityParameters.jrag at line 34
@SuppressWarnings({"unchecked", "cast"}) public boolean isVariableArity() {
boolean isVariableArity_value = isVariableArity_compute();
return isVariableArity_value;
}
private boolean isVariableArity_compute() { return getNumParameter() == 0 ? false : getParameter(getNumParameter()-1).isVariableArity(); }
// Declared in VariableArityParameters.jrag at line 63
@SuppressWarnings({"unchecked", "cast"}) public ParameterDeclaration lastParameter() {
ParameterDeclaration lastParameter_value = lastParameter_compute();
return lastParameter_value;
}
private ParameterDeclaration lastParameter_compute() { return getParameter(getNumParameter() - 1); }
// Declared in InnerClasses.jrag at line 413
@SuppressWarnings({"unchecked", "cast"}) public boolean needsEnclosing() {
boolean needsEnclosing_value = needsEnclosing_compute();
return needsEnclosing_value;
}
private boolean needsEnclosing_compute() { return hostType().needsEnclosing(); }
// Declared in InnerClasses.jrag at line 414
@SuppressWarnings({"unchecked", "cast"}) public boolean needsSuperEnclosing() {
boolean needsSuperEnclosing_value = needsSuperEnclosing_compute();
return needsSuperEnclosing_value;
}
private boolean needsSuperEnclosing_compute() { return hostType().needsSuperEnclosing(); }
// Declared in InnerClasses.jrag at line 416
@SuppressWarnings({"unchecked", "cast"}) public TypeDecl enclosing() {
TypeDecl enclosing_value = enclosing_compute();
return enclosing_value;
}
private TypeDecl enclosing_compute() { return hostType().enclosing(); }
// Declared in InnerClasses.jrag at line 417
@SuppressWarnings({"unchecked", "cast"}) public TypeDecl superEnclosing() {
TypeDecl superEnclosing_value = superEnclosing_compute();
return superEnclosing_value;
}
private TypeDecl superEnclosing_compute() { return hostType().superEnclosing(); }
// Declared in EmitJimple.jrag at line 121
@SuppressWarnings({"unchecked", "cast"}) public int sootTypeModifiers() {
int sootTypeModifiers_value = sootTypeModifiers_compute();
return sootTypeModifiers_value;
}
private int sootTypeModifiers_compute() {
int result = 0;
if(isPublic()) result |= soot.Modifier.PUBLIC;
if(isProtected()) result |= soot.Modifier.PROTECTED;
if(isPrivate()) result |= soot.Modifier.PRIVATE;
return result;
}
protected boolean sootMethod_computed = false;
protected SootMethod sootMethod_value;
// Declared in EmitJimple.jrag at line 288
@SuppressWarnings({"unchecked", "cast"}) public SootMethod sootMethod() {
if(sootMethod_computed)
return sootMethod_value;
int num = boundariesCrossed;
boolean isFinal = this.is$Final();
sootMethod_value = sootMethod_compute();
if(isFinal && num == boundariesCrossed)
sootMethod_computed = true;
return sootMethod_value;
}
private SootMethod sootMethod_compute() {
ArrayList list = new ArrayList();
// this$0
TypeDecl typeDecl = hostType();
if(typeDecl.needsEnclosing())
list.add(typeDecl.enclosingType().getSootType());
if(typeDecl.needsSuperEnclosing()) {
TypeDecl superClass = ((ClassDecl)typeDecl).superclass();
list.add(superClass.enclosingType().getSootType());
}
// args
for(int i = 0; i < getNumParameter(); i++)
list.add(getParameter(i).type().getSootType());
return hostType().getSootClassDecl().getMethod("<init>", list, soot.VoidType.v());
}
protected boolean sootRef_computed = false;
protected SootMethodRef sootRef_value;
// Declared in EmitJimple.jrag at line 303
@SuppressWarnings({"unchecked", "cast"}) public SootMethodRef sootRef() {
if(sootRef_computed)
return sootRef_value;
int num = boundariesCrossed;
boolean isFinal = this.is$Final();
sootRef_value = sootRef_compute();
if(isFinal && num == boundariesCrossed)
sootRef_computed = true;
return sootRef_value;
}
private SootMethodRef sootRef_compute() {
ArrayList parameters = new ArrayList();
TypeDecl typeDecl = hostType();
if(typeDecl.needsEnclosing())
parameters.add(typeDecl.enclosingType().getSootType());
if(typeDecl.needsSuperEnclosing()) {
TypeDecl superClass = ((ClassDecl)typeDecl).superclass();
parameters.add(superClass.enclosingType().getSootType());
}
for(int i = 0; i < getNumParameter(); i++)
parameters.add(getParameter(i).type().getSootType());
SootMethodRef ref = Scene.v().makeConstructorRef(
hostType().getSootClassDecl(),
parameters
);
return ref;
}
protected boolean localNumOfFirstParameter_computed = false;
protected int localNumOfFirstParameter_value;
// Declared in LocalNum.jrag at line 32
@SuppressWarnings({"unchecked", "cast"}) public int localNumOfFirstParameter() {
if(localNumOfFirstParameter_computed)
return localNumOfFirstParameter_value;
int num = boundariesCrossed;
boolean isFinal = this.is$Final();
localNumOfFirstParameter_value = localNumOfFirstParameter_compute();
if(isFinal && num == boundariesCrossed)
localNumOfFirstParameter_computed = true;
return localNumOfFirstParameter_value;
}
private int localNumOfFirstParameter_compute() {
int i = 0;
if(hostType().needsEnclosing())
i++;
if(hostType().needsSuperEnclosing())
i++;
return i;
}
protected boolean offsetFirstEnclosingVariable_computed = false;
protected int offsetFirstEnclosingVariable_value;
// Declared in LocalNum.jrag at line 41
@SuppressWarnings({"unchecked", "cast"}) public int offsetFirstEnclosingVariable() {
if(offsetFirstEnclosingVariable_computed)
return offsetFirstEnclosingVariable_value;
int num = boundariesCrossed;
boolean isFinal = this.is$Final();
offsetFirstEnclosingVariable_value = offsetFirstEnclosingVariable_compute();
if(isFinal && num == boundariesCrossed)
offsetFirstEnclosingVariable_computed = true;
return offsetFirstEnclosingVariable_value;
}
private int offsetFirstEnclosingVariable_compute() { return getNumParameter() == 0 ?
localNumOfFirstParameter() :
getParameter(getNumParameter()-1).localNum() + getParameter(getNumParameter()-1).type().variableSize(); }
// Declared in GenericsCodegen.jrag at line 313
@SuppressWarnings({"unchecked", "cast"}) public ConstructorDecl erasedConstructor() {
ConstructorDecl erasedConstructor_value = erasedConstructor_compute();
return erasedConstructor_value;
}
private ConstructorDecl erasedConstructor_compute() { return this; }
protected java.util.Map handlesException_TypeDecl_values;
// Declared in ExceptionHandling.jrag at line 36
@SuppressWarnings({"unchecked", "cast"}) public boolean handlesException(TypeDecl exceptionType) {
Object _parameters = exceptionType;
if(handlesException_TypeDecl_values == null) handlesException_TypeDecl_values = new java.util.HashMap(4);
if(handlesException_TypeDecl_values.containsKey(_parameters))
return ((Boolean)handlesException_TypeDecl_values.get(_parameters)).booleanValue();
int num = boundariesCrossed;
boolean isFinal = this.is$Final();
boolean handlesException_TypeDecl_value = getParent().Define_boolean_handlesException(this, null, exceptionType);
if(isFinal && num == boundariesCrossed)
handlesException_TypeDecl_values.put(_parameters, Boolean.valueOf(handlesException_TypeDecl_value));
return handlesException_TypeDecl_value;
}
// Declared in TypeAnalysis.jrag at line 267
@SuppressWarnings({"unchecked", "cast"}) public TypeDecl unknownType() {
TypeDecl unknownType_value = getParent().Define_TypeDecl_unknownType(this, null);
return unknownType_value;
}
// Declared in VariableDeclaration.jrag at line 78
public boolean Define_boolean_isConstructorParameter(ASTNode caller, ASTNode child) {
if(caller == getParameterListNoTransform()) {
int childIndex = caller.getIndexOfChild(child);
return true;
}
return getParent().Define_boolean_isConstructorParameter(this, caller);
}
// Declared in Modifiers.jrag at line 282
public boolean Define_boolean_mayBePrivate(ASTNode caller, ASTNode child) {
if(caller == getModifiersNoTransform()) {
return true;
}
return getParent().Define_boolean_mayBePrivate(this, caller);
}
// Declared in LookupMethod.jrag at line 45
public Collection Define_Collection_lookupMethod(ASTNode caller, ASTNode child, String name) {
if(caller == getConstructorInvocationOptNoTransform()){
Collection c = new ArrayList();
for(Iterator iter = lookupMethod(name).iterator(); iter.hasNext(); ) {
MethodDecl m = (MethodDecl)iter.next();
if(!hostType().memberMethods(name).contains(m) || m.isStatic())
c.add(m);
}
return c;
}
return getParent().Define_Collection_lookupMethod(this, caller, name);
}
// Declared in LookupVariable.jrag at line 64
public SimpleSet Define_SimpleSet_lookupVariable(ASTNode caller, ASTNode child, String name) {
if(caller == getParameterListNoTransform()) {
int childIndex = caller.getIndexOfChild(child);
return parameterDeclaration(name);
}
if(caller == getConstructorInvocationOptNoTransform()){
SimpleSet set = parameterDeclaration(name);
if(!set.isEmpty()) return set;
for(Iterator iter = lookupVariable(name).iterator(); iter.hasNext(); ) {
Variable v = (Variable)iter.next();
if(!hostType().memberFields(name).contains(v) || v.isStatic())
set = set.add(v);
}
return set;
}
if(caller == getBlockNoTransform()){
SimpleSet set = parameterDeclaration(name);
if(!set.isEmpty()) return set;
return lookupVariable(name);
}
return getParent().Define_SimpleSet_lookupVariable(this, caller, name);
}
// Declared in ExceptionHandling.jrag at line 133
public boolean Define_boolean_handlesException(ASTNode caller, ASTNode child, TypeDecl exceptionType) {
if(caller == getConstructorInvocationOptNoTransform()) {
return throwsException(exceptionType) || handlesException(exceptionType);
}
if(caller == getBlockNoTransform()) {
return throwsException(exceptionType) || handlesException(exceptionType);
}
return getParent().Define_boolean_handlesException(this, caller, exceptionType);
}
// Declared in UnreachableStatements.jrag at line 32
public boolean Define_boolean_reachable(ASTNode caller, ASTNode child) {
if(caller == getBlockNoTransform()) {
return !hasConstructorInvocation() ? true : getConstructorInvocation().canCompleteNormally();
}
if(caller == getConstructorInvocationOptNoTransform()) {
return true;
}
return getParent().Define_boolean_reachable(this, caller);
}
// Declared in DefiniteAssignment.jrag at line 300
public boolean Define_boolean_isDAbefore(ASTNode caller, ASTNode child, Variable v) {
if(caller == getBlockNoTransform()) {
return hasConstructorInvocation() ? getConstructorInvocation().isDAafter(v) : isDAbefore(v);
}
return getParent().Define_boolean_isDAbefore(this, caller, v);
}
// Declared in Annotations.jrag at line 89
public boolean Define_boolean_mayUseAnnotationTarget(ASTNode caller, ASTNode child, String name) {
if(caller == getModifiersNoTransform()) {
return name.equals("CONSTRUCTOR");
}
return getParent().Define_boolean_mayUseAnnotationTarget(this, caller, name);
}
// Declared in TypeHierarchyCheck.jrag at line 132
public boolean Define_boolean_inExplicitConstructorInvocation(ASTNode caller, ASTNode child) {
if(caller == getConstructorInvocationOptNoTransform()) {
return true;
}
return getParent().Define_boolean_inExplicitConstructorInvocation(this, caller);
}
// Declared in VariableDeclaration.jrag at line 77
public boolean Define_boolean_isMethodParameter(ASTNode caller, ASTNode child) {
if(caller == getParameterListNoTransform()) {
int childIndex = caller.getIndexOfChild(child);
return false;
}
return getParent().Define_boolean_isMethodParameter(this, caller);
}
// Declared in Modifiers.jrag at line 280
public boolean Define_boolean_mayBePublic(ASTNode caller, ASTNode child) {
if(caller == getModifiersNoTransform()) {
return true;
}
return getParent().Define_boolean_mayBePublic(this, caller);
}
// Declared in LocalNum.jrag at line 45
public int Define_int_localNum(ASTNode caller, ASTNode child) {
if(caller == getParameterListNoTransform()) {
int index = caller.getIndexOfChild(child);
{
if(index == 0) {
return localNumOfFirstParameter();
}
return getParameter(index-1).localNum() + getParameter(index-1).type().variableSize();
}
}
return getParent().Define_int_localNum(this, caller);
}
// Declared in Modifiers.jrag at line 281
public boolean Define_boolean_mayBeProtected(ASTNode caller, ASTNode child) {
if(caller == getModifiersNoTransform()) {
return true;
}
return getParent().Define_boolean_mayBeProtected(this, caller);
}
// Declared in NameCheck.jrag at line 242
public ASTNode Define_ASTNode_enclosingBlock(ASTNode caller, ASTNode child) {
if(caller == getBlockNoTransform()) {
return this;
}
return getParent().Define_ASTNode_enclosingBlock(this, caller);
}
// Declared in VariableArityParameters.jrag at line 21
public boolean Define_boolean_variableArityValid(ASTNode caller, ASTNode child) {
if(caller == getParameterListNoTransform()) {
int i = caller.getIndexOfChild(child);
return i == getNumParameter() - 1;
}
return getParent().Define_boolean_variableArityValid(this, caller);
}
// Declared in VariableDeclaration.jrag at line 79
public boolean Define_boolean_isExceptionHandlerParameter(ASTNode caller, ASTNode child) {
if(caller == getParameterListNoTransform()) {
int childIndex = caller.getIndexOfChild(child);
return false;
}
return getParent().Define_boolean_isExceptionHandlerParameter(this, caller);
}
// Declared in Statements.jrag at line 349
public boolean Define_boolean_enclosedByExceptionHandler(ASTNode caller, ASTNode child) {
if(caller == getBlockNoTransform()) {
return getNumException() != 0;
}
return getParent().Define_boolean_enclosedByExceptionHandler(this, caller);
}
// Declared in SyntacticClassification.jrag at line 117
public NameType Define_NameType_nameType(ASTNode caller, ASTNode child) {
if(caller == getConstructorInvocationOptNoTransform()) {
return NameType.EXPRESSION_NAME;
}
if(caller == getExceptionListNoTransform()) {
int childIndex = caller.getIndexOfChild(child);
return NameType.TYPE_NAME;
}
if(caller == getParameterListNoTransform()) {
int childIndex = caller.getIndexOfChild(child);
return NameType.TYPE_NAME;
}
return getParent().Define_NameType_nameType(this, caller);
}
// Declared in TypeCheck.jrag at line 517
public TypeDecl Define_TypeDecl_enclosingInstance(ASTNode caller, ASTNode child) {
if(caller == getConstructorInvocationOptNoTransform()) {
return unknownType();
}
return getParent().Define_TypeDecl_enclosingInstance(this, caller);
}
// Declared in TypeHierarchyCheck.jrag at line 144
public boolean Define_boolean_inStaticContext(ASTNode caller, ASTNode child) {
if(caller == getConstructorInvocationOptNoTransform()) {
return false;
}
if(caller == getBlockNoTransform()) {
return false;
}
return getParent().Define_boolean_inStaticContext(this, caller);
}
// Declared in DefiniteAssignment.jrag at line 756
public boolean Define_boolean_isDUbefore(ASTNode caller, ASTNode child, Variable v) {
if(caller == getBlockNoTransform()) {
return hasConstructorInvocation() ? getConstructorInvocation().isDUafter(v) : isDUbefore(v);
}
return getParent().Define_boolean_isDUbefore(this, caller, v);
}
public ASTNode rewriteTo() {
// Declared in LookupConstructor.jrag at line 186
if(!hasConstructorInvocation() && !hostType().isObject()) {
duringLookupConstructor++;
ASTNode result = rewriteRule0();
duringLookupConstructor--;
return result;
}
return super.rewriteTo();
}
// Declared in LookupConstructor.jrag at line 186
private ConstructorDecl rewriteRule0() {
{
setConstructorInvocation(
new ExprStmt(
new SuperConstructorAccess("super", new List())
)
);
return this;
} }
}
| BuddhaLabs/DeD-OSX | soot/soot-2.3.0/generated/jastadd/soot/JastAddJ/ConstructorDecl.java | Java | gpl-2.0 | 60,391 |
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* 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 only.
*
* 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 net.pms.newgui;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.Borders;
import com.jgoodies.forms.layout.*;
import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nonnull;
import javax.imageio.ImageIO;
import javax.swing.*;
import net.pms.Messages;
import net.pms.PMS;
import net.pms.configuration.PmsConfiguration;
import net.pms.configuration.RendererConfiguration;
import net.pms.newgui.LooksFrame.AbstractTabListenerRegistrar;
import net.pms.newgui.LooksFrame.LooksFrameTab;
import net.pms.newgui.components.AnimatedIcon;
import net.pms.newgui.components.AnimatedIcon.AnimatedIconFrame;
import net.pms.newgui.components.AnimatedIcon.AnimatedIconListenerRegistrar;
import net.pms.newgui.components.AnimatedIcon.AnimatedIconStage;
import net.pms.newgui.components.AnimatedIcon.AnimatedIconType;
import net.pms.newgui.components.AnimatedButton;
import net.pms.util.BasicPlayer;
import net.pms.util.FormLayoutUtil;
import net.pms.util.StringUtil;
import net.pms.util.UMSUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StatusTab {
private static final Logger LOGGER = LoggerFactory.getLogger(StatusTab.class);
private static final Color memColor = new Color(119, 119, 119, 128);
private static final Color bufColor = new Color(75, 140, 181, 128);
public static class RendererItem implements ActionListener {
public ImagePanel icon;
public JLabel label;
public GuiUtil.MarqueeLabel playingLabel;
// public GuiUtil.ScrollLabel playingLabel;
public GuiUtil.FixedPanel playing;
public JLabel time;
public JFrame frame;
public GuiUtil.SmoothProgressBar rendererProgressBar;
public RendererPanel panel;
public String name = " ";
private JPanel _panel = null;
public RendererItem(RendererConfiguration renderer) {
icon = addRendererIcon(renderer.getRendererIcon());
icon.enableRollover();
label = new JLabel(renderer.getRendererName());
playingLabel = new GuiUtil.MarqueeLabel(" ");
// playingLabel = new GuiUtil.ScrollLabel(" ");
playingLabel.setForeground(Color.gray);
int h = (int) playingLabel.getSize().getHeight();
playing = new GuiUtil.FixedPanel(0, h);
playing.add(playingLabel);
time = new JLabel(" ");
time.setForeground(Color.gray);
rendererProgressBar = new GuiUtil.SmoothProgressBar(0, 100, new GuiUtil.SimpleProgressUI(Color.gray, Color.gray));
rendererProgressBar.setStringPainted(true);
rendererProgressBar.setBorderPainted(false);
if (renderer.getAddress() != null) {
rendererProgressBar.setString(renderer.getAddress().getHostAddress());
}
rendererProgressBar.setForeground(bufColor);
}
@Override
public void actionPerformed(final ActionEvent e) {
BasicPlayer.State state = ((BasicPlayer) e.getSource()).getState();
time.setText((state.playback == BasicPlayer.STOPPED || StringUtil.isZeroTime(state.position)) ? " " :
UMSUtils.playedDurationStr(state.position, state.duration));
rendererProgressBar.setValue((int) (100 * state.buffer / bufferSize));
String n = (state.playback == BasicPlayer.STOPPED || StringUtils.isBlank(state.name)) ? " " : state.name;
if (!name.equals(n)) {
name = n;
playingLabel.setText(name);
}
}
public void addTo(Container parent) {
parent.add(getPanel());
parent.validate();
// Maximize the playing label width
int w = _panel.getWidth() - _panel.getInsets().left - _panel.getInsets().right;
playing.setSize(w, (int) playingLabel.getSize().getHeight());
playingLabel.setMaxWidth(w);
}
public void delete() {
try {
// Delete the popup if open
if (frame != null) {
frame.dispose();
frame = null;
}
Container parent = _panel.getParent();
parent.remove(_panel);
parent.revalidate();
parent.repaint();
} catch (Exception e) {
}
}
public JPanel getPanel() {
if (_panel == null) {
PanelBuilder b = new PanelBuilder(new FormLayout(
"center:pref",
"max(140px;pref), 3dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref"
));
b.opaque(true);
CellConstraints cc = new CellConstraints();
b.add(icon, cc.xy(1, 1));
b.add(label, cc.xy(1, 3, CellConstraints.CENTER, CellConstraints.DEFAULT));
b.add(rendererProgressBar, cc.xy(1, 5));
b.add(playing, cc.xy(1, 7, CellConstraints.CENTER, CellConstraints.DEFAULT));
b.add(time, cc.xy(1, 9));
_panel = b.getPanel();
}
return _panel;
}
}
private JPanel renderers;
private JProgressBar memoryProgressBar;
private GuiUtil.SegmentedProgressBarUI memBarUI;
private JLabel bitrateLabel;
private JLabel currentBitrate;
private JLabel currentBitrateLabel;
private JLabel peakBitrate;
private JLabel peakBitrateLabel;
private long rc = 0;
private long peak;
private static DecimalFormat formatter = new DecimalFormat("#,###");
private static int bufferSize;
public enum ConnectionState {
SEARCHING, CONNECTED, DISCONNECTED, BLOCKED, UNKNOWN
}
private ConnectionState connectionState = ConnectionState.UNKNOWN;
private final AnimatedButton connectionStatus = new AnimatedButton();
private final AnimatedIcon searchingIcon;
private final AnimatedIcon connectedIcon;
private final AnimatedIcon connectedIntroIcon;
private final AnimatedIcon disconnectedIcon;
private final AnimatedIcon blockedIcon;
private final StatusTabListenerRegistrar tabListenerRegistrar;
StatusTab(PmsConfiguration configuration, final LooksFrame looksFrame) {
tabListenerRegistrar = new StatusTabListenerRegistrar(looksFrame);
// Build Animations
searchingIcon = new AnimatedIcon(
connectionStatus,
true,
AnimatedIcon.buildAnimation("icon-status-connecting_%02d.png", 0, 50, false, 40, 40, 40)
);
final Icon connectedLeft = LooksFrame.readImageIcon("icon-status-connected_89.png");
final Icon connectedBoth = LooksFrame.readImageIcon("icon-status-connected_90.png");
final Icon connectedNone = LooksFrame.readImageIcon("icon-status-connected_92.png");
final Icon disconnectedNone = LooksFrame.readImageIcon("icon-status-disconnected_00.png");
final Icon disconnectedLeft = LooksFrame.readImageIcon("icon-status-disconnected_01.png");
final Icon disconnectedBoth = LooksFrame.readImageIcon("icon-status-disconnected_02.png");
final Icon disconnectedRight = LooksFrame.readImageIcon("icon-status-disconnected_03.png");
List<AnimatedIconFrame> connectedIntroFrames = new ArrayList<>(Arrays.asList(
AnimatedIcon.buildAnimation("icon-status-connected_%02d.png", 0, 88, false, 40, 500, 40)
));
connectedIntroFrames.add(new AnimatedIconFrame(connectedNone, 200));
connectedIcon = new AnimatedIcon(
connectionStatus,
true,
new AnimatedIconFrame(connectedLeft, 500, 800),
new AnimatedIconFrame(connectedBoth, 80),
new AnimatedIconFrame(connectedLeft, 80, 600),
new AnimatedIconFrame(connectedBoth, 80),
new AnimatedIconFrame(connectedLeft, 100),
new AnimatedIconFrame(connectedBoth, 80),
new AnimatedIconFrame(connectedLeft, 600),
new AnimatedIconFrame(connectedBoth, 80),
new AnimatedIconFrame(connectedLeft, 50, 400),
new AnimatedIconFrame(connectedBoth, 80),
new AnimatedIconFrame(connectedLeft, 100),
new AnimatedIconFrame(connectedBoth, 80),
new AnimatedIconFrame(connectedLeft, 50, 200),
new AnimatedIconFrame(connectedBoth, 80),
new AnimatedIconFrame(connectedLeft, 100, 1000),
new AnimatedIconFrame(connectedBoth, 80)
);
tabListenerRegistrar.register(connectedIcon);
connectedIntroIcon = new AnimatedIcon(
connectionStatus,
new AnimatedIconStage(AnimatedIconType.DEFAULTICON, connectedIcon, true),
connectedIntroFrames
);
disconnectedIcon = new AnimatedIcon(
connectionStatus,
true,
new AnimatedIconFrame(disconnectedNone, 200, 800),
new AnimatedIconFrame(disconnectedLeft, 300),
new AnimatedIconFrame(disconnectedRight, 300),
new AnimatedIconFrame(disconnectedNone, 50, 150),
new AnimatedIconFrame(disconnectedBoth, 80, 600),
new AnimatedIconFrame(disconnectedNone, 10, 600),
new AnimatedIconFrame(disconnectedBoth, 80),
new AnimatedIconFrame(disconnectedNone, 50, 200),
new AnimatedIconFrame(disconnectedBoth, 50, 160),
new AnimatedIconFrame(disconnectedNone, 100, 500),
new AnimatedIconFrame(disconnectedRight, 150),
new AnimatedIconFrame(disconnectedLeft, 150)
);
tabListenerRegistrar.register(disconnectedIcon);
blockedIcon = new AnimatedIcon(connectionStatus, "icon-status-warning.png");
bufferSize = configuration.getMaxMemoryBufferSize();
}
void setConnectionState(ConnectionState connectionState) {
if (connectionState == null) {
throw new IllegalArgumentException("connectionState cannot be null");
}
if (!connectionState.equals(this.connectionState)) {
this.connectionState = connectionState;
AnimatedIcon oldIcon = (AnimatedIcon) connectionStatus.getIcon();
switch (connectionState) {
case SEARCHING:
connectionStatus.setToolTipText(Messages.getString("PMS.130"));
searchingIcon.restartArm();
if (oldIcon != null) {
oldIcon.setNextStage(new AnimatedIconStage(AnimatedIconType.DEFAULTICON, searchingIcon, false));
} else {
connectionStatus.setIcon(searchingIcon);
}
break;
case CONNECTED:
connectionStatus.setToolTipText(Messages.getString("PMS.18"));
connectedIntroIcon.restartArm();
connectedIcon.restartArm();
if (oldIcon != null) {
oldIcon.setNextStage(new AnimatedIconStage(AnimatedIconType.DEFAULTICON, connectedIntroIcon, false));
} else {
connectionStatus.setIcon(connectedIntroIcon);
}
break;
case DISCONNECTED:
connectionStatus.setToolTipText(Messages.getString("PMS.0"));
disconnectedIcon.restartArm();
if (oldIcon != null) {
oldIcon.setNextStage(new AnimatedIconStage(AnimatedIconType.DEFAULTICON, disconnectedIcon, false));
} else {
connectionStatus.setIcon(disconnectedIcon);
}
break;
case BLOCKED:
connectionStatus.setToolTipText(Messages.getString("PMS.141"));
blockedIcon.reset();
if (oldIcon != null) {
oldIcon.setNextStage(new AnimatedIconStage(AnimatedIconType.DEFAULTICON, blockedIcon, false));
} else {
connectionStatus.setIcon(blockedIcon);
}
break;
default:
connectionStatus.setIcon(null);
break;
}
}
}
public void updateCurrentBitrate() {
long total = 0;
List<RendererConfiguration> foundRenderers = PMS.get().getFoundRenderers();
synchronized(foundRenderers) {
for (RendererConfiguration r : foundRenderers) {
total += r.getBuffer();
}
}
if (total == 0) {
currentBitrate.setText("0");
}
}
public JComponent build() {
// Apply the orientation for the locale
ComponentOrientation orientation = ComponentOrientation.getOrientation(PMS.getLocale());
String colSpec = FormLayoutUtil.getColSpec("pref, 30dlu, fill:pref:grow, 30dlu, pref", orientation);
// 1 2 3 4 5
//RowSpec.decode("bottom:max(50dlu;pref)");
FormLayout layout = new FormLayout(colSpec,
// 1 2 3 4 5
// //////////////////////////////////////////////////
"p," // Detected Media Renderers --------------------// 1
+ "9dlu," // //
+ "fill:p:grow," // <renderers> // 3
+ "3dlu," // //
+ "p," // ---------------------------------------------// 5
+ "10dlu," // | | //
+ "[10pt,p]," // Connected | Memory Usage |<bitrate> // 7
+ "1dlu," // | | //
+ "[30pt,p]," // <icon> | <statusbar> | // 9
+ "3dlu," // | | //
//////////////////////////////////////////////////
);
PanelBuilder builder = new PanelBuilder(layout);
builder.border(Borders.DIALOG);
builder.opaque(true);
CellConstraints cc = new CellConstraints();
// Renderers
JComponent cmp = builder.addSeparator(Messages.getString("StatusTab.9"), FormLayoutUtil.flip(cc.xyw(1, 1, 5), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
Font bold = cmp.getFont().deriveFont(Font.BOLD);
Color fgColor = new Color(68, 68, 68);
cmp.setFont(bold);
renderers = new JPanel(new GuiUtil.WrapLayout(FlowLayout.CENTER, 20, 10));
JScrollPane rsp = new JScrollPane(
renderers,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
rsp.setBorder(BorderFactory.createEmptyBorder());
rsp.setPreferredSize(new Dimension(0, 260));
rsp.getHorizontalScrollBar().setLocation(0,250);
builder.add(rsp, cc.xyw(1, 3, 5));
cmp = builder.addSeparator(null, FormLayoutUtil.flip(cc.xyw(1, 5, 5), colSpec, orientation));
connectedIcon.startArm();
connectedIntroIcon.startArm();
searchingIcon.startArm();
disconnectedIcon.startArm();
connectionStatus.setFocusable(false);
builder.add(connectionStatus, FormLayoutUtil.flip(cc.xywh(1, 7, 1, 3, CellConstraints.CENTER, CellConstraints.TOP), colSpec, orientation));
// Set initial connection state
setConnectionState(ConnectionState.SEARCHING);
// Memory
memBarUI = new GuiUtil.SegmentedProgressBarUI(Color.white, Color.gray);
memBarUI.setActiveLabel("{}", Color.white, 0);
memBarUI.setActiveLabel("{}", Color.red, 90);
memBarUI.addSegment("", memColor);
memBarUI.addSegment("", bufColor);
memBarUI.setTickMarks(getTickMarks(), "{}");
memoryProgressBar = new GuiUtil.CustomUIProgressBar(0, 100, memBarUI);
memoryProgressBar.setForeground(new Color(75, 140, 181));
JLabel mem = builder.addLabel("<html><b>" + Messages.getString("StatusTab.6") + "</b> (" + Messages.getString("StatusTab.12") + ")</html>", FormLayoutUtil.flip(cc.xy(3, 7), colSpec, orientation));
mem.setForeground(fgColor);
builder.add(memoryProgressBar, FormLayoutUtil.flip(cc.xyw(3, 9, 1), colSpec, orientation));
// Bitrate
String bitColSpec = "left:pref, 3dlu, right:pref:grow";
PanelBuilder bitrateBuilder = new PanelBuilder(new FormLayout(bitColSpec, "p, 1dlu, p, 1dlu, p"));
bitrateLabel = new JLabel("<html><b>" + Messages.getString("StatusTab.13") + "</b> (" + Messages.getString("StatusTab.11") + ")</html>");
bitrateLabel.setForeground(fgColor);
bitrateBuilder.add(bitrateLabel, FormLayoutUtil.flip(cc.xy(1, 1), bitColSpec, orientation));
currentBitrateLabel = new JLabel(Messages.getString("StatusTab.14"));
currentBitrateLabel.setForeground(fgColor);
bitrateBuilder.add(currentBitrateLabel, FormLayoutUtil.flip(cc.xy(1, 3), bitColSpec, orientation));
currentBitrate = new JLabel("0");
currentBitrate.setForeground(fgColor);
bitrateBuilder.add(currentBitrate, FormLayoutUtil.flip(cc.xy(3, 3), bitColSpec, orientation));
peakBitrateLabel = new JLabel(Messages.getString("StatusTab.15"));
peakBitrateLabel.setForeground(fgColor);
bitrateBuilder.add(peakBitrateLabel, FormLayoutUtil.flip(cc.xy(1, 5), bitColSpec, orientation));
peakBitrate = new JLabel("0");
peakBitrate.setForeground(fgColor);
bitrateBuilder.add(peakBitrate, FormLayoutUtil.flip(cc.xy(3, 5), bitColSpec, orientation));
builder.add(bitrateBuilder.getPanel(), FormLayoutUtil.flip(cc.xywh(5, 7, 1, 3, "left, top"), colSpec, orientation));
JPanel panel = builder.getPanel();
// Apply the orientation to the panel and all components in it
panel.applyComponentOrientation(orientation);
JScrollPane scrollPane = new JScrollPane(
panel,
JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
startMemoryUpdater();
return scrollPane;
}
public void setReadValue(long v, String msg) {
if (v < rc) {
rc = v;
} else {
int sizeinMb = (int) ((v - rc) / 125) / 1024;
if (sizeinMb > peak) {
peak = sizeinMb;
}
currentBitrate.setText(formatter.format(sizeinMb));
peakBitrate.setText(formatter.format(peak));
rc = v;
}
}
public void addRenderer(final RendererConfiguration renderer) {
final RendererItem r = new RendererItem(renderer);
r.addTo(renderers);
renderer.setGuiComponents(r);
r.icon.setAction(new AbstractAction() {
private static final long serialVersionUID = -6316055325551243347L;
@Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (r.frame == null) {
JFrame top = (JFrame) SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame());
// We're using JFrame instead of JDialog here so as to have a minimize button. Since the player panel
// is intrinsically a freestanding module this approach seems valid to me but some frown on it: see
// http://stackoverflow.com/questions/9554636/the-use-of-multiple-jframes-good-bad-practice
r.frame = new JFrame();
r.panel = new RendererPanel(renderer);
r.frame.add(r.panel);
r.panel.update();
r.frame.setResizable(false);
r.frame.setIconImage(((JFrame) PMS.get().getFrame()).getIconImage());
r.frame.setLocationRelativeTo(top);
r.frame.setVisible(true);
} else {
r.frame.setVisible(true);
r.frame.toFront();
}
}
});
}
});
}
public static void updateRenderer(final RendererConfiguration renderer) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if (renderer.gui != null) {
renderer.gui.icon.set(getRendererIcon(renderer.getRendererIcon()));
renderer.gui.label.setText(renderer.getRendererName());
// Update the popup panel if it's been opened
if (renderer.gui.panel != null) {
renderer.gui.panel.update();
}
}
}
});
}
public static ImagePanel addRendererIcon(String icon) {
BufferedImage bi = getRendererIcon(icon);
return bi != null ? new ImagePanel(bi) : null;
}
public static BufferedImage getRendererIcon(String icon) {
BufferedImage bi = null;
if (icon != null) {
if (icon.matches(".*\\S+://.*")) {
try {
bi = ImageIO.read(new URL(icon));
} catch (IOException e) {
LOGGER.debug("Error reading icon url: " + e);
}
if (bi != null) {
return bi;
}
LOGGER.debug("Unable to read icon url \"{}\", using \"{}\" instead.", icon, RendererConfiguration.UNKNOWN_ICON);
icon = RendererConfiguration.UNKNOWN_ICON;
}
try {
InputStream is = null;
/**
* Check for a custom icon file first
*
* The file can be a) the name of a file in the renderers directory b) a path relative
* to the DMS working directory or c) an absolute path. If no file is found,
* the built-in resource (if any) is used instead.
*
* The File constructor does the right thing for the relative and absolute path cases,
* so we only need to detect the bare filename case.
*
* RendererIcon = foo.png // e.g. $DMS/renderers/foo.png
* RendererIcon = images/foo.png // e.g. $DMS/images/foo.png
* RendererIcon = /path/to/foo.png
*/
File f = new File(icon);
if (!f.isAbsolute() && f.getParent() == null) { // filename
f = new File("renderers", icon);
}
if (f.isFile()) {
is = new FileInputStream(f);
}
if (is == null) {
is = LooksFrame.class.getResourceAsStream("/resources/images/clients/" + icon);
}
if (is == null) {
is = LooksFrame.class.getResourceAsStream("/renderers/" + icon);
}
if (is == null) {
LOGGER.debug("Unable to read icon \"{}\", using \"{}\" instead.", icon, RendererConfiguration.UNKNOWN_ICON);
is = LooksFrame.class.getResourceAsStream("/resources/images/clients/" + RendererConfiguration.UNKNOWN_ICON);
}
if (is != null) {
bi = ImageIO.read(is);
}
} catch (IOException e) {
LOGGER.debug("Caught exception", e);
}
}
if (bi == null) {
LOGGER.debug("Failed to load icon: " + icon);
}
return bi;
}
private static int getTickMarks() {
int mb = (int) (Runtime.getRuntime().maxMemory() / 1048576);
return mb < 1000 ? 100 : mb < 2500 ? 250 : mb < 5000 ? 500 : 1000;
}
public void updateMemoryUsage() {
final long max = Runtime.getRuntime().maxMemory() / 1048576;
final long used = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576;
long buf = 0;
List<RendererConfiguration> foundRenderers = PMS.get().getFoundRenderers();
synchronized (foundRenderers) {
for (RendererConfiguration r : PMS.get().getFoundRenderers()) {
buf += (r.getBuffer());
}
}
final long buffer = buf;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
memBarUI.setValues(0, (int) max, (int) (used - buffer), (int) buffer);
}
});
}
private void startMemoryUpdater() {
Runnable r = new Runnable() {
@Override
public void run() {
for(;;) {
updateMemoryUsage();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
return;
}
}
}
};
new Thread(r).start();
}
/**
* Creates a new {@link AnimatedIconListenerRegistrar} that registers tab
* change to and from {@link LooksFrameTab#STATUS_TAB} and application
* minimize events. Suitable for {@link AnimatedIcon}s that's visible
* whenever this tab is visible.
*
* @author Nadahar
*/
public static class StatusTabListenerRegistrar extends AbstractTabListenerRegistrar {
private StatusTabListenerRegistrar(@Nonnull LooksFrame looksFrame) {
super(looksFrame);
}
@Override
protected LooksFrameTab getVisibleTab() {
return LooksFrameTab.STATUS_TAB;
}
}
}
| DigitalMediaServer/DigitalMediaServer | src/main/java/net/pms/newgui/StatusTab.java | Java | gpl-2.0 | 23,246 |
package xyz.zyzhu.spring.config;
import org.apache.log4j.Logger;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.JedisPoolConfig;
/**
* <p>标题: TODO</p>
* <p>功能: </p>
* <p>所属模块: TODO</p>
* <p>版权: Copyright © 2018 SNSOFT</p>
* <p>公司: 赵玉柱练习</p>
* <p>创建日期:2018年2月4日 下午1:34:31</p>
* <p>类全名:xyz.zyzhu.spring.config.RedisConfig</p>
* 作者:赵玉柱
* 初审:
* 复审:
* 监听使用界面:
* @version 8.0
*/
@Configuration
@EnableAutoConfiguration
public class RedisConfig
{
private static Logger logger = Logger.getLogger(RedisConfig.class);
@Bean
@ConfigurationProperties(prefix = "spring.redis")
public JedisPoolConfig getRedisConfig()
{
JedisPoolConfig config = new JedisPoolConfig();
return config;
}
@Bean("RedisCacheManager")
public RedisCacheManager getCacheManager()
{
RedisCacheManager manager = new RedisCacheManager(getRedisTemplate());
return manager;
}
@Bean
@ConfigurationProperties(prefix = "spring.redis")
public JedisConnectionFactory getConnectionFactory()
{
JedisConnectionFactory factory = new JedisConnectionFactory();
JedisPoolConfig config = getRedisConfig();
factory.setPoolConfig(config);
factory.afterPropertiesSet();
logger.info("JedisConnectionFactory bean init success.");
return factory;
}
@Bean
public RedisTemplate<?,?> getRedisTemplate()
{
return getRedisTemplete(Object.class, Object.class);
}
@Bean
public <K extends Object,V extends Object> RedisTemplate<K,V> getRedisTemplete(Class<K> k, Class<V> v)
{
RedisTemplate<K,V> template = new RedisTemplate<>();
template.setConnectionFactory(getConnectionFactory());
template.afterPropertiesSet();
return template;
}
}
| zyz963272311/testGitHub | test-spring-boot/xyz.zyzhu.test-spring-boot/src/main/java/xyz/zyzhu/spring/config/RedisConfig.java | Java | gpl-2.0 | 2,184 |
/*
* Copyright (C) 2007-2014 Geometer Plus <[email protected]>
*
* 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.geometerplus.zlibrary.text.model;
import java.util.ArrayList;
import java.util.List;
import org.geometerplus.zlibrary.core.fonts.FontEntry;
import org.geometerplus.zlibrary.core.fonts.FontManager;
import org.geometerplus.zlibrary.core.util.ZLBoolean3;
public abstract class ZLTextStyleEntry {
public interface Feature {
int LENGTH_LEFT_INDENT = 0;
int LENGTH_RIGHT_INDENT = 1;
int LENGTH_FIRST_LINE_INDENT_DELTA = 2;
int LENGTH_SPACE_BEFORE = 3;
int LENGTH_SPACE_AFTER = 4;
int LENGTH_FONT_SIZE = 5;
int NUMBER_OF_LENGTHS = 6;
int ALIGNMENT_TYPE = NUMBER_OF_LENGTHS;
int FONT_FAMILY = NUMBER_OF_LENGTHS + 1;
int FONT_STYLE_MODIFIER = NUMBER_OF_LENGTHS + 2;
}
public interface FontModifier {
byte FONT_MODIFIER_BOLD = 1 << 0;
byte FONT_MODIFIER_ITALIC = 1 << 1;
byte FONT_MODIFIER_UNDERLINED = 1 << 2;
byte FONT_MODIFIER_STRIKEDTHROUGH = 1 << 3;
byte FONT_MODIFIER_SMALLCAPS = 1 << 4;
byte FONT_MODIFIER_INHERIT = 1 << 5;
byte FONT_MODIFIER_SMALLER = 1 << 6;
byte FONT_MODIFIER_LARGER = (byte)(1 << 7);
}
public interface SizeUnit {
byte PIXEL = 0;
byte POINT = 1;
byte EM_100 = 2;
byte EX_100 = 3;
byte PERCENT = 4;
}
private class Length {
public final short Size;
public final byte Unit;
Length(short size, byte unit) {
Size = size;
Unit = unit;
}
}
private short myFeatureMask;
private Length[] myLengths = new Length[Feature.NUMBER_OF_LENGTHS];
private byte myAlignmentType;
private List<FontEntry> myFontEntries;
private byte mySupportedFontModifiers;
private byte myFontModifiers;
static boolean isFeatureSupported(short mask, int featureId) {
return (mask & (1 << featureId)) != 0;
}
protected ZLTextStyleEntry() {
}
public final boolean isFeatureSupported(int featureId) {
return isFeatureSupported(myFeatureMask, featureId);
}
final void setLength(int featureId, short size, byte unit) {
myFeatureMask |= 1 << featureId;
myLengths[featureId] = new Length(size, unit);
}
private int fullSize(ZLTextMetrics metrics, int featureId) {
switch (featureId) {
default:
case Feature.LENGTH_LEFT_INDENT:
case Feature.LENGTH_RIGHT_INDENT:
case Feature.LENGTH_FIRST_LINE_INDENT_DELTA:
return metrics.FullWidth;
case Feature.LENGTH_SPACE_BEFORE:
case Feature.LENGTH_SPACE_AFTER:
return metrics.FullHeight;
case Feature.LENGTH_FONT_SIZE:
return metrics.FontSize;
}
}
public final int getLength(int featureId, ZLTextMetrics metrics) {
switch (myLengths[featureId].Unit) {
default:
case SizeUnit.PIXEL:
return myLengths[featureId].Size * metrics.FontSize / metrics.DefaultFontSize;
// we understand "point" as "1/2 point"
case SizeUnit.POINT:
return myLengths[featureId].Size
* metrics.DPI * metrics.FontSize
/ 72 / metrics.DefaultFontSize / 2;
case SizeUnit.EM_100:
return (myLengths[featureId].Size * metrics.FontSize + 50) / 100;
case SizeUnit.EX_100:
return (myLengths[featureId].Size * metrics.FontXHeight + 50) / 100;
case SizeUnit.PERCENT:
return (myLengths[featureId].Size * fullSize(metrics, featureId) + 50) / 100;
}
}
final void setAlignmentType(byte alignmentType) {
myFeatureMask |= 1 << Feature.ALIGNMENT_TYPE;
myAlignmentType = alignmentType;
}
public final byte getAlignmentType() {
return myAlignmentType;
}
final void setFontFamilies(FontManager fontManager, int fontFamiliesIndex) {
myFeatureMask |= 1 << Feature.FONT_FAMILY;
myFontEntries = fontManager.getFamilyEntries(fontFamiliesIndex);
}
public final List<FontEntry> getFontEntries() {
return myFontEntries;
}
final void setFontModifiers(byte supported, byte values) {
myFeatureMask |= 1 << Feature.FONT_STYLE_MODIFIER;
mySupportedFontModifiers = supported;
myFontModifiers = values;
}
public final void setFontModifier(byte modifier, boolean on) {
myFeatureMask |= 1 << Feature.FONT_STYLE_MODIFIER;
mySupportedFontModifiers |= modifier;
if (on) {
myFontModifiers |= modifier;
} else {
myFontModifiers &= ~modifier;
}
}
public final ZLBoolean3 getFontModifier(byte modifier) {
if ((mySupportedFontModifiers & modifier) == 0) {
return ZLBoolean3.B3_UNDEFINED;
}
return (myFontModifiers & modifier) == 0 ? ZLBoolean3.B3_FALSE : ZLBoolean3.B3_TRUE;
}
}
| wangtaoenter/Books | Main/src/org/geometerplus/zlibrary/text/model/ZLTextStyleEntry.java | Java | gpl-2.0 | 5,455 |
/**
* Copyright (C) 2006, Laboratorio di Valutazione delle Prestazioni - Politecnico di Milano
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package jmt.gui.exact.panels;
import jmt.analytical.SolverAlgorithm;
import jmt.framework.gui.help.HoverHelp;
import jmt.gui.exact.ExactConstants;
import jmt.gui.exact.ExactModel;
import jmt.gui.exact.ExactWizard;
import jmt.gui.exact.table.ExactTableModel;
/**
* @author alyf (Andrea Conti)
* Date: 11-set-2003
* Time: 23.48.19
*/
/**
* 6th panel: throughput
*/
public final class ThroughputPanel extends SolutionPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private double[][][] throughput;
private double[][] classAggr, stationAggr;
private double[] globalAggr;
/* EDITED by Abhimanyu Chugh */
public ThroughputPanel(ExactWizard ew, SolverAlgorithm alg) {
super(ew, alg);
helpText = "<html>Throughput</html>";
name = "Throughput";
}
/* END */
/**
* gets status from data object
*/
@Override
protected void sync() {
super.sync();
/* EDITED by Abhimanyu Chugh */
throughput = data.getThroughput(algorithm);
classAggr = data.getPerClassX(algorithm);
stationAggr = data.getPerStationX(algorithm);
globalAggr = data.getGlobalX(algorithm);
/* END */
}
@Override
protected ExactTableModel getTableModel() {
return new TPTableModel();
}
@Override
protected String getDescriptionMessage() {
return ExactConstants.DESCRIPTION_THROUGHPUTS;
}
private class TPTableModel extends ExactTableModel {
/**
*
*/
private static final long serialVersionUID = 1L;
TPTableModel() {
prototype = new Double(1000);
rowHeaderPrototype = "Station1000";
}
public int getRowCount() {
if (throughput == null) {
return 0;
}
//OLD
/*
if (stations == 1) return 1;
return stations;
*/
//NEW
//@author Dall'Orso
return stations + 1;
//end NEW
}
public int getColumnCount() {
if (throughput == null) {
return 0;
}
//OLD
/*
if (isSingle) return 1;
return classes;
*/
//NEW
//@author Dall'Orso
return classes + 1;
//end NEW
}
@Override
protected Object getRowName(int rowIndex) {
if (rowIndex == 0) {
return "<html><i>Aggregate</i></html>";
} else {
return stationNames[rowIndex - 1];
}
}
@Override
public String getColumnName(int index) {
if (index == 0) {
return "<html><i>Aggregate</i></html>";
} else {
return classNames[index - 1];
}
}
@Override
protected Object getValueAtImpl(int rowIndex, int columnIndex) {
double d;
if (rowIndex == 0 && columnIndex == 0) {
d = globalAggr[iteration];
} else if (rowIndex == 0 && columnIndex > 0) {
d = classAggr[columnIndex - 1][iteration];
} else if (rowIndex > 0 && columnIndex == 0) {
d = stationAggr[rowIndex - 1][iteration];
} else {
d = throughput[rowIndex - 1][columnIndex - 1][iteration];
}
if (d < 0) {
return null; //causes the renderer to display a gray cell
}
return new Double(d);
}
}
}
| chpatrick/jmt | src/jmt/gui/exact/panels/ThroughputPanel.java | Java | gpl-2.0 | 3,897 |
import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf;
import org.checkerframework.checker.nullness.qual.*;
public class Conditions {
@Nullable Object f;
void test1(Conditions c) {
if (!(c.f!=null))
return;
c.f.hashCode();
}
void test2(Conditions c) {
if (!(c.f!=null) || 5 > 9)
return;
c.f.hashCode();
}
@EnsuresNonNullIf(expression="f", result=true)
public boolean isNN() {
return (f != null);
}
void test1m(Conditions c) {
if (!(c.isNN()))
return;
c.f.hashCode();
}
void test2m(Conditions c) {
if (!(c.isNN()) || 5 > 9)
return;
c.f.hashCode();
}
} | biddyweb/checker-framework | checker/tests/nullness/Conditions.java | Java | gpl-2.0 | 757 |
/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
/*
* Copyright (C) 2008 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 libcore.java.net;
import java.net.HttpRetryException;
import junit.framework.TestCase;
public class OldHttpRetryExceptionTest extends TestCase {
public void test_ConstructorLStringI() {
String [] message = {"Test message", "", "Message", "~!@#$% &*(", null};
int [] codes = {400, 404, 200, 500, 0};
for(int i = 0; i < message.length; i++) {
HttpRetryException hre = new HttpRetryException(message[i],
codes[i]);
assertEquals(message[i], hre.getReason());
assertTrue("responseCode is incorrect: " + hre.responseCode(),
hre.responseCode() == codes[i]);
}
}
public void test_ConstructorLStringILString() {
String [] message = {"Test message", "", "Message", "~!@#$% &*(", null};
int [] codes = {400, -1, Integer.MAX_VALUE, Integer.MIN_VALUE, 0};
String [] locations = {"file:\\error.txt", "http:\\localhost",
"", null, ""};
for(int i = 0; i < message.length; i++) {
HttpRetryException hre = new HttpRetryException(message[i],
codes[i], locations[i]);
assertEquals(message[i], hre.getReason());
assertTrue("responseCode is incorrect: " + hre.responseCode(),
hre.responseCode() == codes[i]);
assertEquals(locations[i], hre.getLocation());
}
}
}
| rex-xxx/mt6572_x201 | mediatek/frameworks/base/tests/net/tests/src/mediatek/net/libcore/OldHttpRetryExceptionTest.java | Java | gpl-2.0 | 4,271 |
package approximateApproach;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import Jama.Matrix;
public class ComputeBoundingBox implements ComputeBoundingBoxInterface{
static private class Node{
double[] m_nodeCoord;
int m_elementId;
public Node(double x, double y, double z, int elementId)
{
m_nodeCoord=new double[3];
m_nodeCoord[0]=x;
m_nodeCoord[1]=y;
m_nodeCoord[2]=z;
m_elementId=elementId;
}
//Class member access functions
public double[] getCoordinates()
{
return m_nodeCoord;
}
public int getElementId()
{
return m_elementId;
}
}
private double[] m_queryPoint;
private double[] m_inspectorBFR;
private double[] m_nearPlane;
private double[] m_farPlane;
private double m_viewAngle;
private String m_outputNodeFile, m_outputElementFile;
private List<Node> nodesList;
//Parameters used in the containment algorithm, their values can be set in the constructor and then used for every node query point
private Matrix M_I, M_F1, M_F2, planeNormal;
private double distanceToNearPoint, distanceToFarPoint;
static private Hashtable<Integer, Integer> elementNodeCount;
static private List<Node> elementsWithNodesAboveDeck;
static private List<Node> elementsWithNodesBelowDeck;
static{
String str;
BufferedReader fileNodesAboveDeck;
BufferedReader fileNodesBelowDeck;
BufferedReader fileVisibleEl;
//nodesAboveDeck=new ArrayList<String> ();
//nodesBelowDeck=new ArrayList<String> ();
elementsWithNodesAboveDeck = new ArrayList<Node> ();
elementsWithNodesBelowDeck = new ArrayList<Node> ();
elementNodeCount=new Hashtable<Integer, Integer>();
System.out.println("I am in static of ComputeBoundingBox and doing IO");
try {
fileNodesAboveDeck = new BufferedReader(new FileReader(Config.getNodesAboveDeck()));
fileNodesBelowDeck = new BufferedReader(new FileReader(Config.getNodesBelowDeck()));
fileVisibleEl = new BufferedReader(new FileReader(Config.getVisibleElementsFile()));
//Iterate over nodes above deck and add to nodesAboveDeck list
while((str=fileNodesAboveDeck.readLine())!=null){
String[] temp=str.split("\\s+");
int element_id=Integer.parseInt(temp[temp.length-1]);
//Store the element ID along with (x,y,z) coordinates of all nodes that constitute the element in elementsWithNodesAboveDeck list
elementsWithNodesAboveDeck.add(new Node(Double.parseDouble(temp[1]), Double.parseDouble(temp[2]), Double.parseDouble(temp[3]), element_id));
if(elementNodeCount.containsKey(element_id))
elementNodeCount.put(element_id, (elementNodeCount.get(element_id)+1));
else
elementNodeCount.put(element_id, 1);
}
//Iterate over nodes below deck and add to nodesBelowDeck list
while((str=fileNodesBelowDeck.readLine())!=null){
String[] temp=str.split("\\s+");
int element_id=Integer.parseInt(temp[temp.length-1]);
//Store the element ID along with (x,y,z) coordinates of all nodes that constitute the element in elementsWithNodesBelowDeck list
elementsWithNodesBelowDeck.add(new Node(Double.parseDouble(temp[1]), Double.parseDouble(temp[2]), Double.parseDouble(temp[3]), element_id));
if(elementNodeCount.containsKey(element_id))
elementNodeCount.put(element_id, (elementNodeCount.get(element_id)+1));
else
elementNodeCount.put(element_id, 1);
}
fileNodesAboveDeck.close();
fileNodesBelowDeck.close();
fileVisibleEl.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//This constructor was last used for real field data
public ComputeBoundingBox(double[] inspectorBFR, double[] nearPlane, double[] farPlane, double viewAngle, int position) {
m_inspectorBFR=inspectorBFR;
m_nearPlane=nearPlane;
m_farPlane=farPlane;
m_viewAngle=viewAngle;
M_I=new Matrix(new double[][] {m_inspectorBFR});
M_F1=new Matrix(new double[][] {m_nearPlane});
M_F2=new Matrix(new double[][] {m_farPlane});
planeNormal=new Matrix(1,3);
for(int i=0;i<3;i++)
planeNormal.set(0,i,((M_F2.minus(M_I).get(0,i))/((M_F2.minus(M_I)).normF())));
distanceToNearPoint=M_I.minus(M_F1).normF();
distanceToFarPoint=M_I.minus(M_F2).normF();
m_outputNodeFile=Config.getBoundedNodes();
m_outputElementFile=Config.getUniqueBoundedElements().concat("position"+Integer.toString(position)+"/0");
}
public ComputeBoundingBox(double[] inspectorBFR, double[] nearPlane, double[] farPlane, double viewAngle, int truePosition, int observedPosition, int sampleNum,int runCount) {
m_inspectorBFR=inspectorBFR;
m_nearPlane=nearPlane;
m_farPlane=farPlane;
m_viewAngle=viewAngle;
M_I=new Matrix(new double[][] {m_inspectorBFR});
M_F1=new Matrix(new double[][] {m_nearPlane});
M_F2=new Matrix(new double[][] {m_farPlane});
planeNormal=new Matrix(1,3);
for(int i=0;i<3;i++)
planeNormal.set(0,i,((M_F2.minus(M_I).get(0,i))/((M_F2.minus(M_I)).normF())));
distanceToNearPoint=M_I.minus(M_F1).normF();
distanceToFarPoint=M_I.minus(M_F2).normF();
m_outputNodeFile=Config.getBoundedNodes().concat(Integer.toString(runCount)+"/position"+Integer.toString(truePosition)+"/observedPos"+Integer.toString(observedPosition)+"/"+Integer.toString(sampleNum));
m_outputElementFile=Config.getUniqueBoundedElements().concat(Integer.toString(runCount)+"/position"+Integer.toString(truePosition)+"/observedPos"+Integer.toString(observedPosition)+"/"+Integer.toString(sampleNum));
}
@Override
public void captureNodesInBox() throws IOException {
int element_id;
//hashElements was used to store number of nodes in context for each element
//Hashtable<Integer, Integer> hashElements=new Hashtable<Integer, Integer>();
//We want to just store the number of elemnets in context
Hashtable<Integer,Boolean> contextualElements=new Hashtable<Integer,Boolean>();
BufferedWriter out_unique_elements=new BufferedWriter(new FileWriter(m_outputElementFile));
if(m_inspectorBFR[2] > (Config.getDeckZPosition()))
nodesList=elementsWithNodesAboveDeck;
else
nodesList=elementsWithNodesBelowDeck;
for(int i=0;i<nodesList.size();i++)
{
element_id=nodesList.get(i).getElementId();
m_queryPoint=nodesList.get(i).getCoordinates();
//This snippet was used to store elements with number of nodes in context
/*if(hashElements.containsKey(element_id) || checkContainment())
{
if(hashElements.containsKey(element_id))
hashElements.put(element_id, (hashElements.get(element_id)+1));
else
hashElements.put(element_id, 1);
}*/
//Just store the elements in context
if(contextualElements.containsKey(element_id))
continue;
else if(checkContainment())
{ contextualElements.put(element_id, true);
out_unique_elements.write(element_id+"\n");
}
}
//Loop to write compute fraction of nodes for each contextual element and write it to file
/*
for(Enumeration<Integer> e=hashElements.keys();e.hasMoreElements();){
Integer tempKey=e.nextElement();
out_unique_elements.write(tempKey+" "+hashElements.get(tempKey)+" "+(double)((double)hashElements.get(tempKey)/(double)elementNodeCount.get(tempKey))+"\n");
}
*/
out_unique_elements.close();
}
@Override
public boolean checkContainment() {
//check for containment of query_point in the bounding box
double phi, phiAngle;
//All points are now in BFR
Matrix M_P=new Matrix(new double[][] {m_queryPoint});
//This condition checks for the query node being in front of the inspector plane (plane that is defined by the inspectors position and line of sight)
if((M_P.minus(M_I).get(0,0)*planeNormal.get(0,0)+M_P.minus(M_I).get(0,1)*planeNormal.get(0,1)+M_P.minus(M_I).get(0,2)*planeNormal.get(0,2)) > 0)
{
phi=(((M_P.minus(M_I).get(0,0))*(M_F1.minus(M_I).get(0,0))) + ((M_P.minus(M_I).get(0,1))*(M_F1.minus(M_I).get(0,1))) + ((M_P.minus(M_I).get(0,2))*(M_F1.minus(M_I).get(0,2))))/((M_P.minus(M_I)).normF()*distanceToNearPoint);
phiAngle=Math.acos(phi);
//Potentially superfluous condition!!!
if(phiAngle>(Math.PI/2))
phiAngle=Math.PI-phiAngle;
double cosOfPhi=Math.cos(phiAngle);
if(phiAngle<=m_viewAngle && distanceToNearPoint<=(((M_I.minus(M_P)).normF())*cosOfPhi) && ((M_I.minus(M_P).normF())*cosOfPhi)<=distanceToFarPoint)
return true;
else
return false;
}
else
return false;
}
}
| athuls/umich-panther | senstore/contextInterpretation/codes_MCMC/FieldData/src/approximateApproach/ComputeBoundingBox.java | Java | gpl-2.0 | 8,690 |
package com.cloupia.feature.purestorage.reports;
import org.apache.log4j.Logger;
import com.cloupia.feature.purestorage.PureUtils;
import com.cloupia.feature.purestorage.accounts.FlashArrayAccount;
import com.cloupia.feature.purestorage.accounts.HostGroupInventoryConfig;
import com.cloupia.feature.purestorage.accounts.HostInventoryConfig;
import com.cloupia.model.cIM.Group;
import com.cloupia.model.cIM.ReportContext;
import com.cloupia.model.cIM.TabularReport;
import com.cloupia.service.cIM.inframgr.TabularReportGeneratorIf;
import com.cloupia.service.cIM.inframgr.reportengine.ReportRegistryEntry;
import com.cloupia.service.cIM.inframgr.reports.TabularReportInternalModel;
import com.purestorage.rest.PureRestClient;
import com.purestorage.rest.host.PureHost;
import com.purestorage.rest.host.PureHostConnection;
import com.purestorage.rest.hostgroup.PureHostGroup;
import com.purestorage.rest.hostgroup.PureHostGroupConnection;
import com.purestorage.rest.PureRestClient;
import java.util.List;
public class HostGroupReportImpl implements TabularReportGeneratorIf
{
static Logger logger = Logger.getLogger(HostGroupReportImpl.class);
@Override
public TabularReport getTabularReportReport(ReportRegistryEntry entry, ReportContext context) throws Exception
{
logger.info("Entering HostGroupReportImpl.getTabularReportReport" );
logger.info("ReportContext.getId()=" + context.getId());
String accountName;
if(context.getId().contains(";")) //Checking the Context
{
String[] parts = context.getId().split(";");
accountName = parts[0];
}
else
{
accountName = context.getId();
}
TabularReport report = new TabularReport();
report.setGeneratedTime(System.currentTimeMillis());
report.setReportName(entry.getReportLabel());
report.setContext(context);
TabularReportInternalModel model = new TabularReportInternalModel();
model.addTextColumn("Id", "Id",true);
model.addTextColumn("Account Name", "Account Name");
model.addTextColumn("Name", "Host Group Name");
model.addNumberColumn("Hosts", "No. of Hosts");
model.addNumberColumn("Volumes", "Number of volumes", false);
model.addTextColumn("Connected Volumes", "Connected Volumes");
model.addDoubleColumn("Provisioned(GB)", "Provisioned size of attached volumes");
model.addDoubleColumn("Volumes(Capacity)", "Size of volumes", false);
model.addDoubleColumn("Reduction", "Reduction", false);
model.completedHeader();
if (accountName != null && accountName.length() > 0)
{
/*FlashArrayAccount acc = FlashArrayAccount.getFlashArrayCredential(accountName);
PureRestClient CLIENT = PureUtils.ConstructPureRestClient(acc);
List<PureHostGroup> hostgroups = CLIENT.hostGroups().list();
for (PureHostGroup hostgroup: hostgroups)*/
List<HostGroupInventoryConfig> hostgroups= PureUtils.getAllPureHostGroup();
for (HostGroupInventoryConfig hostgroup: hostgroups)
{
if (accountName.equalsIgnoreCase(hostgroup.getAccountName()))
{
model.addTextValue(hostgroup.getId());
//model.addTextValue(accountName+"@"+hostgroup.getName());
model.addTextValue(accountName);
model.addTextValue(hostgroup.getHostGroupName()); // Name
model.addNumberValue(hostgroup.getHosts()); //No. of Hosts
model.addNumberValue(hostgroup.getVolumes());
/* List<PureHostGroupConnection> connections = CLIENT.hostGroups().getConnections(hostgroup.getName());
// private and shared connections cannot overlap (i.e. same vol cannot be part of both shared and private connections)
// Number of volumes
long totalSize = 0;
String connVolumes="";
for (PureHostGroupConnection connection: connections)
{
totalSize += CLIENT.volumes().get(connection.getVolumeName()).getSize();
if(connVolumes=="")
{
connVolumes=connection.getVolumeName();
}
else
{
connVolumes=connVolumes+","+connection.getVolumeName();
}
}*/
model.addTextValue(hostgroup.getConnectedVolumes());
model.addDoubleValue(hostgroup.getProvisionedSize()); // Provisioned size of attached volumes
model.addDoubleValue(hostgroup.getVolumeCapacity()); // Provisioned size of attached volumes
model.addDoubleValue(hostgroup.getReduction()); // Provisioned size of attached volumes
model.completedRow();
}
}
}
model.updateReport(report);
return report;
}
} | maheshonecloud/Testrepo | UCSD 6.5 Connector/PureStorageUCSDirectorAdapter_6.5/src/com/cloupia/feature/purestorage/reports/HostGroupReportImpl.java | Java | gpl-2.0 | 5,182 |
package edu.wayne.cs.severe.redress2.entity.refactoring.formulas.im;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import edu.wayne.cs.severe.redress2.controller.MetricUtils;
import edu.wayne.cs.severe.redress2.controller.metric.CodeMetric;
import edu.wayne.cs.severe.redress2.controller.metric.LCOM5Metric;
import edu.wayne.cs.severe.redress2.entity.TypeDeclaration;
import edu.wayne.cs.severe.redress2.entity.refactoring.RefactoringOperation;
public class LCOM5InlineMethodPF extends InlineMethodPredFormua {
@Override
public HashMap<String, Double> predictMetrVal(RefactoringOperation ref,
LinkedHashMap<String, LinkedHashMap<String, Double>> prevMetrics)
throws Exception {
TypeDeclaration srcCls = getSourceClass(ref);
HashMap<String, Double> predMetrs = new HashMap<String, Double>();
predMetrs.put(srcCls.getQualifiedName(), getValLCOM5(srcCls));
return predMetrs;
}
private Double getValLCOM5(TypeDeclaration typeDcl) throws Exception {
if (typeDcl.getCompUnit() == null) {
return 0.0;
}
File compUnitFile = typeDcl.getCompUnit().getSrcFile();
HashSet<String> fields = MetricUtils.getFields(typeDcl);
double numFieldUsage = 0.0;
for (String field : fields) {
int numField = MetricUtils.getNumberOfMethodsUsingString(typeDcl,
field);
numFieldUsage += numField;
}
double numFields = fields.size();
Double numMethods = MetricUtils.getNumberOfMethods(typeDcl,
compUnitFile) - 1;
double metric = (numMethods == 1 || numFields == 0) ? 0
: ((numFieldUsage) / numFields - numMethods) / (1 - numMethods);
return metric;
}
@Override
public CodeMetric getMetric() {
return new LCOM5Metric();
}
}
| BIORIMP/biorimp | BIO-RIMP/src/main/java/edu/wayne/cs/severe/redress2/entity/refactoring/formulas/im/LCOM5InlineMethodPF.java | Java | gpl-2.0 | 1,798 |
package controller;
import entity.EtatDeLieu;
import controller.util.JsfUtil;
import controller.util.PaginationHelper;
import session.EtatDeLieuFacade;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
@ManagedBean(name = "etatDeLieuController")
@SessionScoped
public class EtatDeLieuController implements Serializable {
private EtatDeLieu current;
private DataModel items = null;
@EJB
private session.EtatDeLieuFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public EtatDeLieuController() {
}
public EtatDeLieu getSelected() {
if (current == null) {
current = new EtatDeLieu();
selectedItemIndex = -1;
}
return current;
}
private EtatDeLieuFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
@Override
public int getItemsCount() {
return getFacade().count();
}
@Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (EtatDeLieu) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new EtatDeLieu();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EtatDeLieuCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (EtatDeLieu) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EtatDeLieuUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (EtatDeLieu) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getFacade().remove(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EtatDeLieuDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getFacade().count();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
}
@FacesConverter(forClass = EtatDeLieu.class)
public static class EtatDeLieuControllerConverter implements Converter {
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
EtatDeLieuController controller = (EtatDeLieuController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "etatDeLieuController");
return controller.ejbFacade.find(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof EtatDeLieu) {
EtatDeLieu o = (EtatDeLieu) object;
return getStringKey(o.getIdEtatDeLieu());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + EtatDeLieu.class.getName());
}
}
}
}
| gdevsign/pfrc | AppWebGBIE/src/java/controller/EtatDeLieuController.java | Java | gpl-2.0 | 7,138 |
package com.ctreber.acearth;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import com.ctreber.acearth.util.Point3D;
import com.ctreber.acearth.util.Polygon;
/**
* The map data file is a big array of short (16-bit) ints, as follows: - it is
* a sequence of closed curves - the first value in a curve is the number of
* points in the curve - the second value in a curve indicates land/water (1 or
* -1, respectively) - this is followed by an [x,y,z] triple that indicates a
* point on the unit sphere (each of x, y, and z has been scaled by 30000),
* where the x axis points "to the right" (towards 0 N 90 E), the y axis points
* "up" (towards the north pole), and the z axis points "out of the screen"
* (towards 0 N 0 E). this is the starting point of the curve. - this is
* followed by (one less than the number of points in the curve) triples
* [dx,dy,dz]; the [x,y,z] triple for each successive point in the curve is
* obtained by adding [dx,dy,dz] onto the previous [x,y,z] values. - the curves
* are [must be!] non-self-intersecting and traced in a counter-clockwise
* direction
*
* the curves are sampled at a (roughly) a 20 mile resolution.
*
* <p>
* © 2002 Christian Treber, [email protected]
*
* @author Christian Treber, [email protected]
*
*/
public class MapDataReader {
/** Point value scale (devide value by this number). */
private static final double MAP_DATA_SCALE = 30000.0;
private static List fData;
private static List fPolygons;
private static int fIndex;
/**
* <p>
* Read map data.
*
* @param pFileName
* Map data file name.
* @return Array of map polygons.
* @throws IOException
*/
public static Polygon[] readMapData() throws IOException {
final List lines = new MapData().getLines();
fData = new ArrayList();
for (Iterator it = lines.iterator(); it.hasNext(); ) {
String lLine = (String) it.next();
if (lLine.indexOf("/*") != -1) {
// Filter out comments.
continue;
}
StringTokenizer lST = new StringTokenizer(lLine, ", ");
while (lST.hasMoreTokens()) {
String lToken = lST.nextToken();
final Integer lValue = new Integer(lToken);
fData.add(lValue);
}
}
fPolygons = new ArrayList();
fIndex = 0;
while (getValue(fIndex) != 0) {
processCurve();
}
return (Polygon[]) fPolygons.toArray(new Polygon[0]);
}
private static void processCurve() {
final int lNPoint = getValue(fIndex++);
final int lType = getValue(fIndex++);
final Point3D[] lPoints = new Point3D[lNPoint];
final Point3D lPoint3D = new Point3D(getValue(fIndex++) / MAP_DATA_SCALE, getValue(fIndex++) / MAP_DATA_SCALE,
getValue(fIndex++) / MAP_DATA_SCALE);
lPoints[0] = lPoint3D;
for (int i = 1; i < lNPoint; i++) {
lPoints[i] = new Point3D(lPoints[i - 1].getX() + getValue(fIndex++) / MAP_DATA_SCALE, lPoints[i - 1].getY()
+ getValue(fIndex++) / MAP_DATA_SCALE, lPoints[i - 1].getZ() + getValue(fIndex++) / MAP_DATA_SCALE);
}
final Polygon lPolygon = new Polygon(lType, lPoints);
fPolygons.add(lPolygon);
}
/**
* <p>
* Get value of raw data at specified point.
*
* @param pIndex
* Index of value.
* @return Value of raw data at specified point.
*/
private static int getValue(int pIndex) {
return ((Integer) fData.get(pIndex)).intValue();
}
}
| jensnerche/plantuml | src/com/ctreber/acearth/MapDataReader.java | Java | gpl-2.0 | 3,420 |
/********************************
* 프로젝트 : gargoyle-encryp
* 패키지 : com.kyj.utils
* 작성일 : 2017. 11. 4.
* 작성자 : KYJ
*******************************/
package com.kyj.utils;
/**
* @author KYJ
*
*/
public interface IEncrypConvert {
/**
* 암호화
*
* @작성자 : KYJ
* @작성일 : 2017. 11. 4.
* @param message
* @return
*/
public byte[] encryp(byte[] message) throws Exception;
/**
* 복호화
*
* @작성자 : KYJ
* @작성일 : 2017. 11. 4.
* @param message
* @return
*/
public byte[] decryp(byte[] message) throws Exception;
}
| callakrsos/Gargoyle | gargoyle-encryp/src/main/java/com/kyj/utils/IEncrypConvert.java | Java | gpl-2.0 | 606 |
/*
* $Id$
*
* Authors:
* Jeff Buchbinder <[email protected]>
*
* FreeMED Electronic Medical Record and Practice Management System
* Copyright (C) 1999-2012 FreeMED Software Foundation
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.freemedsoftware.gwt.client.widget;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.freemedsoftware.gwt.client.CurrentState;
import org.freemedsoftware.gwt.client.JsonUtil;
import org.freemedsoftware.gwt.client.PatientEntryScreenInterface;
import org.freemedsoftware.gwt.client.SystemEvent;
import org.freemedsoftware.gwt.client.Util;
import org.freemedsoftware.gwt.client.WidgetInterface;
import org.freemedsoftware.gwt.client.Api.ModuleInterfaceAsync;
import org.freemedsoftware.gwt.client.Api.PatientInterfaceAsync;
import org.freemedsoftware.gwt.client.Util.ProgramMode;
import org.freemedsoftware.gwt.client.screen.PatientScreen;
import org.freemedsoftware.gwt.client.screen.patient.EmrView;
import org.freemedsoftware.gwt.client.screen.patient.LetterEntry;
import org.freemedsoftware.gwt.client.screen.patient.PatientCorrespondenceEntry;
import org.freemedsoftware.gwt.client.screen.patient.PatientIdEntry;
import org.freemedsoftware.gwt.client.screen.patient.ProgressNoteEntry;
import org.freemedsoftware.gwt.client.screen.patient.ReferralEntry;
import org.freemedsoftware.gwt.client.widget.CustomTable.TableWidgetColumnSetInterface;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style.Cursor;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TabBar;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import static org.freemedsoftware.gwt.client.i18n.I18nUtil._;
public class PatientProblemList extends WidgetInterface implements
SystemEvent.Handler {
public final static String moduleName = PatientScreen.moduleName;
public class ActionBar extends Composite implements ClickHandler {
protected final String IMAGE_ANNOTATE = "resources/images/add1.16x16.png";
protected final String IMAGE_DELETE = "resources/images/summary_delete.16x16.png";
protected final String IMAGE_MODIFY = "resources/images/summary_modify.16x16.png";
protected final String IMAGE_PRINT = "resources/images/ico.printer.16x16.png";
protected final String IMAGE_VIEW = "resources/images/summary_view.16x16.png";
protected Integer internalId = 0;
protected HashMap<String, String> data = null;
protected Image annotateImage = null, deleteImage = null,
modifyImage = null, unlockedImage = null, lockedImage = null,
printImage = null, viewImage = null;
protected CheckBox cb = null;
public ActionBar(HashMap<String, String> item) {
// Pull ID for future
internalId = Integer.parseInt(item.get("id"));
data = item;
boolean locked = (Integer.parseInt(data.get("locked")) > 0);
HorizontalPanel hPanel = new HorizontalPanel();
initWidget(hPanel);
// Multiple select box
cb = new CheckBox();
cb.addClickHandler(this);
hPanel.add(cb);
// Build icons
annotateImage = new Image(IMAGE_ANNOTATE);
annotateImage.setTitle(_("Add Annotation"));
annotateImage.addClickHandler(this);
annotateImage.getElement().getStyle().setCursor(Cursor.POINTER);
hPanel.add(annotateImage);
printImage = new Image(IMAGE_PRINT);
printImage.setTitle(_("Print"));
printImage.addClickHandler(this);
printImage.getElement().getStyle().setCursor(Cursor.POINTER);
hPanel.add(printImage);
viewImage = new Image(IMAGE_VIEW);
viewImage.setTitle(_("View"));
viewImage.addClickHandler(this);
viewImage.getElement().getStyle().setCursor(Cursor.POINTER);
hPanel.add(viewImage);
// Display all unlocked things
if (!locked) {
deleteImage = new Image(IMAGE_DELETE);
deleteImage.setTitle(_("Remove"));
deleteImage.addClickHandler(this);
deleteImage.getElement().getStyle().setCursor(Cursor.POINTER);
hPanel.add(deleteImage);
modifyImage = new Image(IMAGE_MODIFY);
modifyImage.setTitle(_("Edit"));
modifyImage.addClickHandler(this);
modifyImage.getElement().getStyle().setCursor(Cursor.POINTER);
hPanel.add(modifyImage);
} else {
// Display all actions for locked items
}
}
public void setChecked(boolean s) {
cb.setValue(s);
}
public void onClick(ClickEvent evt) {
Widget sender = (Widget) evt.getSource();
if (sender == cb) {
// Handle clicking
JsonUtil.debug("current status = "
+ (cb.getValue() ? "checked" : "not"));
// Set in dictionary
setSelected(internalId, cb.getValue());
// Adjust all others to have same status as this.
try {
Iterator<ActionBar> iter = Arrays.asList(
actionBarMap.get(internalId)).iterator();
while (iter.hasNext()) {
ActionBar cur = iter.next();
if (cur != this) {
cur.setChecked(cb.getValue());
}
}
} catch (Exception ex) {
JsonUtil.debug(ex.toString());
}
} else if (sender == annotateImage) {
CreateAnnotationPopup p = new CreateAnnotationPopup(data);
p.center();
} else if (sender == viewImage) {
EmrView emrView = new EmrView(data.get("module_namespace"),
Integer.parseInt(data.get("oid")));
Util.spawnTabPatient(_("View"), emrView, patientScreen);
} else if (sender == printImage) {
EmrPrintDialog d = new EmrPrintDialog();
d.setItems(new Integer[] { Integer.parseInt(data.get("id")) });
d.center();
} else if (sender == deleteImage) {
if (Window
.confirm(_("Are you sure you want to delete this item?"))) {
deleteItem(internalId, data);
}
} else if (sender == modifyImage) {
modifyItem(internalId, data);
} else {
// Do nothing
}
}
}
public class CreateAnnotationPopup extends DialogBox implements
ClickHandler {
protected HashMap<String, String> data = null;
protected TextArea textArea = null;
public CreateAnnotationPopup(HashMap<String, String> rec) {
super(true);
setAnimationEnabled(true);
// Save copy of data
data = rec;
final VerticalPanel verticalPanel = new VerticalPanel();
setStylePrimaryName("freemed-CreateAnnotationPopup");
setWidget(verticalPanel);
textArea = new TextArea();
textArea.setSize("300px", "300px");
verticalPanel.add(textArea);
PushButton submitButton = new PushButton(_("Add Annotation"));
submitButton.addClickHandler(this);
submitButton.setText(_("Add Annotation"));
verticalPanel.add(submitButton);
verticalPanel.setCellHorizontalAlignment(submitButton,
HasHorizontalAlignment.ALIGN_CENTER);
}
public void onClick(ClickEvent evt) {
Window.alert("STUB: need to handle annotation add");
hide();
}
}
protected Integer patientId = new Integer(0);
protected TabPanel tabPanel = null;
protected HashMap<String, CustomTable> tables = new HashMap<String, CustomTable>();
protected HashMap<String, Label> messages = new HashMap<String, Label>();
protected HashMap<String, String>[] dataStore = null;
protected HashMap<Integer, ActionBar[]> actionBarMap = new HashMap<Integer, ActionBar[]>();
protected List<Integer> selected = new ArrayList<Integer>();
protected int maximumRows = 10;
protected PatientScreen patientScreen = null;
public PatientProblemList() {
super(moduleName);
SimplePanel panel = new SimplePanel();
tabPanel = new TabPanel();
tabPanel.setSize("100%", "100%");
tabPanel.setVisible(true);
panel.setWidget(tabPanel);
initWidget(panel);
TabBar tbar = tabPanel.getTabBar();
Element tabBarFirstChild = tbar.getElement().getFirstChildElement()
.getFirstChildElement().getFirstChildElement();
tabBarFirstChild.setAttribute("width", "100%");
tabBarFirstChild.setInnerHTML("HEALTH SUMMARY");
tabBarFirstChild.setClassName("label_bold");
// All
Image allImage = new Image("resources/images/chart_full.16x16.png");
allImage.setTitle(_("All"));
createSummaryTable(allImage, "all");
// Progress Notes
Image notesImage = new Image("resources/images/chart.16x16.png");
notesImage.setTitle(_("Progress Notes"));
createSummaryTable(notesImage, "pnotes");
// Letters
Image lettersImage = new Image(
"resources/images/summary_envelope.16x16.png");
lettersImage.setTitle(_("Letters"));
createSummaryTable(lettersImage, "letters,patletter");
tabPanel.selectTab(0);
// Register on the event bus
CurrentState.getEventBus().addHandler(SystemEvent.TYPE, this);
}
public void modifyItem(Integer item, HashMap<String, String> data) {
PatientEntryScreenInterface i = resolvePatientScreen(data.get("module"));
i.setInternalId(Integer.parseInt(data.get("oid")));
Util.spawnTabPatient("Modify", i, patientScreen);
}
public void deleteItem(Integer item, HashMap<String, String> data) {
final String module = data.get("module");
final Integer internalId = Integer.parseInt(data.get("oid"));
if (Util.getProgramMode() == ProgramMode.STUBBED) {
} else if (Util.getProgramMode() == ProgramMode.JSONRPC) {
String[] params = { module, JsonUtil.jsonify(internalId) };
RequestBuilder builder = new RequestBuilder(
RequestBuilder.POST,
URL
.encode(Util
.getJsonRequest(
"org.freemedsoftware.api.ModuleInterface.ModuleDeleteMethod",
params)));
try {
builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable ex) {
JsonUtil.debug(ex.toString());
CurrentState.getToaster()
.addItem(module, _("Unable to remove entry."),
Toaster.TOASTER_ERROR);
}
public void onResponseReceived(Request request,
Response response) {
JsonUtil.debug("onResponseReceived");
if (Util.checkValidSessionResponse(response.getText())) {
if (200 == response.getStatusCode()) {
JsonUtil.debug(response.getText());
Boolean r = (Boolean) JsonUtil.shoehornJson(
JSONParser.parseStrict(response.getText()),
"Boolean");
if (r) {
loadData();
CurrentState.getToaster().addItem(module,
_("Removed item."),
Toaster.TOASTER_INFO);
} else {
CurrentState.getToaster().addItem(module,
_("Unable to remove entry."),
Toaster.TOASTER_ERROR);
}
} else {
JsonUtil.debug(response.toString());
CurrentState.getToaster().addItem(module,
_("Unable to remove entry."),
Toaster.TOASTER_ERROR);
}
}
}
});
} catch (RequestException e) {
JsonUtil.debug(e.toString());
CurrentState.getToaster().addItem(module,
_("Unable to remove entry."), Toaster.TOASTER_ERROR);
}
} else {
ModuleInterfaceAsync service = null;
try {
service = (ModuleInterfaceAsync) Util
.getProxy("org.freemedsoftware.gwt.client.Api.ModuleInterface");
} catch (Exception e) {
GWT.log("Failed to get proxy for ModuleInterface", e);
}
service.ModuleDeleteMethod(module, internalId,
new AsyncCallback<Integer>() {
@Override
public void onFailure(Throwable caught) {
JsonUtil.debug(caught.toString());
CurrentState.getToaster().addItem(module,
_("Unable to remove entry."),
Toaster.TOASTER_ERROR);
}
@Override
public void onSuccess(Integer result) {
loadData();
CurrentState.getToaster().addItem(module,
_("Removed item."), Toaster.TOASTER_INFO);
}
});
}
}
public void setPatientId(Integer id) {
patientId = id;
// Call initial data load, as patient id is set
loadData();
}
public void setPatientScreen(PatientScreen ps) {
patientScreen = ps;
}
public void addToActionBarMap(Integer key, ActionBar ab) {
ActionBar[] x = actionBarMap.get(key);
if (x == null) {
// Create new
actionBarMap.put(key, new ActionBar[] { ab });
} else {
// Add to map
List<ActionBar> l = new ArrayList<ActionBar>();
for (int iter = 0; iter < x.length; iter++) {
l.add(x[iter]);
}
l.add(ab);
actionBarMap.put(key, (ActionBar[]) l.toArray(new ActionBar[0]));
}
}
public void setMaximumRows(int maxRows) {
maximumRows = maxRows;
Iterator<String> iter = tables.keySet().iterator();
while (iter.hasNext()) {
String k = iter.next();
tables.get(k).setMaximumRows(maximumRows);
}
}
private void createSummaryTable(Widget tab, String criteria) {
CustomTable t = new CustomTable();
t.setWidth("100%");
if (canModify) {
t
.setTableWidgetColumnSetInterface(new TableWidgetColumnSetInterface() {
public Widget setColumn(String columnName,
HashMap<String, String> data) {
// Render only action column, otherwise skip
// renderer
if (columnName.compareToIgnoreCase("action") != 0) {
return null;
}
ActionBar ab = new ActionBar(data);
// Add to mapping, so we can control lots of these
// things
addToActionBarMap(Integer.parseInt(data.get("id")),
ab);
// Push value back to table
return ab;
}
});
}
t.setAllowSelection(false);
t.setMaximumRows(maximumRows);
t.addColumn(_("Date"), "date_mdy");
t.addColumn(_("Module"), "type");
t.addColumn(_("Summary"), "summary");
if (canModify)
t.addColumn(_("Action"), "action");
VerticalPanel vPanel = new VerticalPanel();
vPanel.add(t);
// Label m = new Label();
// m.setText("No Item Found!!.");
// m.setStylePrimaryName("label_italic");
// m.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
// m.setVisible(false);
// vPanel.add(m);
tabPanel.add(vPanel, tab);
tables.put(criteria, t);
// messages.put(criteria, m);
}
protected PatientEntryScreenInterface resolvePatientScreen(String moduleName) {
PatientEntryScreenInterface pSI = null;
if (moduleName.toLowerCase() == "pnotes") {
pSI = new ProgressNoteEntry();
}
if (moduleName.toLowerCase() == "letters") {
pSI = new LetterEntry();
}
if (moduleName.toLowerCase() == "patletter") {
pSI = new PatientCorrespondenceEntry();
}
if (moduleName.toLowerCase() == "patient_ids") {
pSI = new PatientIdEntry();
}
if (moduleName.toLowerCase() == "referrals") {
pSI = new ReferralEntry();
}
if (pSI != null) {
pSI.setPatientId(patientId);
pSI.assignPatientScreen(patientScreen);
}
return pSI;
}
@SuppressWarnings("unchecked")
public void loadData() {
// Clear mappings during populate
selected.clear();
actionBarMap.clear();
if (patientId.intValue() == 0) {
JsonUtil
.debug("ERROR: patientId not defined when loadData called for PatientProblemList");
}
if (Util.getProgramMode() == ProgramMode.STUBBED) {
List<HashMap<String, String>> a = new ArrayList<HashMap<String, String>>();
{
HashMap<String, String> item = new HashMap<String, String>();
item.put("stamp", "2008-01-01");
item.put("type", "test");
item.put("summary", "Test item 1");
item.put("module", "ProgressNotes");
a.add(item);
}
{
HashMap<String, String> item = new HashMap<String, String>();
item.put("stamp", "2008-01-02");
item.put("type", "test");
item.put("summary", "Test item 2");
item.put("module", "ProgressNotes");
a.add(item);
}
{
HashMap<String, String> item = new HashMap<String, String>();
item.put("stamp", "2008-01-02");
item.put("type", "test");
item.put("summary", "Test item 3");
item.put("module", "Letters");
a.add(item);
}
{
HashMap<String, String> item = new HashMap<String, String>();
item.put("stamp", "2008-01-03");
item.put("type", "test");
item.put("summary", "Test item 4");
item.put("module", "Letters");
a.add(item);
}
dataStore = (HashMap<String, String>[]) a
.toArray(new HashMap<?, ?>[0]);
populateData(dataStore);
} else if (Util.getProgramMode() == ProgramMode.JSONRPC) {
String[] params = { patientId.toString() };
RequestBuilder builder = new RequestBuilder(
RequestBuilder.POST,
URL
.encode(Util
.getJsonRequest(
"org.freemedsoftware.api.PatientInterface.EmrAttachmentsByPatient",
params)));
try {
builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable ex) {
Window.alert(ex.toString());
}
public void onResponseReceived(Request request,
Response response) {
JsonUtil.debug("onResponseReceived");
if (Util.checkValidSessionResponse(response.getText())) {
if (200 == response.getStatusCode()) {
JsonUtil.debug(response.getText());
HashMap<String, String>[] r = (HashMap<String, String>[]) JsonUtil
.shoehornJson(JSONParser.parseStrict(response
.getText()),
"HashMap<String,String>[]");
if (r != null) {
JsonUtil
.debug("PatientProblemList... r.length = "
+ new Integer(r.length)
.toString());
dataStore = r;
populateData(dataStore);
}
} else {
Window.alert(response.toString());
}
}
}
});
} catch (RequestException e) {
Window.alert(e.toString());
}
} else {
PatientInterfaceAsync service = null;
try {
service = (PatientInterfaceAsync) Util
.getProxy("org.freemedsoftware.gwt.client.Api.PatientInterface");
} catch (Exception e) {
GWT.log("Failed to get proxy for PatientInterface", e);
}
service.EmrAttachmentsByPatient(patientId,
new AsyncCallback<HashMap<String, String>[]>() {
public void onSuccess(HashMap<String, String>[] r) {
dataStore = r;
populateData(dataStore);
}
public void onFailure(Throwable t) {
GWT.log("Exception", t);
}
});
}
}
/**
* Check to see if a string is in a stack of pipe separated values.
*
* @param needle
* @param haystack
* @return
*/
protected boolean inSet(String needle, String haystack) {
// Handle incidence of needle == haystack
if (needle.equalsIgnoreCase(haystack)) {
return true;
}
String[] stack = haystack.split(",");
for (int iter = 0; iter < stack.length; iter++) {
if (needle.trim().equalsIgnoreCase(stack[iter].trim())) {
return true;
}
}
return false;
}
/**
* Set an item as being selected.
*
* @param key
* @param isSet
*/
protected void setSelected(Integer key, boolean isSet) {
try {
if (isSet) {
selected.add(key);
} else {
selected.remove(key);
}
} catch (Exception ex) {
}
}
/**
* Internal method to populate all sub tables.
*
* @param data
*/
@SuppressWarnings("unchecked")
protected void populateData(HashMap<String, String>[] data) {
JsonUtil.debug("PatientProblemList.populateData");
Iterator<String> tIter = tables.keySet().iterator();
while (tIter.hasNext()) {
String k = tIter.next();
JsonUtil.debug("Populating table " + k);
// Clear table contents
try {
tables.get(k).clearData();
} catch (Exception ex) {
}
// Depending on criteria, etc, choose what do to.
String crit = k;
// JsonUtil.debug(" --> got criteria = " + crit);
// boolean star = tables.get(k).getStarred();
List<HashMap<String, String>> res = new ArrayList<HashMap<String, String>>();
List<HashMap<String, String>> d = Arrays.asList(data);
Iterator<HashMap<String, String>> iter = d.iterator();
while (iter.hasNext()) {
HashMap<String, String> rec = iter.next();
// TODO: handle star
if (crit == null || crit.length() == 0
|| crit.contentEquals("all")) {
// Don't handle criteria at all, effectively passthru
// JsonUtil.debug("-- pass through, no criteria");
} else {
// Handle criteria
if (!inSet(rec.get("module"), crit)) {
JsonUtil.debug(rec.get("module") + " not include "
+ crit);
} else {
JsonUtil.debug(rec.get("module") + " INCLUDE " + crit);
}
if (!inSet(rec.get("module"), crit)) {
continue;
}
}
// If it passes all criteria, add to the stack for the result.
res.add(rec);
}
if (res.size() > 0) {
try {
messages.get(crit).setVisible(false);
} catch (Exception ex) {
JsonUtil.debug(ex.toString());
}
JsonUtil.debug("Populating table " + k + " with "
+ new Integer(res.size()).toString() + " entries");
CustomTable thisTable = tables.get(k);
HashMap<String, String>[] thisData = (HashMap<String, String>[]) res
.toArray(new HashMap<?, ?>[0]);
thisTable.loadData(thisData);
JsonUtil.debug("Completed populating table " + k);
} else {
messages.get(crit).setVisible(true);
JsonUtil.debug("Could not populate null results into table");
}
}
}
@Override
public void onSystemEvent(SystemEvent e) {
if (e.getPatient() == patientId) {
// if (e.getSourceModule() == "vitals") {
loadData();
// }
}
}
}
| freemed/freemed | ui/gwt/src/main/java/org/freemedsoftware/gwt/client/widget/PatientProblemList.java | Java | gpl-2.0 | 22,755 |
package edu.stanford.nlp.pipeline;
import java.io.Reader;
import java.io.StringReader;
import java.util.*;
import edu.stanford.nlp.ling.CoreAnnotation;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.process.*;
import edu.stanford.nlp.international.spanish.process.SpanishTokenizer;
import edu.stanford.nlp.international.french.process.FrenchTokenizer;
import edu.stanford.nlp.util.Generics;
import edu.stanford.nlp.util.PropertiesUtils;
import edu.stanford.nlp.util.logging.Redwood;
/**
* This class will PTB tokenize the input. It assumes that the original
* String is under the CoreAnnotations.TextAnnotation field
* and it will add the output from the
* InvertiblePTBTokenizer ({@code List<CoreLabel>}) under
* CoreAnnotation.TokensAnnotation.
*
* @author Jenny Finkel
* @author Christopher Manning
* @author Ishita Prasad
*/
public class TokenizerAnnotator implements Annotator {
/** A logger for this class */
private static final Redwood.RedwoodChannels log = Redwood.channels(TokenizerAnnotator.class);
/**
* Enum to identify the different TokenizerTypes. To add a new
* TokenizerType, add it to the list with a default options string
* and add a clause in getTokenizerType to identify it.
*/
public enum TokenizerType {
Unspecified(null, null, "invertible,ptb3Escaping=true"),
Arabic ("ar", null, ""),
Chinese ("zh", null, ""),
Spanish ("es", "SpanishTokenizer", "invertible,ptb3Escaping=true,splitAll=true"),
English ("en", "PTBTokenizer", "invertible,ptb3Escaping=true"),
German ("de", null, "invertible,ptb3Escaping=true"),
French ("fr", "FrenchTokenizer", ""),
Whitespace (null, "WhitespaceTokenizer", "");
private final String abbreviation;
private final String className;
private final String defaultOptions;
TokenizerType(String abbreviation, String className, String defaultOptions) {
this.abbreviation = abbreviation;
this.className = className;
this.defaultOptions = defaultOptions;
}
public String getDefaultOptions() {
return defaultOptions;
}
private static final Map<String, TokenizerType> nameToTokenizerMap = initializeNameMap();
private static Map<String, TokenizerType> initializeNameMap() {
Map<String, TokenizerType> map = Generics.newHashMap();
for (TokenizerType type : TokenizerType.values()) {
if (type.abbreviation != null) {
map.put(type.abbreviation.toUpperCase(), type);
}
map.put(type.toString().toUpperCase(), type);
}
return Collections.unmodifiableMap(map);
}
private static final Map<String, TokenizerType> classToTokenizerMap = initializeClassMap();
private static Map<String, TokenizerType> initializeClassMap() {
Map<String, TokenizerType> map = Generics.newHashMap();
for (TokenizerType type : TokenizerType.values()) {
if (type.className != null) {
map.put(type.className.toUpperCase(), type);
}
}
return Collections.unmodifiableMap(map);
}
/**
* Get TokenizerType based on what's in the properties.
*
* @param props Properties to find tokenizer options in
* @return An element of the TokenizerType enum indicating the tokenizer to use
*/
public static TokenizerType getTokenizerType(Properties props) {
String tokClass = props.getProperty("tokenize.class", null);
boolean whitespace = Boolean.valueOf(props.getProperty("tokenize.whitespace", "false"));
String language = props.getProperty("tokenize.language", null);
if(whitespace) {
return Whitespace;
}
if (tokClass != null) {
TokenizerType type = classToTokenizerMap.get(tokClass.toUpperCase());
if (type == null) {
throw new IllegalArgumentException("TokenizerAnnotator: unknown tokenize.class property " + tokClass);
}
return type;
}
if (language != null) {
TokenizerType type = nameToTokenizerMap.get(language.toUpperCase());
if (type == null) {
throw new IllegalArgumentException("TokenizerAnnotator: unknown tokenize.language property " + language);
}
return type;
}
return Unspecified;
}
} // end enum TokenizerType
public static final String EOL_PROPERTY = "tokenize.keepeol";
private final boolean VERBOSE;
private final TokenizerFactory<CoreLabel> factory;
/** new segmenter properties **/
private final boolean useSegmenter;
private final Annotator segmenterAnnotator;
// CONSTRUCTORS
/** Gives a non-verbose, English tokenizer. */
public TokenizerAnnotator() {
this(false);
}
private static String computeExtraOptions(Properties properties) {
String extraOptions = null;
boolean keepNewline = Boolean.valueOf(properties.getProperty(StanfordCoreNLP.NEWLINE_SPLITTER_PROPERTY, "false")); // ssplit.eolonly
String hasSsplit = properties.getProperty("annotators");
if (hasSsplit != null && hasSsplit.contains(StanfordCoreNLP.STANFORD_SSPLIT)) { // ssplit
// Only possibly put in *NL* if not all one (the Boolean method treats null as false)
if ( ! Boolean.parseBoolean(properties.getProperty("ssplit.isOneSentence"))) {
// Set to { NEVER, ALWAYS, TWO_CONSECUTIVE } based on ssplit.newlineIsSentenceBreak
String nlsbString = properties.getProperty(StanfordCoreNLP.NEWLINE_IS_SENTENCE_BREAK_PROPERTY,
StanfordCoreNLP.DEFAULT_NEWLINE_IS_SENTENCE_BREAK);
WordToSentenceProcessor.NewlineIsSentenceBreak nlsb = WordToSentenceProcessor.stringToNewlineIsSentenceBreak(nlsbString);
if (nlsb != WordToSentenceProcessor.NewlineIsSentenceBreak.NEVER) {
keepNewline = true;
}
}
}
if (keepNewline) {
extraOptions = "tokenizeNLs,";
}
return extraOptions;
}
public TokenizerAnnotator(Properties properties) {
this(false, properties, computeExtraOptions(properties));
}
public TokenizerAnnotator(boolean verbose) {
this(verbose, TokenizerType.English);
}
public TokenizerAnnotator(String lang) {
this(true, lang, null);
}
public TokenizerAnnotator(boolean verbose, TokenizerType lang) {
this(verbose, lang.toString());
}
public TokenizerAnnotator(boolean verbose, String lang) {
this(verbose, lang, null);
}
public TokenizerAnnotator(boolean verbose, String lang, String options) {
this(verbose, lang == null ? null : PropertiesUtils.asProperties("tokenize.language", lang), options);
}
public TokenizerAnnotator(boolean verbose, Properties props) {
this(verbose, props, null);
}
public TokenizerAnnotator(boolean verbose, Properties props, String options) {
if (props == null) {
props = new Properties();
}
// check if segmenting must be done
if (props.getProperty("tokenize.language") != null &&
LanguageInfo.isSegmenterLanguage(props.getProperty("tokenize.language"))) {
useSegmenter = true;
if (LanguageInfo.getLanguageFromString(
props.getProperty("tokenize.language")) == LanguageInfo.HumanLanguage.ARABIC)
segmenterAnnotator = new ArabicSegmenterAnnotator("segment", props);
else if (LanguageInfo.getLanguageFromString(
props.getProperty("tokenize.language")) == LanguageInfo.HumanLanguage.CHINESE)
segmenterAnnotator = new ChineseSegmenterAnnotator("segment", props);
else {
segmenterAnnotator = null;
throw new RuntimeException("No segmenter implemented for: "+
LanguageInfo.getLanguageFromString(props.getProperty("tokenize.language")));
}
} else {
useSegmenter = false;
segmenterAnnotator = null;
}
VERBOSE = PropertiesUtils.getBool(props, "tokenize.verbose", verbose);
TokenizerType type = TokenizerType.getTokenizerType(props);
factory = initFactory(type, props, options);
}
/**
* initFactory returns the right type of TokenizerFactory based on the options in the properties file
* and the type. When adding a new Tokenizer, modify TokenizerType.getTokenizerType() to retrieve
* your tokenizer from the properties file, and then add a class is the switch structure here to
* instantiate the new Tokenizer type.
*
* @param type the TokenizerType
* @param props the properties file
* @param extraOptions extra things that should be passed into the tokenizer constructor
*/
private static TokenizerFactory<CoreLabel> initFactory(TokenizerType type, Properties props, String extraOptions) throws IllegalArgumentException{
TokenizerFactory<CoreLabel> factory;
String options = props.getProperty("tokenize.options", null);
// set it to the equivalent of both extraOptions and options
// TODO: maybe we should always have getDefaultOptions() and
// expect the user to turn off default options. That would
// require all options to have negated options, but
// currently there are some which don't have that
if (options == null) {
options = type.getDefaultOptions();
}
if (extraOptions != null) {
if (extraOptions.endsWith(",")) {
options = extraOptions + options;
} else {
options = extraOptions + ',' + options;
}
}
switch(type) {
case Arabic:
case Chinese:
factory = null;
break;
case Spanish:
factory = SpanishTokenizer.factory(new CoreLabelTokenFactory(), options);
break;
case French:
factory = FrenchTokenizer.factory(new CoreLabelTokenFactory(), options);
break;
case Whitespace:
boolean eolIsSignificant = Boolean.valueOf(props.getProperty(EOL_PROPERTY, "false"));
eolIsSignificant = eolIsSignificant || Boolean.valueOf(props.getProperty(StanfordCoreNLP.NEWLINE_SPLITTER_PROPERTY, "false"));
factory = new WhitespaceTokenizer.WhitespaceTokenizerFactory<>(new CoreLabelTokenFactory(), eolIsSignificant);
break;
case English:
case German:
factory = PTBTokenizer.factory(new CoreLabelTokenFactory(), options);
break;
case Unspecified:
log.info("No tokenizer type provided. Defaulting to PTBTokenizer.");
factory = PTBTokenizer.factory(new CoreLabelTokenFactory(), options);
break;
default:
throw new IllegalArgumentException("No valid tokenizer type provided.\n" +
"Use -tokenize.language, -tokenize.class, or -tokenize.whitespace \n" +
"to specify a tokenizer.");
}
return factory;
}
/**
* Returns a thread-safe tokenizer
*/
public Tokenizer<CoreLabel> getTokenizer(Reader r) {
return factory.getTokenizer(r);
}
/**
* Does the actual work of splitting TextAnnotation into CoreLabels,
* which are then attached to the TokensAnnotation.
*/
@Override
public void annotate(Annotation annotation) {
if (VERBOSE) {
log.info("Tokenizing ... ");
}
// for Arabic and Chinese use a segmenter instead
if (useSegmenter) {
segmenterAnnotator.annotate(annotation);
return;
}
if (annotation.containsKey(CoreAnnotations.TextAnnotation.class)) {
String text = annotation.get(CoreAnnotations.TextAnnotation.class);
Reader r = new StringReader(text);
// don't wrap in BufferedReader. It gives you nothing for in-memory String unless you need the readLine() method!
List<CoreLabel> tokens = getTokenizer(r).tokenize();
// cdm 2010-05-15: This is now unnecessary, as it is done in CoreLabelTokenFactory
// for (CoreLabel token: tokens) {
// token.set(CoreAnnotations.TextAnnotation.class, token.get(CoreAnnotations.TextAnnotation.class));
// }
// label newlines
for (CoreLabel token : tokens) {
if (token.word().equals(AbstractTokenizer.NEWLINE_TOKEN) && (token.endPosition() - token.beginPosition() == 1))
token.set(CoreAnnotations.IsNewlineAnnotation.class, true);
else
token.set(CoreAnnotations.IsNewlineAnnotation.class, false);
}
annotation.set(CoreAnnotations.TokensAnnotation.class, tokens);
if (VERBOSE) {
log.info("done.");
log.info("Tokens: " + annotation.get(CoreAnnotations.TokensAnnotation.class));
}
} else {
throw new RuntimeException("Tokenizer unable to find text in annotation: " + annotation);
}
}
@Override
public Set<Class<? extends CoreAnnotation>> requires() {
return Collections.emptySet();
}
@Override
public Set<Class<? extends CoreAnnotation>> requirementsSatisfied() {
return new HashSet<>(Arrays.asList(
CoreAnnotations.TextAnnotation.class,
CoreAnnotations.TokensAnnotation.class,
CoreAnnotations.CharacterOffsetBeginAnnotation.class,
CoreAnnotations.CharacterOffsetEndAnnotation.class,
CoreAnnotations.BeforeAnnotation.class,
CoreAnnotations.AfterAnnotation.class,
CoreAnnotations.TokenBeginAnnotation.class,
CoreAnnotations.TokenEndAnnotation.class,
CoreAnnotations.PositionAnnotation.class,
CoreAnnotations.IndexAnnotation.class,
CoreAnnotations.OriginalTextAnnotation.class,
CoreAnnotations.ValueAnnotation.class,
CoreAnnotations.IsNewlineAnnotation.class
));
}
}
| rupenp/CoreNLP | src/edu/stanford/nlp/pipeline/TokenizerAnnotator.java | Java | gpl-2.0 | 13,435 |
/*
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* 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.jaspersoft.jasperserver.api.engine.common.virtualdatasourcequery.impl;
import com.jaspersoft.jasperserver.api.common.virtualdatasourcequery.teiid.TransactionManagerConfiguration;
/**
* User: ichan
* To change this template use File | Settings | File Templates.
*/
public class TransactionManagerConfigurationImpl implements TransactionManagerConfiguration {
private volatile String serverId = "TeiidEmbeddedServer-TransactionManager";
private volatile String logPart1Filename = "transactionBtm1.log";
private volatile String logPart2Filename = "transactionBtm2.log";
private volatile boolean saveLogFilesToLogDirectory = true;
private volatile boolean forcedWriteEnabled = true;
private volatile boolean forceBatchingEnabled = true;
private volatile int maxLogSizeInMb = 2;
private volatile boolean filterLogStatus = false;
private volatile boolean skipCorruptedLogs = true;
private volatile boolean asynchronous2Pc = false;
private volatile boolean warnAboutZeroResourceTransaction = true;
private volatile boolean debugZeroResourceTransaction = false;
private volatile int defaultTransactionTimeout = 60;
private volatile int gracefulShutdownInterval = 60;
private volatile int backgroundRecoveryIntervalSeconds = 60;
private volatile boolean disableJmx = false;
private volatile String jndiUserTransactionName = null;
private volatile String jndiTransactionSynchronizationRegistryName = null;
private volatile String journal = null;
private volatile String exceptionAnalyzer = null;
private volatile boolean currentNodeOnlyRecovery = true;
private volatile boolean allowMultipleLrc = false;
private volatile String resourceConfigurationFilename = null;
/**
* ASCII ID that must uniquely identify this TM instance. It must not exceed 51 characters or it will be truncated.
* <p>Property name:<br/><b>bitronix.tm.serverId -</b> <i>(defaults to server's IP address but that's unsafe for
* production use)</i></p>
* @return the unique ID of this TM instance.
*/
public String getServerId() {
return serverId;
}
/**
* Set the ASCII ID that must uniquely identify this TM instance. It must not exceed 51 characters or it will be
* truncated.
* @see #getServerId()
* @param serverId the unique ID of this TM instance.
*/
public void setServerId(String serverId) {
this.serverId = serverId;
}
/**
* Get the journal fragment file 1 name.
* <p>Property name:<br/><b>bitronix.tm.journal.disk.logPart1Filename -</b> <i>(defaults to btm1.tlog)</i></p>
* @return the journal fragment file 1 name.
*/
public String getLogPart1Filename() {
return logPart1Filename;
}
/**
* Set the journal fragment file 1 name.
* @see #getLogPart1Filename()
* @param logPart1Filename the journal fragment file 1 name.
*/
public void setLogPart1Filename(String logPart1Filename) {
this.logPart1Filename = logPart1Filename;
}
/**
* Get the journal fragment file 2 name.
* <p>Property name:<br/><b>bitronix.tm.journal.disk.logPart2Filename -</b> <i>(defaults to btm2.tlog)</i></p>
* @return the journal fragment file 2 name.
*/
public String getLogPart2Filename() {
return logPart2Filename;
}
/**
* Set the journal fragment file 2 name.
* @see #getLogPart2Filename()
* @param logPart2Filename the journal fragment file 2 name.
*/
public void setLogPart2Filename(String logPart2Filename) {
this.logPart2Filename = logPart2Filename;
}
/**
* return whether saving log files to default log directory
* @return the state of saving log files to default log directory
*/
public boolean isSaveLogFilesToLogDirectory() {
return saveLogFilesToLogDirectory;
}
/**
* set saving log files to default log directory
* @param saveLogFilesToLogDirectory the state of saving log files to default log directory
*/
public void setSaveLogFilesToLogDirectory(boolean saveLogFilesToLogDirectory) {
this.saveLogFilesToLogDirectory = saveLogFilesToLogDirectory;
}
/**
* Are logs forced to disk? Do not set to false in production since without disk force, integrity is not
* guaranteed.
* <p>Property name:<br/><b>bitronix.tm.journal.disk.forcedWriteEnabled -</b> <i>(defaults to true)</i></p>
* @return true if logs are forced to disk, false otherwise.
*/
public boolean isForcedWriteEnabled() {
return forcedWriteEnabled;
}
/**
* Set if logs are forced to disk. Do not set to false in production since without disk force, integrity is not
* guaranteed.
* @see #isForcedWriteEnabled()
* @param forcedWriteEnabled true if logs should be forced to disk, false otherwise.
*/
public void setForcedWriteEnabled(boolean forcedWriteEnabled) {
this.forcedWriteEnabled = forcedWriteEnabled;
}
/**
* Are disk forces batched? Disabling batching can seriously lower the transaction manager's throughput.
* <p>Property name:<br/><b>bitronix.tm.journal.disk.forceBatchingEnabled -</b> <i>(defaults to true)</i></p>
* @return true if disk forces are batched, false otherwise.
*/
public boolean isForceBatchingEnabled() {
return forceBatchingEnabled;
}
/**
* Set if disk forces are batched. Disabling batching can seriously lower the transaction manager's throughput.
* @see #isForceBatchingEnabled()
* @param forceBatchingEnabled true if disk forces are batched, false otherwise.
*/
public void setForceBatchingEnabled(boolean forceBatchingEnabled) {
this.forceBatchingEnabled = forceBatchingEnabled;
}
/**
* Maximum size in megabytes of the journal fragments. Larger logs allow transactions to stay longer in-doubt but
* the TM pauses longer when a fragment is full.
* <p>Property name:<br/><b>bitronix.tm.journal.disk.maxLogSize -</b> <i>(defaults to 2)</i></p>
* @return the maximum size in megabytes of the journal fragments.
*/
public int getMaxLogSizeInMb() {
return maxLogSizeInMb;
}
/**
* Set the Maximum size in megabytes of the journal fragments. Larger logs allow transactions to stay longer
* in-doubt but the TM pauses longer when a fragment is full.
* @see #getMaxLogSizeInMb()
* @param maxLogSizeInMb the maximum size in megabytes of the journal fragments.
*/
public void setMaxLogSizeInMb(int maxLogSizeInMb) {
this.maxLogSizeInMb = maxLogSizeInMb;
}
/**
* Should only mandatory logs be written? Enabling this parameter lowers space usage of the fragments but makes
* debugging more complex.
* <p>Property name:<br/><b>bitronix.tm.journal.disk.filterLogStatus -</b> <i>(defaults to false)</i></p>
* @return true if only mandatory logs should be written.
*/
public boolean isFilterLogStatus() {
return filterLogStatus;
}
/**
* Set if only mandatory logs should be written. Enabling this parameter lowers space usage of the fragments but
* makes debugging more complex.
* @see #isFilterLogStatus()
* @param filterLogStatus true if only mandatory logs should be written.
*/
public void setFilterLogStatus(boolean filterLogStatus) {
this.filterLogStatus = filterLogStatus;
}
/**
* Should corrupted logs be skipped?
* <p>Property name:<br/><b>bitronix.tm.journal.disk.skipCorruptedLogs -</b> <i>(defaults to false)</i></p>
* @return true if corrupted logs should be skipped.
*/
public boolean isSkipCorruptedLogs() {
return skipCorruptedLogs;
}
/**
* Set if corrupted logs should be skipped.
* @see #isSkipCorruptedLogs()
* @param skipCorruptedLogs true if corrupted logs should be skipped.
*/
public void setSkipCorruptedLogs(boolean skipCorruptedLogs) {
this.skipCorruptedLogs = skipCorruptedLogs;
}
/**
* Should two phase commit be executed asynchronously? Asynchronous two phase commit can improve performance when
* there are many resources enlisted in transactions but is more CPU intensive due to the dynamic thread spawning
* requirements. It also makes debugging more complex.
* <p>Property name:<br/><b>bitronix.tm.2pc.async -</b> <i>(defaults to false)</i></p>
* @return true if two phase commit should be executed asynchronously.
*/
public boolean isAsynchronous2Pc() {
return asynchronous2Pc;
}
/**
* Set if two phase commit should be executed asynchronously. Asynchronous two phase commit can improve performance
* when there are many resources enlisted in transactions but is more CPU intensive due to the dynamic thread
* spawning requirements. It also makes debugging more complex.
* @see #isAsynchronous2Pc()
* @param asynchronous2Pc true if two phase commit should be executed asynchronously.
*/
public void setAsynchronous2Pc(boolean asynchronous2Pc) {
this.asynchronous2Pc = asynchronous2Pc;
}
/**
* Should transactions executed without a single enlisted resource result in a warning or not? Most of the time
* transactions executed with no enlisted resource reflect a bug or a mis-configuration somewhere.
* <p>Property name:<br/><b>bitronix.tm.2pc.warnAboutZeroResourceTransactions -</b> <i>(defaults to true)</i></p>
* @return true if transactions executed without a single enlisted resource should result in a warning.
*/
public boolean isWarnAboutZeroResourceTransaction() {
return warnAboutZeroResourceTransaction;
}
/**
* Set if transactions executed without a single enlisted resource should result in a warning or not. Most of the
* time transactions executed with no enlisted resource reflect a bug or a mis-configuration somewhere.
* @see #isWarnAboutZeroResourceTransaction()
* @param warnAboutZeroResourceTransaction true if transactions executed without a single enlisted resource should
* result in a warning.
*/
public void setWarnAboutZeroResourceTransaction(boolean warnAboutZeroResourceTransaction) {
this.warnAboutZeroResourceTransaction = warnAboutZeroResourceTransaction;
}
/**
* Should creation and commit call stacks of transactions executed without a single enlisted tracked and logged
* or not?
* <p>Property name:<br/><b>bitronix.tm.2pc.debugZeroResourceTransactions -</b> <i>(defaults to false)</i></p>
* @return true if creation and commit call stacks of transactions executed without a single enlisted resource
* should be tracked and logged.
*/
public boolean isDebugZeroResourceTransaction() {
return debugZeroResourceTransaction;
}
/**
* Set if creation and commit call stacks of transactions executed without a single enlisted resource should be
* tracked and logged.
* @see #isDebugZeroResourceTransaction()
* @see #isWarnAboutZeroResourceTransaction()
* @param debugZeroResourceTransaction true if the creation and commit call stacks of transaction executed without
* a single enlisted resource should be tracked and logged.
* @return this.
*/
public void setDebugZeroResourceTransaction(boolean debugZeroResourceTransaction) {
this.debugZeroResourceTransaction = debugZeroResourceTransaction;
}
/**
* Default transaction timeout in seconds.
* <p>Property name:<br/><b>bitronix.tm.timer.defaultTransactionTimeout -</b> <i>(defaults to 60)</i></p>
* @return the default transaction timeout in seconds.
*/
public int getDefaultTransactionTimeout() {
return defaultTransactionTimeout;
}
/**
* Set the default transaction timeout in seconds.
* @see #getDefaultTransactionTimeout()
* @param defaultTransactionTimeout the default transaction timeout in seconds.
*/
public void setDefaultTransactionTimeout(int defaultTransactionTimeout) {
this.defaultTransactionTimeout = defaultTransactionTimeout;
}
/**
* Maximum amount of seconds the TM will wait for transactions to get done before aborting them at shutdown time.
* <p>Property name:<br/><b>bitronix.tm.timer.gracefulShutdownInterval -</b> <i>(defaults to 60)</i></p>
* @return the maximum amount of time in seconds.
*/
public int getGracefulShutdownInterval() {
return gracefulShutdownInterval;
}
/**
* Set the maximum amount of seconds the TM will wait for transactions to get done before aborting them at shutdown
* time.
* @see #getGracefulShutdownInterval()
* @param gracefulShutdownInterval the maximum amount of time in seconds..
*/
public void setGracefulShutdownInterval(int gracefulShutdownInterval) {
this.gracefulShutdownInterval = gracefulShutdownInterval;
}
/**
* Interval in seconds at which to run the recovery process in the background. Disabled when set to 0.
* <p>Property name:<br/><b>bitronix.tm.timer.backgroundRecoveryIntervalSeconds -</b> <i>(defaults to 60)</i></p>
* @return the interval in seconds.
*/
public int getBackgroundRecoveryIntervalSeconds() {
return backgroundRecoveryIntervalSeconds;
}
/**
* Set the interval in seconds at which to run the recovery process in the background. Disabled when set to 0.
* @see #getBackgroundRecoveryIntervalSeconds()
* @param backgroundRecoveryIntervalSeconds the interval in minutes.
*/
public void setBackgroundRecoveryIntervalSeconds(int backgroundRecoveryIntervalSeconds) {
this.backgroundRecoveryIntervalSeconds = backgroundRecoveryIntervalSeconds;
}
/**
* Should JMX Mbeans not be registered even if a JMX MBean server is detected?
* <p>Property name:<br/><b>bitronix.tm.disableJmx -</b> <i>(defaults to false)</i></p>
* @return true if JMX MBeans should never be registered.
*/
public boolean isDisableJmx() {
return disableJmx;
}
/**
* Set to true if JMX Mbeans should not be registered even if a JMX MBean server is detected.
* @see #isDisableJmx()
* @param disableJmx true if JMX MBeans should never be registered.
*/
public void setDisableJmx(boolean disableJmx) {
this.disableJmx = disableJmx;
}
/**
* Get the name the {@link javax.transaction.UserTransaction} should be bound under in the
* {@link bitronix.tm.jndi.BitronixContext}.
* @return the name the {@link javax.transaction.UserTransaction} should
* be bound under in the {@link bitronix.tm.jndi.BitronixContext}.
*/
public String getJndiUserTransactionName() {
return jndiUserTransactionName;
}
/**
* Set the name the {@link javax.transaction.UserTransaction} should be bound under in the
* {@link bitronix.tm.jndi.BitronixContext}.
* @see #getJndiUserTransactionName()
* @param jndiUserTransactionName the name the {@link javax.transaction.UserTransaction} should
* be bound under in the {@link bitronix.tm.jndi.BitronixContext}.
*/
public void setJndiUserTransactionName(String jndiUserTransactionName) {
this.jndiUserTransactionName = jndiUserTransactionName;
}
/**
* Get the name the {@link javax.transaction.TransactionSynchronizationRegistry} should be bound under in the
* {@link bitronix.tm.jndi.BitronixContext}.
* @return the name the {@link javax.transaction.TransactionSynchronizationRegistry} should
* be bound under in the {@link bitronix.tm.jndi.BitronixContext}.
*/
public String getJndiTransactionSynchronizationRegistryName() {
return jndiTransactionSynchronizationRegistryName;
}
/**
* Set the name the {@link javax.transaction.TransactionSynchronizationRegistry} should be bound under in the
* {@link bitronix.tm.jndi.BitronixContext}.
* @see #getJndiUserTransactionName()
* @param jndiTransactionSynchronizationRegistryName the name the {@link javax.transaction.TransactionSynchronizationRegistry} should
* be bound under in the {@link bitronix.tm.jndi.BitronixContext}.
*/
public void setJndiTransactionSynchronizationRegistryName(String jndiTransactionSynchronizationRegistryName) {
this.jndiTransactionSynchronizationRegistryName = jndiTransactionSynchronizationRegistryName;
}
/**
* Get the journal implementation. Can be <code>disk</code>, <code>null</code> or a class name.
* @return the journal name.
*/
public String getJournal() {
return journal;
}
/**
* Set the journal name. Can be <code>disk</code>, <code>null</code> or a class name.
* @see #getJournal()
* @param journal the journal name.
*/
public void setJournal(String journal) {
this.journal = journal;
}
/**
* Get the exception analyzer implementation. Can be <code>null</code> for the default one or a class name.
* @return the exception analyzer name.
*/
public String getExceptionAnalyzer() {
return exceptionAnalyzer;
}
/**
* Set the exception analyzer implementation. Can be <code>null</code> for the default one or a class name.
* @see #getExceptionAnalyzer()
* @param exceptionAnalyzer the exception analyzer name.
*/
public void setExceptionAnalyzer(String exceptionAnalyzer) {
this.exceptionAnalyzer = exceptionAnalyzer;
}
/**
* Should the recovery process <b>not</b> recover XIDs generated with another JVM unique ID? Setting this property to true
* is useful in clustered environments where multiple instances of BTM are running on different nodes.
* @see #getServerId() contains the value used as the JVM unique ID.
* @return true if recovery should filter out recovered XIDs that do not contain this JVM's unique ID, false otherwise.
*/
public boolean isCurrentNodeOnlyRecovery() {
return currentNodeOnlyRecovery;
}
/**
* Set to true if recovery should filter out recovered XIDs that do not contain this JVM's unique ID, false otherwise.
* @see #isCurrentNodeOnlyRecovery()
* @param currentNodeOnlyRecovery true if recovery should filter out recovered XIDs that do not contain this JVM's unique ID, false otherwise.
*/
public void setCurrentNodeOnlyRecovery(boolean currentNodeOnlyRecovery) {
this.currentNodeOnlyRecovery = currentNodeOnlyRecovery;
}
/**
* Should the transaction manager allow enlistment of multiple LRC resources in a single transaction?
* This is highly unsafe but could be useful for testing.
* @return true if the transaction manager should allow enlistment of multiple LRC resources in a single transaction, false otherwise.
*/
public boolean isAllowMultipleLrc() {
return allowMultipleLrc;
}
/**
* Set to true if the transaction manager should allow enlistment of multiple LRC resources in a single transaction.
* @param allowMultipleLrc true if the transaction manager should allow enlistment of multiple LRC resources in a single transaction, false otherwise.
*/
public void setAllowMultipleLrc(boolean allowMultipleLrc) {
this.allowMultipleLrc = allowMultipleLrc;
}
/**
* {@link bitronix.tm.resource.ResourceLoader} configuration file name. {@link bitronix.tm.resource.ResourceLoader}
* will be disabled if this value is null.
* <p>Property name:<br/><b>bitronix.tm.resource.configuration -</b> <i>(defaults to null)</i></p>
* @return the filename of the resources configuration file or null if not configured.
*/
public String getResourceConfigurationFilename() {
return resourceConfigurationFilename;
}
/**
* Set the {@link bitronix.tm.resource.ResourceLoader} configuration file name.
* @see #getResourceConfigurationFilename()
* @param resourceConfigurationFilename the filename of the resources configuration file or null you do not want to
* use the {@link bitronix.tm.resource.ResourceLoader}.
*/
public void setResourceConfigurationFilename(String resourceConfigurationFilename) {
this.resourceConfigurationFilename = resourceConfigurationFilename;
}
}
| leocockroach/JasperServer5.6 | jasperserver-api-impl/engine/src/main/java/com/jaspersoft/jasperserver/api/engine/common/virtualdatasourcequery/impl/TransactionManagerConfigurationImpl.java | Java | gpl-2.0 | 21,464 |
/*
* Copyright (c) Norkart AS 2006-2007
*
* This source code is the property of Norkart AS.
* Its use by other parties is regulated by license or agreement with Norkart.
*
* PositionCRS.java
*
* Created on 24. mai 2007, 14:06
*
*/
package com.norkart.geopos;
/**
*
* @author runaas
*/
public class PositionCRS extends Position {
protected CoordinateReferenceSystem crs;
protected double [] xy = new double[2];
/** Creates a new instance of PositionCRS */
public PositionCRS() {
crs = null;
xy[0] = Double.NaN;
xy[1] = Double.NaN;
}
public PositionCRS(double x, double y, CoordinateReferenceSystem crs) {
this.crs = crs;
xy[0] = x;
xy[1] = y;
crs.fromCRS(xy, 0, pos, 0);
}
public PositionCRS(Position p, CoordinateReferenceSystem crs) {
this.crs = crs;
pos[0] = p.pos[0];
pos[1] = p.pos[1];
crs.toCRS(pos, 0, xy, 0);
}
public Object clone() throws CloneNotSupportedException {
PositionCRS retval = (PositionCRS)super.clone();
if (xy != null)
retval.xy = (double [])(xy.clone());
return retval;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
PositionCRS p = (PositionCRS)obj;
return p.xy[0] == xy[0] && p.xy[1] == xy[1];
}
public double getX() {
return xy[0];
}
public double getY() {
return xy[1];
}
/**
* Set the latitude
*
* @param latitude the new latitude
*/
public void setLatLong(double latitude, double longitude) {
pos[1] = latitude;
pos[0] = longitude;
crs.toCRS(pos, 0, xy, 0);
}
public void setXY(double x, double y) {
xy[0] = x;
xy[1] = y;
crs.fromCRS(xy, 0, pos, 0);
}
}
| Norkart/NK-VirtualGlobe | GeoPos/src/com/norkart/geopos/PositionCRS.java | Java | gpl-2.0 | 1,998 |
/*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.1.2.1</a>, using an XML
* Schema.
* $Id$
*/
package org.opennms.netmgt.config.views.descriptors;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import org.opennms.netmgt.config.views.View;
/**
* Class ViewDescriptor.
*
* @version $Revision$ $Date$
*/
@SuppressWarnings("all") public class ViewDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _elementDefinition.
*/
private boolean _elementDefinition;
/**
* Field _nsPrefix.
*/
private java.lang.String _nsPrefix;
/**
* Field _nsURI.
*/
private java.lang.String _nsURI;
/**
* Field _xmlName.
*/
private java.lang.String _xmlName;
/**
* Field _identity.
*/
private org.exolab.castor.xml.XMLFieldDescriptor _identity;
//----------------/
//- Constructors -/
//----------------/
public ViewDescriptor() {
super();
_nsURI = "http://xmlns.opennms.org/xsd/views";
_xmlName = "view";
_elementDefinition = true;
//-- set grouping compositor
setCompositorAsSequence();
org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null;
org.exolab.castor.mapping.FieldHandler handler = null;
org.exolab.castor.xml.FieldValidator fieldValidator = null;
//-- initialize attribute descriptors
//-- initialize element descriptors
//-- _name
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_name", "name", org.exolab.castor.xml.NodeType.Element);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
View target = (View) object;
return target.getName();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
View target = (View) object;
target.setName( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/views");
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _name
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- _title
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_title", "title", org.exolab.castor.xml.NodeType.Element);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
View target = (View) object;
return target.getTitle();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
View target = (View) object;
target.setTitle( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/views");
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _title
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- _comment
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_comment", "comment", org.exolab.castor.xml.NodeType.Element);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
View target = (View) object;
return target.getComment();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
View target = (View) object;
target.setComment( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/views");
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _comment
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- _common
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.opennms.netmgt.config.views.Common.class, "_common", "common", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
View target = (View) object;
return target.getCommon();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
View target = (View) object;
target.setCommon( (org.opennms.netmgt.config.views.Common) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new org.opennms.netmgt.config.views.Common();
}
};
desc.setSchemaType("org.opennms.netmgt.config.views.Common");
desc.setHandler(handler);
desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/views");
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _common
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
}
desc.setValidator(fieldValidator);
//-- _categories
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.opennms.netmgt.config.views.Categories.class, "_categories", "categories", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
View target = (View) object;
return target.getCategories();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
View target = (View) object;
target.setCategories( (org.opennms.netmgt.config.views.Categories) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new org.opennms.netmgt.config.views.Categories();
}
};
desc.setSchemaType("org.opennms.netmgt.config.views.Categories");
desc.setHandler(handler);
desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/views");
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _categories
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
}
desc.setValidator(fieldValidator);
//-- _membership
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.opennms.netmgt.config.views.Membership.class, "_membership", "membership", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
View target = (View) object;
return target.getMembership();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
View target = (View) object;
target.setMembership( (org.opennms.netmgt.config.views.Membership) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new org.opennms.netmgt.config.views.Membership();
}
};
desc.setSchemaType("org.opennms.netmgt.config.views.Membership");
desc.setHandler(handler);
desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/views");
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _membership
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
}
desc.setValidator(fieldValidator);
}
//-----------/
//- Methods -/
//-----------/
/**
* Method getAccessMode.
*
* @return the access mode specified for this class.
*/
@Override()
public org.exolab.castor.mapping.AccessMode getAccessMode(
) {
return null;
}
/**
* Method getIdentity.
*
* @return the identity field, null if this class has no
* identity.
*/
@Override()
public org.exolab.castor.mapping.FieldDescriptor getIdentity(
) {
return _identity;
}
/**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/
@Override()
public java.lang.Class<?> getJavaClass(
) {
return org.opennms.netmgt.config.views.View.class;
}
/**
* Method getNameSpacePrefix.
*
* @return the namespace prefix to use when marshaling as XML.
*/
@Override()
public java.lang.String getNameSpacePrefix(
) {
return _nsPrefix;
}
/**
* Method getNameSpaceURI.
*
* @return the namespace URI used when marshaling and
* unmarshaling as XML.
*/
@Override()
public java.lang.String getNameSpaceURI(
) {
return _nsURI;
}
/**
* Method getValidator.
*
* @return a specific validator for the class described by this
* ClassDescriptor.
*/
@Override()
public org.exolab.castor.xml.TypeValidator getValidator(
) {
return this;
}
/**
* Method getXMLName.
*
* @return the XML Name for the Class being described.
*/
@Override()
public java.lang.String getXMLName(
) {
return _xmlName;
}
/**
* Method isElementDefinition.
*
* @return true if XML schema definition of this Class is that
* of a global
* element or element with anonymous type definition.
*/
public boolean isElementDefinition(
) {
return _elementDefinition;
}
}
| vishwaAbhinav/OpenNMS | opennms-config/target/generated-sources/castor/org/opennms/netmgt/config/views/descriptors/ViewDescriptor.java | Java | gpl-2.0 | 14,893 |
/*
* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.loop;
import static com.oracle.graal.compiler.common.GraalOptions.*;
import java.util.*;
import com.oracle.graal.debug.*;
import jdk.internal.jvmci.options.*;
import com.oracle.graal.graph.*;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.VirtualState.VirtualClosure;
import com.oracle.graal.nodes.cfg.*;
import com.oracle.graal.nodes.debug.*;
public abstract class LoopPolicies {
@Option(help = "", type = OptionType.Expert) public static final OptionValue<Integer> LoopUnswitchMaxIncrease = new OptionValue<>(500);
@Option(help = "", type = OptionType.Expert) public static final OptionValue<Integer> LoopUnswitchTrivial = new OptionValue<>(10);
@Option(help = "", type = OptionType.Expert) public static final OptionValue<Double> LoopUnswitchFrequencyBoost = new OptionValue<>(10.0);
@Option(help = "", type = OptionType.Expert) public static final OptionValue<Integer> FullUnrollMaxNodes = new OptionValue<>(300);
@Option(help = "", type = OptionType.Expert) public static final OptionValue<Integer> FullUnrollMaxIterations = new OptionValue<>(600);
@Option(help = "", type = OptionType.Expert) public static final OptionValue<Integer> ExactFullUnrollMaxNodes = new OptionValue<>(1200);
private LoopPolicies() {
// does not need to be instantiated
}
// TODO (gd) change when inversion is available
public static boolean shouldPeel(LoopEx loop, ControlFlowGraph cfg) {
if (loop.detectCounted()) {
return false;
}
LoopBeginNode loopBegin = loop.loopBegin();
double entryProbability = cfg.blockFor(loopBegin.forwardEnd()).probability();
if (entryProbability > MinimumPeelProbability.getValue() && loop.size() + loopBegin.graph().getNodeCount() < MaximumDesiredSize.getValue()) {
// check whether we're allowed to peel this loop
for (Node node : loop.inside().nodes()) {
if (node instanceof ControlFlowAnchorNode) {
return false;
}
}
return true;
} else {
return false;
}
}
public static boolean shouldFullUnroll(LoopEx loop) {
if (!loop.isCounted() || !loop.counted().isConstantMaxTripCount()) {
return false;
}
CountedLoopInfo counted = loop.counted();
long maxTrips = counted.constantMaxTripCount();
int maxNodes = (counted.isExactTripCount() && counted.isConstantExactTripCount()) ? ExactFullUnrollMaxNodes.getValue() : FullUnrollMaxNodes.getValue();
maxNodes = Math.min(maxNodes, MaximumDesiredSize.getValue() - loop.loopBegin().graph().getNodeCount());
int size = Math.max(1, loop.size() - 1 - loop.loopBegin().phis().count());
if (size * maxTrips <= maxNodes) {
// check whether we're allowed to unroll this loop
for (Node node : loop.inside().nodes()) {
if (node instanceof ControlFlowAnchorNode) {
return false;
}
}
return true;
} else {
return false;
}
}
public static boolean shouldTryUnswitch(LoopEx loop) {
LoopBeginNode loopBegin = loop.loopBegin();
double loopFrequency = loopBegin.loopFrequency();
if (loopFrequency <= 1.0) {
return false;
}
return loopBegin.unswitches() <= LoopMaxUnswitch.getValue();
}
private static final class CountingClosure implements VirtualClosure {
int count;
public void apply(VirtualState node) {
count++;
}
}
private static class IsolatedInitialization {
static final DebugMetric UNSWITCH_SPLIT_WITH_PHIS = Debug.metric("UnswitchSplitWithPhis");
}
public static boolean shouldUnswitch(LoopEx loop, List<ControlSplitNode> controlSplits) {
int inBranchTotal = 0;
int phis = 0;
for (ControlSplitNode controlSplit : controlSplits) {
for (Node successor : controlSplit.successors()) {
AbstractBeginNode branch = (AbstractBeginNode) successor;
// this may count twice because of fall-through in switches
inBranchTotal += loop.nodesInLoopBranch(branch).count();
}
Block postDomBlock = loop.loopsData().getCFG().blockFor(controlSplit).getPostdominator();
if (postDomBlock != null) {
IsolatedInitialization.UNSWITCH_SPLIT_WITH_PHIS.increment();
phis += ((MergeNode) postDomBlock.getBeginNode()).phis().count();
}
}
CountingClosure stateNodesCount = new CountingClosure();
double loopFrequency = loop.loopBegin().loopFrequency();
int maxDiff = LoopUnswitchTrivial.getValue() + (int) (LoopUnswitchFrequencyBoost.getValue() * (loopFrequency - 1.0 + phis));
maxDiff = Math.min(maxDiff, LoopUnswitchMaxIncrease.getValue());
int remainingGraphSpace = MaximumDesiredSize.getValue() - loop.loopBegin().graph().getNodeCount();
maxDiff = Math.min(maxDiff, remainingGraphSpace);
loop.loopBegin().stateAfter().applyToVirtual(stateNodesCount);
int loopTotal = loop.size() - loop.loopBegin().phis().count() - stateNodesCount.count - 1;
int actualDiff = loopTotal - inBranchTotal;
Debug.log("shouldUnswitch(%s, %s) : delta=%d (%.2f%% inside of branches), max=%d, f=%.2f, phis=%d -> %b", loop, controlSplits, actualDiff, (double) (inBranchTotal) / loopTotal * 100, maxDiff,
loopFrequency, phis, actualDiff <= maxDiff);
return actualDiff <= maxDiff;
}
}
| mur47x111/GraalVM | graal/com.oracle.graal.loop/src/com/oracle/graal/loop/LoopPolicies.java | Java | gpl-2.0 | 6,747 |
package voteHoaiLam_wechoice;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class AutoRegister {
private static BufferedReader configBufferedReader;
private static String configLine;
private static int configTimeout;
private static String configPassword;
private static String configName;
private static int waitTime;
public static void main(String[] args) throws IOException, InterruptedException {
if (OSValidator.isWindows()) {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
}
File config_file = new File ("config.txt");
FileReader configReader = new FileReader (config_file);
configBufferedReader = new BufferedReader(configReader);
while ((configLine = configBufferedReader.readLine()) != null) {
String[] lines = configLine.split("=");
if (lines[0].compareTo("password") == 0) {
configPassword = lines [1];
}
if (lines[0].compareTo("timeout") == 0) {
configTimeout = Integer.parseInt(lines [1]);
}
if (lines[0].compareTo("name") == 0) {
configName = lines [1];
}
if (lines[0].compareTo("wait") == 0) {
waitTime = Integer.parseInt(lines [1]);
}
}
File file = new File("email.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
WebDriver driver = new ChromeDriver();
// TODO Auto-generated method stub
driver.manage().timeouts().implicitlyWait(configTimeout, TimeUnit.SECONDS);
driver.get("http://vietid.net");
WebElement email_addr = driver.findElement(By.id("email"));
WebElement password1 = driver.findElement(By.id("password"));
WebElement password2 = driver.findElement(By.id("re_password"));
WebElement full_name = driver.findElement(By.id("fullname"));
email_addr.sendKeys(line);
password1.sendKeys(configPassword);
password2.sendKeys(configPassword);
full_name.sendKeys(configName);
WebElement register_button = driver.findElement(By.id("register_vietid"));
register_button.click();
driver.quit();
Thread.sleep(waitTime * 1000);
}
fileReader.close();
}
}
| vinhqdang/voteHoaiLam_wechoice | src/voteHoaiLam_wechoice/AutoRegister.java | Java | gpl-2.0 | 2,448 |
/**
* Licensed under the GPL License. You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
* PURPOSE.
*/
package psiprobe.beans.stats.listeners;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The listener interface for receiving abstractStatsCollection events. The class that is interested
* in processing a abstractStatsCollection event implements this interface, and the object created
* with that class is registered with a component using the component's
* {@code addAbstractStatsCollectionListener} method. When the abstractStatsCollection event occurs,
* that object's appropriate method is invoked.
*/
public abstract class AbstractStatsCollectionListener implements StatsCollectionListener {
/** The logger. */
protected final Logger logger = LoggerFactory.getLogger(getClass());
/** The property category. */
private String propertyCategory;
/** The enabled. */
private boolean enabled = true;
@Override
public boolean isEnabled() {
return enabled;
}
/**
* Sets the enabled.
*
* @param enabled the new enabled
*/
protected void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* Gets the property value.
*
* @param name the name
* @param attribute the attribute
* @return the property value
*/
protected String getPropertyValue(String name, String attribute) {
String value = getPropertyValue(getPropertyKey(name, attribute));
if (value == null) {
value = getPropertyValue(getPropertyKey(null, attribute));
}
if (value == null) {
value = getPropertyValue(getPropertyKey(null, null, attribute));
}
return value;
}
/**
* Gets the property value.
*
* @param key the key
* @return the property value
*/
protected String getPropertyValue(String key) {
return System.getProperty(key);
}
/**
* Gets the property key.
*
* @param name the name
* @param attribute the attribute
* @return the property key
*/
protected String getPropertyKey(String name, String attribute) {
return getPropertyKey(getPropertyCategory(), name, attribute);
}
/**
* Gets the property key.
*
* @param category the category
* @param name the name
* @param attribute the attribute
* @return the property key
*/
private String getPropertyKey(String category, String name, String attribute) {
String result = getClass().getPackage().getName();
if (category != null) {
result += '.' + category;
}
if (name != null) {
result += '.' + name;
}
if (attribute != null) {
result += '.' + attribute;
} else {
throw new IllegalArgumentException("key cannot be null");
}
return result;
}
/**
* Reset.
*/
public void reset() {
// Not Implemented;
}
/**
* Gets the property category.
*
* @return the property category
*/
public String getPropertyCategory() {
return propertyCategory;
}
/**
* Sets the property category.
*
* @param propertyCategory the new property category
*/
public void setPropertyCategory(String propertyCategory) {
this.propertyCategory = propertyCategory;
}
}
| dougwm/psi-probe | core/src/main/java/psiprobe/beans/stats/listeners/AbstractStatsCollectionListener.java | Java | gpl-2.0 | 3,506 |
/*******************************************************************************
* UW SPF - The University of Washington Semantic Parsing Framework
* <p>
* Copyright (C) 2013 Yoav Artzi
* <p>
* 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.
* <p>
* 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.
* <p>
* 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 edu.uw.cs.lil.tiny.parser.ccg.model;
import java.io.Serializable;
import edu.uw.cs.lil.tiny.base.hashvector.IHashVector;
import edu.uw.cs.lil.tiny.base.hashvector.IHashVectorImmutable;
import edu.uw.cs.lil.tiny.ccg.lexicon.ILexiconImmutable;
import edu.uw.cs.lil.tiny.ccg.lexicon.LexicalEntry;
import edu.uw.cs.lil.tiny.data.IDataItem;
import edu.uw.cs.lil.tiny.parser.ccg.IParseStep;
/**
* Immutable parsing model.
*
* @author Yoav Artzi
* @param <DI>
* type of data item
* @param <MR>
* Type of semantics.
*/
public interface IModelImmutable<DI extends IDataItem<?>, MR> extends
Serializable {
/**
* Compute features for a given parsing step
*
* @param parseStep
* Parsing step to compute features for.
* @return
*/
IHashVector computeFeatures(IParseStep<MR> parseStep, DI dataItem);
/**
* Compute features for a given parsing step.
*
* @param parseStep
* Parsing step to compute features for.
* @param features
* Feature vector to load with features. The features will be
* added to the given vector.
* @return 'features' vector
*/
IHashVector computeFeatures(IParseStep<MR> parseStep, IHashVector features,
DI dataItem);
/**
* Compute features for a lexical item,
*
* @param lexicalEntry
* Lexical entry to compute features for.
* @return
*/
IHashVector computeFeatures(LexicalEntry<MR> lexicalEntry);
/**
* Compute feature for a lexical item.
*
* @param lexicalEntry
* Lexical entry to compute features for
* @param features
* Feature vector to load with features. The features will be
* added to the given vector.
* @return the 'features' vector
*/
IHashVector computeFeatures(LexicalEntry<MR> lexicalEntry,
IHashVector features);
IDataItemModel<MR> createDataItemModel(DI dataItem);
/** Return the lexicon of the model. The returned lexicon is immutable. */
ILexiconImmutable<MR> getLexicon();
/**
* @return Parameters vectors (immutable).
*/
IHashVectorImmutable getTheta();
/**
* Verified that the given weight vector is valid (i.e., doesn't try to
* update invalid feature weights).
*/
boolean isValidWeightVector(IHashVectorImmutable vector);
double score(IParseStep<MR> parseStep, DI dataItem);
double score(LexicalEntry<MR> entry);
}
| PriyankaKhante/nlp_spf | parser.ccg/src/edu/uw/cs/lil/tiny/parser/ccg/model/IModelImmutable.java | Java | gpl-2.0 | 3,378 |
/*
* Copyright (c) 1998-2008 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.marshal;
import com.caucho.quercus.env.Env;
import com.caucho.quercus.env.NullValue;
import com.caucho.quercus.env.Value;
public class JavaByteObjectArrayMarshal extends JavaArrayMarshal
{
public static final Marshal MARSHAL
= new JavaByteObjectArrayMarshal();
@Override
public Value unmarshal(Env env, Object value)
{
Byte []byteValue = (Byte []) value;
if (byteValue == null)
return NullValue.NULL;
byte []data = new byte[byteValue.length];
for (int i = 0; i < data.length; i++)
data[i] = byteValue[i];
return env.createBinaryBuilder(data);
}
@Override
protected int getMarshalingCostImpl(Value argValue)
{
if (argValue.isString()) {
if (argValue.isUnicode())
return Marshal.UNICODE_BYTE_OBJECT_ARRAY_COST;
else if (argValue.isBinary())
return Marshal.BINARY_BYTE_OBJECT_ARRAY_COST;
else
return Marshal.PHP5_BYTE_OBJECT_ARRAY_COST;
}
else if (argValue.isArray())
return Marshal.THREE;
else
return Marshal.FOUR;
}
@Override
public Class getExpectedClass()
{
return Byte[].class;
}
}
| moriyoshi/quercus-gae | src/main/java/com/caucho/quercus/marshal/JavaByteObjectArrayMarshal.java | Java | gpl-2.0 | 2,199 |
package com.aw.swing.mvp.cmp;
import com.aw.swing.mvp.binding.BindingComponent;
import javax.swing.*;
import java.awt.event.KeyListener;
import java.util.Iterator;
import java.util.List;
/**
* User: Julio Gonzales
* Date: 05-abr-2008
*/
public class ComponentGroup {
private List<JComponent> listOfComponents;
public ComponentGroup(List<JComponent> listOfComponents) {
this.listOfComponents = listOfComponents;
}
public void disable() {
for (Iterator<JComponent> jComponentIterator = listOfComponents.iterator(); jComponentIterator.hasNext();) {
JComponent jComponent = jComponentIterator.next();
BindingComponent bnd = (BindingComponent) jComponent.getClientProperty(BindingComponent.ATTR_BND);
bnd.setUIReadOnly(true);
}
}
public void enable() {
for (Iterator<JComponent> jComponentIterator = listOfComponents.iterator(); jComponentIterator.hasNext();) {
JComponent jComponent = jComponentIterator.next();
BindingComponent bnd = (BindingComponent) jComponent.getClientProperty(BindingComponent.ATTR_BND);
bnd.setUIReadOnly(false);
}
}
public List<JComponent> getListOfComponents() {
return listOfComponents;
}
public void setListOfComponents(List<JComponent> listOfComponents) {
this.listOfComponents = listOfComponents;
}
public void addKeyListener(KeyListener kl) {
for (Iterator<JComponent> jComponentIterator = listOfComponents.iterator(); jComponentIterator.hasNext();) {
JComponent component = jComponentIterator.next();
component.addKeyListener(kl);
}
}
}
| AlanGuerraQuispe/SisAtuxVenta | atux-jrcp/src/main/java/com/aw/swing/mvp/cmp/ComponentGroup.java | Java | gpl-2.0 | 1,750 |
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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.
*
* The Benchmark 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
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest07359")
public class BenchmarkTest07359 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
javax.servlet.http.Cookie[] cookies = request.getCookies();
String param = null;
boolean foundit = false;
if (cookies != null) {
for (javax.servlet.http.Cookie cookie : cookies) {
if (cookie.getName().equals("foo")) {
param = cookie.getValue();
foundit = true;
}
}
if (!foundit) {
// no cookie found in collection
param = "";
}
} else {
// no cookies
param = "";
}
String bar = new Test().doSomething(param);
try {
java.nio.file.Path path = java.nio.file.Paths.get(org.owasp.benchmark.helpers.Utils.testfileDir + bar);
java.io.InputStream is = java.nio.file.Files.newInputStream(path, java.nio.file.StandardOpenOption.READ);
} catch (Exception e) {
// OK to swallow any exception for now
// TODO: Fix this, if possible.
System.out.println("File exception caught and swallowed: " + e.getMessage());
}
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar;
String guess = "ABC";
char switchTarget = guess.charAt(2);
// Simple case statement that assigns param to bar on conditions 'A' or 'C'
switch (switchTarget) {
case 'A':
bar = param;
break;
case 'B':
bar = "bobs_your_uncle";
break;
case 'C':
case 'D':
bar = param;
break;
default:
bar = "bobs_your_uncle";
break;
}
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest07359.java | Java | gpl-2.0 | 3,082 |
/**
* OWASP Benchmark Project v1.2beta
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The OWASP Benchmark 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.
*
* The OWASP Benchmark 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.
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest01195")
public class BenchmarkTest01195 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String param = "";
java.util.Enumeration<String> headers = request.getHeaders("vector");
if (headers.hasMoreElements()) {
param = headers.nextElement(); // just grab first element
}
String bar = new Test().doSomething(param);
try {
double rand = java.security.SecureRandom.getInstance("SHA1PRNG").nextDouble();
String rememberMeKey = Double.toString(rand).substring(2); // Trim off the 0. at the front.
String user = "SafeDonna";
String fullClassName = this.getClass().getName();
String testCaseNumber = fullClassName.substring(fullClassName.lastIndexOf('.')+1+"BenchmarkTest".length());
user+= testCaseNumber;
String cookieName = "rememberMe" + testCaseNumber;
boolean foundUser = false;
javax.servlet.http.Cookie[] cookies = request.getCookies();
for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) {
javax.servlet.http.Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
foundUser = true;
}
}
}
if (foundUser) {
response.getWriter().println("Welcome back: " + user + "<br/>");
} else {
javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
rememberMe.setSecure(true);
request.getSession().setAttribute(cookieName, rememberMeKey);
response.addCookie(rememberMe);
response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName()
+ " whose value is: " + rememberMe.getValue() + "<br/>");
}
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing SecureRandom.nextDouble() - TestCase");
throw new ServletException(e);
}
response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextDouble() executed");
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar;
// Simple ? condition that assigns constant to bar on true condition
int num = 106;
bar = (7*18) + num > 200 ? "This_should_always_happen" : param;
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| ganncamp/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01195.java | Java | gpl-2.0 | 3,887 |
package br.com.mobilemind.veloster.orm.annotations;
/*
* #%L
* Mobile Mind - Veloster API
* %%
* Copyright (C) 2012 Mobile Mind Empresa de Tecnologia
* %%
* 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 java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @author Ricardo Bocchi
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface BatchSize {
int size() default 0;
}
| mobilemindtec/veloster | veloster-api/src/main/java/br/com/mobilemind/veloster/orm/annotations/BatchSize.java | Java | gpl-2.0 | 1,159 |
package com.cricketcraft.chisel.world;
import com.google.common.collect.Maps;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkGenerator;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.feature.WorldGenMinable;
import net.minecraftforge.fml.common.IWorldGenerator;
import java.util.Map;
import java.util.Random;
public class GeneratorChisel implements IWorldGenerator {
private World worldObj = Minecraft.getMinecraft().theWorld;
private class WorldGenInfo {
private int amount;
private int minY, maxY;
private double chance;
private WorldGenInfo(int amount, int minY, int maxY, double chance) {
this.amount = amount;
this.minY = minY;
this.maxY = maxY;
this.chance = chance;
}
}
public static final GeneratorChisel INSTANCE = new GeneratorChisel();
private final Map<WorldGenMinable, WorldGenInfo> map = Maps.newHashMap();
public void addFeature(IBlockState state, int count, int amount) {
addFeature(state, count, amount, 40, 128);
}
public void addFeature(IBlockState state, int count, int amount, int minY, int maxY) {
addFeature(state, count, amount, minY, maxY, 1);
}
public void addFeature(IBlockState state, int count, int amount, int minY, int maxY, double chance) {
map.put(new WorldGenMinable(state, count), new WorldGenInfo(amount, minY, maxY, chance));
}
protected void genStandardOre(WorldGenMinable gen, WorldGenInfo info, World world, Random random, int x, int z) {
for (int l = 0; l < info.amount; ++l) {
if (random.nextDouble() < info.chance) {
int avgX = x + random.nextInt(16);
int avgY = info.minY + random.nextInt(info.maxY - info.minY) + 1;
int avgZ = z + random.nextInt(16);
gen.generate(world, random, new BlockPos(avgX, avgY, avgZ));
}
}
}
@Override
public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider) {
for (WorldGenMinable gen : map.keySet()) {
genStandardOre(gen, map.get(gen), world, random, chunkX * 16, chunkZ * 16);
}
}
}
| Chisel-2/Chisel-3 | src/main/java/com/cricketcraft/chisel/world/GeneratorChisel.java | Java | gpl-2.0 | 2,212 |
package com.lami.tuomatuo.core.model.vo;
import com.lami.tuomatuo.core.model.User;
import com.lami.tuomatuo.core.model.UserProperty;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* Created by xjk on 2016/1/19.
*/
@Data
public class UserInfoVo {
private String imgUrl; // 头像 url
private String name;
private Long dynamicSeeTotal; // 所有动态看过的次数
private Integer sex; // 性别
private Long dynamicSum; // 该用户的动态数
private Long followSum; // 用户现在关注人数
private Long fansSum; // 用户粉丝数
private List<UserDynamicVo> userDynamicVoList = new ArrayList<UserDynamicVo>(); // 用户动态列表, 每页是10个
public UserInfoVo(){ }
public UserInfoVo(User user, UserProperty userProperty){
this.imgUrl = null;
this.name = user.getName();
this.dynamicSeeTotal = userProperty.getDynamicSeeTotal();
this.sex = userProperty.getSex();
this.dynamicSum = userProperty.getDynamicSum();
this.dynamicSeeTotal = userProperty.getDynamicSeeTotal();
this.followSum = userProperty.getFollowSum();
this.fansSum = userProperty.getFansSum();
}
}
| jackkiexu/tuomatuo | tuomatuo-core/src/main/java/com/lami/tuomatuo/core/model/vo/UserInfoVo.java | Java | gpl-2.0 | 1,217 |
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Utilities {
public static String ReadFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
public static void WriteToFile(String path, String text) throws IOException{
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(path), "utf-8"));
writer.write(text);
} finally {
writer.close();
}
}
}
| itzoy/ExpressionCalculator | ExpressionCalculator/src/Utilities.java | Java | gpl-2.0 | 744 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ssanalytics.snapshotplugin.io.dbConnection.dao.contract;
/**
*
* @author Robert
*/
public class NoSnapshotsException extends Exception {
public NoSnapshotsException(String s) {
super(s);
}
}
| christianbors/snapshot-plugin | src/main/java/org/ssanalytics/snapshotplugin/io/dbConnection/dao/contract/NoSnapshotsException.java | Java | gpl-2.0 | 324 |
/*
* Copyright (c) 2010, 2017, 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 javafx.scene.media;
import java.net.URI;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.net.URISyntaxException;
import javafx.beans.NamedArg;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.DoublePropertyBase;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.IntegerPropertyBase;
/**
* An <code>AudioClip</code> represents a segment of audio that can be played
* with minimal latency. Clips are loaded similarly to <code>Media</code>
* objects but have different behavior, for example, a <code>Media</code> cannot
* play itself. <code>AudioClip</code>s are also usable immediately. Playback
* behavior is fire and forget: once one of the play methods is called the only
* operable control is {@link #stop()}. An <code>AudioClip</code> may also be
* played multiple times simultaneously. To accomplish the same task using
* <code>Media</code> one would have to create a new <code>MediaPlayer</code>
* object for each sound played in parallel. <code>Media</code> objects are
* however better suited for long-playing sounds. This is primarily because
* <code>AudioClip</code> stores in memory the raw, uncompressed audio data for
* the entire sound, which can be quite large for long audio clips. A
* <code>MediaPlayer</code> will only have enough decompressed audio data
* pre-rolled in memory to play for a short amount of time so it is much more
* memory efficient for long clips, especially if they are compressed.
* <br>
* <p>Example usage:</p>
* <pre>{@code
* AudioClip plonkSound = new AudioClip("http://somehost/path/plonk.aiff");
* plonkSound.play();
* }</pre>
*
* @since JavaFX 2.0
*/
public final class AudioClip {
private String sourceURL;
private com.sun.media.jfxmedia.AudioClip audioClip;
/**
* Create an <code>AudioClip</code> loaded from the supplied source URL.
*
* @param source URL string from which to load the audio clip. This can be an
* HTTP, HTTPS, FILE or JAR source.
* @throws NullPointerException if the parameter is <code>null</code>.
* @throws IllegalArgumentException if the parameter violates
* <a href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>.
* @throws MediaException if there is some other problem loading the media.
*/
public AudioClip(@NamedArg("source") String source) {
URI srcURI = URI.create(source);
sourceURL = source;
try {
audioClip = com.sun.media.jfxmedia.AudioClip.load(srcURI);
} catch(URISyntaxException use) {
throw new IllegalArgumentException(use);
} catch(FileNotFoundException fnfe) {
throw new MediaException(MediaException.Type.MEDIA_UNAVAILABLE, fnfe.getMessage());
} catch(IOException ioe) {
throw new MediaException(MediaException.Type.MEDIA_INACCESSIBLE, ioe.getMessage());
} catch(com.sun.media.jfxmedia.MediaException me) {
throw new MediaException(MediaException.Type.MEDIA_UNSUPPORTED, me.getMessage());
}
}
/**
* Get the source URL used to create this <code>AudioClip</code>.
* @return source URL as provided to the constructor
*/
public String getSource() {
return sourceURL;
}
/**
* The relative volume level at which the clip is played. Valid range is 0.0
* (muted) to 1.0 (full volume). Values are clamped to this range internally
* so values outside this range will have no additional effect. Volume is
* controlled by attenuation, so values below 1.0 will reduce the sound
* level accordingly.
*/
private DoubleProperty volume;
/**
* Set the default volume level. The new setting will only take effect on
* subsequent plays.
* @see #volumeProperty()
* @param value new default volume level for this clip
*/
public final void setVolume(double value) {
volumeProperty().set(value);
}
/**
* Get the default volume level.
* @see #volumeProperty()
* @return the default volume level for this clip
*/
public final double getVolume() {
return (null == volume) ? 1.0 : volume.get();
}
public DoubleProperty volumeProperty() {
if (volume == null) {
volume = new DoublePropertyBase(1.0) {
@Override
protected void invalidated() {
if (null != audioClip) {
audioClip.setVolume(volume.get());
}
}
@Override
public Object getBean() {
return AudioClip.this;
}
@Override
public String getName() {
return "volume";
}
};
}
return volume;
}
/**
* The relative left and right volume levels of the clip.
* Valid range is -1.0 to 1.0 where -1.0 gives full volume to the left
* channel while muting the right channel, 0.0 gives full volume to both
* channels and 1.0 gives full volume to right channel and mutes the left
* channel. Values outside this range are clamped internally.
*/
private DoubleProperty balance;
/**
* Set the default balance level. The new value will only affect subsequent
* plays.
* @see #balanceProperty()
* @param balance new default balance
*/
public void setBalance(double balance) {
balanceProperty().set(balance);
}
/**
* Get the default balance level for this clip.
* @see #balanceProperty()
* @return the default balance for this clip
*/
public double getBalance() {
return (null != balance) ? balance.get() : 0.0;
}
public DoubleProperty balanceProperty() {
if (null == balance) {
balance = new DoublePropertyBase(0.0) {
@Override
protected void invalidated() {
if (null != audioClip) {
audioClip.setBalance(balance.get());
}
}
@Override
public Object getBean() {
return AudioClip.this;
}
@Override
public String getName() {
return "balance";
}
};
}
return balance;
}
/**
* The relative rate at which the clip is played. Valid range is 0.125
* (1/8 speed) to 8.0 (8x speed); values outside this range are clamped
* internally. Normal playback for a clip is 1.0; any other rate will affect
* pitch and duration accordingly.
*/
private DoubleProperty rate;
/**
* Set the default playback rate. The new value will only affect subsequent
* plays.
* @see #rateProperty()
* @param rate the new default playback rate
*/
public void setRate(double rate) {
rateProperty().set(rate);
}
/**
* Get the default playback rate.
* @see #rateProperty()
* @return default playback rate for this clip
*/
public double getRate() {
return (null != rate) ? rate.get() : 1.0;
}
public DoubleProperty rateProperty() {
if (null == rate) {
rate = new DoublePropertyBase(1.0) {
@Override
protected void invalidated() {
if (null != audioClip) {
audioClip.setPlaybackRate(rate.get());
}
}
@Override
public Object getBean() {
return AudioClip.this;
}
@Override
public String getName() {
return "rate";
}
};
}
return rate;
}
/**
* The relative "center" of the clip. A pan value of 0.0 plays
* the clip normally where a -1.0 pan shifts the clip entirely to the left
* channel and 1.0 shifts entirely to the right channel. Unlike balance this
* setting mixes both channels so neither channel loses data. Setting
* pan on a mono clip has the same effect as setting balance, but with a
* much higher cost in CPU overhead so this is not recommended for mono
* clips.
*/
private DoubleProperty pan;
/**
* Set the default pan value. The new value will only affect subsequent
* plays.
* @see #panProperty()
* @param pan the new default pan value
*/
public void setPan(double pan) {
panProperty().set(pan);
}
/**
* Get the default pan value.
* @see #panProperty()
* @return the default pan value for this clip
*/
public double getPan() {
return (null != pan) ? pan.get() : 0.0;
}
public DoubleProperty panProperty() {
if (null == pan) {
pan = new DoublePropertyBase(0.0) {
@Override
protected void invalidated() {
if (null != audioClip) {
audioClip.setPan(pan.get());
}
}
@Override
public Object getBean() {
return AudioClip.this;
}
@Override
public String getName() {
return "pan";
}
};
}
return pan;
}
/**
* The relative priority of the clip with respect to other clips. This value
* is used to determine which clips to remove when the maximum allowed number
* of clips is exceeded. The lower the priority, the more likely the
* clip is to be stopped and removed from the mixer channel it is occupying.
* Valid range is any integer; there are no constraints. The default priority
* is zero for all clips until changed. The number of simultaneous sounds
* that can be played is implementation- and possibly system-dependent.
*/
private IntegerProperty priority;
/**
* Set the default playback priority. The new value will only affect
* subsequent plays.
* @see #priorityProperty()
* @param priority the new default playback priority
*/
public void setPriority(int priority) {
priorityProperty().set(priority);
}
/**
* Get the default playback priority.
* @see #priorityProperty()
* @return the default playback priority of this clip
*/
public int getPriority() {
return (null != priority) ? priority.get() : 0;
}
public IntegerProperty priorityProperty() {
if (null == priority) {
priority = new IntegerPropertyBase(0) {
@Override
protected void invalidated() {
if (null != audioClip) {
audioClip.setPriority(priority.get());
}
}
@Override
public Object getBean() {
return AudioClip.this;
}
@Override
public String getName() {
return "priority";
}
};
}
return priority;
}
/**
* When {@link #cycleCountProperty cycleCount} is set to this value, the
* <code>AudioClip</code> will loop continuously until stopped. This value is
* synonymous with {@link MediaPlayer#INDEFINITE} and
* {@link javafx.animation.Animation#INDEFINITE}, these values may be used
* interchangeably.
*/
public static final int INDEFINITE = -1;
/**
* The number of times the clip will be played when {@link #play()}
* is called. A cycleCount of 1 plays exactly once, a cycleCount of 2
* plays twice and so on. Valid range is 1 or more, but setting this to
* {@link #INDEFINITE INDEFINITE} will cause the clip to continue looping
* until {@link #stop} is called.
*/
private IntegerProperty cycleCount;
/**
* Set the default cycle count. The new value will only affect subsequent
* plays.
* @see #cycleCountProperty()
* @param count the new default cycle count for this clip
*/
public void setCycleCount(int count) {
cycleCountProperty().set(count);
}
/**
* Get the default cycle count.
* @see #cycleCountProperty()
* @return the default cycleCount for this audio clip
*/
public int getCycleCount() {
return (null != cycleCount) ? cycleCount.get() : 1;
}
public IntegerProperty cycleCountProperty() {
if (null == cycleCount) {
cycleCount = new IntegerPropertyBase(1) {
@Override
protected void invalidated() {
if (null != audioClip) {
int value = cycleCount.get();
if (INDEFINITE != value) {
value = Math.max(1, value);
audioClip.setLoopCount(value - 1);
} else {
audioClip.setLoopCount(value); // INDEFINITE is the same there
}
}
}
@Override
public Object getBean() {
return AudioClip.this;
}
@Override
public String getName() {
return "cycleCount";
}
};
}
return cycleCount;
}
/**
* Play the <code>AudioClip</code> using all the default parameters.
*/
public void play() {
if (null != audioClip) {
audioClip.play();
}
}
/**
* Play the <code>AudioClip</code> using all the default parameters except volume.
* This method does not modify the clip's default parameters.
* @param volume the volume level at which to play the clip
*/
public void play(double volume) {
if (null != audioClip) {
audioClip.play(volume);
}
}
/**
* Play the <code>AudioClip</code> using the given parameters. Values outside
* the ranges as specified by their associated properties are clamped.
* This method does not modify the clip's default parameters.
*
* @param volume Volume level at which to play this clip. Valid volume range is
* 0.0 to 1.0, where 0.0 is effectively muted and 1.0 is full volume.
* @param balance Left/right balance or relative channel volumes for stereo
* effects.
* @param rate Playback rate multiplier. 1.0 will play at the normal
* rate while 2.0 will double the rate.
* @param pan Left/right shift to be applied to the clip. A pan value of
* -1.0 means full left channel, 1.0 means full right channel, 0.0 has no
* effect.
* @param priority Audio effect priority. Lower priority effects will be
* dropped first if too many effects are trying to play simultaneously.
*/
public void play(double volume, double balance, double rate, double pan, int priority) {
if (null != audioClip) {
audioClip.play(volume, balance, rate, pan, audioClip.loopCount(), priority);
}
}
/**
* Indicate whether this <code>AudioClip</code> is playing. If this returns true
* then <code>play()</code> has been called at least once and it is still playing.
* @return true if any mixer channel has this clip queued, false otherwise
*/
public boolean isPlaying() {
return null != audioClip && audioClip.isPlaying();
}
/**
* Immediately stop all playback of this <code>AudioClip</code>.
*/
public void stop() {
if (null != audioClip) {
audioClip.stop();
}
}
}
| teamfx/openjfx-10-dev-rt | modules/javafx.media/src/main/java/javafx/scene/media/AudioClip.java | Java | gpl-2.0 | 17,146 |
package sy.util.base;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5加密工具类
*
* @author 孙宇
*
*/
public class MD5Util {
public static void main(String[] args) {
String s = "孙宇";
System.out.println(md5(s));
}
/**
* md5加密
*
* @param str
* @return
*/
public static String md5(String str) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte[] byteDigest = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < byteDigest.length; offset++) {
i = byteDigest[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
// 32位加密
return buf.toString();
// 16位的加密
// return buf.toString().substring(8, 24);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
}
| lclsdu/CS | sshe/src/main/java/sy/util/base/MD5Util.java | Java | gpl-2.0 | 973 |
package it.unibas.silvio.erogatore;
import it.unibas.silvio.processor.ProcessorLog;
import it.unibas.silvio.util.CostantiCamel;
import it.unibas.silvio.modello.*;
import it.unibas.silvio.util.CostantiSilvio;
import it.unibas.silvio.util.SilvioUtil;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class DetourGestioneRispostaErogatore extends RouteBuilder{
private Log logger = LogFactory.getLog(this.getClass());
public static final String TIPO_RISPOSTA = "TIPO_RISPOSTA";
public static final String RISPOSTA_ACK = "RISPOSTA_ACK";
public static final String CREA_RISPOSTA = "CREA_RISPOSTA";
@Override
public void configure() throws Exception {
this.from(CostantiCamel.DETOUR_GESTIONE_RISPOSTA_EROGATORE)
.thread(ConfigurazioneStatico.getInstance().getThreadPool())
.process(new ProcessorLog(this.getClass()))
.process(new ProcessorDetourRisposta())
.choice().when(header(RISPOSTA_ACK).isEqualTo(true))
.to(CostantiCamel.RISPOSTA_ACK_EROGATORE)
.end()
.choice().when(header(CREA_RISPOSTA).isEqualTo(true))
.process(new ProcessorCreaMessaggio())
.to(CostantiCamel.ENRICHER_DATI_PARZIALI_COMPLETI_EROGATORE)
.end();
}
private class ProcessorCreaMessaggio implements Processor{
public void process(Exchange exchange) throws Exception {
Messaggio messaggioRichiesta = (Messaggio) exchange.getProperty(CostantiSilvio.MESSAGGIO_RICHIESTA);
Messaggio messaggioRisposta = new Messaggio();
messaggioRisposta.setTipo(Messaggio.INVIATO);
messaggioRisposta.setIstanzaOperation(messaggioRichiesta.getIstanzaOperation());
messaggioRisposta.setIstanzaPortType(messaggioRichiesta.getIstanzaPortType());
messaggioRisposta.setIdRelatesTo(messaggioRichiesta.getIdMessaggio());
messaggioRisposta.setChannelErogatore(messaggioRichiesta.getChannelErogatore());
messaggioRisposta.setIndirizzo(messaggioRichiesta.getIndirizzo());
messaggioRisposta.setParametriMessaggioRicevuto(messaggioRichiesta.getParametriMessaggioRicevuto());
exchange.setProperty(CostantiSilvio.MESSAGGIO_RISPOSTA, messaggioRisposta);
SilvioUtil.getSOAPHeaderList(exchange).clear();
}
}
private class ProcessorDetourRisposta implements Processor{
public void process(Exchange exchange) throws Exception {
Messaggio messaggio = (Messaggio) exchange.getProperty(CostantiSilvio.MESSAGGIO_RICHIESTA);
IstanzaOperation istanzaOperation = messaggio.getIstanzaOperation();
IstanzaPortType istanzaPortType = istanzaOperation.getIstanzaPortType();
if(istanzaOperation.isOneWay()){
exchange.getIn().setHeader(RISPOSTA_ACK, true);
logger.info("L'operation è one way. Ho salvato la richiesta e quindi posso sbloccare il fuitore");
return;
}
if(istanzaPortType.isErogazioneRisposta()){
exchange.getIn().setHeader(RISPOSTA_ACK, true);
logger.info("Ho ricevuto una risposta asincrona, l'ho salvate e quindi posso sbloccare l'erogatore");
return;
}
if(istanzaOperation.isAsincrono()){
logger.info("L'operation è ascinrona. Ho salvato la richiesta e quindi posso sbloccare il fuitore. Inoltre devo creare la risposta.");
exchange.getIn().setHeader(RISPOSTA_ACK, true);
}
exchange.getIn().setHeader(CREA_RISPOSTA, true);
}
}
}
| donatellosantoro/freESBee | silvio/src/it/unibas/silvio/erogatore/DetourGestioneRispostaErogatore.java | Java | gpl-2.0 | 3,939 |
/**
* 项目名: java-code-tutorials-nio-java
* 包名: net.fantesy84.server.aio
* 文件名: package-info.java
* Copy Right © 2016 Andronicus Ge
* 时间: 2016年1月7日
*/
/**
* @author Andronicus
* @since 2016年1月7日
*/
package net.fantesy84.server.aio; | fantesy84/java-code-tutorials | java-code-tutorials-nio/java-code-tutorials-nio-java/src/main/java/net/fantesy84/server/aio/package-info.java | Java | gpl-2.0 | 272 |
/*
* Copyright 2006-2021 The MZmine Development Team
*
* This file is part of MZmine.
*
* MZmine 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.
*
* MZmine 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 MZmine; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
package io.github.mzmine.datamodel;
import io.github.mzmine.util.maths.CenterFunction;
import io.github.mzmine.util.scans.SpectraMerging.MergingType;
import java.util.List;
public interface MergedMassSpectrum extends Scan {
/**
* @return A list of spectra used to create this merged spectrum
*/
List<MassSpectrum> getSourceSpectra();
/**
* @return The merging type this spectrum is based on.
*/
MergingType getMergingType();
/**
* @return The center function used to create this merged spectrum.
*/
CenterFunction getCenterFunction();
/**
*
* @return -1 to represent the artificial state of this spectrum.
*/
@Override
default int getScanNumber() {
return -1;
}
}
| mzmine/mzmine3 | src/main/java/io/github/mzmine/datamodel/MergedMassSpectrum.java | Java | gpl-2.0 | 1,507 |
/**
* Copyright 2014 Hans Beemsterboer
*
* This file is part of the TechyTax program.
*
* TechyTax 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.
*
* TechyTax 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 TechyTax; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.techytax.business.zk.calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.cxf.common.util.StringUtils;
import org.techytax.domain.BusinessCalendarEvent;
import org.techytax.domain.Project;
import org.techytax.jpa.dao.ProjectDao;
import org.techytax.zk.login.UserCredentialManager;
import org.zkoss.bind.BindUtils;
import org.zkoss.bind.Property;
import org.zkoss.bind.ValidationContext;
import org.zkoss.bind.Validator;
import org.zkoss.bind.annotation.AfterCompose;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.bind.validator.AbstractValidator;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zkplus.spring.SpringUtil;
import org.zkoss.zul.ListModelList;
public class CalendarEditorViewModel {
private BusinessCalendarEvent calendarEventData = new BusinessCalendarEvent();
@WireVariable
private ProjectDao projectDao;
private Project selectedProject;
private boolean visible = false;
@AfterCompose
public void initSetup() {
projectDao = (ProjectDao) SpringUtil.getBean("projectDao");
}
public BusinessCalendarEvent getCalendarEvent() {
return calendarEventData;
}
public ListModelList<Project> getProjects() {
try {
List<Project> projects = projectDao.findAll(UserCredentialManager.getUser());
for (Project project : projects) {
if (project.equals(calendarEventData.getProject())) {
selectedProject = project;
}
}
return new ListModelList<>(projects);
} catch (IllegalAccessException e) {
Executions.sendRedirect("login.zul");
}
return null;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
@Init
public void init() {
// subscribe a queue, listen to other controller
QueueUtil.lookupQueue().subscribe(new QueueListener());
}
private void startEditing(BusinessCalendarEvent calendarEventData) {
this.calendarEventData = calendarEventData;
visible = true;
// reload entire view-model data when going to edit
BindUtils.postNotifyChange(null, null, this, "*");
}
public boolean isAllDay(Date beginDate, Date endDate) {
int M_IN_DAY = 1000 * 60 * 60 * 24;
boolean allDay = false;
if (beginDate != null && endDate != null) {
long between = endDate.getTime() - beginDate.getTime();
allDay = between > M_IN_DAY;
}
return allDay;
}
public Validator getDateValidator() {
return new AbstractValidator() {
@Override
public void validate(ValidationContext ctx) {
Map<String, Property> formData = ctx.getProperties(ctx.getProperty().getValue());
Date beginDate = (Date) formData.get("beginDate").getValue();
Date endDate = (Date) formData.get("endDate").getValue();
if (beginDate == null) {
addInvalidMessage(ctx, "beginDate", "Begin date is empty");
}
if (endDate == null) {
addInvalidMessage(ctx, "endDate", "End date is empty");
}
if (beginDate != null && endDate != null && beginDate.compareTo(endDate) >= 0) {
addInvalidMessage(ctx, "endDate", "End date is before begin date");
}
}
};
}
@Command
@NotifyChange("visible")
public void cancel() {
QueueMessage message = new QueueMessage(QueueMessage.Type.CANCEL);
QueueUtil.lookupQueue().publish(message);
this.visible = false;
}
@Command
@NotifyChange("visible")
public void delete() {
QueueMessage message = new QueueMessage(QueueMessage.Type.DELETE, calendarEventData);
QueueUtil.lookupQueue().publish(message);
this.visible = false;
}
@Command
@NotifyChange("visible")
public void ok() {
if (selectedProject != null) {
calendarEventData.setProject(selectedProject);
}
QueueMessage message = new QueueMessage(QueueMessage.Type.OK, calendarEventData);
QueueUtil.lookupQueue().publish(message);
this.visible = false;
}
private class QueueListener implements EventListener<QueueMessage> {
@Override
public void onEvent(QueueMessage message) throws Exception {
if (QueueMessage.Type.EDIT.equals(message.getType())) {
CalendarEditorViewModel.this.startEditing((BusinessCalendarEvent) message.getData());
}
}
}
public Project getSelectedProject() {
return selectedProject;
}
@NotifyChange("calendarEvent")
public void setSelectedProject(Project selectedProject) {
this.selectedProject = selectedProject;
if (StringUtils.isEmpty(calendarEventData.getTitle())) {
calendarEventData.setContent(selectedProject.getCode());
}
calendarEventData.setBillable(true);
calendarEventData.setUnitsOfWork(8);
}
} | beemsoft/techytax | techytax-web/src/main/java/org/techytax/business/zk/calendar/CalendarEditorViewModel.java | Java | gpl-2.0 | 5,529 |
/**
*
*/
package com.tincent.demo.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import com.tincent.android.util.TXTimeUtil;
import com.tincent.demo.Constants;
import android.util.Log;
/**
* 调试工具类
*
* @author hui.wang
* @date 2015.3.18
*
*/
public class Debug {
private static final String TAG = "appdemo";
public static int lineNumber(Exception ex) {
return ex.getStackTrace()[0].getLineNumber();
}
public static String funcName(Exception ex) {
return ex.getStackTrace()[0].getMethodName();
}
public static String className(Exception ex) {
return ex.getStackTrace()[0].getClassName();
}
public static String fileName(Exception ex) {
return ex.getStackTrace()[0].getFileName();
}
/**
* Print log message <filename>: <line number> : <method name> : msg
*
* @param ex
* @param msg
*/
public static void o(Exception ex, String msg) {
if (Constants.DEBUG) {
Log.d(TAG, fileName(ex) + " : " + lineNumber(ex) + " : " + funcName(ex) + " : " + msg);
}
}
public static void o(Exception ex) {
if (Constants.DEBUG) {
Log.d(TAG, fileName(ex) + " : " + lineNumber(ex) + " : " + funcName(ex));
}
}
public static void o(String tag, String msg) {
if (Constants.DEBUG) {
Log.d(tag, msg);
}
}
public static void o(String tag, String msg, Throwable tr) {
if (Constants.DEBUG) {
Log.d(tag, msg, tr);
}
}
public static void dump(String msg) {
String filename = TXTimeUtil.convert2StringYMD(System.currentTimeMillis()) + ".log";
File log = new File(Constants.LOG_DIR, filename);
if (!log.exists()) {
try {
// 在指定的文件夹中创建文件
log.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
Debug.o(new Exception(), "log = " + log.toString());
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(log, true);
bw = new BufferedWriter(fw);
bw.write(TXTimeUtil.convert2String(System.currentTimeMillis()));
bw.newLine();
bw.write(msg);
bw.newLine();
bw.flush(); // 刷新该流的缓冲
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void dump(Exception ex) {
dump(ex.toString());
}
public static void dump(Exception ex, String msg) {
dump(fileName(ex) + " : " + lineNumber(ex) + " : " + funcName(ex) + " : " + msg);
}
}
| tincent/libtincent | appdemo/src/com/tincent/demo/util/Debug.java | Java | gpl-2.0 | 2,443 |
/* -*- java -*-
*
* This is sslfingerprint, an fingerprinting and security analysis tool
* for server ssl configurations.
*
* (C) 2010 Ulrich Kuehn <[email protected]>
*
* 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 net.ukuehn.sslfingerprint;
import java.io.*;
public class Debug {
public static final int Fingerprint = 0;
public static final int CollectSuites = 1;
public static final int CheckSSLv2 = 2;
public static final int SockInit = 3;
public static final int Certs = 4;
public static final int Communication = 8;
public static final int Protocol = 9;
public static final int Delay = 11;
public static final int CharEncoding = 12;
static private long debug = 0;
static Log log;
public static void set(long level) {
debug = level;
if (debug != 0) {
System.err.println("Setting debug level "+debug);
}
if (Debug.get(Debug.CharEncoding)) {
System.err.println("Debug: CharEncoding");
}
if (Debug.get(Debug.Delay)) {
System.err.println("Debug: Delay");
}
if (Debug.get(Debug.Communication)) {
System.err.println("Debug: Communication");
}
if (Debug.get(Debug.Protocol)) {
System.err.println("Debug: Protocol");
}
if (Debug.get(Debug.Certs)) {
System.err.println("Debug: Certificates");
}
if (Debug.get(Debug.SockInit)) {
System.err.println("Debug: SockInit");
}
if (Debug.get(Debug.CheckSSLv2)) {
System.err.println("Debug: CheckSSLv2");
}
if (Debug.get(Debug.CollectSuites)) {
System.err.println("Debug: CollectSuites");
}
if (Debug.get(Debug.Fingerprint)) {
System.err.println("Debug: Fingerprint");
}
}
public static boolean get(int what) {
return ((debug & (1 << what)) != 0);
}
} | ukuehn/sslfp | src/net/ukuehn/sslfingerprint/Debug.java | Java | gpl-2.0 | 2,390 |
package juego.razas.construcciones;
public abstract class ConstruccionHabitable extends Construccion {
protected int capacidadDeHabitantes;
public ConstruccionHabitable() {
super();
this.capacidadDeHabitantes = 5;
}
public int capacidadDeHabitantes() {
return this.capacidadDeHabitantes;
}
@Override
public boolean puedeHospedarUnidades() { return true; }
}
| algo3-2015-fiuba/algocraft | src/juego/razas/construcciones/ConstruccionHabitable.java | Java | gpl-2.0 | 380 |
package org.dnacorp.xencyclopedia.converter.bob.point;
/**
* Created by Claudio "Dna" Bonesana
* Date: 09.09.2014 20:55.
*/
public class PNode {
public char id;
public PNode next = null;
public PNode child = null;
}
| cbonesana/XEncyclopedia | BOBConverter/src/org/dnacorp/xencyclopedia/converter/bob/point/PNode.java | Java | gpl-2.0 | 234 |
/*
* Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.security.x509;
import java.lang.reflect.*;
import java.io.IOException;
import java.security.PrivilegedExceptionAction;
import java.security.AccessController;
import java.security.Principal;
import java.util.*;
import sun.security.util.*;
import javax.security.auth.x500.X500Principal;
/**
* Note: As of 1.4, the public class,
* javax.security.auth.x500.X500Principal,
* should be used when parsing, generating, and comparing X.500 DNs.
* This class contains other useful methods for checking name constraints
* and retrieving DNs by keyword.
*
* <p> X.500 names are used to identify entities, such as those which are
* identified by X.509 certificates. They are world-wide, hierarchical,
* and descriptive. Entities can be identified by attributes, and in
* some systems can be searched for according to those attributes.
* <p>
* The ASN.1 for this is:
* <pre>
* GeneralName ::= CHOICE {
* ....
* directoryName [4] Name,
* ....
* Name ::= CHOICE {
* RDNSequence }
*
* RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
*
* RelativeDistinguishedName ::=
* SET OF AttributeTypeAndValue
*
* AttributeTypeAndValue ::= SEQUENCE {
* type AttributeType,
* value AttributeValue }
*
* AttributeType ::= OBJECT IDENTIFIER
*
* AttributeValue ::= ANY DEFINED BY AttributeType
* ....
* DirectoryString ::= CHOICE {
* teletexString TeletexString (SIZE (1..MAX)),
* printableString PrintableString (SIZE (1..MAX)),
* universalString UniversalString (SIZE (1..MAX)),
* utf8String UTF8String (SIZE (1.. MAX)),
* bmpString BMPString (SIZE (1..MAX)) }
* </pre>
* <p>
* This specification requires only a subset of the name comparison
* functionality specified in the X.500 series of specifications. The
* requirements for conforming implementations are as follows:
* <ol TYPE=a>
* <li>attribute values encoded in different types (e.g.,
* PrintableString and BMPString) may be assumed to represent
* different strings;
* <p>
* <li>attribute values in types other than PrintableString are case
* sensitive (this permits matching of attribute values as binary
* objects);
* <p>
* <li>attribute values in PrintableString are not case sensitive
* (e.g., "Marianne Swanson" is the same as "MARIANNE SWANSON"); and
* <p>
* <li>attribute values in PrintableString are compared after
* removing leading and trailing white space and converting internal
* substrings of one or more consecutive white space characters to a
* single space.
* </ol>
* <p>
* These name comparison rules permit a certificate user to validate
* certificates issued using languages or encodings unfamiliar to the
* certificate user.
* <p>
* In addition, implementations of this specification MAY use these
* comparison rules to process unfamiliar attribute types for name
* chaining. This allows implementations to process certificates with
* unfamiliar attributes in the issuer name.
* <p>
* Note that the comparison rules defined in the X.500 series of
* specifications indicate that the character sets used to encode data
* in distinguished names are irrelevant. The characters themselves are
* compared without regard to encoding. Implementations of the profile
* are permitted to use the comparison algorithm defined in the X.500
* series. Such an implementation will recognize a superset of name
* matches recognized by the algorithm specified above.
* <p>
* Note that instances of this class are immutable.
*
* @author David Brownell
* @author Amit Kapoor
* @author Hemma Prafullchandra
* @see GeneralName
* @see GeneralNames
* @see GeneralNameInterface
*/
public class X500Name implements GeneralNameInterface, Principal {
private String dn; // roughly RFC 1779 DN, or null
private String rfc1779Dn; // RFC 1779 compliant DN, or null
private String rfc2253Dn; // RFC 2253 DN, or null
private String canonicalDn; // canonical RFC 2253 DN or null
private RDN[] names; // RDNs (never null)
private X500Principal x500Principal;
private byte[] encoded;
// cached immutable list of the RDNs and all the AVAs
private volatile List<RDN> rdnList;
private volatile List<AVA> allAvaList;
/**
* Constructs a name from a conventionally formatted string, such
* as "CN=Dave, OU=JavaSoft, O=Sun Microsystems, C=US".
* (RFC 1779, 2253, or 4514 style).
*
* @param dname the X.500 Distinguished Name
*/
public X500Name(String dname) throws IOException {
this(dname, Collections.<String, String>emptyMap());
}
/**
* Constructs a name from a conventionally formatted string, such
* as "CN=Dave, OU=JavaSoft, O=Sun Microsystems, C=US".
* (RFC 1779, 2253, or 4514 style).
*
* @param dname the X.500 Distinguished Name
* @param keywordMap an additional keyword/OID map
*/
public X500Name(String dname, Map<String, String> keywordMap)
throws IOException {
parseDN(dname, keywordMap);
}
/**
* Constructs a name from a string formatted according to format.
* Currently, the formats DEFAULT and RFC2253 are supported.
* DEFAULT is the default format used by the X500Name(String)
* constructor. RFC2253 is the format strictly according to RFC2253
* without extensions.
*
* @param dname the X.500 Distinguished Name
* @param format the specified format of the String DN
*/
public X500Name(String dname, String format) throws IOException {
if (dname == null) {
throw new NullPointerException("Name must not be null");
}
if (format.equalsIgnoreCase("RFC2253")) {
parseRFC2253DN(dname);
} else if (format.equalsIgnoreCase("DEFAULT")) {
parseDN(dname, Collections.<String, String>emptyMap());
} else {
throw new IOException("Unsupported format " + format);
}
}
/**
* Constructs a name from fields common in enterprise application
* environments.
*
* <P><EM><STRONG>NOTE:</STRONG> The behaviour when any of
* these strings contain characters outside the ASCII range
* is unspecified in currently relevant standards.</EM>
*
* @param commonName common name of a person, e.g. "Vivette Davis"
* @param organizationUnit small organization name, e.g. "Purchasing"
* @param organizationName large organization name, e.g. "Onizuka, Inc."
* @param country two letter country code, e.g. "CH"
*/
public X500Name(String commonName, String organizationUnit,
String organizationName, String country)
throws IOException {
names = new RDN[4];
/*
* NOTE: it's only on output that little-endian
* ordering is used.
*/
names[3] = new RDN(1);
names[3].assertion[0] = new AVA(commonName_oid,
new DerValue(commonName));
names[2] = new RDN(1);
names[2].assertion[0] = new AVA(orgUnitName_oid,
new DerValue(organizationUnit));
names[1] = new RDN(1);
names[1].assertion[0] = new AVA(orgName_oid,
new DerValue(organizationName));
names[0] = new RDN(1);
names[0].assertion[0] = new AVA(countryName_oid,
new DerValue(country));
}
/**
* Constructs a name from fields common in Internet application
* environments.
*
* <P><EM><STRONG>NOTE:</STRONG> The behaviour when any of
* these strings contain characters outside the ASCII range
* is unspecified in currently relevant standards.</EM>
*
* @param commonName common name of a person, e.g. "Vivette Davis"
* @param organizationUnit small organization name, e.g. "Purchasing"
* @param organizationName large organization name, e.g. "Onizuka, Inc."
* @param localityName locality (city) name, e.g. "Palo Alto"
* @param stateName state name, e.g. "California"
* @param country two letter country code, e.g. "CH"
*/
public X500Name(String commonName, String organizationUnit,
String organizationName, String localityName,
String stateName, String country)
throws IOException {
names = new RDN[6];
/*
* NOTE: it's only on output that little-endian
* ordering is used.
*/
names[5] = new RDN(1);
names[5].assertion[0] = new AVA(commonName_oid,
new DerValue(commonName));
names[4] = new RDN(1);
names[4].assertion[0] = new AVA(orgUnitName_oid,
new DerValue(organizationUnit));
names[3] = new RDN(1);
names[3].assertion[0] = new AVA(orgName_oid,
new DerValue(organizationName));
names[2] = new RDN(1);
names[2].assertion[0] = new AVA(localityName_oid,
new DerValue(localityName));
names[1] = new RDN(1);
names[1].assertion[0] = new AVA(stateName_oid,
new DerValue(stateName));
names[0] = new RDN(1);
names[0].assertion[0] = new AVA(countryName_oid,
new DerValue(country));
}
/**
* Constructs a name from an array of relative distinguished names
*
* @param rdnArray array of relative distinguished names
* @throws IOException on error
*/
public X500Name(RDN[] rdnArray) throws IOException {
if (rdnArray == null) {
names = new RDN[0];
} else {
names = rdnArray.clone();
for (int i = 0; i < names.length; i++) {
if (names[i] == null) {
throw new IOException("Cannot create an X500Name");
}
}
}
}
/**
* Constructs a name from an ASN.1 encoded value. The encoding
* of the name in the stream uses DER (a BER/1 subset).
*
* @param value a DER-encoded value holding an X.500 name.
*/
public X500Name(DerValue value) throws IOException {
//Note that toDerInputStream uses only the buffer (data) and not
//the tag, so an empty SEQUENCE (OF) will yield an empty DerInputStream
this(value.toDerInputStream());
}
/**
* Constructs a name from an ASN.1 encoded input stream. The encoding
* of the name in the stream uses DER (a BER/1 subset).
*
* @param in DER-encoded data holding an X.500 name.
*/
public X500Name(DerInputStream in) throws IOException {
parseDER(in);
}
/**
* Constructs a name from an ASN.1 encoded byte array.
*
* @param name DER-encoded byte array holding an X.500 name.
*/
public X500Name(byte[] name) throws IOException {
DerInputStream in = new DerInputStream(name);
parseDER(in);
}
/**
* Return an immutable List of all RDNs in this X500Name.
*/
public List<RDN> rdns() {
List<RDN> list = rdnList;
if (list == null) {
list = Collections.unmodifiableList(Arrays.asList(names));
rdnList = list;
}
return list;
}
/**
* Return the number of RDNs in this X500Name.
*/
public int size() {
return names.length;
}
/**
* Return an immutable List of the AVAs contained in all the
* RDNs of this X500Name.
*/
public List<AVA> allAvas() {
List<AVA> list = allAvaList;
if (list == null) {
list = new ArrayList<>();
for (int i = 0; i < names.length; i++) {
list.addAll(names[i].avas());
}
}
return list;
}
/**
* Return the total number of AVAs contained in all the RDNs of
* this X500Name.
*/
public int avaSize() {
return allAvas().size();
}
/**
* Return whether this X500Name is empty. An X500Name is not empty
* if it has at least one RDN containing at least one AVA.
*/
public boolean isEmpty() {
int n = names.length;
if (n == 0) {
return true;
}
for (int i = 0; i < n; i++) {
if (names[i].assertion.length != 0) {
return false;
}
}
return true;
}
/**
* Calculates a hash code value for the object. Objects
* which are equal will also have the same hashcode.
*/
public int hashCode() {
return getRFC2253CanonicalName().hashCode();
}
/**
* Compares this name with another, for equality.
*
* @return true iff the names are identical.
*/
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof X500Name == false) {
return false;
}
X500Name other = (X500Name)obj;
// if we already have the canonical forms, compare now
if ((this.canonicalDn != null) && (other.canonicalDn != null)) {
return this.canonicalDn.equals(other.canonicalDn);
}
// quick check that number of RDNs and AVAs match before canonicalizing
int n = this.names.length;
if (n != other.names.length) {
return false;
}
for (int i = 0; i < n; i++) {
RDN r1 = this.names[i];
RDN r2 = other.names[i];
if (r1.assertion.length != r2.assertion.length) {
return false;
}
}
// definite check via canonical form
String thisCanonical = this.getRFC2253CanonicalName();
String otherCanonical = other.getRFC2253CanonicalName();
return thisCanonical.equals(otherCanonical);
}
/*
* Returns the name component as a Java string, regardless of its
* encoding restrictions.
*/
private String getString(DerValue attribute) throws IOException {
if (attribute == null)
return null;
String value = attribute.getAsString();
if (value == null)
throw new IOException("not a DER string encoding, "
+ attribute.tag);
else
return value;
}
/**
* Return type of GeneralName.
*/
public int getType() {
return (GeneralNameInterface.NAME_DIRECTORY);
}
/**
* Returns a "Country" name component. If more than one
* such attribute exists, the topmost one is returned.
*
* @return "C=" component of the name, if any.
*/
public String getCountry() throws IOException {
DerValue attr = findAttribute(countryName_oid);
return getString(attr);
}
/**
* Returns an "Organization" name component. If more than
* one such attribute exists, the topmost one is returned.
*
* @return "O=" component of the name, if any.
*/
public String getOrganization() throws IOException {
DerValue attr = findAttribute(orgName_oid);
return getString(attr);
}
/**
* Returns an "Organizational Unit" name component. If more
* than one such attribute exists, the topmost one is returned.
*
* @return "OU=" component of the name, if any.
*/
public String getOrganizationalUnit() throws IOException {
DerValue attr = findAttribute(orgUnitName_oid);
return getString(attr);
}
/**
* Returns a "Common Name" component. If more than one such
* attribute exists, the topmost one is returned.
*
* @return "CN=" component of the name, if any.
*/
public String getCommonName() throws IOException {
DerValue attr = findAttribute(commonName_oid);
return getString(attr);
}
/**
* Returns a "Locality" name component. If more than one
* such component exists, the topmost one is returned.
*
* @return "L=" component of the name, if any.
*/
public String getLocality() throws IOException {
DerValue attr = findAttribute(localityName_oid);
return getString(attr);
}
/**
* Returns a "State" name component. If more than one
* such component exists, the topmost one is returned.
*
* @return "S=" component of the name, if any.
*/
public String getState() throws IOException {
DerValue attr = findAttribute(stateName_oid);
return getString(attr);
}
/**
* Returns a "Domain" name component. If more than one
* such component exists, the topmost one is returned.
*
* @return "DC=" component of the name, if any.
*/
public String getDomain() throws IOException {
DerValue attr = findAttribute(DOMAIN_COMPONENT_OID);
return getString(attr);
}
/**
* Returns a "DN Qualifier" name component. If more than one
* such component exists, the topmost one is returned.
*
* @return "DNQ=" component of the name, if any.
*/
public String getDNQualifier() throws IOException {
DerValue attr = findAttribute(DNQUALIFIER_OID);
return getString(attr);
}
/**
* Returns a "Surname" name component. If more than one
* such component exists, the topmost one is returned.
*
* @return "SURNAME=" component of the name, if any.
*/
public String getSurname() throws IOException {
DerValue attr = findAttribute(SURNAME_OID);
return getString(attr);
}
/**
* Returns a "Given Name" name component. If more than one
* such component exists, the topmost one is returned.
*
* @return "GIVENNAME=" component of the name, if any.
*/
public String getGivenName() throws IOException {
DerValue attr = findAttribute(GIVENNAME_OID);
return getString(attr);
}
/**
* Returns an "Initials" name component. If more than one
* such component exists, the topmost one is returned.
*
* @return "INITIALS=" component of the name, if any.
*/
public String getInitials() throws IOException {
DerValue attr = findAttribute(INITIALS_OID);
return getString(attr);
}
/**
* Returns a "Generation Qualifier" name component. If more than one
* such component exists, the topmost one is returned.
*
* @return "GENERATION=" component of the name, if any.
*/
public String getGeneration() throws IOException {
DerValue attr = findAttribute(GENERATIONQUALIFIER_OID);
return getString(attr);
}
/**
* Returns an "IP address" name component. If more than one
* such component exists, the topmost one is returned.
*
* @return "IP=" component of the name, if any.
*/
public String getIP() throws IOException {
DerValue attr = findAttribute(ipAddress_oid);
return getString(attr);
}
/**
* Returns a string form of the X.500 distinguished name.
* The format of the string is from RFC 1779. The returned string
* may contain non-standardised keywords for more readability
* (keywords from RFCs 1779, 2253, and 5280).
*/
public String toString() {
if (dn == null) {
generateDN();
}
return dn;
}
/**
* Returns a string form of the X.500 distinguished name
* using the algorithm defined in RFC 1779. Only standard attribute type
* keywords defined in RFC 1779 are emitted.
*/
public String getRFC1779Name() {
return getRFC1779Name(Collections.<String, String>emptyMap());
}
/**
* Returns a string form of the X.500 distinguished name
* using the algorithm defined in RFC 1779. Attribute type
* keywords defined in RFC 1779 are emitted, as well as additional
* keywords contained in the OID/keyword map.
*/
public String getRFC1779Name(Map<String, String> oidMap)
throws IllegalArgumentException {
if (oidMap.isEmpty()) {
// return cached result
if (rfc1779Dn != null) {
return rfc1779Dn;
} else {
rfc1779Dn = generateRFC1779DN(oidMap);
return rfc1779Dn;
}
}
return generateRFC1779DN(oidMap);
}
/**
* Returns a string form of the X.500 distinguished name
* using the algorithm defined in RFC 2253. Only standard attribute type
* keywords defined in RFC 2253 are emitted.
*/
public String getRFC2253Name() {
return getRFC2253Name(Collections.<String, String>emptyMap());
}
/**
* Returns a string form of the X.500 distinguished name
* using the algorithm defined in RFC 2253. Attribute type
* keywords defined in RFC 2253 are emitted, as well as additional
* keywords contained in the OID/keyword map.
*/
public String getRFC2253Name(Map<String, String> oidMap) {
/* check for and return cached name */
if (oidMap.isEmpty()) {
if (rfc2253Dn != null) {
return rfc2253Dn;
} else {
rfc2253Dn = generateRFC2253DN(oidMap);
return rfc2253Dn;
}
}
return generateRFC2253DN(oidMap);
}
private String generateRFC2253DN(Map<String, String> oidMap) {
/*
* Section 2.1 : if the RDNSequence is an empty sequence
* the result is the empty or zero length string.
*/
if (names.length == 0) {
return "";
}
/*
* 2.1 (continued) : Otherwise, the output consists of the string
* encodings of each RelativeDistinguishedName in the RDNSequence
* (according to 2.2), starting with the last element of the sequence
* and moving backwards toward the first.
*
* The encodings of adjoining RelativeDistinguishedNames are separated
* by a comma character (',' ASCII 44).
*/
StringBuilder fullname = new StringBuilder(48);
for (int i = names.length - 1; i >= 0; i--) {
if (i < names.length - 1) {
fullname.append(',');
}
fullname.append(names[i].toRFC2253String(oidMap));
}
return fullname.toString();
}
public String getRFC2253CanonicalName() {
/* check for and return cached name */
if (canonicalDn != null) {
return canonicalDn;
}
/*
* Section 2.1 : if the RDNSequence is an empty sequence
* the result is the empty or zero length string.
*/
if (names.length == 0) {
canonicalDn = "";
return canonicalDn;
}
/*
* 2.1 (continued) : Otherwise, the output consists of the string
* encodings of each RelativeDistinguishedName in the RDNSequence
* (according to 2.2), starting with the last element of the sequence
* and moving backwards toward the first.
*
* The encodings of adjoining RelativeDistinguishedNames are separated
* by a comma character (',' ASCII 44).
*/
StringBuilder fullname = new StringBuilder(48);
for (int i = names.length - 1; i >= 0; i--) {
if (i < names.length - 1) {
fullname.append(',');
}
fullname.append(names[i].toRFC2253String(true));
}
canonicalDn = fullname.toString();
return canonicalDn;
}
/**
* Returns the value of toString(). This call is needed to
* implement the java.security.Principal interface.
*/
public String getName() { return toString(); }
/**
* Find the first instance of this attribute in a "top down"
* search of all the attributes in the name.
*/
private DerValue findAttribute(ObjectIdentifier attribute) {
if (names != null) {
for (int i = 0; i < names.length; i++) {
DerValue value = names[i].findAttribute(attribute);
if (value != null) {
return value;
}
}
}
return null;
}
/**
* Find the most specific ("last") attribute of the given
* type.
*/
public DerValue findMostSpecificAttribute(ObjectIdentifier attribute) {
if (names != null) {
for (int i = names.length - 1; i >= 0; i--) {
DerValue value = names[i].findAttribute(attribute);
if (value != null) {
return value;
}
}
}
return null;
}
/****************************************************************/
private void parseDER(DerInputStream in) throws IOException {
//
// X.500 names are a "SEQUENCE OF" RDNs, which means zero or
// more and order matters. We scan them in order, which
// conventionally is big-endian.
//
DerValue[] nameseq = null;
byte[] derBytes = in.toByteArray();
try {
nameseq = in.getSequence(5);
} catch (IOException ioe) {
if (derBytes == null) {
nameseq = null;
} else {
DerValue derVal = new DerValue(DerValue.tag_Sequence,
derBytes);
derBytes = derVal.toByteArray();
nameseq = new DerInputStream(derBytes).getSequence(5);
}
}
if (nameseq == null) {
names = new RDN[0];
} else {
names = new RDN[nameseq.length];
for (int i = 0; i < nameseq.length; i++) {
names[i] = new RDN(nameseq[i]);
}
}
}
/**
* Encodes the name in DER-encoded form.
*
* @deprecated Use encode() instead
* @param out where to put the DER-encoded X.500 name
*/
@Deprecated
public void emit(DerOutputStream out) throws IOException {
encode(out);
}
/**
* Encodes the name in DER-encoded form.
*
* @param out where to put the DER-encoded X.500 name
*/
public void encode(DerOutputStream out) throws IOException {
DerOutputStream tmp = new DerOutputStream();
for (int i = 0; i < names.length; i++) {
names[i].encode(tmp);
}
out.write(DerValue.tag_Sequence, tmp);
}
/**
* Returned the encoding as an uncloned byte array. Callers must
* guarantee that they neither modify it not expose it to untrusted
* code.
*/
public byte[] getEncodedInternal() throws IOException {
if (encoded == null) {
DerOutputStream out = new DerOutputStream();
DerOutputStream tmp = new DerOutputStream();
for (int i = 0; i < names.length; i++) {
names[i].encode(tmp);
}
out.write(DerValue.tag_Sequence, tmp);
encoded = out.toByteArray();
}
return encoded;
}
/**
* Gets the name in DER-encoded form.
*
* @return the DER encoded byte array of this name.
*/
public byte[] getEncoded() throws IOException {
return getEncodedInternal().clone();
}
/*
* Parses a Distinguished Name (DN) in printable representation.
*
* According to RFC 1779, RDNs in a DN are separated by comma.
* The following examples show both methods of quoting a comma, so that it
* is not considered a separator:
*
* O="Sue, Grabbit and Runn" or
* O=Sue\, Grabbit and Runn
*
* This method can parse RFC 1779, 2253 or 4514 DNs and non-standard 5280
* keywords. Additional keywords can be specified in the keyword/OID map.
*/
private void parseDN(String input, Map<String, String> keywordMap)
throws IOException {
if (input == null || input.length() == 0) {
names = new RDN[0];
return;
}
List<RDN> dnVector = new ArrayList<>();
int dnOffset = 0;
int rdnEnd;
String rdnString;
int quoteCount = 0;
String dnString = input;
int searchOffset = 0;
int nextComma = dnString.indexOf(',');
int nextSemiColon = dnString.indexOf(';');
while (nextComma >=0 || nextSemiColon >=0) {
if (nextSemiColon < 0) {
rdnEnd = nextComma;
} else if (nextComma < 0) {
rdnEnd = nextSemiColon;
} else {
rdnEnd = Math.min(nextComma, nextSemiColon);
}
quoteCount += countQuotes(dnString, searchOffset, rdnEnd);
/*
* We have encountered an RDN delimiter (comma or a semicolon).
* If the comma or semicolon in the RDN under consideration is
* preceded by a backslash (escape), or by a double quote, it
* is part of the RDN. Otherwise, it is used as a separator, to
* delimit the RDN under consideration from any subsequent RDNs.
*/
if (rdnEnd >= 0 && quoteCount != 1 &&
!escaped(rdnEnd, searchOffset, dnString)) {
/*
* Comma/semicolon is a separator
*/
rdnString = dnString.substring(dnOffset, rdnEnd);
// Parse RDN, and store it in vector
RDN rdn = new RDN(rdnString, keywordMap);
dnVector.add(rdn);
// Increase the offset
dnOffset = rdnEnd + 1;
// Set quote counter back to zero
quoteCount = 0;
}
searchOffset = rdnEnd + 1;
nextComma = dnString.indexOf(',', searchOffset);
nextSemiColon = dnString.indexOf(';', searchOffset);
}
// Parse last or only RDN, and store it in vector
rdnString = dnString.substring(dnOffset);
RDN rdn = new RDN(rdnString, keywordMap);
dnVector.add(rdn);
/*
* Store the vector elements as an array of RDNs
* NOTE: It's only on output that little-endian ordering is used.
*/
Collections.reverse(dnVector);
names = dnVector.toArray(new RDN[dnVector.size()]);
}
private void parseRFC2253DN(String dnString) throws IOException {
if (dnString.length() == 0) {
names = new RDN[0];
return;
}
List<RDN> dnVector = new ArrayList<>();
int dnOffset = 0;
String rdnString;
int searchOffset = 0;
int rdnEnd = dnString.indexOf(',');
while (rdnEnd >=0) {
/*
* We have encountered an RDN delimiter (comma).
* If the comma in the RDN under consideration is
* preceded by a backslash (escape), it
* is part of the RDN. Otherwise, it is used as a separator, to
* delimit the RDN under consideration from any subsequent RDNs.
*/
if (rdnEnd > 0 && !escaped(rdnEnd, searchOffset, dnString)) {
/*
* Comma is a separator
*/
rdnString = dnString.substring(dnOffset, rdnEnd);
// Parse RDN, and store it in vector
RDN rdn = new RDN(rdnString, "RFC2253");
dnVector.add(rdn);
// Increase the offset
dnOffset = rdnEnd + 1;
}
searchOffset = rdnEnd + 1;
rdnEnd = dnString.indexOf(',', searchOffset);
}
// Parse last or only RDN, and store it in vector
rdnString = dnString.substring(dnOffset);
RDN rdn = new RDN(rdnString, "RFC2253");
dnVector.add(rdn);
/*
* Store the vector elements as an array of RDNs
* NOTE: It's only on output that little-endian ordering is used.
*/
Collections.reverse(dnVector);
names = dnVector.toArray(new RDN[dnVector.size()]);
}
/*
* Counts double quotes in string.
* Escaped quotes are ignored.
*/
static int countQuotes(String string, int from, int to) {
int count = 0;
for (int i = from; i < to; i++) {
if ((string.charAt(i) == '"' && i == from) ||
(string.charAt(i) == '"' && string.charAt(i-1) != '\\')) {
count++;
}
}
return count;
}
private static boolean escaped
(int rdnEnd, int searchOffset, String dnString) {
if (rdnEnd == 1 && dnString.charAt(rdnEnd - 1) == '\\') {
// case 1:
// \,
return true;
} else if (rdnEnd > 1 && dnString.charAt(rdnEnd - 1) == '\\' &&
dnString.charAt(rdnEnd - 2) != '\\') {
// case 2:
// foo\,
return true;
} else if (rdnEnd > 1 && dnString.charAt(rdnEnd - 1) == '\\' &&
dnString.charAt(rdnEnd - 2) == '\\') {
// case 3:
// foo\\\\\,
int count = 0;
rdnEnd--; // back up to last backSlash
while (rdnEnd >= searchOffset) {
if (dnString.charAt(rdnEnd) == '\\') {
count++; // count consecutive backslashes
}
rdnEnd--;
}
// if count is odd, then rdnEnd is escaped
return (count % 2) != 0 ? true : false;
} else {
return false;
}
}
/*
* Dump the printable form of a distinguished name. Each relative
* name is separated from the next by a ",", and assertions in the
* relative names have "label=value" syntax.
*
* Uses RFC 1779 syntax (i.e. little-endian, comma separators)
*/
private void generateDN() {
if (names.length == 1) {
dn = names[0].toString();
return;
}
StringBuilder sb = new StringBuilder(48);
if (names != null) {
for (int i = names.length - 1; i >= 0; i--) {
if (i != names.length - 1) {
sb.append(", ");
}
sb.append(names[i].toString());
}
}
dn = sb.toString();
}
/*
* Dump the printable form of a distinguished name. Each relative
* name is separated from the next by a ",", and assertions in the
* relative names have "label=value" syntax.
*
* Uses RFC 1779 syntax (i.e. little-endian, comma separators)
* Valid keywords from RFC 1779 are used. Additional keywords can be
* specified in the OID/keyword map.
*/
private String generateRFC1779DN(Map<String, String> oidMap) {
if (names.length == 1) {
return names[0].toRFC1779String(oidMap);
}
StringBuilder sb = new StringBuilder(48);
if (names != null) {
for (int i = names.length - 1; i >= 0; i--) {
if (i != names.length - 1) {
sb.append(", ");
}
sb.append(names[i].toRFC1779String(oidMap));
}
}
return sb.toString();
}
/****************************************************************/
/*
* Maybe return a preallocated OID, to reduce storage costs
* and speed recognition of common X.500 attributes.
*/
static ObjectIdentifier intern(ObjectIdentifier oid) {
ObjectIdentifier interned = internedOIDs.get(oid);
if (interned != null) {
return interned;
}
internedOIDs.put(oid, oid);
return oid;
}
private static final Map<ObjectIdentifier,ObjectIdentifier> internedOIDs
= new HashMap<ObjectIdentifier,ObjectIdentifier>();
/*
* Selected OIDs from X.520
* Includes all those specified in RFC 5280 as MUST or SHOULD
* be recognized
*/
private static final int commonName_data[] = { 2, 5, 4, 3 };
private static final int SURNAME_DATA[] = { 2, 5, 4, 4 };
private static final int SERIALNUMBER_DATA[] = { 2, 5, 4, 5 };
private static final int countryName_data[] = { 2, 5, 4, 6 };
private static final int localityName_data[] = { 2, 5, 4, 7 };
private static final int stateName_data[] = { 2, 5, 4, 8 };
private static final int streetAddress_data[] = { 2, 5, 4, 9 };
private static final int orgName_data[] = { 2, 5, 4, 10 };
private static final int orgUnitName_data[] = { 2, 5, 4, 11 };
private static final int title_data[] = { 2, 5, 4, 12 };
private static final int GIVENNAME_DATA[] = { 2, 5, 4, 42 };
private static final int INITIALS_DATA[] = { 2, 5, 4, 43 };
private static final int GENERATIONQUALIFIER_DATA[] = { 2, 5, 4, 44 };
private static final int DNQUALIFIER_DATA[] = { 2, 5, 4, 46 };
private static final int ipAddress_data[] = { 1, 3, 6, 1, 4, 1, 42, 2, 11, 2, 1 };
private static final int DOMAIN_COMPONENT_DATA[] =
{ 0, 9, 2342, 19200300, 100, 1, 25 };
private static final int userid_data[] =
{ 0, 9, 2342, 19200300, 100, 1, 1 };
public static final ObjectIdentifier commonName_oid;
public static final ObjectIdentifier countryName_oid;
public static final ObjectIdentifier localityName_oid;
public static final ObjectIdentifier orgName_oid;
public static final ObjectIdentifier orgUnitName_oid;
public static final ObjectIdentifier stateName_oid;
public static final ObjectIdentifier streetAddress_oid;
public static final ObjectIdentifier title_oid;
public static final ObjectIdentifier DNQUALIFIER_OID;
public static final ObjectIdentifier SURNAME_OID;
public static final ObjectIdentifier GIVENNAME_OID;
public static final ObjectIdentifier INITIALS_OID;
public static final ObjectIdentifier GENERATIONQUALIFIER_OID;
public static final ObjectIdentifier ipAddress_oid;
public static final ObjectIdentifier DOMAIN_COMPONENT_OID;
public static final ObjectIdentifier userid_oid;
public static final ObjectIdentifier SERIALNUMBER_OID;
static {
/** OID for the "CN=" attribute, denoting a person's common name. */
commonName_oid = intern(ObjectIdentifier.newInternal(commonName_data));
/** OID for the "SERIALNUMBER=" attribute, denoting a serial number for.
a name. Do not confuse with PKCS#9 issuerAndSerialNumber or the
certificate serial number. */
SERIALNUMBER_OID = intern(ObjectIdentifier.newInternal(SERIALNUMBER_DATA));
/** OID for the "C=" attribute, denoting a country. */
countryName_oid = intern(ObjectIdentifier.newInternal(countryName_data));
/** OID for the "L=" attribute, denoting a locality (such as a city) */
localityName_oid = intern(ObjectIdentifier.newInternal(localityName_data));
/** OID for the "O=" attribute, denoting an organization name */
orgName_oid = intern(ObjectIdentifier.newInternal(orgName_data));
/** OID for the "OU=" attribute, denoting an organizational unit name */
orgUnitName_oid = intern(ObjectIdentifier.newInternal(orgUnitName_data));
/** OID for the "S=" attribute, denoting a state (such as Delaware) */
stateName_oid = intern(ObjectIdentifier.newInternal(stateName_data));
/** OID for the "STREET=" attribute, denoting a street address. */
streetAddress_oid = intern(ObjectIdentifier.newInternal(streetAddress_data));
/** OID for the "T=" attribute, denoting a person's title. */
title_oid = intern(ObjectIdentifier.newInternal(title_data));
/** OID for the "DNQUALIFIER=" or "DNQ=" attribute, denoting DN
disambiguating information.*/
DNQUALIFIER_OID = intern(ObjectIdentifier.newInternal(DNQUALIFIER_DATA));
/** OID for the "SURNAME=" attribute, denoting a person's surname.*/
SURNAME_OID = intern(ObjectIdentifier.newInternal(SURNAME_DATA));
/** OID for the "GIVENNAME=" attribute, denoting a person's given name.*/
GIVENNAME_OID = intern(ObjectIdentifier.newInternal(GIVENNAME_DATA));
/** OID for the "INITIALS=" attribute, denoting a person's initials.*/
INITIALS_OID = intern(ObjectIdentifier.newInternal(INITIALS_DATA));
/** OID for the "GENERATION=" attribute, denoting Jr., II, etc.*/
GENERATIONQUALIFIER_OID =
intern(ObjectIdentifier.newInternal(GENERATIONQUALIFIER_DATA));
/*
* OIDs from other sources which show up in X.500 names we
* expect to deal with often
*/
/** OID for "IP=" IP address attributes, used with SKIP. */
ipAddress_oid = intern(ObjectIdentifier.newInternal(ipAddress_data));
/*
* Domain component OID from RFC 1274, RFC 2247, RFC 5280
*/
/*
* OID for "DC=" domain component attributes, used with DNS names in DN
* format
*/
DOMAIN_COMPONENT_OID =
intern(ObjectIdentifier.newInternal(DOMAIN_COMPONENT_DATA));
/** OID for "UID=" denoting a user id, defined in RFCs 1274 & 2798. */
userid_oid = intern(ObjectIdentifier.newInternal(userid_data));
}
/**
* Return constraint type:<ul>
* <li>NAME_DIFF_TYPE = -1: input name is different type from this name
* (i.e. does not constrain)
* <li>NAME_MATCH = 0: input name matches this name
* <li>NAME_NARROWS = 1: input name narrows this name
* <li>NAME_WIDENS = 2: input name widens this name
* <li>NAME_SAME_TYPE = 3: input name does not match or narrow this name,
& but is same type
* </ul>. These results are used in checking NameConstraints during
* certification path verification.
*
* @param inputName to be checked for being constrained
* @returns constraint type above
* @throws UnsupportedOperationException if name is not exact match, but
* narrowing and widening are not supported for this name type.
*/
public int constrains(GeneralNameInterface inputName)
throws UnsupportedOperationException {
int constraintType;
if (inputName == null) {
constraintType = NAME_DIFF_TYPE;
} else if (inputName.getType() != NAME_DIRECTORY) {
constraintType = NAME_DIFF_TYPE;
} else { // type == NAME_DIRECTORY
X500Name inputX500 = (X500Name)inputName;
if (inputX500.equals(this)) {
constraintType = NAME_MATCH;
} else if (inputX500.names.length == 0) {
constraintType = NAME_WIDENS;
} else if (this.names.length == 0) {
constraintType = NAME_NARROWS;
} else if (inputX500.isWithinSubtree(this)) {
constraintType = NAME_NARROWS;
} else if (isWithinSubtree(inputX500)) {
constraintType = NAME_WIDENS;
} else {
constraintType = NAME_SAME_TYPE;
}
}
return constraintType;
}
/**
* Compares this name with another and determines if
* it is within the subtree of the other. Useful for
* checking against the name constraints extension.
*
* @return true iff this name is within the subtree of other.
*/
private boolean isWithinSubtree(X500Name other) {
if (this == other) {
return true;
}
if (other == null) {
return false;
}
if (other.names.length == 0) {
return true;
}
if (this.names.length == 0) {
return false;
}
if (names.length < other.names.length) {
return false;
}
for (int i = 0; i < other.names.length; i++) {
if (!names[i].equals(other.names[i])) {
return false;
}
}
return true;
}
/**
* Return subtree depth of this name for purposes of determining
* NameConstraints minimum and maximum bounds and for calculating
* path lengths in name subtrees.
*
* @returns distance of name from root
* @throws UnsupportedOperationException if not supported for this name type
*/
public int subtreeDepth() throws UnsupportedOperationException {
return names.length;
}
/**
* Return lowest common ancestor of this name and other name
*
* @param other another X500Name
* @return X500Name of lowest common ancestor; null if none
*/
public X500Name commonAncestor(X500Name other) {
if (other == null) {
return null;
}
int otherLen = other.names.length;
int thisLen = this.names.length;
if (thisLen == 0 || otherLen == 0) {
return null;
}
int minLen = (thisLen < otherLen) ? thisLen: otherLen;
//Compare names from highest RDN down the naming tree
//Note that these are stored in RDN[0]...
int i=0;
for (; i < minLen; i++) {
if (!names[i].equals(other.names[i])) {
if (i == 0) {
return null;
} else {
break;
}
}
}
//Copy matching RDNs into new RDN array
RDN[] ancestor = new RDN[i];
for (int j=0; j < i; j++) {
ancestor[j] = names[j];
}
X500Name commonAncestor = null;
try {
commonAncestor = new X500Name(ancestor);
} catch (IOException ioe) {
return null;
}
return commonAncestor;
}
/**
* Constructor object for use by asX500Principal().
*/
private static final Constructor<X500Principal> principalConstructor;
/**
* Field object for use by asX500Name().
*/
private static final Field principalField;
/**
* Retrieve the Constructor and Field we need for reflective access
* and make them accessible.
*/
static {
PrivilegedExceptionAction<Object[]> pa =
new PrivilegedExceptionAction<>() {
public Object[] run() throws Exception {
Class<X500Principal> pClass = X500Principal.class;
Class<?>[] args = new Class<?>[] { X500Name.class };
Constructor<X500Principal> cons = pClass.getDeclaredConstructor(args);
cons.setAccessible(true);
Field field = pClass.getDeclaredField("thisX500Name");
field.setAccessible(true);
return new Object[] {cons, field};
}
};
try {
Object[] result = AccessController.doPrivileged(pa);
@SuppressWarnings("unchecked")
Constructor<X500Principal> constr =
(Constructor<X500Principal>)result[0];
principalConstructor = constr;
principalField = (Field)result[1];
} catch (Exception e) {
throw new InternalError("Could not obtain X500Principal access", e);
}
}
/**
* Get an X500Principal backed by this X500Name.
*
* Note that we are using privileged reflection to access the hidden
* package private constructor in X500Principal.
*/
public X500Principal asX500Principal() {
if (x500Principal == null) {
try {
Object[] args = new Object[] {this};
x500Principal = principalConstructor.newInstance(args);
} catch (Exception e) {
throw new RuntimeException("Unexpected exception", e);
}
}
return x500Principal;
}
/**
* Get the X500Name contained in the given X500Principal.
*
* Note that the X500Name is retrieved using reflection.
*/
public static X500Name asX500Name(X500Principal p) {
try {
X500Name name = (X500Name)principalField.get(p);
name.x500Principal = p;
return name;
} catch (Exception e) {
throw new RuntimeException("Unexpected exception", e);
}
}
}
| shelan/jdk9-mirror | jdk/src/java.base/share/classes/sun/security/x509/X500Name.java | Java | gpl-2.0 | 49,496 |
/*****************************************************************************
* Web3d.org Copyright (c) 2001 - 2006
* Java Source
*
* This source is licensed under the GNU LGPL v2.1
* Please read http://www.gnu.org/copyleft/lgpl.html for more information
*
* This software comes with the standard NO WARRANTY disclaimer for any
* purpose. Use it at your own risk. If there's a problem you get to fix it.
*
****************************************************************************/
package org.web3d.util;
// Original License terms from the Apache project
/*
* Copyright 2002-2004 The Apache Software Foundation.
*
* 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.
*/
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/**
* <p>Provides XML entity utilities.</p>
*
* This code has been copied from the jakarta commons project from an Apache license.
* It has been modified to just support XML escaping.
*
* @see <a href="http://hotwired.lycos.com/webmonkey/reference/special_characters/">ISO Entities</a>
*
* @author <a href="mailto:[email protected]">Alexander Day Chaffee</a>
* @author <a href="mailto:[email protected]">Gary Gregory</a>
* @author Alan Hudson
*
* @version $Revision: 1.3 $
*/
public class XMLTools {
private static final String[][] BASIC_ARRAY = {
{"quot", "34"}, // " - double-quote
{"amp", "38"}, // & - ampersand
{"lt", "60"}, // < - less-than
{"gt", "62"}, // > - greater-than
};
private static final String[][] APOS_ARRAY = {
{"apos", "39"}, // XML apostrophe
};
/**
* <p>The set of entities supported by standard XML.</p>
*/
public static final XMLTools XML;
static {
XML = new XMLTools();
XML.addEntities(BASIC_ARRAY);
XML.addEntities(APOS_ARRAY);
}
static interface EntityMap {
void add(String name, int value);
String name(int value);
int value(String name);
}
static class PrimitiveEntityMap implements EntityMap {
private Map mapNameToValue = new HashMap();
private IntHashMap mapValueToName = new IntHashMap();
public void add(String name, int value) {
mapNameToValue.put(name, new Integer(value));
mapValueToName.put(value, name);
}
public String name(int value) {
return (String) mapValueToName.get(value);
}
public int value(String name) {
Object value = mapNameToValue.get(name);
if (value == null) {
return -1;
}
return ((Integer) value).intValue();
}
}
static abstract class MapIntMap implements XMLTools.EntityMap {
protected Map mapNameToValue;
protected Map mapValueToName;
public void add(String name, int value) {
mapNameToValue.put(name, new Integer(value));
mapValueToName.put(new Integer(value), name);
}
public String name(int value) {
return (String) mapValueToName.get(new Integer(value));
}
public int value(String name) {
Object value = mapNameToValue.get(name);
if (value == null) {
return -1;
}
return ((Integer) value).intValue();
}
}
static class HashEntityMap extends MapIntMap {
public HashEntityMap() {
mapNameToValue = new HashMap();
mapValueToName = new HashMap();
}
}
static class TreeEntityMap extends MapIntMap {
public TreeEntityMap() {
mapNameToValue = new TreeMap();
mapValueToName = new TreeMap();
}
}
static class LookupEntityMap extends PrimitiveEntityMap {
private String[] lookupTable;
private int LOOKUP_TABLE_SIZE = 256;
public String name(int value) {
if (value < LOOKUP_TABLE_SIZE) {
return lookupTable()[value];
}
return super.name(value);
}
private String[] lookupTable() {
if (lookupTable == null) {
createLookupTable();
}
return lookupTable;
}
private void createLookupTable() {
lookupTable = new String[LOOKUP_TABLE_SIZE];
for (int i = 0; i < LOOKUP_TABLE_SIZE; ++i) {
lookupTable[i] = super.name(i);
}
}
}
static class ArrayEntityMap implements EntityMap {
protected int growBy = 100;
protected int size = 0;
protected String[] names;
protected int[] values;
public ArrayEntityMap() {
names = new String[growBy];
values = new int[growBy];
}
public ArrayEntityMap(int growBy) {
this.growBy = growBy;
names = new String[growBy];
values = new int[growBy];
}
public void add(String name, int value) {
ensureCapacity(size + 1);
names[size] = name;
values[size] = value;
size++;
}
protected void ensureCapacity(int capacity) {
if (capacity > names.length) {
int newSize = Math.max(capacity, size + growBy);
String[] newNames = new String[newSize];
System.arraycopy(names, 0, newNames, 0, size);
names = newNames;
int[] newValues = new int[newSize];
System.arraycopy(values, 0, newValues, 0, size);
values = newValues;
}
}
public String name(int value) {
for (int i = 0; i < size; ++i) {
if (values[i] == value) {
return names[i];
}
}
return null;
}
public int value(String name) {
for (int i = 0; i < size; ++i) {
if (names[i].equals(name)) {
return values[i];
}
}
return -1;
}
}
static class BinaryEntityMap extends ArrayEntityMap {
public BinaryEntityMap() {
}
public BinaryEntityMap(int growBy) {
super(growBy);
}
// based on code in java.util.Arrays
private int binarySearch(int key) {
int low = 0;
int high = size - 1;
while (low <= high) {
int mid = (low + high) >> 1;
int midVal = values[mid];
if (midVal < key) {
low = mid + 1;
} else if (midVal > key) {
high = mid - 1;
} else {
return mid; // key found
}
}
return -(low + 1); // key not found.
}
public void add(String name, int value) {
ensureCapacity(size + 1);
int insertAt = binarySearch(value);
if (insertAt > 0) {
return; // note: this means you can't insert the same value twice
}
insertAt = -(insertAt + 1); // binarySearch returns it negative and off-by-one
System.arraycopy(values, insertAt, values, insertAt + 1, size - insertAt);
values[insertAt] = value;
System.arraycopy(names, insertAt, names, insertAt + 1, size - insertAt);
names[insertAt] = name;
size++;
}
public String name(int value) {
int index = binarySearch(value);
if (index < 0) {
return null;
}
return names[index];
}
}
// package scoped for testing
EntityMap map = new XMLTools.LookupEntityMap();
public void addEntities(String[][] entityArray) {
for (int i = 0; i < entityArray.length; ++i) {
addEntity(entityArray[i][0], Integer.parseInt(entityArray[i][1]));
}
}
public void addEntity(String name, int value) {
map.add(name, value);
}
public String entityName(int value) {
return map.name(value);
}
public int entityValue(String name) {
return map.value(name);
}
/**
* <p>Escapes the characters in a <code>String</code>.</p>
*
* <p>For example, if you have called addEntity("foo", 0xA1),
* escape("\u00A1") will return "&foo;"</p>
*
* @param str The <code>String</code> to escape.
* @return A new escaped <code>String</code>.
*/
public String escape(String str) {
//todo: rewrite to use a Writer
StringBuffer buf = new StringBuffer(str.length() * 2);
int i;
for (i = 0; i < str.length(); ++i) {
char ch = str.charAt(i);
String entityName = this.entityName(ch);
if (entityName == null) {
if (ch > 0x7F) {
int intValue = ch;
buf.append("&#");
buf.append(intValue);
buf.append(';');
} else {
buf.append(ch);
}
} else {
buf.append('&');
buf.append(entityName);
buf.append(';');
}
}
return buf.toString();
}
/**
* <p>Unescapes the entities in a <code>String</code>.</p>
*
* <p>For example, if you have called addEntity("foo", 0xA1),
* unescape("&foo;") will return "\u00A1"</p>
*
* @param str The <code>String</code> to escape.
* @return A new escaped <code>String</code>.
*/
public String unescape(String str) {
StringBuffer buf = new StringBuffer(str.length());
int i;
for (i = 0; i < str.length(); ++i) {
char ch = str.charAt(i);
if (ch == '&') {
int semi = str.indexOf(';', i + 1);
if (semi == -1) {
buf.append(ch);
continue;
}
String entityName = str.substring(i + 1, semi);
int entityValue;
if (entityName.length() == 0) {
entityValue = -1;
} else if (entityName.charAt(0) == '#') {
if (entityName.length() == 1) {
entityValue = -1;
} else {
char charAt1 = entityName.charAt(1);
try {
if (charAt1 == 'x' || charAt1=='X') {
entityValue = Integer.valueOf(entityName.substring(2), 16).intValue();
} else {
entityValue = Integer.parseInt(entityName.substring(1));
}
} catch (NumberFormatException ex) {
entityValue = -1;
}
}
} else {
entityValue = this.entityValue(entityName);
}
if (entityValue == -1) {
buf.append('&');
buf.append(entityName);
buf.append(';');
} else {
buf.append((char) (entityValue));
}
i = semi;
} else {
buf.append(ch);
}
}
return buf.toString();
}
}
| Norkart/NK-VirtualGlobe | Xj3D/src/java/org/web3d/util/XMLTools.java | Java | gpl-2.0 | 12,140 |
// **********************************************************************
//
// Generated by the ORBacus IDL to Java Translator
//
// Copyright (c) 2000
// Object Oriented Concepts, Inc.
// Billerica, MA, USA
//
// All Rights Reserved
//
// **********************************************************************
// Version: 4.0.5
package edu.iris.Fissures.IfNetwork;
//
// IDL:iris.edu/Fissures/IfNetwork/NetworkMgr:1.0
//
/**
* The NetworkMgr defines the Network Manager
**/
public interface NetworkMgr extends NetworkMgrOperations,
NetworkDC,
org.omg.CORBA.portable.IDLEntity
{
}
| crotwell/fissuresIDL | src/main/java/edu/iris/Fissures/IfNetwork/NetworkMgr.java | Java | gpl-2.0 | 660 |
package cartho_03.nasa;
public class Daemon extends Thread {
public Cell[] table;
public Object[] system_state;
public Daemon(Cell[] table, Object[] system_state) {
super();
this.table = table;
this.system_state = system_state;
}
public void run() {
int N = 42;
while (true) {
atomic {
if (table[N].achieved && system_state[N] != table[N].value)
issueWarning();
}
}
}
private void issueWarning() {
throw new RuntimeException("PANIC!!!");
}
}
| joaomlourenco/DeTraMA | HL5_tests/src/cartho_03/nasa/Daemon.atom.java | Java | gpl-2.0 | 485 |
package com.ag.controls.viewflow;
public interface FlowIndicator extends ViewFlow.ViewSwitchListener {
/**
* Set the current ViewFlow. This method is called by the ViewFlow when the
* FlowIndicator is attached to it.
*
* @param view
*/
public void setViewFlow(ViewFlow view);
/**
* The scroll position has been changed. A FlowIndicator may implement this
* method to reflect the current position
*
* @param h
* @param v
* @param oldh
* @param oldv
*/
public void onScrolled(int h, int v, int oldh, int oldv);
} | ZhanJohn/AG_Modules | ag_controls/src/main/java/com/ag/controls/viewflow/FlowIndicator.java | Java | gpl-2.0 | 597 |
package net.sf.egonet.web.panel;
import java.util.ArrayList;
import java.util.TreeMap;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;
public class MapEditorPanel<K,V> extends Panel {
protected TreeMap<K,V> map;
private PanelContainer pairEditorContainer;
private String heading, subEditorHeading;
private ArrayList<K> keys;
private ArrayList<V> valueOptions;
public MapEditorPanel(String id, String heading, String subEditorHeading, TreeMap<K,V> map,
ArrayList<K> keys, ArrayList<V> valueOptions)
{
super(id);
this.map = map;
this.heading = heading;
this.subEditorHeading = subEditorHeading;
this.keys = keys;
this.valueOptions = valueOptions;
build();
}
///////////////////////////////////////////////
// Expect to override these three methods. //
///////////////////////////////////////////////
protected String showKey(K key) {
return key+"";
}
protected String showValue(V value) {
return value == null ? "" : value+"";
}
protected void mapChanged() {
}
///////////////////////////////////////////////
private void build() {
add(new Label("heading",heading));
add(new ListView("pairs", new PropertyModel(this,"keys"))
{
public void populateItem(ListItem item) {
final K key = (K) item.getModelObject();
Link pairEditLink = new Link("pairEditLink") {
public void onClick() {
editPair(key);
}
};
pairEditLink.add(new Label("key",showKey(key)));
pairEditLink.add(new Label("value",showValue(map.get(key))));
item.add(pairEditLink);
}
});
pairEditorContainer = new PanelContainer("pairEditorContainer");
add(pairEditorContainer);
}
private void editPair(final K key) {
pairEditorContainer.changePanel(
new SingleSelectionPanel<V>("panel",
subEditorHeading.replaceAll("\\$\\$", showKey(key)),
valueOptions) {
public void action(V newValue) {
map.put(key, newValue);
MapEditorPanel.this.mapChanged();
}
public String show(V value) {
return showValue(value);
}
});
}
public ArrayList<K> getKeys() {
return keys;
}
}
| ericlavigne/egoweb | src/net/sf/egonet/web/panel/MapEditorPanel.java | Java | gpl-2.0 | 2,336 |
/*
* Copyright (c) 2007 Agile-Works
* All rights reserved.
*
* This software is the confidential and proprietary information of
* Agile-Works. ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with Agile-Works.
*/
package com.aw.core.dao.bean;
import java.lang.annotation.*;
/**
* Soporte para mapeo de beans a DB (por Hibernate)
*
* @see com.aw.core.dao.DAOBean
* <p/>
* User: JCM
* Date: 15/10/2007
*/
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DAOSqlColumn {
/**
* Nombre de la columna en la BD
* Nota: El bean debe estar marcado con {@link @DAOSqlTable()}
*/
String value();
}
| AlanGuerraQuispe/SisAtuxVenta | atux-dao/src/main/java/com/aw/core/dao/bean/DAOSqlColumn.java | Java | gpl-2.0 | 851 |
package servlet;
public class Teacher {
private String name;
/**
* Set methods for teacher
*/
public boolean setName(String name){
this.name = name;
return true;
}
public String getName(){
return name;
}
}
| HurinHall/Friend | src/servlet/Teacher.java | Java | gpl-2.0 | 229 |
package com.moriah.acme.entities;
import java.util.Date;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.apache.commons.lang.builder.ToStringBuilder;
import com.moriah.acme.utils.DateAdapter;
@Entity
@Table(name = "acme_gds", schema = "acme_space@cassandra-pu")
public class AcmeGds {
@Id
@Column(name = "gds_id")
private UUID gdsId;
@Column(name = "gds_path")
private String gdsPath;
@Column(name = "gds_name")
private String gdsName;
@Column(name = "gds_type")
private String gdsType;
@Column(name = "gds_desc")
private String gdsDesc;
@Column(name = "status")
private String status;
@Column(name = "create_time")
private Date createTime;
@Column(name = "create_user")
private String createUser;
@Column(name = "update_time")
private Date updateTime;
@Column(name = "update_user")
private String updateUser;
public UUID getGdsId() {
return gdsId;
}
public void setGdsId(UUID gdsId) {
this.gdsId = gdsId;
}
public String getGdsPath() {
return gdsPath;
}
public void setGdsPath(String gdsPath) {
this.gdsPath = gdsPath;
}
public String getGdsName() {
return gdsName;
}
public void setGdsName(String gdsName) {
this.gdsName = gdsName;
}
public String getGdsType() {
return gdsType;
}
public void setGdsType(String gdsType) {
this.gdsType = gdsType;
}
public String getGdsDesc() {
return gdsDesc;
}
public void setGdsDesc(String gdsDesc) {
this.gdsDesc = gdsDesc;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@XmlJavaTypeAdapter(DateAdapter.class)
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getCreateUser() {
return createUser;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
@XmlJavaTypeAdapter(DateAdapter.class)
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getUpdateUser() {
return updateUser;
}
public void setUpdateUser(String updateUser) {
this.updateUser = updateUser;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
| leejiahao/ACME | ACME_WEB/ACME/src/main/java/com/moriah/acme/entities/AcmeGds.java | Java | gpl-2.0 | 2,709 |
package unalcol.optimization.testbed.real.lsgo_benchmark;
/*
* Copyright (c) 2009 Thomas Weise for NICAL
* http://www.it-weise.de/
* [email protected]
*
* GNU LESSER GENERAL PUBLIC LICENSE (Version 2.1, February 1999)
*/
/**
* <p>
* The Single-group Shifted and m-rotated Rastrigin�s Function: F5.
* </p>
* <p>
* This function is not <warning>not threadsafe</warning> because it uses
* internal temporary variables. Therefore, you should always use each
* instance of this function for one single {#link java.lang.Thread} only.
* You may clone or serialize function instances to use multiple threads.
* <p>
*
* @author Thomas Weise
*/
public final class F5 extends ShiftedPermutatedRotatedFunction {
/** the serial version id */
private static final long serialVersionUID = 1;
/** the maximum value */
public static final double MAX = 5d;
/** the minimum value */
public static final double MIN = (-MAX);
/**
* Create a new Single-group Shifted and m-rotated Rastrigin�s Function
*
* @param o
* the shifted global optimum
* @param p
* the permutation vector
* @param m
* the rotation matrix
*/
public F5(final double[] o, final int[] p, final double[] m) {
super(o, p, m, MIN, MAX);
}
/**
* Create a default instance of F5.
*
* @param r
* the randomizer to use
*/
public F5(final Randomizer r) {
this(r.createShiftVector(Defaults.DEFAULT_DIM, MIN, MAX),//
r.createPermVector(Defaults.DEFAULT_DIM),//
r.createRotMatrix1D(Defaults.DEFAULT_M));//
}
/**
* Create a default instance of F5.
*/
public F5() {
this(Defaults.getRandomizer(F5.class));
}
/**
* Compute the value of the elliptic function. This function takes into
* consideration only the first {{@link #getDimension()} elements of the
* candidate vector.
*
* @param x
* the candidate solution vector
* @return the value of the function
*/
// @Override
public final double compute(final double[] x) {
return (Kernel.shiftedPermRotRastrigin(x, this.m_o, this.m_p,//
this.m_m, 0, this.m_matDim, this.m_tmp) * 1e6) + //
Kernel.shiftedPermRastrigin(x, this.m_o, this.m_p, this.m_matDim,//
this.m_dimension - this.m_matDim);
}
/**
* Obtain the full name of the benchmark function (according to
* "Benchmark Functions for the CEC�2010 Special Session and
* Competition on Large-Scale Global Optimization" Ke Tang, Xiaodong
* Li, P. N. Suganthan, Zhenyu Yang, and Thomas Weise CEC'2010)
*
* @return the full name of the benchmark function
*/
// @Override
public final String getFullName() {
return "Single-group Shifted and m-rotated Rastrigin�s Function";//$NON-NLS-1$
}
/**
* Obtain the short name of the benchmark function (according to
* "Benchmark Functions for the CEC�2010 Special Session and
* Competition on Large-Scale Global Optimization" Ke Tang, Xiaodong
* Li, P. N. Suganthan, Zhenyu Yang, and Thomas Weise CEC'2010)
*
* @return the short name of the benchmark function
*/
// @Override
public final String getShortName() {
return "F5"; //$NON-NLS-1$
}
}
| BIORIMP/biorimp | BIO-RIMP/test_data/code/optimization/src/unalcol/optimization/testbed/real/lsgo_benchmark/F5.java | Java | gpl-2.0 | 3,366 |
package de.darcade.UnityConnect.UserInterface.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import java.util.ArrayList;
public class ListAdapter extends ArrayAdapter<ListAdapter.Item> {
public interface Item {
public View inflateView(LayoutInflater layoutInflater);
}
private ArrayList<Item> items;
private LayoutInflater layoutInflater;
public ListAdapter(Context context, ArrayList<Item> items) {
super(context, 0, items);
this.items = items;
layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Item i = items.get(position);
return i.inflateView(layoutInflater);
}
}
| Darcade/UnityConnect-Android | src/main/java/de/darcade/UnityConnect/UserInterface/List/ListAdapter.java | Java | gpl-2.0 | 877 |
import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(sc.nextInt() + sc.nextInt());
sc.close();
}
}
| jeandersonbc/algorithms-and-ds | training/Sum.java | Java | gpl-2.0 | 221 |
package com.auguryrock.luv4s.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class World implements Comparable<World> {
public static final String WORLD = "world";
@Id
protected Integer id;
@ManyToOne
@JoinColumn(name = "match_id")
@JsonIgnore
protected Matchup matchup;
protected Colour colour;
protected Integer score;
protected String nameKey;
public World(Integer id, Colour colour) {
assert id != null;
this.id = id;
this.colour = colour;
this.nameKey = WORLD + id;
}
public World() {
}
public Integer getId() {
return id;
}
public Colour getColour() {
return colour;
}
public String getNameKey() {
return nameKey;
}
public Matchup getMatchup() {
return matchup;
}
public void setMatchup(Matchup matchup) {
this.matchup = matchup;
}
public void setNameKey(String nameKey) {
this.nameKey = nameKey;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
World world = (World) o;
if (colour != world.colour) return false;
if (id != null ? !id.equals(world.id) : world.id != null) return false;
if (nameKey != null ? !nameKey.equals(world.nameKey) : world.nameKey != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (colour != null ? colour.hashCode() : 0);
result = 31 * result + (nameKey != null ? nameKey.hashCode() : 0);
return result;
}
@Override
public int compareTo(World world) {
assert world.getId() != null;
assert id != null;
return id.compareTo(world.getId());
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
}
| MonCherWatson/Luv4s | persistence/src/main/java/com/auguryrock/luv4s/domain/World.java | Java | gpl-2.0 | 2,198 |
package org.bouncycastle.jce.provider;
import java.io.IOException;
import java.math.BigInteger;
import java.security.cert.CRLException;
import java.security.cert.X509CRLEntry;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.DEREnumerated;
import org.bouncycastle.asn1.util.ASN1Dump;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.CRLReason;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.Extensions;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.TBSCertList;
import org.bouncycastle.asn1.x509.X509Extension;
import org.bouncycastle.x509.extension.X509ExtensionUtil;
/**
* The following extensions are listed in RFC 2459 as relevant to CRL Entries
*
* ReasonCode Hode Instruction Code Invalidity Date Certificate Issuer
* (critical)
*/
public class X509CRLEntryObject extends X509CRLEntry
{
private TBSCertList.CRLEntry c;
private X500Name certificateIssuer;
private int hashValue;
private boolean isHashValueSet;
public X509CRLEntryObject(TBSCertList.CRLEntry c)
{
this.c = c;
this.certificateIssuer = null;
}
/**
* Constructor for CRLEntries of indirect CRLs. If <code>isIndirect</code>
* is <code>false</code> {@link #getCertificateIssuer()} will always
* return <code>null</code>, <code>previousCertificateIssuer</code> is
* ignored. If this <code>isIndirect</code> is specified and this CRLEntry
* has no certificate issuer CRL entry extension
* <code>previousCertificateIssuer</code> is returned by
* {@link #getCertificateIssuer()}.
*
* @param c
* TBSCertList.CRLEntry object.
* @param isIndirect
* <code>true</code> if the corresponding CRL is a indirect
* CRL.
* @param previousCertificateIssuer
* Certificate issuer of the previous CRLEntry.
*/
public X509CRLEntryObject(
TBSCertList.CRLEntry c,
boolean isIndirect,
X500Name previousCertificateIssuer)
{
this.c = c;
this.certificateIssuer = loadCertificateIssuer(isIndirect, previousCertificateIssuer);
}
/**
* Will return true if any extensions are present and marked as critical as
* we currently don't handle any extensions!
*/
public boolean hasUnsupportedCriticalExtension()
{
Set extns = getCriticalExtensionOIDs();
return extns != null && !extns.isEmpty();
}
private X500Name loadCertificateIssuer(boolean isIndirect, X500Name previousCertificateIssuer)
{
if (!isIndirect)
{
return null;
}
byte[] ext = getExtensionValue(X509Extension.certificateIssuer.getId());
if (ext == null)
{
return previousCertificateIssuer;
}
try
{
GeneralName[] names = GeneralNames.getInstance(
X509ExtensionUtil.fromExtensionValue(ext)).getNames();
for (int i = 0; i < names.length; i++)
{
if (names[i].getTagNo() == GeneralName.directoryName)
{
return X500Name.getInstance(names[i].getName());
}
}
return null;
}
catch (IOException e)
{
return null;
}
}
public X500Principal getCertificateIssuer()
{
if (certificateIssuer == null)
{
return null;
}
try
{
return new X500Principal(certificateIssuer.getEncoded());
}
catch (IOException e)
{
return null;
}
}
private Set getExtensionOIDs(boolean critical)
{
Extensions extensions = c.getExtensions();
if (extensions != null)
{
Set set = new HashSet();
Enumeration e = extensions.oids();
while (e.hasMoreElements())
{
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
Extension ext = extensions.getExtension(oid);
if (critical == ext.isCritical())
{
set.add(oid.getId());
}
}
return set;
}
return null;
}
public Set getCriticalExtensionOIDs()
{
return getExtensionOIDs(true);
}
public Set getNonCriticalExtensionOIDs()
{
return getExtensionOIDs(false);
}
public byte[] getExtensionValue(String oid)
{
Extensions exts = c.getExtensions();
if (exts != null)
{
Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid));
if (ext != null)
{
try
{
return ext.getExtnValue().getEncoded();
}
catch (Exception e)
{
throw new RuntimeException("error encoding " + e.toString());
}
}
}
return null;
}
/**
* Cache the hashCode value - calculating it with the standard method.
* @return calculated hashCode.
*/
public int hashCode()
{
if (!isHashValueSet)
{
hashValue = super.hashCode();
isHashValueSet = true;
}
return hashValue;
}
public byte[] getEncoded()
throws CRLException
{
try
{
return c.getEncoded(ASN1Encoding.DER);
}
catch (IOException e)
{
throw new CRLException(e.toString());
}
}
public BigInteger getSerialNumber()
{
return c.getUserCertificate().getValue();
}
public Date getRevocationDate()
{
return c.getRevocationDate().getDate();
}
public boolean hasExtensions()
{
return c.getExtensions() != null;
}
public String toString()
{
StringBuffer buf = new StringBuffer();
String nl = System.getProperty("line.separator");
buf.append(" userCertificate: ").append(this.getSerialNumber()).append(nl);
buf.append(" revocationDate: ").append(this.getRevocationDate()).append(nl);
buf.append(" certificateIssuer: ").append(this.getCertificateIssuer()).append(nl);
Extensions extensions = c.getExtensions();
if (extensions != null)
{
Enumeration e = extensions.oids();
if (e.hasMoreElements())
{
buf.append(" crlEntryExtensions:").append(nl);
while (e.hasMoreElements())
{
ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement();
Extension ext = extensions.getExtension(oid);
if (ext.getExtnValue() != null)
{
byte[] octs = ext.getExtnValue().getOctets();
ASN1InputStream dIn = new ASN1InputStream(octs);
buf.append(" critical(").append(ext.isCritical()).append(") ");
try
{
if (oid.equals(X509Extension.reasonCode))
{
buf.append(CRLReason.getInstance(DEREnumerated.getInstance(dIn.readObject()))).append(nl);
}
else if (oid.equals(X509Extension.certificateIssuer))
{
buf.append("Certificate issuer: ").append(GeneralNames.getInstance(dIn.readObject())).append(nl);
}
else
{
buf.append(oid.getId());
buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl);
}
}
catch (Exception ex)
{
buf.append(oid.getId());
buf.append(" value = ").append("*****").append(nl);
}
}
else
{
buf.append(nl);
}
}
}
}
return buf.toString();
}
}
| rex-xxx/mt6572_x201 | external/bouncycastle/bcprov/src/main/java/org/bouncycastle/jce/provider/X509CRLEntryObject.java | Java | gpl-2.0 | 8,873 |
package org.tinycourses.javatutorial.staticmember;
/**
* Author: Tony Crusoe <[email protected]>
* Date: 6/11/14 9:53 PM
*/
public class StaticMemberExperiment {
public static void main(String[] args) {
T t1 = new T();
t1.set_m(1);
t1.set_m_static(2);
t1.print_m();
t1.print_m_static();
T t2 = new T();
t2.set_m(1);
/**
* Remark:
*
* Set value for static member m_static by directly assigning value instead of using the setter method
* set_m_static.
*/
T.m_static=2;
t2.print_m();
t2.print_m_static();
}
}
| tinycourses/repogit-tinycourses-course-javatutorial | src/org/tinycourses/javatutorial/staticmember/StaticMemberExperiment.java | Java | gpl-2.0 | 666 |
/*
* org.openmicroscopy.shoola.agents.treeviewer.util.UserManagerDialog
*
*------------------------------------------------------------------------------
* Copyright (C) 2006-2007 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.util.ui;
//Java imports
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.WindowConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
//Third-party libraries
import info.clearthought.layout.TableLayout;
//Application-internal dependencies
import org.openmicroscopy.shoola.agents.util.ViewerSorter;
import org.openmicroscopy.shoola.util.ui.TitlePanel;
import org.openmicroscopy.shoola.util.ui.UIUtilities;
import pojos.ExperimenterData;
import pojos.GroupData;
/**
* Modal dialog presenting the existing user groups and
* and the experimenters in each group. The user can then select and
* view other people data.
*
* @author Jean-Marie Burel
* <a href="mailto:[email protected]">[email protected]</a>
* @author Donald MacDonald
* <a href="mailto:[email protected]">[email protected]</a>
* @version 3.0
* <small>
* (<b>Internal version:</b> $Revision: $Date: $)
* </small>
* @since OME3.0
*/
public class UserManagerDialog
extends JDialog
implements ActionListener
{
/** Bounds property indicating that a new user has been selected. */
public static final String USER_SWITCH_PROPERTY = "userSwitch";
/** Bounds property indicating that no user selected. */
public static final String NO_USER_SWITCH_PROPERTY = "noUserSwitch";
/** The default size of the window. */
private static final Dimension DEFAULT_SIZE = new Dimension(400, 400);
/** The window's title. */
private static final String TITLE = "Experimenter Selection";
/** The window's description. */
private static final String TEXT = "Select an experimenter.";
/** The description of the {@link #cancel} button. */
private static final String CANCEL_DESCRIPTION = "Close the window.";
/** The description of the {@link #apply} button. */
private static final String APPLY_DESCRIPTION = "View selected " +
"user's data.";
/** Action command ID indicating to close the window. */
private static final int CANCEL = 0;
/** Action command ID indicating to apply the selection. */
private static final int APPLY = 1;
/** Action command ID indicating to display content of a group. */
private static final int GROUPS = 2;
/**
* The size of the invisible components used to separate buttons
* horizontally.
*/
private static final Dimension H_SPACER_SIZE = new Dimension(5, 10);
/** Button to close without applying the selection. */
private JButton cancel;
/** Button to apply the selection. */
private JButton apply;
/** The box hosting the groups. */
private JComboBox groupsBox;
/** The component hosting the users for a given group. */
private JList users;
/** The current user. */
private ExperimenterData loggedUser;
/** Helper class uses to sort elements. */
private ViewerSorter sorter;
/** Map of ordered elements. */
private Map<GroupData, Object[]> orderedMap;
/** Closes and disposes. */
private void cancel()
{
setVisible(false);
dispose();
}
/** Switches the user. */
private void apply()
{
Map<Long, ExperimenterData>
r = new HashMap<Long, ExperimenterData>(1);
GroupData g = (GroupData) groupsBox.getSelectedItem();
Object user = users.getSelectedValue();
if (user == null) {
firePropertyChange(NO_USER_SWITCH_PROPERTY, Boolean.valueOf(false),
Boolean.valueOf(true));
return;
}
r.put(g.getId(), (ExperimenterData) user);
firePropertyChange(USER_SWITCH_PROPERTY, null, r);
cancel();
}
/** Sets the properties of the window. */
private void setProperties()
{
setModal(true);
setTitle(TITLE);
}
/**
* Fills the users' list with the specified objects.
*
* @param data The objects to add.
*/
private void fillList(Object[] data)
{
if (data == null) return;
DefaultListModel model = (DefaultListModel) users.getModel();
ExperimenterData d;
int index = 0;
for (int i = 0; i < data.length; i++) {
d = (ExperimenterData) data[i];
if (d.getId() != loggedUser.getId()) {
model.add(index, d);
index++;
}
}
}
/** Adds listeners. */
private void attachListeners()
{
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
/**
* Cancels while closing the window.
* @see WindowAdapter#windowClosing(WindowEvent)
*/
public void windowClosing(WindowEvent e) {
cancel();
}
});
cancel.setActionCommand(""+CANCEL);
cancel.addActionListener(this);
apply.setActionCommand(""+APPLY);
apply.addActionListener(this);
groupsBox.setActionCommand(""+GROUPS);
groupsBox.addActionListener(this);
users.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
apply.setEnabled(!lsm.isSelectionEmpty());
}
});
}
/**
* Initializes the UI components.
*
* @param groups The groups the user is a member of.
* @param userIcon The icon used to represent an user.
*/
private void initComponents(Set groups, Icon userIcon)
{
sorter = new ViewerSorter();
orderedMap = new LinkedHashMap<GroupData, Object[]>();
cancel = new JButton("Cancel");
cancel.setToolTipText(
UIUtilities.formatToolTipText(CANCEL_DESCRIPTION));
apply = new JButton("Apply");
apply.setEnabled(false);
apply.setToolTipText(
UIUtilities.formatToolTipText(APPLY_DESCRIPTION));
getRootPane().setDefaultButton(apply);
GroupData defaultGroup = loggedUser.getDefaultGroup();
long groupID = defaultGroup.getId();
//Build the array for box.
//Iterator i = map.keySet().iterator();
//Remove not visible group
GroupData g;
GroupData[] objects = new GroupData[groups.size()];
int selectedIndex = 0;
int index = 0;
Object[] children;
GroupData selectedGroup = defaultGroup;
//sort
Iterator i = sorter.sort(groups).iterator();
while (i.hasNext()) {
g = (GroupData) i.next();
objects[index] = g;
if (g.getId() == groupID) {
selectedIndex = index;
selectedGroup = g;
}
children = sorter.sortAsArray(g.getExperimenters());
orderedMap.put(g, children);
index++;
}
//sort by name
groupsBox = new JComboBox(objects);
groupsBox.setRenderer(new GroupsRenderer());
DefaultListModel model = new DefaultListModel();
users = new JList(model);
fillList(orderedMap.get(selectedGroup));
users.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
users.setLayoutOrientation(JList.VERTICAL);
users.setCellRenderer(new UserListRenderer(userIcon));
attachListeners();
if (objects.length != 0)
groupsBox.setSelectedIndex(selectedIndex);
}
/**
* Builds the main component of this dialog.
*
* @return See above.
*/
private JPanel buildContent()
{
double[][] tl = {{TableLayout.PREFERRED, TableLayout.FILL}, //columns
{TableLayout.PREFERRED, 5, TableLayout.FILL}}; //rows
JPanel content = new JPanel();
content.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
content.setLayout(new TableLayout(tl));
//content.add( UIUtilities.setTextFont("Groups"), "0, 0, LEFT, TOP");
//content.add(groups, "1, 0");
content.add(UIUtilities.setTextFont("Experimenters "), "0, 2, LEFT, TOP");
content.add(new JScrollPane(users), "1, 2");
return content;
}
/**
* Builds the tool bar hosting the {@link #cancel} and {@link #apply}
* buttons.
*
* @return See above;
*/
private JPanel buildToolBar()
{
JPanel bar = new JPanel();
bar.setBorder(null);
//bar.add(mySelf);
//bar.add(Box.createRigidArea(H_SPACER_SIZE));
bar.add(apply);
bar.add(Box.createRigidArea(H_SPACER_SIZE));
bar.add(cancel);
JPanel p = UIUtilities.buildComponentPanelRight(bar);
return p;
}
/**
* Builds and lays out the UI.
*
* @param icon The icon displayed in the title panel.
*/
private void buildGUI(Icon icon)
{
TitlePanel titlePanel = new TitlePanel(TITLE, TEXT, icon);
Container c = getContentPane();
c.setLayout(new BorderLayout(0, 0));
c.add(titlePanel, BorderLayout.NORTH);
c.add(buildContent(), BorderLayout.CENTER);
c.add(buildToolBar(), BorderLayout.SOUTH);
}
/**
* Creates a new instance.
*
* @param parent The parent of this dialog.
* @param loggedUser The user currently logged in.
* @param groups The groups the user is a member of.
* @param userIcon The icon representing an user.
* @param icon The icon displayed in the title panel.
*/
public UserManagerDialog(JFrame parent, ExperimenterData loggedUser,
Set groups, Icon userIcon, Icon icon)
{
super(parent);
setProperties();
this.loggedUser = loggedUser;
initComponents(groups, userIcon);
buildGUI(icon);
}
/** Sets the default size of window. */
public void setDefaultSize()
{
setSize(DEFAULT_SIZE);
}
/**
* Performs the actions.
* @see ActionListener#actionPerformed(ActionEvent)
*/
public void actionPerformed(ActionEvent e)
{
int id = Integer.parseInt(e.getActionCommand());
switch (id) {
case CANCEL:
cancel();
break;
case APPLY:
apply();
break;
case GROUPS:
DefaultListModel model = (DefaultListModel) users.getModel();
model.clear();
fillList(orderedMap.get(groupsBox.getSelectedItem()));
}
}
}
| joshmoore/openmicroscopy | components/insight/SRC/org/openmicroscopy/shoola/agents/util/ui/UserManagerDialog.java | Java | gpl-2.0 | 11,158 |
/*
This file is a modified version of Cyclos (www.cyclos.org).
A project of the Social Trade Organisation (www.socialtrade.org).
Cyclos 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.
Cyclos 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 Cyclos; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package nl.strohalm.cyclos.webservices.webshop;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* Parameters for generating a webshop ticket via web services
* @author luis
*/
public class GenerateWebShopTicketParams implements Serializable {
private static final long serialVersionUID = -1816777948198919713L;
private BigDecimal amount;
private String currency;
private String clientAddress;
private String description;
private String returnUrl;
private String toUsername;
public BigDecimal getAmount() {
return amount;
}
public String getClientAddress() {
return clientAddress;
}
public String getCurrency() {
return currency;
}
public String getDescription() {
return description;
}
public String getReturnUrl() {
return returnUrl;
}
public String getToUsername() {
return toUsername;
}
public void setAmount(final BigDecimal amount) {
this.amount = amount;
}
public void setClientAddress(final String clientAddress) {
this.clientAddress = clientAddress;
}
public void setCurrency(final String currency) {
this.currency = currency;
}
public void setDescription(final String description) {
this.description = description;
}
public void setReturnUrl(final String returnUrl) {
this.returnUrl = returnUrl;
}
public void setToUsername(final String toUsername) {
this.toUsername = toUsername;
}
@Override
public String toString() {
return "GenerateWebShopTicketParams(amount=" + amount + ", currency=" + currency + ", clientAddress=" + clientAddress + ", description=" + description + ", returnUrl=" + returnUrl + ", toUsername=" + toUsername + ")";
}
}
| BitcoinReserve/java-client-api | src/nl/strohalm/cyclos/webservices/webshop/GenerateWebShopTicketParams.java | Java | gpl-2.0 | 2,730 |
package com.playground.notification.app.fragments;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.ImageView;
import com.chopping.application.BasicPrefs;
import com.chopping.fragments.BaseFragment;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.playground.notification.R;
import com.playground.notification.app.App;
import com.playground.notification.app.activities.AppActivity;
import com.playground.notification.app.activities.MapActivity;
import com.playground.notification.bus.OpenRouteEvent;
import com.playground.notification.bus.PostOpenRouteEvent;
import com.playground.notification.bus.ShowLocationRatingEvent;
import com.playground.notification.bus.ShowStreetViewEvent;
import com.playground.notification.ds.google.Matrix;
import com.playground.notification.ds.grounds.Playground;
import com.playground.notification.ds.sync.SyncPlayground;
import com.playground.notification.sync.NearRingManager;
import com.playground.notification.utils.Prefs;
import java.lang.ref.WeakReference;
import de.greenrobot.event.EventBus;
import static com.playground.notification.utils.Utils.openRoute;
import static com.playground.notification.utils.Utils.setPlaygroundIcon;
abstract class AppFragment extends BaseFragment {
static final String EXTRAS_GROUND = AppFragment.class.getName() + ".EXTRAS.playground";
static final String EXTRAS_LAT = AppFragment.class.getName() + ".EXTRAS.lat";
static final String EXTRAS_LNG = AppFragment.class.getName() + ".EXTRAS.lng";
/**
* App that use this Chopping should know the preference-storage.
*
* @return An instance of {@link com.chopping.application.BasicPrefs}.
*/
@Override
protected BasicPrefs getPrefs() {
return Prefs.getInstance();
}
protected static final class CommonUIDelegate {
private @NonNull final WeakReference<Fragment> mFragmentWeakReference;
CommonUIDelegate(@NonNull Fragment fragment) {
mFragmentWeakReference = new WeakReference<>(fragment);
}
//------------------------------------------------
//Subscribes, event-handlers
//------------------------------------------------
/**
* Handler for {@link OpenRouteEvent}.
*
* @param e Event {@link OpenRouteEvent}.
*/
@SuppressWarnings("unused")
public void onEvent(@SuppressWarnings("UnusedParameters") OpenRouteEvent e) {
if (mFragmentWeakReference.get() == null) {
return;
}
Fragment fragment = mFragmentWeakReference.get();
FragmentActivity activity = fragment.getActivity();
if (activity == null) {
return;
}
final Bundle arguments = fragment.getArguments();
NearRingManager mgr = NearRingManager.getInstance();
SyncPlayground ringFound = mgr.findInCache((Playground) arguments.getSerializable(EXTRAS_GROUND));
if (ringFound == null) {
AddToNearRingFragment.newInstance(activity, arguments.getDouble(EXTRAS_LAT), arguments.getDouble(EXTRAS_LNG), ((Playground) arguments.getSerializable(EXTRAS_GROUND)))
.show(fragment.getChildFragmentManager(), null);
} else {
EventBus.getDefault()
.post(new PostOpenRouteEvent(false));
}
}
/**
* Handler for {@link PostOpenRouteEvent}.
*
* @param e Event {@link PostOpenRouteEvent}.
*/
@SuppressWarnings("unused")
public void onEvent(PostOpenRouteEvent e) {
if (mFragmentWeakReference.get() == null) {
return;
}
Fragment fragment = mFragmentWeakReference.get();
ImageView mRingIv;
View mDetailVg;
if (fragment instanceof DialogFragment) {
mRingIv = (ImageView) ((DialogFragment) fragment).getDialog()
.findViewById(R.id.ring_iv);
mDetailVg = ((DialogFragment) fragment).getDialog()
.findViewById(R.id.playground_detail_vg);
} else {
View view = fragment.getView();
if (view == null) {
return;
}
mRingIv = (ImageView) view.findViewById(R.id.ring_iv);
mDetailVg = view.findViewById(R.id.playground_detail_vg);
}
if (e.isAddToNearRing()) {
NearRingManager.getInstance()
.addNearRing((Playground) fragment.getArguments()
.getSerializable(EXTRAS_GROUND), mRingIv, mDetailVg);
}
FragmentActivity activity = fragment.getActivity();
if (activity == null) {
return;
}
Bundle arguments = fragment.getArguments();
Playground playground = (Playground) arguments.getSerializable(EXTRAS_GROUND);
if (playground == null) {
return;
}
openRoute(activity, new LatLng(arguments.getDouble(EXTRAS_LAT), arguments.getDouble(EXTRAS_LNG)), playground.getPosition());
}
/**
* Handler for {@link com.playground.notification.bus.ShowLocationRatingEvent}.
*
* @param e Event {@link com.playground.notification.bus.ShowLocationRatingEvent}.
*/
@SuppressWarnings("unused")
public void onEvent(ShowLocationRatingEvent e) {
if (mFragmentWeakReference.get() == null) {
return;
}
Fragment fragment = mFragmentWeakReference.get();
if (!fragment.getUserVisibleHint()) {
return;
}
AppActivity activity = (AppActivity) fragment.getActivity();
if (activity != null) {
activity.showDialogFragment(RatingDialogFragment.newInstance(activity, e.getPlayground(), e.getRating()), "rating");
}
}
//------------------------------------------------
void openStreetView(@Nullable Matrix matrix) {
if (mFragmentWeakReference.get() == null) {
return;
}
Fragment fragment = mFragmentWeakReference.get();
Playground playground = (Playground) fragment.getArguments()
.getSerializable(EXTRAS_GROUND);
if (playground != null && playground.getPosition() != null && matrix != null && matrix.getDestination() != null && matrix.getDestination()
.size() > 0 && matrix.getDestination()
.get(0) != null) {
EventBus.getDefault()
.post(new ShowStreetViewEvent(matrix.getDestination()
.get(0), playground.getPosition()));
}
}
final GoogleMap.OnMapClickListener mOnMapClickListener = new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
if (!App.Instance.getResources()
.getBoolean(R.bool.is_small_screen)) {
return;
}
if (mFragmentWeakReference.get() == null) {
return;
}
Fragment fragment = mFragmentWeakReference.get();
if (App.Instance.getResources()
.getBoolean(R.bool.is_small_screen)) {
Activity activity = fragment.getActivity();
if (activity == null) {
return;
}
if (fragment instanceof DialogFragment) {
((DialogFragment) fragment).dismiss();
}
Playground playground = (Playground) fragment.getArguments()
.getSerializable(EXTRAS_GROUND);
MapActivity.showInstance(activity, playground);
}
}
};
void onMapReady(@NonNull GoogleMap googleMap) {
if (mFragmentWeakReference.get() == null) {
return;
}
Fragment fragment = mFragmentWeakReference.get();
Playground playground = (Playground) fragment.getArguments()
.getSerializable(EXTRAS_GROUND);
if (playground == null || playground.getPosition() == null) {
return;
}
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(playground.getPosition(), 18));
MarkerOptions markerOptions = new MarkerOptions().position(playground.getPosition());
setPlaygroundIcon(App.Instance, playground, markerOptions);
googleMap.addMarker(markerOptions);
googleMap.setOnMapClickListener(mOnMapClickListener);
googleMap.getUiSettings().setMapToolbarEnabled(false);
}
void updateWeatherView(View weatherV) {
Prefs prefs = Prefs.getInstance();
if (!prefs.showWeatherBoard()) {
weatherV.setVisibility(View.GONE);
} else {
weatherV.setVisibility(View.VISIBLE);
}
}
}
}
| XinyueZ/playground-notification | app/src/main/java/com/playground/notification/app/fragments/AppFragment.java | Java | gpl-2.0 | 8,695 |
/**
* Distribution License:
* JSword is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License, version 2.1 as published by
* the Free Software Foundation. This program is distributed in the hope
* that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The License is available on the internet at:
* http://www.gnu.org/copyleft/lgpl.html
* or by writing to:
* Free Software Foundation, Inc.
* 59 Temple Place - Suite 330
* Boston, MA 02111-1307, USA
*
* Copyright: 2005 - 2012
* The copyright to this program is held by it's authors.
*
* ID: $Id: DivTag.java 2221 2012-01-25 21:32:57Z dmsmith $
*/
package org.crosswire.jsword.book.filter.thml;
import org.crosswire.jsword.book.Book;
import org.crosswire.jsword.book.OSISUtil;
import org.crosswire.jsword.passage.Key;
import org.jdom.Element;
import org.xml.sax.Attributes;
/**
* THML Tag to process the div element.
*
* @see gnu.lgpl.License for license details.<br>
* The copyright to this program is held by it's authors.
* @author Joe Walker [joe at eireneh dot com]
*/
public class DivTag extends AbstractTag {
/**
* Create an div tag
*/
public DivTag() {
super();
this.level = 0;
}
/**
* Create an div tag of the given level
*
* @param level
*/
public DivTag(int level) {
super();
this.level = level;
}
/* (non-Javadoc)
* @see org.crosswire.jsword.book.filter.thml.Tag#getTagName()
*/
public String getTagName() {
if (level == 0) {
return "div";
}
return "div" + level;
}
@Override
public Element processTag(Book book, Key key, Element ele, Attributes attrs) {
// See if there are variant readings e.g. WHNU Mat 1.9
String typeAttr = attrs.getValue("type");
if ("variant".equals(typeAttr)) {
Element seg = OSISUtil.factory().createSeg();
seg.setAttribute(OSISUtil.OSIS_ATTR_TYPE, OSISUtil.VARIANT_TYPE);
String classAttr = attrs.getValue("class");
if (classAttr != null) {
seg.setAttribute(OSISUtil.OSIS_ATTR_SUBTYPE, OSISUtil.VARIANT_CLASS + '-' + classAttr);
}
if (ele != null) {
ele.addContent(seg);
}
return seg;
}
Element div = OSISUtil.factory().createDiv();
if (ele != null) {
ele.addContent(div);
}
return div;
}
/**
* The level of the division
*/
private int level;
}
| truhanen/JSana | JSana/src_others/org/crosswire/jsword/book/filter/thml/DivTag.java | Java | gpl-2.0 | 2,891 |
/*
* This code is in the public domain.
*/
package org.geometerplus.android.fbreader.api;
import android.graphics.Bitmap;
import java.util.Date;
import java.util.List;
public interface Api {
// information about fbreader
String getFBReaderVersion() throws ApiException;
// preferences information
List<String> getOptionGroups() throws ApiException;
List<String> getOptionNames(String group) throws ApiException;
String getOptionValue(String group, String name) throws ApiException;
void setOptionValue(String group, String name, String value) throws ApiException;
// book information for current book
String getBookLanguage() throws ApiException;
String getBookTitle() throws ApiException;
//List<String> getBookAuthors() throws ApiException;
List<String> getBookTags() throws ApiException;
String getBookFilePath() throws ApiException;
String getBookHash() throws ApiException;
String getBookUniqueId() throws ApiException;
Date getBookLastTurningTime() throws ApiException;
// book information for book defined by id
String getBookLanguage(long id) throws ApiException;
String getBookTitle(long id) throws ApiException;
//List<String> getBookAuthors(long id) throws ApiException;
List<String> getBookTags(long id) throws ApiException;
String getBookFilePath(long id) throws ApiException;
String getBookHash(long id) throws ApiException;
String getBookUniqueId(long id) throws ApiException;
Date getBookLastTurningTime(long id) throws ApiException;
//long findBookIdByUniqueId(String uniqueId) throws ApiException;
//long findBookIdByFilePath(String uniqueId) throws ApiException;
// text information
int getParagraphsNumber() throws ApiException;
int getParagraphElementsCount(int paragraphIndex) throws ApiException;
String getParagraphText(int paragraphIndex) throws ApiException;
List<String> getParagraphWords(int paragraphIndex) throws ApiException;
List<Integer> getParagraphWordIndices(int paragraphIndex) throws ApiException;
// page information
TextPosition getPageStart() throws ApiException;
TextPosition getPageEnd() throws ApiException;
boolean isPageEndOfSection() throws ApiException;
boolean isPageEndOfText() throws ApiException;
// manage view
void setPageStart(TextPosition position) throws ApiException;
void highlightArea(TextPosition start, TextPosition end) throws ApiException;
void clearHighlighting() throws ApiException;
int getBottomMargin() throws ApiException;
void setBottomMargin(int value) throws ApiException;
int getTopMargin() throws ApiException;
void setTopMargin(int value) throws ApiException;
int getLeftMargin() throws ApiException;
void setLeftMargin(int value) throws ApiException;
int getRightMargin() throws ApiException;
void setRightMargin(int value) throws ApiException;
// action control
List<String> listActions() throws ApiException;
List<String> listActionNames(List<String> actions) throws ApiException;
String getKeyAction(int key, boolean longPress) throws ApiException;
void setKeyAction(int key, boolean longPress, String action) throws ApiException;
List<String> listZoneMaps() throws ApiException;
String getZoneMap() throws ApiException;
void setZoneMap(String name) throws ApiException;
int getZoneMapHeight(String name) throws ApiException;
int getZoneMapWidth(String name) throws ApiException;
void createZoneMap(String name, int width, int height) throws ApiException;
boolean isZoneMapCustom(String name) throws ApiException;
void deleteZoneMap(String name) throws ApiException;
String getTapZoneAction(String name, int h, int v, boolean singleTap) throws ApiException;
void setTapZoneAction(String name, int h, int v, boolean singleTap, String action) throws ApiException;
String getTapActionByCoordinates(String name, int x, int y, int width, int height, String tap) throws ApiException;
List<MenuNode> getMainMenuContent() throws ApiException;
String getResourceString(String... keys) throws ApiException;
Bitmap getBitmap(int resourceId) throws ApiException;
}
| xiaosea/easyreader | src/main/java/org/geometerplus/android/fbreader/api/Api.java | Java | gpl-2.0 | 4,020 |
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 1.3.36
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.pjsip.pjsua;
public class pjmedia_codec_param_info {
private long swigCPtr;
protected boolean swigCMemOwn;
protected pjmedia_codec_param_info(long cPtr, boolean cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
protected static long getCPtr(pjmedia_codec_param_info obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
protected void finalize() {
delete();
}
public synchronized void delete() {
if(swigCPtr != 0 && swigCMemOwn) {
swigCMemOwn = false;
pjsuaJNI.delete_pjmedia_codec_param_info(swigCPtr);
}
swigCPtr = 0;
}
public void setClock_rate(long value) {
pjsuaJNI.pjmedia_codec_param_info_clock_rate_set(swigCPtr, this, value);
}
public long getClock_rate() {
return pjsuaJNI.pjmedia_codec_param_info_clock_rate_get(swigCPtr, this);
}
public void setChannel_cnt(long value) {
pjsuaJNI.pjmedia_codec_param_info_channel_cnt_set(swigCPtr, this, value);
}
public long getChannel_cnt() {
return pjsuaJNI.pjmedia_codec_param_info_channel_cnt_get(swigCPtr, this);
}
public void setAvg_bps(long value) {
pjsuaJNI.pjmedia_codec_param_info_avg_bps_set(swigCPtr, this, value);
}
public long getAvg_bps() {
return pjsuaJNI.pjmedia_codec_param_info_avg_bps_get(swigCPtr, this);
}
public void setMax_bps(long value) {
pjsuaJNI.pjmedia_codec_param_info_max_bps_set(swigCPtr, this, value);
}
public long getMax_bps() {
return pjsuaJNI.pjmedia_codec_param_info_max_bps_get(swigCPtr, this);
}
public void setFrm_ptime(int value) {
pjsuaJNI.pjmedia_codec_param_info_frm_ptime_set(swigCPtr, this, value);
}
public int getFrm_ptime() {
return pjsuaJNI.pjmedia_codec_param_info_frm_ptime_get(swigCPtr, this);
}
public void setEnc_ptime(int value) {
pjsuaJNI.pjmedia_codec_param_info_enc_ptime_set(swigCPtr, this, value);
}
public int getEnc_ptime() {
return pjsuaJNI.pjmedia_codec_param_info_enc_ptime_get(swigCPtr, this);
}
public void setPcm_bits_per_sample(short value) {
pjsuaJNI.pjmedia_codec_param_info_pcm_bits_per_sample_set(swigCPtr, this, value);
}
public short getPcm_bits_per_sample() {
return pjsuaJNI.pjmedia_codec_param_info_pcm_bits_per_sample_get(swigCPtr, this);
}
public void setPt(short value) {
pjsuaJNI.pjmedia_codec_param_info_pt_set(swigCPtr, this, value);
}
public short getPt() {
return pjsuaJNI.pjmedia_codec_param_info_pt_get(swigCPtr, this);
}
public pjmedia_codec_param_info() {
this(pjsuaJNI.new_pjmedia_codec_param_info(), true);
}
}
| erdincay/pjsip-jni | org.pjsip.pjsua/src/org/pjsip/pjsua/pjmedia_codec_param_info.java | Java | gpl-2.0 | 2,960 |
package org.insightcentre.unlp.naisc.learning;
/**
* A differentiable function which can be optimized
*/
public interface Function {
/** receive x. fill in g. return objective.
* @param x The current values of variables.
* @param g The gradient vector. The callback function must compute
* the gradient values for the current variables.
* @return The value of the objective function for the current
* variables.
*/
public double evaluate(final double[] x, double[] g);
}
| jmccrae/naisc | core/src/main/java/org/insightcentre/unlp/naisc/learning/Function.java | Java | gpl-2.0 | 593 |
/*
* Copyright (C) 2012-2022 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.converter.util;
import org.n52.faroe.annotation.Configurable;
import org.n52.faroe.annotation.Setting;
import org.n52.sos.converter.PrefixedIdentifierModifier;
import com.google.common.base.Strings;
/**
* Helper class for the {@link PrefixedIdentifierModifier}
*
* @author <a href="mailto:[email protected]">Carsten Hollmann</a>
* @since 4.4.0
*
*/
@Configurable
public class PrefixedIdentifierHelper {
private String globalPrefix;
private String offeringPrefix;
private String procedurePrefix;
private String observablePropertyPrefix;
private String featureOfInterestPrefix;
/**
* @return the globalPrefix
*/
public String getGlobalPrefix() {
return globalPrefix;
}
/**
* @param globalPrefix the globalPrefix to set
*/
@Setting(PrefixedIdentifierSetting.GLOBAL_PREFIX_KEY)
public void setGlobalPrefix(String globalPrefix) {
this.globalPrefix = globalPrefix;
}
public boolean isSetGlobalPrefix() {
return !Strings.isNullOrEmpty(getGlobalPrefix());
}
/**
* @return the offeringPrefix
*/
public String getOfferingPrefix() {
return offeringPrefix;
}
/**
* @param offeringPrefix the offeringPrefix to set
*/
@Setting(PrefixedIdentifierSetting.OFFERING_PREFIX_KEY)
public void setOfferingPrefix(String offeringPrefix) {
this.offeringPrefix = offeringPrefix;
}
public boolean isSetOfferingPrefix() {
return !Strings.isNullOrEmpty(getOfferingPrefix());
}
/**
* @return the procedurePrefix
*/
public String getProcedurePrefix() {
return procedurePrefix;
}
/**
* @param procedurePrefix the procedurePrefix to set
*/
@Setting(PrefixedIdentifierSetting.PROCEDURE_PREFIX_KEY)
public void setProcedurePrefix(String procedurePrefix) {
this.procedurePrefix = procedurePrefix;
}
public boolean isSetProcedurePrefix() {
return !Strings.isNullOrEmpty(getProcedurePrefix());
}
/**
* @return the observablePropertyPrefix
*/
public String getObservablePropertyPrefix() {
return observablePropertyPrefix;
}
/**
* @param observablePropertyPrefix the observablePropertyPrefix to set
*/
@Setting(PrefixedIdentifierSetting.OBSERVABLE_PROPERTY_PREFIX_KEY)
public void setObservablePropertyPrefix(String observablePropertyPrefix) {
this.observablePropertyPrefix = observablePropertyPrefix;
}
public boolean isSetObservablePropertyPrefix() {
return !Strings.isNullOrEmpty(getObservablePropertyPrefix());
}
/**
* @return the featureOfInterestPrefix
*/
public String getFeatureOfInterestPrefix() {
return featureOfInterestPrefix;
}
/**
* @param featureOfInterestPrefix the featureOfInterestPrefix to set
*/
@Setting(PrefixedIdentifierSetting.FEATURE_OF_INTEREST_PREFIX_KEY)
public void setFeatureOfInterestPrefix(String featureOfInterestPrefix) {
this.featureOfInterestPrefix = featureOfInterestPrefix;
}
public boolean isSetFeatureOfInterestPrefix() {
return !Strings.isNullOrEmpty(getFeatureOfInterestPrefix());
}
public boolean isSetAnyPrefix() {
return isSetGlobalPrefix() || isSetFeatureOfInterestPrefix() || isSetObservablePropertyPrefix()
|| isSetOfferingPrefix() || isSetProcedurePrefix();
}
}
| 52North/SOS | converter/identifier-modifier/prefixed-identifier/src/main/java/org/n52/sos/converter/util/PrefixedIdentifierHelper.java | Java | gpl-2.0 | 4,763 |
/*
* Copyright (c) 2012 Sam Harwell, Tunnel Vision Laboratories LLC
* All rights reserved.
*
* The source code of this document is proprietary work, and is not licensed for
* distribution. For information about licensing, contact Sam Harwell at:
* [email protected]
*/
package org.tvl.goworks.editor.go.codemodel;
/**
*
* @author Sam Harwell
*/
public interface TypeMapModel extends TypeModel {
TypeModel getKeyType();
TypeModel getValueType();
}
| tunnelvisionlabs/goworks | goworks.editor/src/org/tvl/goworks/editor/go/codemodel/TypeMapModel.java | Java | gpl-2.0 | 485 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.