repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
rrr6399/JSatTrakLib | src/name/gano/math/nonlinsolvers/TestDC.java | 2369 | /*
*=====================================================================
* This file is part of JSatTrak.
*
* Copyright 2007-2013 Shawn E. Gano
*
* 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 name.gano.math.nonlinsolvers;
/**
*
* @author Shawn
*/
public class TestDC implements NonLinearEquationSystemProblem
{
// main function
public static void main(String args[])
{
TestDC prob = new TestDC();
double[] fgoals = new double[] {0.0,0.0};
double[] X0 = new double[] {0,0};
//NonLinearEquationSystemSolver dc = new ModifiedNewtonFiniteDiffSolver(prob, fgoals, X0);
NonLinearEquationSystemSolver dc = new ModifiedBroydenSolver(prob, fgoals, X0);
dc.setVerbose(true);
dc.solve();
System.out.println("\n" + dc.getOutputMessage());
}
public double[] evaluateSystemOfEquations(double[] x)
{
double[] f = new double[2];
// f[0] = Math.sin(x[0]);
// f[1] = Math.cos(x[1]) + 0.0;
// f[0] = -2.0*x[0] + 3.0*x[1] -8.0;
// f[1] = 3.0*x[0] - 1.0*x[1] + 5.0;
// f[0] = x[0] - x[1]*x[1];
// f[1] = -2.0*x[0]*x[1] + 2.0*x[1];
// himmelblau
// f[0] = 4*x[0]*x[0]*x[0] + 4*x[0]*x[1]+2*x[1]*x[1] - 42*x[0] -14;
// f[1] = 4*x[1]*x[1]*x[1] + 4*x[0]*x[1]+2*x[0]*x[0] - 26*x[1] -22;
// Ferrais
f[0] = 0.25/Math.PI*x[1]+0.5*x[0]-0.5*Math.sin(x[0]*x[1]);
f[1] = Math.E/Math.PI*x[1]-2*Math.E*x[0]+(1-0.25/Math.PI)*(Math.exp(2*x[0])-Math.E);
return f;
}
}
| apache-2.0 |
OpenUniversity/ovirt-engine | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/AddTagCommand.java | 1202 | package org.ovirt.engine.core.bll;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.action.TagsOperationParameters;
import org.ovirt.engine.core.common.businessentities.Tags;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
public class AddTagCommand<T extends TagsOperationParameters> extends TagsCommandOperationBase<T> {
public AddTagCommand(T parameters) {
super(parameters);
}
@Override
protected void executeCommand() {
DbFacade.getInstance().getTagDao().save(getTag());
TagsDirector.getInstance().addTag(getTag());
setSucceeded(true);
}
@Override
protected boolean validate() {
Tags tag = DbFacade.getInstance().getTagDao()
.getByName(getParameters().getTag().getTagName());
if (tag != null) {
addValidationMessage(EngineMessage.TAGS_SPECIFY_TAG_IS_IN_USE);
return false;
}
return true;
}
@Override
public AuditLogType getAuditLogTypeValue() {
return getSucceeded() ? AuditLogType.USER_ADD_TAG : AuditLogType.USER_ADD_TAG_FAILED;
}
}
| apache-2.0 |
strepsirrhini-army/chaos-loris | src/main/java/io/pivotal/strepsirrhini/chaosloris/web/ScheduleCreateInput.java | 1325 | /*
* Copyright 2015-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.pivotal.strepsirrhini.chaosloris.web;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.validation.constraints.NotNull;
/**
* Input for schedule creation
*/
public final class ScheduleCreateInput {
@NotNull
private final String expression;
@NotNull
private final String name;
@JsonCreator
ScheduleCreateInput(@JsonProperty("expression") String expression, @JsonProperty("name") String name) {
this.expression = expression;
this.name = name;
}
String getExpression() {
return this.expression;
}
String getName() {
return this.name;
}
}
| apache-2.0 |
growbit/turbogwt | turbogwt-mvp/src/main/java/org/turbogwt/mvp/AbstractView.java | 851 | package org.turbogwt.mvp;
import com.google.gwt.user.client.ui.Composite;
/**
* Abstract class for every View in the TurboGWT-MVP framework.
* <p>
* It provides access to its Presenter via the {@link #getPresenter} method.
*
* @param <P> the Presenter that is attached to this View, whenever it is displayed
*
* @author Danilo Reinert
*/
public abstract class AbstractView<P extends Presenter> extends Composite implements View<P> {
private P presenter;
public P getPresenter() {
if (presenter == null) {
throw new IllegalStateException("Presenter is not set. The Presenter must attach itself to the View via " +
"#setPresenter, before the View can use it.");
}
return presenter;
}
public void setPresenter(P presenter) {
this.presenter = presenter;
}
}
| apache-2.0 |
kelongxhu/jedis-sentinel-pool | src/main/java/redis/clients/jedis/Command.java | 3425 | package redis.clients.jedis;
import com.esotericsoftware.reflectasm.MethodAccess;
import org.apache.log4j.Logger;
import java.util.Map;
public abstract class Command {
private final static Logger LOG = Logger.getLogger(Command.class);
private final static MethodAccess access = MethodAccess
.get(ShardedJedis.class);
protected ShardedJedisSentinelPool pool;
public String set(String key, String value) {
return String.valueOf(this.invoke("set", new String[] { key, value },
new Class[] { String.class, String.class }));
}
public String get(String key) {
return String.valueOf(this.invoke("get", new String[] { key },
String.class));
}
public long del(String key) {
return (long) this.invoke("del", new String[] { key }, String.class);
}
public String lpopList(String key) {
return String.valueOf(this.invoke("lpop", new String[] { key },
String.class));
}
public long rpushList(String key, String... values) {
return (long) this.invoke("rpush", new Object[] { key, values },
new Class[] { String.class, String[].class });
}
public long expire(String key, int time) {
return (long) this.invoke("expire", new Object[] { key, time },
new Class[] { String.class, int.class });
}
public long hsetnx(String key, String field, String value) {
return (long) this.invoke("hsetnx", new String[] { key, field, value },
new Class[] { String.class, String.class, String.class });
}
public boolean exist(String key) {
return (boolean) this.invoke("exists", new String[] { key },
String.class);
}
public boolean existInSet(String key, String member) {
return (boolean) this.invoke("sismember", new String[] { key, member },
new Class[] { String.class, String.class });
}
public long saddSet(String key, String... members) {
return (long) this.invoke("sadd", new Object[] { key, members },
new Class[] { String.class, String[].class });
}
public long sremSet(String key, String... members) {
return (long) this.invoke("srem", new Object[] { key, members },
new Class[] { String.class, String[].class });
}
public String spopSet(String key) {
return String.valueOf(this.invoke("spop", new Object[] { key },
new Class[] { String.class }));
}
public long hSet(byte[] key, byte[] field, byte[] value) {
return (long) this.invoke("hset", new Object[] { key, field, value },
new Class[] { byte[].class, byte[].class, byte[].class });
}
@SuppressWarnings("unchecked")
public Map<byte[], byte[]> hGetAll(byte[] key) {
return (Map<byte[], byte[]>) this.invoke("hgetAll",
new Object[] { key }, new Class[] { byte[].class });
}
public byte[] hGet(byte[] key, byte[] field) {
return (byte[]) this.invoke("hget", new Object[] { key, field },
new Class[] { byte[].class, byte[].class });
}
public long del(byte[] key) {
return (long) this.invoke("del", new Object[] { key }, byte[].class);
}
protected Object invoke(String methodName, Object[] args,
Class<?>... parameterTypes) {
Object ret = null;
ShardedJedis jedis = pool.getResource();
try {
/*
* Method method = clazz.getMethod(methodName, parameterTypes); ret
* = method.invoke(jedis, args);
*/
ret = access.invoke(jedis, methodName, parameterTypes, args);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
pool.returnBrokenResource(jedis);
} finally {
pool.returnResource(jedis);
}
return ret;
}
}
| apache-2.0 |
vimaier/conqat | org.conqat.engine.text/src/org/conqat/engine/text/identifier/IdentifierProcessorBase.java | 2775 | /*-------------------------------------------------------------------------+
| |
| Copyright 2005-2011 The ConQAT 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 org.conqat.engine.text.identifier;
import org.conqat.engine.commons.util.ConQATInputProcessorBase;
import org.conqat.engine.core.core.ConQATException;
import org.conqat.engine.sourcecode.resource.ITokenElement;
import org.conqat.engine.sourcecode.resource.ITokenResource;
import org.conqat.engine.sourcecode.resource.TokenElementUtils;
import org.conqat.lib.scanner.ETokenType.ETokenClass;
import org.conqat.lib.scanner.IToken;
/**
* Base class for processors working on identifiers.
*
* @param <T>
* the return type of this processor.
*
* @author $Author: juergens $
* @version $Rev: 35207 $
* @ConQAT.Rating GREEN Hash: 69177F56B4A8847260A2E8EDB12F972C
*/
public abstract class IdentifierProcessorBase<T> extends
ConQATInputProcessorBase<ITokenResource> {
/** {@inheritDoc} */
@Override
public T process() throws ConQATException {
for (ITokenElement element : TokenElementUtils.listTokenElements(input)) {
processElement(element);
}
return obtainResult();
}
/** Template method that calculates and returns the processor's result. */
protected abstract T obtainResult();
/** Process a single source element. */
private void processElement(ITokenElement element) throws ConQATException {
for (IToken token : element.getTokens(getLogger())) {
if (token.getType().getTokenClass() == ETokenClass.IDENTIFIER) {
processIdentifier(token.getText());
}
}
}
/** Template method that is called for each identifier. */
protected abstract void processIdentifier(String identifier);
} | apache-2.0 |
millmanorama/autopsy | Core/src/org/sleuthkit/autopsy/commonfilesearch/InstanceCountNode.java | 6850 | /*
*
* Autopsy Forensic Browser
*
* Copyright 2018 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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 org.sleuthkit.autopsy.commonfilesearch;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.nodes.Sheet;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.datamodel.DisplayableItemNode;
import org.sleuthkit.autopsy.datamodel.DisplayableItemNodeVisitor;
import org.sleuthkit.autopsy.datamodel.NodeProperty;
/**
* Node used to indicate the number of matches found with the MD5 children of
* this Node.
*/
final public class InstanceCountNode extends DisplayableItemNode {
private static final Logger logger = Logger.getLogger(InstanceCountNode.class.getName());
final private int instanceCount;
final private CommonAttributeValueList attributeValues;
/**
* Create a node with the given number of instances, and the given selection
* of metadata.
*
* @param instanceCount
* @param attributeValues
*/
@NbBundle.Messages({
"InstanceCountNode.displayName=Files with %s instances (%s)"
})
public InstanceCountNode(int instanceCount, CommonAttributeValueList attributeValues) {
super(Children.create(new CommonAttributeValueNodeFactory(attributeValues.getMetadataList()), true));
this.instanceCount = instanceCount;
this.attributeValues = attributeValues;
this.setDisplayName(String.format(Bundle.InstanceCountNode_displayName(), Integer.toString(instanceCount), attributeValues.getCommonAttributeListSize()));
this.setIconBaseWithExtension("org/sleuthkit/autopsy/images/fileset-icon-16.png"); //NON-NLS
}
/**
* Number of matches found for each of the MD5 children.
*
* @return int match count
*/
int getInstanceCount() {
return this.instanceCount;
}
/**
* Refresh the node, by dynamically loading in the children when called, and
* calling the CommonAttributeValueNodeFactory to generate nodes for the
* children in attributeValues.
*/
public void refresh() {
attributeValues.displayDelayedMetadata();
setChildren(Children.create(new CommonAttributeValueNodeFactory(attributeValues.getMetadataList()), true));
}
/**
* Get a list of metadata for the MD5s which are children of this object.
*
* @return List<Md5Metadata>
*/
CommonAttributeValueList getAttributeValues() {
return this.attributeValues;
}
@Override
public <T> T accept(DisplayableItemNodeVisitor<T> visitor) {
return visitor.visit(this);
}
@Override
public boolean isLeafTypeNode() {
return false;
}
@Override
public String getItemType() {
return getClass().getName();
}
@NbBundle.Messages({"InstanceCountNode.createSheet.noDescription= "})
@Override
protected Sheet createSheet() {
Sheet sheet = new Sheet();
Sheet.Set sheetSet = sheet.get(Sheet.PROPERTIES);
if (sheetSet == null) {
sheetSet = Sheet.createPropertiesSet();
sheet.put(sheetSet);
}
final String NO_DESCR = Bundle.InstanceCountNode_createSheet_noDescription();
sheetSet.put(new NodeProperty<>(Bundle.CommonFilesSearchResultsViewerTable_filesColLbl(), Bundle.CommonFilesSearchResultsViewerTable_filesColLbl(), NO_DESCR, ""));
sheetSet.put(new NodeProperty<>(Bundle.CommonFilesSearchResultsViewerTable_instancesColLbl(), Bundle.CommonFilesSearchResultsViewerTable_instancesColLbl(), NO_DESCR, this.getInstanceCount()));
sheetSet.put(new NodeProperty<>(Bundle.CommonFilesSearchResultsViewerTable_pathColLbl(), Bundle.CommonFilesSearchResultsViewerTable_pathColLbl(), NO_DESCR, ""));
sheetSet.put(new NodeProperty<>(Bundle.CommonFilesSearchResultsViewerTable_caseColLbl1(), Bundle.CommonFilesSearchResultsViewerTable_caseColLbl1(), NO_DESCR, ""));
sheetSet.put(new NodeProperty<>(Bundle.CommonFilesSearchResultsViewerTable_dataSourceColLbl(), Bundle.CommonFilesSearchResultsViewerTable_dataSourceColLbl(), NO_DESCR, ""));
sheetSet.put(new NodeProperty<>(Bundle.CommonFilesSearchResultsViewerTable_hashsetHitsColLbl(), Bundle.CommonFilesSearchResultsViewerTable_hashsetHitsColLbl(), NO_DESCR, ""));
sheetSet.put(new NodeProperty<>(Bundle.CommonFilesSearchResultsViewerTable_mimeTypeColLbl(), Bundle.CommonFilesSearchResultsViewerTable_mimeTypeColLbl(), NO_DESCR, ""));
sheetSet.put(new NodeProperty<>(Bundle.CommonFilesSearchResultsViewerTable_tagsColLbl1(), Bundle.CommonFilesSearchResultsViewerTable_tagsColLbl1(), NO_DESCR, ""));
return sheet;
}
/**
* ChildFactory which builds CommonFileParentNodes from the
* CommonAttributeValue metadata models.
*/
static class CommonAttributeValueNodeFactory extends ChildFactory<String> {
/**
* List of models, each of which is a parent node matching a single md5,
* containing children FileNodes.
*/
// maps sting version of value to value Object (??)
private final Map<String, CommonAttributeValue> metadata;
CommonAttributeValueNodeFactory(List<CommonAttributeValue> attributeValues) {
this.metadata = new HashMap<>();
Iterator<CommonAttributeValue> iterator = attributeValues.iterator();
while (iterator.hasNext()) {
CommonAttributeValue attributeValue = iterator.next();
this.metadata.put(attributeValue.getValue(), attributeValue);
}
}
@Override
protected boolean createKeys(List<String> list) {
// @@@ We should just use CommonAttributeValue as the key...
list.addAll(this.metadata.keySet());
return true;
}
@Override
protected Node createNodeForKey(String attributeValue) {
CommonAttributeValue md5Metadata = this.metadata.get(attributeValue);
return new CommonAttributeValueNode(md5Metadata);
}
}
}
| apache-2.0 |
java110/MicroCommunity | service-fee/src/main/java/com/java110/fee/bmo/feeDiscount/IUpdateFeeDiscountBMO.java | 433 | package com.java110.fee.bmo.feeDiscount;
import com.alibaba.fastjson.JSONArray;
import com.java110.po.feeDiscount.FeeDiscountPo;
import org.springframework.http.ResponseEntity;
public interface IUpdateFeeDiscountBMO {
/**
* 修改费用折扣
* add by wuxw
*
* @param feeDiscountPo
* @return
*/
ResponseEntity<String> update(FeeDiscountPo feeDiscountPo, JSONArray feeDiscountRuleSpecs);
}
| apache-2.0 |
sonu283304/onos | apps/openstacknetworking/web/src/main/java/org/onosproject/openstacknetworking/web/OpenstackSubnetWebResource.java | 2056 | /*
* Copyright 2015 Open Networking Laboratory
*
* 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 org.onosproject.openstacknetworking.web;
/**
* Handles Rest API call from Neutron ML2 plugin.
*/
import org.onosproject.rest.AbstractWebResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.InputStream;
@Path("subnets")
public class OpenstackSubnetWebResource extends AbstractWebResource {
protected static final Logger log = LoggerFactory
.getLogger(OpenstackSubnetWebResource.class);
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createSubnet(InputStream input) {
return Response.status(Response.Status.OK).build();
}
@PUT
@Path("{subnetId}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response updateSubnet(@PathParam("subnetId") String id,
final InputStream input) {
return Response.status(Response.Status.OK).build();
}
@DELETE
@Path("{subnetId}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteSubnet(@PathParam("subnetId") String id) {
return Response.status(Response.Status.OK).build();
}
}
| apache-2.0 |
youdonghai/intellij-community | platform/lang-impl/src/com/intellij/application/options/colors/FontOptions.java | 13068 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.application.options.colors;
import com.intellij.application.options.EditorFontsConstants;
import com.intellij.icons.AllIcons;
import com.intellij.ide.IdeTooltipManager;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.FontPreferences;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.ui.*;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.util.EventDispatcher;
import com.intellij.util.ui.JBUI;
import net.miginfocom.swing.MigLayout;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
public class FontOptions extends JPanel implements OptionsPanel{
private static final FontInfoRenderer RENDERER = new FontInfoRenderer() {
@Override
protected boolean isEditorFont() {
return true;
}
};
private final EventDispatcher<ColorAndFontSettingsListener> myDispatcher = EventDispatcher.create(ColorAndFontSettingsListener.class);
@NotNull private final ColorAndFontOptions myOptions;
@NotNull private final JTextField myEditorFontSizeField = new JTextField(4);
@NotNull private final JTextField myLineSpacingField = new JTextField(4);
private final FontComboBox myPrimaryCombo = new FontComboBox();
private final JCheckBox myUseSecondaryFontCheckbox = new JCheckBox(ApplicationBundle.message("secondary.font"));
private final JCheckBox myEnableLigaturesCheckbox = new JCheckBox(ApplicationBundle.message("use.ligatures"));
private final FontComboBox mySecondaryCombo = new FontComboBox(false, false);
@NotNull private final JBCheckBox myOnlyMonospacedCheckBox =
new JBCheckBox(ApplicationBundle.message("checkbox.show.only.monospaced.fonts"));
private boolean myIsInSchemeChange;
public FontOptions(@NotNull ColorAndFontOptions options) {
setLayout(new MigLayout("ins 0, gap 5, flowx"));
myOptions = options;
add(myOnlyMonospacedCheckBox, "newline 10, sgx b, sx 2");
add(new JLabel(ApplicationBundle.message("primary.font")), "newline, ax right");
add(myPrimaryCombo, "sgx b");
add(new JLabel(ApplicationBundle.message("editbox.font.size")), "gapleft 20");
add(myEditorFontSizeField);
add(new JLabel(ApplicationBundle.message("editbox.line.spacing")), "gapleft 20");
add(myLineSpacingField);
add(new JLabel(ApplicationBundle.message("label.fallback.fonts.list.description"),
MessageType.INFO.getDefaultIcon(),
SwingConstants.LEFT), "newline, sx 5");
add(myUseSecondaryFontCheckbox, "newline, ax right");
add(mySecondaryCombo, "sgx b");
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
myEnableLigaturesCheckbox.setBorder(null);
panel.add(myEnableLigaturesCheckbox);
JLabel warningIcon = new JLabel(AllIcons.General.BalloonWarning);
IdeTooltipManager.getInstance().setCustomTooltip(
warningIcon,
new TooltipWithClickableLinks.ForBrowser(warningIcon,
ApplicationBundle.message("ligatures.jre.warning",
ApplicationNamesInfo.getInstance().getFullProductName())));
warningIcon.setBorder(JBUI.Borders.emptyLeft(5));
updateWarningIconVisibility(warningIcon);
panel.add(warningIcon);
add(panel, "newline, sx 2");
myOnlyMonospacedCheckBox.setBorder(null);
myUseSecondaryFontCheckbox.setBorder(null);
mySecondaryCombo.setEnabled(false);
myOnlyMonospacedCheckBox.setSelected(EditorColorsManager.getInstance().isUseOnlyMonospacedFonts());
myOnlyMonospacedCheckBox.addActionListener(e -> {
EditorColorsManager.getInstance().setUseOnlyMonospacedFonts(myOnlyMonospacedCheckBox.isSelected());
myPrimaryCombo.setMonospacedOnly(myOnlyMonospacedCheckBox.isSelected());
mySecondaryCombo.setMonospacedOnly(myOnlyMonospacedCheckBox.isSelected());
});
myPrimaryCombo.setMonospacedOnly(myOnlyMonospacedCheckBox.isSelected());
myPrimaryCombo.setRenderer(RENDERER);
mySecondaryCombo.setMonospacedOnly(myOnlyMonospacedCheckBox.isSelected());
mySecondaryCombo.setRenderer(RENDERER);
myUseSecondaryFontCheckbox.addActionListener(e -> {
mySecondaryCombo.setEnabled(myUseSecondaryFontCheckbox.isSelected());
syncFontFamilies();
});
ItemListener itemListener = this::syncFontFamilies;
myPrimaryCombo.addItemListener(itemListener);
mySecondaryCombo.addItemListener(itemListener);
ActionListener actionListener = this::syncFontFamilies;
myPrimaryCombo.addActionListener(actionListener);
mySecondaryCombo.addActionListener(actionListener);
myEditorFontSizeField.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
public void textChanged(DocumentEvent event) {
if (myIsInSchemeChange || !SwingUtilities.isEventDispatchThread()) return;
String selectedFont = myPrimaryCombo.getFontName();
if (selectedFont != null) {
setFontSize(getFontSizeFromField());
}
updateDescription(true);
}
});
myEditorFontSizeField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() != KeyEvent.VK_UP && e.getKeyCode() != KeyEvent.VK_DOWN) return;
boolean up = e.getKeyCode() == KeyEvent.VK_UP;
try {
int value = Integer.parseInt(myEditorFontSizeField.getText());
value += (up ? 1 : -1);
value = Math.min(EditorFontsConstants.getMaxEditorFontSize(), Math.max(EditorFontsConstants.getMinEditorFontSize(), value));
myEditorFontSizeField.setText(String.valueOf(value));
}
catch (NumberFormatException ignored) {
}
}
});
myLineSpacingField.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
public void textChanged(DocumentEvent event) {
if (myIsInSchemeChange) return;
float lineSpacing = getLineSpacingFromField();
if (getLineSpacing() != lineSpacing) {
setCurrentLineSpacing(lineSpacing);
}
updateDescription(true);
}
});
myLineSpacingField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() != KeyEvent.VK_UP && e.getKeyCode() != KeyEvent.VK_DOWN) return;
boolean up = e.getKeyCode() == KeyEvent.VK_UP;
try {
float value = Float.parseFloat(myLineSpacingField.getText());
value += (up ? 1 : -1) * .1F;
value = Math.min(EditorFontsConstants.getMaxEditorLineSpacing(), Math.max(EditorFontsConstants.getMinEditorLineSpacing(), value));
myLineSpacingField.setText(String.format(Locale.ENGLISH, "%.1f", value));
}
catch (NumberFormatException ignored) {
}
}
});
myEnableLigaturesCheckbox.addActionListener(e -> {
getFontPreferences().setUseLigatures(myEnableLigaturesCheckbox.isSelected());
updateWarningIconVisibility(warningIcon);
updateDescription(true);
});
}
private void updateWarningIconVisibility(JLabel warningIcon) {
warningIcon.setVisible(!SystemInfo.isJetbrainsJvm && getFontPreferences().useLigatures());
}
private int getFontSizeFromField() {
try {
return Math.min(EditorFontsConstants.getMaxEditorFontSize(),
Math.max(EditorFontsConstants.getMinEditorFontSize(), Integer.parseInt(myEditorFontSizeField.getText())));
}
catch (NumberFormatException e) {
return EditorFontsConstants.getDefaultEditorFontSize();
}
}
private float getLineSpacingFromField() {
try {
return Math.min(EditorFontsConstants.getMaxEditorLineSpacing(), Math.max(EditorFontsConstants.getMinEditorLineSpacing(), Float.parseFloat(myLineSpacingField.getText())));
} catch (NumberFormatException e){
return EditorFontsConstants.getDefaultEditorLineSpacing();
}
}
/**
* Processes an event from {@code FontComboBox}
* if it is enabled and its item is selected.
*
* @param event the event to process
*/
private void syncFontFamilies(AWTEvent event) {
Object source = event.getSource();
if (source instanceof FontComboBox) {
FontComboBox combo = (FontComboBox)source;
if (combo.isEnabled() && combo.isShowing() && combo.getSelectedItem() != null) {
syncFontFamilies();
}
}
}
private void syncFontFamilies() {
if (myIsInSchemeChange) {
return;
}
FontPreferences fontPreferences = getFontPreferences();
fontPreferences.clearFonts();
String primaryFontFamily = myPrimaryCombo.getFontName();
String secondaryFontFamily = mySecondaryCombo.isEnabled() ? mySecondaryCombo.getFontName() : null;
int fontSize = getFontSizeFromField();
if (primaryFontFamily != null ) {
if (!FontPreferences.DEFAULT_FONT_NAME.equals(primaryFontFamily)) {
fontPreferences.addFontFamily(primaryFontFamily);
}
fontPreferences.register(primaryFontFamily, fontSize);
}
if (secondaryFontFamily != null) {
if (!FontPreferences.DEFAULT_FONT_NAME.equals(secondaryFontFamily)){
fontPreferences.addFontFamily(secondaryFontFamily);
}
fontPreferences.register(secondaryFontFamily, fontSize);
}
updateDescription(true);
}
@Override
public void updateOptionsList() {
myIsInSchemeChange = true;
myLineSpacingField.setText(Float.toString(getLineSpacing()));
FontPreferences fontPreferences = getFontPreferences();
List<String> fontFamilies = fontPreferences.getEffectiveFontFamilies();
myPrimaryCombo.setFontName(fontPreferences.getFontFamily());
boolean isThereSecondaryFont = fontFamilies.size() > 1;
myUseSecondaryFontCheckbox.setSelected(isThereSecondaryFont);
mySecondaryCombo.setFontName(isThereSecondaryFont ? fontFamilies.get(1) : null);
myEditorFontSizeField.setText(String.valueOf(fontPreferences.getSize(fontPreferences.getFontFamily())));
boolean readOnly = ColorAndFontOptions.isReadOnly(myOptions.getSelectedScheme());
myPrimaryCombo.setEnabled(!readOnly);
mySecondaryCombo.setEnabled(isThereSecondaryFont && !readOnly);
myOnlyMonospacedCheckBox.setEnabled(!readOnly);
myLineSpacingField.setEnabled(!readOnly);
myEditorFontSizeField.setEnabled(!readOnly);
myUseSecondaryFontCheckbox.setEnabled(!readOnly);
myEnableLigaturesCheckbox.setEnabled(!readOnly);
myEnableLigaturesCheckbox.setSelected(fontPreferences.useLigatures());
myIsInSchemeChange = false;
}
@NotNull
protected FontPreferences getFontPreferences() {
return getCurrentScheme().getFontPreferences();
}
protected void setFontSize(int fontSize) {
getCurrentScheme().setEditorFontSize(fontSize);
}
protected float getLineSpacing() {
return getCurrentScheme().getLineSpacing();
}
protected void setCurrentLineSpacing(float lineSpacing) {
getCurrentScheme().setLineSpacing(lineSpacing);
}
@Override
@Nullable
public Runnable showOption(final String option) {
return null;
}
@Override
public void applyChangesToScheme() {
}
@Override
public void selectOption(final String typeToSelect) {
}
protected EditorColorsScheme getCurrentScheme() {
return myOptions.getSelectedScheme();
}
public boolean updateDescription(boolean modified) {
EditorColorsScheme scheme = myOptions.getSelectedScheme();
if (modified && ColorAndFontOptions.isReadOnly(scheme)) {
return false;
}
myDispatcher.getMulticaster().fontChanged();
return true;
}
@Override
public void addListener(ColorAndFontSettingsListener listener) {
myDispatcher.addListener(listener);
}
@Override
public JPanel getPanel() {
return this;
}
@Override
public Set<String> processListOptions() {
return new HashSet<>();
}
}
| apache-2.0 |
ron-k/Dagged2-Hello-World | app/src/main/java/com/example/dagger2_hello_world/ApplicationModule.java | 596 | package com.example.dagger2_hello_world;
import android.content.Context;
import android.support.annotation.NonNull;
import javax.inject.Named;
import dagger.Binds;
import dagger.Module;
import dagger.Provides;
@Module
public abstract class ApplicationModule {
@Provides
@NonNull
static Application myApplication() {
return Application.getInstance();
}
@Binds
@NonNull
@Named(ApplicationScope.TAG)
abstract Context context(Application application);
@Binds
@NonNull
abstract android.app.Application application(Application application);
} | apache-2.0 |
jmini/asciidoctorj-experiments | code-converter/mock-code-converter/src/test/java/fr/jmini/asciidoctorj/converter/mockcode/MockCodeGeneratorListItemTest.java | 2308 | package fr.jmini.asciidoctorj.converter.mockcode;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Collections;
import org.asciidoctor.ast.ListItem;
import org.junit.Test;
import fr.jmini.asciidoctorj.converter.code.CodeTestingUtility;
public class MockCodeGeneratorListItemTest {
@Test
public void testListItem() throws Exception {
ListItem mockListItem = createMock();
MockCodeGenerator generator = new MockCodeGenerator();
StringBuilder sb = new StringBuilder();
generator.createListItemCode(sb, mockListItem);
CodeTestingUtility.testGeneratedCode(sb.toString(), this.getClass());
}
// tag::generated-code[]
public ListItem createMock() {
ListItem mockListItem1 = mock(ListItem.class);
when(mockListItem1.getId()).thenReturn("id");
when(mockListItem1.getNodeName()).thenReturn("node-name");
when(mockListItem1.getParent()).thenReturn(null);
when(mockListItem1.getContext()).thenReturn(null);
when(mockListItem1.getDocument()).thenReturn(null);
when(mockListItem1.isInline()).thenReturn(false);
when(mockListItem1.isBlock()).thenReturn(false);
when(mockListItem1.getAttributes()).thenReturn(Collections.emptyMap());
when(mockListItem1.getRoles()).thenReturn(Collections.emptyList());
when(mockListItem1.isReftext()).thenReturn(false);
when(mockListItem1.getReftext()).thenReturn(null);
when(mockListItem1.getCaption()).thenReturn(null);
when(mockListItem1.getTitle()).thenReturn("T");
when(mockListItem1.getStyle()).thenReturn("S");
when(mockListItem1.getLevel()).thenReturn(2);
when(mockListItem1.getContentModel()).thenReturn(null);
when(mockListItem1.getSourceLocation()).thenReturn(null);
when(mockListItem1.getSubstitutions()).thenReturn(Collections.emptyList());
when(mockListItem1.getBlocks()).thenReturn(Collections.emptyList());
when(mockListItem1.getMarker()).thenReturn("m");
when(mockListItem1.getText()).thenReturn("t");
when(mockListItem1.getSource()).thenReturn("s");
when(mockListItem1.hasText()).thenReturn(true);
return mockListItem1;
}
// end::generated-code[]
}
| apache-2.0 |
groupon/vertx-memcache | src/main/java/com/groupon/vertx/memcache/client/response/StoreCommandResponse.java | 1563 | /**
* Copyright 2014 Groupon.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.groupon.vertx.memcache.client.response;
/**
* Represents a memcache store response.
*
* @author Stuart Siegrist (fsiegrist at groupon dot com)
* @since 3.1.0
*/
public final class StoreCommandResponse extends MemcacheCommandResponse {
private final String data;
private StoreCommandResponse(Builder builder) {
super(builder);
data = builder.data;
}
public String getData() {
return data;
}
/**
* Builder for the StoreCommandResponse
*/
public static class Builder extends AbstractBuilder<Builder, StoreCommandResponse> {
private String data;
@Override
protected Builder self() {
return this;
}
public Builder setData(String value) {
data = value;
return self();
}
@Override
public StoreCommandResponse build() {
return new StoreCommandResponse(this);
}
}
}
| apache-2.0 |
wicloud/crop-image | CropperSample/src/com/yuqiaotech/erp/editimage/cropper/util/AspectRatioUtil.java | 3853 | /*
* Copyright 2013, Edmodo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License.
* You may obtain a copy of the License in the LICENSE file, or at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.yuqiaotech.erp.editimage.cropper.util;
import android.graphics.RectF;
import android.support.annotation.NonNull;
/**
* Utility class for handling calculations involving a fixed aspect ratio.
*/
public class AspectRatioUtil {
/**
* Calculates the aspect ratio given a rectangle.
*/
public static float calculateAspectRatio(float left, float top, float right, float bottom) {
final float width = right - left;
final float height = bottom - top;
return width / height;
}
/**
* Calculates the aspect ratio given a rectangle.
*/
public static float calculateAspectRatio(@NonNull RectF rect) {
return rect.width() / rect.height();
}
/**
* Calculates the x-coordinate of the left edge given the other sides of the rectangle and an
* aspect ratio.
*/
public static float calculateLeft(float top, float right, float bottom, float targetAspectRatio) {
final float height = bottom - top;
// targetAspectRatio = width / height
// width = targetAspectRatio * height
// right - left = targetAspectRatio * height
return right - (targetAspectRatio * height);
}
/**
* Calculates the y-coordinate of the top edge given the other sides of the rectangle and an
* aspect ratio.
*/
public static float calculateTop(float left, float right, float bottom, float targetAspectRatio) {
final float width = right - left;
// targetAspectRatio = width / height
// width = targetAspectRatio * height
// height = width / targetAspectRatio
// bottom - top = width / targetAspectRatio
return bottom - (width / targetAspectRatio);
}
/**
* Calculates the x-coordinate of the right edge given the other sides of the rectangle and an
* aspect ratio.
*/
public static float calculateRight(float left, float top, float bottom, float targetAspectRatio) {
final float height = bottom - top;
// targetAspectRatio = width / height
// width = targetAspectRatio * height
// right - left = targetAspectRatio * height
return (targetAspectRatio * height) + left;
}
/**
* Calculates the y-coordinate of the bottom edge given the other sides of the rectangle and an
* aspect ratio.
*/
public static float calculateBottom(float left, float top, float right, float targetAspectRatio) {
final float width = right - left;
// targetAspectRatio = width / height
// width = targetAspectRatio * height
// height = width / targetAspectRatio
// bottom - top = width / targetAspectRatio
return (width / targetAspectRatio) + top;
}
/**
* Calculates the width of a rectangle given the top and bottom edges and an aspect ratio.
*/
public static float calculateWidth(float height, float targetAspectRatio) {
return targetAspectRatio * height;
}
/**
* Calculates the height of a rectangle given the left and right edges and an aspect ratio.
*/
public static float calculateHeight(float width, float targetAspectRatio) {
return width / targetAspectRatio;
}
}
| apache-2.0 |
gchq/stroom | stroom-config/stroom-config-global-impl/src/main/java/stroom/config/global/impl/UserPreferencesDao.java | 303 | package stroom.config.global.impl;
import stroom.ui.config.shared.UserPreferences;
import java.util.Optional;
public interface UserPreferencesDao {
Optional<UserPreferences> fetch(String userId);
int update(String userId, UserPreferences userPreferences);
int delete(String userId);
}
| apache-2.0 |
mingwuyun/cocos2d-java | external/com/cocos2dj/module/btree/BhTree.java | 2892 | package com.cocos2dj.module.btree;
import java.util.HashMap;
import com.badlogic.gdx.ai.btree.BehaviorTree;
import com.badlogic.gdx.ai.btree.Task;
import com.badlogic.gdx.ai.btree.branch.Parallel;
import com.badlogic.gdx.ai.btree.branch.Parallel.Policy;
import com.badlogic.gdx.ai.btree.branch.Selector;
import com.badlogic.gdx.ai.btree.branch.Sequence;
import com.cocos2dj.macros.CCLog;
import com.cocos2dj.module.btree.BhTreeModel.StructBHTNode;
import com.cocos2dj.module.btree.BhLeafTask.DebugTask;
/**
* RcBHT.java
*
* 不用管类型
*
* @author xujun
*
*/
public class BhTree<T> extends BehaviorTree<T> {
static final String TAG = "RcBHT";
//fields>>
HashMap<String, BhLeafTask<T>> tasksMap = new HashMap<>();
private boolean pauseFlag;
//fields<<
public void pause() {
pauseFlag = true;
}
public void resume() {
pauseFlag = false;
}
//func>>
@SuppressWarnings("unchecked")
Task<T> createTask(String type, String name, String args) {
switch(type) {
case "leaf":
BhLeafTask<T> leaf;// = new RcLeafTask<T>();
//相同的name会缓存
if(name != null) {
leaf = tasksMap.get(name);
if(leaf != null) {
CCLog.debug(TAG, "find same leaf task : " + name);
return leaf;
}
if("debug".equals(args)) {
leaf = new DebugTask(name);
} else {
leaf = new BhLeafTask<T>();
}
tasksMap.put(name, leaf);
return leaf;
} else {
if("debug".equals(args)) {
leaf = new DebugTask(name);
} else {
leaf = new BhLeafTask<T>();
}
}
return leaf;
case "parallel":
if(args == null) {
return new Parallel<T>();
} else {
switch(args) {
case "selector":
return new Parallel<T>(Policy.Selector);
case "sequence":
return new Parallel<T>(Policy.Sequence);
}
CCLog.error(TAG, "pattern fail args = " + args + " need selector or sequence");
return null;
}
case "selector":
return new Selector<T>();
case "sequence":
return new Sequence<T>();
}
CCLog.error(TAG, "not found type : " + type);
return null;
}
final Task<T> createTask(StructBHTNode node) {
Task<T> ret = createTask(node.type, node.key, node.args);
if(ret == null) {
CCLog.error(TAG, "createTask fail ");
}
if(node.children != null) {
int len = node.children.length;
for(int i = 0; i < len; ++i) {
Task<T> child = createTask(node.children[i]);
ret.addChild(child);
}
}
return ret;
}
//func<<
//methods>>
public void setup(BhTreeModel model) {
Task<T> root = createTask(model.root);
addChild(root);
}
public void step() {
if(!pauseFlag) {
super.step();
}
}
public BhLeafTask<T> getLeaf(String key) {
BhLeafTask<T> ret = tasksMap.get(key);
// System.out.println("map = " + tasksMap.toString());
if(ret == null) {
CCLog.error(TAG, "task not found : " + key);
}
return ret;
}
//methods<<
}
| apache-2.0 |
shopping24/solr-thymeleaf | src/test/java/com/s24/search/solr/response/LuceneTemplateResolverIT.java | 1192 | package com.s24.search.solr.response;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.analysis.util.ResourceLoader;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.core.SolrResourceLoader;
import org.junit.Test;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.ITemplateResolver;
public class LuceneTemplateResolverIT
extends SolrTestCaseJ4 {
@Test
public void testTemplateResolverConfiguration04() throws Exception {
initCore();
ResourceLoader resourceLoader = new SolrResourceLoader(testSolrHome);
TemplateEngine templateEngine = new TemplateEngine();
LuceneTemplateResolver templateResolver = new LuceneTemplateResolver();
templateResolver.setResourceLoader(resourceLoader);
templateEngine.setTemplateResolver(templateResolver);
templateEngine.getConfiguration();
List<ITemplateResolver> templateResolvers = new ArrayList<>(templateEngine.getTemplateResolvers());
assertEquals(1, templateResolvers.size());
assertEquals("com.s24.search.solr.response.LuceneTemplateResolver", templateResolvers.get(0).getName());
}
} | apache-2.0 |
hkuhn42/bottery | bottery.connector.ms/src/main/java/rocks/bottery/connector/ms/model/OpenIdConfig.java | 4633 | /**
* Copyright (C) 2016-2018 Harald Kuhn
*
* 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 rocks.bottery.connector.ms.model;
import java.io.Serializable;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/*
{
"issuer":"https://api.botframework.com",
"authorization_endpoint":"https://invalid.botframework.com/",
"jwks_uri":"https://login.botframework.com/v1/keys",
"id_token_signing_alg_values_supported":["RSA256"],
"token_endpoint_auth_methods_supported":["private_key_jwt"]
}
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class OpenIdConfig implements Serializable {
private static final long serialVersionUID = 1L;
@XmlElement(name = "issuer")
private String issuer;
@XmlElement(name = "authorization_endpoint")
private String authorizationEndpoint;
@XmlElement(name = "jwks_uri")
private String jwksUri;
@XmlElement(name = "id_token_signing_alg_values_supported")
private List<String> idTokenSigningAlgValuesSupported = null;
@XmlElement(name = "token_endpoint_auth_methods_supported")
private List<String> tokenEndpointAuthMethodsSupported = null;
/**
*
* @return The issuer
*/
public String getIssuer() {
return issuer;
}
/**
*
* @param issuer
* The issuer
*/
public void setIssuer(String issuer) {
this.issuer = issuer;
}
/**
*
* @return The authorizationEndpoint
*/
public String getAuthorizationEndpoint() {
return authorizationEndpoint;
}
/**
*
* @param authorizationEndpoint
* The authorization_endpoint
*/
public void setAuthorizationEndpoint(String authorizationEndpoint) {
this.authorizationEndpoint = authorizationEndpoint;
}
/**
*
* @return The jwksUri
*/
public String getJwksUri() {
return jwksUri;
}
/**
*
* @param jwksUri
* The jwks_uri
*/
public void setJwksUri(String jwksUri) {
this.jwksUri = jwksUri;
}
/**
*
* @return The idTokenSigningAlgValuesSupported
*/
public List<String> getIdTokenSigningAlgValuesSupported() {
return idTokenSigningAlgValuesSupported;
}
/**
*
* @param idTokenSigningAlgValuesSupported
* The id_token_signing_alg_values_supported
*/
public void setIdTokenSigningAlgValuesSupported(List<String> idTokenSigningAlgValuesSupported) {
this.idTokenSigningAlgValuesSupported = idTokenSigningAlgValuesSupported;
}
/**
*
* @return The tokenEndpointAuthMethodsSupported
*/
public List<String> getTokenEndpointAuthMethodsSupported() {
return tokenEndpointAuthMethodsSupported;
}
/**
*
* @param tokenEndpointAuthMethodsSupported
* The token_endpoint_auth_methods_supported
*/
public void setTokenEndpointAuthMethodsSupported(List<String> tokenEndpointAuthMethodsSupported) {
this.tokenEndpointAuthMethodsSupported = tokenEndpointAuthMethodsSupported;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class OpenIdConfig {\n");
sb.append(" issuer: ").append(toIndentedString(issuer)).append("\n");
sb.append(" authorization_endpoint: ").append(toIndentedString(authorizationEndpoint)).append("\n");
sb.append(" jwksUri: ").append(toIndentedString(jwksUri)).append("\n");
sb.append(" tokenEndpointAuthMethodsSupported: ")
.append(toIndentedString(this.tokenEndpointAuthMethodsSupported)).append("\n");
sb.append(" id_token_signing_alg_values_supported: ")
.append(toIndentedString(this.idTokenSigningAlgValuesSupported)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private static String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| apache-2.0 |
rabix/bunny | rabix-bindings-cwl/src/main/java/org/rabix/bindings/cwl/bean/CWLWorkflow.java | 3152 | package org.rabix.bindings.cwl.bean;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.rabix.bindings.cwl.json.CWLStepsDeserializer;
import org.rabix.bindings.model.ValidationReport;
import org.rabix.common.json.BeanPropertyView;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
@JsonDeserialize(as = CWLWorkflow.class)
public class CWLWorkflow extends CWLJobApp {
@JsonProperty("steps")
@JsonDeserialize(using = CWLStepsDeserializer.class)
private List<CWLStep> steps;
@JsonProperty("dataLinks")
@JsonView(BeanPropertyView.Full.class)
private List<CWLDataLink> dataLinks;
public CWLWorkflow() {
this.steps = new ArrayList<>();
this.dataLinks = new ArrayList<>();
}
public CWLWorkflow(List<CWLStep> steps, List<CWLDataLink> dataLinks) {
this.steps = steps;
this.dataLinks = dataLinks;
}
@JsonIgnore
public void addDataLink(CWLDataLink dataLink) {
this.dataLinks.add(dataLink);
}
@JsonIgnore
public void addDataLinks(List<CWLDataLink> dataLinks) {
this.dataLinks.addAll(dataLinks);
}
public List<CWLStep> getSteps() {
return steps;
}
public List<CWLDataLink> getDataLinks() {
return dataLinks;
}
@Override
public String toString() {
return "Workflow [steps=" + steps + ", dataLinks=" + dataLinks + ", id=" + getId() + ", context=" + getContext()
+ ", description=" + getDescription() + ", inputs=" + getInputs() + ", outputs=" + getOutputs() + ", requirements="
+ requirements + "]";
}
@Override
@JsonIgnore
public CWLJobAppType getType() {
return CWLJobAppType.WORKFLOW;
}
private Set<String> checkStepDuplicates() {
Set<String> duplicates = new HashSet<>();
Set<String> ids = new HashSet<>();
for (CWLStep step : steps) {
if (!ids.add(step.getId())) {
duplicates.add(step.getId());
}
}
return duplicates;
}
// private Set<String> unconnectedOutputs() {
//
// }
//
// private Set<String> unconnectedSteps() {
//
// }
//
// private Set<String> unconnectedInputs() {
//
// }
@Override
public ValidationReport validate() {
List<ValidationReport.Item> messages = new ArrayList<>();
messages.addAll(ValidationReport.messagesToItems(validatePortUniqueness(), ValidationReport.Severity.ERROR));
for (String duplicate : checkStepDuplicates()) {
messages.add(ValidationReport.error("Duplicate step id: " + duplicate));
}
if (steps == null || steps.isEmpty()) {
messages.add(ValidationReport.error("Workflow has no steps"));
}
for (CWLStep step : steps) {
for (ValidationReport.Item item : step.getApp().validate().getItems()) {
messages.add(
ValidationReport.item(
item.getSeverity() + " from app in step '" + step.getId() + "': " + item.getMessage(),
item.getSeverity())
);
}
}
return new ValidationReport(messages);
}
}
| apache-2.0 |
a1018875550/PermissionDispatcher | library/src/main/java/org/jokar/permissiondispatcher/annotation/NeedsPermission.java | 431 | package org.jokar.permissiondispatcher.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Register some methods which permissions are needed.
* Created by JokAr on 16/8/22.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @interface NeedsPermission {
String[] value();
}
| apache-2.0 |
Adobe-Marketing-Cloud/htl-tck | src/test/java/io/sightly/tck/html/HTMLExtractorTest.java | 4580 | /*******************************************************************************
* Copyright 2017 Adobe Systems Incorporated
*
* 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 io.sightly.tck.html;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class HTMLExtractorTest {
@Test
public void testHasAttribute() {
assertTrue(HTMLExtractor.hasAttribute("hasAttribute-t01", "<div id='test' title></div>", "#test", "title"));
assertTrue(HTMLExtractor.hasAttribute("hasAttribute-t02", "<div id='test' title='a title'></div>", "#test", "title"));
assertTrue(HTMLExtractor.hasAttribute("hasAttribute-t03", "<div id='test' title=''></div>", "#test", "title"));
assertFalse(HTMLExtractor.hasAttribute("hasAttribute-t04", "<div id='test'></div>", "#test", "title"));
}
@Test
public void testHasAttributeValue() {
class Combination {
private String url;
private String markup;
private String selector;
private String attributeName;
private String attributeValue;
private boolean expectedTrue;
private Combination(String url,
String markup,
String selector,
String attributeName,
String attributeValue,
boolean expectedTrue) {
this.url = url;
this.markup = markup;
this.selector = selector;
this.attributeName = attributeName;
this.attributeValue = attributeValue;
this.expectedTrue = expectedTrue;
}
}
Combination[] combinations = new Combination[]{
new Combination("hasAttributeValue-t01", "<div id=\"test\" title=\"something\"></div>", "#test", "title", "", false),
new Combination("hasAttributeValue-t01", "<div id=\"test\" title=\"something\"></div>", "#test", "title", "something", true),
new Combination("hasAttributeValue-t02", "<div id=\"test\" title=\"\"></div>", "#test", "title", "", true),
new Combination("hasAttributeValue-t02", "<div id=\"test\" title=\"\"></div>", "#test", "title", "something", false),
new Combination("hasAttributeValue-t03", "<div id=\"test\" title></div>", "#test", "title", "", true),
new Combination("hasAttributeValue-t03", "<div id=\"test\" title></div>", "#test", "title", "something", false),
new Combination("hasAttributeValue-t04", "<div id=\"test\"></div>", "#test", "title", "", false),
new Combination("hasAttributeValue-t04", "<div id=\"test\"></div>", "#test", "title", "something", false)
};
StringBuilder sb = new StringBuilder();
int index = 0;
for (Combination c : combinations) {
String message =
String.format("%s: Expected %s when looking up a%s existing attribute named %s with value %s for selector %s in \n " +
" %s",
c.url,
c.expectedTrue,
c.expectedTrue ? "n" : " not",
"'" + c.attributeName + "'",
c.attributeValue == null ? null : "'" + c.attributeValue + "'",
c.selector,
c.markup);
if (c.expectedTrue != HTMLExtractor.hasAttributeValue(c.url, c.markup, c.selector, c.attributeName, c.attributeValue)) {
if (index++ == 0) {
sb.append("\n");
}
sb.append(message).append("\n");
}
}
if (sb.length() > 0) {
fail(sb.toString());
}
}
}
| apache-2.0 |
parshimers/incubator-asterixdb | asterix-installer/src/main/java/edu/uci/ics/asterix/installer/driver/InstallerUtil.java | 3396 | /*
* Copyright 2009-2013 by The Regents of the University of California
* 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 from
*
* 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 edu.uci.ics.asterix.installer.driver;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import edu.uci.ics.asterix.common.configuration.AsterixConfiguration;
import edu.uci.ics.asterix.event.schema.cluster.Cluster;
import edu.uci.ics.asterix.event.schema.cluster.Node;
public class InstallerUtil {
private static final String DEFAULT_ASTERIX_CONFIGURATION_PATH = "conf" + File.separator
+ "asterix-configuration.xml";
public static final String TXN_LOG_DIR = "txnLogs";
public static final String TXN_LOG_DIR_KEY_SUFFIX = "txnLogDir";
public static final String ASTERIX_CONFIGURATION_FILE = "asterix-configuration.xml";
public static final String TXN_LOG_CONFIGURATION_FILE = "log.properties";
public static final int CLUSTER_NET_PORT_DEFAULT = 1098;
public static final int CLIENT_NET_PORT_DEFAULT = 1099;
public static final int HTTP_PORT_DEFAULT = 8888;
public static final int WEB_INTERFACE_PORT_DEFAULT = 19001;
public static String getNodeDirectories(String asterixInstanceName, Node node, Cluster cluster) {
String storeDataSubDir = asterixInstanceName + File.separator + "data" + File.separator;
String[] storeDirs = null;
StringBuffer nodeDataStore = new StringBuffer();
String storeDirValue = node.getStore();
if (storeDirValue == null) {
storeDirValue = cluster.getStore();
if (storeDirValue == null) {
throw new IllegalStateException(" Store not defined for node " + node.getId());
}
storeDataSubDir = node.getId() + File.separator + storeDataSubDir;
}
storeDirs = storeDirValue.split(",");
for (String ns : storeDirs) {
nodeDataStore.append(ns + File.separator + storeDataSubDir.trim());
nodeDataStore.append(",");
}
nodeDataStore.deleteCharAt(nodeDataStore.length() - 1);
return nodeDataStore.toString();
}
public static AsterixConfiguration getAsterixConfiguration(String asterixConf) throws FileNotFoundException,
IOException, JAXBException {
if (asterixConf == null) {
asterixConf = InstallerDriver.getManagixHome() + File.separator + DEFAULT_ASTERIX_CONFIGURATION_PATH;
}
File file = new File(asterixConf);
JAXBContext ctx = JAXBContext.newInstance(AsterixConfiguration.class);
Unmarshaller unmarshaller = ctx.createUnmarshaller();
AsterixConfiguration asterixConfiguration = (AsterixConfiguration) unmarshaller.unmarshal(file);
return asterixConfiguration;
}
}
| apache-2.0 |
52North/geoar-app | src/main/java/org/n52/geoar/newdata/InstalledPluginHolder.java | 7501 | /**
* Copyright 2012 52°North Initiative for Geospatial Open Source Software GmbH
*
* 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 org.n52.geoar.newdata;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.n52.geoar.newdata.Annotations;
import org.n52.geoar.newdata.DataSource;
import org.n52.geoar.newdata.Filter;
import org.n52.geoar.GeoARApplication;
import org.n52.geoar.newdata.CheckList.CheckManager;
import org.n52.geoar.newdata.PluginLoader.PluginInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Parcel;
import dalvik.system.DexClassLoader;
import dalvik.system.DexFile;
public class InstalledPluginHolder extends PluginHolder {
private List<DataSourceHolder> mDataSources = new ArrayList<DataSourceHolder>();
private File pluginFile;
private Long version;
private String identifier;
private boolean loaded = false;
private String description;
private String name;
private Context mPluginContext;
private Bitmap pluginIcon;
private String publisher;
@CheckManager
private CheckList<InstalledPluginHolder>.Checker mChecker;
private DexClassLoader mPluginDexClassLoader;
private boolean iconLoaded;
private static final Logger LOG = LoggerFactory
.getLogger(InstalledPluginHolder.class);
public InstalledPluginHolder(PluginInfo pluginInfo) {
this.version = pluginInfo.version;
this.identifier = pluginInfo.identifier;
this.description = pluginInfo.description;
this.name = pluginInfo.name;
this.pluginFile = pluginInfo.pluginFile;
this.publisher = pluginInfo.publisher;
}
@Override
public String getIdentifier() {
return identifier;
}
@Override
public String getName() {
return name;
}
@Override
public String getPublisher() {
return publisher;
}
@Override
public Long getVersion() {
return version;
}
public String getDescription() {
return description;
};
/**
* Changes to the returned list do not affect loaded data sources
*
* @return
*/
public List<DataSourceHolder> getDataSources() {
if (!loaded) {
try {
loadPlugin();
} catch (IOException e) {
e.printStackTrace();
}
}
return mDataSources;
}
public File getPluginFile() {
return pluginFile;
}
public void setChecked(boolean state) {
mChecker.setChecked(state);
}
public boolean isChecked() {
return mChecker.isChecked();
}
@SuppressLint("NewApi")
private void loadPlugin() throws IOException {
mDataSources.clear();
String pluginBaseFileName = getPluginFile().getName().substring(0,
getPluginFile().getName().lastIndexOf("."));
// Check if the Plugin exists
if (!getPluginFile().exists())
throw new FileNotFoundException("Not found: " + getPluginFile());
File tmpDir = GeoARApplication.applicationContext.getDir(
pluginBaseFileName, 0);
Enumeration<String> entries = DexFile
.loadDex(
getPluginFile().getAbsolutePath(),
tmpDir.getAbsolutePath() + "/" + pluginBaseFileName
+ ".dex", 0).entries();
// Path for optimized dex equals path which will be used by
// dexClassLoader
// create separate ClassLoader for each plugin
mPluginDexClassLoader = new DexClassLoader(getPluginFile()
.getAbsolutePath(), tmpDir.getAbsolutePath(), null,
GeoARApplication.applicationContext.getClassLoader());
try {
while (entries.hasMoreElements()) {
// Check each classname for annotations
String entry = entries.nextElement();
Class<?> entryClass = mPluginDexClassLoader.loadClass(entry);
if (entryClass
.isAnnotationPresent(Annotations.DataSource.class)) {
// Class is a annotated as datasource
if (org.n52.geoar.newdata.DataSource.class
.isAssignableFrom(entryClass)) {
// Class is a datasource
@SuppressWarnings("unchecked")
DataSourceHolder dataSourceHolder = new DataSourceHolder(
(Class<? extends DataSource<? super Filter>>) entryClass,
this);
mDataSources.add(dataSourceHolder);
} else {
LOG.error("Datasource " + entryClass.getSimpleName()
+ " is not implementing DataSource interface");
// TODO handle error, somehow propagate back to user
}
}
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("Dex changed");
} catch (LinkageError e) {
LOG.error("Data source " + getName() + " uses invalid class, "
+ e.getMessage());
}
loaded = true;
}
/**
* Returns a {@link Context} wrapping the
* {@link GeoARApplication#applicationContext}, but returning the value of
* {@link InstalledPluginHolder#getPluginResources()} as
* {@link Context#getResources()} return value.
*
* @return
*/
public Context getPluginContext() {
if (mPluginContext == null) {
mPluginContext = new PluginContext(
GeoARApplication.applicationContext, this);
}
return mPluginContext;
}
public ClassLoader getPluginClassLoader() {
return mPluginDexClassLoader;
}
@Override
public Bitmap getPluginIcon() {
if (!iconLoaded) {
try {
iconLoaded = true;
ZipFile zipFile = new ZipFile(pluginFile);
ZipEntry pluginIconEntry = zipFile.getEntry("icon.png");
if (pluginIconEntry != null) {
pluginIcon = BitmapFactory.decodeStream(zipFile
.getInputStream(pluginIconEntry));
} else {
LOG.info("Plugin " + getName() + " has no icon");
}
} catch (IOException e) {
LOG.error("Plugin " + getName() + " has an invalid icon");
}
}
return pluginIcon;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(getClass().getName());
super.writeToParcel(dest, flags);
}
public void saveState(ObjectOutputStream objectOutputStream)
throws IOException {
objectOutputStream.writeBoolean(isChecked());
for (DataSourceHolder dataSource : mDataSources) {
dataSource.saveState(objectOutputStream);
}
}
public void restoreState(PluginStateInputStream objectInputStream)
throws IOException {
setChecked(objectInputStream.readBoolean());
for (DataSourceHolder dataSource : mDataSources) {
dataSource.restoreState(objectInputStream);
}
}
/**
* Should be called after all state initialization took place, e.g. after
* {@link InstalledPluginHolder#restoreState(PluginStateInputStream)}
*/
public void postConstruct() {
for (DataSourceHolder dataSource : mDataSources) {
dataSource.postConstruct();
}
}
}
| apache-2.0 |
gbif/metrics | metrics-es/src/main/java/org/gbif/metrics/es/Parameter.java | 1522 | /*
* Copyright 2020 Global Biodiversity Information Facility (GBIF)
*
* 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 org.gbif.metrics.es;
import java.util.Objects;
/** Query parameter. */
public class Parameter {
private final String name;
private final String value;
/**
* @param name parameter name/key
* @param value parameter value
*/
public Parameter(String name, String value) {
this.name = name;
this.value = value;
}
/** @return parameter name/key */
public String getName() {
return name;
}
/** @return parameter value */
public String getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Parameter parameter = (Parameter) o;
return name.equals(parameter.name) && value.equals(parameter.value);
}
@Override
public int hashCode() {
return Objects.hash(name, value);
}
}
| apache-2.0 |
pacozaa/BoofCV | main/ip/benchmark/boofcv/abst/filter/convolve/BenchmarkConvolve.java | 7931 | /*
* Copyright (c) 2011-2015, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.abst.filter.convolve;
import boofcv.alg.filter.convolve.ConvolveImageNoBorder;
import boofcv.alg.filter.convolve.ConvolveUnsafe_U8;
import boofcv.alg.filter.convolve.ConvolveWithBorder;
import boofcv.alg.filter.convolve.noborder.*;
import boofcv.alg.misc.ImageMiscOps;
import boofcv.core.image.border.BorderIndex1D_Extend;
import boofcv.core.image.border.ImageBorder1D_S32;
import boofcv.factory.filter.kernel.FactoryKernelGaussian;
import boofcv.struct.convolve.Kernel1D_F32;
import boofcv.struct.convolve.Kernel1D_I32;
import boofcv.struct.convolve.Kernel2D_F32;
import boofcv.struct.convolve.Kernel2D_I32;
import boofcv.struct.image.ImageFloat32;
import boofcv.struct.image.ImageSInt16;
import boofcv.struct.image.ImageSInt32;
import boofcv.struct.image.ImageUInt8;
import java.util.Random;
/**
* Benchmark for different convolution operations.
* @author Peter Abeles
*/
@SuppressWarnings({"UnusedDeclaration"})
public class BenchmarkConvolve {
static int width = 640;
static int height = 480;
Random rand = new Random(234);
static Kernel2D_F32 kernel2D_F32;
static Kernel1D_F32 kernelF32;
static Kernel1D_I32 kernelI32;
static Kernel2D_I32 kernel2D_I32;
static ImageFloat32 input_F32 = new ImageFloat32(width,height);
static ImageFloat32 out_F32 = new ImageFloat32(width,height);
static ImageUInt8 input_U8 = new ImageUInt8(width,height);
static ImageSInt16 input_S16 = new ImageSInt16(width,height);
static ImageUInt8 out_U8 = new ImageUInt8(width,height);
static ImageSInt16 out_S16 = new ImageSInt16(width,height);
static ImageSInt32 out_S32 = new ImageSInt32(width,height);
// iterate through different sized kernel radius
// @Param({"1", "2"})
private int radius;
public BenchmarkConvolve() {
ImageMiscOps.fillUniform(input_U8,rand,0,20);
ImageMiscOps.fillUniform(input_S16,rand,0,20);
ImageMiscOps.fillUniform(input_F32,rand,0,20);
}
protected void setUp() throws Exception {
kernelF32 = FactoryKernelGaussian.gaussian(Kernel1D_F32.class, -1, radius);
kernelI32 = FactoryKernelGaussian.gaussian(Kernel1D_I32.class,-1,radius);
kernel2D_F32 = FactoryKernelGaussian.gaussian(Kernel2D_F32.class,-1,radius);
kernel2D_I32 = FactoryKernelGaussian.gaussian(Kernel2D_I32.class, -1, radius);
}
public int timeHorizontal_F32(int reps) {
for( int i = 0; i < reps; i++ )
ConvolveImageStandard.horizontal(kernelF32, input_F32,out_F32);
return 0;
}
public int timeHorizontal_I8_I8_div2(int reps) {
for( int i = 0; i < reps; i++ )
ConvolveImageStandard.horizontal(kernelI32, input_U8, out_U8, 10);
return 0;
}
public int timeHorizontalUnroll_I8_I8_div(int reps) {
for( int i = 0; i < reps; i++ )
if( !ConvolveImageUnrolled_U8_I8_Div.horizontal(kernelI32, input_U8, out_U8,10) )
throw new RuntimeException();
return 0;
}
public int timeHorizontal_I8_I16(int reps) {
for( int i = 0; i < reps; i++ )
ConvolveImageStandard.horizontal(kernelI32, input_U8, out_S16);
return 0;
}
public int timeHorizontal_I16_I16(int reps) {
for( int i = 0; i < reps; i++ )
ConvolveImageStandard.horizontal(kernelI32, input_S16, out_S16);
return 0;
}
public int timeVertical_F32(int reps) {
for( int i = 0; i < reps; i++ )
ConvolveImageStandard.vertical(kernelF32, input_F32, out_F32);
return 0;
}
public int timeVertical_I8_I8_div(int reps) {
for( int i = 0; i < reps; i++ )
ConvolveImageStandard.vertical(kernelI32, input_U8, out_U8,10);
return 0;
}
public int timeVerticalUnrolled_U8_I8_div(int reps) {
for( int i = 0; i < reps; i++ )
if( !ConvolveImageUnrolled_U8_I8_Div.vertical(kernelI32, input_U8, out_U8,10) )
throw new RuntimeException();
return 0;
}
public int timeVertical_I8_I16(int reps) {
for( int i = 0; i < reps; i++ )
ConvolveImageStandard.vertical(kernelI32, input_U8, out_S16);
return 0;
}
public int timeVertical_I16_I16(int reps) {
for( int i = 0; i < reps; i++ )
ConvolveImageStandard.vertical(kernelI32, input_S16, out_S16);
return 0;
}
public int timeConvolve2D_F32(int reps) {
for( int i = 0; i < reps; i++ )
ConvolveImageNoBorder.convolve(kernel2D_F32, input_F32, out_F32);
return 0;
}
public int timeConvolve2D_Std_F32(int reps) {
for( int i = 0; i < reps; i++ )
ConvolveImageStandard.convolve(kernel2D_F32, input_F32,out_F32);
return 0;
}
public int timeConvolve2D_Unrolled_F32(int reps) {
for( int i = 0; i < reps; i++ )
if( !ConvolveImageUnrolled_F32_F32.convolve(kernel2D_F32, input_F32,out_F32) )
throw new RuntimeException();
return 0;
}
public int timeConvolve2D_I8_I16(int reps) {
for( int i = 0; i < reps; i++ )
ConvolveImageNoBorder.convolve(kernel2D_I32, input_U8, out_S16);
return 0;
}
public int timeConvolve2D_Extend_I8_I16(int reps) {
for( int i = 0; i < reps; i++ )
ConvolveWithBorder.convolve(kernel2D_I32, input_U8, out_S16, new ImageBorder1D_S32(BorderIndex1D_Extend.class));
return 0;
}
public int timeConvolve2D_Std_I8_I8_DIV(int reps) {
for( int i = 0; i < reps; i++ )
ConvolveImageStandard.convolve(kernel2D_I32, input_U8, out_U8,10);
return 0;
}
public int timeConvolve2D_I8_I8_DIV(int reps) {
for( int i = 0; i < reps; i++ )
ConvolveImageNoBorder.convolve(kernel2D_I32, input_U8, out_U8,10);
return 0;
}
public int timeConvolveUnsafe2D_I8_I8_DIV(int reps) {
for( int i = 0; i < reps; i++ )
ConvolveUnsafe_U8.convolve(kernel2D_I32, input_U8, out_U8, 10);
return 0;
}
public int timeConvolve2D_Std_I8_I16(int reps) {
for( int i = 0; i < reps; i++ )
ConvolveImageNoBorder.convolve(kernel2D_I32, input_U8, out_U8,10);
return 0;
}
public int timeHorizontalUnrolled_F32(int reps) {
for( int i = 0; i < reps; i++ )
if( !ConvolveImageUnrolled_F32_F32.horizontal(kernelF32, input_F32,out_F32) )
throw new RuntimeException();
return 0;
}
public int timeVerticalUnrolled_F32(int reps) {
for( int i = 0; i < reps; i++ )
if( !ConvolveImageUnrolled_F32_F32.vertical(kernelF32, input_F32, out_F32) )
throw new RuntimeException();
return 0;
}
public int timeHorizontalUnrolled_U8(int reps) {
for( int i = 0; i < reps; i++ )
if( !ConvolveImageUnrolled_U8_I16.horizontal(kernelI32, input_U8, out_S16) )
throw new RuntimeException();
return 0;
}
public int timeVerticalUnrolled_U8(int reps) {
for( int i = 0; i < reps; i++ )
if( !ConvolveImageUnrolled_U8_I16.vertical(kernelI32, input_U8, out_S16) )
throw new RuntimeException();
return 0;
}
public int timeHorizontalUnrolled_I16(int reps) {
for( int i = 0; i < reps; i++ )
if( !ConvolveImageUnrolled_S16_I16.horizontal(kernelI32, input_S16, out_S16) )
throw new RuntimeException();
return 0;
}
public int timeVerticalUnrolled_I16(int reps) {
for( int i = 0; i < reps; i++ )
if( !ConvolveImageUnrolled_S16_I16.vertical(kernelI32, input_S16, out_S16) )
throw new RuntimeException();
return 0;
}
public int timeBox_U8_S32_Vertical6(int reps) {
for( int i = 0; i < reps; i++ )
ImplConvolveBox.vertical(input_U8, out_S32,radius);
return 0;
}
// public static void main( String args[] ) {
// System.out.println("========= Profile Image Size "+ width +" x "+ height +" ==========");
//
// Runner.main(BenchmarkConvolve.class, args);
// }
}
| apache-2.0 |
pdxrunner/geode | geode-core/src/main/java/org/apache/geode/internal/tcp/TCPConduit.java | 37478 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.tcp;
import java.io.IOException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import javax.net.ssl.SSLException;
import org.apache.logging.log4j.Logger;
import org.apache.geode.CancelCriterion;
import org.apache.geode.CancelException;
import org.apache.geode.SystemFailure;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.distributed.DistributedSystemDisconnectedException;
import org.apache.geode.distributed.internal.DMStats;
import org.apache.geode.distributed.internal.DistributionConfig;
import org.apache.geode.distributed.internal.DistributionManager;
import org.apache.geode.distributed.internal.DistributionMessage;
import org.apache.geode.distributed.internal.LonerDistributionManager;
import org.apache.geode.distributed.internal.direct.DirectChannel;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.distributed.internal.membership.MembershipManager;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.internal.logging.LoggingExecutors;
import org.apache.geode.internal.logging.LoggingThread;
import org.apache.geode.internal.logging.log4j.AlertAppender;
import org.apache.geode.internal.logging.log4j.LogMarker;
import org.apache.geode.internal.net.SocketCreator;
import org.apache.geode.internal.net.SocketCreatorFactory;
import org.apache.geode.internal.security.SecurableCommunicationChannel;
/**
* <p>
* TCPConduit manages a server socket and a collection of connections to other systems. Connections
* are identified by DistributedMember IDs. These types of messages are currently supported:
* </p>
*
* <pre>
* <p>
* DistributionMessage - message is delivered to the server's
* ServerDelegate
* <p>
* </pre>
* <p>
* In the current implementation, ServerDelegate is the DirectChannel used by the GemFire
* DistributionManager to send and receive messages.
* <p>
* If the ServerDelegate is null, DistributionMessages are ignored by the TCPConduit.
* </p>
*
* @since GemFire 2.0
*/
public class TCPConduit implements Runnable {
private static final Logger logger = LogService.getLogger();
/**
* max amount of time (ms) to wait for listener threads to stop
*/
private static int LISTENER_CLOSE_TIMEOUT;
/**
* backlog is the "accept" backlog configuration parameter all conduits server socket
*/
private static int BACKLOG;
/**
* use javax.net.ssl.SSLServerSocketFactory?
*/
static boolean useSSL;
/**
* Force use of Sockets rather than SocketChannels (NIO). Note from Bruce: due to a bug in the
* java VM, NIO cannot be used with IPv6 addresses on Windows. When that condition holds, the
* useNIO flag must be disregarded.
*/
private static boolean USE_NIO;
/**
* use direct ByteBuffers instead of heap ByteBuffers for NIO operations
*/
static boolean useDirectBuffers;
/**
* The socket producer used by the cluster
*/
private final SocketCreator socketCreator;
private MembershipManager membershipManager;
/**
* true if NIO can be used for the server socket
*/
private boolean useNIO;
static {
init();
}
public MembershipManager getMembershipManager() {
return membershipManager;
}
public static int getBackLog() {
return BACKLOG;
}
public static void init() {
useSSL = Boolean.getBoolean("p2p.useSSL");
// only use nio if not SSL
USE_NIO = !useSSL && !Boolean.getBoolean("p2p.oldIO");
// only use direct buffers if we are using nio
useDirectBuffers = USE_NIO && !Boolean.getBoolean("p2p.nodirectBuffers");
LISTENER_CLOSE_TIMEOUT = Integer.getInteger("p2p.listenerCloseTimeout", 60000).intValue();
// fix for bug 37730
BACKLOG = Integer.getInteger("p2p.backlog", HANDSHAKE_POOL_SIZE + 1).intValue();
}
///////////////// permanent conduit state
/**
* the size of OS TCP/IP buffers, not set by default
*/
public int tcpBufferSize = DistributionConfig.DEFAULT_SOCKET_BUFFER_SIZE;
public int idleConnectionTimeout = DistributionConfig.DEFAULT_SOCKET_LEASE_TIME;
/**
* port is the tcp/ip port that this conduit binds to. If it is zero, a port from
* membership-port-range is selected to bind to. The actual port number this conduit is listening
* on will be in the "id" instance variable
*/
private int port;
private int[] tcpPortRange = new int[] {DistributionConfig.DEFAULT_MEMBERSHIP_PORT_RANGE[0],
DistributionConfig.DEFAULT_MEMBERSHIP_PORT_RANGE[1]};
/**
* The java groups address that this conduit is associated with
*/
private InternalDistributedMember localAddr;
/**
* address is the InetAddress that this conduit uses for identity
*/
private final InetAddress address;
/**
* isBindAddress is true if we should bind to the address
*/
private final boolean isBindAddress;
/**
* the object that receives DistributionMessage messages received by this conduit.
*/
private final DirectChannel directChannel;
private DMStats stats;
/**
* Config from the delegate
*
* @since GemFire 4.2.1
*/
DistributionConfig config;
////////////////// runtime state that is re-initialized on a restart
/**
* server socket address
*/
private InetSocketAddress id;
protected volatile boolean stopped;
/**
* the listener thread
*/
private Thread thread;
/**
* if using NIO, this is the object used for accepting connections
*/
private ServerSocketChannel channel;
/**
* the server socket
*/
private ServerSocket socket;
/**
* a table of Connections from this conduit to others
*/
private ConnectionTable conTable;
/**
* <p>
* creates a new TCPConduit bound to the given InetAddress and port. The given ServerDelegate will
* receive any DistributionMessages passed to the conduit.
* </p>
* <p>
* This constructor forces the conduit to ignore the following system properties and look for them
* only in the <i>props</i> argument:
* </p>
*
* <pre>
* p2p.tcpBufferSize
* p2p.idleConnectionTimeout
* </pre>
*/
public TCPConduit(MembershipManager mgr, int port, InetAddress address, boolean isBindAddress,
DirectChannel receiver, Properties props) throws ConnectionException {
parseProperties(props);
this.address = address;
this.isBindAddress = isBindAddress;
this.port = port;
this.directChannel = receiver;
this.stats = null;
this.config = null;
this.membershipManager = mgr;
if (directChannel != null) {
this.stats = directChannel.getDMStats();
this.config = directChannel.getDMConfig();
}
if (this.getStats() == null) {
this.stats = new LonerDistributionManager.DummyDMStats();
}
try {
this.conTable = ConnectionTable.create(this);
} catch (IOException io) {
throw new ConnectionException(
"Unable to initialize connection table",
io);
}
this.socketCreator =
SocketCreatorFactory.getSocketCreatorForComponent(SecurableCommunicationChannel.CLUSTER);
this.useNIO = USE_NIO;
if (this.useNIO) {
InetAddress addr = address;
if (addr == null) {
try {
addr = SocketCreator.getLocalHost();
} catch (java.net.UnknownHostException e) {
throw new ConnectionException("Unable to resolve localHost address", e);
}
}
// JDK bug 6230761 - NIO can't be used with IPv6 on Windows
if (addr instanceof Inet6Address) {
String os = System.getProperty("os.name");
if (os != null) {
if (os.indexOf("Windows") != -1) {
this.useNIO = false;
}
}
}
}
startAcceptor();
}
/**
* parse instance-level properties from the given object
*/
private void parseProperties(Properties p) {
if (p != null) {
String s;
s = p.getProperty("p2p.tcpBufferSize", "" + tcpBufferSize);
try {
tcpBufferSize = Integer.parseInt(s);
} catch (Exception e) {
logger.warn("exception parsing p2p.tcpBufferSize",
e);
}
if (tcpBufferSize < Connection.SMALL_BUFFER_SIZE) {
// enforce minimum
tcpBufferSize = Connection.SMALL_BUFFER_SIZE;
}
s = p.getProperty("p2p.idleConnectionTimeout", "" + idleConnectionTimeout);
try {
idleConnectionTimeout = Integer.parseInt(s);
} catch (Exception e) {
logger.warn("exception parsing p2p.idleConnectionTimeout", e);
}
s = p.getProperty("membership_port_range_start");
try {
tcpPortRange[0] = Integer.parseInt(s);
} catch (Exception e) {
logger.warn("Exception parsing membership-port-range start port.", e);
}
s = p.getProperty("membership_port_range_end");
try {
tcpPortRange[1] = Integer.parseInt(s);
} catch (Exception e) {
logger.warn("Exception parsing membership-port-range end port.",
e);
}
}
}
private ExecutorService hsPool;
/**
* the reason for a shutdown, if abnormal
*/
private volatile Exception shutdownCause;
private static final int HANDSHAKE_POOL_SIZE =
Integer.getInteger("p2p.HANDSHAKE_POOL_SIZE", 10).intValue();
private static final long HANDSHAKE_POOL_KEEP_ALIVE_TIME =
Long.getLong("p2p.HANDSHAKE_POOL_KEEP_ALIVE_TIME", 60).longValue();
/**
* added to fix bug 40436
*/
public void setMaximumHandshakePoolSize(int maxSize) {
if (this.hsPool != null) {
ThreadPoolExecutor handshakePool = (ThreadPoolExecutor) this.hsPool;
if (maxSize > handshakePool.getMaximumPoolSize()) {
handshakePool.setMaximumPoolSize(maxSize);
}
}
}
/**
* binds the server socket and gets threads going
*/
private void startAcceptor() throws ConnectionException {
int localPort;
int p = this.port;
InetAddress ba = this.address;
{
ExecutorService tmp_hsPool = null;
String threadName = "P2P-Handshaker " + ba + ":" + p + " Thread ";
try {
tmp_hsPool =
LoggingExecutors.newThreadPoolWithSynchronousFeedThatHandlesRejection(threadName, null,
null, 1, HANDSHAKE_POOL_SIZE, HANDSHAKE_POOL_KEEP_ALIVE_TIME);
} catch (IllegalArgumentException poolInitException) {
throw new ConnectionException(
"while creating handshake pool",
poolInitException);
}
this.hsPool = tmp_hsPool;
}
createServerSocket();
try {
localPort = socket.getLocalPort();
id = new InetSocketAddress(socket.getInetAddress(), localPort);
stopped = false;
thread = new LoggingThread("P2P Listener Thread " + id, this);
try {
thread.setPriority(Thread.MAX_PRIORITY);
} catch (Exception e) {
logger.info("unable to set listener priority: {}", e.getMessage());
}
if (!Boolean.getBoolean("p2p.test.inhibitAcceptor")) {
thread.start();
} else {
logger.fatal(
"p2p.test.inhibitAcceptor was found to be set, inhibiting incoming tcp/ip connections");
socket.close();
this.hsPool.shutdownNow();
}
} catch (IOException io) {
String s = "While creating ServerSocket on port " + p;
throw new ConnectionException(s, io);
}
this.port = localPort;
}
/**
* creates the server sockets. This can be used to recreate the socket using this.port and
* this.bindAddress, which must be set before invoking this method.
*/
private void createServerSocket() {
int p = this.port;
int b = BACKLOG;
InetAddress bindAddress = this.address;
try {
if (this.useNIO) {
if (p <= 0) {
socket = socketCreator.createServerSocketUsingPortRange(bindAddress, b, isBindAddress,
this.useNIO, 0, tcpPortRange);
} else {
ServerSocketChannel channel = ServerSocketChannel.open();
socket = channel.socket();
InetSocketAddress inetSocketAddress =
new InetSocketAddress(isBindAddress ? bindAddress : null, p);
socket.bind(inetSocketAddress, b);
}
if (useNIO) {
try {
// set these buffers early so that large buffers will be allocated
// on accepted sockets (see java.net.ServerSocket.setReceiverBufferSize javadocs)
socket.setReceiveBufferSize(tcpBufferSize);
int newSize = socket.getReceiveBufferSize();
if (newSize != tcpBufferSize) {
logger.info("{} is {} instead of the requested {}",
"Listener receiverBufferSize", Integer.valueOf(newSize),
Integer.valueOf(tcpBufferSize));
}
} catch (SocketException ex) {
logger.warn("Failed to set listener receiverBufferSize to {}",
tcpBufferSize);
}
}
channel = socket.getChannel();
} else {
try {
if (p <= 0) {
socket = socketCreator.createServerSocketUsingPortRange(bindAddress, b, isBindAddress,
this.useNIO, this.tcpBufferSize, tcpPortRange);
} else {
socket = socketCreator.createServerSocket(p, b, isBindAddress ? bindAddress : null,
this.tcpBufferSize);
}
int newSize = socket.getReceiveBufferSize();
if (newSize != this.tcpBufferSize) {
logger.info("Listener receiverBufferSize is {} instead of the requested {}",
Integer.valueOf(newSize),
Integer.valueOf(this.tcpBufferSize));
}
} catch (SocketException ex) {
logger.warn("Failed to set listener receiverBufferSize to {}",
this.tcpBufferSize);
}
}
port = socket.getLocalPort();
} catch (IOException io) {
throw new ConnectionException(
String.format("While creating ServerSocket on port %s with address %s",
new Object[] {Integer.valueOf(p), bindAddress}),
io);
}
}
/**
* Ensure that the ConnectionTable class gets loaded.
*
* @see SystemFailure#loadEmergencyClasses()
*/
public static void loadEmergencyClasses() {
ConnectionTable.loadEmergencyClasses();
}
/**
* Close the ServerSocketChannel, ServerSocket, and the ConnectionTable.
*
* @see SystemFailure#emergencyClose()
*/
public void emergencyClose() {
// stop(); // Causes grief
if (stopped) {
return;
}
stopped = true;
try {
if (channel != null) {
channel.close();
// NOTE: do not try to interrupt the listener thread at this point.
// Doing so interferes with the channel's socket logic.
} else {
if (socket != null) {
socket.close();
}
}
} catch (IOException e) {
// ignore, please!
}
// this.hsPool.shutdownNow(); // I don't trust this not to allocate objects or to synchronize
// this.conTable.close(); not safe against deadlocks
ConnectionTable.emergencyClose();
socket = null;
thread = null;
conTable = null;
}
/* stops the conduit, closing all tcp/ip connections */
public void stop(Exception cause) {
if (!stopped) {
stopped = true;
shutdownCause = cause;
if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) {
logger.trace(LogMarker.DM_VERBOSE, "Shutting down conduit");
}
try {
// set timeout endpoint here since interrupt() has been known
// to hang
long timeout = System.currentTimeMillis() + LISTENER_CLOSE_TIMEOUT;
Thread t = this.thread;;
if (channel != null) {
channel.close();
// NOTE: do not try to interrupt the listener thread at this point.
// Doing so interferes with the channel's socket logic.
} else {
ServerSocket s = this.socket;
if (s != null) {
s.close();
}
if (t != null) {
t.interrupt();
}
}
do {
t = this.thread;
if (t == null || !t.isAlive()) {
break;
}
t.join(200);
} while (timeout > System.currentTimeMillis());
if (t != null && t.isAlive()) {
logger.warn(
"Unable to shut down listener within {}ms. Unable to interrupt socket.accept() due to JDK bug. Giving up.",
Integer.valueOf(LISTENER_CLOSE_TIMEOUT));
}
} catch (IOException | InterruptedException e) {
// we're already trying to shutdown, ignore
} finally {
this.hsPool.shutdownNow();
}
// close connections after shutting down acceptor to fix bug 30695
this.conTable.close();
socket = null;
thread = null;
conTable = null;
}
}
/**
* Returns whether or not this conduit is stopped
*
* @since GemFire 3.0
*/
public boolean isStopped() {
return this.stopped;
}
/**
* starts the conduit again after it's been stopped. This will clear the server map if the
* conduit's port is zero (wildcard bind)
*/
public void restart() throws ConnectionException {
if (!stopped) {
return;
}
this.stats = null;
if (directChannel != null) {
this.stats = directChannel.getDMStats();
}
if (this.getStats() == null) {
this.stats = new LonerDistributionManager.DummyDMStats();
}
try {
this.conTable = ConnectionTable.create(this);
} catch (IOException io) {
throw new ConnectionException(
"Unable to initialize connection table",
io);
}
startAcceptor();
}
/**
* this is the server socket listener thread's run loop
*/
public void run() {
ConnectionTable.threadWantsSharedResources();
if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) {
logger.trace(LogMarker.DM_VERBOSE, "Starting P2P Listener on {}", id);
}
for (;;) {
SystemFailure.checkFailure();
if (stopper.isCancelInProgress()) {
break;
}
if (stopped) {
break;
}
if (Thread.currentThread().isInterrupted()) {
break;
}
if (stopper.isCancelInProgress()) {
break; // part of bug 37271
}
Socket othersock = null;
try {
if (this.useNIO) {
SocketChannel otherChannel = channel.accept();
othersock = otherChannel.socket();
} else {
try {
othersock = socket.accept();
} catch (SSLException ex) {
// SW: This is the case when there is a problem in P2P
// SSL configuration, so need to exit otherwise goes into an
// infinite loop just filling the logs
logger.warn("Stopping P2P listener due to SSL configuration problem.",
ex);
break;
}
othersock.setSoTimeout(0);
socketCreator.handshakeIfSocketIsSSL(othersock, idleConnectionTimeout);
}
if (stopped) {
try {
if (othersock != null) {
othersock.close();
}
} catch (Exception e) {
}
continue;
}
acceptConnection(othersock);
} catch (ClosedByInterruptException cbie) {
// safe to ignore
} catch (ClosedChannelException | CancelException e) {
break;
} catch (IOException e) {
this.getStats().incFailedAccept();
try {
if (othersock != null) {
othersock.close();
}
} catch (IOException ignore) {
}
if (!stopped) {
if (e instanceof SocketException && "Socket closed".equalsIgnoreCase(e.getMessage())) {
// safe to ignore; see bug 31156
if (!socket.isClosed()) {
logger.warn("ServerSocket threw 'socket closed' exception but says it is not closed",
e);
try {
socket.close();
createServerSocket();
} catch (IOException ioe) {
logger.fatal("Unable to close and recreate server socket",
ioe);
// post 5.1.0x, this should force shutdown
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
// Don't reset; we're just exiting the thread
logger.info("Interrupted and exiting while trying to recreate listener sockets");
return;
}
}
}
} else if ("Too many open files".equals(e.getMessage())) {
getConTable().fileDescriptorsExhausted();
} else {
logger.warn(e.getMessage(), e);
}
}
} catch (Exception e) {
logger.warn(e.getMessage(), e);
}
if (!stopped && socket.isClosed()) {
// NOTE: do not check for distributed system closing here. Messaging
// may need to occur during the closing of the DS or cache
logger.warn("ServerSocket closed - reopening");
try {
createServerSocket();
} catch (ConnectionException ex) {
logger.warn(ex.getMessage(), ex);
}
}
} // for
if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) {
logger.trace("Stopped P2P Listener on {}", id);
}
}
private void acceptConnection(final Socket othersock) {
try {
this.hsPool.execute(new Runnable() {
public void run() {
basicAcceptConnection(othersock);
}
});
} catch (RejectedExecutionException rejected) {
try {
othersock.close();
} catch (IOException ignore) {
}
}
}
private ConnectionTable getConTable() {
ConnectionTable result = this.conTable;
if (result == null) {
stopper.checkCancelInProgress(null);
throw new DistributedSystemDisconnectedException(
"tcp layer has been shutdown");
}
return result;
}
protected void basicAcceptConnection(Socket othersock) {
try {
getConTable().acceptConnection(othersock, new PeerConnectionFactory());
} catch (IOException io) {
// exception is logged by the Connection
if (!stopped) {
this.getStats().incFailedAccept();
}
} catch (ConnectionException ex) {
// exception is logged by the Connection
if (!stopped) {
this.getStats().incFailedAccept();
}
} catch (CancelException e) {
} catch (Exception e) {
if (!stopped) {
this.getStats().incFailedAccept();
logger.warn("Failed to accept connection from {} because {}",
othersock.getInetAddress(), e);
}
}
}
/**
* return true if "new IO" classes are being used for the server socket
*/
protected boolean useNIO() {
return this.useNIO;
}
/**
* records the current outgoing message count on all thread-owned ordered connections
*
* @since GemFire 5.1
*/
public void getThreadOwnedOrderedConnectionState(DistributedMember member, Map result) {
getConTable().getThreadOwnedOrderedConnectionState(member, result);
}
/**
* wait for the incoming connections identified by the keys in the argument to receive and
* dispatch the number of messages associated with the key
*
* @since GemFire 5.1
*/
public void waitForThreadOwnedOrderedConnectionState(DistributedMember member, Map channelState)
throws InterruptedException {
getConTable().waitForThreadOwnedOrderedConnectionState(member, channelState);
}
/**
* connections send messageReceived when a message object has been read.
*
* @param bytesRead number of bytes read off of network to get this message
*/
protected void messageReceived(Connection receiver, DistributionMessage message, int bytesRead) {
if (logger.isTraceEnabled()) {
logger.trace("{} received {} from {}", id, message, receiver);
}
if (directChannel != null) {
DistributionMessage msg = message;
msg.setBytesRead(bytesRead);
msg.setSender(receiver.getRemoteAddress());
msg.setSharedReceiver(receiver.isSharedResource());
directChannel.receive(msg, bytesRead);
}
}
/**
* gets the address of this conduit's ServerSocket endpoint
*/
public InetSocketAddress getSocketId() {
return id;
}
/**
* gets the actual port to which this conduit's ServerSocket is bound
*/
public int getPort() {
return id.getPort();
}
/**
* Gets the local member ID that identifies this conduit
*/
public InternalDistributedMember getMemberId() {
return this.localAddr;
}
public void setMemberId(InternalDistributedMember addr) {
localAddr = addr;
}
/**
* Return a connection to the given member. This method must continue to attempt to create a
* connection to the given member as long as that member is in the membership view and the system
* is not shutting down.
*
* @param memberAddress the IDS associated with the remoteId
* @param preserveOrder whether this is an ordered or unordered connection
* @param retry false if this is the first attempt
* @param startTime the time this operation started
* @param ackTimeout the ack-wait-threshold * 1000 for the operation to be transmitted (or zero)
* @param ackSATimeout the ack-severe-alert-threshold * 1000 for the operation to be transmitted
* (or zero)
*
* @return the connection
*/
public Connection getConnection(InternalDistributedMember memberAddress,
final boolean preserveOrder, boolean retry, long startTime, long ackTimeout,
long ackSATimeout) throws java.io.IOException, DistributedSystemDisconnectedException {
if (stopped) {
throw new DistributedSystemDisconnectedException(
"The conduit is stopped");
}
Connection conn = null;
InternalDistributedMember memberInTrouble = null;
boolean breakLoop = false;
for (;;) {
stopper.checkCancelInProgress(null);
boolean interrupted = Thread.interrupted();
try {
// If this is the second time through this loop, we had
// problems. Tear down the connection so that it gets
// rebuilt.
if (retry || conn != null) { // not first time in loop
if (!membershipManager.memberExists(memberAddress)
|| membershipManager.isShunned(memberAddress)
|| membershipManager.shutdownInProgress()) {
throw new IOException(
"TCP/IP connection lost and member is not in view");
}
// bug35953: Member is still in view; we MUST NOT give up!
// Pause just a tiny bit...
try {
Thread.sleep(100);
} catch (InterruptedException e) {
interrupted = true;
stopper.checkCancelInProgress(e);
}
// try again after sleep
if (!membershipManager.memberExists(memberAddress)
|| membershipManager.isShunned(memberAddress)) {
// OK, the member left. Just register an error.
throw new IOException(
"TCP/IP connection lost and member is not in view");
}
// Print a warning (once)
if (memberInTrouble == null) {
memberInTrouble = memberAddress;
logger.warn("Attempting TCP/IP reconnect to {}", memberInTrouble);
} else {
if (logger.isDebugEnabled()) {
logger.debug("Attempting TCP/IP reconnect to {}", memberInTrouble);
}
}
// Close the connection (it will get rebuilt later).
this.getStats().incReconnectAttempts();
if (conn != null) {
try {
if (logger.isDebugEnabled()) {
logger.debug("Closing old connection. conn={} before retrying. memberInTrouble={}",
conn, memberInTrouble);
}
conn.closeForReconnect("closing before retrying");
} catch (CancelException ex) {
throw ex;
} catch (Exception ex) {
}
}
} // not first time in loop
Exception problem = null;
try {
// Get (or regenerate) the connection
// bug36202: this could generate a ConnectionException, so it
// must be caught and retried
boolean retryForOldConnection;
boolean debugRetry = false;
do {
retryForOldConnection = false;
conn = getConTable().get(memberAddress, preserveOrder, startTime, ackTimeout,
ackSATimeout);
if (conn == null) {
// conduit may be closed - otherwise an ioexception would be thrown
problem = new IOException(
String.format("Unable to reconnect to server; possible shutdown: %s",
memberAddress));
} else if (conn.isClosing() || !conn.getRemoteAddress().equals(memberAddress)) {
if (logger.isDebugEnabled()) {
logger.debug("Got an old connection for {}: {}@{}", memberAddress, conn,
conn.hashCode());
}
conn.closeOldConnection("closing old connection");
conn = null;
retryForOldConnection = true;
debugRetry = true;
}
} while (retryForOldConnection);
if (debugRetry && logger.isDebugEnabled()) {
logger.debug("Done removing old connections");
}
// we have a connection; fall through and return it
} catch (ConnectionException e) {
// Race condition between acquiring the connection and attempting
// to use it: another thread closed it.
problem = e;
// [sumedh] No need to retry since Connection.createSender has already
// done retries and now member is really unreachable for some reason
// even though it may be in the view
breakLoop = true;
} catch (IOException e) {
problem = e;
// bug #43962 don't keep trying to connect to an alert listener
if (AlertAppender.isThreadAlerting()) {
if (logger.isDebugEnabled()) {
logger.debug("Giving up connecting to alert listener {}", memberAddress);
}
breakLoop = true;
}
}
if (problem != null) {
// Some problems are not recoverable; check and error out early.
if (!membershipManager.memberExists(memberAddress)
|| membershipManager.isShunned(memberAddress)) { // left the view
// Bracket our original warning
if (memberInTrouble != null) {
// make this msg info to bracket warning
logger.info("Ending reconnect attempt because {} has disappeared.",
memberInTrouble);
}
throw new IOException(String.format("Peer has disappeared from view: %s",
memberAddress));
} // left the view
if (membershipManager.shutdownInProgress()) { // shutdown in progress
// Bracket our original warning
if (memberInTrouble != null) {
// make this msg info to bracket warning
logger.info("Ending reconnect attempt to {} because shutdown has started.",
memberInTrouble);
}
stopper.checkCancelInProgress(null);
throw new DistributedSystemDisconnectedException(
"Abandoned because shutdown is in progress");
} // shutdown in progress
// Log the warning. We wait until now, because we want
// to have m defined for a nice message...
if (memberInTrouble == null) {
logger.warn("Error sending message to {} (will reattempt): {}",
memberAddress, problem);
memberInTrouble = memberAddress;
} else {
if (logger.isDebugEnabled()) {
logger.debug("Error sending message to {}", memberAddress, problem);
}
}
if (breakLoop) {
if (!problem.getMessage().startsWith("Cannot form connection to alert listener")) {
logger.warn("Throwing IOException after finding breakLoop=true",
problem);
}
if (problem instanceof IOException) {
throw (IOException) problem;
} else {
IOException ioe = new IOException(String.format("Problem connecting to %s",
memberAddress));
ioe.initCause(problem);
throw ioe;
}
}
// Retry the operation (indefinitely)
continue;
} // problem != null
// Success!
// Make sure our logging is bracketed if there was a problem
if (memberInTrouble != null) {
logger.info("Successfully reconnected to member {}", memberInTrouble);
if (logger.isTraceEnabled()) {
logger.trace("new connection is {} memberAddress={}", conn, memberAddress);
}
}
return conn;
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
} // for(;;)
}
@Override
public String toString() {
return "" + id;
}
/**
* Returns the distribution manager of the direct channel
*/
public DistributionManager getDM() {
return directChannel.getDM();
}
public void removeEndpoint(DistributedMember mbr, String reason, boolean notifyDisconnect) {
ConnectionTable ct = this.conTable;
if (ct == null) {
return;
}
ct.removeEndpoint(mbr, reason, notifyDisconnect);
}
/**
* check to see if there are still any receiver threads for the given end-point
*/
public boolean hasReceiversFor(DistributedMember endPoint) {
ConnectionTable ct = this.conTable;
return (ct != null) && ct.hasReceiversFor(endPoint);
}
/**
* Stats from the delegate
*/
public DMStats getStats() {
return stats;
}
protected class Stopper extends CancelCriterion {
@Override
public String cancelInProgress() {
DistributionManager dm = getDM();
if (dm == null) {
return "no distribution manager";
}
if (TCPConduit.this.stopped) {
return "Conduit has been stopped";
}
return null;
}
@Override
public RuntimeException generateCancelledException(Throwable e) {
String reason = cancelInProgress();
if (reason == null) {
return null;
}
DistributionManager dm = getDM();
if (dm == null) {
return new DistributedSystemDisconnectedException("no distribution manager");
}
RuntimeException result = dm.getCancelCriterion().generateCancelledException(e);
if (result != null) {
return result;
}
// We know we've been stopped; generate the exception
result = new DistributedSystemDisconnectedException("Conduit has been stopped");
result.initCause(e);
return result;
}
}
private final Stopper stopper = new Stopper();
public CancelCriterion getCancelCriterion() {
return stopper;
}
/**
* if the conduit is disconnected due to an abnormal condition, this will describe the reason
*
* @return exception that caused disconnect
*/
public Exception getShutdownCause() {
return this.shutdownCause;
}
/**
* returns the SocketCreator that should be used to produce sockets for TCPConduit connections.
*/
protected SocketCreator getSocketCreator() {
return socketCreator;
}
/**
* ARB: Called by Connection before handshake reply is sent. Returns true if member is part of
* view, false if membership is not confirmed before timeout.
*/
public boolean waitForMembershipCheck(InternalDistributedMember remoteId) {
return membershipManager.waitForNewMember(remoteId);
}
}
| apache-2.0 |
TibiSecurity/progkorny | src/main/java/view/FormPanel.java | 12691 | package view;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.border.Border;
import model.Manufacturer;
import model.Model;
public class FormPanel extends JPanel {
private JLabel nameLabel;
private JLabel phoneLabel;
private JLabel creationDateLabel;
private JLabel carInfoLabel;
private JTextField nameField;
private JTextField phoneField;
private JFormattedTextField creationDateField;
private static final String CMAN_NOT_SELECTABLE_OPTION = "-Válassz autógyártót-";
private JComboBox<String> carManComboBox;
private static final String CMOD_NOT_SELECTABLE_OPTION = "-Válassz autótípust-";
private JComboBox<String> carModelComboBox;
private JTextField licensePlateNoField;
private JTextField yearField;
private JTextField colorField;
private JTextField odometerField;
private JLabel licensePlateNoLabel;
private JLabel yearLabel;
private JLabel colorLabel;
private JLabel odometerLabel;
private JButton okBtn;
private FormListener formListener;
private CarManChooserListener carManChooserListener;
public FormPanel(List<Manufacturer> manufacturers) {
Dimension dim = getPreferredSize();
dim.width = 250;
setPreferredSize(dim);
nameLabel = new JLabel("*Név: ");
phoneLabel = new JLabel("Telefonszám: ");
creationDateLabel = new JLabel("Mai dátum: ");
carInfoLabel = new JLabel("Gépjármű információk: ");
nameField = new JTextField(10);
phoneField = new JTextField(10);
carManComboBox = new JComboBox<String>();
carModelComboBox = new JComboBox<String>();
licensePlateNoField = new JTextField(10);
yearField = new JTextField(10);
colorField = new JTextField(10);
odometerField = new JTextField(10);
licensePlateNoLabel = new JLabel("Rendszám: ");
yearLabel = new JLabel("Gyártási év: ");
colorLabel = new JLabel("Szín: ");
odometerLabel = new JLabel("Km-óra állás: ");
licensePlateNoField.setText("*Rendszám");
licensePlateNoField.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
if(licensePlateNoField.getText().trim().equals(""))
licensePlateNoField.setText("*Rendszám");
}
public void focusGained(FocusEvent e) {
if(licensePlateNoField.getText().trim().equals("*Rendszám"))
licensePlateNoField.setText("");
}
});
yearField.setText("Gyártási év");
yearField.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
if(yearField.getText().trim().equals(""))
yearField.setText("Gyártási év");
}
public void focusGained(FocusEvent e) {
if(yearField.getText().trim().equals("Gyártási év"))
yearField.setText("");
}
});
colorField.setText("Gépjármű színe");
colorField.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
if(colorField.getText().trim().equals(""))
colorField.setText("Gépjármű színe");
}
public void focusGained(FocusEvent e) {
if(colorField.getText().trim().equals("Gépjármű színe"))
colorField.setText("");
}
});
odometerField.setText("Kilóméteróra állás");
odometerField.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
if(odometerField.getText().trim().equals(""))
odometerField.setText("Kilóméteróra állás");
}
public void focusGained(FocusEvent e) {
if(odometerField.getText().trim().equals("Kilóméteróra állás"))
odometerField.setText("");
}
});
carModelComboBox.setVisible(false);
carManComboBox.setModel(new DefaultComboBoxModel<String>() {
boolean selectionAllowed = true;
public void setSelectedItem(Object anObject) {
if (!CMAN_NOT_SELECTABLE_OPTION.equals(anObject)) {
super.setSelectedItem(anObject);
} else if (selectionAllowed) {
// Allow this just once
selectionAllowed = false;
super.setSelectedItem(anObject);
}
}
});
carModelComboBox.setModel(new DefaultComboBoxModel<String>() {
boolean selectionAllowed = true;
public void setSelectedItem(Object anObject) {
if (!CMOD_NOT_SELECTABLE_OPTION.equals(anObject)) {
super.setSelectedItem(anObject);
} else if (selectionAllowed) {
// Allow this just once
selectionAllowed = false;
super.setSelectedItem(anObject);
}
}
});
carManComboBox.addItem(CMAN_NOT_SELECTABLE_OPTION);
for (Manufacturer man : manufacturers) {
carManComboBox.addItem(man.getManufacturerName());
}
Date todaysDate = new Date();
SimpleDateFormat dateformat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
creationDateField = new JFormattedTextField(
dateformat.format(todaysDate));
creationDateField.setEditable(false);
okBtn = new JButton("OK");
okBtn.setMnemonic(KeyEvent.VK_O);
nameLabel.setDisplayedMnemonic(KeyEvent.VK_N);
nameLabel.setLabelFor(nameField);
phoneLabel.setDisplayedMnemonic(KeyEvent.VK_T);
phoneLabel.setLabelFor(phoneField);
carManComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String carMan = (String) carManComboBox.getSelectedItem();
CarManChooserEvent eCM = new CarManChooserEvent(this, carMan);
if (carManChooserListener != null) {
carManChooserListener.carManChooserEventOccured(eCM);
}
}
});
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String phoneNum = phoneField.getText();
Date creationDate = new Date();
String carMan = (String) carManComboBox.getSelectedItem();
String carModel = (String) carModelComboBox.getSelectedItem();
String licensePlateNo = licensePlateNoField.getText();
String year = yearField.getText();
String color = colorField.getText();
String odometer = odometerField.getText();
if( year.equals("Gyártási év") ){
year = "";
}
if( color.equals("Gépjármű színe") ){
color = "";
}
if (name.equals("")) {
JOptionPane.showMessageDialog(FormPanel.this,
"A 'Név' mező nem maradhat üresen!",
"Adatbázis hiba", JOptionPane.ERROR_MESSAGE);
} else if(carMan.equals(CMAN_NOT_SELECTABLE_OPTION)){
JOptionPane.showMessageDialog(FormPanel.this,
"Autógyártó választása kötelező!",
"Adatbázis hiba", JOptionPane.ERROR_MESSAGE);
} else if(carModel.equals(CMOD_NOT_SELECTABLE_OPTION)){
JOptionPane.showMessageDialog(FormPanel.this,
"Autótípus választása kötelező!",
"Adatbázis hiba", JOptionPane.ERROR_MESSAGE);
} else if(licensePlateNo.equals("*Rendszám")){
JOptionPane.showMessageDialog(FormPanel.this,
"Rendszám megadása kötelező!",
"Adatbázis hiba", JOptionPane.ERROR_MESSAGE);
} else if(!odometer.equals("Kilóméteróra állás") && !isInteger(odometer) ){
JOptionPane.showMessageDialog(FormPanel.this,
"A kilóméteróra állás szám kell hogy legyen!",
"Adatbázis hiba", JOptionPane.ERROR_MESSAGE);
} else {
Integer odoMeter;
if( odometer.equals("Kilóméteróra állás") ){
odoMeter = 0;
} else{
odoMeter = Integer.parseInt(odometer);
}
nameField.setText("");
phoneField.setText("");
licensePlateNoField.setText("*Rendszám");
yearField.setText("Gyártási év");
colorField.setText("Gépjármű színe");
odometerField.setText("Kilóméteróra állás");
FormEvent ev = new FormEvent(this, name, phoneNum, creationDate,
carMan, carModel,
licensePlateNo, year, color, odoMeter);
if (formListener != null) {
formListener.formEventOccured(ev);
}
}
}
});
Border innerBorder = BorderFactory.createTitledBorder("Új ügyfél");
Border outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
setBorder(BorderFactory.createCompoundBorder(outerBorder, innerBorder));
layoutComponents();
}
public void layoutComponents() {
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
// Name label and name field
gc.gridy = 0;
gc.gridx = 0;
gc.weightx = 1;
gc.weighty = 0.1;
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.LINE_END;
gc.insets = new Insets(0, 0, 0, 5);
add(nameLabel, gc);
gc.gridx++;
gc.anchor = GridBagConstraints.LINE_START;
gc.insets = new Insets(0, 0, 0, 0);
add(nameField, gc);
// Phone label and name field
gc.gridy++;
gc.gridx = 0;
gc.weightx = 1;
gc.weighty = 0.1;
gc.anchor = GridBagConstraints.LINE_END;
gc.insets = new Insets(0, 0, 0, 5);
add(phoneLabel, gc);
gc.gridx++;
gc.anchor = GridBagConstraints.LINE_START;
gc.insets = new Insets(0, 0, 0, 0);
add(phoneField, gc);
// Date
gc.gridy++;
gc.gridx = 0;
gc.weightx = 1;
gc.weighty = 0.1;
gc.anchor = GridBagConstraints.LINE_END;
gc.insets = new Insets(0, 0, 0, 5);
add(creationDateLabel, gc);
gc.gridx++;
gc.anchor = GridBagConstraints.LINE_START;
gc.insets = new Insets(0, 0, 0, 0);
add(creationDateField, gc);
////////////// Separator //////////////
gc.gridy++;
gc.gridx = 0;
gc.weightx = 1.0;
gc.weighty = 0.3;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.gridwidth = GridBagConstraints.REMAINDER;
add(new JSeparator(JSeparator.HORIZONTAL), gc);
// Car info label
gc.gridy++;
gc.gridx = 0;
gc.weightx = 1;
gc.weighty = 0.1;
gc.anchor = GridBagConstraints.LINE_START;
gc.fill = GridBagConstraints.NONE;
gc.insets = new Insets(0, 0, 0, 0);
add(carInfoLabel, gc);
// Car manufacturer chooser
gc.gridy++;
gc.gridx = 0;
gc.weightx = 1;
gc.weighty = 0.1;
gc.anchor = GridBagConstraints.LINE_END;
gc.fill = GridBagConstraints.NONE;
gc.insets = new Insets(5, 0, 0, 0);
add(carManComboBox, gc);
// Car model chooser
gc.gridy++;
gc.gridx = 0;
gc.weightx = 1;
gc.weighty = 0.1;
gc.anchor = GridBagConstraints.LINE_END;
gc.fill = GridBagConstraints.NONE;
gc.insets = new Insets(5, 0, 0, 0);
add(carModelComboBox, gc);
// Car license plate no.
gc.gridy++;
gc.gridx = 1;
gc.weightx = 1;
gc.weighty = 0.1;
gc.anchor = GridBagConstraints.LINE_START;
gc.insets = new Insets(0, 0, 0, 0);
add(licensePlateNoField, gc);
// Car year
gc.gridy++;
gc.gridx = 1;
gc.weightx = 1;
gc.weighty = 0.1;
gc.anchor = GridBagConstraints.LINE_START;
gc.insets = new Insets(0, 0, 0, 0);
add(yearField, gc);
// Car color
gc.gridy++;
gc.gridx = 1;
gc.weightx = 1;
gc.weighty = 0.1;
gc.anchor = GridBagConstraints.LINE_START;
gc.insets = new Insets(0, 0, 0, 0);
add(colorField, gc);
// Car odometer
gc.gridy++;
gc.gridx = 1;
gc.weightx = 1;
gc.weighty = 0.1;
gc.anchor = GridBagConstraints.LINE_START;
gc.insets = new Insets(0, 0, 0, 0);
add(odometerField, gc);
// OK Button
gc.gridy++;
gc.gridx = 1;
gc.weightx = 1;
gc.weighty = 1.5;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
gc.fill = GridBagConstraints.NONE;
gc.insets = new Insets(0, 0, 0, 5);
add(okBtn, gc);
}
public void setFormListener(FormListener listener) {
this.formListener = listener;
}
public void setCarManChooserListener(CarManChooserListener listener) {
this.carManChooserListener = listener;
}
public void setCarModelComboBox(List<Model> models) {
this.carModelComboBox.removeAllItems();
carModelComboBox.addItem(CMOD_NOT_SELECTABLE_OPTION);
for (Model model : models) {
this.carModelComboBox.addItem(model.getModelName());
}
carModelComboBox.setVisible(true);
}
public static boolean isInteger(String str) {
int length = str.length();
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = str.charAt(i);
if (c <= '/' || c >= ':') {
return false;
}
}
return true;
}
}
| apache-2.0 |
michaeloverman/Weather | app/src/main/java/com/example/android/sunshine/app/DetailActivity.java | 4561 | package com.example.android.sunshine.app;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.ShareActionProvider;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.overman.weather.app.R;
public class DetailActivity extends ActionBarActivity {
//private ShareActionProvider mShareActionProvider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new DetailFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
final String LOG_TAG = "onCreateOptionsMenu";
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detail, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
//Intent settingsIntent = new Intent(this, SettingsActivity.class);
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view
*/
public class DetailFragment extends Fragment {
private String LOG_TAG = this.getClass().getSimpleName();
private static final String SHARE_HASHTAG = " #WeatherApp";
private String forecastStr;
public DetailFragment() {
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
forecastStr = intent.getStringExtra(Intent.EXTRA_TEXT);
((TextView) rootView.findViewById(R.id.detail_text))
.setText(forecastStr);
}
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.detailfragment, menu);
// Retrieve the share menu item
MenuItem menuItem = menu.findItem(R.id.menu_item_share);
// Get the provider and hold onto it to set/change the share intent
ShareActionProvider myShareActionProvider = new ShareActionProvider(getActivity());
MenuItemCompat.setActionProvider(menuItem, myShareActionProvider);
// ShareActionProvider myShareActionProvider =
// (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
// Attach an intent to this provider.
// if (myShareActionProvider != null) {
// myShareActionProvider.setShareIntent(createShareForecastIntent());
// } else {
// Log.d(LOG_TAG, "share actionprovider is null ?!?");
// }
Intent myShareIntent = createShareForecastIntent();
myShareActionProvider.setShareIntent(myShareIntent);
}
private Intent createShareForecastIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,
forecastStr + SHARE_HASHTAG);
return shareIntent;
}
}
}
| apache-2.0 |
jiaozhujun/c3f | src-core/com/youcan/core/l.java | 1306 | package com.youcan.core;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import com.youcan.core.l;
public class l {
protected l() {
//do nothing
System.out.println("l started.");
}
private static Logger log;
public static final boolean init(String logName) {
if ((log = LogManager.exists(logName)) != null) {
return true;
}
return false;
}
public static final void print(Object message) {
System.out.print(message);
}
public static final void println(Object message) {
System.out.println(message);
}
public static final void warn(Object message) {
log.warn(message);
}
public static final void info(Object message) {
log.info(message);
}
public static final void debug(Object message) {
log.debug(message);
}
public static final void error(Object message) {
log.error(message);
}
public static final void error(Object message, Throwable t) {
log.error(message, t);
}
public static final void fatal(Object message) {
log.fatal(message);
}
public static final void fatal(Object message, Throwable t) {
log.fatal(message, t);
}
public static final Logger getLog() {
return log;
}
public static final void setLog(Logger log) {
l.log = log;
}
}
| apache-2.0 |
NovaViper/ZeroQuest | 1.6.4-src/common/zeroquest/entity/helper/CustomJakanHelper.java | 1197 | /*
** 2013 October 27
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
*/
package common.zeroquest.entity.helper;
import java.util.Random;
import common.zeroquest.entity.EntityJakanPrime;
import net.minecraft.entity.DataWatcher;
import net.minecraft.nbt.NBTTagCompound;
/**
*
* @author Nico Bergemann <barracuda415 at yahoo.de>
*/
public class CustomJakanHelper {
protected final EntityJakanPrime dragon;
protected final DataWatcher dataWatcher;
protected final Random rand;
public CustomJakanHelper(EntityJakanPrime dragon) {
this.dragon = dragon;
this.dataWatcher = dragon.getDataWatcher();
this.rand = dragon.getRNG();
}
public void writeToNBT(NBTTagCompound nbt) {}
public void readFromNBT(NBTTagCompound nbt) {}
public void applyEntityAttributes() {}
public void onLivingUpdate() {}
public void onDeathUpdate() {}
public void onDeath() {}
}
| apache-2.0 |
yahoo/athenz | libs/java/auth_core/src/test/java/com/yahoo/athenz/auth/oauth/validator/OAuthJwtAccessTokenValidatorTest.java | 4643 | /*
* Copyright 2020 Yahoo Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yahoo.athenz.auth.oauth.validator;
import static org.testng.Assert.*;
import java.io.FileInputStream;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import com.yahoo.athenz.auth.oauth.token.OAuthJwtAccessToken;
import com.yahoo.athenz.auth.oauth.token.OAuthJwtAccessTokenException;
import com.yahoo.athenz.auth.util.CryptoException;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class OAuthJwtAccessTokenValidatorTest {
private final ClassLoader classLoader = this.getClass().getClassLoader();
private OAuthJwtAccessTokenValidator baseValidator = null;
private final X509Certificate readCert(String resourceName) throws Exception {
try (FileInputStream certIs = new FileInputStream(this.classLoader.getResource(resourceName).getFile())) {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
return (X509Certificate) cf.generateCertificate(certIs);
}
}
@BeforeMethod
public void initialize() throws Exception {
this.baseValidator = new OAuthJwtAccessTokenValidator() {
public void validate(OAuthJwtAccessToken jwt) throws OAuthJwtAccessTokenException {}
public void validateClientId(OAuthJwtAccessToken jwt, String clientId) throws OAuthJwtAccessTokenException {}
public void validateCertificateBinding(OAuthJwtAccessToken jwt, String certificateThumbprint) throws OAuthJwtAccessTokenException {}
};
}
@Test
public void testGetX509CertificateCommonName() throws Exception {
// on null
assertThrows(NullPointerException.class, () -> this.baseValidator.getX509CertificateCommonName(null));
X509Certificate cert = this.readCert("jwt_ui.athenz.io.pem");
assertEquals(this.baseValidator.getX509CertificateCommonName(cert), "ui.athenz.io");
}
@Test
public void testGetX509CertificateThumbprint() throws Exception {
// on null
assertThrows(NullPointerException.class, () -> this.baseValidator.getX509CertificateThumbprint(null));
X509Certificate cert = this.readCert("jwt_ui.athenz.io.pem");
assertEquals(this.baseValidator.getX509CertificateThumbprint(cert), "zlkxyoX95le-Nv7OI0BxcjTOogvy9PGH-v_CBr_DsEk");
}
@Test
public void testValidateCertificateBinding() throws Exception {
final OAuthJwtAccessTokenValidator mock = Mockito.mock(OAuthJwtAccessTokenValidator.class, Mockito.CALLS_REAL_METHODS);
// on CertificateEncodingException
Mockito.doThrow(new CertificateEncodingException()).when(mock).getX509CertificateThumbprint(null);
assertThrows(OAuthJwtAccessTokenException.class, () -> mock.validateCertificateBinding(null, (X509Certificate) null));
// on CryptoException
Mockito.doThrow(new CryptoException()).when(mock).getX509CertificateThumbprint(null);
assertThrows(OAuthJwtAccessTokenException.class, () -> mock.validateCertificateBinding(null, (X509Certificate) null));
// actual call
OAuthJwtAccessTokenValidator validator = Mockito.mock(OAuthJwtAccessTokenValidator.class, Mockito.CALLS_REAL_METHODS);
X509Certificate cert = this.readCert("jwt_ui.athenz.io.pem");
Mockito.doReturn("zlkxyoX95le-Nv7OI0BxcjTOogvy9PGH-v_CBr_DsEk").when(validator).getX509CertificateThumbprint(cert);
ArgumentCaptor<OAuthJwtAccessToken> tokenArg = ArgumentCaptor.forClass(OAuthJwtAccessToken.class);
ArgumentCaptor<String> thumbprintArg = ArgumentCaptor.forClass(String.class);
validator.validateCertificateBinding(null, cert);
Mockito.verify(validator, Mockito.times(1)).validateCertificateBinding(tokenArg.capture(), thumbprintArg.capture());
assertNull(tokenArg.getValue());
assertEquals(thumbprintArg.getValue(), "zlkxyoX95le-Nv7OI0BxcjTOogvy9PGH-v_CBr_DsEk");
}
}
| apache-2.0 |
vmatelsky/churches | Churches/com.churches.by/src/main/java/com/churches/by/ui/AboutDialog.java | 684 | package com.churches.by.ui;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import com.churches.by.R;
public class AboutDialog extends DialogFragment {
public AboutDialog() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return inflater.inflate(R.layout.about_dialog, container, false);
}
}
| apache-2.0 |
mtaylor/DataBroker | control-common/src/main/java/com/arjuna/databroker/control/comms/PropertiesDTO.java | 727 | /*
* Copyright (c) 2013-2014, Arjuna Technologies Limited, Newcastle-upon-Tyne, England. All rights reserved.
*/
package com.arjuna.databroker.control.comms;
import java.io.Serializable;
import java.util.Map;
public class PropertiesDTO implements Serializable
{
private static final long serialVersionUID = -4823706453142980142L;
public PropertiesDTO()
{
}
public PropertiesDTO(Map<String, String> properties)
{
_properties = properties;
}
public Map<String, String> getProperties()
{
return _properties;
}
public void setProperties(Map<String, String> properties)
{
_properties = properties;
}
private Map<String, String> _properties;
} | apache-2.0 |
gchq/stroom | stroom-security/stroom-security-impl/src/main/java/stroom/security/impl/SessionListService.java | 946 | /*
* Copyright 2017 Crown Copyright
*
* 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 stroom.security.impl;
import stroom.security.shared.SessionListResponse;
public interface SessionListService {
/**
* List all sessions on the specified node
*/
SessionListResponse listSessions(final String nodeName);
/**
* List all sessions on all nodes
*/
SessionListResponse listSessions();
}
| apache-2.0 |
ifnul/ums-backend | is-lnu-converter/src/main/java/org/lnu/is/converter/person/paper/PersonPaperResourceConverter.java | 1692 | package org.lnu.is.converter.person.paper;
import org.lnu.is.annotations.Converter;
import org.lnu.is.converter.AbstractConverter;
import org.lnu.is.domain.honors.type.HonorType;
import org.lnu.is.domain.paper.type.PaperType;
import org.lnu.is.domain.person.Person;
import org.lnu.is.domain.person.paper.PersonPaper;
import org.lnu.is.resource.person.paper.PersonPaperResource;
/**
* Person Paper Resource Converter.
* @author ivanursul
*
*/
@Converter("personPaperResourceConverter")
public class PersonPaperResourceConverter extends AbstractConverter<PersonPaperResource, PersonPaper> {
@Override
public PersonPaper convert(final PersonPaperResource source, final PersonPaper target) {
if (source.getPersonId() != null) {
Person person = new Person();
person.setId(source.getPersonId());
target.setPerson(person);
}
if (source.getPaperTypeId() != null) {
PaperType paperType = new PaperType();
paperType.setId(source.getPaperTypeId());
target.setPaperType(paperType);
}
if (source.getHonorsTypeId() != null) {
HonorType honorsType = new HonorType();
honorsType.setId(source.getHonorsTypeId());
target.setHonorsType(honorsType);
}
target.setDocSeries(source.getDocSeries());
target.setDocNum(source.getDocNum());
target.setDocDate(source.getDocDate());
target.setDocIssued(source.getDocIssued());
target.setDocPin(source.getDocPin());
target.setMark(source.getMark());
target.setIsChecked(source.getIsChecked());
target.setIsForeign(source.getIsForeign());
return target;
}
@Override
public PersonPaper convert(final PersonPaperResource source) {
return convert(source, new PersonPaper());
}
}
| apache-2.0 |
cshaxu/voldemort | src/java/voldemort/server/protocol/vold/VoldemortNativeRequestHandler.java | 8979 | package voldemort.server.protocol.vold;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.apache.log4j.Logger;
import voldemort.VoldemortException;
import voldemort.common.VoldemortOpCode;
import voldemort.common.nio.ByteBufferBackedInputStream;
import voldemort.common.nio.ByteBufferContainer;
import voldemort.server.RequestRoutingType;
import voldemort.server.StoreRepository;
import voldemort.server.protocol.AbstractRequestHandler;
import voldemort.server.protocol.RequestHandler;
import voldemort.server.protocol.StreamRequestHandler;
import voldemort.store.ErrorCodeMapper;
import voldemort.store.Store;
import voldemort.utils.ByteArray;
import voldemort.versioning.ObsoleteVersionException;
/**
* Server-side request handler for voldemort native client protocol
*
*
*/
public class VoldemortNativeRequestHandler extends AbstractRequestHandler implements RequestHandler {
private static final Logger logger = Logger.getLogger(VoldemortNativeRequestHandler.class);
private final int protocolVersion;
public VoldemortNativeRequestHandler(ErrorCodeMapper errorMapper,
StoreRepository repository,
int protocolVersion) {
super(errorMapper, repository);
if(protocolVersion < 0 || protocolVersion > 3)
throw new IllegalArgumentException("Unknown protocol version: " + protocolVersion);
this.protocolVersion = protocolVersion;
}
private ClientRequestHandler getClientRequestHanlder(byte opCode,
Store<ByteArray, byte[], byte[]> store)
throws IOException {
switch(opCode) {
case VoldemortOpCode.GET_OP_CODE:
return new GetRequestHandler(store, protocolVersion);
case VoldemortOpCode.GET_ALL_OP_CODE:
return new GetAllRequestHandler(store, protocolVersion);
case VoldemortOpCode.PUT_OP_CODE:
return new PutRequestHandler(store, protocolVersion);
case VoldemortOpCode.DELETE_OP_CODE:
return new DeleteRequestHandler(store, protocolVersion);
case VoldemortOpCode.GET_VERSION_OP_CODE:
return new GetVersionRequestHandler(store, protocolVersion);
default:
throw new IOException("Unknown op code: " + opCode);
}
}
@Override
public StreamRequestHandler handleRequest(final DataInputStream inputStream,
final DataOutputStream outputStream)
throws IOException {
return handleRequest(inputStream, outputStream, null);
}
private void clearBuffer(ByteBufferContainer outputContainer) {
if(outputContainer != null) {
outputContainer.getBuffer().clear();
}
}
@Override
public StreamRequestHandler handleRequest(final DataInputStream inputStream,
final DataOutputStream outputStream,
final ByteBufferContainer outputContainer)
throws IOException {
long startTimeMs = -1;
long startTimeNs = -1;
if(logger.isDebugEnabled()) {
startTimeMs = System.currentTimeMillis();
startTimeNs = System.nanoTime();
}
byte opCode = inputStream.readByte();
String storeName = inputStream.readUTF();
RequestRoutingType routingType = getRoutingType(inputStream);
Store<ByteArray, byte[], byte[]> store = getStore(storeName, routingType);
if(store == null) {
clearBuffer(outputContainer);
writeException(outputStream, new VoldemortException("No store named '" + storeName
+ "'."));
return null;
}
ClientRequestHandler requestHandler = getClientRequestHanlder(opCode, store);
try {
requestHandler.parseRequest(inputStream);
requestHandler.processRequest();
} catch ( VoldemortException e) {
// Put generates lot of ObsoleteVersionExceptions, suppress them
// they are harmless and indicates normal mode of operation.
if(!(e instanceof ObsoleteVersionException)) {
logger.error("Store" + storeName + ". Error: " + e.getMessage());
}
clearBuffer(outputContainer);
writeException(outputStream, e);
return null;
}
// We are done with Input, clear the buffers
clearBuffer(outputContainer);
int size = requestHandler.getResponseSize();
if(outputContainer != null) {
outputContainer.growBuffer(size);
}
requestHandler.writeResponse(outputStream);
outputStream.flush();
if(logger.isDebugEnabled()) {
String debugPrefix = "OpCode " + opCode + " started at: " + startTimeMs
+ " handlerRef: " + System.identityHashCode(inputStream)
+ " Elapsed : " + (System.nanoTime() - startTimeNs) + " ns, ";
logger.debug(debugPrefix + requestHandler.getDebugMessage() );
}
return null;
}
private RequestRoutingType getRoutingType(DataInputStream inputStream) throws IOException {
RequestRoutingType routingType = RequestRoutingType.NORMAL;
if(protocolVersion > 0) {
boolean isRouted = inputStream.readBoolean();
routingType = RequestRoutingType.getRequestRoutingType(isRouted, false);
}
if(protocolVersion > 1) {
int routingTypeCode = inputStream.readByte();
routingType = RequestRoutingType.getRequestRoutingType(routingTypeCode);
}
return routingType;
}
/**
* This is pretty ugly. We end up mimicking the request logic here, so this
* needs to stay in sync with handleRequest.
*/
@Override
public boolean isCompleteRequest(final ByteBuffer buffer) throws VoldemortException {
DataInputStream inputStream = new DataInputStream(new ByteBufferBackedInputStream(buffer));
try {
byte opCode = inputStream.readByte();
// Store Name
inputStream.readUTF();
// Store routing type
getRoutingType(inputStream);
switch(opCode) {
case VoldemortOpCode.GET_VERSION_OP_CODE:
if(!GetVersionRequestHandler.isCompleteRequest(inputStream, buffer))
return false;
break;
case VoldemortOpCode.GET_OP_CODE:
if(!GetRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))
return false;
break;
case VoldemortOpCode.GET_ALL_OP_CODE:
if(!GetAllRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))
return false;
break;
case VoldemortOpCode.PUT_OP_CODE: {
if(!PutRequestHandler.isCompleteRequest(inputStream, buffer, protocolVersion))
return false;
break;
}
case VoldemortOpCode.DELETE_OP_CODE: {
if(!DeleteRequestHandler.isCompleteRequest(inputStream, buffer))
return false;
break;
}
default:
throw new VoldemortException(" Unrecognized Voldemort OpCode " + opCode);
}
// This should not happen, if we reach here and if buffer has more
// data, there is something wrong.
if(buffer.hasRemaining()) {
logger.info(" Probably a client bug, Discarding additional bytes in isCompleteRequest. Opcode "
+ opCode
+ " remaining bytes " + buffer.remaining());
}
return true;
} catch(IOException e) {
// This could also occur if the various methods we call into
// re-throw a corrupted value error as some other type of exception.
// For example, updating the position on a buffer past its limit
// throws an InvalidArgumentException.
if(logger.isDebugEnabled())
logger.debug("Probable partial read occurred causing exception", e);
return false;
}
}
private void writeException(DataOutputStream stream, VoldemortException e) throws IOException {
short code = getErrorMapper().getCode(e);
stream.writeShort(code);
stream.writeUTF(e.getMessage());
stream.flush();
}
}
| apache-2.0 |
fuerve/VillageElder | src/test/java/com/fuerve/villageelder/indexing/IndexManagerTest.java | 8850 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.fuerve.villageelder.indexing;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Field;
import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.LongField;
import org.apache.lucene.facet.taxonomy.CategoryPath;
import org.apache.lucene.facet.taxonomy.TaxonomyWriter;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.junit.Test;
/**
* Unit tests for {@link IndexManager}.
* @author lparker
*
*/
public class IndexManagerTest {
/**
* Test method for {@link com.fuerve.villageelder.indexing.IndexManager#IndexManager(org.apache.lucene.store.Directory, org.apache.lucene.store.Directory)}.
* @throws Exception
*/
@Test
public final void testIndexManagerDirectoryDirectory() throws Exception {
RAMDirectory indexDirectory = new RAMDirectory();
RAMDirectory taxonomyDirectory = new RAMDirectory();
Field idField = IndexManager.class.getDeclaredField("indexDirectory");
Field tdField = IndexManager.class.getDeclaredField("taxonomyDirectory");
Field iwField = IndexManager.class.getDeclaredField("indexWriter");
Field twField = IndexManager.class.getDeclaredField("taxonomyWriter");
Field stField = IndexManager.class.getDeclaredField("stringDirectories");
Field initField = IndexManager.class.getDeclaredField("initialized");
idField.setAccessible(true);
tdField.setAccessible(true);
iwField.setAccessible(true);
twField.setAccessible(true);
stField.setAccessible(true);
initField.setAccessible(true);
IndexManager target = new IndexManager(indexDirectory, taxonomyDirectory);
// TEST 1: A newly constructed IndexManager believes itself
// to be uninitialized, as indicated by the 'initialized'
// field.
boolean initActual = initField.getBoolean(target);
assertFalse(initActual);
target.initializeIndex();
Directory idActual = (Directory) idField.get(target);
Directory tdActual = (Directory) tdField.get(target);
IndexWriter iwActual = (IndexWriter) iwField.get(target);
TaxonomyWriter twActual = (TaxonomyWriter) twField.get(target);
boolean stActual = (Boolean) stField.get(target);
initActual = initField.getBoolean(target);
// TEST 2: The IndexManager's index directory is what was passed in.
assertEquals(indexDirectory, idActual);
// TEST 3: The IndexManager's taxonomy directory is what was passed in.
assertEquals(taxonomyDirectory, tdActual);
// TEST 4: The IndexWriter's directory is what was passed in.
assertEquals(indexDirectory, iwActual.getDirectory());
// TEST 5: The taxonomy index is initialized afresh with no categories
// in it.
assertEquals(1, twActual.getSize());
// TEST 6: An IndexManager constructed with Directories does not
// believe that it needs to construct new Directories from string
// pathnames.
assertEquals(false, stActual);
// TEST 7: The IndexManager's initialized field is true after it
// has been initialized.
assertEquals(true, initActual);
target.dispose();
// TEST 8: The IndexManager's index writer is null after it has
// been disposed.
iwActual = (IndexWriter) iwField.get(target);
assertEquals(null, iwActual);
// TEST 9: The IndexManager's taxonomy writer is null after it
// has been disposed.
twActual = (TaxonomyWriter) twField.get(target);
assertEquals(null, twActual);
// TEST 10: The IndexManager's initialized flag is false after
// it has been disposed.
initActual = initField.getBoolean(target);
assertEquals(false, initActual);
}
/**
* Test method for {@link com.fuerve.villageelder.indexing.IndexManager#IndexManager(org.apache.lucene.store.Directory, org.apache.lucene.store.Directory, org.apache.lucene.index.IndexWriterConfig.OpenMode)}.
*/
@Test
public final void testIndexManagerDirectoryDirectoryOpenMode() throws Exception {
RAMDirectory indexDirectory = new RAMDirectory();
RAMDirectory taxonomyDirectory = new RAMDirectory();
Field idField = IndexManager.class.getDeclaredField("indexDirectory");
Field tdField = IndexManager.class.getDeclaredField("taxonomyDirectory");
Field iwField = IndexManager.class.getDeclaredField("indexWriter");
Field twField = IndexManager.class.getDeclaredField("taxonomyWriter");
Field stField = IndexManager.class.getDeclaredField("stringDirectories");
Field initField = IndexManager.class.getDeclaredField("initialized");
idField.setAccessible(true);
tdField.setAccessible(true);
iwField.setAccessible(true);
twField.setAccessible(true);
stField.setAccessible(true);
initField.setAccessible(true);
IndexManager target = new IndexManager(indexDirectory, taxonomyDirectory, OpenMode.CREATE);
target.initializeIndex();
TaxonomyWriter tw = (TaxonomyWriter) twField.get(target);
IndexWriter iw = (IndexWriter) iwField.get(target);
tw.addCategory(new CategoryPath("test/stuff", '/'));
Document doc = new Document();
doc.add(new LongField("testfield", 1000L, Store.YES));
iw.addDocument(doc);
target.dispose();
// TEST: Initializing an index, disposing it and initializing another
// index instance on the same Directories results in loading the same
// index.
IndexManager target2 = new IndexManager(indexDirectory, taxonomyDirectory, OpenMode.APPEND);
target2.initializeIndex();
iw = (IndexWriter) iwField.get(target2);
tw = (TaxonomyWriter) twField.get(target2);
assertEquals(1, iw.numDocs());
assertEquals(3, tw.getSize());
target2.dispose();
}
/**
* Test method for {@link com.fuerve.villageelder.indexing.IndexManager#getIndexWriter()}.
*/
@Test
public final void testGetIndexWriter() throws Exception {
RAMDirectory indexDirectory = new RAMDirectory();
RAMDirectory taxonomyDirectory = new RAMDirectory();
IndexManager target = new IndexManager(indexDirectory, taxonomyDirectory);
target.initializeIndex();
Document doc = new Document();
doc.add(new LongField("testfield", 1000L, Store.YES));
target.getIndexWriter().addDocument(doc);
assertEquals(1, target.getIndexWriter().numDocs());
target.dispose();
}
/**
* Test method for {@link com.fuerve.villageelder.indexing.IndexManager#getTaxonomyWriter()}.
*/
@Test
public final void testGetTaxonomyWriter() throws Exception {
RAMDirectory indexDirectory = new RAMDirectory();
RAMDirectory taxonomyDirectory = new RAMDirectory();
IndexManager target = new IndexManager(indexDirectory, taxonomyDirectory);
target.initializeIndex();
target.getTaxonomyWriter().addCategory(new CategoryPath("test/stuff", '/'));
assertEquals(3, target.getTaxonomyWriter().getSize());
target.dispose();
}
/**
* Test method for {@link com.fuerve.villageelder.indexing.IndexManager#getAnalyzer()}.
*/
@Test
public final void testGetAnalyzer() throws Exception {
RAMDirectory indexDirectory = new RAMDirectory();
RAMDirectory taxonomyDirectory = new RAMDirectory();
IndexManager target = new IndexManager(indexDirectory, taxonomyDirectory);
target.initializeIndex();
assertTrue(target.getAnalyzer() instanceof PerFieldAnalyzerWrapper);
target.dispose();
}
}
| apache-2.0 |
jasonchuang/SoftwareVideoPlayer | src/com/jasonsoft/softwarevideoplayer/LoadThumbnailTask.java | 3200 | package com.jasonsoft.softwarevideoplayer;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore.Video;
import android.provider.MediaStore.Video.Thumbnails;
import android.view.View;
import android.widget.ImageView;
import com.jasonsoft.softwarevideoplayer.cache.CacheManager;
import com.jasonsoft.softwarevideoplayer.data.AsyncDrawable;
import com.jasonsoft.softwarevideoplayer.data.LoadThumbnailParams;
import com.jasonsoft.softwarevideoplayer.data.LoadThumbnailResult;
import java.lang.ref.WeakReference;
public class LoadThumbnailTask extends AsyncTask<LoadThumbnailParams, Void, LoadThumbnailResult> {
private Context mContext;
private final WeakReference<ImageView> thumbnailViewReference;
private long data = 0;
public LoadThumbnailTask(Context context, ImageView thumbnailView) {
this.mContext = context;
this.thumbnailViewReference = new WeakReference<ImageView>(thumbnailView);
}
@Override
protected LoadThumbnailResult doInBackground(LoadThumbnailParams... params) {
data = params[0].origId;
Bitmap bitmap = Thumbnails.getThumbnail(mContext.getContentResolver(), data,
Thumbnails.MINI_KIND, new Options());
android.util.Log.d("jason", "doInBackground data:" + data);
android.util.Log.d("jason", "doInBackground bitmap:" + bitmap);
if (data > 0 && bitmap != null) {
CacheManager.getInstance().addThumbnailToMemoryCache(String.valueOf(data), bitmap);
}
if (this.isCancelled()) { return null; }
return new LoadThumbnailResult(bitmap);
}
@Override
protected void onPostExecute(LoadThumbnailResult result) {
if (isCancelled() || null == result) {
return;
}
final ImageView thumbnailView = thumbnailViewReference.get();
final LoadThumbnailTask loadThumbnailTask = getLoadThumbnailTask(thumbnailView);
if (this == loadThumbnailTask && thumbnailView != null) {
setThumbnail(result.bitmap, thumbnailView);
}
}
public long getData() {
return data;
}
/**
* @param imageView Any imageView
* @return Retrieve the currently active work task (if any) associated with this imageView.
* null if there is no such task.
*/
public static LoadThumbnailTask getLoadThumbnailTask(ImageView imageView) {
if (imageView != null) {
final Drawable drawable = imageView.getDrawable();
if (drawable instanceof AsyncDrawable) {
final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
return asyncDrawable.getLoadThumbnailTask();
}
}
return null;
}
void setThumbnail(Bitmap bitmap, ImageView thumbnailView) {
thumbnailView.setImageBitmap(bitmap);
thumbnailView.setVisibility(View.VISIBLE);
}
}
| apache-2.0 |
noironetworks/genie | src/main/java/org/opendaylight/opflex/genie/content/format/meta/mdl/FContDef.java | 2728 | package org.opendaylight.opflex.genie.content.format.meta.mdl;
import java.util.TreeMap;
import org.opendaylight.opflex.genie.content.model.mclass.MClass;
import org.opendaylight.opflex.genie.content.model.mprop.MProp;
import org.opendaylight.opflex.genie.engine.file.WriteStats;
import org.opendaylight.opflex.genie.engine.format.*;
import org.opendaylight.opflex.genie.engine.model.Ident;
/**
* Created by midvorki on 8/4/14.
*/
public class FContDef
extends GenericFormatterTask
{
public FContDef(
FormatterCtx aInFormatterCtx,
FileNameRule aInFileNameRule,
Indenter aInIndenter,
BlockFormatDirective aInHeaderFormatDirective,
BlockFormatDirective aInCommentFormatDirective,
boolean aInIsUserFile,
WriteStats aInStats)
{
super(aInFormatterCtx,
aInFileNameRule,
aInIndenter,
aInHeaderFormatDirective,
aInCommentFormatDirective,
aInIsUserFile,
aInStats);
}
public void generate()
{
out.println();
MClass lRoot = MClass.getContainmentRoot();
genClass(0, lRoot);
}
private void genClass(int aInIndent, MClass aInClass)
{
out.print(aInIndent, aInClass.getFullConcatenatedName());
genProps(aInIndent + 1, aInClass);
genContained(aInIndent, aInClass);
}
private void genProps(int aInIndent, MClass aInClass)
{
TreeMap<String,MProp> lProps = new TreeMap<String, MProp>();
aInClass.findProp(lProps, false);
if (!lProps.isEmpty())
{
out.print('[');
for (MProp lProp : lProps.values())
{
genProp(aInIndent,lProp);
}
out.println(']');
}
else
{
out.println();
}
}
private void genProp(int aInIndent, MProp aInProp)
{
out.println();
out.print(aInIndent,
aInProp.getLID().getName() +
"=<" +
aInProp.getType(false).getFullConcatenatedName() + "/" + aInProp.getType(true).getFullConcatenatedName() + "|group:" + aInProp.getGroup() + ">;");
}
private void genContained(int aInIndent, MClass aInParent)
{
TreeMap<Ident,MClass> lContained = new TreeMap<Ident,MClass>();
aInParent.getContainsClasses(lContained, true, true);
if (!lContained.isEmpty())
{
out.println(aInIndent, '{');
for (MClass lClass : lContained.values())
{
genClass(aInIndent+1, lClass);
}
out.println(aInIndent, '}');
}
}
} | apache-2.0 |
tedwen/transmem | src/com/transmem/doc/BitextLoader.java | 4846 | package com.transmem.doc;
import java.io.IOException;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.logging.Logger;
import java.sql.SQLException;
/**
* Bitext loader loads a bilingual parallel text from two separate files.
* The files should be in plain text format with proper punctuation marks
* for each sentence. In other words, a sentence in the source language
* text should have a corresponding sentence in the translation text.
* The current implementation does not include automatic alignment, it is
* the user's responsibility to guarantee that the sentences are aligned.
* This class implements ITextSaver for TextParser to parse the text into
* sentences.
*/
public class BitextLoader implements ITextSaver
{
public static final Logger log_ = Logger.getLogger(BitextLoader.class.getName());
class Record
{
public int index_;
public int length_;
public Record link_; //link to the other language sentence
public Record(int index, int length)
{
this.index_ = index;
this.length_ = length;
this.link_ = null;
}
}
private IUnitSaver saver_ = null;
private String sencoding_, tencoding_;
private File[] tempfiles_; //temporary filenames
private PrintWriter[] tempwriters_;
private ArrayList<Record>[] slens_; //length of sentences
private int curfile_, index_;
/**
* Construct BitextLoader with two file names.
*/
public BitextLoader(String sfilename, String tfilename,
String sencoding, String tencoding, IUnitSaver saver) throws IOException,SQLException
{
this.saver_ = saver;
this.sencoding_ = sencoding;
this.tencoding_ = tencoding;
parseFiles(sfilename, tfilename);
}
/**
* Parse the two files to get sentences.
* @param sfilename - source text filename
* @param tfilename - target text filename
*/
protected void parseFiles(String sfilename, String tfilename) throws IOException,SQLException
{
this.slens_ = new ArrayList[2];//{new ArrayList<Record>(),new ArrayList<Record>()};
this.slens_[0] = new ArrayList<Record>();
this.slens_[1] = new ArrayList<Record>();
//parse two files one by one, saving sentences into temporary text files
this.tempfiles_ = new File[2];
this.tempfiles_[0] = File.createTempFile("tmbis",".tmp");
log_.info("Temporary file created 4 src: "+tempfiles_[0]);
this.tempwriters_[0] = new PrintWriter(this.tempfiles_[0]);
this.curfile_ = 0;
this.index_ = 0;
TextParser tps = new TextParser();
tps.parse(sfilename, this.sencoding_, this);
this.tempwriters_[0].close();
this.tempfiles_[1] = File.createTempFile("tmbid",".tmp");
log_.info("Temporary file created 4 dst: "+tempfiles_[1]);
this.tempwriters_[1] = new PrintWriter(this.tempfiles_[1]);
this.curfile_ = 1;
this.index_ = 0;
TextParser tpd = new TextParser();
tpd.parse(tfilename, this.tencoding_, this);
this.tempwriters_[1].close();
//merge and align the sentences
boolean saved = false;
if ((this.slens_[0].size() > 0) && (this.slens_[0].size() == this.slens_[1].size()))
{
mergeAndAlign();
saved = true;
}
//finally delete the temp files
this.tempfiles_[0].delete();
this.tempfiles_[1].delete();
log_.info("Temporary files deleted");
File f = new File(sfilename);
f.delete();
f = new File(tfilename);
f.delete();
log_.info("Uploaded files deleted");
if (!saved)
throw new IOException("Sentences do not match");
}
/**
* Align the sentences from the two files and merge if necessary.
* A true aligner is an AI research topic, so we ignore that at the moment,
* and leave the un-matched sentences empty. The user is then responsible
* to edit the sentences and align manually.
*/
public void mergeAndAlign() throws SQLException,IOException
{
BufferedReader reader1 = new BufferedReader(new FileReader(this.tempfiles_[0]));
BufferedReader reader2 = new BufferedReader(new FileReader(this.tempfiles_[1]));
while (true)
{
String s1 = reader1.readLine();
String s2 = reader2.readLine();
if (s1 == null && s2 == null) break;
this.saver_.saveUnit(s1, s2);
}
reader1.close();
reader2.close();
}
// Interface method, not used here
public void startParagraph(int startpos) throws java.sql.SQLException
{
}
// Interface method, not used here
public void endParagraph(int endpos) throws java.sql.SQLException
{
}
/**
* Called by a TextParser object when a sentence is ready to save.
* @param sentence - String as a sentence
* @param startpos - ignored
* @param endpos - ignored
*/
public void saveSentence(String sentence, int startpos, int endpos) throws java.sql.SQLException
{
this.tempwriters_[this.curfile_].println(sentence);
this.slens_[this.curfile_].add(new Record(this.index_, sentence.length()));
this.index_ ++;
}
}
| apache-2.0 |
jdcheng/proctor-git | proctor-common/src/main/java/com/indeed/proctor/common/AbstractProctorLoader.java | 4349 | package com.indeed.proctor.common;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.indeed.util.core.DataLoadingTimerTask;
import com.indeed.util.varexport.Export;
import com.indeed.proctor.common.model.Audit;
import com.indeed.proctor.common.model.TestMatrixArtifact;
import org.apache.log4j.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.el.FunctionMapper;
import java.io.IOException;
import java.util.Map;
public abstract class AbstractProctorLoader extends DataLoadingTimerTask implements Supplier<Proctor> {
private static final Logger LOGGER = Logger.getLogger(AbstractProctorLoader.class);
@Nonnull
protected final Map<String, TestSpecification> requiredTests;
@Nullable
private Proctor current = null;
@Nullable
private Audit lastAudit = null;
@Nullable
private String lastLoadErrorMessage= "load never attempted";
@Nonnull
private final FunctionMapper functionMapper;
public AbstractProctorLoader(@Nonnull final Class<?> cls, @Nonnull final ProctorSpecification specification, @Nonnull final FunctionMapper functionMapper) {
super(cls.getSimpleName());
this.requiredTests = specification.getTests();
this.functionMapper = functionMapper;
}
@Nullable
abstract TestMatrixArtifact loadTestMatrix() throws IOException, MissingTestMatrixException;
@Nonnull
abstract String getSource();
@Override
public boolean load() {
final Proctor newProctor;
try {
newProctor = doLoad();
} catch (@Nonnull final Throwable t) {
lastLoadErrorMessage = t.getMessage();
throw new RuntimeException("Unable to reload proctor from " + getSource(), t);
}
lastLoadErrorMessage = null;
if (newProctor == null) {
// This should only happen if the versions of the matrix files are the same.
return false;
}
this.current = newProctor;
final Audit lastAudit = Preconditions.checkNotNull(this.lastAudit, "Missing last audit");
setDataVersion(lastAudit.getVersion() + " @ " + lastAudit.getUpdated() + " by " + lastAudit.getUpdatedBy());
LOGGER.info("Successfully loaded new test matrix definition: " + lastAudit.getVersion() + " @ " + lastAudit.getUpdated() + " by " + lastAudit.getUpdatedBy());
return true;
}
@Nullable
public Proctor doLoad() throws IOException, MissingTestMatrixException {
final TestMatrixArtifact testMatrix = loadTestMatrix();
if (testMatrix == null) {
throw new MissingTestMatrixException("Failed to load Test Matrix from " + getSource());
}
final ProctorLoadResult loadResult = ProctorUtils.verifyAndConsolidate(testMatrix, getSource(), requiredTests, functionMapper);
final Audit newAudit = testMatrix.getAudit();
if (lastAudit != null) {
final Audit audit = Preconditions.checkNotNull(newAudit, "Missing audit");
if(lastAudit.getVersion() == audit.getVersion()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Not reloading " + getSource() + " test matrix definition because audit is unchanged: " + lastAudit.getVersion() + " @ " + lastAudit.getUpdated() + " by " + lastAudit.getUpdatedBy());
}
return null;
}
}
final Proctor proctor = Proctor.construct(testMatrix, loadResult, functionMapper);
// kind of lame to modify lastAudit here but current in load(), but the interface is a little constraining
this.lastAudit = newAudit;
return proctor;
}
@Nullable
public Proctor get() {
return current;
}
@Nullable
@Export(name = "last-audit")
public Audit getLastAudit() {
return lastAudit;
}
@Nullable
@Export(name = "last-error", doc = "The last error message thrown by the loader. null indicates a successful load.")
public String getLastLoadErrorMessage() {
return lastLoadErrorMessage;
}
// this is used for healthchecks
@SuppressWarnings({"UnusedDeclaration"})
public boolean isLoadedDataSuccessfullyRecently() {
return dataLoadTimer.isLoadedDataSuccessfullyRecently();
}
}
| apache-2.0 |
dev9com/crash-dummy | src/main/java/com/dev9/crash/bad/FillHeapLocalMethodOnStack.java | 757 | package com.dev9.crash.bad;
import com.dev9.crash.AbstractBadThing;
import org.springframework.stereotype.Service;
@Service
public class FillHeapLocalMethodOnStack extends AbstractBadThing {
public String getBadThingDescription() {
return "Fills up the heap using an object with a local method. This method allocates an object on the stack which grows until OOM.";
}
public String getBadThingName() {
return "Fill Up The Heap On The Stack";
}
@Override
public String getBadThingId() {
return "fill-up-the-heap-object-local-method-stack-oom";
}
public String doBadThing() throws Exception {
MemoryMasher mm = new MemoryMasher();
mm.stackHeapMasher();
return null;
}
}
| apache-2.0 |
dbflute-test/dbflute-test-dbms-mysql | src/main/java/org/docksidestage/mysql/dbflute/allcommon/CDef.java | 262223 | /*
* Copyright 2004-2013 the Seasar Foundation and the Others.
*
* 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 org.docksidestage.mysql.dbflute.allcommon;
import java.util.*;
import org.dbflute.exception.ClassificationNotFoundException;
import org.dbflute.jdbc.Classification;
import org.dbflute.jdbc.ClassificationCodeType;
import org.dbflute.jdbc.ClassificationMeta;
import org.dbflute.jdbc.ClassificationUndefinedHandlingType;
import org.dbflute.optional.OptionalThing;
import static org.dbflute.util.DfTypeUtil.emptyStrings;
/**
* The definition of classification.
* @author DBFlute(AutoGenerator)
*/
public interface CDef extends Classification {
/**
* 会員が受けられるサービスのランクを示す
*/
public enum ServiceRank implements CDef {
/** PLATINUM: platinum rank */
Platinum("PLT", "PLATINUM", emptyStrings())
,
/** GOLD: gold rank */
Gold("GLD", "GOLD", emptyStrings())
,
/** SILVER: silver rank */
Silver("SIL", "SILVER", emptyStrings())
,
/** BRONZE: bronze rank */
Bronze("BRZ", "BRONZE", emptyStrings())
,
/** PLASTIC: plastic rank (deprecated: テーブル区分値の非推奨要素指定のテストのため) */
@Deprecated
Plastic("PLS", "PLASTIC", emptyStrings())
;
private static final Map<String, ServiceRank> _codeClsMap = new HashMap<String, ServiceRank>();
private static final Map<String, ServiceRank> _nameClsMap = new HashMap<String, ServiceRank>();
static {
for (ServiceRank value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private ServiceRank(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.ServiceRank; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<ServiceRank> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof ServiceRank) { return OptionalThing.of((ServiceRank)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<ServiceRank> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static ServiceRank codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof ServiceRank) { return (ServiceRank)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static ServiceRank nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<ServiceRank> listAll() {
return new ArrayList<ServiceRank>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<ServiceRank> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: ServiceRank." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<ServiceRank> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<ServiceRank> clsList = new ArrayList<ServiceRank>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<ServiceRank> groupOf(String groupName) {
return new ArrayList<ServiceRank>(4);
}
@Override public String toString() { return code(); }
}
/**
* mainly region of member address
*/
public enum Region implements CDef {
/** アメリカ */
アメリカ("1", "アメリカ", emptyStrings())
,
/** カナダ */
カナダ("2", "カナダ", emptyStrings())
,
/** 中国 */
中国("3", "中国", emptyStrings())
,
/** 千葉 */
千葉("4", "千葉", emptyStrings())
;
private static final Map<String, Region> _codeClsMap = new HashMap<String, Region>();
private static final Map<String, Region> _nameClsMap = new HashMap<String, Region>();
static {
for (Region value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private Region(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.Region; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<Region> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof Region) { return OptionalThing.of((Region)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<Region> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static Region codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof Region) { return (Region)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static Region nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<Region> listAll() {
return new ArrayList<Region>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<Region> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: Region." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<Region> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<Region> clsList = new ArrayList<Region>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<Region> groupOf(String groupName) {
return new ArrayList<Region>(4);
}
@Override public String toString() { return code(); }
}
/**
* reason for member withdrawal
*/
public enum WithdrawalReason implements CDef {
/** SIT: サイトが使いにくいから */
Sit("SIT", "SIT", emptyStrings())
,
/** PRD: 商品に魅力がないから */
Prd("PRD", "PRD", emptyStrings())
,
/** FRT: フリテンだから */
Frt("FRT", "FRT", emptyStrings())
,
/** OTH: その他理由 */
Oth("OTH", "OTH", emptyStrings())
;
private static final Map<String, WithdrawalReason> _codeClsMap = new HashMap<String, WithdrawalReason>();
private static final Map<String, WithdrawalReason> _nameClsMap = new HashMap<String, WithdrawalReason>();
static {
for (WithdrawalReason value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private WithdrawalReason(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.WithdrawalReason; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<WithdrawalReason> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof WithdrawalReason) { return OptionalThing.of((WithdrawalReason)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<WithdrawalReason> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static WithdrawalReason codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof WithdrawalReason) { return (WithdrawalReason)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static WithdrawalReason nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<WithdrawalReason> listAll() {
return new ArrayList<WithdrawalReason>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<WithdrawalReason> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: WithdrawalReason." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<WithdrawalReason> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<WithdrawalReason> clsList = new ArrayList<WithdrawalReason>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<WithdrawalReason> groupOf(String groupName) {
return new ArrayList<WithdrawalReason>(4);
}
@Override public String toString() { return code(); }
}
/**
* 支払方法
*/
public enum PaymentMethod implements CDef {
/** 手渡し: Face-to-Faceの手渡しで商品と交換 */
ByHand("HAN", "手渡し", emptyStrings())
,
/** 銀行振込: 銀行振込で確認してから商品発送 */
BankTransfer("BAK", "銀行振込", emptyStrings())
,
/** クレジットカード: クレジットカードの番号を教えてもらう */
CreditCard("CRC", "クレジットカード", emptyStrings())
;
private static final Map<String, PaymentMethod> _codeClsMap = new HashMap<String, PaymentMethod>();
private static final Map<String, PaymentMethod> _nameClsMap = new HashMap<String, PaymentMethod>();
static {
for (PaymentMethod value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private PaymentMethod(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.PaymentMethod; }
/**
* Is the classification in the group? <br>
* 最も推奨されている方法 <br>
* The group elements:[ByHand]
* @return The determination, true or false.
*/
public boolean isRecommended() {
return ByHand.equals(this);
}
public boolean inGroup(String groupName) {
if ("recommended".equals(groupName)) { return isRecommended(); }
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<PaymentMethod> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof PaymentMethod) { return OptionalThing.of((PaymentMethod)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<PaymentMethod> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static PaymentMethod codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof PaymentMethod) { return (PaymentMethod)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static PaymentMethod nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<PaymentMethod> listAll() {
return new ArrayList<PaymentMethod>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<PaymentMethod> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
if ("recommended".equalsIgnoreCase(groupName)) { return listOfRecommended(); }
throw new ClassificationNotFoundException("Unknown classification group: PaymentMethod." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<PaymentMethod> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<PaymentMethod> clsList = new ArrayList<PaymentMethod>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of group classification elements. (returns new copied list) <br>
* 最も推奨されている方法 <br>
* The group elements:[ByHand]
* @return The snapshot list of classification elements in the group. (NotNull)
*/
public static List<PaymentMethod> listOfRecommended() {
return new ArrayList<PaymentMethod>(Arrays.asList(ByHand));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<PaymentMethod> groupOf(String groupName) {
if ("recommended".equals(groupName)) { return listOfRecommended(); }
return new ArrayList<PaymentMethod>(4);
}
@Override public String toString() { return code(); }
}
/**
* the test of reference variable in grouping map
*/
public enum GroupingReference implements CDef {
/** LAND_NAME */
LAND_NAME("LND", "LAND_NAME", emptyStrings())
,
/** SEA_NAME */
SEA_NAME("SEA", "SEA_NAME", emptyStrings())
,
/** IKSPIARY_NAME */
IKSPIARY_NAME("IKS", "IKSPIARY_NAME", emptyStrings())
,
/** AMPHI_NAME */
AMPHI_NAME("AMP", "AMPHI_NAME", emptyStrings())
;
private static final Map<String, GroupingReference> _codeClsMap = new HashMap<String, GroupingReference>();
private static final Map<String, GroupingReference> _nameClsMap = new HashMap<String, GroupingReference>();
static {
for (GroupingReference value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private GroupingReference(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.GroupingReference; }
/**
* Is the classification in the group? <br>
* サービスが利用できる会員 <br>
* The group elements:[LAND_NAME, SEA_NAME]
* @return The determination, true or false.
*/
public boolean isServiceAvailable() {
return LAND_NAME.equals(this) || SEA_NAME.equals(this);
}
/**
* Is the classification in the group? <br>
* The group elements:[LAND_NAME, SEA_NAME, IKSPIARY_NAME]
* @return The determination, true or false.
*/
public boolean isServicePlus() {
return LAND_NAME.equals(this) || SEA_NAME.equals(this) || IKSPIARY_NAME.equals(this);
}
/**
* Is the classification in the group? <br>
* The group elements:[AMPHI_NAME, LAND_NAME, SEA_NAME, IKSPIARY_NAME]
* @return The determination, true or false.
*/
public boolean isNestedPlus() {
return AMPHI_NAME.equals(this) || LAND_NAME.equals(this) || SEA_NAME.equals(this) || IKSPIARY_NAME.equals(this);
}
/**
* Is the classification in the group? <br>
* The group elements:[IKSPIARY_NAME]
* @return The determination, true or false.
*/
public boolean isOneDef() {
return IKSPIARY_NAME.equals(this);
}
/**
* Is the classification in the group? <br>
* The group elements:[LAND_NAME, SEA_NAME, IKSPIARY_NAME]
* @return The determination, true or false.
*/
public boolean isDupRef() {
return LAND_NAME.equals(this) || SEA_NAME.equals(this) || IKSPIARY_NAME.equals(this);
}
public boolean inGroup(String groupName) {
if ("serviceAvailable".equals(groupName)) { return isServiceAvailable(); }
if ("servicePlus".equals(groupName)) { return isServicePlus(); }
if ("nestedPlus".equals(groupName)) { return isNestedPlus(); }
if ("oneDef".equals(groupName)) { return isOneDef(); }
if ("dupRef".equals(groupName)) { return isDupRef(); }
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<GroupingReference> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof GroupingReference) { return OptionalThing.of((GroupingReference)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<GroupingReference> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static GroupingReference codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof GroupingReference) { return (GroupingReference)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static GroupingReference nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<GroupingReference> listAll() {
return new ArrayList<GroupingReference>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<GroupingReference> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
if ("serviceAvailable".equalsIgnoreCase(groupName)) { return listOfServiceAvailable(); }
if ("servicePlus".equalsIgnoreCase(groupName)) { return listOfServicePlus(); }
if ("nestedPlus".equalsIgnoreCase(groupName)) { return listOfNestedPlus(); }
if ("oneDef".equalsIgnoreCase(groupName)) { return listOfOneDef(); }
if ("dupRef".equalsIgnoreCase(groupName)) { return listOfDupRef(); }
throw new ClassificationNotFoundException("Unknown classification group: GroupingReference." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<GroupingReference> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<GroupingReference> clsList = new ArrayList<GroupingReference>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of group classification elements. (returns new copied list) <br>
* サービスが利用できる会員 <br>
* The group elements:[LAND_NAME, SEA_NAME]
* @return The snapshot list of classification elements in the group. (NotNull)
*/
public static List<GroupingReference> listOfServiceAvailable() {
return new ArrayList<GroupingReference>(Arrays.asList(LAND_NAME, SEA_NAME));
}
/**
* Get the list of group classification elements. (returns new copied list) <br>
* The group elements:[LAND_NAME, SEA_NAME, IKSPIARY_NAME]
* @return The snapshot list of classification elements in the group. (NotNull)
*/
public static List<GroupingReference> listOfServicePlus() {
return new ArrayList<GroupingReference>(Arrays.asList(LAND_NAME, SEA_NAME, IKSPIARY_NAME));
}
/**
* Get the list of group classification elements. (returns new copied list) <br>
* The group elements:[AMPHI_NAME, LAND_NAME, SEA_NAME, IKSPIARY_NAME]
* @return The snapshot list of classification elements in the group. (NotNull)
*/
public static List<GroupingReference> listOfNestedPlus() {
return new ArrayList<GroupingReference>(Arrays.asList(AMPHI_NAME, LAND_NAME, SEA_NAME, IKSPIARY_NAME));
}
/**
* Get the list of group classification elements. (returns new copied list) <br>
* The group elements:[IKSPIARY_NAME]
* @return The snapshot list of classification elements in the group. (NotNull)
*/
public static List<GroupingReference> listOfOneDef() {
return new ArrayList<GroupingReference>(Arrays.asList(IKSPIARY_NAME));
}
/**
* Get the list of group classification elements. (returns new copied list) <br>
* The group elements:[LAND_NAME, SEA_NAME, IKSPIARY_NAME]
* @return The snapshot list of classification elements in the group. (NotNull)
*/
public static List<GroupingReference> listOfDupRef() {
return new ArrayList<GroupingReference>(Arrays.asList(LAND_NAME, SEA_NAME, IKSPIARY_NAME));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<GroupingReference> groupOf(String groupName) {
if ("serviceAvailable".equals(groupName)) { return listOfServiceAvailable(); }
if ("servicePlus".equals(groupName)) { return listOfServicePlus(); }
if ("nestedPlus".equals(groupName)) { return listOfNestedPlus(); }
if ("oneDef".equals(groupName)) { return listOfOneDef(); }
if ("dupRef".equals(groupName)) { return listOfDupRef(); }
return new ArrayList<GroupingReference>(4);
}
@Override public String toString() { return code(); }
}
/**
* The test of relation reference
*/
public enum SelfReference implements CDef {
/** foo801 */
Foo801("801", "foo801", emptyStrings())
,
/** foo811 */
Foo811("811", "foo811", emptyStrings())
,
/** bar802: 0 */
Bar802("802", "bar802", emptyStrings())
,
/** baz803: 0 */
Baz803("803", "baz803", emptyStrings())
,
/** bar812: 0 */
Bar812("812", "bar812", emptyStrings())
,
/** baz813: 0 */
Baz813("813", "baz813", emptyStrings())
;
private static final Map<String, SelfReference> _codeClsMap = new HashMap<String, SelfReference>();
private static final Map<String, SelfReference> _nameClsMap = new HashMap<String, SelfReference>();
static {
for (SelfReference value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private SelfReference(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.SelfReference; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<SelfReference> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof SelfReference) { return OptionalThing.of((SelfReference)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<SelfReference> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static SelfReference codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof SelfReference) { return (SelfReference)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static SelfReference nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<SelfReference> listAll() {
return new ArrayList<SelfReference>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<SelfReference> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: SelfReference." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<SelfReference> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<SelfReference> clsList = new ArrayList<SelfReference>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<SelfReference> groupOf(String groupName) {
return new ArrayList<SelfReference>(4);
}
@Override public String toString() { return code(); }
}
/**
* The test of top only
*/
public enum TopCommentOnly implements CDef {
;
private static final Map<String, TopCommentOnly> _codeClsMap = new HashMap<String, TopCommentOnly>();
private static final Map<String, TopCommentOnly> _nameClsMap = new HashMap<String, TopCommentOnly>();
static {
for (TopCommentOnly value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private TopCommentOnly(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.TopCommentOnly; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<TopCommentOnly> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof TopCommentOnly) { return OptionalThing.of((TopCommentOnly)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<TopCommentOnly> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static TopCommentOnly codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof TopCommentOnly) { return (TopCommentOnly)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static TopCommentOnly nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<TopCommentOnly> listAll() {
return new ArrayList<TopCommentOnly>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<TopCommentOnly> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: TopCommentOnly." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<TopCommentOnly> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<TopCommentOnly> clsList = new ArrayList<TopCommentOnly>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<TopCommentOnly> groupOf(String groupName) {
return new ArrayList<TopCommentOnly>(4);
}
@Override public String toString() { return code(); }
}
/**
* the test of sub-item map for implicit classification
*/
public enum SubItemImplicit implements CDef {
/** Aaa: means foo */
Foo("FOO", "Aaa", emptyStrings())
,
/** Bbb: means bar */
Bar("BAR", "Bbb", emptyStrings())
;
private static final Map<String, SubItemImplicit> _codeClsMap = new HashMap<String, SubItemImplicit>();
private static final Map<String, SubItemImplicit> _nameClsMap = new HashMap<String, SubItemImplicit>();
static {
for (SubItemImplicit value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private static final Map<String, Map<String, Object>> _subItemMapMap = new HashMap<String, Map<String, Object>>();
static {
{
Map<String, Object> subItemMap = new HashMap<String, Object>();
subItemMap.put("regularStringItem", "value1<tag>");
subItemMap.put("regularNumberItem", "123");
subItemMap.put("regularVariousItem", "list:{\n ; reg\n ; var\n ; ite\n}");
subItemMap.put("listItem", "list:{\n ; aa\n ; bb\n ; cc\n}");
_subItemMapMap.put(Foo.code(), Collections.unmodifiableMap(subItemMap));
}
{
Map<String, Object> subItemMap = new HashMap<String, Object>();
subItemMap.put("regularStringItem", "value2<teg>");
subItemMap.put("regularNumberItem", "456");
subItemMap.put("regularVariousItem", "map:{\n ; reg = var\n ; ous = ite\n}");
subItemMap.put("mapItem", "map:{\n ; key11 = value11\n}");
subItemMap.put("containsLine", "va\nlue");
_subItemMapMap.put(Bar.code(), Collections.unmodifiableMap(subItemMap));
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private SubItemImplicit(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return _subItemMapMap.get(code()); }
public ClassificationMeta meta() { return CDef.DefMeta.SubItemImplicit; }
public String regularStringItem() {
return (String)subItemMap().get("regularStringItem");
}
public String regularNumberItem() {
return (String)subItemMap().get("regularNumberItem");
}
public Object regularVariousItem() {
return subItemMap().get("regularVariousItem");
}
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<SubItemImplicit> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof SubItemImplicit) { return OptionalThing.of((SubItemImplicit)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<SubItemImplicit> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static SubItemImplicit codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof SubItemImplicit) { return (SubItemImplicit)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static SubItemImplicit nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<SubItemImplicit> listAll() {
return new ArrayList<SubItemImplicit>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<SubItemImplicit> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: SubItemImplicit." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<SubItemImplicit> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<SubItemImplicit> clsList = new ArrayList<SubItemImplicit>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<SubItemImplicit> groupOf(String groupName) {
return new ArrayList<SubItemImplicit>(4);
}
@Override public String toString() { return code(); }
}
/**
* the test of sub-item map for table classification
*/
public enum SubItemTable implements CDef {
/** 正式会員: 正式な会員としてサイトサービスが利用可能 */
正式会員("FML", "正式会員", emptyStrings())
,
/** 退会会員: 退会が確定した会員でサイトサービスはダメ */
退会会員("WDL", "退会会員", emptyStrings())
,
/** 仮会員: 入会直後のステータスで一部のサイトサービスが利用可能 */
仮会員("PRV", "仮会員", emptyStrings())
;
private static final Map<String, SubItemTable> _codeClsMap = new HashMap<String, SubItemTable>();
private static final Map<String, SubItemTable> _nameClsMap = new HashMap<String, SubItemTable>();
static {
for (SubItemTable value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private static final Map<String, Map<String, Object>> _subItemMapMap = new HashMap<String, Map<String, Object>>();
static {
{
Map<String, Object> subItemMap = new HashMap<String, Object>();
subItemMap.put("key1", "1");
subItemMap.put("key2", "正式会員");
subItemMap.put("key3", null);
_subItemMapMap.put(正式会員.code(), Collections.unmodifiableMap(subItemMap));
}
{
Map<String, Object> subItemMap = new HashMap<String, Object>();
subItemMap.put("key1", "2");
subItemMap.put("key2", "退会会員");
subItemMap.put("key3", null);
_subItemMapMap.put(退会会員.code(), Collections.unmodifiableMap(subItemMap));
}
{
Map<String, Object> subItemMap = new HashMap<String, Object>();
subItemMap.put("key1", "3");
subItemMap.put("key2", "仮会員");
subItemMap.put("key3", null);
_subItemMapMap.put(仮会員.code(), Collections.unmodifiableMap(subItemMap));
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private SubItemTable(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return _subItemMapMap.get(code()); }
public ClassificationMeta meta() { return CDef.DefMeta.SubItemTable; }
public String key1() {
return (String)subItemMap().get("key1");
}
public String key2() {
return (String)subItemMap().get("key2");
}
public String key3() {
return (String)subItemMap().get("key3");
}
/**
* Is the classification in the group? <br>
* サービスが利用できる会員 <br>
* The group elements:[正式会員, 仮会員]
* @return The determination, true or false.
*/
public boolean isServiceAvailable() {
return 正式会員.equals(this) || 仮会員.equals(this);
}
/**
* Is the classification in the group? <br>
* The group elements:[退会会員]
* @return The determination, true or false.
*/
public boolean isLastestStatus() {
return 退会会員.equals(this);
}
public boolean inGroup(String groupName) {
if ("serviceAvailable".equals(groupName)) { return isServiceAvailable(); }
if ("lastestStatus".equals(groupName)) { return isLastestStatus(); }
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<SubItemTable> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof SubItemTable) { return OptionalThing.of((SubItemTable)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<SubItemTable> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static SubItemTable codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof SubItemTable) { return (SubItemTable)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static SubItemTable nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<SubItemTable> listAll() {
return new ArrayList<SubItemTable>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<SubItemTable> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
if ("serviceAvailable".equalsIgnoreCase(groupName)) { return listOfServiceAvailable(); }
if ("lastestStatus".equalsIgnoreCase(groupName)) { return listOfLastestStatus(); }
throw new ClassificationNotFoundException("Unknown classification group: SubItemTable." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<SubItemTable> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<SubItemTable> clsList = new ArrayList<SubItemTable>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of group classification elements. (returns new copied list) <br>
* サービスが利用できる会員 <br>
* The group elements:[正式会員, 仮会員]
* @return The snapshot list of classification elements in the group. (NotNull)
*/
public static List<SubItemTable> listOfServiceAvailable() {
return new ArrayList<SubItemTable>(Arrays.asList(正式会員, 仮会員));
}
/**
* Get the list of group classification elements. (returns new copied list) <br>
* The group elements:[退会会員]
* @return The snapshot list of classification elements in the group. (NotNull)
*/
public static List<SubItemTable> listOfLastestStatus() {
return new ArrayList<SubItemTable>(Arrays.asList(退会会員));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<SubItemTable> groupOf(String groupName) {
if ("serviceAvailable".equals(groupName)) { return listOfServiceAvailable(); }
if ("lastestStatus".equals(groupName)) { return listOfLastestStatus(); }
return new ArrayList<SubItemTable>(4);
}
@Override public String toString() { return code(); }
}
/**
* boolean classification for boolean column
*/
public enum BooleanFlg implements CDef {
/** Checked: means yes */
True("true", "Checked", emptyStrings())
,
/** Unchecked: means no */
False("false", "Unchecked", emptyStrings())
;
private static final Map<String, BooleanFlg> _codeClsMap = new HashMap<String, BooleanFlg>();
private static final Map<String, BooleanFlg> _nameClsMap = new HashMap<String, BooleanFlg>();
static {
for (BooleanFlg value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private BooleanFlg(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.BooleanFlg; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<BooleanFlg> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof BooleanFlg) { return OptionalThing.of((BooleanFlg)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<BooleanFlg> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static BooleanFlg codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof BooleanFlg) { return (BooleanFlg)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static BooleanFlg nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<BooleanFlg> listAll() {
return new ArrayList<BooleanFlg>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<BooleanFlg> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: BooleanFlg." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<BooleanFlg> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<BooleanFlg> clsList = new ArrayList<BooleanFlg>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<BooleanFlg> groupOf(String groupName) {
return new ArrayList<BooleanFlg>(4);
}
@Override public String toString() { return code(); }
}
/**
* master type of variant relation (biz-many-to-one)
*/
public enum VariantRelationMasterType implements CDef {
/** FooCls */
FooCls("FOO", "FooCls", emptyStrings())
,
/** BarCls */
BarCls("BAR", "BarCls", emptyStrings())
,
/** QuxCls */
QuxCls("QUX", "QuxCls", emptyStrings())
,
/** CorgeCls */
CorgeCls("CORGE", "CorgeCls", emptyStrings())
;
private static final Map<String, VariantRelationMasterType> _codeClsMap = new HashMap<String, VariantRelationMasterType>();
private static final Map<String, VariantRelationMasterType> _nameClsMap = new HashMap<String, VariantRelationMasterType>();
static {
for (VariantRelationMasterType value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private VariantRelationMasterType(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.VariantRelationMasterType; }
/**
* Is the classification in the group? <br>
* Foo or Bar or Qux <br>
* The group elements:[FooCls, BarCls, QuxCls]
* @return The determination, true or false.
*/
public boolean isFooBarQux() {
return FooCls.equals(this) || BarCls.equals(this) || QuxCls.equals(this);
}
public boolean inGroup(String groupName) {
if ("fooBarQux".equals(groupName)) { return isFooBarQux(); }
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<VariantRelationMasterType> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof VariantRelationMasterType) { return OptionalThing.of((VariantRelationMasterType)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<VariantRelationMasterType> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static VariantRelationMasterType codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof VariantRelationMasterType) { return (VariantRelationMasterType)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static VariantRelationMasterType nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<VariantRelationMasterType> listAll() {
return new ArrayList<VariantRelationMasterType>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<VariantRelationMasterType> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
if ("fooBarQux".equalsIgnoreCase(groupName)) { return listOfFooBarQux(); }
throw new ClassificationNotFoundException("Unknown classification group: VariantRelationMasterType." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<VariantRelationMasterType> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<VariantRelationMasterType> clsList = new ArrayList<VariantRelationMasterType>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of group classification elements. (returns new copied list) <br>
* Foo or Bar or Qux <br>
* The group elements:[FooCls, BarCls, QuxCls]
* @return The snapshot list of classification elements in the group. (NotNull)
*/
public static List<VariantRelationMasterType> listOfFooBarQux() {
return new ArrayList<VariantRelationMasterType>(Arrays.asList(FooCls, BarCls, QuxCls));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<VariantRelationMasterType> groupOf(String groupName) {
if ("fooBarQux".equals(groupName)) { return listOfFooBarQux(); }
return new ArrayList<VariantRelationMasterType>(4);
}
@Override public String toString() { return code(); }
}
/**
* qux type of variant relation (biz-many-to-one)
*/
public enum VariantRelationQuxType implements CDef {
/** Qua */
Qua("Qua", "Qua", emptyStrings())
,
/** Que */
Que("Que", "Que", emptyStrings())
,
/** Quo */
Quo("Quo", "Quo", emptyStrings())
;
private static final Map<String, VariantRelationQuxType> _codeClsMap = new HashMap<String, VariantRelationQuxType>();
private static final Map<String, VariantRelationQuxType> _nameClsMap = new HashMap<String, VariantRelationQuxType>();
static {
for (VariantRelationQuxType value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private VariantRelationQuxType(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.VariantRelationQuxType; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<VariantRelationQuxType> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof VariantRelationQuxType) { return OptionalThing.of((VariantRelationQuxType)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<VariantRelationQuxType> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static VariantRelationQuxType codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof VariantRelationQuxType) { return (VariantRelationQuxType)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static VariantRelationQuxType nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<VariantRelationQuxType> listAll() {
return new ArrayList<VariantRelationQuxType>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<VariantRelationQuxType> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: VariantRelationQuxType." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<VariantRelationQuxType> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<VariantRelationQuxType> clsList = new ArrayList<VariantRelationQuxType>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<VariantRelationQuxType> groupOf(String groupName) {
return new ArrayList<VariantRelationQuxType>(4);
}
@Override public String toString() { return code(); }
}
/**
* merged
*/
public enum QuxCls implements CDef {
/** Merged: merged qux element */
Merged("MRG", "Merged", emptyStrings())
,
/** QuxOne: QuxOne */
QuxOne("Q01", "QuxOne", emptyStrings())
,
/** QuxTwo: QuxTwo */
QuxTwo("Q02", "QuxTwo", emptyStrings())
,
/** QuxThree: QuxThree */
QuxThree("Q03", "QuxThree", emptyStrings())
;
private static final Map<String, QuxCls> _codeClsMap = new HashMap<String, QuxCls>();
private static final Map<String, QuxCls> _nameClsMap = new HashMap<String, QuxCls>();
static {
for (QuxCls value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private QuxCls(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.QuxCls; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<QuxCls> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof QuxCls) { return OptionalThing.of((QuxCls)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<QuxCls> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static QuxCls codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof QuxCls) { return (QuxCls)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static QuxCls nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<QuxCls> listAll() {
return new ArrayList<QuxCls>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<QuxCls> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: QuxCls." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<QuxCls> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<QuxCls> clsList = new ArrayList<QuxCls>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<QuxCls> groupOf(String groupName) {
return new ArrayList<QuxCls>(4);
}
@Override public String toString() { return code(); }
}
/**
* delimiter; & endBrace} & path\foo\bar
*/
public enum EscapedDfpropCls implements CDef {
/** First: delimiter & rear escape char */
First(";@\\", "First", emptyStrings())
,
/** Second: escape char & endBrace & delimiter */
Second("\\};", "Second", emptyStrings())
,
/** Third: startBrace & equal & endBrace */
Third("{=}", "Third", emptyStrings())
;
private static final Map<String, EscapedDfpropCls> _codeClsMap = new HashMap<String, EscapedDfpropCls>();
private static final Map<String, EscapedDfpropCls> _nameClsMap = new HashMap<String, EscapedDfpropCls>();
static {
for (EscapedDfpropCls value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private EscapedDfpropCls(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.EscapedDfpropCls; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<EscapedDfpropCls> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof EscapedDfpropCls) { return OptionalThing.of((EscapedDfpropCls)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<EscapedDfpropCls> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static EscapedDfpropCls codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof EscapedDfpropCls) { return (EscapedDfpropCls)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static EscapedDfpropCls nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<EscapedDfpropCls> listAll() {
return new ArrayList<EscapedDfpropCls>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<EscapedDfpropCls> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: EscapedDfpropCls." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<EscapedDfpropCls> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<EscapedDfpropCls> clsList = new ArrayList<EscapedDfpropCls>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<EscapedDfpropCls> groupOf(String groupName) {
return new ArrayList<EscapedDfpropCls>(4);
}
@Override public String toString() { return code(); }
}
/**
* /*IF pmb.yourTop*/><&
*/
public enum EscapedJavaDocCls implements CDef {
/** First: /*IF pmb.yourFooComment*/><& */
First("FOO", "First", emptyStrings())
,
/** Second: /*IF pmb.yourBarComment*/><& */
Second("BAR", "Second", emptyStrings())
;
private static final Map<String, EscapedJavaDocCls> _codeClsMap = new HashMap<String, EscapedJavaDocCls>();
private static final Map<String, EscapedJavaDocCls> _nameClsMap = new HashMap<String, EscapedJavaDocCls>();
static {
for (EscapedJavaDocCls value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private EscapedJavaDocCls(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.EscapedJavaDocCls; }
/**
* Is the classification in the group? <br>
* /*IF pmb.yourGroup*/><& <br>
* The group elements:[First, Second]
* @return The determination, true or false.
*/
public boolean isLineGroup() {
return First.equals(this) || Second.equals(this);
}
public boolean inGroup(String groupName) {
if ("lineGroup".equals(groupName)) { return isLineGroup(); }
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<EscapedJavaDocCls> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof EscapedJavaDocCls) { return OptionalThing.of((EscapedJavaDocCls)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<EscapedJavaDocCls> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static EscapedJavaDocCls codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof EscapedJavaDocCls) { return (EscapedJavaDocCls)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static EscapedJavaDocCls nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<EscapedJavaDocCls> listAll() {
return new ArrayList<EscapedJavaDocCls>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<EscapedJavaDocCls> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
if ("lineGroup".equalsIgnoreCase(groupName)) { return listOfLineGroup(); }
throw new ClassificationNotFoundException("Unknown classification group: EscapedJavaDocCls." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<EscapedJavaDocCls> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<EscapedJavaDocCls> clsList = new ArrayList<EscapedJavaDocCls>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of group classification elements. (returns new copied list) <br>
* /*IF pmb.yourGroup*/><& <br>
* The group elements:[First, Second]
* @return The snapshot list of classification elements in the group. (NotNull)
*/
public static List<EscapedJavaDocCls> listOfLineGroup() {
return new ArrayList<EscapedJavaDocCls>(Arrays.asList(First, Second));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<EscapedJavaDocCls> groupOf(String groupName) {
if ("lineGroup".equals(groupName)) { return listOfLineGroup(); }
return new ArrayList<EscapedJavaDocCls>(4);
}
@Override public String toString() { return code(); }
}
/**
* 6
*/
public enum EscapedNumberInitialCls implements CDef {
/** 1Foo */
N1Foo("1FO", "1Foo", emptyStrings())
,
/** 3Bar */
N3Bar("3BA", "3Bar", emptyStrings())
,
/** 7Qux */
N7Qux("7QU", "7Qux", emptyStrings())
,
/** Corge9 */
Corge9("CO9", "Corge9", emptyStrings())
;
private static final Map<String, EscapedNumberInitialCls> _codeClsMap = new HashMap<String, EscapedNumberInitialCls>();
private static final Map<String, EscapedNumberInitialCls> _nameClsMap = new HashMap<String, EscapedNumberInitialCls>();
static {
for (EscapedNumberInitialCls value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private EscapedNumberInitialCls(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.EscapedNumberInitialCls; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<EscapedNumberInitialCls> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof EscapedNumberInitialCls) { return OptionalThing.of((EscapedNumberInitialCls)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<EscapedNumberInitialCls> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static EscapedNumberInitialCls codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof EscapedNumberInitialCls) { return (EscapedNumberInitialCls)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static EscapedNumberInitialCls nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<EscapedNumberInitialCls> listAll() {
return new ArrayList<EscapedNumberInitialCls>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<EscapedNumberInitialCls> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: EscapedNumberInitialCls." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<EscapedNumberInitialCls> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<EscapedNumberInitialCls> clsList = new ArrayList<EscapedNumberInitialCls>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<EscapedNumberInitialCls> groupOf(String groupName) {
return new ArrayList<EscapedNumberInitialCls>(4);
}
@Override public String toString() { return code(); }
}
/**
* top first line top second line top third line
*/
public enum LineSepCommentCls implements CDef {
/** First: foo first line foo second line */
First("FOO", "First", emptyStrings())
,
/** Second: bar first line bar second line */
Second("BAR", "Second", emptyStrings())
;
private static final Map<String, LineSepCommentCls> _codeClsMap = new HashMap<String, LineSepCommentCls>();
private static final Map<String, LineSepCommentCls> _nameClsMap = new HashMap<String, LineSepCommentCls>();
static {
for (LineSepCommentCls value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private LineSepCommentCls(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.LineSepCommentCls; }
/**
* Is the classification in the group? <br>
* group first line group second line <br>
* The group elements:[First, Second]
* @return The determination, true or false.
*/
public boolean isLineGroup() {
return First.equals(this) || Second.equals(this);
}
public boolean inGroup(String groupName) {
if ("lineGroup".equals(groupName)) { return isLineGroup(); }
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<LineSepCommentCls> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof LineSepCommentCls) { return OptionalThing.of((LineSepCommentCls)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<LineSepCommentCls> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static LineSepCommentCls codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof LineSepCommentCls) { return (LineSepCommentCls)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static LineSepCommentCls nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<LineSepCommentCls> listAll() {
return new ArrayList<LineSepCommentCls>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<LineSepCommentCls> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
if ("lineGroup".equalsIgnoreCase(groupName)) { return listOfLineGroup(); }
throw new ClassificationNotFoundException("Unknown classification group: LineSepCommentCls." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<LineSepCommentCls> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<LineSepCommentCls> clsList = new ArrayList<LineSepCommentCls>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of group classification elements. (returns new copied list) <br>
* group first line group second line <br>
* The group elements:[First, Second]
* @return The snapshot list of classification elements in the group. (NotNull)
*/
public static List<LineSepCommentCls> listOfLineGroup() {
return new ArrayList<LineSepCommentCls>(Arrays.asList(First, Second));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<LineSepCommentCls> groupOf(String groupName) {
if ("lineGroup".equals(groupName)) { return listOfLineGroup(); }
return new ArrayList<LineSepCommentCls>(4);
}
@Override public String toString() { return code(); }
}
/**
* no camelizing classification
*/
public enum NamingDefaultCamelizingType implements CDef {
/** Bonvo */
Bonvo("BONVO", "Bonvo", emptyStrings())
,
/** dstore */
Dstore("DSTORE", "dstore", emptyStrings())
,
/** LAND陸oneman */
LAND陸oneman("LAND", "LAND陸oneman", emptyStrings())
,
/** PI AR-I */
PiArI("PIARI", "PI AR-I", emptyStrings())
,
/** SEA海MYSTIC */
Sea海mystic("SEA", "SEA海MYSTIC", emptyStrings())
;
private static final Map<String, NamingDefaultCamelizingType> _codeClsMap = new HashMap<String, NamingDefaultCamelizingType>();
private static final Map<String, NamingDefaultCamelizingType> _nameClsMap = new HashMap<String, NamingDefaultCamelizingType>();
static {
for (NamingDefaultCamelizingType value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private NamingDefaultCamelizingType(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.NamingDefaultCamelizingType; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<NamingDefaultCamelizingType> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof NamingDefaultCamelizingType) { return OptionalThing.of((NamingDefaultCamelizingType)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<NamingDefaultCamelizingType> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static NamingDefaultCamelizingType codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof NamingDefaultCamelizingType) { return (NamingDefaultCamelizingType)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static NamingDefaultCamelizingType nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<NamingDefaultCamelizingType> listAll() {
return new ArrayList<NamingDefaultCamelizingType>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<NamingDefaultCamelizingType> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: NamingDefaultCamelizingType." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<NamingDefaultCamelizingType> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<NamingDefaultCamelizingType> clsList = new ArrayList<NamingDefaultCamelizingType>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<NamingDefaultCamelizingType> groupOf(String groupName) {
return new ArrayList<NamingDefaultCamelizingType>(4);
}
@Override public String toString() { return code(); }
}
/**
* no camelizing classification
*/
public enum NamingNoCamelizingType implements CDef {
/** Bonvo */
Bonvo("BONVO", "Bonvo", emptyStrings())
,
/** dstore */
dstore("DSTORE", "dstore", emptyStrings())
,
/** LAND陸oneman */
LAND陸oneman("LAND", "LAND陸oneman", emptyStrings())
,
/** PI AR-I */
PI_ARI("PIARI", "PI AR-I", emptyStrings())
,
/** SEA海MYSTIC */
SEA海MYSTIC("SEA", "SEA海MYSTIC", emptyStrings())
;
private static final Map<String, NamingNoCamelizingType> _codeClsMap = new HashMap<String, NamingNoCamelizingType>();
private static final Map<String, NamingNoCamelizingType> _nameClsMap = new HashMap<String, NamingNoCamelizingType>();
static {
for (NamingNoCamelizingType value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private NamingNoCamelizingType(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.NamingNoCamelizingType; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<NamingNoCamelizingType> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof NamingNoCamelizingType) { return OptionalThing.of((NamingNoCamelizingType)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<NamingNoCamelizingType> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static NamingNoCamelizingType codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof NamingNoCamelizingType) { return (NamingNoCamelizingType)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static NamingNoCamelizingType nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<NamingNoCamelizingType> listAll() {
return new ArrayList<NamingNoCamelizingType>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<NamingNoCamelizingType> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: NamingNoCamelizingType." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<NamingNoCamelizingType> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<NamingNoCamelizingType> clsList = new ArrayList<NamingNoCamelizingType>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<NamingNoCamelizingType> groupOf(String groupName) {
return new ArrayList<NamingNoCamelizingType>(4);
}
@Override public String toString() { return code(); }
}
/**
* is deprecated classification
*/
@Deprecated
public enum DeprecatedTopBasicType implements CDef {
/** FooName */
FooName("FOO", "FooName", emptyStrings())
,
/** BarName */
BarName("BAR", "BarName", emptyStrings())
,
/** QuxName */
QuxName("QUX", "QuxName", emptyStrings())
;
private static final Map<String, DeprecatedTopBasicType> _codeClsMap = new HashMap<String, DeprecatedTopBasicType>();
private static final Map<String, DeprecatedTopBasicType> _nameClsMap = new HashMap<String, DeprecatedTopBasicType>();
static {
for (DeprecatedTopBasicType value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private DeprecatedTopBasicType(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.DeprecatedTopBasicType; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<DeprecatedTopBasicType> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof DeprecatedTopBasicType) { return OptionalThing.of((DeprecatedTopBasicType)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<DeprecatedTopBasicType> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static DeprecatedTopBasicType codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof DeprecatedTopBasicType) { return (DeprecatedTopBasicType)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static DeprecatedTopBasicType nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<DeprecatedTopBasicType> listAll() {
return new ArrayList<DeprecatedTopBasicType>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<DeprecatedTopBasicType> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: DeprecatedTopBasicType." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<DeprecatedTopBasicType> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<DeprecatedTopBasicType> clsList = new ArrayList<DeprecatedTopBasicType>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<DeprecatedTopBasicType> groupOf(String groupName) {
return new ArrayList<DeprecatedTopBasicType>(4);
}
@Override public String toString() { return code(); }
}
/**
* has deprecated element
*/
public enum DeprecatedMapBasicType implements CDef {
/** FooName */
FooName("FOO", "FooName", emptyStrings())
,
/** BarName: (deprecated: test of deprecated) */
@Deprecated
BarName("BAR", "BarName", emptyStrings())
,
/** QuxName */
QuxName("QUX", "QuxName", emptyStrings())
;
private static final Map<String, DeprecatedMapBasicType> _codeClsMap = new HashMap<String, DeprecatedMapBasicType>();
private static final Map<String, DeprecatedMapBasicType> _nameClsMap = new HashMap<String, DeprecatedMapBasicType>();
static {
for (DeprecatedMapBasicType value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private DeprecatedMapBasicType(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.DeprecatedMapBasicType; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<DeprecatedMapBasicType> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof DeprecatedMapBasicType) { return OptionalThing.of((DeprecatedMapBasicType)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<DeprecatedMapBasicType> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static DeprecatedMapBasicType codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof DeprecatedMapBasicType) { return (DeprecatedMapBasicType)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static DeprecatedMapBasicType nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<DeprecatedMapBasicType> listAll() {
return new ArrayList<DeprecatedMapBasicType>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<DeprecatedMapBasicType> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: DeprecatedMapBasicType." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<DeprecatedMapBasicType> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<DeprecatedMapBasicType> clsList = new ArrayList<DeprecatedMapBasicType>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<DeprecatedMapBasicType> groupOf(String groupName) {
return new ArrayList<DeprecatedMapBasicType>(4);
}
@Override public String toString() { return code(); }
}
/**
* has deprecated element
*/
public enum DeprecatedMapCollaborationType implements CDef {
/** FooName */
FooName("FOO", "FooName", emptyStrings())
,
/** BarBar: here (deprecated: test of deprecated) */
@Deprecated
BarName("BAR", "BarBar", emptyStrings())
,
/** QuxQux: (deprecated: no original comment) */
@Deprecated
QuxName("QUX", "QuxQux", emptyStrings())
;
private static final Map<String, DeprecatedMapCollaborationType> _codeClsMap = new HashMap<String, DeprecatedMapCollaborationType>();
private static final Map<String, DeprecatedMapCollaborationType> _nameClsMap = new HashMap<String, DeprecatedMapCollaborationType>();
static {
for (DeprecatedMapCollaborationType value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private DeprecatedMapCollaborationType(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.DeprecatedMapCollaborationType; }
/**
* Is the classification in the group? <br>
* contains deprecated element here <br>
* The group elements:[FooName, BarName]
* @return The determination, true or false.
*/
public boolean isContainsDeprecated() {
return FooName.equals(this) || BarName.equals(this);
}
public boolean inGroup(String groupName) {
if ("containsDeprecated".equals(groupName)) { return isContainsDeprecated(); }
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<DeprecatedMapCollaborationType> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof DeprecatedMapCollaborationType) { return OptionalThing.of((DeprecatedMapCollaborationType)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<DeprecatedMapCollaborationType> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static DeprecatedMapCollaborationType codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof DeprecatedMapCollaborationType) { return (DeprecatedMapCollaborationType)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static DeprecatedMapCollaborationType nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<DeprecatedMapCollaborationType> listAll() {
return new ArrayList<DeprecatedMapCollaborationType>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<DeprecatedMapCollaborationType> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
if ("containsDeprecated".equalsIgnoreCase(groupName)) { return listOfContainsDeprecated(); }
throw new ClassificationNotFoundException("Unknown classification group: DeprecatedMapCollaborationType." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<DeprecatedMapCollaborationType> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<DeprecatedMapCollaborationType> clsList = new ArrayList<DeprecatedMapCollaborationType>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of group classification elements. (returns new copied list) <br>
* contains deprecated element here <br>
* The group elements:[FooName, BarName]
* @return The snapshot list of classification elements in the group. (NotNull)
*/
public static List<DeprecatedMapCollaborationType> listOfContainsDeprecated() {
return new ArrayList<DeprecatedMapCollaborationType>(Arrays.asList(FooName, BarName));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<DeprecatedMapCollaborationType> groupOf(String groupName) {
if ("containsDeprecated".equals(groupName)) { return listOfContainsDeprecated(); }
return new ArrayList<DeprecatedMapCollaborationType>(4);
}
@Override public String toString() { return code(); }
}
/**
* unique key as classification
*/
public enum UQClassificationType implements CDef {
;
private static final Map<String, UQClassificationType> _codeClsMap = new HashMap<String, UQClassificationType>();
private static final Map<String, UQClassificationType> _nameClsMap = new HashMap<String, UQClassificationType>();
static {
for (UQClassificationType value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private UQClassificationType(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.UQClassificationType; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<UQClassificationType> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof UQClassificationType) { return OptionalThing.of((UQClassificationType)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<UQClassificationType> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static UQClassificationType codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof UQClassificationType) { return (UQClassificationType)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static UQClassificationType nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<UQClassificationType> listAll() {
return new ArrayList<UQClassificationType>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<UQClassificationType> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: UQClassificationType." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<UQClassificationType> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<UQClassificationType> clsList = new ArrayList<UQClassificationType>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<UQClassificationType> groupOf(String groupName) {
return new ArrayList<UQClassificationType>(4);
}
@Override public String toString() { return code(); }
}
/**
* Classification of Bar
*/
public enum BarCls implements CDef {
/** BarOne: BarOne */
BarOne("B01", "BarOne", emptyStrings())
,
/** BarTwo: BarTwo */
BarTwo("B02", "BarTwo", emptyStrings())
,
/** BarThree: BarThree */
BarThree("B03", "BarThree", emptyStrings())
,
/** BarFour: BarFour */
BarFour("B04", "BarFour", emptyStrings())
,
/** BarFive: BarFive */
BarFive("B05", "BarFive", emptyStrings())
;
private static final Map<String, BarCls> _codeClsMap = new HashMap<String, BarCls>();
private static final Map<String, BarCls> _nameClsMap = new HashMap<String, BarCls>();
static {
for (BarCls value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private BarCls(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.BarCls; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<BarCls> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof BarCls) { return OptionalThing.of((BarCls)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<BarCls> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static BarCls codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof BarCls) { return (BarCls)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static BarCls nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<BarCls> listAll() {
return new ArrayList<BarCls>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<BarCls> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: BarCls." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<BarCls> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<BarCls> clsList = new ArrayList<BarCls>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<BarCls> groupOf(String groupName) {
return new ArrayList<BarCls>(4);
}
@Override public String toString() { return code(); }
}
/**
* Classification of Foo
*/
public enum FooCls implements CDef {
/** FooOne: FooOne */
FooOne("F01", "FooOne", emptyStrings())
,
/** FooTwo: FooTwo */
FooTwo("F02", "FooTwo", emptyStrings())
,
/** FooThree: FooThree */
FooThree("F03", "FooThree", emptyStrings())
,
/** FooFour: FooFour */
FooFour("F04", "FooFour", emptyStrings())
;
private static final Map<String, FooCls> _codeClsMap = new HashMap<String, FooCls>();
private static final Map<String, FooCls> _nameClsMap = new HashMap<String, FooCls>();
static {
for (FooCls value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private FooCls(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.FooCls; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<FooCls> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof FooCls) { return OptionalThing.of((FooCls)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<FooCls> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static FooCls codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof FooCls) { return (FooCls)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static FooCls nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<FooCls> listAll() {
return new ArrayList<FooCls>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<FooCls> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: FooCls." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<FooCls> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<FooCls> clsList = new ArrayList<FooCls>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<FooCls> groupOf(String groupName) {
return new ArrayList<FooCls>(4);
}
@Override public String toString() { return code(); }
}
/**
* フラグを示す
*/
public enum Flg implements CDef {
/** はい: 有効を示す */
True("1", "はい", emptyStrings())
,
/** いいえ: 無効を示す */
False("0", "いいえ", emptyStrings())
;
private static final Map<String, Flg> _codeClsMap = new HashMap<String, Flg>();
private static final Map<String, Flg> _nameClsMap = new HashMap<String, Flg>();
static {
for (Flg value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private Flg(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.Flg; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<Flg> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof Flg) { return OptionalThing.of((Flg)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<Flg> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static Flg codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof Flg) { return (Flg)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static Flg nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<Flg> listAll() {
return new ArrayList<Flg>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<Flg> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: Flg." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<Flg> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<Flg> clsList = new ArrayList<Flg>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<Flg> groupOf(String groupName) {
return new ArrayList<Flg>(4);
}
@Override public String toString() { return code(); }
}
/**
* 会員ステータス: 会員の状態を示す
*/
public enum MemberStatus implements CDef {
/** 正式会員: 正式な会員を示す */
Formalized("FML", "正式会員", emptyStrings())
,
/** 仮会員: 仮の会員を示す */
Provisional("PRV", "仮会員", emptyStrings())
,
/** 退会会員: 退会した会員を示す */
Withdrawal("WDL", "退会会員", emptyStrings())
;
private static final Map<String, MemberStatus> _codeClsMap = new HashMap<String, MemberStatus>();
private static final Map<String, MemberStatus> _nameClsMap = new HashMap<String, MemberStatus>();
static {
for (MemberStatus value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private MemberStatus(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.MemberStatus; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<MemberStatus> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof MemberStatus) { return OptionalThing.of((MemberStatus)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<MemberStatus> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static MemberStatus codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof MemberStatus) { return (MemberStatus)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static MemberStatus nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<MemberStatus> listAll() {
return new ArrayList<MemberStatus>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<MemberStatus> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: MemberStatus." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<MemberStatus> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<MemberStatus> clsList = new ArrayList<MemberStatus>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<MemberStatus> groupOf(String groupName) {
return new ArrayList<MemberStatus>(4);
}
@Override public String toString() { return code(); }
}
/**
* 商品ステータス: 商品の状態を示す
*/
public enum ProductStatus implements CDef {
/** 生産販売可能 */
OnSale("ONS", "生産販売可能", emptyStrings())
,
/** 生産中止 */
ProductStop("PST", "生産中止", emptyStrings())
,
/** 販売中止 */
SaleStop("SST", "販売中止", emptyStrings())
;
private static final Map<String, ProductStatus> _codeClsMap = new HashMap<String, ProductStatus>();
private static final Map<String, ProductStatus> _nameClsMap = new HashMap<String, ProductStatus>();
static {
for (ProductStatus value : values()) {
_codeClsMap.put(value.code().toLowerCase(), value);
for (String sister : value.sisterSet()) { _codeClsMap.put(sister.toLowerCase(), value); }
_nameClsMap.put(value.name().toLowerCase(), value);
}
}
private String _code; private String _alias; private Set<String> _sisterSet;
private ProductStatus(String code, String alias, String[] sisters)
{ _code = code; _alias = alias; _sisterSet = Collections.unmodifiableSet(new LinkedHashSet<String>(Arrays.asList(sisters))); }
public String code() { return _code; } public String alias() { return _alias; }
public Set<String> sisterSet() { return _sisterSet; }
public Map<String, Object> subItemMap() { return Collections.emptyMap(); }
public ClassificationMeta meta() { return CDef.DefMeta.ProductStatus; }
public boolean inGroup(String groupName) {
return false;
}
/**
* Get the classification of the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns empty)
* @return The optional classification corresponding to the code. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<ProductStatus> of(Object code) {
if (code == null) { return OptionalThing.ofNullable(null, () -> { throw new ClassificationNotFoundException("null code specified"); }); }
if (code instanceof ProductStatus) { return OptionalThing.of((ProductStatus)code); }
if (code instanceof OptionalThing<?>) { return of(((OptionalThing<?>)code).orElse(null)); }
return OptionalThing.ofNullable(_codeClsMap.get(code.toString().toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification code: " + code);
});
}
/**
* Find the classification by the name. (CaseInsensitive)
* @param name The string of name, which is case-insensitive. (NotNull)
* @return The optional classification corresponding to the name. (NotNull, EmptyAllowed: if not found, returns empty)
*/
public static OptionalThing<ProductStatus> byName(String name) {
if (name == null) { throw new IllegalArgumentException("The argument 'name' should not be null."); }
return OptionalThing.ofNullable(_nameClsMap.get(name.toLowerCase()), () ->{
throw new ClassificationNotFoundException("Unknown classification name: " + name);
});
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use of(code).</span> <br>
* Get the classification by the code. (CaseInsensitive)
* @param code The value of code, which is case-insensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the code. (NullAllowed: if not found, returns null)
*/
public static ProductStatus codeOf(Object code) {
if (code == null) { return null; }
if (code instanceof ProductStatus) { return (ProductStatus)code; }
return _codeClsMap.get(code.toString().toLowerCase());
}
/**
* <span style="color: #AD4747; font-size: 120%">Old style so use byName(name).</span> <br>
* Get the classification by the name (also called 'value' in ENUM world).
* @param name The string of name, which is case-sensitive. (NullAllowed: if null, returns null)
* @return The instance of the corresponding classification to the name. (NullAllowed: if not found, returns null)
*/
public static ProductStatus nameOf(String name) {
if (name == null) { return null; }
try { return valueOf(name); } catch (RuntimeException ignored) { return null; }
}
/**
* Get the list of all classification elements. (returns new copied list)
* @return The snapshot list of all classification elements. (NotNull)
*/
public static List<ProductStatus> listAll() {
return new ArrayList<ProductStatus>(Arrays.asList(values()));
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if not found, throws exception)
*/
public static List<ProductStatus> listByGroup(String groupName) {
if (groupName == null) { throw new IllegalArgumentException("The argument 'groupName' should not be null."); }
throw new ClassificationNotFoundException("Unknown classification group: ProductStatus." + groupName);
}
/**
* Get the list of classification elements corresponding to the specified codes. (returns new copied list) <br>
* @param codeList The list of plain code, which is case-insensitive. (NotNull)
* @return The snapshot list of classification elements in the code list. (NotNull, EmptyAllowed: when empty specified)
*/
public static List<ProductStatus> listOf(Collection<String> codeList) {
if (codeList == null) { throw new IllegalArgumentException("The argument 'codeList' should not be null."); }
List<ProductStatus> clsList = new ArrayList<ProductStatus>(codeList.size());
for (String code : codeList) { clsList.add(of(code).get()); }
return clsList;
}
/**
* Get the list of classification elements in the specified group. (returns new copied list) <br>
* @param groupName The string of group name, which is case-sensitive. (NullAllowed: if null, returns empty list)
* @return The snapshot list of classification elements in the group. (NotNull, EmptyAllowed: if the group is not found)
*/
public static List<ProductStatus> groupOf(String groupName) {
return new ArrayList<ProductStatus>(4);
}
@Override public String toString() { return code(); }
}
public enum DefMeta implements ClassificationMeta {
/** 会員が受けられるサービスのランクを示す */
ServiceRank
,
/** mainly region of member address */
Region
,
/** reason for member withdrawal */
WithdrawalReason
,
/** 支払方法 */
PaymentMethod
,
/** the test of reference variable in grouping map */
GroupingReference
,
/** The test of relation reference */
SelfReference
,
/** The test of top only */
TopCommentOnly
,
/** the test of sub-item map for implicit classification */
SubItemImplicit
,
/** the test of sub-item map for table classification */
SubItemTable
,
/** boolean classification for boolean column */
BooleanFlg
,
/** master type of variant relation (biz-many-to-one) */
VariantRelationMasterType
,
/** qux type of variant relation (biz-many-to-one) */
VariantRelationQuxType
,
/** merged */
QuxCls
,
/** delimiter; & endBrace} & path\foo\bar */
EscapedDfpropCls
,
/** /*IF pmb.yourTop*/><& */
EscapedJavaDocCls
,
/** 6 */
EscapedNumberInitialCls
,
/** top first line top second line top third line */
LineSepCommentCls
,
/** no camelizing classification */
NamingDefaultCamelizingType
,
/** no camelizing classification */
NamingNoCamelizingType
,
/** is deprecated classification */
DeprecatedTopBasicType
,
/** has deprecated element */
DeprecatedMapBasicType
,
/** has deprecated element */
DeprecatedMapCollaborationType
,
/** unique key as classification */
UQClassificationType
,
/** Classification of Bar */
BarCls
,
/** Classification of Foo */
FooCls
,
/** フラグを示す */
Flg
,
/** 会員ステータス: 会員の状態を示す */
MemberStatus
,
/** 商品ステータス: 商品の状態を示す */
ProductStatus
;
public String classificationName() {
return name(); // same as definition name
}
public OptionalThing<? extends Classification> of(Object code) {
if (ServiceRank.name().equals(name())) { return CDef.ServiceRank.of(code); }
if (Region.name().equals(name())) { return CDef.Region.of(code); }
if (WithdrawalReason.name().equals(name())) { return CDef.WithdrawalReason.of(code); }
if (PaymentMethod.name().equals(name())) { return CDef.PaymentMethod.of(code); }
if (GroupingReference.name().equals(name())) { return CDef.GroupingReference.of(code); }
if (SelfReference.name().equals(name())) { return CDef.SelfReference.of(code); }
if (TopCommentOnly.name().equals(name())) { return CDef.TopCommentOnly.of(code); }
if (SubItemImplicit.name().equals(name())) { return CDef.SubItemImplicit.of(code); }
if (SubItemTable.name().equals(name())) { return CDef.SubItemTable.of(code); }
if (BooleanFlg.name().equals(name())) { return CDef.BooleanFlg.of(code); }
if (VariantRelationMasterType.name().equals(name())) { return CDef.VariantRelationMasterType.of(code); }
if (VariantRelationQuxType.name().equals(name())) { return CDef.VariantRelationQuxType.of(code); }
if (QuxCls.name().equals(name())) { return CDef.QuxCls.of(code); }
if (EscapedDfpropCls.name().equals(name())) { return CDef.EscapedDfpropCls.of(code); }
if (EscapedJavaDocCls.name().equals(name())) { return CDef.EscapedJavaDocCls.of(code); }
if (EscapedNumberInitialCls.name().equals(name())) { return CDef.EscapedNumberInitialCls.of(code); }
if (LineSepCommentCls.name().equals(name())) { return CDef.LineSepCommentCls.of(code); }
if (NamingDefaultCamelizingType.name().equals(name())) { return CDef.NamingDefaultCamelizingType.of(code); }
if (NamingNoCamelizingType.name().equals(name())) { return CDef.NamingNoCamelizingType.of(code); }
if (DeprecatedTopBasicType.name().equals(name())) { return CDef.DeprecatedTopBasicType.of(code); }
if (DeprecatedMapBasicType.name().equals(name())) { return CDef.DeprecatedMapBasicType.of(code); }
if (DeprecatedMapCollaborationType.name().equals(name())) { return CDef.DeprecatedMapCollaborationType.of(code); }
if (UQClassificationType.name().equals(name())) { return CDef.UQClassificationType.of(code); }
if (BarCls.name().equals(name())) { return CDef.BarCls.of(code); }
if (FooCls.name().equals(name())) { return CDef.FooCls.of(code); }
if (Flg.name().equals(name())) { return CDef.Flg.of(code); }
if (MemberStatus.name().equals(name())) { return CDef.MemberStatus.of(code); }
if (ProductStatus.name().equals(name())) { return CDef.ProductStatus.of(code); }
throw new IllegalStateException("Unknown definition: " + this); // basically unreachable
}
public OptionalThing<? extends Classification> byName(String name) {
if (ServiceRank.name().equals(name())) { return CDef.ServiceRank.byName(name); }
if (Region.name().equals(name())) { return CDef.Region.byName(name); }
if (WithdrawalReason.name().equals(name())) { return CDef.WithdrawalReason.byName(name); }
if (PaymentMethod.name().equals(name())) { return CDef.PaymentMethod.byName(name); }
if (GroupingReference.name().equals(name())) { return CDef.GroupingReference.byName(name); }
if (SelfReference.name().equals(name())) { return CDef.SelfReference.byName(name); }
if (TopCommentOnly.name().equals(name())) { return CDef.TopCommentOnly.byName(name); }
if (SubItemImplicit.name().equals(name())) { return CDef.SubItemImplicit.byName(name); }
if (SubItemTable.name().equals(name())) { return CDef.SubItemTable.byName(name); }
if (BooleanFlg.name().equals(name())) { return CDef.BooleanFlg.byName(name); }
if (VariantRelationMasterType.name().equals(name())) { return CDef.VariantRelationMasterType.byName(name); }
if (VariantRelationQuxType.name().equals(name())) { return CDef.VariantRelationQuxType.byName(name); }
if (QuxCls.name().equals(name())) { return CDef.QuxCls.byName(name); }
if (EscapedDfpropCls.name().equals(name())) { return CDef.EscapedDfpropCls.byName(name); }
if (EscapedJavaDocCls.name().equals(name())) { return CDef.EscapedJavaDocCls.byName(name); }
if (EscapedNumberInitialCls.name().equals(name())) { return CDef.EscapedNumberInitialCls.byName(name); }
if (LineSepCommentCls.name().equals(name())) { return CDef.LineSepCommentCls.byName(name); }
if (NamingDefaultCamelizingType.name().equals(name())) { return CDef.NamingDefaultCamelizingType.byName(name); }
if (NamingNoCamelizingType.name().equals(name())) { return CDef.NamingNoCamelizingType.byName(name); }
if (DeprecatedTopBasicType.name().equals(name())) { return CDef.DeprecatedTopBasicType.byName(name); }
if (DeprecatedMapBasicType.name().equals(name())) { return CDef.DeprecatedMapBasicType.byName(name); }
if (DeprecatedMapCollaborationType.name().equals(name())) { return CDef.DeprecatedMapCollaborationType.byName(name); }
if (UQClassificationType.name().equals(name())) { return CDef.UQClassificationType.byName(name); }
if (BarCls.name().equals(name())) { return CDef.BarCls.byName(name); }
if (FooCls.name().equals(name())) { return CDef.FooCls.byName(name); }
if (Flg.name().equals(name())) { return CDef.Flg.byName(name); }
if (MemberStatus.name().equals(name())) { return CDef.MemberStatus.byName(name); }
if (ProductStatus.name().equals(name())) { return CDef.ProductStatus.byName(name); }
throw new IllegalStateException("Unknown definition: " + this); // basically unreachable
}
public Classification codeOf(Object code) { // null if not found, old style so use of(code)
if (ServiceRank.name().equals(name())) { return CDef.ServiceRank.codeOf(code); }
if (Region.name().equals(name())) { return CDef.Region.codeOf(code); }
if (WithdrawalReason.name().equals(name())) { return CDef.WithdrawalReason.codeOf(code); }
if (PaymentMethod.name().equals(name())) { return CDef.PaymentMethod.codeOf(code); }
if (GroupingReference.name().equals(name())) { return CDef.GroupingReference.codeOf(code); }
if (SelfReference.name().equals(name())) { return CDef.SelfReference.codeOf(code); }
if (TopCommentOnly.name().equals(name())) { return CDef.TopCommentOnly.codeOf(code); }
if (SubItemImplicit.name().equals(name())) { return CDef.SubItemImplicit.codeOf(code); }
if (SubItemTable.name().equals(name())) { return CDef.SubItemTable.codeOf(code); }
if (BooleanFlg.name().equals(name())) { return CDef.BooleanFlg.codeOf(code); }
if (VariantRelationMasterType.name().equals(name())) { return CDef.VariantRelationMasterType.codeOf(code); }
if (VariantRelationQuxType.name().equals(name())) { return CDef.VariantRelationQuxType.codeOf(code); }
if (QuxCls.name().equals(name())) { return CDef.QuxCls.codeOf(code); }
if (EscapedDfpropCls.name().equals(name())) { return CDef.EscapedDfpropCls.codeOf(code); }
if (EscapedJavaDocCls.name().equals(name())) { return CDef.EscapedJavaDocCls.codeOf(code); }
if (EscapedNumberInitialCls.name().equals(name())) { return CDef.EscapedNumberInitialCls.codeOf(code); }
if (LineSepCommentCls.name().equals(name())) { return CDef.LineSepCommentCls.codeOf(code); }
if (NamingDefaultCamelizingType.name().equals(name())) { return CDef.NamingDefaultCamelizingType.codeOf(code); }
if (NamingNoCamelizingType.name().equals(name())) { return CDef.NamingNoCamelizingType.codeOf(code); }
if (DeprecatedTopBasicType.name().equals(name())) { return CDef.DeprecatedTopBasicType.codeOf(code); }
if (DeprecatedMapBasicType.name().equals(name())) { return CDef.DeprecatedMapBasicType.codeOf(code); }
if (DeprecatedMapCollaborationType.name().equals(name())) { return CDef.DeprecatedMapCollaborationType.codeOf(code); }
if (UQClassificationType.name().equals(name())) { return CDef.UQClassificationType.codeOf(code); }
if (BarCls.name().equals(name())) { return CDef.BarCls.codeOf(code); }
if (FooCls.name().equals(name())) { return CDef.FooCls.codeOf(code); }
if (Flg.name().equals(name())) { return CDef.Flg.codeOf(code); }
if (MemberStatus.name().equals(name())) { return CDef.MemberStatus.codeOf(code); }
if (ProductStatus.name().equals(name())) { return CDef.ProductStatus.codeOf(code); }
throw new IllegalStateException("Unknown definition: " + this); // basically unreachable
}
public Classification nameOf(String name) { // null if not found, old style so use byName(name)
if (ServiceRank.name().equals(name())) { return CDef.ServiceRank.valueOf(name); }
if (Region.name().equals(name())) { return CDef.Region.valueOf(name); }
if (WithdrawalReason.name().equals(name())) { return CDef.WithdrawalReason.valueOf(name); }
if (PaymentMethod.name().equals(name())) { return CDef.PaymentMethod.valueOf(name); }
if (GroupingReference.name().equals(name())) { return CDef.GroupingReference.valueOf(name); }
if (SelfReference.name().equals(name())) { return CDef.SelfReference.valueOf(name); }
if (TopCommentOnly.name().equals(name())) { return CDef.TopCommentOnly.valueOf(name); }
if (SubItemImplicit.name().equals(name())) { return CDef.SubItemImplicit.valueOf(name); }
if (SubItemTable.name().equals(name())) { return CDef.SubItemTable.valueOf(name); }
if (BooleanFlg.name().equals(name())) { return CDef.BooleanFlg.valueOf(name); }
if (VariantRelationMasterType.name().equals(name())) { return CDef.VariantRelationMasterType.valueOf(name); }
if (VariantRelationQuxType.name().equals(name())) { return CDef.VariantRelationQuxType.valueOf(name); }
if (QuxCls.name().equals(name())) { return CDef.QuxCls.valueOf(name); }
if (EscapedDfpropCls.name().equals(name())) { return CDef.EscapedDfpropCls.valueOf(name); }
if (EscapedJavaDocCls.name().equals(name())) { return CDef.EscapedJavaDocCls.valueOf(name); }
if (EscapedNumberInitialCls.name().equals(name())) { return CDef.EscapedNumberInitialCls.valueOf(name); }
if (LineSepCommentCls.name().equals(name())) { return CDef.LineSepCommentCls.valueOf(name); }
if (NamingDefaultCamelizingType.name().equals(name())) { return CDef.NamingDefaultCamelizingType.valueOf(name); }
if (NamingNoCamelizingType.name().equals(name())) { return CDef.NamingNoCamelizingType.valueOf(name); }
if (DeprecatedTopBasicType.name().equals(name())) { return CDef.DeprecatedTopBasicType.valueOf(name); }
if (DeprecatedMapBasicType.name().equals(name())) { return CDef.DeprecatedMapBasicType.valueOf(name); }
if (DeprecatedMapCollaborationType.name().equals(name())) { return CDef.DeprecatedMapCollaborationType.valueOf(name); }
if (UQClassificationType.name().equals(name())) { return CDef.UQClassificationType.valueOf(name); }
if (BarCls.name().equals(name())) { return CDef.BarCls.valueOf(name); }
if (FooCls.name().equals(name())) { return CDef.FooCls.valueOf(name); }
if (Flg.name().equals(name())) { return CDef.Flg.valueOf(name); }
if (MemberStatus.name().equals(name())) { return CDef.MemberStatus.valueOf(name); }
if (ProductStatus.name().equals(name())) { return CDef.ProductStatus.valueOf(name); }
throw new IllegalStateException("Unknown definition: " + this); // basically unreachable
}
public List<Classification> listAll() {
if (ServiceRank.name().equals(name())) { return toClsList(CDef.ServiceRank.listAll()); }
if (Region.name().equals(name())) { return toClsList(CDef.Region.listAll()); }
if (WithdrawalReason.name().equals(name())) { return toClsList(CDef.WithdrawalReason.listAll()); }
if (PaymentMethod.name().equals(name())) { return toClsList(CDef.PaymentMethod.listAll()); }
if (GroupingReference.name().equals(name())) { return toClsList(CDef.GroupingReference.listAll()); }
if (SelfReference.name().equals(name())) { return toClsList(CDef.SelfReference.listAll()); }
if (TopCommentOnly.name().equals(name())) { return toClsList(CDef.TopCommentOnly.listAll()); }
if (SubItemImplicit.name().equals(name())) { return toClsList(CDef.SubItemImplicit.listAll()); }
if (SubItemTable.name().equals(name())) { return toClsList(CDef.SubItemTable.listAll()); }
if (BooleanFlg.name().equals(name())) { return toClsList(CDef.BooleanFlg.listAll()); }
if (VariantRelationMasterType.name().equals(name())) { return toClsList(CDef.VariantRelationMasterType.listAll()); }
if (VariantRelationQuxType.name().equals(name())) { return toClsList(CDef.VariantRelationQuxType.listAll()); }
if (QuxCls.name().equals(name())) { return toClsList(CDef.QuxCls.listAll()); }
if (EscapedDfpropCls.name().equals(name())) { return toClsList(CDef.EscapedDfpropCls.listAll()); }
if (EscapedJavaDocCls.name().equals(name())) { return toClsList(CDef.EscapedJavaDocCls.listAll()); }
if (EscapedNumberInitialCls.name().equals(name())) { return toClsList(CDef.EscapedNumberInitialCls.listAll()); }
if (LineSepCommentCls.name().equals(name())) { return toClsList(CDef.LineSepCommentCls.listAll()); }
if (NamingDefaultCamelizingType.name().equals(name())) { return toClsList(CDef.NamingDefaultCamelizingType.listAll()); }
if (NamingNoCamelizingType.name().equals(name())) { return toClsList(CDef.NamingNoCamelizingType.listAll()); }
if (DeprecatedTopBasicType.name().equals(name())) { return toClsList(CDef.DeprecatedTopBasicType.listAll()); }
if (DeprecatedMapBasicType.name().equals(name())) { return toClsList(CDef.DeprecatedMapBasicType.listAll()); }
if (DeprecatedMapCollaborationType.name().equals(name())) { return toClsList(CDef.DeprecatedMapCollaborationType.listAll()); }
if (UQClassificationType.name().equals(name())) { return toClsList(CDef.UQClassificationType.listAll()); }
if (BarCls.name().equals(name())) { return toClsList(CDef.BarCls.listAll()); }
if (FooCls.name().equals(name())) { return toClsList(CDef.FooCls.listAll()); }
if (Flg.name().equals(name())) { return toClsList(CDef.Flg.listAll()); }
if (MemberStatus.name().equals(name())) { return toClsList(CDef.MemberStatus.listAll()); }
if (ProductStatus.name().equals(name())) { return toClsList(CDef.ProductStatus.listAll()); }
throw new IllegalStateException("Unknown definition: " + this); // basically unreachable
}
public List<Classification> listByGroup(String groupName) { // exception if not found
if (ServiceRank.name().equals(name())) { return toClsList(CDef.ServiceRank.listByGroup(groupName)); }
if (Region.name().equals(name())) { return toClsList(CDef.Region.listByGroup(groupName)); }
if (WithdrawalReason.name().equals(name())) { return toClsList(CDef.WithdrawalReason.listByGroup(groupName)); }
if (PaymentMethod.name().equals(name())) { return toClsList(CDef.PaymentMethod.listByGroup(groupName)); }
if (GroupingReference.name().equals(name())) { return toClsList(CDef.GroupingReference.listByGroup(groupName)); }
if (SelfReference.name().equals(name())) { return toClsList(CDef.SelfReference.listByGroup(groupName)); }
if (TopCommentOnly.name().equals(name())) { return toClsList(CDef.TopCommentOnly.listByGroup(groupName)); }
if (SubItemImplicit.name().equals(name())) { return toClsList(CDef.SubItemImplicit.listByGroup(groupName)); }
if (SubItemTable.name().equals(name())) { return toClsList(CDef.SubItemTable.listByGroup(groupName)); }
if (BooleanFlg.name().equals(name())) { return toClsList(CDef.BooleanFlg.listByGroup(groupName)); }
if (VariantRelationMasterType.name().equals(name())) { return toClsList(CDef.VariantRelationMasterType.listByGroup(groupName)); }
if (VariantRelationQuxType.name().equals(name())) { return toClsList(CDef.VariantRelationQuxType.listByGroup(groupName)); }
if (QuxCls.name().equals(name())) { return toClsList(CDef.QuxCls.listByGroup(groupName)); }
if (EscapedDfpropCls.name().equals(name())) { return toClsList(CDef.EscapedDfpropCls.listByGroup(groupName)); }
if (EscapedJavaDocCls.name().equals(name())) { return toClsList(CDef.EscapedJavaDocCls.listByGroup(groupName)); }
if (EscapedNumberInitialCls.name().equals(name())) { return toClsList(CDef.EscapedNumberInitialCls.listByGroup(groupName)); }
if (LineSepCommentCls.name().equals(name())) { return toClsList(CDef.LineSepCommentCls.listByGroup(groupName)); }
if (NamingDefaultCamelizingType.name().equals(name())) { return toClsList(CDef.NamingDefaultCamelizingType.listByGroup(groupName)); }
if (NamingNoCamelizingType.name().equals(name())) { return toClsList(CDef.NamingNoCamelizingType.listByGroup(groupName)); }
if (DeprecatedTopBasicType.name().equals(name())) { return toClsList(CDef.DeprecatedTopBasicType.listByGroup(groupName)); }
if (DeprecatedMapBasicType.name().equals(name())) { return toClsList(CDef.DeprecatedMapBasicType.listByGroup(groupName)); }
if (DeprecatedMapCollaborationType.name().equals(name())) { return toClsList(CDef.DeprecatedMapCollaborationType.listByGroup(groupName)); }
if (UQClassificationType.name().equals(name())) { return toClsList(CDef.UQClassificationType.listByGroup(groupName)); }
if (BarCls.name().equals(name())) { return toClsList(CDef.BarCls.listByGroup(groupName)); }
if (FooCls.name().equals(name())) { return toClsList(CDef.FooCls.listByGroup(groupName)); }
if (Flg.name().equals(name())) { return toClsList(CDef.Flg.listByGroup(groupName)); }
if (MemberStatus.name().equals(name())) { return toClsList(CDef.MemberStatus.listByGroup(groupName)); }
if (ProductStatus.name().equals(name())) { return toClsList(CDef.ProductStatus.listByGroup(groupName)); }
throw new IllegalStateException("Unknown definition: " + this); // basically unreachable
}
public List<Classification> listOf(Collection<String> codeList) {
if (ServiceRank.name().equals(name())) { return toClsList(CDef.ServiceRank.listOf(codeList)); }
if (Region.name().equals(name())) { return toClsList(CDef.Region.listOf(codeList)); }
if (WithdrawalReason.name().equals(name())) { return toClsList(CDef.WithdrawalReason.listOf(codeList)); }
if (PaymentMethod.name().equals(name())) { return toClsList(CDef.PaymentMethod.listOf(codeList)); }
if (GroupingReference.name().equals(name())) { return toClsList(CDef.GroupingReference.listOf(codeList)); }
if (SelfReference.name().equals(name())) { return toClsList(CDef.SelfReference.listOf(codeList)); }
if (TopCommentOnly.name().equals(name())) { return toClsList(CDef.TopCommentOnly.listOf(codeList)); }
if (SubItemImplicit.name().equals(name())) { return toClsList(CDef.SubItemImplicit.listOf(codeList)); }
if (SubItemTable.name().equals(name())) { return toClsList(CDef.SubItemTable.listOf(codeList)); }
if (BooleanFlg.name().equals(name())) { return toClsList(CDef.BooleanFlg.listOf(codeList)); }
if (VariantRelationMasterType.name().equals(name())) { return toClsList(CDef.VariantRelationMasterType.listOf(codeList)); }
if (VariantRelationQuxType.name().equals(name())) { return toClsList(CDef.VariantRelationQuxType.listOf(codeList)); }
if (QuxCls.name().equals(name())) { return toClsList(CDef.QuxCls.listOf(codeList)); }
if (EscapedDfpropCls.name().equals(name())) { return toClsList(CDef.EscapedDfpropCls.listOf(codeList)); }
if (EscapedJavaDocCls.name().equals(name())) { return toClsList(CDef.EscapedJavaDocCls.listOf(codeList)); }
if (EscapedNumberInitialCls.name().equals(name())) { return toClsList(CDef.EscapedNumberInitialCls.listOf(codeList)); }
if (LineSepCommentCls.name().equals(name())) { return toClsList(CDef.LineSepCommentCls.listOf(codeList)); }
if (NamingDefaultCamelizingType.name().equals(name())) { return toClsList(CDef.NamingDefaultCamelizingType.listOf(codeList)); }
if (NamingNoCamelizingType.name().equals(name())) { return toClsList(CDef.NamingNoCamelizingType.listOf(codeList)); }
if (DeprecatedTopBasicType.name().equals(name())) { return toClsList(CDef.DeprecatedTopBasicType.listOf(codeList)); }
if (DeprecatedMapBasicType.name().equals(name())) { return toClsList(CDef.DeprecatedMapBasicType.listOf(codeList)); }
if (DeprecatedMapCollaborationType.name().equals(name())) { return toClsList(CDef.DeprecatedMapCollaborationType.listOf(codeList)); }
if (UQClassificationType.name().equals(name())) { return toClsList(CDef.UQClassificationType.listOf(codeList)); }
if (BarCls.name().equals(name())) { return toClsList(CDef.BarCls.listOf(codeList)); }
if (FooCls.name().equals(name())) { return toClsList(CDef.FooCls.listOf(codeList)); }
if (Flg.name().equals(name())) { return toClsList(CDef.Flg.listOf(codeList)); }
if (MemberStatus.name().equals(name())) { return toClsList(CDef.MemberStatus.listOf(codeList)); }
if (ProductStatus.name().equals(name())) { return toClsList(CDef.ProductStatus.listOf(codeList)); }
throw new IllegalStateException("Unknown definition: " + this); // basically unreachable
}
public List<Classification> groupOf(String groupName) { // old style
if (ServiceRank.name().equals(name())) { return toClsList(CDef.ServiceRank.groupOf(groupName)); }
if (Region.name().equals(name())) { return toClsList(CDef.Region.groupOf(groupName)); }
if (WithdrawalReason.name().equals(name())) { return toClsList(CDef.WithdrawalReason.groupOf(groupName)); }
if (PaymentMethod.name().equals(name())) { return toClsList(CDef.PaymentMethod.groupOf(groupName)); }
if (GroupingReference.name().equals(name())) { return toClsList(CDef.GroupingReference.groupOf(groupName)); }
if (SelfReference.name().equals(name())) { return toClsList(CDef.SelfReference.groupOf(groupName)); }
if (TopCommentOnly.name().equals(name())) { return toClsList(CDef.TopCommentOnly.groupOf(groupName)); }
if (SubItemImplicit.name().equals(name())) { return toClsList(CDef.SubItemImplicit.groupOf(groupName)); }
if (SubItemTable.name().equals(name())) { return toClsList(CDef.SubItemTable.groupOf(groupName)); }
if (BooleanFlg.name().equals(name())) { return toClsList(CDef.BooleanFlg.groupOf(groupName)); }
if (VariantRelationMasterType.name().equals(name())) { return toClsList(CDef.VariantRelationMasterType.groupOf(groupName)); }
if (VariantRelationQuxType.name().equals(name())) { return toClsList(CDef.VariantRelationQuxType.groupOf(groupName)); }
if (QuxCls.name().equals(name())) { return toClsList(CDef.QuxCls.groupOf(groupName)); }
if (EscapedDfpropCls.name().equals(name())) { return toClsList(CDef.EscapedDfpropCls.groupOf(groupName)); }
if (EscapedJavaDocCls.name().equals(name())) { return toClsList(CDef.EscapedJavaDocCls.groupOf(groupName)); }
if (EscapedNumberInitialCls.name().equals(name())) { return toClsList(CDef.EscapedNumberInitialCls.groupOf(groupName)); }
if (LineSepCommentCls.name().equals(name())) { return toClsList(CDef.LineSepCommentCls.groupOf(groupName)); }
if (NamingDefaultCamelizingType.name().equals(name())) { return toClsList(CDef.NamingDefaultCamelizingType.groupOf(groupName)); }
if (NamingNoCamelizingType.name().equals(name())) { return toClsList(CDef.NamingNoCamelizingType.groupOf(groupName)); }
if (DeprecatedTopBasicType.name().equals(name())) { return toClsList(CDef.DeprecatedTopBasicType.groupOf(groupName)); }
if (DeprecatedMapBasicType.name().equals(name())) { return toClsList(CDef.DeprecatedMapBasicType.groupOf(groupName)); }
if (DeprecatedMapCollaborationType.name().equals(name())) { return toClsList(CDef.DeprecatedMapCollaborationType.groupOf(groupName)); }
if (UQClassificationType.name().equals(name())) { return toClsList(CDef.UQClassificationType.groupOf(groupName)); }
if (BarCls.name().equals(name())) { return toClsList(CDef.BarCls.groupOf(groupName)); }
if (FooCls.name().equals(name())) { return toClsList(CDef.FooCls.groupOf(groupName)); }
if (Flg.name().equals(name())) { return toClsList(CDef.Flg.groupOf(groupName)); }
if (MemberStatus.name().equals(name())) { return toClsList(CDef.MemberStatus.groupOf(groupName)); }
if (ProductStatus.name().equals(name())) { return toClsList(CDef.ProductStatus.groupOf(groupName)); }
throw new IllegalStateException("Unknown definition: " + this); // basically unreachable
}
@SuppressWarnings("unchecked")
private List<Classification> toClsList(List<?> clsList) {
return (List<Classification>)clsList;
}
public ClassificationCodeType codeType() {
if (ServiceRank.name().equals(name())) { return ClassificationCodeType.String; }
if (Region.name().equals(name())) { return ClassificationCodeType.Number; }
if (WithdrawalReason.name().equals(name())) { return ClassificationCodeType.String; }
if (PaymentMethod.name().equals(name())) { return ClassificationCodeType.String; }
if (GroupingReference.name().equals(name())) { return ClassificationCodeType.String; }
if (SelfReference.name().equals(name())) { return ClassificationCodeType.Number; }
if (TopCommentOnly.name().equals(name())) { return ClassificationCodeType.String; }
if (SubItemImplicit.name().equals(name())) { return ClassificationCodeType.Number; }
if (SubItemTable.name().equals(name())) { return ClassificationCodeType.String; }
if (BooleanFlg.name().equals(name())) { return ClassificationCodeType.Boolean; }
if (VariantRelationMasterType.name().equals(name())) { return ClassificationCodeType.String; }
if (VariantRelationQuxType.name().equals(name())) { return ClassificationCodeType.String; }
if (QuxCls.name().equals(name())) { return ClassificationCodeType.String; }
if (EscapedDfpropCls.name().equals(name())) { return ClassificationCodeType.String; }
if (EscapedJavaDocCls.name().equals(name())) { return ClassificationCodeType.String; }
if (EscapedNumberInitialCls.name().equals(name())) { return ClassificationCodeType.String; }
if (LineSepCommentCls.name().equals(name())) { return ClassificationCodeType.String; }
if (NamingDefaultCamelizingType.name().equals(name())) { return ClassificationCodeType.String; }
if (NamingNoCamelizingType.name().equals(name())) { return ClassificationCodeType.String; }
if (DeprecatedTopBasicType.name().equals(name())) { return ClassificationCodeType.String; }
if (DeprecatedMapBasicType.name().equals(name())) { return ClassificationCodeType.String; }
if (DeprecatedMapCollaborationType.name().equals(name())) { return ClassificationCodeType.String; }
if (UQClassificationType.name().equals(name())) { return ClassificationCodeType.String; }
if (BarCls.name().equals(name())) { return ClassificationCodeType.String; }
if (FooCls.name().equals(name())) { return ClassificationCodeType.String; }
if (Flg.name().equals(name())) { return ClassificationCodeType.Number; }
if (MemberStatus.name().equals(name())) { return ClassificationCodeType.String; }
if (ProductStatus.name().equals(name())) { return ClassificationCodeType.String; }
return ClassificationCodeType.String; // as default
}
public ClassificationUndefinedHandlingType undefinedHandlingType() {
if (ServiceRank.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (Region.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (WithdrawalReason.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (PaymentMethod.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (GroupingReference.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (SelfReference.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (TopCommentOnly.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (SubItemImplicit.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (SubItemTable.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (BooleanFlg.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (VariantRelationMasterType.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (VariantRelationQuxType.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (QuxCls.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (EscapedDfpropCls.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (EscapedJavaDocCls.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (EscapedNumberInitialCls.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (LineSepCommentCls.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (NamingDefaultCamelizingType.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (NamingNoCamelizingType.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (DeprecatedTopBasicType.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (DeprecatedMapBasicType.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (DeprecatedMapCollaborationType.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (UQClassificationType.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (BarCls.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (FooCls.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (Flg.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (MemberStatus.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
if (ProductStatus.name().equals(name())) { return ClassificationUndefinedHandlingType.EXCEPTION; }
return ClassificationUndefinedHandlingType.LOGGING; // as default
}
public static OptionalThing<CDef.DefMeta> find(String classificationName) { // instead of valueOf()
if (classificationName == null) { throw new IllegalArgumentException("The argument 'classificationName' should not be null."); }
if (ServiceRank.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.ServiceRank); }
if (Region.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.Region); }
if (WithdrawalReason.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.WithdrawalReason); }
if (PaymentMethod.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.PaymentMethod); }
if (GroupingReference.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.GroupingReference); }
if (SelfReference.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.SelfReference); }
if (TopCommentOnly.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.TopCommentOnly); }
if (SubItemImplicit.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.SubItemImplicit); }
if (SubItemTable.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.SubItemTable); }
if (BooleanFlg.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.BooleanFlg); }
if (VariantRelationMasterType.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.VariantRelationMasterType); }
if (VariantRelationQuxType.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.VariantRelationQuxType); }
if (QuxCls.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.QuxCls); }
if (EscapedDfpropCls.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.EscapedDfpropCls); }
if (EscapedJavaDocCls.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.EscapedJavaDocCls); }
if (EscapedNumberInitialCls.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.EscapedNumberInitialCls); }
if (LineSepCommentCls.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.LineSepCommentCls); }
if (NamingDefaultCamelizingType.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.NamingDefaultCamelizingType); }
if (NamingNoCamelizingType.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.NamingNoCamelizingType); }
if (DeprecatedTopBasicType.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.DeprecatedTopBasicType); }
if (DeprecatedMapBasicType.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.DeprecatedMapBasicType); }
if (DeprecatedMapCollaborationType.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.DeprecatedMapCollaborationType); }
if (UQClassificationType.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.UQClassificationType); }
if (BarCls.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.BarCls); }
if (FooCls.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.FooCls); }
if (Flg.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.Flg); }
if (MemberStatus.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.MemberStatus); }
if (ProductStatus.name().equalsIgnoreCase(classificationName)) { return OptionalThing.of(CDef.DefMeta.ProductStatus); }
return OptionalThing.ofNullable(null, () -> {
throw new ClassificationNotFoundException("Unknown classification: " + classificationName);
});
}
public static CDef.DefMeta meta(String classificationName) { // old style so use find(name)
if (classificationName == null) { throw new IllegalArgumentException("The argument 'classificationName' should not be null."); }
if (ServiceRank.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.ServiceRank; }
if (Region.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.Region; }
if (WithdrawalReason.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.WithdrawalReason; }
if (PaymentMethod.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.PaymentMethod; }
if (GroupingReference.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.GroupingReference; }
if (SelfReference.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.SelfReference; }
if (TopCommentOnly.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.TopCommentOnly; }
if (SubItemImplicit.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.SubItemImplicit; }
if (SubItemTable.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.SubItemTable; }
if (BooleanFlg.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.BooleanFlg; }
if (VariantRelationMasterType.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.VariantRelationMasterType; }
if (VariantRelationQuxType.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.VariantRelationQuxType; }
if (QuxCls.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.QuxCls; }
if (EscapedDfpropCls.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.EscapedDfpropCls; }
if (EscapedJavaDocCls.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.EscapedJavaDocCls; }
if (EscapedNumberInitialCls.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.EscapedNumberInitialCls; }
if (LineSepCommentCls.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.LineSepCommentCls; }
if (NamingDefaultCamelizingType.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.NamingDefaultCamelizingType; }
if (NamingNoCamelizingType.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.NamingNoCamelizingType; }
if (DeprecatedTopBasicType.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.DeprecatedTopBasicType; }
if (DeprecatedMapBasicType.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.DeprecatedMapBasicType; }
if (DeprecatedMapCollaborationType.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.DeprecatedMapCollaborationType; }
if (UQClassificationType.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.UQClassificationType; }
if (BarCls.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.BarCls; }
if (FooCls.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.FooCls; }
if (Flg.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.Flg; }
if (MemberStatus.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.MemberStatus; }
if (ProductStatus.name().equalsIgnoreCase(classificationName)) { return CDef.DefMeta.ProductStatus; }
throw new IllegalStateException("Unknown classification: " + classificationName);
}
@SuppressWarnings("unused")
private String[] xinternalEmptyString() {
return emptyStrings(); // to suppress 'unused' warning of import statement
}
}
}
| apache-2.0 |
Ardesco/selenium | java/server/src/org/openqa/selenium/grid/server/BaseServerFlags.java | 3196 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium.grid.server;
import com.beust.jcommander.Parameter;
import com.google.auto.service.AutoService;
import org.openqa.selenium.grid.config.ConfigValue;
import org.openqa.selenium.grid.config.HasRoles;
import org.openqa.selenium.grid.config.Role;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Set;
import static org.openqa.selenium.grid.config.StandardGridRoles.HTTPD_ROLE;
@AutoService(HasRoles.class)
public class BaseServerFlags implements HasRoles {
@Parameter(
names = {"--host"},
description = "IP or hostname : usually determined automatically.")
@ConfigValue(section = "server", name = "hostname", example = "\"localhost\"")
private String host;
@Parameter(description = "Port to listen on.", names = {"-p", "--port"})
@ConfigValue(section = "server", name = "port", example = "4444")
private int port;
@Parameter(description = "Maximum number of listener threads.", names = "--max-threads")
@ConfigValue(section = "server", name = "max-threads", example = "12")
private int maxThreads = Runtime.getRuntime().availableProcessors() * 3;
@Parameter(names = "--allow-cors",
description = "Whether the Selenium server should allow web browser connections from any host",
arity = 1)
@ConfigValue(section = "server", name = "allow-cors", example = "true")
private Boolean allowCORS;
@Parameter(description = "Private key for https", names = "--https-private-key")
@ConfigValue(section = "server", name = "https-private-key", example = "\"/path/to/key.pkcs8\"")
private Path httpsPrivateKey;
@Parameter(description = "Server certificate for https", names = "--https-certificate")
@ConfigValue(section = "server", name = "https-certificate", example = "\"/path/to/cert.pem\"")
private Path httpsCertificate;
@Parameter(description = "Node registration secret", names = "--registration-secret")
@ConfigValue(section = "server", name = "registration-secret", example = "\"Hunter2\"")
private String registrationSecret;
@Parameter(description = "Use a self-signed certificate for HTTPS communication", names = "--self-signed-https", hidden = true)
@ConfigValue(section = "server", name = "https-self-signed", example = "false")
private Boolean isSelfSigned = false;
@Override
public Set<Role> getRoles() {
return Collections.singleton(HTTPD_ROLE);
}
}
| apache-2.0 |
raydac/netbeans-mmd-plugin | mind-map/mind-map-swing-panel/src/main/java/com/igormaznitsa/mindmap/plugins/processors/ExtraJumpPlugin.java | 2189 | /*
* Copyright 2015-2018 Igor Maznitsa.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.igormaznitsa.mindmap.plugins.processors;
import com.igormaznitsa.mindmap.model.Extra;
import com.igormaznitsa.mindmap.model.Topic;
import com.igormaznitsa.mindmap.plugins.PopUpSection;
import com.igormaznitsa.mindmap.plugins.api.AbstractFocusedTopicPlugin;
import com.igormaznitsa.mindmap.plugins.api.ExternallyExecutedPlugin;
import com.igormaznitsa.mindmap.plugins.api.PluginContext;
import com.igormaznitsa.mindmap.swing.panel.Texts;
import com.igormaznitsa.mindmap.swing.services.IconID;
import com.igormaznitsa.mindmap.swing.services.ImageIconServiceProvider;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.swing.Icon;
public class ExtraJumpPlugin extends AbstractFocusedTopicPlugin implements ExternallyExecutedPlugin {
private static final Icon ICO = ImageIconServiceProvider.findInstance().getIconForId(IconID.POPUP_EXTRAS_JUMP);
@Override
public int getOrder() {
return 4;
}
@Override
@Nullable
protected Icon getIcon(@Nonnull final PluginContext contextl, @Nullable final Topic activeTopic) {
return ICO;
}
@Override
@Nonnull
protected String getName(@Nonnull final PluginContext context, @Nullable final Topic activeTopic) {
if (activeTopic == null) {
return "...";
}
return activeTopic.getExtras().containsKey(Extra.ExtraType.TOPIC) ? Texts.getString("MMDGraphEditor.makePopUp.miEditTransition") :
Texts.getString("MMDGraphEditor.makePopUp.miAddTransition");
}
@Override
@Nonnull
public PopUpSection getSection() {
return PopUpSection.EXTRAS;
}
}
| apache-2.0 |
kahboom/apiman | gateway/platforms/servlet/src/test/java/io/apiman/gateway/platforms/servlet/auth/tls/CipherAndProtocolSelectionTest.java | 16375 | /*
* Copyright 2015 JBoss Inc
*
* 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 io.apiman.gateway.platforms.servlet.auth.tls;
import io.apiman.common.config.options.TLSOptions;
import io.apiman.gateway.engine.IApiConnection;
import io.apiman.gateway.engine.IApiConnectionResponse;
import io.apiman.gateway.engine.IApiConnector;
import io.apiman.gateway.engine.async.IAsyncResult;
import io.apiman.gateway.engine.async.IAsyncResultHandler;
import io.apiman.gateway.engine.auth.RequiredAuthType;
import io.apiman.gateway.engine.beans.Api;
import io.apiman.gateway.engine.beans.ApiRequest;
import io.apiman.gateway.engine.beans.exceptions.ConnectorException;
import io.apiman.gateway.platforms.servlet.connectors.HttpConnectorFactory;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
* Tests various standard TLS scenarios, in which the client is *not* authenticated. Some of these include
* authentication of the server certificate, whilst others are all trusting (devmode).
*
* @author Marc Savy <msavy@redhat.com>
*/
@SuppressWarnings("nls")
public class CipherAndProtocolSelectionTest {
private Server server;
private HttpConfiguration http_config;
private Map<String, String> config = new HashMap<>();
private Map<String, String> jettyRequestAttributes;
@Rule
public ExpectedException exception = ExpectedException.none();
private SslContextFactory jettySslContextFactory;
@Before
public void setupJetty() throws Exception {
server = new Server();
server.setStopAtShutdown(true);
http_config = new HttpConfiguration();
http_config.setSecureScheme("https");
jettySslContextFactory = new SslContextFactory();
jettySslContextFactory.setTrustStorePath(getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
jettySslContextFactory.setTrustStorePassword("password");
jettySslContextFactory.setKeyStorePath(getResourcePath("2waytest/mutual_trust_via_ca/service_ks.jks"));
jettySslContextFactory.setKeyStorePassword("password");
jettySslContextFactory.setKeyManagerPassword("password");
// Use default trust store
// No client auth
jettySslContextFactory.setNeedClientAuth(false);
jettySslContextFactory.setWantClientAuth(false);
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer());
ServerConnector sslConnector = new ServerConnector(server,
new SslConnectionFactory(jettySslContextFactory,"http/1.1"),
new HttpConnectionFactory(https_config));
sslConnector.setPort(8008);
server.addConnector(sslConnector);
// Thanks to Jetty getting started guide.
server.setHandler(new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
jettyRequestAttributes = new HashMap<>();
Enumeration<String> requestAttrNames = request.getAttributeNames();
while (requestAttrNames.hasMoreElements()) {
String elem = requestAttrNames.nextElement();
jettyRequestAttributes.put(elem, request.getAttribute(elem).toString());
System.out.println(elem + " - " + request.getAttribute(elem).toString());
}
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println("apiman");
}
});
}
@After
public void destroyJetty() throws Exception {
server.stop();
server.destroy();
config.clear();
}
ApiRequest request = new ApiRequest();
Api api = new Api();
{
request.setApiKey("12345");
request.setDestination("/");
request.getHeaders().put("test", "it-worked");
request.setTransportSecure(true);
request.setRemoteAddr("https://localhost:8008/");
request.setType("GET");
api.setEndpoint("https://localhost:8008/");
api.getEndpointProperties().put(RequiredAuthType.ENDPOINT_AUTHORIZATION_TYPE, "mtls");
}
/**
* Scenario:
* - Should not use a disallowed cipher in the exchange
* @throws Exception any exception
*/
@Test
public void shouldNotUseDisallowedCipher() throws Exception {
final String preferredCipher = getPrefferedCipher();
config.put(TLSOptions.TLS_TRUSTSTORE, getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
config.put(TLSOptions.TLS_TRUSTSTOREPASSWORD, "password");
config.put(TLSOptions.TLS_ALLOWANYHOST, "true");
config.put(TLSOptions.TLS_ALLOWSELFSIGNED, "false");
config.put(TLSOptions.TLS_DISALLOWEDCIPHERS, preferredCipher);
server.start();
HttpConnectorFactory factory = new HttpConnectorFactory(config);
IApiConnector connector = factory.createConnector(request, api, RequiredAuthType.DEFAULT, false);
IApiConnection connection = connector.connect(request,
new IAsyncResultHandler<IApiConnectionResponse>() {
@Override
public void handle(IAsyncResult<IApiConnectionResponse> result) {
if (result.isError())
throw new RuntimeException(result.getError());
Assert.assertTrue(result.isSuccess());
Assert.assertFalse(jettyRequestAttributes.get("javax.servlet.request.cipher_suite").equals(""));
Assert.assertFalse(jettyRequestAttributes.get("javax.servlet.request.cipher_suite").equals(preferredCipher));
}
});
connection.end();
}
/**
* Scenario:
* - Only allowed protocol is one that is disallowed by remote end
* @throws Exception any exception
*/
@Test
public void shouldFailWhenNoValidCipherAllowed() throws Exception {
String preferredCipher = getPrefferedCipher();
config.put(TLSOptions.TLS_TRUSTSTORE, getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
config.put(TLSOptions.TLS_TRUSTSTOREPASSWORD, "password");
config.put(TLSOptions.TLS_ALLOWANYHOST, "true");
config.put(TLSOptions.TLS_ALLOWSELFSIGNED, "false");
config.put(TLSOptions.TLS_ALLOWEDCIPHERS, preferredCipher);
jettySslContextFactory.setExcludeCipherSuites(preferredCipher);
server.start();
HttpConnectorFactory factory = new HttpConnectorFactory(config);
IApiConnector connector = factory.createConnector(request, api, RequiredAuthType.DEFAULT, false);
IApiConnection connection = connector.connect(request,
new IAsyncResultHandler<IApiConnectionResponse>() {
@Override
public void handle(IAsyncResult<IApiConnectionResponse> result) {
Assert.assertTrue(result.isError());
System.out.println(result.getError());
//result.getError().printStackTrace();
Assert.assertTrue(result.getError().getCause() instanceof javax.net.ssl.SSLHandshakeException);
}
});
exception.expect(RuntimeException.class);
connection.end();
}
/**
* Scenario:
* - Only allowed cipher is one that is disallowed by remote end
* @throws Exception any exception
*/
@Test
public void shouldFailWhenNoValidProtocolAllowed() throws Exception {
config.put(TLSOptions.TLS_TRUSTSTORE, getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
config.put(TLSOptions.TLS_TRUSTSTOREPASSWORD, "password");
config.put(TLSOptions.TLS_ALLOWANYHOST, "true");
config.put(TLSOptions.TLS_ALLOWSELFSIGNED, "false");
config.put(TLSOptions.TLS_ALLOWEDPROTOCOLS, "SSLv3");
jettySslContextFactory.setExcludeProtocols("SSLv3");
server.start();
HttpConnectorFactory factory = new HttpConnectorFactory(config);
IApiConnector connector = factory.createConnector(request, api, RequiredAuthType.DEFAULT, false);
IApiConnection connection = connector.connect(request,
new IAsyncResultHandler<IApiConnectionResponse>() {
@Override
public void handle(IAsyncResult<IApiConnectionResponse> result) {
Assert.assertTrue(result.isError());
System.out.println(result.getError());
//result.getError().printStackTrace();
Assert.assertTrue(result.getError().getCause() instanceof java.net.UnknownServiceException);
}
});
exception.expect(RuntimeException.class);
connection.end();
}
/**
* Scenario:
* - Only allowed protocol is one that is disallowed by remote end
* @throws Exception any exception
*/
@Test
public void shouldFailWhenAllAvailableProtocolsExcluded() throws Exception {
config.put(TLSOptions.TLS_TRUSTSTORE, getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
config.put(TLSOptions.TLS_TRUSTSTOREPASSWORD, "password");
config.put(TLSOptions.TLS_ALLOWANYHOST, "true");
config.put(TLSOptions.TLS_ALLOWSELFSIGNED, "false");
config.put(TLSOptions.TLS_ALLOWEDPROTOCOLS, "SSLv3");
jettySslContextFactory.setExcludeProtocols("SSLv3");
server.start();
HttpConnectorFactory factory = new HttpConnectorFactory(config);
IApiConnector connector = factory.createConnector(request, api, RequiredAuthType.DEFAULT, false);
IApiConnection connection = connector.connect(request,
new IAsyncResultHandler<IApiConnectionResponse>() {
@Override
public void handle(IAsyncResult<IApiConnectionResponse> result) {
Assert.assertTrue(result.isError());
System.out.println(result.getError());
Assert.assertTrue(result.getError().getCause() instanceof java.net.UnknownServiceException);
}
});
exception.expect(RuntimeException.class);
connection.end();
}
/**
* Scenario:
* - Only allowed protocol is one that is disallowed by remote end
* @throws Exception any exception
*/
@Test
public void shouldFailWhenRemoteProtocolsAreExcluded() throws Exception {
config.put(TLSOptions.TLS_TRUSTSTORE, getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
config.put(TLSOptions.TLS_TRUSTSTOREPASSWORD, "password");
config.put(TLSOptions.TLS_ALLOWANYHOST, "true");
config.put(TLSOptions.TLS_ALLOWSELFSIGNED, "false");
config.put(TLSOptions.TLS_DISALLOWEDPROTOCOLS, "SSLv3");
jettySslContextFactory.setIncludeProtocols("SSLv3");
jettySslContextFactory.setExcludeProtocols("SSLv1", "SSLv2", "TLSv1", "TLSv2");
server.start();
HttpConnectorFactory factory = new HttpConnectorFactory(config);
IApiConnector connector = factory.createConnector(request, api, RequiredAuthType.DEFAULT, false);
IApiConnection connection = connector.connect(request,
new IAsyncResultHandler<IApiConnectionResponse>() {
@Override
public void handle(IAsyncResult<IApiConnectionResponse> result) {
Assert.assertTrue(result.isError());
System.out.println(result.getError());
Assert.assertTrue(result.getError() instanceof ConnectorException);
}
});
exception.expect(RuntimeException.class);
connection.end();
}
/**
* Scenario:
* - Only allowed protocol is one that is disallowed by remote end
* @throws Exception any exception
*/
@Test
public void shouldFailWhenRemoteCiphersAreExcluded() throws Exception {
String preferredCipher = getPrefferedCipher();
config.put(TLSOptions.TLS_TRUSTSTORE, getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
config.put(TLSOptions.TLS_TRUSTSTOREPASSWORD, "password");
config.put(TLSOptions.TLS_ALLOWANYHOST, "true");
config.put(TLSOptions.TLS_ALLOWSELFSIGNED, "false");
config.put(TLSOptions.TLS_DISALLOWEDCIPHERS, preferredCipher);
jettySslContextFactory.setIncludeCipherSuites(preferredCipher);
server.start();
HttpConnectorFactory factory = new HttpConnectorFactory(config);
IApiConnector connector = factory.createConnector(request, api, RequiredAuthType.DEFAULT, false);
IApiConnection connection = connector.connect(request,
new IAsyncResultHandler<IApiConnectionResponse>() {
@Override
public void handle(IAsyncResult<IApiConnectionResponse> result) {
Assert.assertTrue(result.isError());
System.out.println(result.getError());
Assert.assertTrue(result.getError().getCause() instanceof javax.net.ssl.SSLHandshakeException);
}
});
exception.expect(RuntimeException.class);
connection.end();
}
private String getResourcePath(String res) {
URL resource = CipherAndProtocolSelectionTest.class.getResource(res);
try {
return Paths.get(resource.toURI()).toFile().getAbsolutePath();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
private String getPrefferedCipher() throws Exception {
config.put(TLSOptions.TLS_TRUSTSTORE, getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
config.put(TLSOptions.TLS_TRUSTSTOREPASSWORD, "password");
config.put(TLSOptions.TLS_ALLOWANYHOST, "true");
config.put(TLSOptions.TLS_ALLOWSELFSIGNED, "false");
server.start();
final StringBuffer sbuff = new StringBuffer();
final CountDownLatch latch = new CountDownLatch(1);
HttpConnectorFactory factory = new HttpConnectorFactory(config);
IApiConnector connector = factory.createConnector(request, api, RequiredAuthType.DEFAULT, false);
IApiConnection connection = connector.connect(request,
new IAsyncResultHandler<IApiConnectionResponse>() {
@Override
public void handle(IAsyncResult<IApiConnectionResponse> result) {
if (result.isError())
throw new RuntimeException(result.getError());
sbuff.append(jettyRequestAttributes.get("javax.servlet.request.cipher_suite"));
latch.countDown();
}
});
connection.end();
server.stop();
latch.await();
return sbuff.toString();
}
}
| apache-2.0 |
cfaddict/jhipster-course | sample-app/entblog/src/main/java/com/therealdanvega/blog/repository/BlogRepository.java | 453 | package com.therealdanvega.blog.repository;
import com.therealdanvega.blog.domain.Blog;
import org.springframework.data.jpa.repository.*;
import java.util.List;
/**
* Spring Data JPA repository for the Blog entity.
*/
@SuppressWarnings("unused")
public interface BlogRepository extends JpaRepository<Blog,Long> {
@Query("select blog from Blog blog where blog.user.login = ?#{principal.username}")
List<Blog> findByUserIsCurrentUser();
}
| apache-2.0 |
jeffbrown/grailsnolib | grails-test-suite-uber/src/test/groovy/org/codehaus/groovy/grails/validation/ValidatorConstraintTests.java | 4992 | package org.codehaus.groovy.grails.validation;
import groovy.lang.Closure;
import groovy.lang.GroovyShell;
/**
* Test cases for custom 'validator' constraint.
*
* @author Sergey Nebolsin (<a href="mailto:nebolsin@gmail.com"/>)
*/
public class ValidatorConstraintTests extends AbstractConstraintTests {
private static final String PROP_NAME = "firstName";
private GroovyShell shell = new GroovyShell();
@Override
protected Class<?> getConstraintClass() {
return ValidatorConstraint.class;
}
private Closure getClosure( String code ) {
return (Closure) shell.evaluate( code );
}
protected Constraint getConstraint( String closure ) {
return super.getConstraint( "testString", getClosure(closure) );
}
public void testBooleanReturn() {
testConstraintMessageCodes(
getConstraint("{val,obj -> return false}"),
"test",
new String[] { "testClass.testString.validator.error","testClass.testString.validator.invalid"},
new Object[] { "testString", TestClass.class, "test" }
);
testConstraintPassed(
getConstraint( "{val,obj -> return true}" ),
"test"
);
testConstraintDefaultMessage(
getConstraint("{val,obj -> return false}"),
"test",
"Property [{0}] of class [{1}] with value [{2}] does not pass custom validation"
);
// Test null and blank values.
testConstraintFailed(
getConstraint( "{val,obj -> return val == null}" ),
"test"
);
testConstraintPassed(
getConstraint( "{val,obj -> return val == null}" ),
null
);
testConstraintFailed(
getConstraint( "{val,obj -> return val?.trim() == ''}" ),
"test"
);
testConstraintPassed(
getConstraint( "{val,obj -> return val?.trim() == ''}" ),
" "
);
}
public void testStringReturn() {
testConstraintMessageCode(
getConstraint("{val,obj -> return 'test.message'}"),
"test",
"testClass.testString.test.message",
new Object[] { "testString", TestClass.class, "test" }
);
try {
testConstraintFailed(
getConstraint("{val,obj -> return 123L}"),
"test"
);
fail("Validator constraint must throw an exception about wrong closure return");
} catch( IllegalArgumentException iae ) {
// Greate
}
}
public void testListReturn() {
testConstraintMessageCode(
getConstraint("{val,obj -> return ['test.message', 'arg', 123L]}"),
"test",
"testClass.testString.test.message",
new Object[] { "testString", TestClass.class, "test", "arg", new Long(123) }
);
try {
testConstraintFailed(
getConstraint("{val,obj -> return [123L,'arg1','arg2']}"),
"test"
);
fail("Validator constraint must throw an exception about wrong closure return");
} catch( IllegalArgumentException iae ) {
// Greate
}
}
/**
* Tests that the delegate that provides access to the name of the
* constrained property is available to custom validators.
*/
public void testDelegate() {
testConstraintPassed(
getConstraint("{val, obj -> return propertyName == 'testString'}"),
"test");
}
public void testConstraintCreation() {
Constraint validatorConstraint = new ValidatorConstraint();
assertEquals( ConstrainedProperty.VALIDATOR_CONSTRAINT, validatorConstraint.getName() );
assertTrue( validatorConstraint.supports( TestClass.class ));
assertFalse( validatorConstraint.supports( null ));
validatorConstraint.setOwningClass( TestClass.class );
validatorConstraint.setPropertyName( PROP_NAME );
try {
getConstraint( "testString", "Test");
fail("ValidatorConstraint must throw an exception for non-closure parameter.");
} catch ( IllegalArgumentException iae ) {
// Great since validator constraint only applicable for Closure parameter
}
try {
getConstraint( "{ param1, param2, param3, param4 -> return true}" );
fail("ValidatorConstraint must throw exception about closure with more that 3 params");
} catch ( IllegalArgumentException iae ) {
// Great since validator constraint only applicable for Closure's with 1, 2 or 3 params
}
}
}
| apache-2.0 |
wpinnoo/GarbageCalendar | app/src/main/java/eu/pinnoo/garbagecalendar/data/Sector.java | 2236 | /*
* Copyright 2014 Wouter Pinnoo
*
* 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 eu.pinnoo.garbagecalendar.data;
import java.io.Serializable;
/**
*
* @author Wouter Pinnoo <pinnoo.wouter@gmail.com>
*/
public class Sector implements Serializable {
private static final long serialVersionUID = -843402748713889036L;
private AreaType type;
private String code;
public Sector(AreaType type, String code) {
this.type = type;
this.code = code;
}
@Override
public boolean equals(Object o) {
if (o instanceof Sector) {
Sector s = (Sector) o;
return s.getCode().equals(getCode())
&& s.getType().equals(getType());
}
return false;
}
@Override
public int hashCode() {
int hash = 7;
hash = 23 * hash + (this.type != null ? this.type.hashCode() : 0);
hash = 23 * hash + (this.code != null ? this.code.hashCode() : 0);
return hash;
}
@Override
public String toString() {
return type.toString() + code;
}
public Sector(String str) {
if (str.matches("[LlVv][0-9][0-9]")) {
switch (str.charAt(0)) {
case 'L':
type = AreaType.L;
break;
case 'V':
type = AreaType.V;
break;
default:
type = AreaType.NONE;
}
code = str.substring(1);
} else {
type = AreaType.CITY;
code = str;
}
}
public AreaType getType() {
return type;
}
public String getCode() {
return code;
}
}
| apache-2.0 |
porcelli-forks/kie-wb-common | kie-wb-common-dmn/kie-wb-common-dmn-api/src/test/java/org/kie/workbench/common/dmn/api/definition/model/LiteralExpressionTest.java | 3360 | /*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* 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 org.kie.workbench.common.dmn.api.definition.model;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.dmn.api.definition.HasTypeRef;
import org.kie.workbench.common.dmn.api.property.dmn.Description;
import org.kie.workbench.common.dmn.api.property.dmn.ExpressionLanguage;
import org.kie.workbench.common.dmn.api.property.dmn.Id;
import org.kie.workbench.common.dmn.api.property.dmn.Text;
import org.kie.workbench.common.dmn.api.property.dmn.types.BuiltInType;
import org.mockito.runners.MockitoJUnitRunner;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@RunWith(MockitoJUnitRunner.class)
public class LiteralExpressionTest {
private static final String LITERAL_ID = "LITERAL-ID";
private static final String DESCRIPTION = "DESCRIPTION";
private static final String TEXT = "TEXT";
private static final String EXPRESSION_LANGUAGE = "EXPRESSION-LANGUAGE";
private LiteralExpression literalExpression;
@Before
public void setup() {
this.literalExpression = new LiteralExpression();
}
@Test
public void testGetHasTypeRefs() {
final java.util.List<HasTypeRef> actualHasTypeRefs = literalExpression.getHasTypeRefs();
final java.util.List<HasTypeRef> expectedHasTypeRefs = singletonList(literalExpression);
assertEquals(expectedHasTypeRefs, actualHasTypeRefs);
}
@Test
public void testComponentWidths() {
assertEquals(literalExpression.getRequiredComponentWidthCount(),
literalExpression.getComponentWidths().size());
literalExpression.getComponentWidths().forEach(Assert::assertNull);
}
@Test
public void testCopy() {
final LiteralExpression source = new LiteralExpression(
new Id(LITERAL_ID),
new Description(DESCRIPTION),
BuiltInType.BOOLEAN.asQName(),
new Text(TEXT),
null,
new ExpressionLanguage(EXPRESSION_LANGUAGE)
);
final LiteralExpression target = source.copy();
assertNotNull(target);
assertNotEquals(LITERAL_ID, target.getId());
assertEquals(DESCRIPTION, target.getDescription().getValue());
assertEquals(BuiltInType.BOOLEAN.asQName(), target.getTypeRef());
assertEquals(TEXT, target.getText().getValue());
assertNull(target.getImportedValues());
assertEquals(EXPRESSION_LANGUAGE, target.getExpressionLanguage().getValue());
}
}
| apache-2.0 |
mattyb149/nifi | nifi-commons/nifi-record/src/main/java/org/apache/nifi/serialization/record/util/DataTypeUtils.java | 80351 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.serialization.record.util;
import org.apache.nifi.serialization.SimpleRecordSchema;
import org.apache.nifi.serialization.record.DataType;
import org.apache.nifi.serialization.record.MapRecord;
import org.apache.nifi.serialization.record.Record;
import org.apache.nifi.serialization.record.RecordField;
import org.apache.nifi.serialization.record.RecordFieldType;
import org.apache.nifi.serialization.record.RecordSchema;
import org.apache.nifi.serialization.record.type.ArrayDataType;
import org.apache.nifi.serialization.record.type.ChoiceDataType;
import org.apache.nifi.serialization.record.type.DecimalDataType;
import org.apache.nifi.serialization.record.type.EnumDataType;
import org.apache.nifi.serialization.record.type.MapDataType;
import org.apache.nifi.serialization.record.type.RecordDataType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Queue;
import java.util.Set;
import java.util.TimeZone;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Pattern;
public class DataTypeUtils {
private static final Logger logger = LoggerFactory.getLogger(DataTypeUtils.class);
// Regexes for parsing Floating-Point numbers
private static final String OptionalSign = "[\\-\\+]?";
private static final String Infinity = "(Infinity)";
private static final String NotANumber = "(NaN)";
private static final String Base10Digits = "\\d+";
private static final String Base10Decimal = "\\." + Base10Digits;
private static final String OptionalBase10Decimal = "(\\.\\d*)?";
private static final String Base10Exponent = "[eE]" + OptionalSign + Base10Digits;
private static final String OptionalBase10Exponent = "(" + Base10Exponent + ")?";
private static final String doubleRegex =
OptionalSign +
"(" +
Infinity + "|" +
NotANumber + "|"+
"(" + Base10Digits + OptionalBase10Decimal + ")" + "|" +
"(" + Base10Digits + OptionalBase10Decimal + Base10Exponent + ")" + "|" +
"(" + Base10Decimal + OptionalBase10Exponent + ")" +
")";
private static final String decimalRegex =
OptionalSign +
"(" + Base10Digits + OptionalBase10Decimal + ")" + "|" +
"(" + Base10Digits + OptionalBase10Decimal + Base10Exponent + ")" + "|" +
"(" + Base10Decimal + OptionalBase10Exponent + ")";
private static final Pattern FLOATING_POINT_PATTERN = Pattern.compile(doubleRegex);
private static final Pattern DECIMAL_PATTERN = Pattern.compile(decimalRegex);
private static final TimeZone gmt = TimeZone.getTimeZone("gmt");
private static final Supplier<DateFormat> DEFAULT_DATE_FORMAT = () -> getDateFormat(RecordFieldType.DATE.getDefaultFormat());
private static final Supplier<DateFormat> DEFAULT_TIME_FORMAT = () -> getDateFormat(RecordFieldType.TIME.getDefaultFormat());
private static final Supplier<DateFormat> DEFAULT_TIMESTAMP_FORMAT = () -> getDateFormat(RecordFieldType.TIMESTAMP.getDefaultFormat());
private static final int FLOAT_SIGNIFICAND_PRECISION = 24; // As specified in IEEE 754 binary32
private static final int DOUBLE_SIGNIFICAND_PRECISION = 53; // As specified in IEEE 754 binary64
private static final Long MAX_GUARANTEED_PRECISE_WHOLE_IN_FLOAT = Double.valueOf(Math.pow(2, FLOAT_SIGNIFICAND_PRECISION)).longValue();
private static final Long MIN_GUARANTEED_PRECISE_WHOLE_IN_FLOAT = -MAX_GUARANTEED_PRECISE_WHOLE_IN_FLOAT;
private static final Long MAX_GUARANTEED_PRECISE_WHOLE_IN_DOUBLE = Double.valueOf(Math.pow(2, DOUBLE_SIGNIFICAND_PRECISION)).longValue();
private static final Long MIN_GUARANTEED_PRECISE_WHOLE_IN_DOUBLE = -MAX_GUARANTEED_PRECISE_WHOLE_IN_DOUBLE;
private static final BigInteger MAX_FLOAT_VALUE_IN_BIGINT = BigInteger.valueOf(MAX_GUARANTEED_PRECISE_WHOLE_IN_FLOAT);
private static final BigInteger MIN_FLOAT_VALUE_IN_BIGINT = BigInteger.valueOf(MIN_GUARANTEED_PRECISE_WHOLE_IN_FLOAT);
private static final BigInteger MAX_DOUBLE_VALUE_IN_BIGINT = BigInteger.valueOf(MAX_GUARANTEED_PRECISE_WHOLE_IN_DOUBLE);
private static final BigInteger MIN_DOUBLE_VALUE_IN_BIGINT = BigInteger.valueOf(MIN_GUARANTEED_PRECISE_WHOLE_IN_DOUBLE);
private static final double MAX_FLOAT_VALUE_IN_DOUBLE = Float.valueOf(Float.MAX_VALUE).doubleValue();
private static final double MIN_FLOAT_VALUE_IN_DOUBLE = -MAX_FLOAT_VALUE_IN_DOUBLE;
private static final Map<RecordFieldType, Predicate<Object>> NUMERIC_VALIDATORS = new EnumMap<>(RecordFieldType.class);
static {
NUMERIC_VALIDATORS.put(RecordFieldType.BIGINT, value -> value instanceof BigInteger);
NUMERIC_VALIDATORS.put(RecordFieldType.LONG, value -> value instanceof Long);
NUMERIC_VALIDATORS.put(RecordFieldType.INT, value -> value instanceof Integer);
NUMERIC_VALIDATORS.put(RecordFieldType.BYTE, value -> value instanceof Byte);
NUMERIC_VALIDATORS.put(RecordFieldType.SHORT, value -> value instanceof Short);
NUMERIC_VALIDATORS.put(RecordFieldType.DOUBLE, value -> value instanceof Double);
NUMERIC_VALIDATORS.put(RecordFieldType.FLOAT, value -> value instanceof Float);
NUMERIC_VALIDATORS.put(RecordFieldType.DECIMAL, value -> value instanceof BigDecimal);
}
public static Object convertType(final Object value, final DataType dataType, final String fieldName) {
return convertType(value, dataType, fieldName, StandardCharsets.UTF_8);
}
public static Object convertType(final Object value, final DataType dataType, final String fieldName, final Charset charset) {
return convertType(value, dataType, DEFAULT_DATE_FORMAT, DEFAULT_TIME_FORMAT, DEFAULT_TIMESTAMP_FORMAT, fieldName, charset);
}
public static DateFormat getDateFormat(final RecordFieldType fieldType, final Supplier<DateFormat> dateFormat,
final Supplier<DateFormat> timeFormat, final Supplier<DateFormat> timestampFormat) {
switch (fieldType) {
case DATE:
return dateFormat.get();
case TIME:
return timeFormat.get();
case TIMESTAMP:
return timestampFormat.get();
}
return null;
}
public static Object convertType(final Object value, final DataType dataType, final Supplier<DateFormat> dateFormat, final Supplier<DateFormat> timeFormat,
final Supplier<DateFormat> timestampFormat, final String fieldName) {
return convertType(value, dataType, dateFormat, timeFormat, timestampFormat, fieldName, StandardCharsets.UTF_8);
}
public static Object convertType(final Object value, final DataType dataType, final Supplier<DateFormat> dateFormat, final Supplier<DateFormat> timeFormat,
final Supplier<DateFormat> timestampFormat, final String fieldName, final Charset charset) {
if (value == null) {
return null;
}
switch (dataType.getFieldType()) {
case BIGINT:
return toBigInt(value, fieldName);
case BOOLEAN:
return toBoolean(value, fieldName);
case BYTE:
return toByte(value, fieldName);
case CHAR:
return toCharacter(value, fieldName);
case DATE:
return toDate(value, dateFormat, fieldName);
case DECIMAL:
return toBigDecimal(value, fieldName);
case DOUBLE:
return toDouble(value, fieldName);
case FLOAT:
return toFloat(value, fieldName);
case INT:
return toInteger(value, fieldName);
case LONG:
return toLong(value, fieldName);
case SHORT:
return toShort(value, fieldName);
case ENUM:
return toEnum(value, (EnumDataType) dataType, fieldName);
case STRING:
return toString(value, () -> getDateFormat(dataType.getFieldType(), dateFormat, timeFormat, timestampFormat), charset);
case TIME:
return toTime(value, timeFormat, fieldName);
case TIMESTAMP:
return toTimestamp(value, timestampFormat, fieldName);
case ARRAY:
return toArray(value, fieldName, ((ArrayDataType)dataType).getElementType(), charset);
case MAP:
return toMap(value, fieldName);
case RECORD:
final RecordDataType recordType = (RecordDataType) dataType;
final RecordSchema childSchema = recordType.getChildSchema();
return toRecord(value, childSchema, fieldName, charset);
case CHOICE: {
final ChoiceDataType choiceDataType = (ChoiceDataType) dataType;
final DataType chosenDataType = chooseDataType(value, choiceDataType);
if (chosenDataType == null) {
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass()
+ " for field " + fieldName + " to any of the following available Sub-Types for a Choice: " + choiceDataType.getPossibleSubTypes());
}
return convertType(value, chosenDataType, fieldName, charset);
}
}
return null;
}
public static boolean isCompatibleDataType(final Object value, final DataType dataType) {
switch (dataType.getFieldType()) {
case ARRAY:
return isArrayTypeCompatible(value, ((ArrayDataType) dataType).getElementType());
case BIGINT:
return isBigIntTypeCompatible(value);
case BOOLEAN:
return isBooleanTypeCompatible(value);
case BYTE:
return isByteTypeCompatible(value);
case CHAR:
return isCharacterTypeCompatible(value);
case DATE:
return isDateTypeCompatible(value, dataType.getFormat());
case DECIMAL:
return isDecimalTypeCompatible(value);
case DOUBLE:
return isDoubleTypeCompatible(value);
case FLOAT:
return isFloatTypeCompatible(value);
case INT:
return isIntegerTypeCompatible(value);
case LONG:
return isLongTypeCompatible(value);
case RECORD: {
final RecordSchema schema = ((RecordDataType) dataType).getChildSchema();
return isRecordTypeCompatible(schema, value);
}
case SHORT:
return isShortTypeCompatible(value);
case TIME:
return isTimeTypeCompatible(value, dataType.getFormat());
case TIMESTAMP:
return isTimestampTypeCompatible(value, dataType.getFormat());
case STRING:
return isStringTypeCompatible(value);
case ENUM:
return isEnumTypeCompatible(value, (EnumDataType) dataType);
case MAP:
return isMapTypeCompatible(value);
case CHOICE: {
final DataType chosenDataType = chooseDataType(value, (ChoiceDataType) dataType);
return chosenDataType != null;
}
}
return false;
}
public static DataType chooseDataType(final Object value, final ChoiceDataType choiceType) {
Queue<DataType> possibleSubTypes = new LinkedList<>(choiceType.getPossibleSubTypes());
List<DataType> compatibleSimpleSubTypes = new ArrayList<>();
DataType subType;
while ((subType = possibleSubTypes.poll()) != null) {
if (subType instanceof ChoiceDataType) {
possibleSubTypes.addAll(((ChoiceDataType) subType).getPossibleSubTypes());
} else {
if (isCompatibleDataType(value, subType)) {
compatibleSimpleSubTypes.add(subType);
}
}
}
int nrOfCompatibleSimpleSubTypes = compatibleSimpleSubTypes.size();
final DataType chosenSimpleType;
if (nrOfCompatibleSimpleSubTypes == 0) {
chosenSimpleType = null;
} else if (nrOfCompatibleSimpleSubTypes == 1) {
chosenSimpleType = compatibleSimpleSubTypes.get(0);
} else {
chosenSimpleType = findMostSuitableType(value, compatibleSimpleSubTypes, Function.identity())
.orElse(compatibleSimpleSubTypes.get(0));
}
return chosenSimpleType;
}
public static <T> Optional<T> findMostSuitableType(Object value, List<T> types, Function<T, DataType> dataTypeMapper) {
if (value instanceof String) {
return findMostSuitableTypeByStringValue((String) value, types, dataTypeMapper);
} else {
DataType inferredDataType = inferDataType(value, null);
if (inferredDataType != null && !inferredDataType.getFieldType().equals(RecordFieldType.STRING)) {
for (T type : types) {
if (inferredDataType.equals(dataTypeMapper.apply(type))) {
return Optional.of(type);
}
}
for (T type : types) {
if (getWiderType(dataTypeMapper.apply(type), inferredDataType).isPresent()) {
return Optional.of(type);
}
}
}
}
return Optional.empty();
}
public static <T> Optional<T> findMostSuitableTypeByStringValue(String valueAsString, List<T> types, Function<T, DataType> dataTypeMapper) {
// Sorting based on the RecordFieldType enum ordering looks appropriate here as we want simpler types
// first and the enum's ordering seems to reflect that
Collections.sort(types, Comparator.comparing(type -> dataTypeMapper.apply(type).getFieldType()));
for (T type : types) {
try {
if (isCompatibleDataType(valueAsString, dataTypeMapper.apply(type))) {
return Optional.of(type);
}
} catch (Exception e) {
logger.error("Exception thrown while checking if '" + valueAsString + "' is compatible with '" + type + "'", e);
}
}
return Optional.empty();
}
public static Record toRecord(final Object value, final RecordSchema recordSchema, final String fieldName) {
return toRecord(value, recordSchema, fieldName, StandardCharsets.UTF_8);
}
public static Record toRecord(final Object value, final RecordSchema recordSchema, final String fieldName, final Charset charset) {
if (value == null) {
return null;
}
if (value instanceof Record) {
return ((Record) value);
}
if (value instanceof Map) {
if (recordSchema == null) {
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass()
+ " to Record for field " + fieldName + " because the value is a Map but no Record Schema was provided");
}
final Map<?, ?> map = (Map<?, ?>) value;
final Map<String, Object> coercedValues = new LinkedHashMap<>();
for (final Map.Entry<?, ?> entry : map.entrySet()) {
final Object keyValue = entry.getKey();
if (keyValue == null) {
continue;
}
final String key = keyValue.toString();
final Optional<DataType> desiredTypeOption = recordSchema.getDataType(key);
if (!desiredTypeOption.isPresent()) {
continue;
}
final Object rawValue = entry.getValue();
final Object coercedValue = convertType(rawValue, desiredTypeOption.get(), fieldName, charset);
coercedValues.put(key, coercedValue);
}
return new MapRecord(recordSchema, coercedValues);
}
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Record for field " + fieldName);
}
public static Record toRecord(final Object value, final String fieldName) {
return toRecord(value, fieldName, StandardCharsets.UTF_8);
}
public static RecordSchema inferSchema(final Map<String, Object> values, final String fieldName, final Charset charset) {
if (values == null) {
return null;
}
final List<RecordField> inferredFieldTypes = new ArrayList<>();
final Map<String, Object> coercedValues = new LinkedHashMap<>();
for (final Map.Entry<?, ?> entry : values.entrySet()) {
final Object keyValue = entry.getKey();
if (keyValue == null) {
continue;
}
final String key = keyValue.toString();
final Object rawValue = entry.getValue();
final DataType inferredDataType = inferDataType(rawValue, RecordFieldType.STRING.getDataType());
final RecordField recordField = new RecordField(key, inferredDataType, true);
inferredFieldTypes.add(recordField);
final Object coercedValue = convertType(rawValue, inferredDataType, fieldName, charset);
coercedValues.put(key, coercedValue);
}
final RecordSchema inferredSchema = new SimpleRecordSchema(inferredFieldTypes);
return inferredSchema;
}
public static Record toRecord(final Object value, final String fieldName, final Charset charset) {
if (value == null) {
return null;
}
if (value instanceof Record) {
return ((Record) value);
}
final List<RecordField> inferredFieldTypes = new ArrayList<>();
if (value instanceof Map) {
final Map<?, ?> map = (Map<?, ?>) value;
final Map<String, Object> coercedValues = new LinkedHashMap<>();
for (final Map.Entry<?, ?> entry : map.entrySet()) {
final Object keyValue = entry.getKey();
if (keyValue == null) {
continue;
}
final String key = keyValue.toString();
final Object rawValue = entry.getValue();
final DataType inferredDataType = inferDataType(rawValue, RecordFieldType.STRING.getDataType());
final RecordField recordField = new RecordField(key, inferredDataType, true);
inferredFieldTypes.add(recordField);
final Object coercedValue = convertType(rawValue, inferredDataType, fieldName, charset);
coercedValues.put(key, coercedValue);
}
final RecordSchema inferredSchema = new SimpleRecordSchema(inferredFieldTypes);
return new MapRecord(inferredSchema, coercedValues);
}
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Record for field " + fieldName);
}
public static DataType inferDataType(final Object value, final DataType defaultType) {
if (value == null) {
return defaultType;
}
if (value instanceof String) {
return RecordFieldType.STRING.getDataType();
}
if (value instanceof Record) {
final RecordSchema schema = ((Record) value).getSchema();
return RecordFieldType.RECORD.getRecordDataType(schema);
}
if (value instanceof Number) {
if (value instanceof Long) {
return RecordFieldType.LONG.getDataType();
}
if (value instanceof Integer) {
return RecordFieldType.INT.getDataType();
}
if (value instanceof Short) {
return RecordFieldType.SHORT.getDataType();
}
if (value instanceof Byte) {
return RecordFieldType.BYTE.getDataType();
}
if (value instanceof Float) {
return RecordFieldType.FLOAT.getDataType();
}
if (value instanceof Double) {
return RecordFieldType.DOUBLE.getDataType();
}
if (value instanceof BigInteger) {
return RecordFieldType.BIGINT.getDataType();
}
if (value instanceof BigDecimal) {
final BigDecimal bigDecimal = (BigDecimal) value;
return RecordFieldType.DECIMAL.getDecimalDataType(bigDecimal.precision(), bigDecimal.scale());
}
}
if (value instanceof Boolean) {
return RecordFieldType.BOOLEAN.getDataType();
}
if (value instanceof java.sql.Time) {
return RecordFieldType.TIME.getDataType();
}
if (value instanceof java.sql.Timestamp) {
return RecordFieldType.TIMESTAMP.getDataType();
}
if (value instanceof java.util.Date) {
return RecordFieldType.DATE.getDataType();
}
if (value instanceof Character) {
return RecordFieldType.CHAR.getDataType();
}
// A value of a Map could be either a Record or a Map type. In either case, it must have Strings as keys.
if (value instanceof Map) {
final Map<String, Object> map;
// Only transform the map if the keys aren't strings
boolean allStrings = true;
for (final Object key : ((Map<?, ?>) value).keySet()) {
if (!(key instanceof String)) {
allStrings = false;
break;
}
}
if (allStrings) {
map = (Map<String, Object>) value;
} else {
final Map<?, ?> m = (Map<?, ?>) value;
map = new HashMap<>(m.size());
m.forEach((k, v) -> map.put(k == null ? null : k.toString(), v));
}
return inferRecordDataType(map);
// // Check if all types are the same.
// if (map.isEmpty()) {
// return RecordFieldType.MAP.getMapDataType(RecordFieldType.STRING.getDataType());
// }
//
// Object valueFromMap = null;
// Class<?> valueClass = null;
// for (final Object val : map.values()) {
// if (val == null) {
// continue;
// }
//
// valueFromMap = val;
// final Class<?> currentValClass = val.getClass();
// if (valueClass == null) {
// valueClass = currentValClass;
// } else {
// // If we have two elements that are of different types, then we cannot have a Map. Must be a Record.
// if (valueClass != currentValClass) {
// return inferRecordDataType(map);
// }
// }
// }
//
// // All values appear to be of the same type, so assume that it's a map.
// final DataType elementDataType = inferDataType(valueFromMap, RecordFieldType.STRING.getDataType());
// return RecordFieldType.MAP.getMapDataType(elementDataType);
}
if (value.getClass().isArray()) {
DataType mergedDataType = null;
int length = Array.getLength(value);
for(int index = 0; index < length; index++) {
final DataType inferredDataType = inferDataType(Array.get(value, index), RecordFieldType.STRING.getDataType());
mergedDataType = mergeDataTypes(mergedDataType, inferredDataType);
}
if (mergedDataType == null) {
mergedDataType = RecordFieldType.STRING.getDataType();
}
return RecordFieldType.ARRAY.getArrayDataType(mergedDataType);
}
if (value instanceof Iterable) {
final Iterable iterable = (Iterable<?>) value;
DataType mergedDataType = null;
for (final Object arrayValue : iterable) {
final DataType inferredDataType = inferDataType(arrayValue, RecordFieldType.STRING.getDataType());
mergedDataType = mergeDataTypes(mergedDataType, inferredDataType);
}
if (mergedDataType == null) {
mergedDataType = RecordFieldType.STRING.getDataType();
}
return RecordFieldType.ARRAY.getArrayDataType(mergedDataType);
}
return defaultType;
}
private static DataType inferRecordDataType(final Map<String, ?> map) {
final List<RecordField> fields = new ArrayList<>(map.size());
for (final Map.Entry<String, ?> entry : map.entrySet()) {
final String key = entry.getKey();
final Object value = entry.getValue();
final DataType dataType = inferDataType(value, RecordFieldType.STRING.getDataType());
final RecordField field = new RecordField(key, dataType, true);
fields.add(field);
}
final RecordSchema schema = new SimpleRecordSchema(fields);
return RecordFieldType.RECORD.getRecordDataType(schema);
}
/**
* Check if the given record structured object compatible with the schema.
* @param schema record schema, schema validation will not be performed if schema is null
* @param value the record structured object, i.e. Record or Map
* @return True if the object is compatible with the schema
*/
private static boolean isRecordTypeCompatible(RecordSchema schema, Object value) {
if (value == null) {
return false;
}
if (!(value instanceof Record) && !(value instanceof Map)) {
return false;
}
if (schema == null) {
return true;
}
for (final RecordField childField : schema.getFields()) {
final Object childValue;
if (value instanceof Record) {
childValue = ((Record) value).getValue(childField);
} else {
childValue = ((Map) value).get(childField.getFieldName());
}
if (childValue == null && !childField.isNullable()) {
logger.debug("Value is not compatible with schema because field {} has a null value, which is not allowed in the schema", childField.getFieldName());
return false;
}
if (childValue == null) {
continue; // consider compatible
}
if (!isCompatibleDataType(childValue, childField.getDataType())) {
return false;
}
}
return true;
}
public static Object[] toArray(final Object value, final String fieldName, final DataType elementDataType) {
return toArray(value, fieldName, elementDataType, StandardCharsets.UTF_8);
}
public static Object[] toArray(final Object value, final String fieldName, final DataType elementDataType, final Charset charset) {
if (value == null) {
return null;
}
if (value instanceof Object[]) {
return (Object[]) value;
}
if (value instanceof String && RecordFieldType.BYTE.getDataType().equals(elementDataType)) {
byte[] src = ((String) value).getBytes(charset);
Byte[] dest = new Byte[src.length];
for (int i = 0; i < src.length; i++) {
dest[i] = src[i];
}
return dest;
}
if (value instanceof byte[]) {
byte[] src = (byte[]) value;
Byte[] dest = new Byte[src.length];
for (int i = 0; i < src.length; i++) {
dest[i] = src[i];
}
return dest;
}
if (value instanceof List) {
final List<?> list = (List<?>)value;
return list.toArray();
}
try {
if (value instanceof Blob) {
Blob blob = (Blob) value;
long rawBlobLength = blob.length();
if(rawBlobLength > Integer.MAX_VALUE) {
throw new IllegalTypeConversionException("Value of type " + value.getClass() + " too large to convert to Object Array for field " + fieldName);
}
int blobLength = (int) rawBlobLength;
byte[] src = blob.getBytes(1, blobLength);
Byte[] dest = new Byte[blobLength];
for (int i = 0; i < src.length; i++) {
dest[i] = src[i];
}
return dest;
} else {
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Object Array for field " + fieldName);
}
} catch (IllegalTypeConversionException itce) {
throw itce;
} catch (Exception e) {
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Object Array for field " + fieldName, e);
}
}
public static boolean isArrayTypeCompatible(final Object value, final DataType elementDataType) {
if (value == null) {
return false;
}
// Either an object array (check the element type) or a String to be converted to byte[]
if (value instanceof Object[]) {
for (Object o : ((Object[]) value)) {
// Check each element to ensure its type is the same or can be coerced (if need be)
if (!isCompatibleDataType(o, elementDataType)) {
return false;
}
}
return true;
} else {
return value instanceof String && RecordFieldType.BYTE.getDataType().equals(elementDataType);
}
}
@SuppressWarnings("unchecked")
public static Map<String, Object> toMap(final Object value, final String fieldName) {
if (value == null) {
return null;
}
if (value instanceof Map) {
final Map<?, ?> original = (Map<?, ?>) value;
boolean keysAreStrings = true;
for (final Object key : original.keySet()) {
if (!(key instanceof String)) {
keysAreStrings = false;
}
}
if (keysAreStrings) {
return (Map<String, Object>) value;
}
final Map<String, Object> transformed = new LinkedHashMap<>();
for (final Map.Entry<?, ?> entry : original.entrySet()) {
final Object key = entry.getKey();
if (key == null) {
transformed.put(null, entry.getValue());
} else {
transformed.put(key.toString(), entry.getValue());
}
}
return transformed;
}
if (value instanceof Record) {
final Record record = (Record) value;
final RecordSchema recordSchema = record.getSchema();
if (recordSchema == null) {
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type Record to Map for field " + fieldName
+ " because Record does not have an associated Schema");
}
final Map<String, Object> map = new LinkedHashMap<>();
for (final String recordFieldName : recordSchema.getFieldNames()) {
map.put(recordFieldName, record.getValue(recordFieldName));
}
return map;
}
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Map for field " + fieldName);
}
/**
* Creates a native Java object from a given object of a specified type. Non-scalar (complex, nested, etc.) data types are processed iteratively/recursively, such that all
* included objects are native Java objects, rather than Record API objects or implementation-specific objects.
* @param value The object to be converted
* @param dataType The type of the provided object
* @return An object representing a native Java conversion of the given input object
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public static Object convertRecordFieldtoObject(final Object value, final DataType dataType) {
if (value == null) {
return null;
}
if (value instanceof Record) {
Record record = (Record) value;
RecordSchema recordSchema = record.getSchema();
if (recordSchema == null) {
throw new IllegalTypeConversionException("Cannot convert value of type Record to Map because Record does not have an associated Schema");
}
final Map<String, Object> recordMap = new LinkedHashMap<>();
for (RecordField field : recordSchema.getFields()) {
final DataType fieldDataType = field.getDataType();
final String fieldName = field.getFieldName();
Object fieldValue = record.getValue(fieldName);
if (fieldValue == null) {
recordMap.put(fieldName, null);
} else if (isScalarValue(fieldDataType, fieldValue)) {
recordMap.put(fieldName, fieldValue);
} else if (fieldDataType instanceof RecordDataType) {
Record nestedRecord = (Record) fieldValue;
recordMap.put(fieldName, convertRecordFieldtoObject(nestedRecord, fieldDataType));
} else if (fieldDataType instanceof MapDataType) {
recordMap.put(fieldName, convertRecordMapToJavaMap((Map) fieldValue, ((MapDataType)fieldDataType).getValueType()));
} else if (fieldDataType instanceof ArrayDataType) {
recordMap.put(fieldName, convertRecordArrayToJavaArray((Object[])fieldValue, ((ArrayDataType) fieldDataType).getElementType()));
} else {
throw new IllegalTypeConversionException("Cannot convert value [" + fieldValue + "] of type " + fieldDataType.toString()
+ " to Map for field " + fieldName + " because the type is not supported");
}
}
return recordMap;
} else if (value instanceof Map) {
return convertRecordMapToJavaMap((Map) value, ((MapDataType) dataType).getValueType());
} else if (dataType != null && isScalarValue(dataType, value)) {
return value;
} else if (value instanceof Object[] && dataType instanceof ArrayDataType) {
// This is likely a Map whose values are represented as an array. Return a new array with each element converted to a Java object
return convertRecordArrayToJavaArray((Object[]) value, ((ArrayDataType) dataType).getElementType());
}
throw new IllegalTypeConversionException("Cannot convert value of class " + value.getClass().getName() + " because the type is not supported");
}
public static Map<String, Object> convertRecordMapToJavaMap(final Map<String, Object> map, DataType valueDataType) {
if (map == null) {
return null;
}
Map<String, Object> resultMap = new LinkedHashMap<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
resultMap.put(entry.getKey(), convertRecordFieldtoObject(entry.getValue(), valueDataType));
}
return resultMap;
}
public static Object[] convertRecordArrayToJavaArray(final Object[] array, DataType elementDataType) {
if (array == null || array.length == 0 || isScalarValue(elementDataType, array[0])) {
return array;
} else {
// Must be an array of complex types, build an array of converted values
Object[] resultArray = new Object[array.length];
for (int i = 0; i < array.length; i++) {
resultArray[i] = convertRecordFieldtoObject(array[i], elementDataType);
}
return resultArray;
}
}
public static boolean isMapTypeCompatible(final Object value) {
return value != null && (value instanceof Map || value instanceof MapRecord);
}
public static String toString(final Object value, final Supplier<DateFormat> format) {
return toString(value, format, StandardCharsets.UTF_8);
}
public static String toString(final Object value, final Supplier<DateFormat> format, final Charset charset) {
if (value == null) {
return null;
}
if (value instanceof String) {
return (String) value;
}
if (format == null && value instanceof java.util.Date) {
return String.valueOf(((java.util.Date) value).getTime());
}
if (value instanceof java.util.Date) {
return formatDate((java.util.Date) value, format);
}
if (value instanceof byte[]) {
return new String((byte[])value, charset);
}
if (value instanceof Byte[]) {
Byte[] src = (Byte[]) value;
byte[] dest = new byte[src.length];
for(int i=0;i<src.length;i++) {
dest[i] = src[i];
}
return new String(dest, charset);
}
if (value instanceof Object[]) {
Object[] o = (Object[]) value;
if (o.length > 0) {
byte[] dest = new byte[o.length];
for (int i = 0; i < o.length; i++) {
dest[i] = (byte) o[i];
}
return new String(dest, charset);
} else {
return ""; // Empty array = empty string
}
}
if (value instanceof Clob) {
Clob clob = (Clob) value;
StringBuilder sb = new StringBuilder();
char[] buffer = new char[32 * 1024]; // 32K default buffer
try (Reader reader = clob.getCharacterStream()) {
int charsRead;
while ((charsRead = reader.read(buffer)) != -1) {
sb.append(buffer, 0, charsRead);
}
return sb.toString();
} catch (Exception e) {
throw new IllegalTypeConversionException("Cannot convert value " + value + " of type " + value.getClass() + " to a valid String", e);
}
}
return value.toString();
}
private static String formatDate(final java.util.Date date, final Supplier<DateFormat> formatSupplier) {
final DateFormat dateFormat = formatSupplier.get();
if (dateFormat == null) {
return String.valueOf((date).getTime());
}
return dateFormat.format(date);
}
public static String toString(final Object value, final String format) {
return toString(value, format, StandardCharsets.UTF_8);
}
public static String toString(final Object value, final String format, final Charset charset) {
if (value == null) {
return null;
}
if (value instanceof String) {
return (String) value;
}
if (format == null && value instanceof java.util.Date) {
return String.valueOf(((java.util.Date) value).getTime());
}
if (value instanceof java.sql.Date) {
return getDateFormat(format).format((java.util.Date) value);
}
if (value instanceof java.sql.Time) {
return getDateFormat(format).format((java.util.Date) value);
}
if (value instanceof java.sql.Timestamp) {
return getDateFormat(format).format((java.util.Date) value);
}
if (value instanceof java.util.Date) {
return getDateFormat(format).format((java.util.Date) value);
}
if (value instanceof Blob) {
Blob blob = (Blob) value;
StringBuilder sb = new StringBuilder();
byte[] buffer = new byte[32 * 1024]; // 32K default buffer
try (InputStream inStream = blob.getBinaryStream()) {
int bytesRead;
while ((bytesRead = inStream.read(buffer)) != -1) {
sb.append(new String(buffer, charset), 0, bytesRead);
}
return sb.toString();
} catch (Exception e) {
throw new IllegalTypeConversionException("Cannot convert value " + value + " of type " + value.getClass() + " to a valid String", e);
}
}
if (value instanceof Clob) {
Clob clob = (Clob) value;
StringBuilder sb = new StringBuilder();
char[] buffer = new char[32 * 1024]; // 32K default buffer
try (Reader reader = clob.getCharacterStream()) {
int charsRead;
while ((charsRead = reader.read(buffer)) != -1) {
sb.append(buffer, 0, charsRead);
}
return sb.toString();
} catch (Exception e) {
throw new IllegalTypeConversionException("Cannot convert value " + value + " of type " + value.getClass() + " to a valid String", e);
}
}
if (value instanceof Object[]) {
return Arrays.toString((Object[]) value);
}
if (value instanceof byte[]) {
return new String((byte[]) value, charset);
}
return value.toString();
}
public static boolean isStringTypeCompatible(final Object value) {
return value != null;
}
public static boolean isEnumTypeCompatible(final Object value, final EnumDataType enumType) {
return enumType.getEnums() != null && enumType.getEnums().contains(value);
}
private static Object toEnum(Object value, EnumDataType dataType, String fieldName) {
if(dataType.getEnums() != null && dataType.getEnums().contains(value)) {
return value.toString();
}
throw new IllegalTypeConversionException("Cannot convert value " + value + " of type " + dataType.toString() + " for field " + fieldName);
}
public static java.sql.Date toDate(final Object value, final Supplier<DateFormat> format, final String fieldName) {
if (value == null) {
return null;
}
if (value instanceof Date) {
return (Date) value;
}
if (value instanceof java.util.Date) {
java.util.Date _temp = (java.util.Date)value;
return new Date(_temp.getTime());
}
if (value instanceof Number) {
final long longValue = ((Number) value).longValue();
return new Date(longValue);
}
if (value instanceof String) {
try {
final String string = ((String) value).trim();
if (string.isEmpty()) {
return null;
}
if (format == null) {
return new Date(Long.parseLong(string));
}
final DateFormat dateFormat = format.get();
if (dateFormat == null) {
return new Date(Long.parseLong(string));
}
final java.util.Date utilDate = dateFormat.parse(string);
return new Date(utilDate.getTime());
} catch (final ParseException | NumberFormatException e) {
throw new IllegalTypeConversionException("Could not convert value [" + value
+ "] of type java.lang.String to Date because the value is not in the expected date format: " + format + " for field " + fieldName);
}
}
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Date for field " + fieldName);
}
public static boolean isDateTypeCompatible(final Object value, final String format) {
if (value == null) {
return false;
}
if (value instanceof java.util.Date || value instanceof Number) {
return true;
}
if (value instanceof String) {
if (format == null) {
return isInteger((String) value);
}
try {
getDateFormat(format).parse((String) value);
return true;
} catch (final ParseException e) {
return false;
}
}
return false;
}
private static boolean isInteger(final String value) {
if (value == null || value.isEmpty()) {
return false;
}
for (int i = 0; i < value.length(); i++) {
if (!Character.isDigit(value.charAt(i))) {
return false;
}
}
return true;
}
public static Time toTime(final Object value, final Supplier<DateFormat> format, final String fieldName) {
if (value == null) {
return null;
}
if (value instanceof Time) {
return (Time) value;
}
if (value instanceof Number) {
final long longValue = ((Number) value).longValue();
return new Time(longValue);
}
if (value instanceof String) {
try {
final String string = ((String) value).trim();
if (string.isEmpty()) {
return null;
}
if (format == null) {
return new Time(Long.parseLong(string));
}
final DateFormat dateFormat = format.get();
if (dateFormat == null) {
return new Time(Long.parseLong(string));
}
final java.util.Date utilDate = dateFormat.parse(string);
return new Time(utilDate.getTime());
} catch (final ParseException e) {
throw new IllegalTypeConversionException("Could not convert value [" + value
+ "] of type java.lang.String to Time for field " + fieldName + " because the value is not in the expected date format: " + format);
}
}
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Time for field " + fieldName);
}
public static DateFormat getDateFormat(final String format) {
if (format == null) {
return null;
}
final DateFormat df = new SimpleDateFormat(format);
df.setTimeZone(gmt);
return df;
}
public static DateFormat getDateFormat(final String format, final String timezoneID) {
if (format == null || timezoneID == null) {
return null;
}
final DateFormat df = new SimpleDateFormat(format);
df.setTimeZone(TimeZone.getTimeZone(timezoneID));
return df;
}
public static boolean isTimeTypeCompatible(final Object value, final String format) {
return isDateTypeCompatible(value, format);
}
public static Timestamp toTimestamp(final Object value, final Supplier<DateFormat> format, final String fieldName) {
if (value == null) {
return null;
}
if (value instanceof Timestamp) {
return (Timestamp) value;
}
if (value instanceof java.util.Date) {
return new Timestamp(((java.util.Date)value).getTime());
}
if (value instanceof Number) {
final long longValue = ((Number) value).longValue();
return new Timestamp(longValue);
}
if (value instanceof String) {
final String string = ((String) value).trim();
if (string.isEmpty()) {
return null;
}
try {
if (format == null) {
return new Timestamp(Long.parseLong(string));
}
final DateFormat dateFormat = format.get();
if (dateFormat == null) {
return new Timestamp(Long.parseLong(string));
}
final java.util.Date utilDate = dateFormat.parse(string);
return new Timestamp(utilDate.getTime());
} catch (final ParseException e) {
final DateFormat dateFormat = format.get();
final String formatDescription;
if (dateFormat == null) {
formatDescription = "Numeric";
} else if (dateFormat instanceof SimpleDateFormat) {
formatDescription = ((SimpleDateFormat) dateFormat).toPattern();
} else {
formatDescription = dateFormat.toString();
}
throw new IllegalTypeConversionException("Could not convert value [" + value
+ "] of type java.lang.String to Timestamp for field " + fieldName + " because the value is not in the expected date format: "
+ formatDescription);
}
}
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Timestamp for field " + fieldName);
}
public static boolean isTimestampTypeCompatible(final Object value, final String format) {
return isDateTypeCompatible(value, format);
}
public static BigInteger toBigInt(final Object value, final String fieldName) {
if (value == null) {
return null;
}
if (value instanceof BigInteger) {
return (BigInteger) value;
}
if (value instanceof Number) {
return BigInteger.valueOf(((Number) value).longValue());
}
if (value instanceof String) {
try {
return new BigInteger((String) value);
} catch (NumberFormatException nfe) {
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to BigInteger for field " + fieldName
+ ", value is not a valid representation of BigInteger", nfe);
}
}
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to BigInteger for field " + fieldName);
}
public static boolean isBigIntTypeCompatible(final Object value) {
return isNumberTypeCompatible(value, DataTypeUtils::isIntegral);
}
public static boolean isDecimalTypeCompatible(final Object value) {
return isNumberTypeCompatible(value, DataTypeUtils::isDecimal);
}
public static Boolean toBoolean(final Object value, final String fieldName) {
if (value == null) {
return null;
}
if (value instanceof Boolean) {
return (Boolean) value;
}
if (value instanceof String) {
final String string = (String) value;
if (string.equalsIgnoreCase("true")) {
return Boolean.TRUE;
} else if (string.equalsIgnoreCase("false")) {
return Boolean.FALSE;
}
}
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Boolean for field " + fieldName);
}
public static boolean isBooleanTypeCompatible(final Object value) {
if (value == null) {
return false;
}
if (value instanceof Boolean) {
return true;
}
if (value instanceof String) {
final String string = (String) value;
return string.equalsIgnoreCase("true") || string.equalsIgnoreCase("false");
}
return false;
}
public static BigDecimal toBigDecimal(final Object value, final String fieldName) {
if (value == null) {
return null;
}
if (value instanceof BigDecimal) {
return (BigDecimal) value;
}
if (value instanceof Number) {
final Number number = (Number) value;
if (number instanceof Byte
|| number instanceof Short
|| number instanceof Integer
|| number instanceof Long) {
return BigDecimal.valueOf(number.longValue());
}
if (number instanceof BigInteger) {
return new BigDecimal((BigInteger) number);
}
if (number instanceof Float) {
return new BigDecimal(Float.toString((Float) number));
}
if (number instanceof Double) {
return new BigDecimal(Double.toString((Double) number));
}
}
if (value instanceof String) {
try {
return new BigDecimal((String) value);
} catch (NumberFormatException nfe) {
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to BigDecimal for field " + fieldName
+ ", value is not a valid representation of BigDecimal", nfe);
}
}
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to BigDecimal for field " + fieldName);
}
public static Double toDouble(final Object value, final String fieldName) {
if (value == null) {
return null;
}
if (value instanceof Number) {
return ((Number) value).doubleValue();
}
if (value instanceof String) {
return Double.parseDouble((String) value);
}
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Double for field " + fieldName);
}
public static boolean isDoubleTypeCompatible(final Object value) {
return isNumberTypeCompatible(value, s -> isDouble(s));
}
private static boolean isNumberTypeCompatible(final Object value, final Predicate<String> stringPredicate) {
if (value == null) {
return false;
}
if (value instanceof Number) {
return true;
}
if (value instanceof String) {
return stringPredicate.test((String) value);
}
return false;
}
public static Float toFloat(final Object value, final String fieldName) {
if (value == null) {
return null;
}
if (value instanceof Number) {
return ((Number) value).floatValue();
}
if (value instanceof String) {
return Float.parseFloat((String) value);
}
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Float for field " + fieldName);
}
public static boolean isFloatTypeCompatible(final Object value) {
return isNumberTypeCompatible(value, s -> isFloatingPoint(s));
}
private static boolean isDecimal(final String value) {
if (value == null || value.isEmpty()) {
return false;
}
return DECIMAL_PATTERN.matcher(value).matches();
}
private static boolean isFloatingPoint(final String value) {
if (value == null || value.isEmpty()) {
return false;
}
if (!FLOATING_POINT_PATTERN.matcher(value).matches()) {
return false;
}
// Just to ensure that the exponents are in range, etc.
try {
Float.parseFloat(value);
} catch (final NumberFormatException nfe) {
return false;
}
return true;
}
private static boolean isDouble(final String value) {
if (value == null || value.isEmpty()) {
return false;
}
if (!FLOATING_POINT_PATTERN.matcher(value).matches()) {
return false;
}
// Just to ensure that the exponents are in range, etc.
try {
Double.parseDouble(value);
} catch (final NumberFormatException nfe) {
return false;
}
return true;
}
public static Long toLong(final Object value, final String fieldName) {
if (value == null) {
return null;
}
if (value instanceof Number) {
return ((Number) value).longValue();
}
if (value instanceof String) {
return Long.parseLong((String) value);
}
if (value instanceof java.util.Date) {
return ((java.util.Date) value).getTime();
}
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Long for field " + fieldName);
}
public static boolean isLongTypeCompatible(final Object value) {
if (value == null) {
return false;
}
if (value instanceof Number) {
return true;
}
if (value instanceof java.util.Date) {
return true;
}
if (value instanceof String) {
return isIntegral((String) value, Long.MIN_VALUE, Long.MAX_VALUE);
}
return false;
}
/**
* Check if the value is an integral.
*/
private static boolean isIntegral(final String value) {
if (value == null || value.isEmpty()) {
return false;
}
int initialPosition = 0;
final char firstChar = value.charAt(0);
if (firstChar == '+' || firstChar == '-') {
initialPosition = 1;
if (value.length() == 1) {
return false;
}
}
for (int i = initialPosition; i < value.length(); i++) {
if (!Character.isDigit(value.charAt(i))) {
return false;
}
}
return true;
}
/**
* Check if the value is an integral within a value range.
*/
private static boolean isIntegral(final String value, final long minValue, final long maxValue) {
if (!isIntegral(value)) {
return false;
}
try {
final long longValue = Long.parseLong(value);
return longValue >= minValue && longValue <= maxValue;
} catch (final NumberFormatException nfe) {
// In case the value actually exceeds the max value of a Long
return false;
}
}
public static Integer toInteger(final Object value, final String fieldName) {
if (value == null) {
return null;
}
if (value instanceof Number) {
try {
return Math.toIntExact(((Number) value).longValue());
} catch (ArithmeticException ae) {
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Integer for field " + fieldName
+ " as it causes an arithmetic overflow (the value is too large, e.g.)", ae);
}
}
if (value instanceof String) {
return Integer.parseInt((String) value);
}
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Integer for field " + fieldName);
}
public static boolean isIntegerTypeCompatible(final Object value) {
return isNumberTypeCompatible(value, s -> isIntegral(s, Integer.MIN_VALUE, Integer.MAX_VALUE));
}
public static Short toShort(final Object value, final String fieldName) {
if (value == null) {
return null;
}
if (value instanceof Number) {
return ((Number) value).shortValue();
}
if (value instanceof String) {
return Short.parseShort((String) value);
}
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Short for field " + fieldName);
}
public static boolean isShortTypeCompatible(final Object value) {
return isNumberTypeCompatible(value, s -> isIntegral(s, Short.MIN_VALUE, Short.MAX_VALUE));
}
public static Byte toByte(final Object value, final String fieldName) {
if (value == null) {
return null;
}
if (value instanceof Number) {
return ((Number) value).byteValue();
}
if (value instanceof String) {
return Byte.parseByte((String) value);
}
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Byte for field " + fieldName);
}
public static boolean isByteTypeCompatible(final Object value) {
return isNumberTypeCompatible(value, s -> isIntegral(s, Byte.MIN_VALUE, Byte.MAX_VALUE));
}
public static Character toCharacter(final Object value, final String fieldName) {
if (value == null) {
return null;
}
if (value instanceof Character) {
return ((Character) value);
}
if (value instanceof CharSequence) {
final CharSequence charSeq = (CharSequence) value;
if (charSeq.length() == 0) {
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass()
+ " to Character because it has a length of 0 for field " + fieldName);
}
return charSeq.charAt(0);
}
throw new IllegalTypeConversionException("Cannot convert value [" + value + "] of type " + value.getClass() + " to Character for field " + fieldName);
}
public static boolean isCharacterTypeCompatible(final Object value) {
return value != null && (value instanceof Character || (value instanceof CharSequence && ((CharSequence) value).length() > 0));
}
public static RecordSchema merge(final RecordSchema thisSchema, final RecordSchema otherSchema) {
if (thisSchema == null) {
return otherSchema;
}
if (otherSchema == null) {
return thisSchema;
}
if (thisSchema == otherSchema) {
return thisSchema;
}
final List<RecordField> otherFields = otherSchema.getFields();
if (otherFields.isEmpty()) {
return thisSchema;
}
final List<RecordField> thisFields = thisSchema.getFields();
if (thisFields.isEmpty()) {
return otherSchema;
}
final Map<String, Integer> fieldIndices = new HashMap<>();
final List<RecordField> fields = new ArrayList<>();
for (int i = 0; i < thisFields.size(); i++) {
final RecordField field = thisFields.get(i);
final Integer index = Integer.valueOf(i);
fieldIndices.put(field.getFieldName(), index);
for (final String alias : field.getAliases()) {
fieldIndices.put(alias, index);
}
fields.add(field);
}
for (final RecordField otherField : otherFields) {
Integer fieldIndex = fieldIndices.get(otherField.getFieldName());
// Find the field in 'thisSchema' that corresponds to 'otherField',
// if one exists.
if (fieldIndex == null) {
for (final String alias : otherField.getAliases()) {
fieldIndex = fieldIndices.get(alias);
if (fieldIndex != null) {
break;
}
}
}
// If there is no field with the same name then just add 'otherField'.
if (fieldIndex == null) {
fields.add(otherField);
continue;
}
// Merge the two fields, if necessary
final RecordField thisField = fields.get(fieldIndex);
if (isMergeRequired(thisField, otherField)) {
final RecordField mergedField = merge(thisField, otherField);
fields.set(fieldIndex, mergedField);
}
}
return new SimpleRecordSchema(fields);
}
private static boolean isMergeRequired(final RecordField thisField, final RecordField otherField) {
if (!thisField.getDataType().equals(otherField.getDataType())) {
return true;
}
if (!thisField.getAliases().equals(otherField.getAliases())) {
return true;
}
if (!Objects.equals(thisField.getDefaultValue(), otherField.getDefaultValue())) {
return true;
}
return false;
}
public static RecordField merge(final RecordField thisField, final RecordField otherField) {
final String fieldName = thisField.getFieldName();
final Set<String> aliases = new HashSet<>();
aliases.addAll(thisField.getAliases());
aliases.addAll(otherField.getAliases());
final Object defaultValue;
if (thisField.getDefaultValue() == null && otherField.getDefaultValue() != null) {
defaultValue = otherField.getDefaultValue();
} else {
defaultValue = thisField.getDefaultValue();
}
final DataType dataType = mergeDataTypes(thisField.getDataType(), otherField.getDataType());
return new RecordField(fieldName, dataType, defaultValue, aliases, thisField.isNullable() || otherField.isNullable());
}
public static DataType mergeDataTypes(final DataType thisDataType, final DataType otherDataType) {
if (thisDataType == null) {
return otherDataType;
}
if (otherDataType == null) {
return thisDataType;
}
if (thisDataType.equals(otherDataType)) {
return thisDataType;
} else {
// If one type is 'wider' than the other (such as an INT and a LONG), just use the wider type (LONG, in this case),
// rather than using a CHOICE of the two.
final Optional<DataType> widerType = getWiderType(thisDataType, otherDataType);
if (widerType.isPresent()) {
return widerType.get();
}
final Set<DataType> possibleTypes = new LinkedHashSet<>();
if (thisDataType.getFieldType() == RecordFieldType.CHOICE) {
possibleTypes.addAll(((ChoiceDataType) thisDataType).getPossibleSubTypes());
} else {
possibleTypes.add(thisDataType);
}
if (otherDataType.getFieldType() == RecordFieldType.CHOICE) {
possibleTypes.addAll(((ChoiceDataType) otherDataType).getPossibleSubTypes());
} else {
possibleTypes.add(otherDataType);
}
ArrayList<DataType> possibleChildTypes = new ArrayList<>(possibleTypes);
Collections.sort(possibleChildTypes, Comparator.comparing(DataType::getFieldType));
return RecordFieldType.CHOICE.getChoiceDataType(possibleChildTypes);
}
}
public static Optional<DataType> getWiderType(final DataType thisDataType, final DataType otherDataType) {
final RecordFieldType thisFieldType = thisDataType.getFieldType();
final RecordFieldType otherFieldType = otherDataType.getFieldType();
final int thisIntTypeValue = getIntegerTypeValue(thisFieldType);
final int otherIntTypeValue = getIntegerTypeValue(otherFieldType);
if (thisIntTypeValue > -1 && otherIntTypeValue > -1) {
if (thisIntTypeValue > otherIntTypeValue) {
return Optional.of(thisDataType);
}
return Optional.of(otherDataType);
}
switch (thisFieldType) {
case FLOAT:
if (otherFieldType == RecordFieldType.DOUBLE) {
return Optional.of(otherDataType);
} else if (otherFieldType == RecordFieldType.DECIMAL) {
return Optional.of(otherDataType);
}
break;
case DOUBLE:
if (otherFieldType == RecordFieldType.FLOAT) {
return Optional.of(thisDataType);
} else if (otherFieldType == RecordFieldType.DECIMAL) {
return Optional.of(otherDataType);
}
break;
case DECIMAL:
if (otherFieldType == RecordFieldType.DOUBLE) {
return Optional.of(thisDataType);
} else if (otherFieldType == RecordFieldType.FLOAT) {
return Optional.of(thisDataType);
} else if (otherFieldType == RecordFieldType.DECIMAL) {
final DecimalDataType thisDecimalDataType = (DecimalDataType) thisDataType;
final DecimalDataType otherDecimalDataType = (DecimalDataType) otherDataType;
final int precision = Math.max(thisDecimalDataType.getPrecision(), otherDecimalDataType.getPrecision());
final int scale = Math.max(thisDecimalDataType.getScale(), otherDecimalDataType.getScale());
return Optional.of(RecordFieldType.DECIMAL.getDecimalDataType(precision, scale));
}
break;
case CHAR:
if (otherFieldType == RecordFieldType.STRING) {
return Optional.of(otherDataType);
}
break;
case STRING:
if (otherFieldType == RecordFieldType.CHAR) {
return Optional.of(thisDataType);
}
break;
}
return Optional.empty();
}
private static int getIntegerTypeValue(final RecordFieldType fieldType) {
switch (fieldType) {
case BIGINT:
return 4;
case LONG:
return 3;
case INT:
return 2;
case SHORT:
return 1;
case BYTE:
return 0;
default:
return -1;
}
}
/**
* Converts the specified field data type into a java.sql.Types constant (INTEGER = 4, e.g.)
*
* @param dataType the DataType to be converted
* @return the SQL type corresponding to the specified RecordFieldType
*/
public static int getSQLTypeValue(final DataType dataType) {
if (dataType == null) {
return Types.NULL;
}
RecordFieldType fieldType = dataType.getFieldType();
switch (fieldType) {
case BIGINT:
case LONG:
return Types.BIGINT;
case BOOLEAN:
return Types.BOOLEAN;
case BYTE:
return Types.TINYINT;
case CHAR:
return Types.CHAR;
case DATE:
return Types.DATE;
case DOUBLE:
return Types.DOUBLE;
case FLOAT:
return Types.FLOAT;
case DECIMAL:
return Types.NUMERIC;
case INT:
return Types.INTEGER;
case SHORT:
return Types.SMALLINT;
case STRING:
return Types.VARCHAR;
case TIME:
return Types.TIME;
case TIMESTAMP:
return Types.TIMESTAMP;
case ARRAY:
return Types.ARRAY;
case MAP:
case RECORD:
return Types.STRUCT;
case CHOICE:
throw new IllegalTypeConversionException("Cannot convert CHOICE, type must be explicit");
default:
throw new IllegalTypeConversionException("Cannot convert unknown type " + fieldType.name());
}
}
public static boolean isScalarValue(final DataType dataType, final Object value) {
final RecordFieldType fieldType = dataType.getFieldType();
final RecordFieldType chosenType;
if (fieldType == RecordFieldType.CHOICE) {
final ChoiceDataType choiceDataType = (ChoiceDataType) dataType;
final DataType chosenDataType = chooseDataType(value, choiceDataType);
if (chosenDataType == null) {
return false;
}
chosenType = chosenDataType.getFieldType();
} else {
chosenType = fieldType;
}
switch (chosenType) {
case ARRAY:
case MAP:
case RECORD:
return false;
}
return true;
}
public static Charset getCharset(String charsetName) {
if(charsetName == null) {
return StandardCharsets.UTF_8;
} else {
return Charset.forName(charsetName);
}
}
/**
* Returns true if the given value is an integer value and fits into a float variable without precision loss. This is
* decided based on the numerical value of the input and the significant bytes used in the float.
*
* @param value The value to check.
*
* @return True in case of the value meets the conditions, false otherwise.
*/
public static boolean isIntegerFitsToFloat(final Object value) {
if (!(value instanceof Integer)) {
return false;
}
final int intValue = (Integer) value;
return MIN_GUARANTEED_PRECISE_WHOLE_IN_FLOAT <= intValue && intValue <= MAX_GUARANTEED_PRECISE_WHOLE_IN_FLOAT;
}
/**
* Returns true if the given value is a long value and fits into a float variable without precision loss. This is
* decided based on the numerical value of the input and the significant bytes used in the float.
*
* @param value The value to check.
*
* @return True in case of the value meets the conditions, false otherwise.
*/
public static boolean isLongFitsToFloat(final Object value) {
if (!(value instanceof Long)) {
return false;
}
final long longValue = (Long) value;
return MIN_GUARANTEED_PRECISE_WHOLE_IN_FLOAT <= longValue && longValue <= MAX_GUARANTEED_PRECISE_WHOLE_IN_FLOAT;
}
/**
* Returns true if the given value is a long value and fits into a double variable without precision loss. This is
* decided based on the numerical value of the input and the significant bytes used in the double.
*
* @param value The value to check.
*
* @return True in case of the value meets the conditions, false otherwise.
*/
public static boolean isLongFitsToDouble(final Object value) {
if (!(value instanceof Long)) {
return false;
}
final long longValue = (Long) value;
return MIN_GUARANTEED_PRECISE_WHOLE_IN_DOUBLE <= longValue && longValue <= MAX_GUARANTEED_PRECISE_WHOLE_IN_DOUBLE;
}
/**
* Returns true if the given value is a BigInteger value and fits into a float variable without precision loss. This is
* decided based on the numerical value of the input and the significant bytes used in the float.
*
* @param value The value to check.
*
* @return True in case of the value meets the conditions, false otherwise.
*/
public static boolean isBigIntFitsToFloat(final Object value) {
if (!(value instanceof BigInteger)) {
return false;
}
final BigInteger bigIntValue = (BigInteger) value;
return bigIntValue.compareTo(MIN_FLOAT_VALUE_IN_BIGINT) >= 0 && bigIntValue.compareTo(MAX_FLOAT_VALUE_IN_BIGINT) <= 0;
}
/**
* Returns true if the given value is a BigInteger value and fits into a double variable without precision loss. This is
* decided based on the numerical value of the input and the significant bytes used in the double.
*
* @param value The value to check.
*
* @return True in case of the value meets the conditions, false otherwise.
*/
public static boolean isBigIntFitsToDouble(final Object value) {
if (!(value instanceof BigInteger)) {
return false;
}
final BigInteger bigIntValue = (BigInteger) value;
return bigIntValue.compareTo(MIN_DOUBLE_VALUE_IN_BIGINT) >= 0 && bigIntValue.compareTo(MAX_DOUBLE_VALUE_IN_BIGINT) <= 0;
}
/**
* Returns true in case the incoming value is a double which is within the range of float variable type.
*
* <p>
* Note: the method only considers the covered range but not precision. The reason for this is that at this point the
* double representation might already slightly differs from the original text value.
* </p>
*
* @param value The value to check.
*
* @return True in case of the double value fits to float data type.
*/
public static boolean isDoubleWithinFloatInterval(final Object value) {
if (!(value instanceof Double)) {
return false;
}
final Double doubleValue = (Double) value;
return MIN_FLOAT_VALUE_IN_DOUBLE <= doubleValue && doubleValue <= MAX_FLOAT_VALUE_IN_DOUBLE;
}
/**
* Checks if an incoming value satisfies the requirements of a given (numeric) type or any of it's narrow data type.
*
* @param value Incoming value.
* @param fieldType The expected field type.
*
* @return Returns true if the incoming value satisfies the data type of any of it's narrow data types. Otherwise returns false. Only numeric data types are supported.
*/
public static boolean isFittingNumberType(final Object value, final RecordFieldType fieldType) {
if (NUMERIC_VALIDATORS.get(fieldType).test(value)) {
return true;
}
for (final RecordFieldType recordFieldType : fieldType.getNarrowDataTypes()) {
if (NUMERIC_VALIDATORS.get(recordFieldType).test(value)) {
return true;
}
}
return false;
}
}
| apache-2.0 |
lisongshan/causalGraphicalModel | causality/src/main/java/net/graphical/model/causality/graph/model/AdjImpl/GraphBase.java | 10564 | package net.graphical.model.causality.graph.model.AdjImpl;
import net.graphical.model.causality.graph.model.Edge;
import net.graphical.model.causality.graph.model.EdgeType;
import net.graphical.model.causality.graph.model.Node;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by sli on 10/27/15.
*/
public class GraphBase {
protected Vertex[] vertexes;
protected ArrayList<Edge> edges;
private Map<Integer, Integer> NodeNumberToArrayIndexMap = new HashMap<>();
public GraphBase(List<Node> nodes, List<Edge> inputEdges) {
this.vertexes = new Vertex[nodes.size()];
int index = 0;
for(Node node : nodes){
NodeNumberToArrayIndexMap.put(node.getNumber(), index);
vertexes[index++] = new Vertex(this, node);
}
this.edges = new ArrayList<>() ;
for(Edge oldEdge : inputEdges){//make sure levels are there
Edge edge = new Edge(getVertexByNumber(oldEdge.getFirstNode().getNumber()).getNode()
,getVertexByNumber(oldEdge.getSecondNode().getNumber()).getNode()
, oldEdge.getEdgeType()
);
this.edges.add(edge);
vertexes[NodeNumberToArrayIndexMap.get(edge.getFirstNode().getNumber())].addEdge(edge);
vertexes[NodeNumberToArrayIndexMap.get(edge.getSecondNode().getNumber()) ].addEdge(edge);
}
}
public List<Vertex> getVertexes() {
return Arrays.asList(vertexes);
}
public Vertex getVertexByNumber(int nodeNumber){
return vertexes[NodeNumberToArrayIndexMap.get(nodeNumber)];
}
public boolean isDirectedGraph(){
return edges.stream().filter(e->!e.getEdgeType().isDirected()).collect(Collectors.toList()).isEmpty();
}
public boolean isUnDirectedGraph(){
return edges.stream().filter(e->e.getEdgeType().isDirected()).collect(Collectors.toList()).isEmpty();
}
public List<Edge> getEdges() {
return edges;
}
public void exploreReset() {
for (int i = 0; i < vertexes.length; i++){
vertexes[i].setIsExplored(false);
}
}
public List<Node> getNodes() {
return Arrays.asList(vertexes).stream().map(v -> v.getNode()).collect(Collectors.toList());
}
//follow algorithm presented in REF_UNO
//Directed Edges are ignored.
public List<List<Node>> getAllCliques(){
return getAllCliques(getNodes());
}
public List<List<Node>> getAllCliques(List<Node> subNodes){
SortedSet<Node> CAND_Empty = new TreeSet<Node>() ;//vertexes neigbor to all vertexes of clique K
CAND_Empty.addAll(subNodes);
Map<List<Node>, SortedSet<Node>> cliqueToCandKMap = new HashMap<>();
cliqueToCandKMap.put(Arrays.asList(), CAND_Empty);
List<List<Node>> result = new ArrayList<>();
while(!cliqueToCandKMap.isEmpty()){
List<List<Node>> cliques = new ArrayList<>();
Map<List<Node>, SortedSet<Node>> newCliqueToCandKMap = new HashMap<>();
for(List<Node> clique : cliqueToCandKMap.keySet()){
cliques.add(clique);
//update newCliqueToCandKMap
SortedSet<Node> cand = cliqueToCandKMap.get(clique);
for(Node node : cand){
if(node.getNumber() > tail(clique)){
List<Node> newClique = new ArrayList<>();
newClique.addAll(clique);
newClique.add(node);
newCliqueToCandKMap.put(newClique, updateCand(cand, node));
}
}
}
result.addAll(cliques);
cliqueToCandKMap = newCliqueToCandKMap;
}
return result;
}
private SortedSet<Node> updateCand(SortedSet<Node> cand, Node node) {
Vertex v = getVertexByNumber(node.getNumber());
Set<Node> neighbors = new TreeSet<>(v.getNeighbors());
TreeSet<Node> newCand = new TreeSet<>(cand);
newCand.retainAll(neighbors);
return newCand;
}
private int tail(List<Node> clique) {
if(clique.isEmpty())
return -1;
return clique.stream().map(node -> new Integer(node.getNumber())).max((i1,i2) -> i1 - i2).get().intValue();
}
//Bron–Kerbosch algorithm: standard
//Directed edges are ignored.
public List<List<Node>> getAllMaxmalCliques_standard(){
List<List<Node>> result = new ArrayList<>();
doBronKerbosch_standard(new ArrayList<>(), new TreeSet<>(getNodes()), new TreeSet<>(), result);
return result;
}
//Directed edges are ignored.
public List<List<Node>> getAllMaximalCliques(List<Node> subNodes){
List<List<Node>> result = new ArrayList<>();
doBronKerbosch_standard(new ArrayList<>(), new TreeSet<>(subNodes), new TreeSet<>(), result);
return result;
}
public List<ConnectedUndirectedGraph> getChainComponents(){
List<Edge> edges = new ArrayList<>();
for(Edge edge: getEdges()){
if(!edge.isDirected()){
edges.add(edge);
}
}
UndirectedGraph ug = new UndirectedGraph(getNodes(), edges);
return ug.getConnectedComponents();
}
/**
* algrothm: REF_CK
* @param R
* @param P
* @param X
* @param result
*
* R is a clique
* Constraints between R,P,X:
* P is subset of CAND(R)
* R and X cannot be neigbors (any)
*
* Important: directed edges are ignored.
*/
public void doBronKerbosch_standard(List<Node> R, TreeSet<Node> P, TreeSet<Node> X, List<List<Node>> result ){
if(X.isEmpty() && P.isEmpty()){
List<Node> clique = new ArrayList<>(R);
result.add (clique);
R.clear();
}
else
{
int size = P.size();
for(int i = 0; i < size; i++){
Node node = P.first();
P.remove(node);
List<Node> newR = new ArrayList<>(R);
newR.add(node);
TreeSet newP = new TreeSet(P);
newP.retainAll(getVertexByNumber(node.getNumber()).getNeighbors());
TreeSet newX = new TreeSet(X);
newX.retainAll(getVertexByNumber(node.getNumber()).getNeighbors());
doBronKerbosch_standard(newR, newP, newX, result);
X.add(node);
}
}
}
public List<List<Node>> getAllMaxmalCliques_pivot(){
List<List<Node>> result = new ArrayList<>();
doBronKerbosch_pivot(new ArrayList<>(), new TreeSet<>(getNodes()), new TreeSet<>(), result);
return result;
}
//algrothm: REF_CK
private void doBronKerbosch_pivot(List<Node> R, TreeSet<Node> P, TreeSet<Node> X, List<List<Node>> result ){
if(X.isEmpty() && P.isEmpty()){
List<Node> clique = new ArrayList<>(R);
result.add (clique);
R.clear();
}
else
{
Node pivotNode = getPivotNode(P);
int size = P.size();
for(int i = 0; i < size; i++){
if(getVertexByNumber(pivotNode.getNumber()).isNeighor(pivotNode)){
continue;
}
Node node = P.first();
P.remove(node);
List<Node> newR = new ArrayList<>(R);
newR.add(node);
TreeSet newP = new TreeSet(P);
newP.retainAll(getVertexByNumber(node.getNumber()).getNeighbors());
TreeSet newX = new TreeSet(X);
newX.retainAll(getVertexByNumber(node.getNumber()).getNeighbors());
doBronKerbosch_pivot(newR, newP, newX, result);
X.add(node);
}
}
}
private Node getPivotNode(TreeSet<Node> p) {
//just one way of chosing pivot node;
if(p.isEmpty())
return null;
return p.stream().max((n1,n2)-> getVertexByNumber(n1.getNumber()).getDegree() - getVertexByNumber(n2.getNumber()).getDegree()).get();
}
public GraphBase subtract(List<Node> cliqueC) {
List<Node> nodeList = getNodes().stream().filter(n-> !cliqueC.contains(n)).collect(Collectors.toList());
List<Edge> edgeList = getEdges().stream().filter(e -> !e.hasNodeIn(cliqueC)).collect(Collectors.toList());;
return new GraphBase(nodeList, edgeList);
}
public boolean hasSameEdges(ChainGraph g0) {
Set<Edge> thisEdgeSet = new HashSet<>(this.getEdges());
Set<Edge> thatEdgeSet = new HashSet<>(g0.getEdges());
return thisEdgeSet.equals(thatEdgeSet);
}
public void removeEdge(Node v, Node u) {
Edge found = findEdge(v, u);
edges.remove(found);
//update Vertex edge list;
Vertex vV = getVertexByNumber(v.getNumber());
vV.removeEdge(found);
Vertex uV = getVertexByNumber(u.getNumber());
uV.removeEdge(found);
}
public void addDirectedEdge(Node u, Node v) {
//add u->u, where u, v is already in graph
Edge newEdge = new Edge(u, v, EdgeType.DIRECTED_PLUS);
edges.add(newEdge);
//update Vertex edge list;
Vertex vV = getVertexByNumber(v.getNumber());
vV.addEdge(newEdge);
Vertex uV = getVertexByNumber(u.getNumber());
uV.addEdge(newEdge);
}
public Edge findEdge(Node v, Node u) {
for(Edge edge : edges){
if(edge.hasNode(v) && edge.hasNode(u)){
return edge;
}
}
return null;
}
public void turnDirectedEdge(Node v, Node u) {
removeEdge(v, u);
addDirectedEdge(u,v);
}
public int noOfUndirectEdge() {
int count = 0;
for(Edge edge : edges){
if(!edge.getEdgeType().isDirected()){
count ++;
}
}
return count;
}
public int noOfDirectEdge() {
int count = 0;
for(Edge edge : edges){
if(edge.getEdgeType().isDirected()){
count ++;
}
}
return count;
}
public int getArrayIndex(int number) {
return NodeNumberToArrayIndexMap.get(number);
}
@Override
public String toString(){
String str = "number of edges: " + edges.size() + "\n";
for(Edge edge : edges){
str += edge.toString() + "\n";
}
return str;
}
}
| apache-2.0 |
vivchar/RendererRecyclerViewAdapter | rendererrecyclerviewadapter/src/main/java/com/github/vivchar/rendererrecyclerviewadapter/DiffCallback.java | 248 | package com.github.vivchar.rendererrecyclerviewadapter;
import androidx.recyclerview.widget.DiffUtil;
/**
* Created by Vivchar Vitaly on 21.10.17.
*/
public abstract class DiffCallback <BM extends ViewModel> extends DiffUtil.ItemCallback<BM> {} | apache-2.0 |
gspandy/divconq | divconq.core/src/main/java/divconq/log/Logger.java | 16322 | /* ************************************************************************
#
# DivConq
#
# http://divconq.com/
#
# Copyright:
# Copyright 2014 eTimeline, LLC. All rights reserved.
#
# License:
# See the license.txt file in the project's top-level directory for details.
#
# Authors:
# * Andy White
#
************************************************************************ */
package divconq.log;
import io.netty.util.ResourceLeakDetector;
import io.netty.util.ResourceLeakDetector.Level;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.io.File;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.concurrent.locks.ReentrantLock;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import divconq.lang.Memory;
import divconq.lang.op.OperationContext;
import divconq.lang.op.OperationResult;
import divconq.locale.LocaleUtil;
import divconq.util.HexUtil;
import divconq.xml.XElement;
/**
* When logging messages to the debug log each message has a debug level.
* The logger has a filter level and messages of lower priority than the
* current debug level will not be logged.
*
* Note that 99% of the time the "current" debug level is determined by
* the current TaskContext. The preferred way to log messages is through
* the TaskContext or through an OperationResult. Ultimately a filter
* is used to determine what should go in the log.
*
* In fact, when you call "void error(String message, String... tags)"
* and other logging methods, theses methods will lookup the current
* task context. So it is more efficient to work directly with task
* context, however, occasional calls to these global logger methods
* are fine.
*
* @author Andy
*
*/
public class Logger {
static protected DebugLevel globalLevel = DebugLevel.Info;
static protected String locale = Locale.getDefault().toString();
// typically task logging is handled by a service on the bus, but on occasions
// we want it to log to the file as well, from settings change this to 'true'
static protected boolean toFile = true;
static protected boolean toConsole = true;
static protected PrintWriter logWriter = null;
static protected ReentrantLock writeLock = new ReentrantLock();
static protected long filestart = 0;
static protected ILogHandler handler = null;
static protected XElement config = null;
static public DebugLevel getGlobalLevel() {
return Logger.globalLevel;
}
static public void setGlobalLevel(DebugLevel v) {
Logger.globalLevel = v;
// keep hub context up to date
OperationContext.updateHubContext();
}
static public String getLocale() {
return Logger.locale;
}
static public void setLocale(String v) {
Logger.locale = v;
// keep hub context up to date
OperationContext.updateHubContext();
}
static public void setLogHandler(ILogHandler v) {
Logger.handler = v;
}
static public void setToConsole(boolean v) {
Logger.toConsole = v;
}
/**
* Called from Hub.start this method configures the logging features.
*
* @param config xml holding the configuration
*/
static public void init(XElement config) {
Logger.config = config;
// TODO return operation result
// TODO load levels, path etc
// include a setting for startup logging - if present set the TC log level directly
Logger.startNewLogFile();
// set by operation context init
//Logger.locale = LocaleUtil.getDefaultLocale();
// From here on we can use netty and so we need the logger setup
InternalLoggerFactory.setDefaultFactory(new divconq.log.netty.LoggerFactory());
if (Logger.config != null) {
// set by operation context init
//if (Logger.config.hasAttribute("Level"))
// Logger.globalLevel = DebugLevel.parse(Logger.config.getAttribute("Level"));
if (Logger.config.hasAttribute("NettyLevel")) {
ResourceLeakDetector.setLevel(Level.valueOf(Logger.config.getAttribute("NettyLevel")));
Logger.debug("Netty Level set to: " + ResourceLeakDetector.getLevel());
}
else if (!"none".equals(System.getenv("dcnet"))) {
// TODO anything more we should do here? maybe paranoid isn't helpful?
}
// set by operation context init
//if (Logger.config.hasAttribute("Locale"))
// Logger.locale = Logger.config.getAttribute("Locale");
}
}
static protected void startNewLogFile() {
try {
File logfile = new File("./logs/"
+ DateTimeFormat.forPattern("yyyyMMdd'_'HHmmss").print(new DateTime(DateTimeZone.UTC))
+ ".log");
if (!logfile.getParentFile().exists())
if (!logfile.getParentFile().mkdirs())
Logger.error("Unable to create logs folder.");
logfile.createNewFile();
if (Logger.logWriter != null) {
Logger.logWriter.flush();
Logger.logWriter.close();
}
Logger.trace("Opening log file: " + logfile.getCanonicalPath());
Logger.logWriter = new PrintWriter(logfile, "utf-8");
Logger.filestart = System.currentTimeMillis();
}
catch (Exception x) {
Logger.error("Unable to create log file: " + x);
}
}
/*
* In a distributed setup, DivConq may route logging to certain Hubs and
* bypass the local log file. During shutdown logging returns to local
* log file so that the dcBus can shutdown and stop routing the messages.
* @param or
*/
static public void stop(OperationResult or) {
// TODO return operation result
Logger.toFile = true; // go back to logging to file
// TODO say no to database
}
static public boolean isDebug() {
OperationContext ctx = OperationContext.get();
DebugLevel setlevel = (ctx != null) ? ctx.getLevel() : Logger.globalLevel;
return (setlevel.getCode() >= DebugLevel.Debug.getCode());
}
static public boolean isTrace() {
OperationContext ctx = OperationContext.get();
DebugLevel setlevel = (ctx != null) ? ctx.getLevel() : Logger.globalLevel;
return (setlevel.getCode() >= DebugLevel.Trace.getCode());
}
/*
* Insert a (string) message into the log
*
* @param message error text
* @param tags searchable values associated with the message, key-value pairs can be created by putting two tags adjacent
*/
static public void error(String message, String... tags) {
Logger.log(OperationContext.get(), DebugLevel.Error, message, tags);
}
/*
* Insert a (string) message into the log
*
* @param message warning text
* @param tags searchable values associated with the message, key-value pairs can be created by putting two tags adjacent
*/
static public void warn(String message, String... tags) {
Logger.log(OperationContext.get(), DebugLevel.Warn, message, tags);
}
/*
* Insert a (string) message into the log
*
* @param message info text
* @param tags searchable values associated with the message, key-value pairs can be created by putting two tags adjacent
*/
static public void info(String message, String... tags) {
Logger.log(OperationContext.get(), DebugLevel.Info, message, tags);
}
/*
* Insert a (string) message into the log
*
* @param accessCode to translate
* @param locals for the translation
*/
static public void debug(String message, String... tags) {
Logger.log(OperationContext.get(), DebugLevel.Debug, message, tags);
}
/*
* Insert a (string) message into the log
*
* @param accessCode to translate
* @param locals for the translation
*/
static public void trace(String message, String... tags) {
Logger.log(OperationContext.get(), DebugLevel.Trace, message, tags);
}
/*
* Insert a (string) message into the log
*
* @param code to translate
* @param params for the translation
*/
static public void errorTr(long code, Object... params) {
Logger.log(OperationContext.get(), DebugLevel.Error, code, params);
}
/*
* Insert a (string) message into the log
*
* @param code to translate
* @param params for the translation
*/
static public void warnTr(long code, Object... params) {
Logger.log(OperationContext.get(), DebugLevel.Warn, code, params);
}
/*
* Insert a (string) message into the log
*
* @param code to translate
* @param params for the translation
*/
static public void infoTr(long code, Object... params) {
Logger.log(OperationContext.get(), DebugLevel.Info, code, params);
}
/*
* Insert a (string) message into the log
*
* @param code to translate
* @param params for the translation
*/
static public void traceTr(long code, Object... params) {
Logger.log(OperationContext.get(), DebugLevel.Trace, code, params);
}
/*
* Insert a (string) translated message into the log
*
* @param ctx context for log settings, null for none
* @param level message level
* @param code to translate
* @param params for the translation
*/
static public void log(OperationContext ctx, DebugLevel level, long code, Object... params) {
Logger.log(ctx, level, LocaleUtil.tr(Logger.locale, "_code_" + code, params), "Code", code + "");
}
/*
* Insert a (string) message into the log
*
* @param ctx context for log settings, null for none
* @param level message level
* @param message text to store in log
* @param tags searchable values associated with the message, key-value pairs can be created by putting two tags adjacent
*/
static public void log(OperationContext ctx, DebugLevel level, String message, String... tags) {
DebugLevel setlevel = (ctx != null) ? ctx.getLevel() : Logger.globalLevel;
// do not log, is being filtered
if (setlevel.getCode() < level.getCode())
return;
Logger.logWr((ctx != null) ? ctx.getOpId() : null, level, message, tags);
}
/*
* Insert a (string) translated message into the log
*
* @param ctx context for log settings, null for none
* @param level message level
* @param code to translate
* @param params for the translation
*/
static public void logWr(String taskid, DebugLevel level, long code, Object... params) {
Logger.logWr(taskid, level, LocaleUtil.tr(Logger.locale, "_code_" + code, params), "Code", code + "");
}
/*
* don't check, just write
*
* @param taskid
* @param level
* @param message
* @param tags
*/
static public void logWr(String taskid, DebugLevel level, String message, String... tags) {
String indicate = "M" + level.getIndicator();
/* TODO
if (Logger.toDatabase) {
Message lmsg = new Message("Logger");
lmsg.addHeader("Op", "Log");
lmsg.addHeader("Indicator", indicate);
lmsg.addHeader("Occurred", occur);
lmsg.addHeader("Tags", tagvalue);
lmsg.addStringAttachment(message);
Hub.instance.getBus().sendMessage(lmsg);
}
*/
// write to file if not a Task or if File Tasks is flagged
if (Logger.toFile || Logger.toConsole) {
if (message != null)
message = message.replace("\n", "\n\t"); // tab sub-lines
Logger.write(taskid, indicate, message, tags);
}
}
/*
* Insert a chunk of hex encoded memory into the log
*
* @param ctx context for log settings, null for none
* @param level message level
* @param data memory to hex encode and store
* @param tags searchable values associated with the message, key-value pairs can be created by putting two tags adjacent
*/
static public void log(OperationContext ctx, DebugLevel level, Memory data, String... tags) {
DebugLevel setlevel = (ctx != null) ? ctx.getLevel() : Logger.globalLevel;
// do not log, is being filtered
if (setlevel.getCode() < level.getCode())
return;
String indicate = "H" + level.getIndicator();
/* TODO
if (tc != null) {
Message lmsg = new Message("Logger");
lmsg.addHeader("Op", "Log");
lmsg.addHeader("Indicator", indicate);
lmsg.addHeader("Occurred", occur);
lmsg.addHeader("Tags", tagvalue);
lmsg.addAttachment(data);
Hub.instance.getBus().sendMessage(lmsg);
}
*/
// write to file if not a Task or if File Tasks is flagged
if (Logger.toFile || Logger.toConsole)
Logger.write((ctx != null) ? ctx.getOpId() : null, indicate, HexUtil.bufferToHex(data), tags);
}
/*
* A boundary delineates in section of a task log from another, making it
* easier for a log viewer to organize the content. Boundary's are treated
* like "info" messages, if only errors or warnings are being logged then
* the boundary entry will be skipped.
*
* @param ctx context for log settings, null for none
* @param tags searchable values associated with the message, key-value pairs can be created by putting two tags adjacent
*/
static public void boundary(OperationContext ctx, String... tags) {
DebugLevel setlevel = (ctx != null) ? ctx.getLevel() : Logger.globalLevel;
// do not log, is being filtered
if (setlevel.getCode() < DebugLevel.Info.getCode())
return;
Logger.boundaryWr((ctx != null) ? ctx.getOpId() : null, tags);
}
/*
* Don't check, just write
*
* @param taskid
* @param tags
*/
static public void boundaryWr(String taskid, String... tags) {
/* TODO
if (tc != null) {
Message lmsg = new Message("Logger");
lmsg.addHeader("Op", "Log");
lmsg.addHeader("Indicator", "B");
lmsg.addHeader("Occurred", occur);
lmsg.addHeader("Tags", tagvalue);
Hub.instance.getBus().sendMessage(lmsg);
}
*/
// write to file if not a Task or if File Tasks is flagged
if (Logger.toFile || Logger.toConsole)
Logger.write(taskid, "B ", "", tags);
}
static protected void write(String taskid, String indicator, String message, String... tags) {
if (taskid == null)
taskid = "00000_19700101T000000000Z_000000000000000";
DateTime occur = new DateTime(DateTimeZone.UTC);
String tagvalue = "";
if ((tags != null) && tags.length > 0) {
tagvalue = "|";
for (String tag : tags)
tagvalue += tag + "|";
}
if (Logger.handler != null)
Logger.handler.write(occur.toString(), taskid, indicator, tagvalue, message);
if (tagvalue.length() > 0)
tagvalue += " ";
Logger.write(occur + " " + taskid + " " + indicator + " " + tagvalue + message);
}
static protected void write(String msg) {
if (Logger.toConsole)
System.out.println(msg);
if (!Logger.toFile || (Logger.logWriter == null))
return;
Logger.writeLock.lock();
// start a new log file every 24 hours
if (System.currentTimeMillis() - Logger.filestart > 86400000)
Logger.startNewLogFile();
try {
Logger.logWriter.println(msg);
Logger.logWriter.flush();
}
catch (Exception x) {
// ignore, logger is broken
}
Logger.writeLock.unlock();
}
}
| apache-2.0 |
consulo/hub.consulo.io | backend/src/main/java/consulo/hub/backend/repository/PluginChannelRestController.java | 6497 | package consulo.hub.backend.repository;
import consulo.hub.shared.auth.Roles;
import consulo.hub.shared.auth.domain.UserAccount;
import consulo.hub.shared.repository.PluginChannel;
import consulo.hub.shared.repository.PluginNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Nonnull;
import java.io.File;
/**
* @author VISTALL
* @since 24-Sep-16
*/
@RestController
public class PluginChannelRestController
{
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
private static class NotAuthorizedException extends RuntimeException
{
}
private final PluginChannelsService myUserConfigurationService;
private final PluginDeployService myPluginDeployService;
private final PluginStatisticsService myPluginStatisticsService;
@Autowired
public PluginChannelRestController(@Nonnull PluginChannelsService userConfigurationService,
@Nonnull PluginDeployService pluginDeployService,
@Nonnull PluginStatisticsService pluginStatisticsService)
{
myUserConfigurationService = userConfigurationService;
myPluginDeployService = pluginDeployService;
myPluginStatisticsService = pluginStatisticsService;
}
// api methods
@RequestMapping("/api/repository/download")
public ResponseEntity<?> download(@RequestParam("channel") PluginChannel channel,
@RequestParam("platformVersion") String platformVersion,
@Deprecated @RequestParam(value = "pluginId", required = false) final String pluginId,
@RequestParam(value = "id", required = false /* TODO [VISTALL] remove it after dropping 'pluginId' parameter*/) final String id,
@RequestParam(value = "noTracking", defaultValue = "false", required = false) boolean noTracking,
@RequestParam(value = "platformBuildSelect", defaultValue = "false", required = false) boolean platformBuildSelect,
@RequestParam(value = "zip", defaultValue = "false", required = false) boolean zip,
@RequestParam(value = "viaUpdate", defaultValue = "false", required = false) boolean viaUpdate,
@RequestParam(value = "version", required = false) String version)
{
if(id == null && pluginId == null)
{
throw new IllegalArgumentException("'id' is null");
}
String idValue = id;
if(pluginId != null)
{
idValue = pluginId;
}
PluginChannelService channelService = myUserConfigurationService.getRepositoryByChannel(channel);
String idNew = idValue;
if(zip)
{
idNew = idValue + "-zip";
}
PluginNode select = channelService.select(platformVersion, idNew, version, platformBuildSelect);
if(select == null)
{
idNew = idValue;
select = channelService.select(platformVersion, idNew, version, platformBuildSelect);
}
if(select == null)
{
return ResponseEntity.notFound().build();
}
if(!noTracking)
{
myPluginStatisticsService.increaseDownload(idNew, channel, select.version, platformVersion, viaUpdate);
}
File targetFile = select.targetFile;
assert targetFile != null;
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + targetFile.getName() + "\"").body(new FileSystemResource(targetFile));
}
@RequestMapping(value = "/api/repository/platformDeploy", method = RequestMethod.POST)
public PluginNode platformDeploy(@RequestParam("channel") PluginChannel channel,
@RequestParam("file") MultipartFile file,
@RequestParam(value = "history", required = false) MultipartFile history,
@RequestParam("platformVersion") int platformVersion,
@AuthenticationPrincipal UserAccount userAccount) throws Exception
{
if(!hasRole(userAccount, Roles.ROLE_SUPERDEPLOYER))
{
throw new NotAuthorizedException();
}
return myPluginDeployService.deployPlatform(channel, platformVersion, file, history);
}
@RequestMapping(value = "/api/repository/pluginDeploy", method = RequestMethod.POST)
public PluginNode pluginDeploy(@RequestParam("channel") PluginChannel channel,
@RequestParam("file") MultipartFile file,
@RequestParam(value = "history", required = false) MultipartFile history,
@AuthenticationPrincipal UserAccount userAccount) throws Exception
{
if(!hasRole(userAccount, Roles.ROLE_SUPERDEPLOYER))
{
throw new NotAuthorizedException();
}
return myPluginDeployService.deployPlugin(channel, () -> history == null ? null : history.getInputStream(), file::getInputStream);
}
private static boolean hasRole(UserAccount userAccount, String role)
{
return userAccount.getAuthorities().contains(new SimpleGrantedAuthority(role));
}
@RequestMapping("/api/repository/list")
public PluginNode[] list(@RequestParam("channel") PluginChannel channel,
@RequestParam("platformVersion") String platformVersion,
@RequestParam(value = "platformBuildSelect", defaultValue = "false", required = false) boolean platformBuildSelect)
{
PluginChannelService channelService = myUserConfigurationService.getRepositoryByChannel(channel);
return channelService.select(myPluginStatisticsService, platformVersion, platformBuildSelect);
}
@RequestMapping("/api/repository/info")
public ResponseEntity<PluginNode> info(@RequestParam("channel") PluginChannel channel,
@RequestParam("platformVersion") String platformVersion,
@RequestParam("id") final String id,
@RequestParam(value = "zip", defaultValue = "false", required = false) boolean zip,
@RequestParam(value = "version") String version)
{
PluginChannelService channelService = myUserConfigurationService.getRepositoryByChannel(channel);
String idNew = id;
if(zip)
{
idNew = id + "-zip";
}
PluginNode select = channelService.select(platformVersion, idNew, version, true);
if(select == null)
{
idNew = id;
select = channelService.select(platformVersion, idNew, version, true);
}
if(select == null)
{
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
return ResponseEntity.ok(select.clone());
}
}
| apache-2.0 |
naveenmadhire/json-wikipedia | src/main/java/it/cnr/isti/hpc/wikipedia/reader/WikipediaArticleReader.java | 5043 | /**
* Copyright 2011 Diego Ceccarelli
*
* 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 it.cnr.isti.hpc.wikipedia.reader;
import info.bliki.wiki.dump.IArticleFilter;
import info.bliki.wiki.dump.Siteinfo;
import info.bliki.wiki.dump.WikiArticle;
import info.bliki.wiki.dump.WikiXMLParser;
import it.cnr.isti.hpc.benchmark.Stopwatch;
import it.cnr.isti.hpc.io.IOUtils;
import it.cnr.isti.hpc.log.ProgressLogger;
import it.cnr.isti.hpc.wikipedia.article.Article;
import it.cnr.isti.hpc.wikipedia.article.Article.Type;
import it.cnr.isti.hpc.wikipedia.parser.ArticleParser;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
/**
* A reader that converts a Wikipedia dump in its json dump. The json dump will
* contain all the article in the XML dump, one article per line. Each line will
* be compose by the json serialization of the object Article.
*
* @see Article
*
* @author Diego Ceccarelli, diego.ceccarelli@isti.cnr.it created on 18/nov/2011
*/
public class WikipediaArticleReader {
/**
* Logger for this class
*/
private static final Logger logger = LoggerFactory
.getLogger(WikipediaArticleReader.class);
private WikiXMLParser wxp;
private BufferedWriter out;
private ArticleParser parser;
// private JsonRecordParser<Article> encoder;
private static ProgressLogger pl = new ProgressLogger("parsed {} articles",
10000);
private static Stopwatch sw = new Stopwatch();
/**
* Generates a converter from the xml to json dump.
*
* @param inputFile
* - the xml file (compressed)
* @param outputFile
* - the json output file, containing one article per line (if
* the filename ends with <tt>.gz </tt> the output will be
* compressed).
*
* @param lang
* - the language of the dump
*
*
*/
public WikipediaArticleReader(String inputFile, String outputFile,
String lang) {
this(new File(inputFile), new File(outputFile), lang);
}
/**
* Generates a converter from the xml to json dump.
*
* @param inputFile
* - the xml file (compressed)
* @param outputFile
* - the json output file, containing one article per line (if
* the filename ends with <tt>.gz </tt> the output will be
* compressed).
*
* @param lang
* - the language of the dump
*
*
*/
public WikipediaArticleReader(File inputFile, File outputFile, String lang) {
JsonConverter handler = new JsonConverter();
// encoder = new JsonRecordParser<Article>(Article.class);
parser = new ArticleParser(lang);
try {
wxp = new WikiXMLParser(inputFile.getAbsolutePath(), handler);
} catch (Exception e) {
logger.error("creating the parser {}", e.toString());
System.exit(-1);
}
out = IOUtils.getPlainOrCompressedUTF8Writer(outputFile
.getAbsolutePath());
}
/**
* Starts the parsing
*/
public void start() throws IOException, SAXException {
wxp.parse();
out.close();
logger.info(sw.stat("articles"));
}
private class JsonConverter implements IArticleFilter {
public void process(WikiArticle page, Siteinfo si) {
pl.up();
sw.start("articles");
String title = page.getTitle();
String id = page.getId();
String namespace = page.getNamespace();
Integer integerNamespace = page.getIntegerNamespace();
String timestamp = page.getTimeStamp();
Type type = Type.UNKNOWN;
if (page.isCategory())
type = Type.CATEGORY;
if (page.isTemplate()) {
type = Type.TEMPLATE;
// FIXME just to go fast;
sw.stop("articles");
return;
}
if (page.isProject()) {
type = Type.PROJECT;
// FIXME just to go fast;
sw.stop("articles");
return;
}
if (page.isFile()) {
type = Type.FILE;
// FIXME just to go fast;
sw.stop("articles");
return;
}
if (page.isMain())
type = Type.ARTICLE;
Article article = new Article();
article.setTitle(title);
article.setWikiId(Integer.parseInt(id));
article.setNamespace(namespace);
article.setIntegerNamespace(integerNamespace);
article.setTimestamp(timestamp);
article.setType(type);
parser.parse(article, page.getText());
try {
out.write(article.toJson());
out.write("\n");
} catch (IOException e) {
logger.error("writing the output file {}", e.toString());
System.exit(-1);
}
sw.stop("articles");
return;
}
}
}
| apache-2.0 |
yljnet/Labuy | app/src/main/java/com/netsun/labuy/utils/HttpUtils.java | 1145 | package com.netsun.labuy.utils;
import java.io.IOException;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by Administrator on 2017/2/24.
*/
public class HttpUtils {
public static void get(String url, Callback callback) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(callback);
}
public static void post(String url, RequestBody body, Callback callback) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).post(body).build();
client.newCall(request).enqueue(callback);
}
public static Response get(String url){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
try {
Response response = client.newCall(request).execute();
return response;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
| apache-2.0 |
morungos/turalt-openmentor | src/test/java/com/turalt/openmentor/security/SessionAuthenticationFilterTest.java | 9236 | package com.turalt.openmentor.security;
import static org.easymock.EasyMock.*;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.hamcrest.core.StringContains;
import com.turalt.openmentor.test.AbstractShiroTest;
public class SessionAuthenticationFilterTest extends AbstractShiroTest {
private SessionAuthenticationFilter filter;
private DefaultWebSecurityManager manager;
@Before
public void initialize() {
filter = new SessionAuthenticationFilter();
DefaultWebSessionManager sessions = new DefaultWebSessionManager();
manager = new DefaultWebSecurityManager();
manager.setSessionManager(sessions);
setSecurityManager(manager);
}
@After
public void tearDown() {
manager = null;
setSecurityManager(null);
clearSubject();
}
@Test
public void testGetSetApplicationName() {
Assert.assertEquals("application", filter.getApplicationName());
filter.setApplicationName("awesome");
Assert.assertEquals("awesome", filter.getApplicationName());
}
@Test
public void testGetSetUsernameParam() {
Assert.assertEquals("username", filter.getUsernameParam());
filter.setUsernameParam("awesome");
Assert.assertEquals("awesome", filter.getUsernameParam());
}
@Test
public void testGetSetPasswordParam() {
Assert.assertEquals("password", filter.getPasswordParam());
filter.setPasswordParam("awesome");
Assert.assertEquals("awesome", filter.getPasswordParam());
}
@Test
public void testGetSetAuthcScheme() {
Assert.assertEquals("session", filter.getAuthcScheme());
filter.setAuthcScheme("awesome");
Assert.assertEquals("awesome", filter.getAuthcScheme());
}
@Test
public void testGetSetAuthzScheme() {
Assert.assertEquals("session", filter.getAuthzScheme());
filter.setAuthzScheme("awesome");
Assert.assertEquals("awesome", filter.getAuthzScheme());
}
@Test
public void testGetSetFailureKeyAttribute() {
Assert.assertEquals("shiroLoginFailure", filter.getFailureKeyAttribute());
filter.setFailureKeyAttribute("awesome");
Assert.assertEquals("awesome", filter.getFailureKeyAttribute());
}
@Test
public void testGetSetFailureAttribute() {
MockHttpServletRequest request = new MockHttpServletRequest();
AuthenticationException e = new AuthenticationException("Aaargh");
filter.setFailureAttribute(request, e);
Assert.assertEquals(e.getClass().getName(), request.getAttribute("shiroLoginFailure"));
}
@Test
public void testGetUsername() {
HttpServletRequest request = createMock(HttpServletRequest.class);
expect(request.getParameter("username")).andStubReturn("admin");
replay(request);
Assert.assertEquals("admin", filter.getUsername(request));
}
@Test
public void testGetPassword() {
HttpServletRequest request = createMock(HttpServletRequest.class);
expect(request.getParameter("password")).andStubReturn("junk");
replay(request);
Assert.assertEquals("junk", filter.getPassword(request));
}
@Test
public void testOnLoginFailure() throws UnsupportedEncodingException {
AuthenticationToken token = createMock(AuthenticationToken.class);
replay(token);
AuthenticationException e = createMock(AuthenticationException.class);
expect(e.getMessage()).andStubReturn("Oops: my bad");
replay(e);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Assert.assertEquals(false, filter.onLoginFailure(token, e, request, response));
Assert.assertEquals("application/json", response.getContentType());
Assert.assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatus());
Assert.assertEquals("{\"message\":\"Oops: my bad\"}", response.getContentAsString());
}
@Test
public void testOnAccessDeniedWithoutSession() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContextPath("http://localhost:8666/");
request.setRequestURI("/api/studies");
Assert.assertEquals(false, filter.onAccessDenied(request, response));
Assert.assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
}
/**
* Checks the main login process. This requires a security manager to be set up,
* as it actually goes through the login process.
* @throws Exception
*/
@Test
public void testOnAccessDeniedIncorrectMethod() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContextPath("http://localhost:8666/");
request.setRequestURI("/login.jsp");
request.setMethod("GET");
Assert.assertEquals(false, filter.onAccessDenied(request, response));
Assert.assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
}
/**
* Checks the main login process. This requires a security manager to be set up,
* as it actually goes through the login process.
* @throws Exception
*/
@Test
public void testOnAccessDeniedEmptyLoginRequest() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContextPath("http://localhost:8666/");
request.setRequestURI("/login.jsp");
request.setMethod("POST");
Assert.assertEquals(false, filter.onAccessDenied(request, response));
Assert.assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatus());
Assert.assertEquals("application/json", response.getContentType());
Gson gson = new Gson();
JsonObject data = gson.fromJson(response.getContentAsString(), JsonObject.class);
Assert.assertTrue(data.isJsonObject());
Assert.assertTrue(data.has("message"));
Assert.assertTrue(data.get("message").isJsonPrimitive());
Assert.assertThat(data.get("message").getAsString(), StringContains.containsString("Authentication failed"));
}
/**
* Checks the main login process with a real username and password.
* @throws Exception
*/
@Test
public void testOnAccessDeniedValidLoginRequest() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContextPath("http://localhost:8666/");
request.setRequestURI("/login.jsp");
request.setMethod("POST");
request.setParameter("username", "user");
request.setParameter("password", "password");
PrincipalCollection principals = new SimplePrincipalCollection("user", "mock");
AuthenticationInfo info = createMock(AuthenticationInfo.class);
expect(info.getPrincipals()).andStubReturn(principals);
replay(info);
Realm realm = createMock(Realm.class);
expect(realm.supports(anyObject(AuthenticationToken.class))).andStubReturn(true);
expect(realm.getAuthenticationInfo(anyObject(AuthenticationToken.class))).andStubReturn(info);
replay(realm);
manager.setRealm(realm);
Subject subjectUnderTest = new Subject.Builder(manager).buildSubject();
setSubject(subjectUnderTest);
Assert.assertEquals(false, filter.onAccessDenied(request, response));
Assert.assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, response.getStatus());
}
/**
* Checks the main login process with a real username and password.
* @throws Exception
*/
@Test
public void testOnAccessDeniedInvalidLoginRequest() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContextPath("http://localhost:8666/");
request.setRequestURI("/login.jsp");
request.setMethod("POST");
request.setParameter("username", "user");
request.setParameter("password", "password");
// Null is the correct expected response for a missing account, which is enough for now
Realm realm = createMock(Realm.class);
expect(realm.supports(anyObject(AuthenticationToken.class))).andStubReturn(true);
expect(realm.getAuthenticationInfo(anyObject(AuthenticationToken.class))).andStubReturn(null);
replay(realm);
manager.setRealm(realm);
Subject subjectUnderTest = new Subject.Builder(manager).buildSubject();
setSubject(subjectUnderTest);
Assert.assertEquals(false, filter.onAccessDenied(request, response));
Assert.assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatus());
}
} | apache-2.0 |
schlusslicht/Cheiron | src/Cheiron/Datasource/Datasource.java | 413 | package Cheiron.Datasource;
import java.util.Map;
public abstract class Datasource {
public abstract Map<String, Map<String, String>> getData() throws Exception;
public Object get(String field) throws Exception {
return this.getClass().getDeclaredField(field).get(this);
}
public void set(String field, Object value) throws Exception {
this.getClass().getDeclaredField(field).set(this, value);
}
}
| apache-2.0 |
equella/Equella | Source/Plugins/Core/com.equella.core/src/com/tle/web/sections/jquery/libraries/JQueryDroppable.java | 1764 | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0, (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tle.web.sections.jquery.libraries;
import com.tle.common.i18n.CurrentLocale;
import com.tle.core.javascript.JavascriptModule;
import com.tle.web.sections.jquery.JQueryLibraryInclude;
import com.tle.web.sections.render.PreRenderable;
@SuppressWarnings("nls")
public class JQueryDroppable implements JavascriptModule {
private static final long serialVersionUID = 1L;
public static final PreRenderable PRERENDER =
new JQueryLibraryInclude(
"jquery.ui.droppable.js",
JQueryUICore.PRERENDER,
JQueryMouse.PRERENDER,
JQueryUIWidget.PRERENDER,
JQueryDraggable.PRERENDER)
.hasMin();
@Override
public String getDisplayName() {
return CurrentLocale.get("com.tle.web.sections.jquery.modules.droppable.name");
}
@Override
public String getId() {
return "droppable";
}
@Override
public Object getPreRenderer() {
return PRERENDER;
}
}
| apache-2.0 |
lucasgrittem/AppsCwb | FuelClubWeb/src/br/com/fuelclub/entity/Dias_Da_Semana.java | 2617 | package br.com.fuelclub.entity;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table (name = "Dias_da_Semana")
public class Dias_Da_Semana {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long diasDaSemana_id;
private String diasDaSemana_descricao;
@ManyToMany
private List<PostoCombustivel> postos;
public Long getDiasDaSemana_id() {
return diasDaSemana_id;
}
public void setDiasDaSemana_id(Long diasDaSemana_id) {
this.diasDaSemana_id = diasDaSemana_id;
}
public String getDiasDaSemana_descricao() {
return diasDaSemana_descricao;
}
public void setDiasDaSemana_descricao(String diasDaSemana_descricao) {
this.diasDaSemana_descricao = diasDaSemana_descricao;
}
public List<PostoCombustivel> getPostos() {
return postos;
}
public void setPostos(List<PostoCombustivel> postos) {
this.postos = postos;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((diasDaSemana_descricao == null) ? 0 : diasDaSemana_descricao.hashCode());
result = prime * result + ((diasDaSemana_id == null) ? 0 : diasDaSemana_id.hashCode());
result = prime * result + ((postos == null) ? 0 : postos.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Dias_Da_Semana other = (Dias_Da_Semana) obj;
if (diasDaSemana_descricao == null) {
if (other.diasDaSemana_descricao != null)
return false;
} else if (!diasDaSemana_descricao.equals(other.diasDaSemana_descricao))
return false;
if (diasDaSemana_id == null) {
if (other.diasDaSemana_id != null)
return false;
} else if (!diasDaSemana_id.equals(other.diasDaSemana_id))
return false;
if (postos == null) {
if (other.postos != null)
return false;
} else if (!postos.equals(other.postos))
return false;
return true;
}
@Override
public String toString() {
return "Dias_Da_Semana [diasDaSemana_descricao=" + diasDaSemana_descricao + "]";
}
public Dias_Da_Semana(Long diasDaSemana_id, String diasDaSemana_descricao, List<PostoCombustivel> postos) {
super();
this.diasDaSemana_id = diasDaSemana_id;
this.diasDaSemana_descricao = diasDaSemana_descricao;
this.postos = postos;
}
public Dias_Da_Semana() {
super();
// TODO Auto-generated constructor stub
}
}
| apache-2.0 |
hmmlopez/citrus | modules/citrus-core/src/main/java/com/consol/citrus/validation/json/JsonPathMessageConstructionInterceptor.java | 4178 | /*
* Copyright 2006-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.consol.citrus.validation.json;
import com.consol.citrus.context.TestContext;
import com.consol.citrus.exceptions.CitrusRuntimeException;
import com.consol.citrus.exceptions.UnknownElementException;
import com.consol.citrus.message.Message;
import com.consol.citrus.message.MessageType;
import com.consol.citrus.validation.interceptor.AbstractMessageConstructionInterceptor;
import com.jayway.jsonpath.*;
import net.minidev.json.parser.JSONParser;
import net.minidev.json.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* @author Christoph Deppisch
* @since 2.3
*/
public class JsonPathMessageConstructionInterceptor extends AbstractMessageConstructionInterceptor {
/** Logger */
private static Logger log = LoggerFactory.getLogger(JsonPathMessageConstructionInterceptor.class);
/** Overwrites message elements before validating (via JSONPath expressions) */
private Map<String, String> jsonPathExpressions = new HashMap<>();
/**
* Default constructor.
*/
public JsonPathMessageConstructionInterceptor() {
super();
}
/**
* Default constructor using fields.
* @param jsonPathExpressions
*/
public JsonPathMessageConstructionInterceptor(Map<String, String> jsonPathExpressions) {
super();
this.jsonPathExpressions = jsonPathExpressions;
}
/**
* Intercept the message payload construction and replace elements identified
* via XPath expressions.
*
* Method parses the message payload to DOM document representation, therefore message payload
* needs to be XML here.
*/
@Override
public Message interceptMessage(Message message, String messageType, TestContext context) {
if (message.getPayload() == null || !StringUtils.hasText(message.getPayload(String.class))) {
return message;
}
String jsonPathExpression = null;
try {
JSONParser parser = new JSONParser(JSONParser.MODE_JSON_SIMPLE);
Object jsonData = parser.parse(message.getPayload(String.class));
DocumentContext documentContext = JsonPath.parse(jsonData);
for (Map.Entry<String, String> entry : jsonPathExpressions.entrySet()) {
jsonPathExpression = entry.getKey();
String valueExpression = context.replaceDynamicContentInString(entry.getValue());
documentContext.set(jsonPathExpression, valueExpression);
if (log.isDebugEnabled()) {
log.debug("Element " + jsonPathExpression + " was set to value: " + valueExpression);
}
}
message.setPayload(jsonData.toString());
} catch (ParseException e) {
throw new CitrusRuntimeException("Failed to parse JSON text", e);
} catch (PathNotFoundException e) {
throw new UnknownElementException(String.format("Could not find element for expression: %s", jsonPathExpression), e);
}
return message;
}
@Override
public boolean supportsMessageType(String messageType) {
return MessageType.JSON.toString().equalsIgnoreCase(messageType);
}
public void setJsonPathExpressions(Map<String, String> jsonPathExpressions) {
this.jsonPathExpressions = jsonPathExpressions;
}
public Map<String, String> getJsonPathExpressions() {
return jsonPathExpressions;
}
}
| apache-2.0 |
stori-es/stori_es | dashboard/src/main/java/org/consumersunion/stories/dashboard/client/application/ui/block/configurator/BlockConfigurator.java | 664 | package org.consumersunion.stories.dashboard.client.application.ui.block.configurator;
import org.consumersunion.stories.common.client.util.Callback;
import org.consumersunion.stories.dashboard.client.application.ui.block.HasValidation;
import com.google.gwt.editor.client.Editor;
/**
* Interface for the various {@link org.consumersunion.stories.common.shared.model.questionnaire.Block} 'configurators'
* used to specify parameters specific to each Block 'type' (e.g., text,
* multi-select, etc.).
*/
public interface BlockConfigurator<T> extends Editor<T>, HasValidation<T> {
void setDoneCallback(Callback<T> doneCallback);
T getEditedValue();
}
| apache-2.0 |
spring-projects/spring-security | config/src/main/java/org/springframework/security/config/http/UserDetailsServiceFactoryBean.java | 5210 | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.http;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.HierarchicalBeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationContextException;
import org.springframework.security.authentication.CachingUserDetailsService;
import org.springframework.security.config.authentication.AbstractUserDetailsServiceBeanDefinitionParser;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.StringUtils;
/**
* Bean used to lookup a named UserDetailsService or AuthenticationUserDetailsService.
*
* @author Luke Taylor
* @since 3.1
*/
public class UserDetailsServiceFactoryBean implements ApplicationContextAware {
private ApplicationContext beanFactory;
UserDetailsService userDetailsService(String id) {
if (!StringUtils.hasText(id)) {
return getUserDetailsService();
}
return (UserDetailsService) this.beanFactory.getBean(id);
}
UserDetailsService cachingUserDetailsService(String id) {
if (!StringUtils.hasText(id)) {
return getUserDetailsService();
}
// Overwrite with the caching version if available
String cachingId = id + AbstractUserDetailsServiceBeanDefinitionParser.CACHING_SUFFIX;
if (this.beanFactory.containsBeanDefinition(cachingId)) {
return (UserDetailsService) this.beanFactory.getBean(cachingId);
}
return (UserDetailsService) this.beanFactory.getBean(id);
}
@SuppressWarnings("unchecked")
AuthenticationUserDetailsService authenticationUserDetailsService(String name) {
UserDetailsService uds;
if (!StringUtils.hasText(name)) {
Map<String, ?> beans = getBeansOfType(AuthenticationUserDetailsService.class);
if (!beans.isEmpty()) {
if (beans.size() > 1) {
throw new ApplicationContextException("More than one AuthenticationUserDetailsService registered."
+ " Please use a specific Id reference.");
}
return (AuthenticationUserDetailsService) beans.values().toArray()[0];
}
uds = getUserDetailsService();
}
else {
Object bean = this.beanFactory.getBean(name);
if (bean instanceof AuthenticationUserDetailsService) {
return (AuthenticationUserDetailsService) bean;
}
else if (bean instanceof UserDetailsService) {
uds = cachingUserDetailsService(name);
if (uds == null) {
uds = (UserDetailsService) bean;
}
}
else {
throw new ApplicationContextException(
"Bean '" + name + "' must be a UserDetailsService or an" + " AuthenticationUserDetailsService");
}
}
return new UserDetailsByNameServiceWrapper(uds);
}
/**
* Obtains a user details service for use in RememberMeServices etc. Will return a
* caching version if available so should not be used for beans which need to separate
* the two.
*/
private UserDetailsService getUserDetailsService() {
Map<String, ?> beans = getBeansOfType(CachingUserDetailsService.class);
if (beans.size() == 0) {
beans = getBeansOfType(UserDetailsService.class);
}
if (beans.size() == 0) {
throw new ApplicationContextException("No UserDetailsService registered.");
}
if (beans.size() > 1) {
throw new ApplicationContextException("More than one UserDetailsService registered. Please "
+ "use a specific Id reference in <remember-me/> or <x509 /> elements.");
}
return (UserDetailsService) beans.values().toArray()[0];
}
@Override
public void setApplicationContext(ApplicationContext beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
private Map<String, ?> getBeansOfType(Class<?> type) {
Map<String, ?> beans = this.beanFactory.getBeansOfType(type);
// Check ancestor bean factories if they exist and the current one has none of the
// required type
BeanFactory parent = this.beanFactory.getParentBeanFactory();
while (parent != null && beans.size() == 0) {
if (parent instanceof ListableBeanFactory) {
beans = ((ListableBeanFactory) parent).getBeansOfType(type);
}
if (parent instanceof HierarchicalBeanFactory) {
parent = ((HierarchicalBeanFactory) parent).getParentBeanFactory();
}
else {
break;
}
}
return beans;
}
}
| apache-2.0 |
tilioteo/vmaps | src/main/java/org/vaadin/gwtgraphics/client/Image.java | 4289 | /*
* Copyright 2011 Henri Kerola
*
* 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 org.vaadin.gwtgraphics.client;
/**
* Image represents a raster image that can be embedded into DrawingArea.
*
* @author Henri Kerola
*
*/
public class Image extends AbstractDrawing implements Sizeable, Positionable, Animatable {
/**
* Create a new Image with the given properties.
*
* @param x
* the x-coordinate position of the top-left corner of the image
* in pixels
* @param y
* the y-coordinate position of the top-left corner of the image
* in pixels
* @param width
* the width of the image in pixels
* @param height
* the height of the image in pixels
* @param href
* URL to an image to be shown.
*/
public Image(int x, int y, int width, int height, String href) {
setX(x);
setY(y);
setWidth(width);
setHeight(height);
setHref(href);
}
@Override
public Class<? extends Drawing> getType() {
return Image.class;
}
@Override
public int getX() {
return getImpl().getX(getElement());
}
@Override
public void setX(int x) {
getImpl().setX(getElement(), x, isAttached());
}
@Override
public int getY() {
return getImpl().getY(getElement());
}
@Override
public void setY(int y) {
getImpl().setY(getElement(), y, isAttached());
}
/**
* Returns the URL of the image currently shown.
*
* @return URL of the image
*/
public String getHref() {
return getImpl().getImageHref(getElement());
}
/**
* Sets the URL of the image to be shown.
*
* @param href
* URL of the image to be shown
*/
public void setHref(String href) {
getImpl().setImageHref(getElement(), href);
}
/**
* Returns the width of the Image in pixels.
*
* @return the width of the Image in pixels
*/
@Override
public int getWidth() {
return getImpl().getWidth(getElement());
}
/**
* Sets the width of the Image in pixels.
*
* @param width
* the new width in pixels
*/
@Override
public void setWidth(int width) {
getImpl().setWidth(getElement(), width);
}
@Override
public void setWidth(String width) {
boolean successful = false;
if (width != null && width.endsWith("px")) {
try {
setWidth(Integer.parseInt(width.substring(0, width.length() - 2)));
successful = true;
} catch (NumberFormatException e) {
}
}
if (!successful) {
throw new IllegalArgumentException("Only pixel units (px) are supported");
}
}
/**
* Returns the height of the Image in pixels.
*
* @return the height of the Image in pixels
*/
@Override
public int getHeight() {
return getImpl().getHeight(getElement());
}
/**
* Sets the height of the Image in pixels.
*
* @param height
* the new height in pixels
*/
@Override
public void setHeight(int height) {
getImpl().setHeight(getElement(), height);
}
@Override
public void setHeight(String height) {
boolean successful = false;
if (height != null && height.endsWith("px")) {
try {
setHeight(Integer.parseInt(height.substring(0, height.length() - 2)));
successful = true;
} catch (NumberFormatException e) {
}
}
if (!successful) {
throw new IllegalArgumentException("Only pixel units (px) are supported");
}
}
@Override
public void setPropertyDouble(String property, double value) {
property = property.toLowerCase();
if ("x".equals(property)) {
setX((int) value);
} else if ("y".equals(property)) {
setY((int) value);
} else if ("width".equals(property)) {
setWidth((int) value);
} else if ("height".equals(property)) {
setHeight((int) value);
} else if ("rotation".equals(property)) {
setRotation((int) value);
}
}
} | apache-2.0 |
newsreader/StreamEventCoreference | src/main/java/eu/newsreader/eventcoreference/output/CorefSetToSem.java | 27687 | package eu.newsreader.eventcoreference.output;
import eu.newsreader.eventcoreference.input.CorefSaxParser;
import eu.newsreader.eventcoreference.objects.CoRefSetAgata;
import eu.newsreader.eventcoreference.objects.CorefTargetAgata;
import eu.newsreader.eventcoreference.objects.Triple;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: kyoto
* Date: 10/11/13
* Time: 11:17 AM
* To change this template use File | Settings | File Templates.
*/
public class CorefSetToSem {
static public void main (String[] args) {
boolean STOP = false;
int sentenceRange = 0;
String eventFilePath = "/Users/kyoto/Desktop/Events/ECB/ECBcorpus_StanfordAnnotation/EECB1.0/results-1/lemma-cross-document-in-topic/" +
"eecb-events-kyoto-first-n-v-token-3.xml.sim.word-baseline.0.coref.xml";
String participantFilePath = "/Users/kyoto/Desktop/Events/ECB/ECBcorpus_StanfordAnnotation/EECB1.0/results-1/lemma-cross-document-in-topic/" +
"participants-30-july-2013.xml.sim.word-baseline.0.coref.xml";
String locationFilePath = "/Users/kyoto/Desktop/Events/ECB/ECBcorpus_StanfordAnnotation/EECB1.0/results-1/lemma-cross-document-in-topic/" +
"Location-26-jul-2013.xml.sim.word-baseline.0.coref.xml";
String timeFilePath = "/Users/kyoto/Desktop/Events/ECB/ECBcorpus_StanfordAnnotation/EECB1.0/results-1/lemma-cross-document-in-topic/" +
"Time-26-jul-2013.xml.sim.word-baseline.0.coref.xml";
String componentId = ".";
String outputlabel = "test";
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.equals("--event") && (args.length>i)) {
eventFilePath = args[i+1];
componentId+="e";
}
else if (arg.equals("--range") && (args.length>i)) {
try {
sentenceRange = Integer.parseInt(args[i+1]);
} catch (NumberFormatException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
else if (arg.equals("--participant") && (args.length>i)) {
participantFilePath = args[i+1];
componentId+="p";
}
else if (arg.equals("--time") && (args.length>i)) {
timeFilePath = args[i+1];
componentId+="t";
}
else if (arg.equals("--location") && (args.length>i)) {
locationFilePath = args[i+1];
componentId+="l";
}
else if (arg.equals("--label") && (args.length>i)) {
outputlabel = args[i+1];
}
}
if (eventFilePath.isEmpty()) {
System.out.println("Missing argument --event <path to coreference events file");
STOP = true;
}
if (participantFilePath.isEmpty()) {
System.out.println("Missing argument --participant <path to coreference participants file");
}
if (timeFilePath.isEmpty()) {
System.out.println("Missing argument --time <path to coreference time file");
}
if (locationFilePath.isEmpty()) {
System.out.println("Missing argument --location <path to coreference location file");
}
if (!STOP) {
try {
// String outputFilePath = eventFilePath+componentId+".sentenceRange."+sentenceRange+"."+outputlabel+"-semevent.xml";
String outputFilePath = new File(eventFilePath).getParent()+"/"+outputlabel+".sentenceRange."+sentenceRange+"."+"semevent.xml";
FileOutputStream fos = new FileOutputStream(outputFilePath);
String str ="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n";
str += "<SEM>"+"\n";
fos.write(str.getBytes());
// we read the events and their components using a coreference parser
// the parser builds up a HashMap with file identifiers as keys and arraylists with elements as data within that file
CorefSaxParser events = new CorefSaxParser();
events.parseFile(eventFilePath);
CorefSaxParser participants = new CorefSaxParser();
if (new File(participantFilePath).exists()) {
participants.parseFile(participantFilePath);
}
CorefSaxParser times = new CorefSaxParser();
if (new File(timeFilePath).exists()) {
times.parseFile(timeFilePath);
}
CorefSaxParser locations = new CorefSaxParser();
if (new File(locationFilePath).exists()) {
locations.parseFile(locationFilePath);
}
/// we first iterate over the map with file identifiers and the event coref maps
Set keySet = events.corefMap.keySet();
Iterator keys = keySet.iterator();
while (keys.hasNext()) {
String key = (String) keys.next();
/// keys are file identifiers
// We now get the components for the key (= particular file identifier), so just for one file
ArrayList<CoRefSetAgata> coRefSetsEventAgatas = events.corefMap.get(key);
ArrayList<CoRefSetAgata> participantSets = participants.corefMap.get(key);
ArrayList<CoRefSetAgata> timeSets = times.corefMap.get(key);
ArrayList<CoRefSetAgata> locationSets = locations.corefMap.get(key);
/// we create the initial output string
str = "<topic name=\""+key+"\" eventCount=\""+ coRefSetsEventAgatas.size()+"\"";
str += " participantCount=\"";
if (participantSets!=null) {
str += participantSets.size()+"\"";
}
else {
str += "0\"";
}
str += " timeCount=\"";
if (timeSets!=null) {
str += timeSets.size()+"\"";
}
else {
str += "0\"";
}
str += " locationCount=\"";
if (locationSets!=null) {
str += locationSets.size()+"\"";
}
else {
str += "0\"";
}
str += ">\n";
fos.write(str.getBytes());
if (coRefSetsEventAgatas !=null) {
/// we iterate over the events of a single file
str = "<semEvents>\n";
fos.write(str.getBytes());
for (int i = 0; i < coRefSetsEventAgatas.size(); i++) {
CoRefSetAgata coRefSetAgata = coRefSetsEventAgatas.get(i);
str = "\t<semEvent id=\""+key+"/e"+ coRefSetAgata.getId()+"\" lcs=\""+ coRefSetAgata.getLcs()+"\" score=\""+ coRefSetAgata.getScore()+"\" synset=\""+ coRefSetAgata.getMostFrequentSynset()+"\" label=\""+ coRefSetAgata.getMostFrequentLemma()+"\" mentions=\""+ coRefSetAgata.getTargets().size()+"\">\n";
fos.write(str.getBytes());
for (int j = 0; j < coRefSetAgata.getTargets().size(); j++) {
CorefTargetAgata eventTarget = coRefSetAgata.getTargets().get(j);
str = "\t"+eventTarget.toString();
fos.write(str.getBytes());
}
str = "\t</semEvent>\n";
fos.write(str.getBytes());
}
str = "</semEvents>\n";
fos.write(str.getBytes());
}
if (participantSets!=null) {
/// we iterate over the participants of a single file
str = "<semAgents>\n";
fos.write(str.getBytes());
for (int i = 0; i < participantSets.size(); i++) {
CoRefSetAgata coRefSetAgata = participantSets.get(i);
str = "\t<semAgent id=\""+key+"/a"+ coRefSetAgata.getId()+"\" lcs=\""+ coRefSetAgata.getLcs()+"\" score=\""+ coRefSetAgata.getScore()+"\" synset=\""+ coRefSetAgata.getMostFrequentSynset()+"\" label=\""+ coRefSetAgata.getMostFrequentLemma()+"\" mentions=\""+ coRefSetAgata.getTargets().size()+"\">\n";
fos.write(str.getBytes());
for (int j = 0; j < coRefSetAgata.getTargets().size(); j++) {
CorefTargetAgata eventTarget = coRefSetAgata.getTargets().get(j);
str = "\t"+eventTarget.toString();
fos.write(str.getBytes());
}
str = "\t</semAgent>\n";
fos.write(str.getBytes());
}
str = "</semAgents>\n";
fos.write(str.getBytes());
}
if (locationSets!=null) {
/// we iterate over the locations of a single file
str = "<semPlaces>\n";
fos.write(str.getBytes());
for (int i = 0; i < locationSets.size(); i++) {
CoRefSetAgata coRefSetAgata = locationSets.get(i);
str = "\t<semPlace id=\""+key+"/p"+ coRefSetAgata.getId()+"\" lcs=\""+ coRefSetAgata.getLcs()+"\" score=\""+ coRefSetAgata.getScore()+"\" synset=\""+ coRefSetAgata.getMostFrequentSynset()+"\" label=\""+ coRefSetAgata.getMostFrequentLemma()+"\" mentions=\""+ coRefSetAgata.getTargets().size()+"\">\n";
fos.write(str.getBytes());
for (int j = 0; j < coRefSetAgata.getTargets().size(); j++) {
CorefTargetAgata eventTarget = coRefSetAgata.getTargets().get(j);
str = "\t"+eventTarget.toString();
fos.write(str.getBytes());
}
str = "\t</semPlace>\n";
fos.write(str.getBytes());
}
str = "</semPlaces>\n";
fos.write(str.getBytes());
}
if (timeSets!=null) {
/// we iterate over the time of a single file
str = "<semTimes>\n";
fos.write(str.getBytes());
for (int i = 0; i < timeSets.size(); i++) {
CoRefSetAgata coRefSetAgata = timeSets.get(i);
str = " <semTime id=\""+key+"/t"+ coRefSetAgata.getId()+"\" lcs=\""+ coRefSetAgata.getLcs()+"\" score=\""+ coRefSetAgata.getScore()+"\" synset=\""+ coRefSetAgata.getMostFrequentSynset()+"\" label=\""+ coRefSetAgata.getMostFrequentLemma()+"\" mentions=\""+ coRefSetAgata.getTargets().size()+"\">\n";
fos.write(str.getBytes());
for (int j = 0; j < coRefSetAgata.getTargets().size(); j++) {
CorefTargetAgata eventTarget = coRefSetAgata.getTargets().get(j);
str = "\t"+eventTarget.toString();
fos.write(str.getBytes());
}
str = "\t</semTime>\n";
fos.write(str.getBytes());
}
str = "</semTimes>\n";
fos.write(str.getBytes());
}
/// now we get the relations
getRelations(fos, events.fileName, coRefSetsEventAgatas, participantSets, timeSets, locationSets, sentenceRange, key);
str = "</topic>\n";
fos.write(str.getBytes());
}
str = "</SEM>\n";
fos.write(str.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
/**
* <semEvents>
<semEvent id="eecb1.0/456>
<target id="corpus/filename_url/t115"/>
</semEvent>
</semEvents>
<semAgents>
<semAgent id="eecb1.0/2">
<target id="corpus/filename_url/t111"/>
</semAgent>
</semAgents>
<semTimes>
<semTime id="eecb1.0/1"/>
</semTimes>
<semPlaces>
<semPlace id="eecb1.0/6"/>
</semPlaces>
<semRelations>
<semRelation id = "eecb1.0/75698" predicate="semHasAgent" subject="eecb1.0/456" object="eecb1.0/2>
<target id="corpus/filename_url/pr23r3"/>
</semRelation>
<semRelation id = "eecb1.0/75698" predicate="semHasTime" subject="eecb1.0/456" object="eecb1.0/2/>
<semRelation id = "eecb1.0/75698" predicate="semHasPlace" subject="eecb1.0/456" object="eecb1.0/2/>
</semRelations>
*/
static void getRelations (FileOutputStream fos, String fileName,
ArrayList<CoRefSetAgata> coRefSetsEventAgatas,
ArrayList<CoRefSetAgata> participantSets,
ArrayList<CoRefSetAgata> timeSets,
ArrayList<CoRefSetAgata> locationSets,
int sentenceRange,
String key
) throws IOException {
String str = "<semRelations>\n";
fos.write(str.getBytes());
int relationCounter = 0;
/// we iterate over the events of a single file
ArrayList<Triple> triplesA = new ArrayList<Triple>();
ArrayList<Triple> triplesP = new ArrayList<Triple>();
ArrayList<Triple> triplesT = new ArrayList<Triple>();
for (int i = 0; i < coRefSetsEventAgatas.size(); i++) {
CoRefSetAgata coRefSetAgata = coRefSetsEventAgatas.get(i);
for (int j = 0; j < coRefSetAgata.getTargets().size(); j++) {
CorefTargetAgata eventTarget = coRefSetAgata.getTargets().get(j);
/// we obtain the sentence ids for the targets of the coreference set of the events
/// this sentence range determines which components belong to the event.
/// by passing in the sentenceRange parameter you can indicate the number of sentences before and after that are also valid contexts
//// if zero the context is restricted to the same sentence
ArrayList<String> rangeOfSentenceIds = getSentenceRange(eventTarget.getSentenceId(), sentenceRange);
if (participantSets!=null) {
// System.out.println("PARTICIPANTS");
for (int s = 0; s < participantSets.size(); s++) {
CoRefSetAgata refSet = participantSets.get(s);
//// loop to add results for range of sentences
for (int k = 0; k < rangeOfSentenceIds.size(); k++) {
String sentenceId = rangeOfSentenceIds.get(k);
if (refSet.containsTargetSentenceId(sentenceId)) {
for (int l = 0; l < refSet.getTargets().size(); l++) {
CorefTargetAgata corefTargetAgata = refSet.getTargets().get(l);
if (eventTarget.getDocId().equals(corefTargetAgata.getDocId())) {
String predicate = "semHasAgent";
String subject = key+"/e"+ coRefSetAgata.getId();
String object = key+"/a"+ refSet.getId();
Triple triple = new Triple(predicate, subject, object);
String target = "\t\t<target id =\""+ eventTarget.getDocId()+"/"+eventTarget.getSentenceId()+"\""+"/>";
target += " <!-- "+eventTarget.getWord()+"--"+predicate+"--"+ corefTargetAgata.getWord()+" -->";
int givenTriple = getTriple(triplesA, triple);
if (givenTriple==-1) {
relationCounter++;
String id = key+"/"+relationCounter;
triple.setId(id);
triple.addMentions(target);
triplesA.add(triple);
}
else {
if (!triplesA.get(givenTriple).getMentions().contains(target)) {
triplesA.get(givenTriple).addMentions(target);
}
}
}
else {
// System.out.println("corefTarget.getDocId() = " + corefTarget.getDocId());
// System.out.println("eventTarget.getDocId() = " + eventTarget.getDocId());
}
}
}
}
}
}
if (timeSets!=null) {
// System.out.println("TIME");
for (int s = 0; s < timeSets.size(); s++) {
CoRefSetAgata refSet = timeSets.get(s);
//// loop to add results for range of sentences
for (int k = 0; k < rangeOfSentenceIds.size(); k++) {
String sentenceId = rangeOfSentenceIds.get(k);
if (refSet.containsTargetSentenceId(sentenceId)) {
for (int l = 0; l < refSet.getTargets().size(); l++) {
CorefTargetAgata corefTargetAgata = refSet.getTargets().get(l);
if (eventTarget.getDocId().equals(corefTargetAgata.getDocId())) {
String predicate = "semHasTime";
String subject = key+"/e"+ coRefSetAgata.getId();
String object = key+"/t"+ refSet.getId();
Triple triple = new Triple(predicate, subject, object);
String target = "\t\t<target id =\""+ eventTarget.getDocId()+"/"+eventTarget.getSentenceId()+"\""+"/>";
target += " <!-- "+eventTarget.getWord()+"--"+predicate+"--"+ corefTargetAgata.getWord()+" -->";
int givenTriple = getTriple(triplesA, triple);
if (givenTriple==-1) {
relationCounter++;
String id = key+"/"+relationCounter;
triple.setId(id);
triple.addMentions(target);
triplesA.add(triple);
}
else {
if (!triplesA.get(givenTriple).getMentions().contains(target)) {
triplesA.get(givenTriple).addMentions(target);
}
}
}
else {
// System.out.println("corefTarget.getDocId() = " + corefTarget.getDocId());
// System.out.println("eventTarget.getDocId() = " + eventTarget.getDocId());
}
}
}
}
}
}
if (locationSets!=null) {
// System.out.println("PLACES");
for (int s = 0; s < locationSets.size(); s++) {
CoRefSetAgata refSet = locationSets.get(s);
//// loop to add results for range of sentences
for (int k = 0; k < rangeOfSentenceIds.size(); k++) {
String sentenceId = rangeOfSentenceIds.get(k);
if (refSet.containsTargetSentenceId(sentenceId)) {
for (int l = 0; l < refSet.getTargets().size(); l++) {
CorefTargetAgata corefTargetAgata = refSet.getTargets().get(l);
if (eventTarget.getDocId().equals(corefTargetAgata.getDocId())) {
String predicate = "semHasPlace";
String subject = key+"/e"+ coRefSetAgata.getId();
String object = key+"/p"+ refSet.getId();
Triple triple = new Triple(predicate, subject, object);
String target = "\t\t<target id =\""+ eventTarget.getDocId()+"/"+eventTarget.getSentenceId()+"\""+"/>";
target += " <!-- "+eventTarget.getWord()+"--"+predicate+"--"+ corefTargetAgata.getWord()+" -->";
int givenTriple = getTriple(triplesA, triple);
if (givenTriple==-1) {
relationCounter++;
String id = key+"/"+relationCounter;
triple.setId(id);
triple.addMentions(target);
triplesA.add(triple);
}
else {
if (!triplesA.get(givenTriple).getMentions().contains(target)) {
triplesA.get(givenTriple).addMentions(target);
}
}
}
else {
// System.out.println("corefTarget.getDocId() = " + corefTarget.getDocId());
// System.out.println("eventTarget.getDocId() = " + eventTarget.getDocId());
}
}
}
}
}
}
}
}
for (int k = 0; k < triplesA.size(); k++) {
Triple triple = triplesA.get(k);
str = triple.toString();
fos.write(str.getBytes());
}
for (int k = 0; k < triplesP.size(); k++) {
Triple triple = triplesP.get(k);
str = triple.toString();
fos.write(str.getBytes());
}
for (int k = 0; k < triplesT.size(); k++) {
Triple triple = triplesT.get(k);
str = triple.toString();
fos.write(str.getBytes());
}
}
static int getTriple (ArrayList<Triple> triples, Triple triple) {
for (int i = 0; i < triples.size(); i++) {
Triple triple1 = triples.get(i);
/*
System.out.println("triple1.toString() = " + triple1.toString());
System.out.println("triple.toString() = " + triple.toString());
*/
/*
if (triple.getSubject().equals("TOPIC_44_EVENT_COREFERENCE_CORPUS/e35")) {
System.out.println(triple.getObject()+":"+triple1.getObject());
}
*/
if ((triple1.getPredicate().equalsIgnoreCase(triple.getPredicate())) &&
(triple1.getSubject().equalsIgnoreCase(triple.getSubject())) &&
(triple1.getObject().equalsIgnoreCase(triple.getObject()))
) {
return i;
}
}
return -1;
}
/**
*
* @param corefMap
* @param sentenceIdString
* @param sentenceRange
* @return
*/
static ArrayList<CoRefSetAgata> getCorefSetFromRange (HashMap<String, ArrayList<CoRefSetAgata>> corefMap, String sentenceIdString, int sentenceRange) {
ArrayList<CoRefSetAgata> coRefSetAgatas = null;
coRefSetAgatas = corefMap.get(sentenceIdString);
if (sentenceRange>0) {
/// we assume that the sentence id is an integer
Integer sentenceId = Integer.parseInt(sentenceIdString);
if (sentenceId!=null) {
for (int i = sentenceId; i < sentenceRange; i++) {
ArrayList<CoRefSetAgata> nextSet = corefMap.get(sentenceId+i);
if (nextSet!=null) {
for (int j = 0; j < nextSet.size(); j++) {
CoRefSetAgata coRefSetAgata = nextSet.get(j);
coRefSetAgatas.add(coRefSetAgata);
}
}
}
/* for (int i = sentenceId; i < sentenceRange; i++) {
ArrayList<CoRefSet> nextSet = corefMap.get(sentenceId-i);
if (nextSet!=null) {
for (int j = 0; j < nextSet.size(); j++) {
CoRefSet coRefSet = nextSet.get(j);
coRefSets.add(coRefSet);
}
}
}*/
}
}
return coRefSetAgatas;
}
static ArrayList<String> getSentenceRange (String sentenceIdString, int sentenceRange) {
ArrayList<String> sentenceIdRange = new ArrayList<String>();
sentenceIdRange.add(sentenceIdString);
if (sentenceRange>0) {
/// we assume that the sentence id is an integer
Integer sentenceId = null;
try {
sentenceId = Integer.parseInt(sentenceIdString);
} catch (NumberFormatException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
if (sentenceId!=null) {
for (int i = sentenceId; i < sentenceRange; i++) {
sentenceIdRange.add(new Integer(i).toString());
}
for (int i = sentenceId; i < sentenceRange; i++) {
sentenceIdRange.add(new Integer(i).toString());
}
}
}
return sentenceIdRange;
}
}
| apache-2.0 |
denisneuling/cctrl.jar | cctrl-api/src/main/java/com/cloudcontrolled/api/model/Version.java | 2646 | /*
* Copyright 2012 Denis Neuling
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cloudcontrolled.api.model;
/**
* The version object contains informations about the latest available software
* to access the cloudCOntrol API.
*
* @author Denis Neuling (denisneuling@gmail.com)
*
*/
public class Version extends AbstractModel {
private String pycclib;
private String cctrl;
/**
* <p>
* Constructor for Version.
* </p>
*/
public Version() {
}
/**
* <p>
* Getter for the field <code>pycclib</code>.
* </p>
*
* @return pycclib the latest pycclib release version
*/
public String getPycclib() {
return pycclib;
}
/**
* <p>
* Setter for the field <code>pycclib</code>.
* </p>
*
* @param pycclib
* the latest pycclib release version
*/
public void setPycclib(String pycclib) {
this.pycclib = pycclib;
}
/**
* <p>
* Getter for the field <code>cctrl</code>.
* </p>
*
* @return cctrl the latest cctrl release version
*/
public String getCctrl() {
return cctrl;
}
/**
* <p>
* Setter for the field <code>cctrl</code>.
* </p>
*
* @param cctrl
* the latest cctrl release version to set
*/
public void setCctrl(String cctrl) {
this.cctrl = cctrl;
}
/** {@inheritDoc} */
@Override
public String toString() {
return "Version [pycclib=" + pycclib + ", cctrl=" + cctrl + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((cctrl == null) ? 0 : cctrl.hashCode());
result = prime * result + ((pycclib == null) ? 0 : pycclib.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Version other = (Version) obj;
if (cctrl == null) {
if (other.cctrl != null)
return false;
} else if (!cctrl.equals(other.cctrl))
return false;
if (pycclib == null) {
if (other.pycclib != null)
return false;
} else if (!pycclib.equals(other.pycclib))
return false;
return true;
}
}
| apache-2.0 |
lburgazzoli/apache-activemq-artemis | examples/features/standard/ssl-enabled-dual-authentication/src/main/java/org/apache/activemq/artemis/jms/example/SSLDualAuthenticationExample.java | 3962 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.jms.example;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.InitialContext;
/**
* A simple JMS Queue example that uses dual broker authentication mechanisms for SSL and non-SSL connections.
*/
public class SSLDualAuthenticationExample {
public static void main(final String[] args) throws Exception {
Connection producerConnection = null;
Connection consumerConnection = null;
InitialContext initialContext = null;
try {
// Step 1. Create an initial context to perform the JNDI lookup.
initialContext = new InitialContext();
// Step 2. Perfom a lookup on the queue
Queue queue = (Queue) initialContext.lookup("queue/exampleQueue");
// Step 3. Perform a lookup on the producer's SSL Connection Factory
ConnectionFactory producerConnectionFactory = (ConnectionFactory) initialContext.lookup("SslConnectionFactory");
// Step 4. Perform a lookup on the consumer's Connection Factory
ConnectionFactory consumerConnectionFactory = (ConnectionFactory) initialContext.lookup("ConnectionFactory");
// Step 5.Create a JMS Connection for the producer
producerConnection = producerConnectionFactory.createConnection();
// Step 6.Create a JMS Connection for the consumer
consumerConnection = consumerConnectionFactory.createConnection("consumer", "activemq");
// Step 7. Create a JMS Session for the producer
Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Step 8. Create a JMS Session for the consumer
Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Step 9. Create a JMS Message Producer
MessageProducer producer = producerSession.createProducer(queue);
// Step 10. Create a Text Message
TextMessage message = producerSession.createTextMessage("This is a text message");
System.out.println("Sent message: " + message.getText());
// Step 11. Send the Message
producer.send(message);
// Step 12. Create a JMS Message Consumer
MessageConsumer messageConsumer = consumerSession.createConsumer(queue);
// Step 13. Start the Connection
consumerConnection.start();
// Step 14. Receive the message
TextMessage messageReceived = (TextMessage) messageConsumer.receive(5000);
System.out.println("Received message: " + messageReceived.getText());
initialContext.close();
}
finally {
// Step 15. Be sure to close our JMS resources!
if (initialContext != null) {
initialContext.close();
}
if (producerConnection != null) {
producerConnection.close();
}
if (consumerConnection != null) {
consumerConnection.close();
}
}
}
}
| apache-2.0 |
TU-Berlin/mathosphere | mathosphere-core/src/test/java/com/formulasearchengine/mathosphere/mlp/text/WikidataInterfaceTest.java | 6118 | package com.formulasearchengine.mathosphere.mlp.text;
import com.google.common.collect.Lists;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by Moritz on 12.12.2015.
*/
public class WikidataInterfaceTest {
String[] qIds = new String[] {"Q7913892",
"Q12503",
"Q3176558",
"Q36161",
"Q739925",
"Q49008",
"Q12503",
"Q5156597",
"Q11567",
"Q1413083",
"Q50700",
"Q50701",
"Q935944",
"Q50701",
"Q935944",
"Q1144319",
"Q50700",
"Q3150667",
"Q2256802",
"Q729113",
"Q21199",
"Q33456",
"Q44946",
"Q230883",
"Q21199",
"Q21199",
"Q50700",
"Q50700",
"Q50700",
"Q50700",
"Q378201",
"Q302462",
"Q3913",
"Q3913",
"Q3913",
"Q12916",
"Q12916",
"Q11352",
"Q2303886",
"Q526719",
"Q11348",
"Q1027788",
"Q12916",
"Q12916",
"Q946764",
"Q19033",
"Q126017",
"Q230963",
"Q2303886",
"Q168698",
"Q917476",
"Q17285",
"Q1663694",
"Q1663694",
"Q1663694",
"Q1663694",
"Q5597315",
"Q5597315",
"Q2303886",
"Q46276",
"Q2140940",
"Q36253",
"Q1096885",
"Q189569",
"Q3176558",
"Q188889",
"Q188889",
"Q13824",
"Q2111",
"Q174102",
"Q1440227",
"Q167",
"Q1515261",
"Q1128317",
"Q111059",
"Q111059",
"Q43260",
"Q3150667",
"Q43260",
"Q11567",
"Q2095069",
"Q21199",
"Q21199",
"Q2303886",
"Q2303886",
"Q1137759",
"Q193796",
"Q12916",
"Q6520159",
"Q11471",
"Q167",
"Q12916",
"Q12916",
"Q21199",
"Q21199",
"Q3686031",
"Q11471",
"Q9492",
"Q12916",
"Q4440864",
"Q12916",
"Q18373",
"Q2111",
"Q1289248",
"Q876346",
"Q1289248",
"Q464794",
"Q193794",
"Q192826",
"Q11471",
"Q929043",
"Q2518235",
"Q782566",
"Q1074380",
"Q1413083",
"Q1413083",
"Q1008943",
"Q1256787",
"Q13471665",
"Q1289248",
"Q2337858",
"Q11348",
"Q11348",
"Q11348",
"Q11471",
"Q2918589",
"Q1045555",
"Q21199",
"Q82580",
"Q18848",
"Q18848",
"Q1952404",
"Q11703678",
"Q11703678",
"Q2303886",
"Q1096885",
"Q4440864",
"Q2362761",
"Q11471",
"Q3176558",
"Q30006",
"Q11567",
"Q3258885",
"Q131030",
"Q21406831",
"Q131030",
"Q186290",
"Q1591095",
"Q11348",
"Q3150667",
"Q474715",
"Q379825",
"Q379825",
"Q192704",
"Q44432",
"Q44432",
"Q319913",
"Q12916",
"Q12916",
"Q2627460",
"Q2627460",
"Q190109",
"Q83478",
"Q18848",
"Q379825",
"Q844128",
"Q2608202",
"Q29539",
"Q11465",
"Q176737",
"Q176737",
"Q176737",
"Q1413083",
"Q1759756",
"Q900231",
"Q39297",
"Q39297",
"Q39552",
"Q39297",
"Q1948412",
"Q3554818",
"Q21199",
"Q12916",
"Q168698",
"Q50701",
"Q11053",
"Q12916",
"Q12916",
"Q12916",
"Q12503",
"Q12503",
"Q176623",
"Q10290214",
"Q10290214",
"Q505735",
"Q1057607",
"Q11471",
"Q1057607",
"Q5227327",
"Q6901742",
"Q159375",
"Q2858846",
"Q1134404",
"Q12916",
"Q4440864",
"Q838611",
"Q44946",
"Q173817",
"Q12916",
"Q21199",
"Q12916",
"Q190056",
"Q10290214",
"Q10290214",
"Q506041",
"Q2858846"};
@Test
public void testGetAliases() throws Exception {
for (String qid : qIds) {
Path file = Paths.get(File.createTempFile("temp", Long.toString(System.nanoTime())).getPath());
List<String> aliases = WikidataInterface.getAliases(qid);
aliases = aliases.stream().map(a -> "\"" + a + "\"").collect(Collectors.toList());
Files.write(file, aliases, Charset.forName("UTF-8"));
}
}
@Test
public void testGetEntities() throws Exception {
final ArrayList<String> expected = Lists.newArrayList("Q12916");
Assert.assertEquals(expected.get(0), WikidataInterface.getEntities("real number").get(0));
}
} | apache-2.0 |
sguisse/InfoWkspOrga | 10-Application/Application/Swing-Sample-APP/src/main/java/com/sgu/infowksporga/jfx/menu/action/edit/RemoveFileExplorerViewFilesAction.java | 2323 | package com.sgu.infowksporga.jfx.menu.action.edit;
import java.awt.event.ActionEvent;
import com.sgu.apt.annotation.AnnotationConfig;
import com.sgu.apt.annotation.i18n.I18n;
import com.sgu.apt.annotation.i18n.I18nProperty;
import com.sgu.core.framework.gui.swing.util.UtilGUI;
import com.sgu.infowksporga.jfx.menu.action.AbstractInfoWrkspOrgaAction;
import com.sgu.infowksporga.jfx.views.file.explorer.rules.IsAtLeastViewFileSelectedRule;
/**
* Description : RemoveDirectoryDeskViewFilesAction class<br>
* Move to trash all workspace selected files from directory view
*
* @author SGU
*/
public class RemoveFileExplorerViewFilesAction extends AbstractInfoWrkspOrgaAction {
/**
* The attribute serialVersionUID
*/
private static final long serialVersionUID = -3651435084049489336L;
/**
* Constructor<br>
*/
@I18n(baseProject = AnnotationConfig.I18N_TARGET_APPLICATION_PROPERTIES_FOLDER, filePackage = "i18n", fileName = "application-prez",
properties = { // Action buttons
@I18nProperty(key = "menu.edit.remove.file.explorer.view.files.text", value = "Supprimer"), // Force /n
@I18nProperty(key = "menu.edit.remove.file.explorer.view.files.name", value = "DELETE_SELECTED_DIRECTORIES_FILES"), // Force /n
@I18nProperty(key = "menu.edit.remove.file.explorer.view.files.tooltip",
value = "Supprime les fichiers/dossiers sélectionnés de toutes les vues (même non visible)"), // Force /n
@I18nProperty(key = "menu.edit.remove.file.explorer.view.files.mnemonic", value = "p"), // Force /n
@I18nProperty(key = "menu.edit.remove.file.explorer.view.files.shortcut", value = "control D"), // Force /n
@I18nProperty(key = "menu.edit.remove.file.explorer.view.files.icon", value = "/icons/delete.png"), // Force /n
})
public RemoveFileExplorerViewFilesAction() {
super("menu.edit.remove.file.explorer.view.files");
setRule(new IsAtLeastViewFileSelectedRule(null));
}
/** {@inheritDoc} */
@Override
public void actionPerformed(final ActionEvent evt) {
//final RemoveFilesToTrashServiceUI facade = SpringBeanHelper.getImplementationByInterface(RemoveFilesToTrashServiceUI.class);
//facade.execute(facade, null);
UtilGUI.showNotYetImplementedDlg();
}
}
| apache-2.0 |
jpatanooga/Canova | canova-api/src/main/java/org/canova/api/berkeley/MyMethod.java | 157 | package org.canova.api.berkeley;
/**
* A function wrapping interface.
* @author John DeNero
*/
public interface MyMethod<I, O> {
public O call(I obj);
}
| apache-2.0 |
DSC-SPIDAL/dapwc | src/main/java/edu/indiana/soic/spidal/dapwc/PlotTools.java | 14272 | package edu.indiana.soic.spidal.dapwc;
public class PlotTools
{
// TODO - fix PlotTools
/* public static void CreatePlotWithCenters(String centerFile, String pointsFile, String clusterNumberFile, int numberOfCenterPointsToIncludeInEachCenterType, String centerPlotFile, String plotDescription)
{
*//* Generate all types of center clusters per cluster
*
* Center clusters are,
* 1. Original Min Mean
* 2. MDS Min Mean
* 3. MDS Center of Gravity (CoG)
* 4. Overall Best
* 5. Bucket Fraction 0
* Bucket Fraction 1 and so on
*
* Number of center points to include in each center type = n
* n <= N, which is the number of center points found for each center type by PWC
* N is specified through NumberOfCenters parameter in PWC
*
* Assumes a center file from a PWC center finding run
* Assumes a points file, which has each point mapped to its cluster in the format
* PointNumber<TAB>Xcoord<TAB>Ycoord<TAB>Zcoord<TAB>ClusterNumber
*//*
*//* Colors to use with PlotViz
reads color info from Matlab50.txt file *//*
java.util.ArrayList<Color> matlab50Colors = GenerateMatlab50Colors();
*//* XML elements to hold points and clusters to be used in PlotViz file *//*
XElement clustersElement = new XElement("clusters");
XElement pointsElement = new XElement("points");
*//* Hashtable mapping point number to a PlotVizPoint data structure for the points in the given points file *//*
java.util.Hashtable existingPointsTable = new java.util.Hashtable();
*//* Maximum number of points int the points file *//*
int maxpnum = 0;
*//* Maximum number of clusters that points are mapped to in the points file*//*
int maxcnum = 0;
edu.indiana.soic.spidal.Boxspidal.general.Box<Integer> boxmaxpnum = new edu.indiana.soic.spidal.Boxspidal.general.Box<Integer>(maxpnum);
edu.indiana.soic.spidal.generaloic.spidal.Box<Integer> boxmaxcnum = new edu.indiana.soic.spidal.Boxspidal.general.Box<Integer>(maxcnum);
ProcessPointsFile(pointsFile, clusterNumberFile, clustersElement, pointsElement, boxmaxpnum, boxmaxcnum, existingPointsTable, matlab50Colors);
maxpnum = boxmaxpnum.content;
maxcnum = boxmaxcnum.content;
*//* Table mapping each cluster (i.e. group) number to another table called method table
* method table maps each method (e.g. smallest distance mean, smallest MDS distance mean, etc.) name to the list center points for that particular method
* the order of points in the list is as same as in the given center file *//*
java.util.Hashtable groupTable = ProcessCenterFile(centerFile);
CreatePlotWithCentersInternal(centerPlotFile, plotDescription, clustersElement, pointsElement, maxpnum, existingPointsTable, maxcnum, matlab50Colors, groupTable, numberOfCenterPointsToIncludeInEachCenterType);
}
private static void CreatePlotWithCentersInternal(String centerPlotFile, String plotDescription, XElement clustersElement, XElement pointsElement, int maxpnum, java.util.Hashtable existingPointsTable, int maxcnum, java.util.ArrayList<Color> matlab50Colors, java.util.Hashtable groupTable, int numberOfCenterPointsToIncludeInEachCenterType)
{
++maxcnum;
for (DictionaryEntry groupToMethodTable : groupTable)
{
int group = (int)groupToMethodTable.Key; // group is the original cluster number
java.util.Hashtable methodTable = (java.util.Hashtable)groupToMethodTable.Value;
int methodCount = methodTable.size();
int tempCount = methodCount;
for (DictionaryEntry methodToCenterPoints : methodTable)
{
String method = (String)methodToCenterPoints.Key; // method is one of smallest distance mean, smallest MDS mean, etc.
// cluster number to be used in PlotViz for this center type
int methodNumber = methodCount - tempCount--;
int clusterNumberForCenterType = group * methodCount + methodNumber + maxcnum;
// cluster name to be used in PlotViz for this center type
String centerTypeName = group + "" + method + ".centerpoints";
// add an XML element to represent this center type as a cluster in PlotViz
clustersElement.Add(CreateClusterElement(clusterNumberForCenterType, centerTypeName, matlab50Colors.get(group % matlab50Colors.size()), false, 2.0, methodNumber));
java.util.ArrayList<CenterInfo> cps = (java.util.ArrayList<CenterInfo>)methodToCenterPoints.Value;
// Picking the topmost n point for each method
for (int i = 0; i < numberOfCenterPointsToIncludeInEachCenterType; i++)
{
CenterInfo cp = cps.get(i);
PlotVizPoint p = (PlotVizPoint)existingPointsTable.get(cp.getPnum());
pointsElement.Add(CreatePointElement(++maxpnum, clusterNumberForCenterType, ("cluster:" + group + "-idx:" + p.getIndex() + "method:" + method), p.getX(), p.getY(), p.getZ()));
}
}
}
XElement plotElement = CreatePlotElement(plotDescription, true);
XElement plotvizElement = new XElement("plotviz");
plotvizElement.Add(plotElement);
plotvizElement.Add(clustersElement);
plotvizElement.Add(pointsElement);
plotvizElement.Save(centerPlotFile);
}
private static void ProcessPointsFile(String pointsFile, String clusterNumberFile, XElement clusters, XElement points, edu.indiana.soic.spidal.generaloic.spidal.Box<Integer> maxpnum, edu.indiana.soic.spidal.generaloic.spidal.Box<Integer> maxcnum, java.util.Hashtable pointsTable, java.util.ArrayList<Color> matlab50Colors)
{
//C# TO JAVA CONVERTER NOTE: The following 'using' block is replaced by its Java equivalent:
// using (StreamReader preader = new StreamReader(pointsFile), creader = new StreamReader(clusterNumberFile))
StreamReader preader = new StreamReader(pointsFile);
StreamReader creader = new StreamReader(clusterNumberFile);
try
{
java.util.HashSet<Integer> clusterNumbers = new java.util.HashSet<Integer>();
maxpnum.content = -1;
while (!preader.EndOfStream)
{
String pline = preader.ReadLine();
String cline = creader.ReadLine();
if (!tangible.DotNetToJavaStringHelper.isNullOrEmpty(pline) && !tangible.DotNetToJavaStringHelper.isNullOrEmpty(cline))
{
PlotVizPoint p = ReadPointLine(pline.trim());
if (maxpnum.content < p.getIndex())
{
maxpnum.content = p.getIndex();
}
pointsTable.put(p.getIndex(), p);
int cnum = ReadCnum(cline);
p.setCluster(cnum);
if (!clusterNumbers.contains(p.getCluster()))
{
clusterNumbers.add(p.getCluster());
clusters.Add(CreateClusterElement(p.getCluster(), (new Integer(p.getCluster())).toString(CultureInfo.InvariantCulture), matlab50Colors.get(p.getCluster() % matlab50Colors.size()), true, 0.1, Glyphs.Hexagon2D));
}
points.Add(CreatePointElement(p.getIndex(), p.getCluster(), "", p.getX(), p.getY(), p.getZ()));
}
}
maxcnum.content = clusterNumbers.Max();
}
finally
{
preader.dispose();
creader.dispose();
}
}
private static int ReadCnum(String line)
{
char[] sep = new char[] {' ', '\t'};
String[] splits = line.split(sep, StringSplitOptions.RemoveEmptyEntries);
return splits.length == 2 ? Integer.parseInt(splits[1]) : splits.length == 5 ? Integer.parseInt(splits[4]) : 0;
}
private static java.util.ArrayList<Color> GenerateMatlab50Colors()
{
//C# TO JAVA CONVERTER NOTE: The following 'using' block is replaced by its Java equivalent:
// using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Salsa.PairwiseClusteringTPL.Matlab50.txt"))
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Salsa.PairwiseClusteringTPL.Matlab50.txt");
try
{
if (stream != null)
{
//C# TO JAVA CONVERTER NOTE: The following 'using' block is replaced by its Java equivalent:
// using (StreamReader reader = new StreamReader(stream))
StreamReader reader = new StreamReader(stream);
try
{
java.util.ArrayList<Color> colors = new java.util.ArrayList<Color>();
char[] sep = new char[] {' ', '\t'};
String[] splits;
String split;
int startIdx = 3;
int r, g, b, a;
while (!reader.EndOfStream)
{
String line = reader.ReadLine();
if (!tangible.DotNetToJavaStringHelper.isNullOrEmpty(line))
{
splits = line.trim().split(java.util.regex.Pattern.quote(sep.toString()), -1);
split = splits[0];
r = Integer.parseInt(split.substring(startIdx, startIdx + (split.length() - (startIdx + 1))));
split = splits[1];
g = Integer.parseInt(split.substring(startIdx, startIdx + (split.length() - (startIdx + 1))));
split = splits[2];
b = Integer.parseInt(split.substring(startIdx, startIdx + (split.length() - (startIdx + 1))));
split = splits[3];
a = Integer.parseInt(split.substring(startIdx, startIdx + (split.length() - (startIdx + 1))));
colors.add(Color.FromArgb(a, r, g, b));
}
}
return colors;
}
finally
{
reader.dispose();
}
}
else
{
throw new RuntimeException("Unable to load embedded resource: Matlab50.txt");
}
}
finally
{
stream.dispose();
}
}
private static PlotVizPoint ReadPointLine(String line)
{
char[] sep = new char[] {' ', '\t'};
String[] splits = line.split(sep, StringSplitOptions.RemoveEmptyEntries);
PlotVizPoint p = new PlotVizPoint(Double.parseDouble(splits[1]), Double.parseDouble(splits[2]), Double.parseDouble(splits[3]), Integer.parseInt(splits[0]), Integer.parseInt(splits[4]));
return p;
}
private static CenterInfo ReadCenterLine(String line)
{
char[] sep = new char[] {' ', '\t'};
char[] eqsep = new char[] {'='};
String[] splits = line.split(sep, StringSplitOptions.RemoveEmptyEntries);
int pnum = Integer.parseInt(splits[0].split(java.util.regex.Pattern.quote(eqsep.toString()), -1)[1]);
double measure = Double.parseDouble(splits[1].split(java.util.regex.Pattern.quote(eqsep.toString()), -1)[1]);
int methodIdx = 2;
String source = "";
double count = 0.0;
if (splits[2].startsWith("Count"))
{
methodIdx = 4;
count = Double.parseDouble(splits[2].split(java.util.regex.Pattern.quote(eqsep.toString()), -1)[1]);
source = splits[3].split(java.util.regex.Pattern.quote(eqsep.toString()), -1)[1];
}
String method = splits[methodIdx].split(java.util.regex.Pattern.quote(eqsep.toString()), -1)[1];
int group = Integer.parseInt(splits[methodIdx + 1].split(java.util.regex.Pattern.quote(eqsep.toString()), -1)[1]);
String seqName = splits[methodIdx + 2].split(java.util.regex.Pattern.quote(eqsep.toString()), -1)[1];
for (int i = methodIdx + 3; i < splits.length - 4; ++i)
{
seqName += (" " + splits[i]);
}
int seqLength = Integer.parseInt(splits[splits.length - 4].split(java.util.regex.Pattern.quote(eqsep.toString()), -1)[1]);
return new CenterInfo(pnum, measure, method, group, seqName, seqLength, source, count);
}
private static java.util.Hashtable ProcessCenterFile(String centerFile)
{
//C# TO JAVA CONVERTER NOTE: The following 'using' block is replaced by its Java equivalent:
// using (StreamReader reader = new StreamReader(centerFile))
StreamReader reader = new StreamReader(centerFile);
try
{
java.util.Hashtable groupTable = new java.util.Hashtable();
while (!reader.EndOfStream)
{
CenterInfo cp = ReadCenterLine(reader.ReadLine());
AddToGroupTable(groupTable, cp);
}
return groupTable;
}
finally
{
reader.dispose();
}
}
private static void AddToGroupTable(java.util.Hashtable groupTable, CenterInfo cp)
{
if (groupTable.containsKey(cp.getCluster()))
{
java.util.Hashtable methodTable = (java.util.Hashtable)groupTable.get(cp.getCluster());
if (methodTable.containsKey(cp.getMethod()))
{
// Need a list to maintain the order of points
java.util.ArrayList<CenterInfo> cps = (java.util.ArrayList<CenterInfo>)methodTable.get(cp.getMethod());
cps.add(cp);
}
else
{
// Need a list to maintain the order of points
java.util.ArrayList<CenterInfo> cps = new java.util.ArrayList<CenterInfo>(java.util.Arrays.asList(new CenterInfo[] {cp}));
methodTable.put(cp.getMethod(), cps);
}
}
else
{
// Need a list to maintain the order of points
java.util.ArrayList<CenterInfo> cps = new java.util.ArrayList<CenterInfo>(java.util.Arrays.asList(new CenterInfo[] {cp}));
java.util.Hashtable methodTable = new java.util.Hashtable();
methodTable.put(cp.getMethod(), cps);
groupTable.put(cp.getCluster(), methodTable);
}
}
private static XElement CreatePlotElement(String name, boolean glyphVisible)
{
XElement plot = new XElement("plot", new XElement("title", name), new XElement("pointsize", 1), new XElement("glyph", new XElement("visible", glyphVisible ? 1 : 0), new XElement("scale", 1)), new XElement("camera", new XElement("focumode", 0), new XElement("focus", new XAttribute("x", 0), new XAttribute("y", 0), new XAttribute("z", 0))));
return plot;
}
private static XElement CreateClusterElement(int key, String label, Color color, boolean isDefault, double size, int shape)
{
XElement cluster = new XElement("cluster", new XElement("key", key), new XElement("label", label), new XElement("visible", 1), new XElement("default", isDefault ? 1 : 0), new XElement("color", new XAttribute("r", color.R), new XAttribute("g", color.G), new XAttribute("b", color.B), new XAttribute("a", color.A)), new XElement("size", size), new XElement("shape", shape));
return cluster;
}
private static XElement CreatePointElement(int key, int clusterKey, String label, double x, double y, double z)
{
XElement point = new XElement("point", new XElement("key", key), new XElement("clusterkey", clusterKey), new XElement("label", label), new XElement("location", new XAttribute("x", x), new XAttribute("y", y), new XAttribute("z", z)));
return point;
}
//C# TO JAVA CONVERTER WARNING: Java does not allow user-defined value types. The behavior of this class will differ from the original:
//ORIGINAL LINE: struct Glyphs
private final static class Glyphs
{
public static int Triangle2D = 0;
public static int Rectangle2D = 1;
public static int Pentagon2D = 2;
public static int Hexagon2D = 3;
public static int Tetrahedron3D = 4;
public static int Cube3D = 5;
public static int Sphere3D = 6;
public static int Cylinder3D = 7;
}*/
} | apache-2.0 |
limagiran/hearthstone | src/com/limagiran/hearthstone/heroi/view/PanelHeroi.java | 1754 | package com.limagiran.hearthstone.heroi.view;
import com.limagiran.hearthstone.heroi.control.Heroi;
import com.limagiran.hearthstone.util.AbsolutesConstraints;
import com.limagiran.hearthstone.util.Images;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.netbeans.lib.awtextra.AbsoluteConstraints;
import org.netbeans.lib.awtextra.AbsoluteLayout;
/**
*
* @author Vinicius
*/
public class PanelHeroi extends JPanel {
private Animacao animacao;
private Congelado congelado;
private JLabel heroi;
private final ImageIcon imagemHeroi;
private final Heroi hero;
public PanelHeroi(Heroi hero, ImageIcon image) {
super(new AbsoluteLayout());
this.hero = hero;
imagemHeroi = image;
init();
}
private void init() {
setOpaque(false);
congelado = new Congelado();
heroi = new JLabel(imagemHeroi, JLabel.CENTER);
animacao = new Animacao(hero);
add(animacao, new AbsoluteConstraints(0, 0, imagemHeroi.getIconWidth(), imagemHeroi.getIconHeight()));
add(congelado, AbsolutesConstraints.ZERO);
add(heroi, AbsolutesConstraints.ZERO);
}
public void atualizar() {
congelado.repaint();
heroi.repaint();
}
public void setFreeze(boolean flag) {
congelado.setVisible(flag);
}
public Animacao getAnimacao() {
return animacao;
}
@Override
public String toString() {
return hero.getToString();
}
}
class Congelado extends JLabel {
public Congelado() {
super(Images.HEROI_CONGELADO, JLabel.CENTER);
init();
}
private void init() {
setOpaque(false);
setVisible(false);
}
} | apache-2.0 |
googleapis/java-compute | google-cloud-compute/src/main/java/com/google/cloud/compute/v1/stub/HttpJsonRegionDiskTypesCallableFactory.java | 4644 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.compute.v1.stub;
import com.google.api.core.BetaApi;
import com.google.api.gax.httpjson.HttpJsonCallSettings;
import com.google.api.gax.httpjson.HttpJsonCallableFactory;
import com.google.api.gax.httpjson.HttpJsonOperationSnapshotCallable;
import com.google.api.gax.httpjson.HttpJsonStubCallableFactory;
import com.google.api.gax.httpjson.longrunning.stub.OperationsStub;
import com.google.api.gax.rpc.BatchingCallSettings;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.OperationCallable;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.ServerStreamingCallSettings;
import com.google.api.gax.rpc.ServerStreamingCallable;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.longrunning.Operation;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* REST callable factory implementation for the RegionDiskTypes service API.
*
* <p>This class is for advanced usage.
*/
@Generated("by gapic-generator-java")
@BetaApi
public class HttpJsonRegionDiskTypesCallableFactory
implements HttpJsonStubCallableFactory<Operation, OperationsStub> {
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createUnaryCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
UnaryCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createUnaryCallable(
httpJsonCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT, PagedListResponseT>
UnaryCallable<RequestT, PagedListResponseT> createPagedCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
PagedCallSettings<RequestT, ResponseT, PagedListResponseT> callSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createPagedCallable(
httpJsonCallSettings, callSettings, clientContext);
}
@Override
public <RequestT, ResponseT> UnaryCallable<RequestT, ResponseT> createBatchingCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
BatchingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createBatchingCallable(
httpJsonCallSettings, callSettings, clientContext);
}
@BetaApi(
"The surface for long-running operations is not stable yet and may change in the future.")
@Override
public <RequestT, ResponseT, MetadataT>
OperationCallable<RequestT, ResponseT, MetadataT> createOperationCallable(
HttpJsonCallSettings<RequestT, Operation> httpJsonCallSettings,
OperationCallSettings<RequestT, ResponseT, MetadataT> callSettings,
ClientContext clientContext,
OperationsStub operationsStub) {
UnaryCallable<RequestT, Operation> innerCallable =
HttpJsonCallableFactory.createBaseUnaryCallable(
httpJsonCallSettings, callSettings.getInitialCallSettings(), clientContext);
HttpJsonOperationSnapshotCallable<RequestT, Operation> initialCallable =
new HttpJsonOperationSnapshotCallable<RequestT, Operation>(
innerCallable,
httpJsonCallSettings.getMethodDescriptor().getOperationSnapshotFactory());
return HttpJsonCallableFactory.createOperationCallable(
callSettings, clientContext, operationsStub.longRunningClient(), initialCallable);
}
@Override
public <RequestT, ResponseT>
ServerStreamingCallable<RequestT, ResponseT> createServerStreamingCallable(
HttpJsonCallSettings<RequestT, ResponseT> httpJsonCallSettings,
ServerStreamingCallSettings<RequestT, ResponseT> callSettings,
ClientContext clientContext) {
return HttpJsonCallableFactory.createServerStreamingCallable(
httpJsonCallSettings, callSettings, clientContext);
}
}
| apache-2.0 |
shiyuzhe/coolweather | app/src/main/java/android/coolweather/com/coolweather/service/AutoUpdateService.java | 3589 | package android.coolweather.com.coolweather.service;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.coolweather.com.coolweather.gson.Weather;
import android.coolweather.com.coolweather.util.HttpUtil;
import android.coolweather.com.coolweather.util.Utility;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class AutoUpdateService extends Service {
@Override
public IBinder onBind(Intent intent) {
throw null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("syz","更新天气");
updateWeather();
updateBingPic();
AlarmManager manager = (AlarmManager)getSystemService(ALARM_SERVICE);
int anHour = 8*60*60*1000;
Long triggerAtTime = SystemClock.elapsedRealtime()+anHour;
Intent i = new Intent(this,AutoUpdateService.class);
PendingIntent pi = PendingIntent.getService(this,0,i,0);
manager.cancel(pi);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi);
return super.onStartCommand(intent, flags, startId);
}
/*
*更新天气信息
*/
public void updateWeather(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String weatherString = prefs.getString("weather",null);
if(weatherString != null){
Weather weather = Utility.handleWeatherResponse(weatherString);
String weatherId= weather.basic.weatherId;
String weatherUrl = "http://guolin.tech/api/weather?cityid="+weatherId+"&key=bc0418b57b2d4918819d3974ac1285d9";
HttpUtil.sendOKHTTPRequest(weatherUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final Weather weather = Utility.handleWeatherResponse(responseText);
if(weather!=null&"ok".equals(weather.status)){
SharedPreferences.Editor editor =PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit();
editor.putString("weather",responseText);
editor.apply();
}
}
});
}
}
/*
*加载bing每日一图
*/
private void updateBingPic(){
String requestBingPic = "http://guolin.tech/api/bing_pic";
HttpUtil.sendOKHTTPRequest(requestBingPic, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String bingPic = response.body().string();
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit();
editor.putString("bing_pic",bingPic);
editor.apply();
}
});
}
}
| apache-2.0 |
leapframework/framework | data/orm/src/main/java/leap/orm/domain/Domain.java | 4481 | /*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 leap.orm.domain;
import leap.lang.*;
import leap.lang.annotation.Nullable;
import leap.lang.enums.Bool;
import leap.lang.expression.Expression;
import leap.lang.jdbc.JdbcType;
import leap.orm.generator.IdGenerator;
import java.util.regex.Pattern;
public class Domain implements Sourced,Named {
private final Object source;
private final String name;
private final String defaultColumnName;
private final JdbcType type;
private final Integer length;
private final Integer precision;
private final Integer scale;
private final Boolean nullable;
private final String defaultValue;
private final Boolean insert;
private final Boolean update;
private final Expression insertValue;
private final Expression updateValue;
private final Boolean filterable;
private final Boolean sortable;
private final Boolean filter;
private final Expression filterValue;
private final Expression filterIfValue;
private final Float sortOrder;
private final boolean autoMapping;
private final IdGenerator idGenerator;
public Domain(Object source, String name, String defaultColumnName, JdbcType type, Integer length, Integer precision, Integer scale,
Boolean nullable, String defaultValue, Boolean insert, Expression insertValue, Boolean update, Expression updateValue,
Boolean filterable, Boolean sortable,
Boolean filter, Expression filterValue,Expression filterIfValue, Float sortOrder, boolean autoMapping, IdGenerator idGenerator) {
Args.notEmpty(name,"name");
this.source = source;
this.name = name;
this.defaultColumnName = defaultColumnName;
this.type = type;
this.length = length;
this.precision = precision;
this.scale = scale;
this.nullable = nullable;
this.defaultValue = defaultValue;
this.insert = insert;
this.insertValue = insertValue;
this.update = update;
this.updateValue = updateValue;
this.filterable = filterable;
this.sortable = sortable;
this.filter = filter;
this.filterValue = filterValue;
this.filterIfValue=filterIfValue;
this.sortOrder = sortOrder;
this.autoMapping = autoMapping;
this.idGenerator = idGenerator;
}
@Override
public Object getSource() {
return source;
}
public String getName() {
return name;
}
public String getDefaultColumnName() {
return defaultColumnName;
}
public JdbcType getType() {
return type;
}
public Integer getLength() {
return length;
}
public Integer getPrecision() {
return precision;
}
public Integer getScale() {
return scale;
}
public Boolean getNullable() {
return nullable;
}
public String getDefaultValue() {
return defaultValue;
}
public Expression getInsertValue() {
return insertValue;
}
public Boolean getInsert() {
return insert;
}
public Boolean getUpdate() {
return update;
}
public Expression getUpdateValue() {
return updateValue;
}
public Boolean getFilterable() {
return filterable;
}
public Boolean getSortable() {
return sortable;
}
public Boolean getFilter() {
return filter;
}
public Expression getFilterValue() {
return filterValue;
}
public Float getSortOrder() {
return sortOrder;
}
public boolean isAutoMapping() {
return autoMapping;
}
public IdGenerator getIdGenerator() {
return idGenerator;
}
@Override
public String toString() {
return "Domain : " + name;
}
public Expression getFilterIfValue() {
return filterIfValue;
}
}
| apache-2.0 |
dzb/fw-kit | src/main/java/fw/db/connection/impl/RecordHandlerImpl.java | 1457 | package fw.db.connection.impl;
import fw.common.util.CE;
import fw.common.util.LE;
import fw.db.connection.DBException;
import fw.db.connection.RecordHandler;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
/**
* 通用的EntityBean查询映射处理类<br/>
* NOTE: 给定的Entity必须符合STREET规定的命名规则
* @author dzb
*
* @param <T>
*/
class RecordHandlerImpl<T> implements RecordHandler<T> {
private final CE<T> ce;
//private String[] propNames = nul
public RecordHandlerImpl(Class<T> classOfT) {
ce = CE.of(classOfT);
//propNames =LE.getPropertyNames(classOfT);
}
public T mapping(ResultSet rs, int row) throws DBException {
try {
ResultSetMetaData rsm = rs.getMetaData();
String[] columnNames = new String[rsm.getColumnCount()];
for (int i=0; i<rsm.getColumnCount(); i++){
columnNames[i] = rsm.getColumnName(i+1).toLowerCase();
}
T bean = ce.create();
for (String cn : columnNames) {
Object v = rs.getObject(cn);
String fn = DBUtils.convColumnNameToPropertyName(cn);
// TODO think about the comment block check logic
// Field field = ce.getField(fn);
// v = LE.coerce(v, field.getType());
LE.setPropertyValue(bean, fn, v);
}
return bean;
} catch (Throwable e) {
throw new DBException(e);
}
}
}
| apache-2.0 |
jcampos8782/guice-persist-hibernate | guice-persist-hibernate-core/src/test/java/me/jasoncampos/inject/persist/hibernate/HibernatePersistModuleTest.java | 2609 | package me.jasoncampos.inject.persist.hibernate;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.junit.Before;
import org.junit.Test;
import com.google.inject.AbstractModule;
import com.google.inject.CreationException;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.persist.PersistService;
import com.google.inject.persist.UnitOfWork;
public class HibernatePersistModuleTest {
private Injector injector;
@Before
public void beforeEach() {
injector = Guice.createInjector(new HibernatePersistModule(TestEntityProvider.class, TestPropertyProvider.class));
}
@Test(expected = CreationException.class)
public void failsToIntializeWithoutRequiredProviders() {
Guice.createInjector(new HibernatePersistModule());
}
@Test
public void initializationSucceedsUsingProviderConstructor() {
Guice.createInjector(new HibernatePersistModule(TestEntityProvider.class, TestPropertyProvider.class));
}
@Test
public void intializationSucceedsUsingAdditionalModule() {
Guice.createInjector(new HibernatePersistModule(), new AbstractModule() {
@Override
protected void configure() {
bind(HibernateEntityClassProvider.class).to(TestEntityProvider.class);
bind(HibernatePropertyProvider.class).to(TestPropertyProvider.class);
}
});
}
@Test
public void testPersistServiceAndSessionFactoryProviderAreSingleton() {
final HibernatePersistService persistService = (HibernatePersistService) injector.getInstance(PersistService.class);
final HibernatePersistService hibernatePersistService = injector.getInstance(HibernatePersistService.class);
;
assertEquals(persistService, hibernatePersistService);
}
@Test
public void testUnitOfWorkAndSessionProviderAreSingleton() {
final HibernateUnitOfWork unitOfWork = (HibernateUnitOfWork) injector.getInstance(UnitOfWork.class);
final HibernateUnitOfWork hibernateUnitOfWork = injector.getInstance(HibernateUnitOfWork.class);
assertEquals(unitOfWork, hibernateUnitOfWork);
}
@Entity
private static class TestEntity {
@Id
long id;
}
private static class TestEntityProvider implements HibernateEntityClassProvider {
@Override
public List<Class<? extends Object>> get() {
return Arrays.asList(TestEntity.class);
}
}
private static class TestPropertyProvider implements HibernatePropertyProvider {
@Override
public Map<String, String> get() {
return Collections.emptyMap();
}
}
}
| apache-2.0 |
Toporin/SatoChipClient | src/main/java/org/satochip/satochipclient/CardConnectorException.java | 2634 | /*
* java API for the SatoChip Bitcoin Hardware Wallet
* (c) 2015 by Toporin - 16DMCk4WUaHofchAhpMaQS4UPm4urcy2dN
* Sources available on https://github.com/Toporin
*
* Copyright 2015 by Toporin (https://github.com/Toporin)
*
* 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 org.satochip.satochipclient;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
/**
* A CardConnectorException is thrown when a APDU command returns a response different from 0x9000
*/
public class CardConnectorException extends Exception{
/** Block or transaction hash */
private CommandAPDU c;
private ResponseAPDU r;
/**
* Creates a new exception with a detail message
*
* @param msg Detail message
*/
public CardConnectorException(String msg, CommandAPDU c, ResponseAPDU r) {
super(msg);
//only for debug purpose as it may contains sensitive data!
//this.c= c;
//this.r= r;
// safer to remove sensitive information
this.c= new CommandAPDU(c.getCLA(), c.getINS(), c.getP1(), c.getP2(), null);
byte[] sw12=new byte[2];
sw12[0]=(byte)r.getSW1();
sw12[1]=(byte)r.getSW2();
this.r= new ResponseAPDU(sw12);
}
CardConnectorException(String unable_to_recover_public_key_from_signatu) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Returns the SW12 code associated with this exception
*
* @return SW12
*/
public short getSW12() {
return (short)r.getSW();
}
/**
* Returns the SW12 code associated with this exception
*
* @return SW12
*/
public short getIns() {
return (short)c.getINS();
}
public ResponseAPDU getResponse(){
return r;
}
public CommandAPDU getCommand(){
return c;
}
}
| apache-2.0 |
a642500/Ybook | app/src/main/java/com/ybook/app/pinnedheaderlistview/SectionedBaseAdapter.java | 6634 | package com.ybook.app.pinnedheaderlistview;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.ybook.app.pinnedheaderlistview.PinnedHeaderListView.PinnedSectionedHeaderAdapter;
public abstract class SectionedBaseAdapter extends BaseAdapter implements PinnedSectionedHeaderAdapter {
private static int HEADER_VIEW_TYPE = 0;
private static int ITEM_VIEW_TYPE = 0;
/**
* Holds the calculated values of @{link getPositionInSectionForPosition}
*/
private SparseArray<Integer> mSectionPositionCache;
/**
* Holds the calculated values of @{link getSectionForPosition}
*/
private SparseArray<Integer> mSectionCache;
/**
* Holds the calculated values of @{link getCountForSection}
*/
private SparseArray<Integer> mSectionCountCache;
/**
* Caches the item count
*/
private int mCount;
/**
* Caches the section count
*/
private int mSectionCount;
public SectionedBaseAdapter() {
super();
mSectionCache = new SparseArray<Integer>();
mSectionPositionCache = new SparseArray<Integer>();
mSectionCountCache = new SparseArray<Integer>();
mCount = -1;
mSectionCount = -1;
}
@Override
public void notifyDataSetChanged() {
mSectionCache.clear();
mSectionPositionCache.clear();
mSectionCountCache.clear();
mCount = -1;
mSectionCount = -1;
super.notifyDataSetChanged();
}
@Override
public void notifyDataSetInvalidated() {
mSectionCache.clear();
mSectionPositionCache.clear();
mSectionCountCache.clear();
mCount = -1;
mSectionCount = -1;
super.notifyDataSetInvalidated();
}
@Override
public final int getCount() {
if (mCount >= 0) {
return mCount;
}
int count = 0;
for (int i = 0; i < internalGetSectionCount(); i++) {
count += internalGetCountForSection(i);
count++; // for the header view
}
mCount = count;
return count;
}
@Override
public final Object getItem(int position) {
return getItem(getSectionForPosition(position), getPositionInSectionForPosition(position));
}
@Override
public final long getItemId(int position) {
return getItemId(getSectionForPosition(position), getPositionInSectionForPosition(position));
}
@Override
public final View getView(int position, View convertView, ViewGroup parent) {
if (isSectionHeader(position)) {
return getSectionHeaderView(getSectionForPosition(position), convertView, parent);
}
return getItemView(getSectionForPosition(position), getPositionInSectionForPosition(position), convertView, parent);
}
@Override
public final int getItemViewType(int position) {
if (isSectionHeader(position)) {
return getItemViewTypeCount() + getSectionHeaderViewType(getSectionForPosition(position));
}
return getItemViewType(getSectionForPosition(position), getPositionInSectionForPosition(position));
}
@Override
public final int getViewTypeCount() {
return getItemViewTypeCount() + getSectionHeaderViewTypeCount();
}
public final int getSectionForPosition(int position) {
// first try to retrieve values from cache
Integer cachedSection = mSectionCache.get(position);
if (cachedSection != null) {
return cachedSection;
}
int sectionStart = 0;
for (int i = 0; i < internalGetSectionCount(); i++) {
int sectionCount = internalGetCountForSection(i);
int sectionEnd = sectionStart + sectionCount + 1;
if (position >= sectionStart && position < sectionEnd) {
mSectionCache.put(position, i);
return i;
}
sectionStart = sectionEnd;
}
return 0;
}
public int getPositionInSectionForPosition(int position) {
// first try to retrieve values from cache
Integer cachedPosition = mSectionPositionCache.get(position);
if (cachedPosition != null) {
return cachedPosition;
}
int sectionStart = 0;
for (int i = 0; i < internalGetSectionCount(); i++) {
int sectionCount = internalGetCountForSection(i);
int sectionEnd = sectionStart + sectionCount + 1;
if (position >= sectionStart && position < sectionEnd) {
int positionInSection = position - sectionStart - 1;
mSectionPositionCache.put(position, positionInSection);
return positionInSection;
}
sectionStart = sectionEnd;
}
return 0;
}
public final boolean isSectionHeader(int position) {
int sectionStart = 0;
for (int i = 0; i < internalGetSectionCount(); i++) {
if (position == sectionStart) {
return true;
} else if (position < sectionStart) {
return false;
}
sectionStart += internalGetCountForSection(i) + 1;
}
return false;
}
public int getItemViewType(int section, int position) {
return ITEM_VIEW_TYPE;
}
public int getItemViewTypeCount() {
return 1;
}
public int getSectionHeaderViewType(int section) {
return HEADER_VIEW_TYPE;
}
public int getSectionHeaderViewTypeCount() {
return 1;
}
public abstract Object getItem(int section, int position);
public abstract long getItemId(int section, int position);
public abstract int getSectionCount();
public abstract int getCountForSection(int section);
public abstract View getItemView(int section, int position, View convertView, ViewGroup parent);
public abstract View getSectionHeaderView(int section, View convertView, ViewGroup parent);
private int internalGetCountForSection(int section) {
Integer cachedSectionCount = mSectionCountCache.get(section);
if (cachedSectionCount != null) {
return cachedSectionCount;
}
int sectionCount = getCountForSection(section);
mSectionCountCache.put(section, sectionCount);
return sectionCount;
}
private int internalGetSectionCount() {
if (mSectionCount >= 0) {
return mSectionCount;
}
mSectionCount = getSectionCount();
return mSectionCount;
}
}
| apache-2.0 |
MKisilyov/P4CTM | src/com/luxoft/p4ctm/CTMBuilderOptions.java | 6603 | /*
* Copyright 2013 Maksim Kisilyov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.luxoft.p4ctm;
import java.io.*;
import java.util.Properties;
public class CTMBuilderOptions
{
private String server;
private String user;
private String password;
private String fileSpec;
private String requirementIdRegex;
private String typeOfChangeRegex;
private String acceptedTypesOfChangeRegex;
private String clDescriptionsOverridePath;
private String requirementsInputFile;
private String requirementsInputRegex;
private String requirementsFilterFile;
private String matrixOutputFile;
public CTMBuilderOptions()
{
this.server = "perforce:1666";
this.user = "anonymous";
this.password = "";
this.fileSpec = "//depot/...";
this.requirementIdRegex = "(?m)^\\[[xX]\\] TTS/Ref : (.*?)\\s*?$";
this.typeOfChangeRegex = "(?m)^\\[[xX]\\] (?:BF|FE|OP|QI|IN|OT) = (.*?)\\s*?$";
this.acceptedTypesOfChangeRegex = "BugFix|Feature";
this.clDescriptionsOverridePath = null;
this.requirementsInputFile = null;
this.requirementsInputRegex = "(?ms)CTRS ID: (?<rid>.*?)$.*?Object Heading: (?<name>.*?)$.*?Object Text: (?<desc>.*?)$";
this.requirementsFilterFile = null;
this.matrixOutputFile = "TM.xls";
}
public CTMBuilderOptions(String server, String user, String password, String fileSpec,
String requirementIdSearchPattern, String typeOfChangeRegex,
String acceptedTypesOfChangeRegex, String CLDescriptionsInputPath,
String requirementsInputFile, String requirementsInputRegex,
String requirementsFilterFile, String matrixOutputFile)
{
this.server = server;
this.user = user;
this.password = password;
this.fileSpec = fileSpec;
this.requirementIdRegex = requirementIdSearchPattern;
this.typeOfChangeRegex = typeOfChangeRegex;
this.acceptedTypesOfChangeRegex = acceptedTypesOfChangeRegex;
this.clDescriptionsOverridePath = CLDescriptionsInputPath;
this.requirementsInputFile = requirementsInputFile;
this.requirementsInputRegex = requirementsInputRegex;
this.requirementsFilterFile = requirementsFilterFile;
this.matrixOutputFile = matrixOutputFile;
}
public void loadFromXML(File input) throws IOException
{
new XMLIO().readXML(input);
}
public void storeToXML(File output) throws IOException
{
new XMLIO().writeXML(output);
}
public String getServer()
{
return server;
}
public String getUser()
{
return user;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getFileSpec()
{
return fileSpec;
}
public String getRequirementIdRegex()
{
return requirementIdRegex;
}
public String getTypeOfChangeRegex()
{
return typeOfChangeRegex;
}
public String getAcceptedTypesOfChangeRegex()
{
return acceptedTypesOfChangeRegex;
}
public String getCLDescriptionsOverridePath()
{
return clDescriptionsOverridePath;
}
public String getRequirementsInputFile()
{
return requirementsInputFile;
}
public String getRequirementsInputRegex()
{
return requirementsInputRegex;
}
public String getRequirementsFilterFile()
{
return requirementsFilterFile;
}
public String getMatrixOutputFile()
{
return matrixOutputFile;
}
private interface Archive
{
String fill(String key, String value);
}
private class XMLIO extends Properties
{
private void serialize(Archive archive)
{
server = archive.fill("server", server);
user = archive.fill("user", user);
fileSpec = archive.fill("file spec", fileSpec);
requirementIdRegex = archive.fill("requirement id regex", requirementIdRegex);
typeOfChangeRegex = archive.fill("type of change regex", typeOfChangeRegex);
acceptedTypesOfChangeRegex = archive.fill("accepted types of change regex", acceptedTypesOfChangeRegex);
clDescriptionsOverridePath = archive.fill("cl descriptions override path", clDescriptionsOverridePath);
requirementsInputFile = archive.fill("requirements input file", requirementsInputFile);
requirementsInputRegex = archive.fill("requirements input regex", requirementsInputRegex);
requirementsFilterFile = archive.fill("requirements filter file", requirementsFilterFile);
matrixOutputFile = archive.fill("output file", matrixOutputFile);
}
public void readXML(File file) throws IOException
{
try (InputStream inputStream = new FileInputStream(file))
{
loadFromXML(inputStream);
serialize(new InputArchive());
}
}
public void writeXML(File file) throws IOException
{
try (OutputStream outputStream = new FileOutputStream(file))
{
serialize(new OutputArchive());
storeToXML(outputStream, null);
}
}
private class InputArchive implements Archive
{
@Override
public String fill(String key, String value)
{
return getProperty(key);
}
}
private class OutputArchive implements Archive
{
@Override
public String fill(String key, String value)
{
if (key == null || value == null)
{
return null;
}
setProperty(key, value);
return value;
}
}
}
}
| apache-2.0 |
pCloud/pcloud-networking-java | serialization/src/test/java/com/pcloud/networking/serialization/EnumTypeAdapterTest.java | 5009 | /*
* Copyright (c) 2017 pCloud AG
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pcloud.networking.serialization;
import com.pcloud.networking.protocol.*;
import okio.Buffer;
import okio.ByteString;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class EnumTypeAdapterTest {
private enum StringEnumType {
@ParameterValue("something1")
FIRST_VALUE,
@ParameterValue("something2")
SECOND_VALUE,
@ParameterValue("something3")
THIRD_VALUE,
}
private enum NumberEnumType {
@ParameterValue("5000")
FIRST_VALUE,
@ParameterValue("2")
SECOND_VALUE,
@ParameterValue("10")
THIRD_VALUE,
}
private enum DuplicateNamesEnumType1 {
@ParameterValue("something")
FIRST_VALUE,
@ParameterValue("something")
SECOND_VALUE,
@ParameterValue("something")
THIRD_VALUE,
}
private enum DuplicateNamesEnumType2 {
@ParameterValue("something")
something1,
something,
}
private enum DuplicateNamesEnumType3 {
@ParameterValue("1")
FIRST_VALUE,
@ParameterValue("1")
SECOND_VALUE,
}
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void returns_Correct_Constant_When_Deserializing_Strings() throws Exception {
ProtocolReader reader = readerWithValues("something1", "something2", "something3");
TypeAdapter<StringEnumType> adapter = new EnumTypeAdapter<>(StringEnumType.class);
assertEquals(StringEnumType.FIRST_VALUE, adapter.deserialize(reader));
assertEquals(StringEnumType.SECOND_VALUE, adapter.deserialize(reader));
assertEquals(StringEnumType.THIRD_VALUE, adapter.deserialize(reader));
}
@Test
public void returns_Correct_Constant_When_Deserializing_Numbers() throws Exception {
ProtocolReader reader = readerWithValues(5000, 2, 10);
TypeAdapter<NumberEnumType> adapter = new EnumTypeAdapter<>(NumberEnumType.class);
assertEquals(NumberEnumType.FIRST_VALUE, adapter.deserialize(reader));
assertEquals(NumberEnumType.SECOND_VALUE, adapter.deserialize(reader));
assertEquals(NumberEnumType.THIRD_VALUE, adapter.deserialize(reader));
}
@Test
public void throws_On_Duplicate_Type_Annotations_When_Initialized1() throws Exception {
expectedException.expect(IllegalStateException.class);
TypeAdapter<DuplicateNamesEnumType1> adapter = new EnumTypeAdapter<>(DuplicateNamesEnumType1.class);
}
@Test
public void throws_On_Duplicate_Type_Annotations_When_Initialized2() throws Exception {
expectedException.expect(IllegalStateException.class);
TypeAdapter<DuplicateNamesEnumType2> adapter = new EnumTypeAdapter<>(DuplicateNamesEnumType2.class);
}
@Test
public void throws_On_Duplicate_Type_Annotations_When_Initialized3() throws Exception {
expectedException.expect(IllegalStateException.class);
TypeAdapter<DuplicateNamesEnumType2> adapter = new EnumTypeAdapter<>(DuplicateNamesEnumType2.class);
}
@Test
public void throws_On_Invalid_Protocol_Type1() throws Exception {
ProtocolReader reader = readerWithValues(false, true, false);
TypeAdapter<NumberEnumType> adapter = new EnumTypeAdapter<>(NumberEnumType.class);
expectedException.expect(SerializationException.class);
adapter.deserialize(reader);
}
@Test
public void throws_On_Invalid_Protocol_Type2() throws Exception {
ProtocolReader reader = readerWithValues();
TypeAdapter<NumberEnumType> adapter = new EnumTypeAdapter<>(NumberEnumType.class);
expectedException.expect(SerializationException.class);
adapter.deserialize(reader);
}
private static ProtocolReader readerWithValues(Object... values) throws IOException {
ByteString response = ResponseBytesWriter.empty()
.beginObject()
.writeValue("values", values)
.endObject()
.bytes();
ProtocolResponseReader reader = new BytesReader(new Buffer().write(response));
reader.beginResponse();
reader.beginObject();
reader.readString();
reader.beginArray();
return reader;
}
} | apache-2.0 |
AndrewHancock/MiniJava-compiler | src/main/java/ir/ops/ArrayAccess.java | 691 | package ir.ops;
import ir.visitor.IrVisitor;
public class ArrayAccess implements Expression
{
private Expression reference;
private DataType type;
private Expression index;
public ArrayAccess(Expression reference, DataType type, Expression index)
{
this.reference = reference;
this.type = type;
this.index = index;
}
@Override
public void accept(IrVisitor visitor)
{
visitor.visit(this);
}
public Expression getReference()
{
return reference;
}
public DataType getType()
{
return type;
}
public Expression getIndex()
{
return index;
}
@Override
public String toString()
{
return reference.toString() + "[" + index.toString() + "]";
}
}
| apache-2.0 |
hrovira/addama-googlecode | commons/httpclient-support/src/main/java/org/systemsbiology/addama/commons/httpclient/support/IsExpectedStatusCodeResponseCallback.java | 1491 | /*
** Copyright (C) 2003-2010 Institute for Systems Biology
** Seattle, Washington, USA.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.systemsbiology.addama.commons.httpclient.support;
import org.apache.commons.httpclient.HttpMethod;
/**
* @author hrovira
*/
public final class IsExpectedStatusCodeResponseCallback implements ResponseCallback {
private final int expectedStatusCode;
public IsExpectedStatusCodeResponseCallback(int expectedStatusCode) {
this.expectedStatusCode = expectedStatusCode;
}
public Object onResponse(int statusCode, HttpMethod method) throws HttpClientResponseException {
return (statusCode == expectedStatusCode);
}
} | apache-2.0 |
mkobayas/minimum-marshaller | src/test/java/org/mk300/marshal/minimum/test/LinkedBlockingDequeTest.java | 3613 | package org.mk300.marshal.minimum.test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicReferenceArray;
import org.apache.commons.io.HexDump;
import org.junit.Test;
import org.mk300.marshal.minimum.MinimumMarshaller;
@SuppressWarnings({"rawtypes", "unchecked"})
public class LinkedBlockingDequeTest {
@Test
public void testLinkedBlockingDeque() throws Exception {
LinkedBlockingDeque data = new LinkedBlockingDeque(10);
data.add(new Date(0));
data.add(new Date(3));
data.add(new Date(4));
data.add(new Date(5));
data.add(new Date(6));
data.add(new Date(7));
testAndPrintHexAndCheck(data);
}
// LinkedBlockingDeque は equalsメソッドを実装していない・・・
private void testAndPrintHexAndCheck(LinkedBlockingDeque<Date> target) throws Exception{
try {
byte[] bytes = MinimumMarshaller.marshal(target);
System.out.println(target.getClass().getSimpleName() + " binary size is " + bytes.length);
ByteArrayOutputStream os = new ByteArrayOutputStream();
HexDump.dump(bytes, 0, os, 0);
System.out.println(os.toString());
System.out.println("");
LinkedBlockingDeque<Date> o = (LinkedBlockingDeque<Date>)MinimumMarshaller.unmarshal(bytes);
// 正確に復元されていることの検証
if( o.size() != target.size()) {
throw new RuntimeException("オブジェクトが異なります。target=" + target + ", desr=" + o);
}
if( o.remainingCapacity() != target.remainingCapacity()) {
throw new RuntimeException("オブジェクトが異なります。target=" + target + ", desr=" + o);
}
Date[] desr = o.toArray(new Date[0]);
Date[] origin = target.toArray(new Date[0]);
for(int i=0; i<desr.length ; i++) {
if(desr[i] == null && origin[i] == null) {
continue;
}
if(desr[i] == null || origin[i] == null) {
throw new RuntimeException("オブジェクトが異なります。target=" + target + ", desr=" + o);
}
if( ! desr[i].equals(origin[i])) {
throw new RuntimeException("オブジェクトが異なります。target=" + target + ", desr=" + o);
}
}
} finally {
}
// おまけ 普通のByteArray*Streamも使えるか?
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
MinimumMarshaller.marshal(target, baos);
byte[] bytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
LinkedBlockingDeque<Date> o = (LinkedBlockingDeque<Date>)MinimumMarshaller.unmarshal(bais);
// 正確に復元されていることの検証
if( o.size() != target.size()) {
throw new RuntimeException("オブジェクトが異なります。target=" + target + ", desr=" + o);
}
if( o.remainingCapacity() != target.remainingCapacity()) {
throw new RuntimeException("オブジェクトが異なります。target=" + target + ", desr=" + o);
}
Date[] desr = o.toArray(new Date[0]);
Date[] origin = target.toArray(new Date[0]);
for(int i=0; i<desr.length ; i++) {
if(desr[i] == null && origin[i] == null) {
continue;
}
if(desr[i] == null || origin[i] == null) {
throw new RuntimeException("オブジェクトが異なります。target=" + target + ", desr=" + o);
}
if( ! desr[i].equals(origin[i])) {
throw new RuntimeException("オブジェクトが異なります。target=" + target + ", desr=" + o);
}
}
} finally {
}
}
}
| apache-2.0 |
uolcombr/runas | src/main/java/br/com/uol/runas/MainApplication.java | 1072 | /*
* Copyright 2013-2014 UOL - Universo Online Team
*
* 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 br.com.uol.runas;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan
@EnableAutoConfiguration
public class MainApplication {
public static void main(String[] args) {
System.getProperties().put("server.port", 8195);
SpringApplication.run(MainApplication.class, args);
}
}
| apache-2.0 |
MedStudy/brightcove-player-plugin | src/android/Cmd.java | 248 | package net.nopattern.cordova.brightcoveplayer;
/**
* Created by peterchin on 6/9/16.
*/
public enum Cmd {
LOAD,
LOADED,
DISABLE,
ENABLE,
PAUSE,
PLAY,
HIDE,
SHOW,
SEEK,
RATE,
RESUME,
REPOSITION
};
| apache-2.0 |
palava/palava-model | src/main/java/de/cosmocode/palava/model/business/AbstractAddress.java | 7669 | /**
* Copyright 2010 CosmoCode GmbH
*
* 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 de.cosmocode.palava.model.business;
import java.util.Locale;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.EmailValidator;
import org.apache.commons.validator.UrlValidator;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import de.cosmocode.commons.Locales;
import de.cosmocode.commons.Patterns;
import de.cosmocode.commons.TrimMode;
/**
* Abstract base implementation of the {@link AddressBase} interface.
*
* @author Willi Schoenborn
*/
@Embeddable
@MappedSuperclass
public abstract class AbstractAddress implements AddressBase {
private static final EmailValidator EMAIL_VALIDATOR = EmailValidator.getInstance();
private static final UrlValidator URL_VALIDATOR = new UrlValidator();
private static final Set<String> INVERSE_ADDRESS_COUNTRIES = ImmutableSet.of(
Locale.US.getCountry(),
Locale.UK.getCountry(),
Locale.CANADA.getCountry(),
Locales.AUSTRALIA.getCountry(),
Locale.FRANCE.getCountry(),
Locales.NEW_ZEALAND.getCountry()
);
private String street;
@Column(name = "street_number")
private String streetNumber;
private String additional;
@Column(name = "postal_code")
private String postalCode;
private String district;
@Column(name = "city_name")
private String cityName;
private String state;
@Column(name = "country_code")
private String countryCode;
private Double latitude;
private Double longitude;
private String phone;
@Column(name = "mobile_phone")
private String mobilePhone;
private String fax;
@Column(unique = true)
private String email;
private String website;
@Transient
private final transient Location location = new InternalLocation();
@Override
public String getStreet() {
return street;
}
@Override
public void setStreet(String street) {
this.street = TrimMode.NULL.apply(street);
}
@Override
public String getStreetNumber() {
return streetNumber;
}
@Override
public void setStreetNumber(String streetNumber) {
this.streetNumber = TrimMode.NULL.apply(streetNumber);
}
@Override
public String getLocalizedAddress() {
if (INVERSE_ADDRESS_COUNTRIES.contains(countryCode)) {
return getAddressInverse();
} else {
return getAddress();
}
}
private String getAddress() {
return String.format("%s %s", street, streetNumber).trim();
}
private String getAddressInverse() {
return String.format("%s %s", streetNumber, street).trim();
}
@Override
public String getAdditional() {
return additional;
}
@Override
public void setAdditional(String additional) {
this.additional = TrimMode.NULL.apply(additional);
}
@Override
public String getPostalCode() {
return postalCode;
}
@Override
public void setPostalCode(String postalCode) {
this.postalCode = TrimMode.NULL.apply(postalCode);
}
@Override
public String getDistrict() {
return district;
}
@Override
public void setDistrict(String district) {
this.district = TrimMode.NULL.apply(district);
}
@Override
public String getCityName() {
return cityName;
}
@Override
public void setCityName(String cityName) {
this.cityName = TrimMode.NULL.apply(cityName);
}
@Override
public String getState() {
return state;
}
@Override
public void setState(String state) {
this.state = TrimMode.NULL.apply(state);
}
@Override
public String getCountryCode() {
return countryCode == null ? null : countryCode.toUpperCase();
}
@Override
public void setCountryCode(String code) {
this.countryCode = StringUtils.upperCase(TrimMode.NULL.apply(code));
if (countryCode == null) return;
Preconditions.checkArgument(Patterns.ISO_3166_1_ALPHA_2.matcher(countryCode).matches(),
"%s does not match %s", countryCode, Patterns.ISO_3166_1_ALPHA_2.pattern()
);
}
@Override
public Location getLocation() {
return location;
}
/**
* Internal implementation of the {@link Location} interface which
* owns a reference to the enclosing class and is able to directly manipulate the
* corresponding values.
*
* @author Willi Schoenborn
*/
private final class InternalLocation extends AbstractLocation {
@Override
public Double getLatitude() {
return latitude;
}
@Override
public void setLatitude(Double latitude) {
AbstractAddress.this.latitude = latitude;
}
@Override
public Double getLongitude() {
return longitude;
}
@Override
public void setLongitude(Double longitude) {
AbstractAddress.this.longitude = longitude;
}
}
@Override
public void setLocation(Location location) {
Preconditions.checkNotNull(location, "Location");
this.latitude = location.getLatitude();
this.longitude = location.getLongitude();
}
@Override
public boolean hasLocation() {
return latitude != null && longitude != null;
}
@Override
public String getPhone() {
return phone;
}
@Override
public void setPhone(String phone) {
this.phone = TrimMode.NULL.apply(phone);
}
@Override
public String getMobilePhone() {
return mobilePhone;
}
@Override
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = TrimMode.NULL.apply(mobilePhone);
}
@Override
public String getFax() {
return fax;
}
@Override
public void setFax(String fax) {
this.fax = TrimMode.NULL.apply(fax);
}
@Override
public String getEmail() {
return email;
}
@Override
public void setEmail(String e) {
this.email = TrimMode.NULL.apply(e);
if (email == null) return;
Preconditions.checkArgument(EMAIL_VALIDATOR.isValid(email), "%s is not a valid email", email);
}
@Override
public String getWebsite() {
return website;
}
@Override
public void setWebsite(String w) {
this.website = TrimMode.NULL.apply(w);
if (website == null) return;
Preconditions.checkArgument(URL_VALIDATOR.isValid(website), "%s is not a valid website", website);
}
}
| apache-2.0 |
gzxishan/OftenPorter | Demo/src/main/java/cn/xishan/oftenporter/demo/testmem/porter/MemUnit.java | 481 | package cn.xishan.oftenporter.demo.testmem.porter;
import cn.xishan.oftenporter.porter.core.annotation.AutoSet;
import cn.xishan.oftenporter.porter.core.util.LogMethodInvoke;
/**
* @author Created by https://github.com/CLovinr on 2018/9/22.
*/
public class MemUnit
{
@AutoSet
Obj1 obj1;
@LogMethodInvoke
public void test(){
testInner();
}
@LogMethodInvoke
void testInner(){
System.out.println("..................."+obj1);
}
}
| apache-2.0 |
pushtechnology/diffusion-rest-adapter | configuration-model/src/main/java/com/pushtechnology/adapters/rest/model/v13/EndpointConfig.java | 1884 | /*******************************************************************************
* Copyright (C) 2017 Push Technology Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.pushtechnology.adapters.rest.model.v13;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NonNull;
import lombok.ToString;
import lombok.Value;
/**
* Endpoint configuration. Version 13.
* <p>
* Description of a REST endpoint to poll.
*
* @author Push Technology Limited
*/
@Value
@Builder
@AllArgsConstructor
@ToString(of = "name")
public class EndpointConfig {
/**
* The name of the endpoint.
*/
@NonNull
String name;
/**
* The URL of the endpoint.
*/
@NonNull
String url;
/**
* The topic path to map the endpoint to. It is relative to the service
* topic path root.
*/
@NonNull
String topicPath;
/**
* The type of content produced by the endpoint.
* <p>
* Supports the values:
* <ul>
* <li>auto</li>
* <li>json</li>
* <li>application/json</li>
* <li>text/json</li>
* <li>string</li>
* <li>text/plain</li>
* <li>binary</li>
* <li>application/octet-stream</li>
* </ul>
*/
@NonNull
String produces;
}
| apache-2.0 |
rPraml/org.openntf.domino | domino/commons/src/main/java/org/openntf/domino/commons/Hash.java | 3653 | /*
* Copyright 2015 - FOCONIS AG
*
* 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 o
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package org.openntf.domino.commons;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Class to compute several hashes. (mainly MD5, maybe extended to SHA-1 and others)
*
* @author Roland Praml, FOCONIS AG
*
*/
public enum Hash {
;
/**
* Checksum (various variants). The algorithm to be used has to be passed as parameter.
*/
public static String checksum(final byte[] whose, final String algorithmName) throws NoSuchAlgorithmException {
MessageDigest algorithm = MessageDigest.getInstance(algorithmName);
algorithm.reset();
algorithm.update(whose);
return finishChecksum(algorithm);
}
private static String finishChecksum(final MessageDigest algorithm) {
BigInteger bi = new BigInteger(1, algorithm.digest());
return bi.toString(16);
}
public static String checksum(final String whose, final String alg) throws NoSuchAlgorithmException {
return checksum(whose.getBytes(Strings.UTF_8_CHARSET), alg);
}
public static String checksum(final File whose, final String alg) throws IOException, NoSuchAlgorithmException {
byte[] buffer = new byte[32768];
MessageDigest algorithm = MessageDigest.getInstance(alg);
algorithm.reset();
FileInputStream fis = new FileInputStream(whose);
int nread;
try {
while ((nread = fis.read(buffer)) > 0)
algorithm.update(buffer, 0, nread);
return finishChecksum(algorithm);
} finally {
fis.close();
}
}
public static String checksum(final Serializable whose, final String algorithm) throws NoSuchAlgorithmException {
String result = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream out = new ObjectOutputStream(baos);
out.writeObject(whose);
result = checksum(baos.toByteArray(), algorithm);
out.close();
} catch (IOException ioex) {
throw new RuntimeException("Unexpected IOException", ioex);
}
return result;
}
/**
* Same variants for MD5.
*/
public static String md5(final byte[] whose) {
try {
return checksum(whose, "MD5");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("No MD5 algorithm present, why that?");
}
}
public static String md5(final String whose) {
try {
return checksum(whose, "MD5");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("No MD5 algorithm present, why that?");
}
}
public static String md5(final File whose) throws IOException {
try {
return checksum(whose, "MD5");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("No MD5 algorithm present, why that?");
}
}
public static String md5(final Serializable whose) {
try {
return checksum(whose, "MD5");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("No MD5 algorithm present, why that?");
}
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-inspector/src/main/java/com/amazonaws/services/inspector/model/transform/DurationRangeJsonUnmarshaller.java | 2962 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.inspector.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.inspector.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* DurationRange JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DurationRangeJsonUnmarshaller implements Unmarshaller<DurationRange, JsonUnmarshallerContext> {
public DurationRange unmarshall(JsonUnmarshallerContext context) throws Exception {
DurationRange durationRange = new DurationRange();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("minSeconds", targetDepth)) {
context.nextToken();
durationRange.setMinSeconds(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("maxSeconds", targetDepth)) {
context.nextToken();
durationRange.setMaxSeconds(context.getUnmarshaller(Integer.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return durationRange;
}
private static DurationRangeJsonUnmarshaller instance;
public static DurationRangeJsonUnmarshaller getInstance() {
if (instance == null)
instance = new DurationRangeJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
SLAsticSPE/slastic | src-gen/kieker/tools/slastic/metamodel/componentAssembly/AssemblyConnector.java | 1803 | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package kieker.tools.slastic.metamodel.componentAssembly;
import kieker.tools.slastic.metamodel.core.FQNamedEntity;
import kieker.tools.slastic.metamodel.typeRepository.ConnectorType;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Assembly Connector</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link kieker.tools.slastic.metamodel.componentAssembly.AssemblyConnector#getConnectorType <em>Connector Type</em>}</li>
* </ul>
* </p>
*
* @see kieker.tools.slastic.metamodel.componentAssembly.ComponentAssemblyPackage#getAssemblyConnector()
* @model abstract="true"
* @generated
*/
public interface AssemblyConnector extends FQNamedEntity {
/**
* Returns the value of the '<em><b>Connector Type</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Connector Type</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Connector Type</em>' reference.
* @see #setConnectorType(ConnectorType)
* @see kieker.tools.slastic.metamodel.componentAssembly.ComponentAssemblyPackage#getAssemblyConnector_ConnectorType()
* @model required="true" ordered="false"
* @generated
*/
ConnectorType getConnectorType();
/**
* Sets the value of the '{@link kieker.tools.slastic.metamodel.componentAssembly.AssemblyConnector#getConnectorType <em>Connector Type</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Connector Type</em>' reference.
* @see #getConnectorType()
* @generated
*/
void setConnectorType(ConnectorType value);
} // AssemblyConnector
| apache-2.0 |
zpao/buck | src/com/facebook/buck/features/project/intellij/IntellijModulesListParser.java | 3637 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.features.project.intellij;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.util.log.Logger;
import com.facebook.buck.features.project.intellij.model.ModuleIndexEntry;
import com.facebook.buck.util.xml.XmlDomParser;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSet.Builder;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/** Responsible for parsing an existing modules.xml file */
public class IntellijModulesListParser {
private static Logger LOG = Logger.get(IntellijModulesListParser.class);
/**
* @param modulesFile modules.xml input stream
* @return A list of module entries as specified by the modules.xml file
* @throws IOException
*/
public ImmutableSet<ModuleIndexEntry> getAllModules(InputStream modulesFile) throws IOException {
final Document doc;
try {
doc = XmlDomParser.parse(modulesFile);
} catch (SAXException e) {
LOG.error("Cannot read modules.xml file", e);
throw new HumanReadableException(
"Could not update 'modules.xml' file because it is malformed", e);
}
final Builder<ModuleIndexEntry> builder = ImmutableSet.builder();
try {
XPath xpath = XPathFactory.newInstance().newXPath();
final NodeList moduleList =
(NodeList)
xpath
.compile("/project/component/modules/module")
.evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < moduleList.getLength(); i++) {
final Element moduleEntry = (Element) moduleList.item(i);
if (!moduleEntry.hasAttribute("filepath")) {
continue;
}
String filepath = moduleEntry.getAttribute("filepath");
String fileurl = moduleEntry.getAttribute("fileurl");
String filepathWithoutProjectPrefix;
// The template has a hardcoded $PROJECT_DIR$/ prefix, so we need to strip that out
// of the value we pass to ST
if (filepath.startsWith("$PROJECT_DIR$")) {
filepathWithoutProjectPrefix = filepath.substring("$PROJECT_DIR$".length() + 1);
} else {
filepathWithoutProjectPrefix = filepath;
}
builder.add(
ModuleIndexEntry.builder()
.setFilePath(Paths.get(filepathWithoutProjectPrefix))
.setFileUrl(fileurl)
.setGroup(
moduleEntry.hasAttribute("group") ? moduleEntry.getAttribute("group") : null)
.build());
}
} catch (XPathExpressionException e) {
throw new HumanReadableException("Illegal xpath expression.", e);
}
return builder.build();
}
}
| apache-2.0 |
Swapnil133609/Zeus-Controls | app/src/main/java/com/bvalosek/cpuspy/CpuSpyApp.java | 2362 | //-----------------------------------------------------------------------------
//
// (C) Brandon Valosek, 2011 <bvalosek@gmail.com>
//
//-----------------------------------------------------------------------------
// Modified by Willi Ye to work with big.LITTLE
package com.bvalosek.cpuspy;
import android.app.Application;
import android.content.Context;
import com.swapnil133609.zeuscontrols.utils.Utils;
import java.util.HashMap;
import java.util.Map;
/**
* main application class
*/
public class CpuSpyApp extends Application {
private final String PREF_OFFSETS;
/**
* the long-living object used to monitor the system frequency states
*/
private final CpuStateMonitor _monitor;
public CpuSpyApp(int core) {
PREF_OFFSETS = "offsets" + core;
_monitor = new CpuStateMonitor(core);
}
/**
* On application start, load the saved offsets and stash the current kernel
* version string
*/
@Override
public void onCreate() {
super.onCreate();
loadOffsets(getApplicationContext());
}
/**
* @return the internal CpuStateMonitor object
*/
public CpuStateMonitor getCpuStateMonitor() {
return _monitor;
}
/**
* Load the saved string of offsets from preferences and put it into the
* state monitor
*/
public void loadOffsets(Context context) {
String prefs = Utils.getString(PREF_OFFSETS, "", context);
if (prefs.length() < 1) return;
// split the string by peroids and then the info by commas and load
Map<Integer, Long> offsets = new HashMap<>();
String[] sOffsets = prefs.split(",");
for (String offset : sOffsets) {
String[] parts = offset.split(" ");
offsets.put(Utils.stringToInt(parts[0]), Utils.stringToLong(parts[1]));
}
_monitor.setOffsets(offsets);
}
/**
* Save the state-time offsets as a string e.g. "100 24, 200 251, 500 124
* etc
*/
public void saveOffsets(Context context) {
// build the string by iterating over the freq->duration map
String str = "";
for (Map.Entry<Integer, Long> entry : _monitor.getOffsets().entrySet())
str += entry.getKey() + " " + entry.getValue() + ",";
Utils.saveString(PREF_OFFSETS, str, context);
}
} | apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-kendra/src/main/java/com/amazonaws/services/kendra/model/ConfluenceSpaceToIndexFieldMapping.java | 10473 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.kendra.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Defines the mapping between a field in the Confluence data source to an Amazon Kendra index field.
* </p>
* <p>
* You must first create the index field using the <code>UpdateIndex</code> API.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/kendra-2019-02-03/ConfluenceSpaceToIndexFieldMapping"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ConfluenceSpaceToIndexFieldMapping implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The name of the field in the data source.
* </p>
*/
private String dataSourceFieldName;
/**
* <p>
* The format for date fields in the data source. If the field specified in <code>DataSourceFieldName</code> is a
* date field you must specify the date format. If the field is not a date field, an exception is thrown.
* </p>
*/
private String dateFieldFormat;
/**
* <p>
* The name of the index field to map to the Confluence data source field. The index field type must match the
* Confluence field type.
* </p>
*/
private String indexFieldName;
/**
* <p>
* The name of the field in the data source.
* </p>
*
* @param dataSourceFieldName
* The name of the field in the data source.
* @see ConfluenceSpaceFieldName
*/
public void setDataSourceFieldName(String dataSourceFieldName) {
this.dataSourceFieldName = dataSourceFieldName;
}
/**
* <p>
* The name of the field in the data source.
* </p>
*
* @return The name of the field in the data source.
* @see ConfluenceSpaceFieldName
*/
public String getDataSourceFieldName() {
return this.dataSourceFieldName;
}
/**
* <p>
* The name of the field in the data source.
* </p>
*
* @param dataSourceFieldName
* The name of the field in the data source.
* @return Returns a reference to this object so that method calls can be chained together.
* @see ConfluenceSpaceFieldName
*/
public ConfluenceSpaceToIndexFieldMapping withDataSourceFieldName(String dataSourceFieldName) {
setDataSourceFieldName(dataSourceFieldName);
return this;
}
/**
* <p>
* The name of the field in the data source.
* </p>
*
* @param dataSourceFieldName
* The name of the field in the data source.
* @return Returns a reference to this object so that method calls can be chained together.
* @see ConfluenceSpaceFieldName
*/
public ConfluenceSpaceToIndexFieldMapping withDataSourceFieldName(ConfluenceSpaceFieldName dataSourceFieldName) {
this.dataSourceFieldName = dataSourceFieldName.toString();
return this;
}
/**
* <p>
* The format for date fields in the data source. If the field specified in <code>DataSourceFieldName</code> is a
* date field you must specify the date format. If the field is not a date field, an exception is thrown.
* </p>
*
* @param dateFieldFormat
* The format for date fields in the data source. If the field specified in <code>DataSourceFieldName</code>
* is a date field you must specify the date format. If the field is not a date field, an exception is
* thrown.
*/
public void setDateFieldFormat(String dateFieldFormat) {
this.dateFieldFormat = dateFieldFormat;
}
/**
* <p>
* The format for date fields in the data source. If the field specified in <code>DataSourceFieldName</code> is a
* date field you must specify the date format. If the field is not a date field, an exception is thrown.
* </p>
*
* @return The format for date fields in the data source. If the field specified in <code>DataSourceFieldName</code>
* is a date field you must specify the date format. If the field is not a date field, an exception is
* thrown.
*/
public String getDateFieldFormat() {
return this.dateFieldFormat;
}
/**
* <p>
* The format for date fields in the data source. If the field specified in <code>DataSourceFieldName</code> is a
* date field you must specify the date format. If the field is not a date field, an exception is thrown.
* </p>
*
* @param dateFieldFormat
* The format for date fields in the data source. If the field specified in <code>DataSourceFieldName</code>
* is a date field you must specify the date format. If the field is not a date field, an exception is
* thrown.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ConfluenceSpaceToIndexFieldMapping withDateFieldFormat(String dateFieldFormat) {
setDateFieldFormat(dateFieldFormat);
return this;
}
/**
* <p>
* The name of the index field to map to the Confluence data source field. The index field type must match the
* Confluence field type.
* </p>
*
* @param indexFieldName
* The name of the index field to map to the Confluence data source field. The index field type must match
* the Confluence field type.
*/
public void setIndexFieldName(String indexFieldName) {
this.indexFieldName = indexFieldName;
}
/**
* <p>
* The name of the index field to map to the Confluence data source field. The index field type must match the
* Confluence field type.
* </p>
*
* @return The name of the index field to map to the Confluence data source field. The index field type must match
* the Confluence field type.
*/
public String getIndexFieldName() {
return this.indexFieldName;
}
/**
* <p>
* The name of the index field to map to the Confluence data source field. The index field type must match the
* Confluence field type.
* </p>
*
* @param indexFieldName
* The name of the index field to map to the Confluence data source field. The index field type must match
* the Confluence field type.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ConfluenceSpaceToIndexFieldMapping withIndexFieldName(String indexFieldName) {
setIndexFieldName(indexFieldName);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getDataSourceFieldName() != null)
sb.append("DataSourceFieldName: ").append(getDataSourceFieldName()).append(",");
if (getDateFieldFormat() != null)
sb.append("DateFieldFormat: ").append(getDateFieldFormat()).append(",");
if (getIndexFieldName() != null)
sb.append("IndexFieldName: ").append(getIndexFieldName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ConfluenceSpaceToIndexFieldMapping == false)
return false;
ConfluenceSpaceToIndexFieldMapping other = (ConfluenceSpaceToIndexFieldMapping) obj;
if (other.getDataSourceFieldName() == null ^ this.getDataSourceFieldName() == null)
return false;
if (other.getDataSourceFieldName() != null && other.getDataSourceFieldName().equals(this.getDataSourceFieldName()) == false)
return false;
if (other.getDateFieldFormat() == null ^ this.getDateFieldFormat() == null)
return false;
if (other.getDateFieldFormat() != null && other.getDateFieldFormat().equals(this.getDateFieldFormat()) == false)
return false;
if (other.getIndexFieldName() == null ^ this.getIndexFieldName() == null)
return false;
if (other.getIndexFieldName() != null && other.getIndexFieldName().equals(this.getIndexFieldName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getDataSourceFieldName() == null) ? 0 : getDataSourceFieldName().hashCode());
hashCode = prime * hashCode + ((getDateFieldFormat() == null) ? 0 : getDateFieldFormat().hashCode());
hashCode = prime * hashCode + ((getIndexFieldName() == null) ? 0 : getIndexFieldName().hashCode());
return hashCode;
}
@Override
public ConfluenceSpaceToIndexFieldMapping clone() {
try {
return (ConfluenceSpaceToIndexFieldMapping) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.kendra.model.transform.ConfluenceSpaceToIndexFieldMappingMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-shield/src/main/java/com/amazonaws/services/shield/model/SummarizedAttackVector.java | 7238 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.shield.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* A summary of information about the attack.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/shield-2016-06-02/SummarizedAttackVector" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SummarizedAttackVector implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The attack type, for example, SNMP reflection or SYN flood.
* </p>
*/
private String vectorType;
/**
* <p>
* The list of counters that describe the details of the attack.
* </p>
*/
private java.util.List<SummarizedCounter> vectorCounters;
/**
* <p>
* The attack type, for example, SNMP reflection or SYN flood.
* </p>
*
* @param vectorType
* The attack type, for example, SNMP reflection or SYN flood.
*/
public void setVectorType(String vectorType) {
this.vectorType = vectorType;
}
/**
* <p>
* The attack type, for example, SNMP reflection or SYN flood.
* </p>
*
* @return The attack type, for example, SNMP reflection or SYN flood.
*/
public String getVectorType() {
return this.vectorType;
}
/**
* <p>
* The attack type, for example, SNMP reflection or SYN flood.
* </p>
*
* @param vectorType
* The attack type, for example, SNMP reflection or SYN flood.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SummarizedAttackVector withVectorType(String vectorType) {
setVectorType(vectorType);
return this;
}
/**
* <p>
* The list of counters that describe the details of the attack.
* </p>
*
* @return The list of counters that describe the details of the attack.
*/
public java.util.List<SummarizedCounter> getVectorCounters() {
return vectorCounters;
}
/**
* <p>
* The list of counters that describe the details of the attack.
* </p>
*
* @param vectorCounters
* The list of counters that describe the details of the attack.
*/
public void setVectorCounters(java.util.Collection<SummarizedCounter> vectorCounters) {
if (vectorCounters == null) {
this.vectorCounters = null;
return;
}
this.vectorCounters = new java.util.ArrayList<SummarizedCounter>(vectorCounters);
}
/**
* <p>
* The list of counters that describe the details of the attack.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setVectorCounters(java.util.Collection)} or {@link #withVectorCounters(java.util.Collection)} if you want
* to override the existing values.
* </p>
*
* @param vectorCounters
* The list of counters that describe the details of the attack.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SummarizedAttackVector withVectorCounters(SummarizedCounter... vectorCounters) {
if (this.vectorCounters == null) {
setVectorCounters(new java.util.ArrayList<SummarizedCounter>(vectorCounters.length));
}
for (SummarizedCounter ele : vectorCounters) {
this.vectorCounters.add(ele);
}
return this;
}
/**
* <p>
* The list of counters that describe the details of the attack.
* </p>
*
* @param vectorCounters
* The list of counters that describe the details of the attack.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public SummarizedAttackVector withVectorCounters(java.util.Collection<SummarizedCounter> vectorCounters) {
setVectorCounters(vectorCounters);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getVectorType() != null)
sb.append("VectorType: ").append(getVectorType()).append(",");
if (getVectorCounters() != null)
sb.append("VectorCounters: ").append(getVectorCounters());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof SummarizedAttackVector == false)
return false;
SummarizedAttackVector other = (SummarizedAttackVector) obj;
if (other.getVectorType() == null ^ this.getVectorType() == null)
return false;
if (other.getVectorType() != null && other.getVectorType().equals(this.getVectorType()) == false)
return false;
if (other.getVectorCounters() == null ^ this.getVectorCounters() == null)
return false;
if (other.getVectorCounters() != null && other.getVectorCounters().equals(this.getVectorCounters()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getVectorType() == null) ? 0 : getVectorType().hashCode());
hashCode = prime * hashCode + ((getVectorCounters() == null) ? 0 : getVectorCounters().hashCode());
return hashCode;
}
@Override
public SummarizedAttackVector clone() {
try {
return (SummarizedAttackVector) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.shield.model.transform.SummarizedAttackVectorMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| apache-2.0 |
punkhorn/camel-upstream | components/camel-rest/src/main/java/org/apache/camel/component/rest/RestEndpoint.java | 20335 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.rest;
import java.util.Map;
import java.util.Set;
import org.apache.camel.Component;
import org.apache.camel.Consumer;
import org.apache.camel.ExchangePattern;
import org.apache.camel.NoFactoryAvailableException;
import org.apache.camel.NoSuchBeanException;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.spi.FactoryFinder;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.RestConfiguration;
import org.apache.camel.spi.RestConsumerFactory;
import org.apache.camel.spi.RestProducerFactory;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;
import org.apache.camel.support.DefaultEndpoint;
import org.apache.camel.util.HostUtils;
import org.apache.camel.util.ObjectHelper;
import static org.apache.camel.support.RestProducerFactoryHelper.setupComponent;
/**
* The rest component is used for either hosting REST services (consumer) or calling external REST services (producer).
*/
@UriEndpoint(firstVersion = "2.14.0", scheme = "rest", title = "REST", syntax = "rest:method:path:uriTemplate", label = "core,rest", lenientProperties = true)
public class RestEndpoint extends DefaultEndpoint {
public static final String[] DEFAULT_REST_CONSUMER_COMPONENTS = new String[]{"coap", "netty-http", "netty4-http", "jetty", "restlet", "servlet", "spark-java", "undertow"};
public static final String[] DEFAULT_REST_PRODUCER_COMPONENTS = new String[]{"http", "http4", "netty4-http", "jetty", "restlet", "undertow"};
public static final String DEFAULT_API_COMPONENT_NAME = "swagger";
public static final String RESOURCE_PATH = "META-INF/services/org/apache/camel/rest/";
@UriPath(label = "common", enums = "get,post,put,delete,patch,head,trace,connect,options") @Metadata(required = true)
private String method;
@UriPath(label = "common") @Metadata(required = true)
private String path;
@UriPath(label = "common")
private String uriTemplate;
@UriParam(label = "common")
private String consumes;
@UriParam(label = "common")
private String produces;
@UriParam(label = "common")
private String componentName;
@UriParam(label = "common")
private String inType;
@UriParam(label = "common")
private String outType;
@UriParam(label = "common")
private String routeId;
@UriParam(label = "consumer")
private String description;
@UriParam(label = "producer")
private String apiDoc;
@UriParam(label = "producer")
private String host;
@UriParam(label = "producer", multiValue = true)
private String queryParameters;
@UriParam(label = "producer", enums = "auto,off,json,xml,json_xml")
private RestConfiguration.RestBindingMode bindingMode;
private Map<String, Object> parameters;
public RestEndpoint(String endpointUri, RestComponent component) {
super(endpointUri, component);
setExchangePattern(ExchangePattern.InOut);
}
@Override
public RestComponent getComponent() {
return (RestComponent) super.getComponent();
}
public String getMethod() {
return method;
}
/**
* HTTP method to use.
*/
public void setMethod(String method) {
this.method = method;
}
public String getPath() {
return path;
}
/**
* The base path
*/
public void setPath(String path) {
this.path = path;
}
public String getUriTemplate() {
return uriTemplate;
}
/**
* The uri template
*/
public void setUriTemplate(String uriTemplate) {
this.uriTemplate = uriTemplate;
}
public String getConsumes() {
return consumes;
}
/**
* Media type such as: 'text/xml', or 'application/json' this REST service accepts.
* By default we accept all kinds of types.
*/
public void setConsumes(String consumes) {
this.consumes = consumes;
}
public String getProduces() {
return produces;
}
/**
* Media type such as: 'text/xml', or 'application/json' this REST service returns.
*/
public void setProduces(String produces) {
this.produces = produces;
}
public String getComponentName() {
return componentName;
}
/**
* The Camel Rest component to use for the REST transport, such as restlet, spark-rest.
* If no component has been explicit configured, then Camel will lookup if there is a Camel component
* that integrates with the Rest DSL, or if a org.apache.camel.spi.RestConsumerFactory is registered in the registry.
* If either one is found, then that is being used.
*/
public void setComponentName(String componentName) {
this.componentName = componentName;
}
public String getInType() {
return inType;
}
/**
* To declare the incoming POJO binding type as a FQN class name
*/
public void setInType(String inType) {
this.inType = inType;
}
public String getOutType() {
return outType;
}
/**
* To declare the outgoing POJO binding type as a FQN class name
*/
public void setOutType(String outType) {
this.outType = outType;
}
public String getRouteId() {
return routeId;
}
/**
* Name of the route this REST services creates
*/
public void setRouteId(String routeId) {
this.routeId = routeId;
}
public String getDescription() {
return description;
}
/**
* Human description to document this REST service
*/
public void setDescription(String description) {
this.description = description;
}
public Map<String, Object> getParameters() {
return parameters;
}
/**
* Additional parameters to configure the consumer of the REST transport for this REST service
*/
public void setParameters(Map<String, Object> parameters) {
this.parameters = parameters;
}
public String getApiDoc() {
return apiDoc;
}
/**
* The swagger api doc resource to use.
* The resource is loaded from classpath by default and must be in JSon format.
*/
public void setApiDoc(String apiDoc) {
this.apiDoc = apiDoc;
}
public String getHost() {
return host;
}
/**
* Host and port of HTTP service to use (override host in swagger schema)
*/
public void setHost(String host) {
this.host = host;
}
public String getQueryParameters() {
return queryParameters;
}
/**
* Query parameters for the HTTP service to call
*/
public void setQueryParameters(String queryParameters) {
this.queryParameters = queryParameters;
}
public RestConfiguration.RestBindingMode getBindingMode() {
return bindingMode;
}
/**
* Configures the binding mode for the producer. If set to anything
* other than 'off' the producer will try to convert the body of
* the incoming message from inType to the json or xml, and the
* response from json or xml to outType.
*/
public void setBindingMode(RestConfiguration.RestBindingMode bindingMode) {
this.bindingMode = bindingMode;
}
public void setBindingMode(String bindingMode) {
this.bindingMode = RestConfiguration.RestBindingMode.valueOf(bindingMode.toLowerCase());
}
@Override
public Producer createProducer() throws Exception {
if (ObjectHelper.isEmpty(host)) {
// hostname must be provided
throw new IllegalArgumentException("Hostname must be configured on either restConfiguration"
+ " or in the rest endpoint uri as a query parameter with name host, eg rest:" + method + ":" + path + "?host=someserver");
}
RestProducerFactory apiDocFactory = null;
RestProducerFactory factory = null;
if (apiDoc != null) {
log.debug("Discovering camel-swagger-java on classpath for using api-doc: {}", apiDoc);
// lookup on classpath using factory finder to automatic find it (just add camel-swagger-java to classpath etc)
try {
FactoryFinder finder = getCamelContext().getFactoryFinder(RESOURCE_PATH);
Object instance = finder.newInstance(DEFAULT_API_COMPONENT_NAME);
if (instance instanceof RestProducerFactory) {
// this factory from camel-swagger-java will facade the http component in use
apiDocFactory = (RestProducerFactory) instance;
}
parameters.put("apiDoc", apiDoc);
} catch (NoFactoryAvailableException e) {
throw new IllegalStateException("Cannot find camel-swagger-java on classpath to use with api-doc: " + apiDoc);
}
}
String cname = getComponentName();
if (cname != null) {
Object comp = getCamelContext().getRegistry().lookupByName(getComponentName());
if (comp instanceof RestProducerFactory) {
factory = (RestProducerFactory) comp;
} else {
comp = setupComponent(getComponentName(), getCamelContext(), (Map<String, Object>) parameters.get("component"));
if (comp instanceof RestProducerFactory) {
factory = (RestProducerFactory) comp;
}
}
if (factory == null) {
if (comp != null) {
throw new IllegalArgumentException("Component " + getComponentName() + " is not a RestProducerFactory");
} else {
throw new NoSuchBeanException(getComponentName(), RestProducerFactory.class.getName());
}
}
cname = getComponentName();
}
// try all components
if (factory == null) {
for (String name : getCamelContext().getComponentNames()) {
Component comp = setupComponent(name, getCamelContext(), (Map<String, Object>) parameters.get("component"));
if (comp instanceof RestProducerFactory) {
factory = (RestProducerFactory) comp;
cname = name;
break;
}
}
}
parameters.put("componentName", cname);
// lookup in registry
if (factory == null) {
Set<RestProducerFactory> factories = getCamelContext().getRegistry().findByType(RestProducerFactory.class);
if (factories != null && factories.size() == 1) {
factory = factories.iterator().next();
}
}
// no explicit factory found then try to see if we can find any of the default rest consumer components
// and there must only be exactly one so we safely can pick this one
if (factory == null) {
RestProducerFactory found = null;
String foundName = null;
for (String name : DEFAULT_REST_PRODUCER_COMPONENTS) {
Object comp = setupComponent(getComponentName(), getCamelContext(), (Map<String, Object>) parameters.get("component"));
if (comp instanceof RestProducerFactory) {
if (found == null) {
found = (RestProducerFactory) comp;
foundName = name;
} else {
throw new IllegalArgumentException("Multiple RestProducerFactory found on classpath. Configure explicit which component to use");
}
}
}
if (found != null) {
log.debug("Auto discovered {} as RestProducerFactory", foundName);
factory = found;
}
}
if (factory != null) {
log.debug("Using RestProducerFactory: {}", factory);
RestConfiguration config = getCamelContext().getRestConfiguration(cname, true);
Producer producer;
if (apiDocFactory != null) {
// wrap the factory using the api doc factory which will use the factory
parameters.put("restProducerFactory", factory);
producer = apiDocFactory.createProducer(getCamelContext(), host, method, path, uriTemplate, queryParameters, consumes, produces, config, parameters);
} else {
producer = factory.createProducer(getCamelContext(), host, method, path, uriTemplate, queryParameters, consumes, produces, config, parameters);
}
RestProducer answer = new RestProducer(this, producer, config);
answer.setOutType(outType);
answer.setType(inType);
answer.setBindingMode(bindingMode);
return answer;
} else {
throw new IllegalStateException("Cannot find RestProducerFactory in Registry or as a Component to use");
}
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
RestConsumerFactory factory = null;
String cname = null;
if (getComponentName() != null) {
Object comp = getCamelContext().getRegistry().lookupByName(getComponentName());
if (comp instanceof RestConsumerFactory) {
factory = (RestConsumerFactory) comp;
} else {
comp = getCamelContext().getComponent(getComponentName());
if (comp instanceof RestConsumerFactory) {
factory = (RestConsumerFactory) comp;
}
}
if (factory == null) {
if (comp != null) {
throw new IllegalArgumentException("Component " + getComponentName() + " is not a RestConsumerFactory");
} else {
throw new NoSuchBeanException(getComponentName(), RestConsumerFactory.class.getName());
}
}
cname = getComponentName();
}
// try all components
if (factory == null) {
for (String name : getCamelContext().getComponentNames()) {
Component comp = getCamelContext().getComponent(name);
if (comp instanceof RestConsumerFactory) {
factory = (RestConsumerFactory) comp;
cname = name;
break;
}
}
}
// lookup in registry
if (factory == null) {
Set<RestConsumerFactory> factories = getCamelContext().getRegistry().findByType(RestConsumerFactory.class);
if (factories != null && factories.size() == 1) {
factory = factories.iterator().next();
}
}
// no explicit factory found then try to see if we can find any of the default rest consumer components
// and there must only be exactly one so we safely can pick this one
if (factory == null) {
RestConsumerFactory found = null;
String foundName = null;
for (String name : DEFAULT_REST_CONSUMER_COMPONENTS) {
Object comp = getCamelContext().getComponent(name, true);
if (comp instanceof RestConsumerFactory) {
if (found == null) {
found = (RestConsumerFactory) comp;
foundName = name;
} else {
throw new IllegalArgumentException("Multiple RestConsumerFactory found on classpath. Configure explicit which component to use");
}
}
}
if (found != null) {
log.debug("Auto discovered {} as RestConsumerFactory", foundName);
factory = found;
}
}
if (factory != null) {
// if no explicit port/host configured, then use port from rest configuration
String scheme = "http";
String host = "";
int port = 80;
RestConfiguration config = getCamelContext().getRestConfiguration(cname, true);
if (config.getScheme() != null) {
scheme = config.getScheme();
}
if (config.getHost() != null) {
host = config.getHost();
}
int num = config.getPort();
if (num > 0) {
port = num;
}
// if no explicit hostname set then resolve the hostname
if (ObjectHelper.isEmpty(host)) {
if (config.getHostNameResolver() == RestConfiguration.RestHostNameResolver.allLocalIp) {
host = "0.0.0.0";
} else if (config.getHostNameResolver() == RestConfiguration.RestHostNameResolver.localHostName) {
host = HostUtils.getLocalHostName();
} else if (config.getHostNameResolver() == RestConfiguration.RestHostNameResolver.localIp) {
host = HostUtils.getLocalIp();
}
}
// calculate the url to the rest service
String path = getPath();
if (!path.startsWith("/")) {
path = "/" + path;
}
// there may be an optional context path configured to help Camel calculate the correct urls for the REST services
// this may be needed when using camel-servlet where we cannot get the actual context-path or port number of the servlet engine
// during init of the servlet
String contextPath = config.getContextPath();
if (contextPath != null) {
if (!contextPath.startsWith("/")) {
path = "/" + contextPath + path;
} else {
path = contextPath + path;
}
}
String baseUrl = scheme + "://" + host + (port != 80 ? ":" + port : "") + path;
String url = baseUrl;
if (uriTemplate != null) {
// make sure to avoid double slashes
if (uriTemplate.startsWith("/")) {
url = url + uriTemplate;
} else {
url = url + "/" + uriTemplate;
}
}
Consumer consumer = factory.createConsumer(getCamelContext(), processor, getMethod(), getPath(),
getUriTemplate(), getConsumes(), getProduces(), config, getParameters());
configureConsumer(consumer);
// add to rest registry so we can keep track of them, we will remove from the registry when the consumer is removed
// the rest registry will automatic keep track when the consumer is removed,
// and un-register the REST service from the registry
getCamelContext().getRestRegistry().addRestService(consumer, url, baseUrl, getPath(), getUriTemplate(), getMethod(),
getConsumes(), getProduces(), getInType(), getOutType(), getRouteId(), getDescription());
return consumer;
} else {
throw new IllegalStateException("Cannot find RestConsumerFactory in Registry or as a Component to use");
}
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public boolean isLenientProperties() {
return true;
}
}
| apache-2.0 |
redisson/redisson | redisson-spring-data/redisson-spring-data-22/src/main/java/org/redisson/spring/data/connection/RedissonReactiveStreamCommands.java | 13883 | /**
* Copyright (c) 2013-2021 Nikita Koksharov
*
* 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 org.redisson.spring.data.connection;
import org.reactivestreams.Publisher;
import org.redisson.api.StreamMessageId;
import org.redisson.client.codec.ByteArrayCodec;
import org.redisson.client.codec.StringCodec;
import org.redisson.client.protocol.RedisCommand;
import org.redisson.client.protocol.RedisCommands;
import org.redisson.client.protocol.RedisStrictCommand;
import org.redisson.reactive.CommandReactiveExecutor;
import org.springframework.data.redis.connection.ReactiveRedisConnection;
import org.springframework.data.redis.connection.ReactiveStreamCommands;
import org.springframework.data.redis.connection.stream.ByteBufferRecord;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.connection.stream.StreamOffset;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.util.Assert;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.stream.Collectors;
/**
*
* @author Nikita Koksharov
*
*/
public class RedissonReactiveStreamCommands extends RedissonBaseReactive implements ReactiveStreamCommands {
RedissonReactiveStreamCommands(CommandReactiveExecutor executorService) {
super(executorService);
}
private static List<String> toStringList(List<RecordId> recordIds) {
return recordIds.stream().map(RecordId::getValue).collect(Collectors.toList());
}
@Override
public Flux<ReactiveRedisConnection.NumericResponse<AcknowledgeCommand, Long>> xAck(Publisher<AcknowledgeCommand> publisher) {
return execute(publisher, command -> {
Assert.notNull(command.getKey(), "Key must not be null!");
Assert.notNull(command.getGroup(), "Group must not be null!");
Assert.notNull(command.getRecordIds(), "recordIds must not be null!");
List<Object> params = new ArrayList<>();
byte[] k = toByteArray(command.getKey());
params.add(k);
params.add(command.getGroup());
params.addAll(toStringList(command.getRecordIds()));
Mono<Long> m = write(k, StringCodec.INSTANCE, RedisCommands.XACK, params.toArray());
return m.map(v -> new ReactiveRedisConnection.NumericResponse<>(command, v));
});
}
@Override
public Flux<ReactiveRedisConnection.CommandResponse<AddStreamRecord, RecordId>> xAdd(Publisher<AddStreamRecord> publisher) {
return execute(publisher, command -> {
Assert.notNull(command.getKey(), "Key must not be null!");
Assert.notNull(command.getBody(), "Body must not be null!");
byte[] k = toByteArray(command.getKey());
List<Object> params = new LinkedList<>();
params.add(k);
if (!command.getRecord().getId().shouldBeAutoGenerated()) {
params.add(command.getRecord().getId().getValue());
} else {
params.add("*");
}
for (Map.Entry<ByteBuffer, ByteBuffer> entry : command.getBody().entrySet()) {
params.add(toByteArray(entry.getKey()));
params.add(toByteArray(entry.getValue()));
}
Mono<StreamMessageId> m = write(k, StringCodec.INSTANCE, RedisCommands.XADD, params.toArray());
return m.map(v -> new ReactiveRedisConnection.CommandResponse<>(command, RecordId.of(v.toString())));
});
}
@Override
public Flux<ReactiveRedisConnection.CommandResponse<DeleteCommand, Long>> xDel(Publisher<DeleteCommand> publisher) {
return execute(publisher, command -> {
Assert.notNull(command.getKey(), "Key must not be null!");
Assert.notNull(command.getRecordIds(), "recordIds must not be null!");
byte[] k = toByteArray(command.getKey());
List<Object> params = new ArrayList<>();
params.add(k);
params.addAll(toStringList(command.getRecordIds()));
Mono<Long> m = write(k, StringCodec.INSTANCE, RedisCommands.XDEL, params.toArray());
return m.map(v -> new ReactiveRedisConnection.CommandResponse<>(command, v));
});
}
@Override
public Flux<ReactiveRedisConnection.NumericResponse<ReactiveRedisConnection.KeyCommand, Long>> xLen(Publisher<ReactiveRedisConnection.KeyCommand> publisher) {
return execute(publisher, command -> {
Assert.notNull(command.getKey(), "Key must not be null!");
byte[] k = toByteArray(command.getKey());
Mono<Long> m = write(k, StringCodec.INSTANCE, RedisCommands.XLEN, k);
return m.map(v -> new ReactiveRedisConnection.NumericResponse<>(command, v));
});
}
@Override
public Flux<ReactiveRedisConnection.CommandResponse<RangeCommand, Flux<ByteBufferRecord>>> xRange(Publisher<RangeCommand> publisher) {
return range(RedisCommands.XRANGE, publisher);
}
private Flux<ReactiveRedisConnection.CommandResponse<RangeCommand, Flux<ByteBufferRecord>>> range(RedisCommand<?> rangeCommand, Publisher<RangeCommand> publisher) {
return execute(publisher, command -> {
Assert.notNull(command.getKey(), "Key must not be null!");
Assert.notNull(command.getRange(), "Range must not be null!");
Assert.notNull(command.getLimit(), "Limit must not be null!");
byte[] k = toByteArray(command.getKey());
List<Object> params = new LinkedList<>();
params.add(k);
if (rangeCommand == RedisCommands.XRANGE) {
params.add(command.getRange().getLowerBound().getValue().orElse("-"));
params.add(command.getRange().getUpperBound().getValue().orElse("+"));
} else {
params.add(command.getRange().getUpperBound().getValue().orElse("+"));
params.add(command.getRange().getLowerBound().getValue().orElse("-"));
}
if (command.getLimit().getCount() > 0) {
params.add("COUNT");
params.add(command.getLimit().getCount());
}
Mono<Map<StreamMessageId, Map<byte[], byte[]>>> m = write(k, ByteArrayCodec.INSTANCE, rangeCommand, params.toArray());
return m.map(v -> new ReactiveRedisConnection.CommandResponse<>(command, Flux.fromStream(v.entrySet().stream()).map(e -> {
Map<ByteBuffer, ByteBuffer> map = e.getValue().entrySet().stream()
.collect(Collectors.toMap(entry -> ByteBuffer.wrap(entry.getKey()),
entry -> ByteBuffer.wrap(entry.getValue())));
return StreamRecords.newRecord()
.in(command.getKey())
.withId(RecordId.of(e.getKey().toString()))
.ofBuffer(map);
})));
});
}
@Override
public Flux<ReactiveRedisConnection.CommandResponse<ReadCommand, Flux<ByteBufferRecord>>> read(Publisher<ReadCommand> publisher) {
return execute(publisher, command -> {
Assert.notNull(command.getStreamOffsets(), "StreamOffsets must not be null!");
Assert.notNull(command.getReadOptions(), "ReadOptions must not be null!");
List<Object> params = new ArrayList<>();
if (command.getConsumer() != null) {
params.add("GROUP");
params.add(command.getConsumer().getGroup());
params.add(command.getConsumer().getName());
}
if (command.getReadOptions().getCount() != null && command.getReadOptions().getCount() > 0) {
params.add("COUNT");
params.add(command.getReadOptions().getCount());
}
if (command.getReadOptions().getBlock() != null && command.getReadOptions().getBlock() > 0) {
params.add("BLOCK");
params.add(command.getReadOptions().getBlock());
}
if (command.getConsumer() != null && command.getReadOptions().isNoack()) {
params.add("NOACK");
}
params.add("STREAMS");
for (StreamOffset<ByteBuffer> streamOffset : command.getStreamOffsets()) {
params.add(toByteArray(streamOffset.getKey()));
}
for (StreamOffset<ByteBuffer> streamOffset : command.getStreamOffsets()) {
params.add(streamOffset.getOffset().getOffset());
}
Mono<Map<String, Map<StreamMessageId, Map<byte[], byte[]>>>> m;
if (command.getConsumer() == null) {
if (command.getReadOptions().getBlock() != null && command.getReadOptions().getBlock() > 0) {
m = read(toByteArray(command.getStreamOffsets().get(0).getKey()), ByteArrayCodec.INSTANCE, RedisCommands.XREAD_BLOCKING, params.toArray());
} else {
m = read(toByteArray(command.getStreamOffsets().get(0).getKey()), ByteArrayCodec.INSTANCE, RedisCommands.XREAD, params.toArray());
}
} else {
if (command.getReadOptions().getBlock() != null && command.getReadOptions().getBlock() > 0) {
m = read(toByteArray(command.getStreamOffsets().get(0).getKey()), ByteArrayCodec.INSTANCE, RedisCommands.XREADGROUP_BLOCKING, params.toArray());
} else {
m = read(toByteArray(command.getStreamOffsets().get(0).getKey()), ByteArrayCodec.INSTANCE, RedisCommands.XREADGROUP, params.toArray());
}
}
return m.map(v -> new ReactiveRedisConnection.CommandResponse<>(command, Flux.fromStream(v.entrySet().stream())
.map(ee -> {
return ee.getValue().entrySet().stream().map(e -> {
Map<ByteBuffer, ByteBuffer> map = e.getValue().entrySet().stream()
.collect(Collectors.toMap(entry -> ByteBuffer.wrap(entry.getKey()),
entry -> ByteBuffer.wrap(entry.getValue())));
return StreamRecords.newRecord()
.in(ee.getKey())
.withId(RecordId.of(e.getKey().toString()))
.ofBuffer(map);
});
}).flatMap(Flux::fromStream)
));
});
}
private static final RedisStrictCommand<String> XGROUP_STRING = new RedisStrictCommand<>("XGROUP");
@Override
public Flux<ReactiveRedisConnection.CommandResponse<GroupCommand, String>> xGroup(Publisher<GroupCommand> publisher) {
return execute(publisher, command -> {
Assert.notNull(command.getKey(), "Key must not be null!");
Assert.notNull(command.getGroupName(), "GroupName must not be null!");
byte[] k = toByteArray(command.getKey());
if (command.getAction().equals(GroupCommand.GroupCommandAction.CREATE)) {
Assert.notNull(command.getReadOffset(), "ReadOffset must not be null!");
Mono<String> m = write(k, StringCodec.INSTANCE, XGROUP_STRING, "CREATE", k, command.getGroupName(), command.getReadOffset().getOffset(), "MKSTREAM");
return m.map(v -> new ReactiveRedisConnection.CommandResponse<>(command, v));
}
if (command.getAction().equals(GroupCommand.GroupCommandAction.DELETE_CONSUMER)) {
Assert.notNull(command.getConsumerName(), "ConsumerName must not be null!");
Mono<Long> m = write(k, StringCodec.INSTANCE, RedisCommands.XGROUP_LONG, "DELCONSUMER", k, command.getGroupName(), command.getConsumerName());
return m.map(v -> new ReactiveRedisConnection.CommandResponse<>(command, v > 0 ? "OK" : "Error"));
}
if (command.getAction().equals(GroupCommand.GroupCommandAction.DESTROY)) {
Mono<Long> m = write(k, StringCodec.INSTANCE, RedisCommands.XGROUP_LONG, "DESTROY", k, command.getGroupName());
return m.map(v -> new ReactiveRedisConnection.CommandResponse<>(command, v > 0 ? "OK" : "Error"));
}
throw new IllegalArgumentException("unknown command " + command.getAction());
});
}
@Override
public Flux<ReactiveRedisConnection.CommandResponse<RangeCommand, Flux<ByteBufferRecord>>> xRevRange(Publisher<RangeCommand> publisher) {
return range(RedisCommands.XREVRANGE, publisher);
}
@Override
public Flux<ReactiveRedisConnection.NumericResponse<ReactiveRedisConnection.KeyCommand, Long>> xTrim(Publisher<TrimCommand> publisher) {
return execute(publisher, command -> {
Assert.notNull(command.getKey(), "Key must not be null!");
Assert.notNull(command.getCount(), "Count must not be null!");
byte[] k = toByteArray(command.getKey());
Mono<Long> m = write(k, StringCodec.INSTANCE, RedisCommands.XTRIM, k, "MAXLEN", command.getCount());
return m.map(v -> new ReactiveRedisConnection.NumericResponse<>(command, v));
});
}
}
| apache-2.0 |
Javaec/ChattyRus | test/chatty/AddressbookTest.java | 1323 |
package chatty;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author tduva
*/
public class AddressbookTest {
private Addressbook ab;
public AddressbookTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
ab = new Addressbook("addressbookTest");
}
@After
public void tearDown() {
}
// TODO add test methods here.
// The methods must be annotated with annotation @Test. For example:
//
// @Test
// public void hello() {}
@Test
public void testAdd() {
ab.add("abc", "123");
List<AddressbookEntry> desiredResult = new ArrayList<>();
Set<String> categories = new HashSet<>();
categories.add("123");
desiredResult.add(new AddressbookEntry("Abc", categories));
assertEquals(ab.getEntries(), desiredResult);
assertEquals(ab.get("abc").getCategories(), categories);
assertEquals(ab.getEntries().size(), 1);
}
}
| apache-2.0 |