repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
xiaolianggu/gu
LIST/src/com/list/dao/impl/MysqlCarJoinMroDaoImpl.java
6730
package com.list.dao.impl; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.list.dao.CarJoinMroDao; import com.list.model.CarJoinMroModel; import com.list.model.SnwAverageModel; import com.list.model.SnwModel; import com.list.utils.ModelFDUtils; public class MysqlCarJoinMroDaoImpl implements CarJoinMroDao { private Statement st ; private Connection conn; public MysqlCarJoinMroDaoImpl( Connection conn) { this.conn = conn; } @Override public List<CarJoinMroModel> countVehicleUse(int start, int end, String sort) throws Exception { List<CarJoinMroModel> slist = new ArrayList<CarJoinMroModel>(); CarJoinMroModel carJoinMroModel = null; ResultSet rs = null; StringBuffer sql = new StringBuffer(); sql.append("SELECT *, count(vehicle_use) AS part_name_sum, avg(average) as groupAverage FROM `carjoinmro` "); sql.append("GROUP BY vehicle_use ORDER BY "+sort+" DESC "); sql.append("limit " + start + "," + end); System.out.println(sql.toString()); try { st = conn.createStatement(); rs = st.executeQuery(sql.toString()); while (rs.next()) { carJoinMroModel = new CarJoinMroModel(); carJoinMroModel = this.packObject(carJoinMroModel, rs); slist.add(carJoinMroModel); } } catch (SQLException e) { throw e; } finally { if(rs != null){ // 关闭记录集 try{ rs.close() ; rs = null; }catch(SQLException e){ throw e; } } if(st != null){ // 关闭声明 try{ st.close() ; st = null; }catch(SQLException e){ throw e; } } } return slist; } @Override public long getCountVehicleUse() throws Exception { ResultSet rs = null; long count = 0; StringBuffer sql = new StringBuffer(); sql.append("select count(*) from ( "); sql.append("select vehicle_use from carjoinmro GROUP BY vehicle_use "); sql.append(")subQuery "); System.out.println(sql.toString()); try { st = conn.createStatement(); rs = st.executeQuery(sql.toString()); while (rs.next()) { count = rs.getInt(1); } } catch (SQLException e) { throw e; } finally { if(rs != null){ // 关闭记录集 try{ rs.close() ; rs = null; }catch(SQLException e){ throw e; } } if(st != null){ // 关闭声明 try{ st.close() ; st = null; }catch(SQLException e){ throw e; } } } return count; } @Override public List<CarJoinMroModel> countVehicleUseData(String vehicle_use, int start, int end) throws Exception { List<CarJoinMroModel> slist = new ArrayList<CarJoinMroModel>(); CarJoinMroModel carJoinMroModel = null; ResultSet rs = null; StringBuffer sql = new StringBuffer(); sql.append("SELECT * FROM `carjoinmro` where vehicle_use = '"); sql.append(vehicle_use + "' ORDER BY --average DESC "); sql.append("limit " + start + "," + end); System.out.println(sql.toString()); try { st = conn.createStatement(); rs = st.executeQuery(sql.toString()); String[] f = {"part_name_sum","groupAverage"}; while (rs.next()) { carJoinMroModel = new CarJoinMroModel(); carJoinMroModel = (CarJoinMroModel) ModelFDUtils.setObject(f,carJoinMroModel, rs); slist.add(carJoinMroModel); } } catch (SQLException e) { throw e; } finally { if(rs != null){ // 关闭记录集 try{ rs.close() ; rs = null; }catch(SQLException e){ throw e; } } if(st != null){ // 关闭声明 try{ st.close() ; st = null; }catch(SQLException e){ throw e; } } } return slist; } @Override public long getCountVehicleUseData(String vehicle_use) throws Exception { ResultSet rs = null; long count = 0; StringBuffer sql = new StringBuffer(); sql.append("select count(*) from `carjoinmro` where vehicle_use = '"); sql.append(vehicle_use + "' "); System.out.println(sql.toString()); try { st = conn.createStatement(); rs = st.executeQuery(sql.toString()); while (rs.next()) { count = rs.getInt(1); } } catch (SQLException e) { throw e; } finally { if(rs != null){ // 关闭记录集 try{ rs.close() ; rs = null; }catch(SQLException e){ throw e; } } if(st != null){ // 关闭声明 try{ st.close() ; st = null; }catch(SQLException e){ throw e; } } } return count; } private CarJoinMroModel packObject(CarJoinMroModel smodel, ResultSet rs) throws SQLException { try { smodel = (CarJoinMroModel) ModelFDUtils.setObject(smodel, rs); } catch (Exception e) { throw e; } return smodel; } @Override public List<CarJoinMroModel> createTable() throws Exception { List<CarJoinMroModel> slist = new ArrayList<CarJoinMroModel>(); CarJoinMroModel snwModel = null; ResultSet rs = null; StringBuffer sql = new StringBuffer(); sql.append("select * from `carjoinmro` a "); System.out.println(sql.toString()); try { st = conn.createStatement(); rs = st.executeQuery(sql.toString()); String[] f = {"part_name_sum","groupAverage"}; while (rs.next()) { snwModel = new CarJoinMroModel(); snwModel = (CarJoinMroModel) ModelFDUtils.setObject(f,snwModel, rs); slist.add(snwModel); } } catch (SQLException e) { throw e; } finally { if(rs != null){ // 关闭记录集 try{ rs.close() ; rs = null; }catch(SQLException e){ throw e; } } if(st != null){ // 关闭声明 try{ st.close() ; st = null; }catch(SQLException e){ throw e; } } } return slist; } }
mit
rsandell/docker-workflow-plugin
src/main/java/org/jenkinsci/plugins/docker/workflow/ServerEndpointStep.java
3946
/* * The MIT License * * Copyright (c) 2015, CloudBees, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.docker.workflow; import com.google.common.collect.ImmutableSet; import hudson.Extension; import hudson.FilePath; import hudson.model.Run; import java.io.IOException; import java.util.Set; import javax.annotation.Nonnull; import org.jenkinsci.plugins.docker.commons.credentials.DockerServerEndpoint; import org.jenkinsci.plugins.docker.commons.credentials.KeyMaterialFactory; import org.jenkinsci.plugins.workflow.steps.Step; import org.jenkinsci.plugins.workflow.steps.StepContext; import org.jenkinsci.plugins.workflow.steps.StepDescriptor; import org.jenkinsci.plugins.workflow.steps.StepExecution; import org.kohsuke.stapler.DataBoundConstructor; public class ServerEndpointStep extends Step { private final @Nonnull DockerServerEndpoint server; @DataBoundConstructor public ServerEndpointStep(@Nonnull DockerServerEndpoint server) { assert server != null; this.server = server; } public DockerServerEndpoint getServer() { return server; } @Override public StepExecution start(StepContext context) throws Exception { return new Execution2(this, context); } private static final class Execution2 extends AbstractEndpointStepExecution2 { private static final long serialVersionUID = 1; private transient final ServerEndpointStep step; Execution2(ServerEndpointStep step, StepContext context) { super(context); this.step = step; } @Override protected KeyMaterialFactory newKeyMaterialFactory() throws IOException, InterruptedException { return step.server.newKeyMaterialFactory(getContext().get(Run.class), getContext().get(FilePath.class).getChannel()); } } /** @deprecated only here for binary compatibility */ @Deprecated public static class Execution extends AbstractEndpointStepExecution { private static final long serialVersionUID = 1; } @Extension public static class DescriptorImpl extends StepDescriptor { @Override public String getFunctionName() { return "withDockerServer"; } @Override public String getDisplayName() { return "Sets up Docker server endpoint"; } @Override public boolean takesImplicitBlockArgument() { return true; } @Override public boolean isAdvanced() { return true; } @Override public Set<? extends Class<?>> getRequiredContext() { return ImmutableSet.of(Run.class, FilePath.class); } // TODO allow DockerServerEndpoint fields to be inlined, as in RegistryEndpointStep, so Docker.groovy can say simply: script.withDockerServer(uri: uri, credentialsId: credentialsId) {…} } }
mit
s1rius/fresco
imagepipeline/src/main/java/com/facebook/imagepipeline/producers/ProducerConstants.java
1116
/* * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.imagepipeline.producers; /** * Constants to be used various {@link Producer}s for logging purposes in the extra maps for the * {@link com.facebook.imagepipeline.listener.RequestListener}. * * The elements are package visible on purpose such that the individual producers create public * constants of the ones that they actually use. */ class ProducerConstants { static final String EXTRA_CACHED_VALUE_FOUND = "cached_value_found"; static final String EXTRA_BITMAP_SIZE = "bitmapSize"; static final String EXTRA_HAS_GOOD_QUALITY = "hasGoodQuality"; static final String EXTRA_IMAGE_TYPE = "imageType"; static final String EXTRA_IS_FINAL = "isFinal"; static final String EXTRA_IMAGE_FORMAT_NAME = "imageFormat"; static final String ENCODED_IMAGE_SIZE = "encodedImageSize"; static final String REQUESTED_IMAGE_SIZE = "requestedImageSize"; static final String SAMPLE_SIZE = "sampleSize"; }
mit
ebf/ews-java-api
src/main/java/microsoft/exchange/webservices/data/property/definition/ComplexPropertyDefinitionBase.java
6702
/* * The MIT License * Copyright (c) 2012 Microsoft Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package microsoft.exchange.webservices.data.property.definition; import microsoft.exchange.webservices.data.core.EwsServiceXmlReader; import microsoft.exchange.webservices.data.core.EwsServiceXmlWriter; import microsoft.exchange.webservices.data.core.PropertyBag; import microsoft.exchange.webservices.data.core.service.ServiceObject; import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion; import microsoft.exchange.webservices.data.core.enumeration.property.PropertyDefinitionFlags; import microsoft.exchange.webservices.data.core.enumeration.misc.XmlNamespace; import microsoft.exchange.webservices.data.misc.OutParam; import microsoft.exchange.webservices.data.property.complex.ComplexProperty; import java.util.EnumSet; /** * Represents abstract complex property definition. */ public abstract class ComplexPropertyDefinitionBase extends PropertyDefinition { /** * Initializes a new instance. * * @param xmlElementName Name of the XML element. * @param flags The flags. * @param version The version. */ protected ComplexPropertyDefinitionBase(String xmlElementName, EnumSet<PropertyDefinitionFlags> flags, ExchangeVersion version) { super(xmlElementName, flags, version); } /** * Initializes a new instance. * * @param xmlElementName Name of the XML element. * @param uri The URI. * @param version The version. */ protected ComplexPropertyDefinitionBase(String xmlElementName, String uri, ExchangeVersion version) { super(xmlElementName, uri, version); } /** * Initializes a new instance. * * @param xmlElementName Name of the XML element. * @param uri The URI. * @param flags The flags. * @param version The version. */ protected ComplexPropertyDefinitionBase(String xmlElementName, String uri, EnumSet<PropertyDefinitionFlags> flags, ExchangeVersion version) { super(xmlElementName, uri, flags, version); } /** * Creates the property instance. * * @param owner The owner. * @return ComplexProperty. */ public abstract ComplexProperty createPropertyInstance(ServiceObject owner); /** * Internals the load from XML. * * @param reader The reader. * @param propertyBag The property bag. * @throws Exception the exception */ protected void internalLoadFromXml(EwsServiceXmlReader reader, PropertyBag propertyBag) throws Exception { OutParam<Object> complexProperty = new OutParam<Object>(); boolean justCreated = getPropertyInstance(propertyBag, complexProperty); if (!justCreated && this.hasFlag(PropertyDefinitionFlags.UpdateCollectionItems, propertyBag.getOwner().getService().getRequestedServerVersion())) { ComplexProperty c = (ComplexProperty) complexProperty.getParam(); if (complexProperty.getParam() instanceof ComplexProperty) { c.updateFromXml(reader, reader.getLocalName()); } } else { ComplexProperty c = (ComplexProperty) complexProperty.getParam(); c.loadFromXml(reader, reader.getLocalName()); } /*if (!propertyBag.tryGetValue(this, complexProperty) || !this.hasFlag(PropertyDefinitionFlags.ReuseInstance)) { complexProperty.setParam(this.createPropertyInstance(propertyBag .getOwner())); } if (complexProperty.getParam() instanceof ComplexProperty) { ComplexProperty c = (ComplexProperty)complexProperty.getParam(); c.loadFromXml(reader, reader.getLocalName()); }*/ propertyBag.setObjectFromPropertyDefinition(this, complexProperty .getParam()); } /** * Gets the property instance. * * @param propertyBag The property bag. * @param complexProperty The property instance. * @return True if the instance is newly created. */ private boolean getPropertyInstance(PropertyBag propertyBag, OutParam<Object> complexProperty) { boolean retValue = false; if (!propertyBag.tryGetValue(this, complexProperty) || !this .hasFlag(PropertyDefinitionFlags.ReuseInstance, propertyBag.getOwner().getService().getRequestedServerVersion())) { complexProperty.setParam(this.createPropertyInstance(propertyBag .getOwner())); retValue = true; } return retValue; } /** * Loads from XML. * * @param reader The reader. * @param propertyBag The property bag. * @throws Exception the exception */ @Override public void loadPropertyValueFromXml(EwsServiceXmlReader reader, PropertyBag propertyBag) throws Exception { reader.ensureCurrentNodeIsStartElement(XmlNamespace.Types, this .getXmlElement()); if (!reader.isEmptyElement() || reader.hasAttributes()) { this.internalLoadFromXml(reader, propertyBag); } reader.readEndElementIfNecessary(XmlNamespace.Types, this .getXmlElement()); } /** * Writes to XML. * * @param writer The writer. * @param propertyBag The property bag. * @param isUpdateOperation Indicates whether the context is an update operation. * @throws Exception the exception */ @Override public void writePropertyValueToXml(EwsServiceXmlWriter writer, PropertyBag propertyBag, boolean isUpdateOperation) throws Exception { ComplexProperty complexProperty = propertyBag.getObjectFromPropertyDefinition(this); if (complexProperty != null) { complexProperty.writeToXml(writer, this.getXmlElement()); } } }
mit
quartz-powered/server
src/main/java/org/quartzpowered/protocol/codec/v1_8_R1/play/client/EntityDestroyCodec.java
2274
/** * This file is a component of Quartz Powered, this license makes sure any work * associated with Quartz Powered, must follow the conditions of the license included. * * The MIT License (MIT) * * Copyright (c) 2015 Quartz Powered * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.quartzpowered.protocol.codec.v1_8_R1.play.client; import org.quartzpowered.network.buffer.Buffer; import org.quartzpowered.network.protocol.codec.Codec; import org.quartzpowered.protocol.packet.play.client.EntityDestroyPacket; import java.util.ArrayList; import java.util.List; public class EntityDestroyCodec implements Codec<EntityDestroyPacket> { @Override public void encode(Buffer buffer, EntityDestroyPacket packet) { List<Integer> entityIds = packet.getEntityIds(); buffer.writeVarInt(entityIds.size()); entityIds.forEach(buffer::writeVarInt); } @Override public void decode(Buffer buffer, EntityDestroyPacket packet) { int entityIdSize = buffer.readVarInt(); List<Integer> entityIds = new ArrayList<>(entityIdSize); for (int i = 0; i < entityIdSize; i++) { entityIds.add(buffer.readVarInt()); } packet.setEntityIds(entityIds); } }
mit
AlexGoetz/WAECM-project
src/main/java/service/ServiceException.java
325
package service; public class ServiceException extends Exception { public ServiceException() { super(); } public ServiceException(String message) { super(message); } public ServiceException(String message, Throwable cause) { super(message, cause); } public ServiceException(Throwable cause) { super(cause); } }
mit
mallowigi/material-theme-jetbrains
src/main/java/com/chrisrm/idea/actions/arrows/MTDarculaArrows.java
1444
/* * The MIT License (MIT) * * Copyright (c) 2018 Chris Magnussen and Elior Boukhobza * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.chrisrm.idea.actions.arrows; import com.chrisrm.idea.config.ui.ArrowsStyles; public final class MTDarculaArrows extends MTAbstractArrowsAction { @Override protected ArrowsStyles getArrowsStyle() { return ArrowsStyles.DARCULA; } }
mit
jasonjkeller/WatchlistPro
src/com/aquafx_project/controls/skin/AquaCheckBoxSkin.java
5599
package com.aquafx_project.controls.skin; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.CheckBox; import javafx.scene.effect.BlurType; import javafx.scene.effect.DropShadow; import javafx.scene.effect.InnerShadow; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import com.aquafx_project.controls.skin.effects.Shadow; import com.sun.javafx.scene.control.skin.CheckBoxSkin; public class AquaCheckBoxSkin extends CheckBoxSkin implements AquaSkin{ public AquaCheckBoxSkin(CheckBox checkbox) { super(checkbox); registerChangeListener(checkbox.focusedProperty(), "FOCUSED"); registerChangeListener(checkbox.selectedProperty(), "SELECTED"); if (getSkinnable().isFocused()) { setFocusBorder(); } else { setDropShadow(); } final ChangeListener<Boolean> windowFocusChangedListener = new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observableValue, Boolean oldValue, Boolean newValue) { if (newValue != null) { if (!newValue.booleanValue()) { if (getSkinnable().isSelected() | getSkinnable().isIndeterminate()) { for (Node child : getChildren()) { if (child.getStyleClass().get(0).equals("box")) { child.getStyleClass().add("unfocused"); } } } } else { for (Node child : getChildren()) { if (child.getStyleClass().get(0).equals("box")) { child.getStyleClass().remove("unfocused"); } } } } } }; getSkinnable().sceneProperty().addListener(new ChangeListener<Scene>() { @Override public void changed(ObservableValue<? extends Scene> observableValue, Scene oldScene, Scene newScene) { if (oldScene != null && oldScene.getWindow() != null) { oldScene.getWindow().focusedProperty().removeListener(windowFocusChangedListener); } if (newScene != null && newScene.getWindow() != null) { newScene.getWindow().focusedProperty().addListener(windowFocusChangedListener); } } }); if (getSkinnable().getScene() != null && getSkinnable().getScene().getWindow() != null) { getSkinnable().getScene().getWindow().focusedProperty().addListener(windowFocusChangedListener); } } private void setDropShadow() { for (Node child : getChildren()) { if (child.getStyleClass().get(0).equals("box")) { child.setEffect(new Shadow(false)); } } } private void setSelectedFocusBorder() { InnerShadow innerFocus = new InnerShadow(); innerFocus.setColor(Color.rgb(104, 155, 201, 0.7)); innerFocus.setBlurType(BlurType.ONE_PASS_BOX); innerFocus.setRadius(6.5); innerFocus.setChoke(0.7); innerFocus.setOffsetX(0.0); innerFocus.setOffsetY(0.0); DropShadow outerFocus = new DropShadow(); outerFocus.setColor(Color.rgb(104, 155, 201)); outerFocus.setBlurType(BlurType.ONE_PASS_BOX); outerFocus.setRadius(7.0); outerFocus.setSpread(0.7); outerFocus.setOffsetX(0.0); outerFocus.setOffsetY(0.0); outerFocus.setInput(innerFocus); for (Node child : getChildren()) { if (child instanceof StackPane) { child.setEffect(outerFocus); } } } private void setFocusBorder() { InnerShadow innerFocus = new InnerShadow(); innerFocus.setColor(Color.rgb(104, 155, 201)); innerFocus.setBlurType(BlurType.ONE_PASS_BOX); innerFocus.setRadius(6.5); innerFocus.setChoke(0.7); innerFocus.setOffsetX(0.0); innerFocus.setOffsetY(0.0); DropShadow outerFocus = new DropShadow(); outerFocus.setColor(Color.rgb(104, 155, 201)); outerFocus.setBlurType(BlurType.ONE_PASS_BOX); outerFocus.setRadius(5.0); outerFocus.setSpread(0.6); outerFocus.setOffsetX(0.0); outerFocus.setOffsetY(0.0); outerFocus.setInput(innerFocus); for (Node child : getChildren()) { if (child instanceof StackPane) { child.setEffect(outerFocus); } } } @Override protected void handleControlPropertyChanged(String p) { super.handleControlPropertyChanged(p); if (p == "SELECTED") { if (getSkinnable().isFocused()) { if (getSkinnable().isSelected()) { setSelectedFocusBorder(); } else { setFocusBorder(); } } } if (p == "FOCUSED") { if (getSkinnable().isFocused()) { if (getSkinnable().isSelected()) { setSelectedFocusBorder(); } else { setFocusBorder(); } } else if (!getSkinnable().isFocused()) { setDropShadow(); } } } }
mit
reasonml-editor/reasonml-idea-plugin
src/com/reason/lang/dune/DuneTypes.java
1903
package com.reason.lang.dune; import com.reason.lang.core.type.ORCompositeElementType; import com.reason.lang.core.type.ORTokenElementType; public class DuneTypes { public static final DuneTypes INSTANCE = new DuneTypes(); private DuneTypes() {} // Composite element types public final ORCompositeElementType C_FIELD = new ORCompositeElementType("Field", DuneLanguage.INSTANCE); public final ORCompositeElementType C_FIELDS = new ORCompositeElementType("Fields", DuneLanguage.INSTANCE); public final ORCompositeElementType C_STANZA = new ORCompositeElementType("Stanza", DuneLanguage.INSTANCE); public final ORCompositeElementType C_SEXPR = new ORCompositeElementType("S-expr", DuneLanguage.INSTANCE); public final ORCompositeElementType C_VAR = new ORCompositeElementType("Var", DuneLanguage.INSTANCE); // Token element types public final ORTokenElementType ATOM = new ORTokenElementType("ATOM", DuneLanguage.INSTANCE); public final ORTokenElementType COLON = new ORTokenElementType("COLON", DuneLanguage.INSTANCE); public final ORTokenElementType COMMENT = new ORTokenElementType("COMMENT", DuneLanguage.INSTANCE); public final ORTokenElementType EQUAL = new ORTokenElementType("EQUAL", DuneLanguage.INSTANCE); public final ORTokenElementType LPAREN = new ORTokenElementType("LPAREN", DuneLanguage.INSTANCE); public final ORTokenElementType RPAREN = new ORTokenElementType("RPAREN", DuneLanguage.INSTANCE); public final ORTokenElementType SHARP = new ORTokenElementType("SHARP", DuneLanguage.INSTANCE); public final ORTokenElementType STRING = new ORTokenElementType("String", DuneLanguage.INSTANCE); public final ORTokenElementType VAR_END = new ORTokenElementType("VAR_END", DuneLanguage.INSTANCE); public final ORTokenElementType VAR_START = new ORTokenElementType("VAR_START", DuneLanguage.INSTANCE); }
mit
tobsbot/AKGBensheim
app/src/main/java/de/tobiaserthal/akgbensheim/homework/HomeworkHostFragment.java
4783
package de.tobiaserthal.akgbensheim.homework; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.view.MarginLayoutParamsCompat; import android.support.v4.view.animation.FastOutLinearInInterpolator; import android.support.v4.view.animation.LinearOutSlowInInterpolator; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Interpolator; import android.widget.FrameLayout; import de.tobiaserthal.akgbensheim.R; import de.tobiaserthal.akgbensheim.backend.model.ModelUtils; import de.tobiaserthal.akgbensheim.base.tabs.TabbedHostFragment; public class HomeworkHostFragment extends TabbedHostFragment { private FloatingActionButton actionButton; private static final int ANIM_DURATION = 150; private static final Interpolator IN_INTERPOLATOR = new LinearOutSlowInInterpolator(); private static final Interpolator OUT_INTERPOLATOR = new FastOutLinearInInterpolator(); @Override public View onCreateContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { FrameLayout root = (FrameLayout) super.onCreateContentView( inflater, container, savedInstanceState); actionButton = (FloatingActionButton) inflater.inflate(R.layout.action_button, root, false); actionButton.setImageResource(R.drawable.ic_plus); actionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ModelUtils.newDummyHomework(getActivity()); } }); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.END ); int marginHorizontal = getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin); int marginVertical = getResources().getDimensionPixelSize(R.dimen.activity_vertical_margin); layoutParams.bottomMargin = marginVertical; layoutParams.topMargin = marginVertical; MarginLayoutParamsCompat.setMarginStart(layoutParams, marginHorizontal); MarginLayoutParamsCompat.setMarginEnd(layoutParams, marginHorizontal); root.addView(actionButton, layoutParams); return root; } @Override public void onPageSelected(int position) { if(needsButton(position)) { showFab(true); } else { hideFab(true); } } private boolean needsButton(int position) { return ((HomeworkFragment) getFragmentAt(position)).needsButton(); } private void showFab(boolean animated) { actionButton.animate().cancel(); if(!animated) { actionButton.setTranslationY(0); actionButton.setVisibility(View.VISIBLE); return; } actionButton.animate() .translationY(0) .setInterpolator(IN_INTERPOLATOR) .setDuration(ANIM_DURATION) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { actionButton.setVisibility(View.VISIBLE); } }) .start(); } private void hideFab(boolean animated) { actionButton.animate().cancel(); if(!animated) { actionButton.setTranslationY(getContentView().getHeight() - actionButton.getTop()); actionButton.setVisibility(View.GONE); return; } actionButton.animate() .translationY(getContentView().getHeight() - actionButton.getTop()) .setInterpolator(OUT_INTERPOLATOR) .setDuration(ANIM_DURATION) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { actionButton.setVisibility(View.GONE); } }) .start(); } public static class Builder extends TabbedHostFragment.Builder { private Builder() { super(HomeworkFragment.class); } public static Builder withDefault() { return new Builder(); } @Override public HomeworkHostFragment build() { return build(HomeworkHostFragment.class); } } }
mit
sake/bouncycastle-java
src/org/bouncycastle/cms/CMSCompressedDataParser.java
3433
package org.bouncycastle.cms; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.InflaterInputStream; import org.bouncycastle.asn1.ASN1OctetStringParser; import org.bouncycastle.asn1.ASN1SequenceParser; import org.bouncycastle.asn1.BERTags; import org.bouncycastle.asn1.cms.CompressedDataParser; import org.bouncycastle.asn1.cms.ContentInfoParser; import org.bouncycastle.operator.InputExpander; import org.bouncycastle.operator.InputExpanderProvider; /** * Class for reading a CMS Compressed Data stream. * <pre> * CMSCompressedDataParser cp = new CMSCompressedDataParser(inputStream); * * process(cp.getContent(new ZlibExpanderProvider()).getContentStream()); * </pre> * Note: this class does not introduce buffering - if you are processing large files you should create * the parser with: * <pre> * CMSCompressedDataParser ep = new CMSCompressedDataParser(new BufferedInputStream(inputStream, bufSize)); * </pre> * where bufSize is a suitably large buffer size. */ public class CMSCompressedDataParser extends CMSContentInfoParser { public CMSCompressedDataParser( byte[] compressedData) throws CMSException { this(new ByteArrayInputStream(compressedData)); } public CMSCompressedDataParser( InputStream compressedData) throws CMSException { super(compressedData); } /** * @deprecated use getContent(InputExpandedProvider) */ public CMSTypedStream getContent() throws CMSException { try { CompressedDataParser comData = new CompressedDataParser((ASN1SequenceParser)_contentInfo.getContent(BERTags.SEQUENCE)); ContentInfoParser content = comData.getEncapContentInfo(); ASN1OctetStringParser bytes = (ASN1OctetStringParser)content.getContent(BERTags.OCTET_STRING); return new CMSTypedStream(content.getContentType().toString(), new InflaterInputStream(bytes.getOctetStream())); } catch (IOException e) { throw new CMSException("IOException reading compressed content.", e); } } /** * Return a typed stream which will allow the reading of the compressed content in * expanded form. * * @param expanderProvider a provider of expander algorithm implementations. * @return a type stream which will yield the un-compressed content. * @throws CMSException if there is an exception parsing the CompressedData object. */ public CMSTypedStream getContent(InputExpanderProvider expanderProvider) throws CMSException { try { CompressedDataParser comData = new CompressedDataParser((ASN1SequenceParser)_contentInfo.getContent(BERTags.SEQUENCE)); ContentInfoParser content = comData.getEncapContentInfo(); InputExpander expander = expanderProvider.get(comData.getCompressionAlgorithmIdentifier()); ASN1OctetStringParser bytes = (ASN1OctetStringParser)content.getContent(BERTags.OCTET_STRING); return new CMSTypedStream(content.getContentType().getId(), expander.getInputStream(bytes.getOctetStream())); } catch (IOException e) { throw new CMSException("IOException reading compressed content.", e); } } }
mit
eriqadams/computer-graphics
lib/lwjgl-2.9.1/lwjgl-source-2.9.1/src/generated/org/lwjgl/opengl/ARBMatrixPalette.java
4787
/* MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.opengl; import org.lwjgl.*; import java.nio.*; public final class ARBMatrixPalette { public static final int GL_MATRIX_PALETTE_ARB = 0x8840, GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB = 0x8841, GL_MAX_PALETTE_MATRICES_ARB = 0x8842, GL_CURRENT_PALETTE_MATRIX_ARB = 0x8843, GL_MATRIX_INDEX_ARRAY_ARB = 0x8844, GL_CURRENT_MATRIX_INDEX_ARB = 0x8845, GL_MATRIX_INDEX_ARRAY_SIZE_ARB = 0x8846, GL_MATRIX_INDEX_ARRAY_TYPE_ARB = 0x8847, GL_MATRIX_INDEX_ARRAY_STRIDE_ARB = 0x8848, GL_MATRIX_INDEX_ARRAY_POINTER_ARB = 0x8849; private ARBMatrixPalette() {} public static void glCurrentPaletteMatrixARB(int index) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glCurrentPaletteMatrixARB; BufferChecks.checkFunctionAddress(function_pointer); nglCurrentPaletteMatrixARB(index, function_pointer); } static native void nglCurrentPaletteMatrixARB(int index, long function_pointer); public static void glMatrixIndexPointerARB(int size, int stride, ByteBuffer pPointer) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glMatrixIndexPointerARB; BufferChecks.checkFunctionAddress(function_pointer); GLChecks.ensureArrayVBOdisabled(caps); BufferChecks.checkDirect(pPointer); if ( LWJGLUtil.CHECKS ) StateTracker.getReferences(caps).ARB_matrix_palette_glMatrixIndexPointerARB_pPointer = pPointer; nglMatrixIndexPointerARB(size, GL11.GL_UNSIGNED_BYTE, stride, MemoryUtil.getAddress(pPointer), function_pointer); } public static void glMatrixIndexPointerARB(int size, int stride, IntBuffer pPointer) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glMatrixIndexPointerARB; BufferChecks.checkFunctionAddress(function_pointer); GLChecks.ensureArrayVBOdisabled(caps); BufferChecks.checkDirect(pPointer); if ( LWJGLUtil.CHECKS ) StateTracker.getReferences(caps).ARB_matrix_palette_glMatrixIndexPointerARB_pPointer = pPointer; nglMatrixIndexPointerARB(size, GL11.GL_UNSIGNED_INT, stride, MemoryUtil.getAddress(pPointer), function_pointer); } public static void glMatrixIndexPointerARB(int size, int stride, ShortBuffer pPointer) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glMatrixIndexPointerARB; BufferChecks.checkFunctionAddress(function_pointer); GLChecks.ensureArrayVBOdisabled(caps); BufferChecks.checkDirect(pPointer); if ( LWJGLUtil.CHECKS ) StateTracker.getReferences(caps).ARB_matrix_palette_glMatrixIndexPointerARB_pPointer = pPointer; nglMatrixIndexPointerARB(size, GL11.GL_UNSIGNED_SHORT, stride, MemoryUtil.getAddress(pPointer), function_pointer); } static native void nglMatrixIndexPointerARB(int size, int type, int stride, long pPointer, long function_pointer); public static void glMatrixIndexPointerARB(int size, int type, int stride, long pPointer_buffer_offset) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glMatrixIndexPointerARB; BufferChecks.checkFunctionAddress(function_pointer); GLChecks.ensureArrayVBOenabled(caps); nglMatrixIndexPointerARBBO(size, type, stride, pPointer_buffer_offset, function_pointer); } static native void nglMatrixIndexPointerARBBO(int size, int type, int stride, long pPointer_buffer_offset, long function_pointer); public static void glMatrixIndexuARB(ByteBuffer pIndices) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glMatrixIndexubvARB; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(pIndices); nglMatrixIndexubvARB(pIndices.remaining(), MemoryUtil.getAddress(pIndices), function_pointer); } static native void nglMatrixIndexubvARB(int pIndices_size, long pIndices, long function_pointer); public static void glMatrixIndexuARB(ShortBuffer pIndices) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glMatrixIndexusvARB; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(pIndices); nglMatrixIndexusvARB(pIndices.remaining(), MemoryUtil.getAddress(pIndices), function_pointer); } static native void nglMatrixIndexusvARB(int pIndices_size, long pIndices, long function_pointer); public static void glMatrixIndexuARB(IntBuffer pIndices) { ContextCapabilities caps = GLContext.getCapabilities(); long function_pointer = caps.glMatrixIndexuivARB; BufferChecks.checkFunctionAddress(function_pointer); BufferChecks.checkDirect(pIndices); nglMatrixIndexuivARB(pIndices.remaining(), MemoryUtil.getAddress(pIndices), function_pointer); } static native void nglMatrixIndexuivARB(int pIndices_size, long pIndices, long function_pointer); }
mit
jklepp-tgm/dLock
src/test/java/tgm/hit/rtn/dlock/protocol/Test_ProtocolConstructors.java
4704
package tgm.hit.rtn.dlock.protocol; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import tgm.hit.rtn.dlock.Peer; import tgm.hit.rtn.dlock.protocol.PackageType; import tgm.hit.rtn.dlock.protocol.requests.*; import tgm.hit.rtn.dlock.protocol.responses.NoCurrentLock; import tgm.hit.rtn.dlock.protocol.responses.ObjectIsLocked; import tgm.hit.rtn.dlock.protocol.responses.PeerList; import tgm.hit.rtn.dlock.protocol.responses.Welcome; /** * Tests the constructors of all the protocol Packages */ public class Test_ProtocolConstructors { String testObject; Peer[] testPeers; @Before public void prepare() { testObject = "TestObject"; testPeers = new Peer[]{ new Peer(123, "host1"), new Peer(321, "127.0.0.1"), new Peer(6666, "example.com") }; } // // requests // // Bye @Test public void test_Bye_type() { Bye pkg = new Bye(); Assert.assertEquals(pkg.type, PackageType.REQUEST); } @Test public void test_Bye_msg() { Bye pkg = new Bye(); Assert.assertEquals(pkg.msg, Bye.BYE_MESSAGE); } // GetPeerList @Test public void test_GetPeerList_type() { GetPeerList pkg = new GetPeerList(); Assert.assertEquals(pkg.type, PackageType.REQUEST); } @Test public void test_GetPeerList_msg() { GetPeerList pkg = new GetPeerList(); Assert.assertEquals(pkg.msg, GetPeerList.GET_PEER_LIST_MESSAGE); } // Hallo @Test public void test_Hallo_type() { Hallo pkg = new Hallo(); Assert.assertEquals(pkg.type, PackageType.REQUEST); } @Test public void test_Hallo_msg() { Hallo pkg = new Hallo(); Assert.assertEquals(pkg.msg, Hallo.HALLO_MESSAGE); } // Lock @Test public void test_Lock_type() { Lock pkg = new Lock(testObject); Assert.assertEquals(pkg.type, PackageType.REQUEST); } @Test public void test_Lock_msg() { Lock pkg = new Lock(testObject); Assert.assertEquals(pkg.msg, Lock.LOCK_MESSAGE); } @Test public void test_Lock_object() { Lock pkg = new Lock(testObject); Assert.assertEquals(pkg.object, testObject); } // Unlock @Test public void test_Unlock_type() { Unlock pkg = new Unlock(testObject); Assert.assertEquals(pkg.type, PackageType.REQUEST); } @Test public void test_Unlock_msg() { Unlock pkg = new Unlock(testObject); Assert.assertEquals(pkg.msg, Unlock.UNLOCK_MESSAGE); } @Test public void test_Unlock_object() { Unlock pkg = new Unlock(testObject); Assert.assertEquals(pkg.object, testObject); } // // responses // // NoCurrentLock @Test public void test_NoCurrentLock_type() { NoCurrentLock pkg = new NoCurrentLock(testObject); Assert.assertEquals(pkg.type, PackageType.RESPONSE); } @Test public void test_NoCurrentLock_msg() { NoCurrentLock pkg = new NoCurrentLock(testObject); Assert.assertEquals(pkg.msg, NoCurrentLock.NO_CURRENT_LOCK_MESSAGE); } @Test public void test_NoCurrentLock_object() { NoCurrentLock pkg = new NoCurrentLock(testObject); Assert.assertEquals(pkg.object, testObject); } // ObjectIsLocked @Test public void test_ObjectIsLocked_type() { ObjectIsLocked pkg = new ObjectIsLocked(testObject); Assert.assertEquals(pkg.type, PackageType.RESPONSE); } @Test public void test_ObjectIsLocked_msg() { ObjectIsLocked pkg = new ObjectIsLocked(testObject); Assert.assertEquals(pkg.msg, ObjectIsLocked.OBJECT_IS_LOCKED_MESSAGE); } @Test public void test_ObjectIsLocked_object() { ObjectIsLocked pkg = new ObjectIsLocked(testObject); Assert.assertEquals(pkg.object, testObject); } // PeerList @Test public void test_PeerList_type() { PeerList pkg = new PeerList(testPeers); Assert.assertEquals(pkg.type, PackageType.RESPONSE); } @Test public void test_PeerList_msg() { PeerList pkg = new PeerList(testPeers); Assert.assertEquals(pkg.msg, PeerList.PEER_LIST_MESSAGE); } @Test public void test_PeerList_object() { PeerList pkg = new PeerList(testPeers); Assert.assertArrayEquals(pkg.peers, testPeers); } // Welcome @Test public void test_Welcome_type() { Welcome pkg = new Welcome(); Assert.assertEquals(pkg.type, PackageType.RESPONSE); } @Test public void test_Welcome_msg() { Welcome pkg = new Welcome(); Assert.assertEquals(pkg.msg, Welcome.WELCOME_MESSAGE); } }
mit
mansardasoft/timeloggerNoICE
src/timelogger/domain/TimeRecordListCollection.java
4398
/** * "Visual Paradigm: DO NOT MODIFY THIS FILE!" * * This is an automatic generated file. It will be regenerated every time * you generate persistence class. * * Modifying its content may cause the program not work, or your work may lost. */ /** * Licensee: DuKe TeAm * License Type: Purchased */ package timelogger.domain; import org.orm.*; public class TimeRecordListCollection extends org.orm.util.ORMList { public TimeRecordListCollection(Object owner, org.orm.util.ORMAdapter adapter, int ownerKey, int targetKey, int collType) { super(owner, adapter, ownerKey, targetKey, true, collType); } public TimeRecordListCollection(Object owner, org.orm.util.ORMAdapter adapter, int ownerKey, int collType) { super(owner, adapter, ownerKey, -1, false, collType); } /** * Return an iterator over the persistent objects * @return The persisten objects iterator */ public java.util.Iterator getIterator() { return super.getIterator(_ownerAdapter); } /** * Add the specified persistent object to ORMList * @param value the persistent object */ public void add(TimeRecord value) { if (value != null) { super.add(value, value._ormAdapter); } } /** * Remove the specified persistent object from ORMList * @param value the persistent object */ public void remove(TimeRecord value) { super.remove(value, value._ormAdapter); } /** * Return true if ORMList contains the specified persistent object * @param value the persistent object * @return True if this contains the specified persistent object */ public boolean contains(TimeRecord value) { return super.contains(value); } /** * Return an array containing all of the persistent objects in ORMList * @return The persistent objects array */ public TimeRecord[] toArray() { return (TimeRecord[]) super.toArray(new TimeRecord[size()]); } /** * Return an sorted array containing all of the persistent objects in ORMList * @param propertyName Name of the property for sorting:<ul> * <li>ID</li> * <li>inizio</li> * <li>fine</li> * <li>commento</li> * <li>fatturato</li> * </ul> * @return The persistent objects sorted array */ public TimeRecord[] toArray(String propertyName) { return toArray(propertyName, true); } /** * Return an sorted array containing all of the persistent objects in ORMList * @param propertyName Name of the property for sorting:<ul> * <li>ID</li> * <li>inizio</li> * <li>fine</li> * <li>commento</li> * <li>fatturato</li> * </ul> * @param ascending true for ascending, false for descending * @return The persistent objects sorted array */ public TimeRecord[] toArray(String propertyName, boolean ascending) { return (TimeRecord[]) super.toArray(new TimeRecord[size()], propertyName, ascending); } /** * Return the persistent object at the specified position in ORMList. * @param index - The specified position * @return - The persistent object */ public TimeRecord get(int index) { return (TimeRecord) super.getImpl(index); } /** * Remove the persistent object at the specified position in ORMList. * @param index The specified position * @return Removed persistent object */ public TimeRecord remove(int index) { TimeRecord value = get(index); if (value != null) { return (TimeRecord) super.removeImpl(index, value._ormAdapter); } return null; } /** * Insert the specified persistent object at the specified position in ORMList. * @param index The specified position * @param value The specified persistent object */ public void add(int index, TimeRecord value) { if (value != null) { super.add(index, value, value._ormAdapter); } } /** * Find the specified position of specified persistent object ORMList. * @param value The persistent object */ public int indexOf(TimeRecord value) { return super.indexOf(value); } /** * Replace the persistent object at the specified position in ORMList with the specified persistent object. * @param index The specified position * @param value The persistent object * @return Return replaced object */ public TimeRecord set(int index, TimeRecord value) { return (TimeRecord) super.set(index, value); } protected PersistentManager getPersistentManager() throws PersistentException { return timelogger.domain.TimeloggerPersistentManager.instance(); } }
mit
NorthFacing/Mapper
base/src/test/java/tk/mybatis/mapper/test/othres/TestDelimiter.java
2126
/* * The MIT License (MIT) * * Copyright (c) 2014-2017 abel533@gmail.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package tk.mybatis.mapper.test.othres; import org.junit.Assert; import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author liuzh * @since 2017/7/13. */ public class TestDelimiter { public static final Pattern DELIMITER = Pattern.compile("^[`\\[\"]?(.*?)[`\\]\"]?$"); @Test public void test(){ Matcher matcher = DELIMITER.matcher("normal"); if(matcher.find()){ Assert.assertEquals("normal", matcher.group(1)); } matcher = DELIMITER.matcher("`mysql`"); if(matcher.find()){ Assert.assertEquals("mysql", matcher.group(1)); } matcher = DELIMITER.matcher("[sqlserver]"); if(matcher.find()){ Assert.assertEquals("sqlserver", matcher.group(1)); } matcher = DELIMITER.matcher("\"oracle\""); if(matcher.find()){ Assert.assertEquals("oracle", matcher.group(1)); } } }
mit
TeamSPoon/logicmoo_base
prolog/logicmoo/pdt_server/pdt.connector.tests/src/org/cs3/prolog/load/test/FileSearchPathConfiguratorTest.java
6425
/***************************************************************************** * This file is part of the Prolog Development Tool (PDT) * * Author: Tobias Rho, Lukas Degener, Andreas Becker, Fabian Noth * WWW: http://sewiki.iai.uni-bonn.de/research/pdt/start * Mail: pdt@lists.iai.uni-bonn.de * Copyright (C): 2004-2012, CS Dept. III, University of Bonn * * All rights reserved. This program is made available under the terms * of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * ****************************************************************************/ package org.cs3.prolog.load.test; import java.lang.reflect.Array; import java.util.Arrays; import java.util.List; import junit.framework.ComparisonFailure; import junit.framework.TestCase; import org.cs3.pdt.connector.load.FileSearchPathConfigurator; import org.cs3.pdt.connector.load.PrologLibrary; import org.cs3.pdt.connector.load.PrologLibraryManager; public class FileSearchPathConfiguratorTest extends TestCase { PrologLibraryManager mgr; DummyPrologLibrary a = new DummyPrologLibrary("a",""); DummyPrologLibrary b = new DummyPrologLibrary("b", "a"); DummyPrologLibrary c = new DummyPrologLibrary("c", ""); DummyPrologLibrary d = new DummyPrologLibrary("d","ac"); DummyPrologLibrary e = new DummyPrologLibrary("e","b"); @Override public void setUp() { mgr = new PrologLibraryManager(); } public void testGetRequiredLibs_NullMng() { String[] libs = {"a"}; try { FileSearchPathConfigurator.getRequiredLibs(null, libs); fail("an exception should occure"); }catch(NullPointerException e) { } } public void testGetRequiredLibs_NullLibs() { try { FileSearchPathConfigurator.getRequiredLibs(mgr, null); fail("an exception should occure"); }catch(NullPointerException e) { } } public void testGetRequiredLibs_NoLibsNeeded() { String[] libs = {"a"}; mgr.addLibrary(a); PrologLibrary[] result=FileSearchPathConfigurator.getRequiredLibs(mgr, libs); PrologLibrary[] expected={a}; arrayEquals("",expected,result); } public void testGetRequiredLibs_OneNeededIsThere() { String[] libs = {"b"}; mgr.addLibrary(a); mgr.addLibrary(b); PrologLibrary[] result=FileSearchPathConfigurator.getRequiredLibs(mgr, libs); PrologLibrary[] expected={b,a}; List<PrologLibrary> resultList = Arrays.asList(result); List<PrologLibrary> expectedList = Arrays.asList(expected); assertEquals(expectedList.size(),resultList.size()); assertTrue(resultList.containsAll(expectedList)); } public void testGetRequiredLibs_TwoNeededAreThere() { String[] libs = {"d"}; mgr.addLibrary(a); mgr.addLibrary(c); mgr.addLibrary(d); PrologLibrary[] result=FileSearchPathConfigurator.getRequiredLibs(mgr, libs); PrologLibrary[] expected={d,a,c}; List<PrologLibrary> resultList = Arrays.asList(result); List<PrologLibrary> expectedList = Arrays.asList(expected); assertEquals(expectedList.size(),resultList.size()); assertTrue(resultList.containsAll(expectedList)); } public void testGetRequiredLibs_OneNeededDirectlyOneNeededIndirectlyBothAreThere() { String[] libs = {"e"}; mgr.addLibrary(a); mgr.addLibrary(b); mgr.addLibrary(e); PrologLibrary[] result=FileSearchPathConfigurator.getRequiredLibs(mgr, libs); PrologLibrary[] expected={e,b,a}; List<PrologLibrary> resultList = Arrays.asList(result); List<PrologLibrary> expectedList = Arrays.asList(expected); assertEquals(expectedList.size(),resultList.size()); assertTrue(resultList.containsAll(expectedList)); } public void testGetRequiredLibs_LibNotThere() { String[] libs = {"a"}; try { FileSearchPathConfigurator.getRequiredLibs(mgr, libs); fail("an exception should occure"); } catch(IllegalArgumentException e) { assertEquals("library id a is unresolved", e.getMessage()); } } public void testGetRequiredLibs_RequiredLibNotThere() { String[] libs = {"b"}; mgr.addLibrary(b); try { FileSearchPathConfigurator.getRequiredLibs(mgr, libs); fail("an exception should occure"); } catch(IllegalArgumentException e) { assertEquals("library id b is broken", e.getMessage()); } } public void testGetRequiredLibs_WrongLibId() { String[] libs = {"x"}; try { FileSearchPathConfigurator.getRequiredLibs(mgr, libs); fail("an exception should occure"); } catch(IllegalArgumentException e) { assertEquals("library id x is unresolved", e.getMessage()); } } /** * Copied from Junit 4 Assert * * to avoid the use of assertArrayEquals * * Asserts that two object arrays are equal. If they are not, an * {@link AssertionError} is thrown with the given message. If * <code>expecteds</code> and <code>actuals</code> are <code>null</code>, * they are considered equal. * * @param message * the identifying message for the {@link AssertionError} (<code>null</code> * okay) * @param expecteds * Object array or array of arrays (multi-dimensional array) with * expected values. * @param actuals * Object array or array of arrays (multi-dimensional array) with * actual values */ private static void arrayEquals(String message, Object expecteds,Object actuals) { if (expecteds == actuals) return; String header= message == null ? "" : message + ": "; if (expecteds == null) fail(header + "expected array was null"); if (actuals == null) fail(header + "actual array was null"); int actualsLength= Array.getLength(actuals); int expectedsLength= Array.getLength(expecteds); if (actualsLength != expectedsLength) fail(header + "array lengths differed, expected.length=" + expectedsLength + " actual.length=" + actualsLength); for (int i= 0; i < expectedsLength; i++) { Object expected= Array.get(expecteds, i); Object actual= Array.get(actuals, i); if (isArray(expected) && isArray(actual)) { try { arrayEquals(message, expected, actual); } catch (ComparisonFailure e) { throw e; } } else try { assertEquals(expected, actual); } catch (AssertionError e) { throw new ComparisonFailure(header, expected.toString(), actual.toString()); } } } private static boolean isArray(Object expected) { return expected != null && expected.getClass().isArray(); } }
mit
martinsawicki/azure-sdk-for-java
azure-mgmt-dns/src/main/java/com/microsoft/azure/management/dns/DnsRecordSet.java
47742
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure.management.dns; import com.microsoft.azure.management.apigeneration.Fluent; import com.microsoft.azure.management.dns.implementation.RecordSetInner; import com.microsoft.azure.management.resources.fluentcore.arm.models.ExternalChildResource; import com.microsoft.azure.management.resources.fluentcore.model.Attachable; import com.microsoft.azure.management.resources.fluentcore.model.Settable; import com.microsoft.azure.management.resources.fluentcore.model.HasInner; import java.util.List; import java.util.Map; /** * An immutable client-side representation of a record set in Azure DNS Zone. */ @Fluent public interface DnsRecordSet extends ExternalChildResource<DnsRecordSet, DnsZone>, HasInner<RecordSetInner> { /** * @return the type of records in this record set */ RecordType recordType(); /** * @return TTL of the records in this record set */ long timeToLive(); /** * @return the metadata associated with this record set. */ Map<String, String> metadata(); /** * @return the etag associated with the record set. */ String eTag(); /** * The entirety of a DNS zone record set definition as a part of parent definition. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface Definition<ParentT> extends DefinitionStages.ARecordSetBlank<ParentT>, DefinitionStages.WithARecordIPv4Address<ParentT>, DefinitionStages.WithARecordIPv4AddressOrAttachable<ParentT>, DefinitionStages.AaaaRecordSetBlank<ParentT>, DefinitionStages.WithAaaaRecordIPv6Address<ParentT>, DefinitionStages.WithAaaaRecordIPv6AddressOrAttachable<ParentT>, DefinitionStages.CNameRecordSetBlank<ParentT>, DefinitionStages.WithCNameRecordAlias<ParentT>, DefinitionStages.WithCNameRecordSetAttachable<ParentT>, DefinitionStages.MXRecordSetBlank<ParentT>, DefinitionStages.WithMXRecordMailExchange<ParentT>, DefinitionStages.WithMXRecordMailExchangeOrAttachable<ParentT>, DefinitionStages.NSRecordSetBlank<ParentT>, DefinitionStages.WithNSRecordNameServer<ParentT>, DefinitionStages.WithNSRecordNameServerOrAttachable<ParentT>, DefinitionStages.PtrRecordSetBlank<ParentT>, DefinitionStages.WithPtrRecordTargetDomainName<ParentT>, DefinitionStages.WithPtrRecordTargetDomainNameOrAttachable<ParentT>, DefinitionStages.SrvRecordSetBlank<ParentT>, DefinitionStages.WithSrvRecordEntry<ParentT>, DefinitionStages.WithSrvRecordEntryOrAttachable<ParentT>, DefinitionStages.TxtRecordSetBlank<ParentT>, DefinitionStages.WithTxtRecordTextValue<ParentT>, DefinitionStages.WithTxtRecordTextValueOrAttachable<ParentT>, DefinitionStages.WithAttach<ParentT> { } /** * Grouping of DNS zone record set definition stages as a part of parent DNS zone definition. */ interface DefinitionStages { /** * The first stage of an A record definition. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface ARecordSetBlank<ParentT> extends WithARecordIPv4Address<ParentT> { } /** * The stage of the A record set definition allowing to add first A record. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithARecordIPv4Address<ParentT> { /** * Creates an A record with the provided IPv4 address in this record set. * * @param ipv4Address the IPv4 address * @return the next stage of the definition */ WithARecordIPv4AddressOrAttachable<ParentT> withIPv4Address(String ipv4Address); } /** * The stage of the A record set definition allowing to add additional A records or * attach the record set to the parent. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithARecordIPv4AddressOrAttachable<ParentT> extends WithARecordIPv4Address<ParentT>, WithAttach<ParentT> { } /** * The first stage of a AAAA record definition. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface AaaaRecordSetBlank<ParentT> extends WithAaaaRecordIPv6Address<ParentT> { } /** * The stage of the AAAA record set definition allowing to add first AAAA record. * * @param <ParentT> the return type of {@link WithAttach#attach()} */ interface WithAaaaRecordIPv6Address<ParentT> { /** * Creates an AAAA record with the provided IPv6 address in this record set. * * @param ipv6Address an IPv6 address * @return the next stage of the definition */ WithAaaaRecordIPv6AddressOrAttachable<ParentT> withIPv6Address(String ipv6Address); } /** * The stage of the AAAA record set definition allowing to add additional AAAA records or * attach the record set to the parent. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithAaaaRecordIPv6AddressOrAttachable<ParentT> extends WithAaaaRecordIPv6Address<ParentT>, WithAttach<ParentT> { } /** * The first stage of a CNAME record set definition. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface CNameRecordSetBlank<ParentT> extends WithCNameRecordAlias<ParentT> { } /** * The stage of a CNAME record definition allowing to add alias. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithCNameRecordAlias<ParentT> { /** * Creates a CNAME record with the provided alias. * * @param alias the alias * @return the next stage of the definition */ WithCNameRecordSetAttachable<ParentT> withAlias(String alias); } /** * The stage of the CNAME record set definition allowing attach the record set to the parent. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithCNameRecordSetAttachable<ParentT> extends WithAttach<ParentT> { } /** * The first stage of a MX record definition. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface MXRecordSetBlank<ParentT> extends WithMXRecordMailExchange<ParentT> { } /** * The stage of the MX record set definition allowing to add first MX record. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithMXRecordMailExchange<ParentT> { /** * Creates and assigns priority to a MX record with the provided mail exchange server in this record set. * * @param mailExchangeHostName the host name of the mail exchange server * @param priority the priority for the mail exchange host, lower the value higher the priority * @return the next stage of the definition */ WithMXRecordMailExchangeOrAttachable<ParentT> withMailExchange(String mailExchangeHostName, int priority); } /** * The stage of the MX record set definition allowing to add additional MX records or attach the record set * to the parent. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithMXRecordMailExchangeOrAttachable<ParentT> extends WithMXRecordMailExchange<ParentT>, WithAttach<ParentT> { } /** * The first stage of a NS record definition. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface NSRecordSetBlank<ParentT> extends WithNSRecordNameServer<ParentT> { } /** * The stage of the NS record set definition allowing to add a NS record. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithNSRecordNameServer<ParentT> { /** * Creates a NS record with the provided name server in this record set. * * @param nameServerHostName the name server host name * @return the next stage of the definition */ WithNSRecordNameServerOrAttachable<ParentT> withNameServer(String nameServerHostName); } /** * The stage of the NS record set definition allowing to add additional NS records or * attach the record set to the parent. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithNSRecordNameServerOrAttachable<ParentT> extends WithNSRecordNameServer<ParentT>, WithAttach<ParentT> { } /** * The first stage of a PTR record definition. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface PtrRecordSetBlank<ParentT> extends WithPtrRecordTargetDomainName<ParentT> { } /** * The stage of the PTR record set definition allowing to add first CNAME record. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithPtrRecordTargetDomainName<ParentT> { /** * Creates a PTR record with the provided target domain name in this record set. * * @param targetDomainName the target domain name * @return the next stage of the definition */ WithPtrRecordTargetDomainNameOrAttachable<ParentT> withTargetDomainName(String targetDomainName); } /** * The stage of the PTR record set definition allowing to add additional PTR records or * attach the record set to the parent. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithPtrRecordTargetDomainNameOrAttachable<ParentT> extends WithPtrRecordTargetDomainName<ParentT>, WithAttach<ParentT> { } /** * The first stage of a SRV record definition. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface SrvRecordSetBlank<ParentT> extends WithSrvRecordEntry<ParentT> { } /** * The stage of the SRV record definition allowing to add first service record. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithSrvRecordEntry<ParentT> { /** * Specifies a service record for a service. * * @param target the canonical name of the target host running the service * @param port the port on which the service is bounded * @param priority the priority of the target host, lower the value higher the priority * @param weight the relative weight (preference) of the records with the same priority, higher the value more the preference * @return the next stage of the definition */ WithSrvRecordEntryOrAttachable<ParentT> withRecord(String target, int port, int priority, int weight); } /** * The stage of the SRV record set definition allowing to add additional SRV records or attach the record set * to the parent. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithSrvRecordEntryOrAttachable<ParentT> extends WithSrvRecordEntry<ParentT>, WithAttach<ParentT> { } /** * The first stage of a TXT record definition. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface TxtRecordSetBlank<ParentT> extends WithTxtRecordTextValue<ParentT> { } /** * The stage of the TXT record definition allowing to add first TXT record. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithTxtRecordTextValue<ParentT> { /** * Creates a Txt record with the given text in this record set. * * @param text the text value * @return the next stage of the definition */ WithTxtRecordTextValueOrAttachable<ParentT> withText(String text); } /** * The stage of the TXT record set definition allowing to add additional TXT records or attach the record set * to the parent. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithTxtRecordTextValueOrAttachable<ParentT> extends WithTxtRecordTextValue<ParentT>, WithAttach<ParentT> { } /** * The stage of the record set definition allowing to specify the Time To Live (TTL) for the records in this record set. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithTtl<ParentT> { /** * Specifies the Time To Live for the records in the record set. * * @param ttlInSeconds TTL in seconds * @return the next stage of the definition */ WithAttach<ParentT> withTimeToLive(long ttlInSeconds); } /** * The stage of the record set definition allowing to specify metadata. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithMetadata<ParentT> { /** * Adds a metadata to the resource. * * @param key the key for the metadata * @param value the value for the metadata * @return the next stage of the definition */ WithAttach<ParentT> withMetadata(String key, String value); } /** * The stage of the record set definition allowing to enable ETag validation. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithETagCheck<ParentT> { /** * Specifies that If-None-Match header needs to set to * to prevent updating an existing record set. * * @return the next stage of the definition */ WithAttach<ParentT> withETagCheck(); } /** The final stage of the DNS zone record set definition. * <p> * At this stage, any remaining optional settings can be specified, or the DNS zone record set * definition can be attached to the parent traffic manager profile definition using {@link DnsRecordSet.DefinitionStages.WithAttach#attach()}. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithAttach<ParentT> extends Attachable.InDefinition<ParentT>, DefinitionStages.WithTtl<ParentT>, DefinitionStages.WithMetadata<ParentT>, DefinitionStages.WithETagCheck<ParentT> { } } /** * The entirety of a DNS zone record set definition as a part of parent update. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface UpdateDefinition<ParentT> extends UpdateDefinitionStages.ARecordSetBlank<ParentT>, UpdateDefinitionStages.WithARecordIPv4Address<ParentT>, UpdateDefinitionStages.WithARecordIPv4AddressOrAttachable<ParentT>, UpdateDefinitionStages.AaaaRecordSetBlank<ParentT>, UpdateDefinitionStages.WithAaaaRecordIPv6Address<ParentT>, UpdateDefinitionStages.WithAaaaRecordIPv6AddressOrAttachable<ParentT>, UpdateDefinitionStages.CNameRecordSetBlank<ParentT>, UpdateDefinitionStages.WithCNameRecordAlias<ParentT>, UpdateDefinitionStages.WithCNameRecordSetAttachable<ParentT>, UpdateDefinitionStages.MXRecordSetBlank<ParentT>, UpdateDefinitionStages.WithMXRecordMailExchange<ParentT>, UpdateDefinitionStages.WithMXRecordMailExchangeOrAttachable<ParentT>, UpdateDefinitionStages.NSRecordSetBlank<ParentT>, UpdateDefinitionStages.WithNSRecordNameServer<ParentT>, UpdateDefinitionStages.WithNSRecordNameServerOrAttachable<ParentT>, UpdateDefinitionStages.PtrRecordSetBlank<ParentT>, UpdateDefinitionStages.WithPtrRecordTargetDomainName<ParentT>, UpdateDefinitionStages.WithPtrRecordTargetDomainNameOrAttachable<ParentT>, UpdateDefinitionStages.SrvRecordSetBlank<ParentT>, UpdateDefinitionStages.WithSrvRecordEntry<ParentT>, UpdateDefinitionStages.WithSrvRecordEntryOrAttachable<ParentT>, UpdateDefinitionStages.TxtRecordSetBlank<ParentT>, UpdateDefinitionStages.WithTxtRecordTextValue<ParentT>, UpdateDefinitionStages.WithTxtRecordTextValueOrAttachable<ParentT>, UpdateDefinitionStages.WithAttach<ParentT> { } /** * Grouping of DNS zone record set definition stages as a part of parent DNS zone update. */ interface UpdateDefinitionStages { /** * The first stage of a A record definition. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface ARecordSetBlank<ParentT> extends WithARecordIPv4Address<ParentT> { } /** * The stage of the A record set definition allowing to add first A record. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithARecordIPv4Address<ParentT> { /** * Creates an A record with the provided IPv4 address in this record set. * * @param ipv4Address the IPv4 address * @return the next stage of the definition */ WithARecordIPv4AddressOrAttachable<ParentT> withIPv4Address(String ipv4Address); } /** * The stage of the A record set definition allowing to add additional A records or * attach the record set to the parent. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithARecordIPv4AddressOrAttachable<ParentT> extends WithARecordIPv4Address<ParentT>, WithAttach<ParentT> { } /** * The first stage of a AAAA record definition. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface AaaaRecordSetBlank<ParentT> extends WithAaaaRecordIPv6Address<ParentT> { } /** * The stage of the AAAA record set definition allowing to add first AAAA record. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithAaaaRecordIPv6Address<ParentT> { /** * Creates an AAAA record with the provided IPv6 address in this record set. * * @param ipv6Address the IPv6 address * @return the next stage of the definition */ WithAaaaRecordIPv6AddressOrAttachable<ParentT> withIPv6Address(String ipv6Address); } /** * The stage of the AAAA record set definition allowing to add additional A records or * attach the record set to the parent. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithAaaaRecordIPv6AddressOrAttachable<ParentT> extends WithAaaaRecordIPv6Address<ParentT>, WithAttach<ParentT> { } /** * The first stage of a CNAME record set definition. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface CNameRecordSetBlank<ParentT> extends WithCNameRecordAlias<ParentT> { } /** * The stage of a CNAME record definition allowing to add alias. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithCNameRecordAlias<ParentT> { /** * Creates a CNAME record with the provided alias. * * @param alias the alias * @return the next stage of the definition */ WithCNameRecordSetAttachable<ParentT> withAlias(String alias); } /** * The stage of the CNAME record set definition allowing attach the record set to the parent. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithCNameRecordSetAttachable<ParentT> extends WithAttach<ParentT> { } /** * The first stage of an MX record definition. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface MXRecordSetBlank<ParentT> extends WithMXRecordMailExchange<ParentT> { } /** * The stage of the MX record set definition allowing to add first MX record. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithMXRecordMailExchange<ParentT> { /** * Creates and assigns priority to a MX record with the provided mail exchange server in this record set. * * @param mailExchangeHostName the host name of the mail exchange server * @param priority the priority for the mail exchange host, lower the value higher the priority * @return the next stage of the definition */ WithMXRecordMailExchangeOrAttachable<ParentT> withMailExchange(String mailExchangeHostName, int priority); } /** * The stage of the MX record set definition allowing to add additional MX records or attach the record set * to the parent. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithMXRecordMailExchangeOrAttachable<ParentT> extends WithMXRecordMailExchange<ParentT>, WithAttach<ParentT> { } /** * The first stage of a NS record definition. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface NSRecordSetBlank<ParentT> extends WithNSRecordNameServer<ParentT> { } /** * The stage of the NS record set definition allowing to add a NS record. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithNSRecordNameServer<ParentT> { /** * Creates a NS record with the provided name server in this record set. * * @param nameServerHostName the name server host name * @return the next stage of the definition */ WithNSRecordNameServerOrAttachable<ParentT> withNameServer(String nameServerHostName); } /** * The stage of the NS record set definition allowing to add additional NS records or * attach the record set to the parent. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithNSRecordNameServerOrAttachable<ParentT> extends WithNSRecordNameServer<ParentT>, WithAttach<ParentT> { } /** * The first stage of a PTR record definition. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface PtrRecordSetBlank<ParentT> extends WithPtrRecordTargetDomainName<ParentT> { } /** * The stage of the PTR record set definition allowing to add first CNAME record. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithPtrRecordTargetDomainName<ParentT> { /** * Creates a PTR record with the provided target domain name in this record set. * * @param targetDomainName the target domain name * @return the next stage of the definition */ WithPtrRecordTargetDomainNameOrAttachable<ParentT> withTargetDomainName(String targetDomainName); } /** * The stage of the PTR record set definition allowing to add additional PTR records or * attach the record set to the parent. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithPtrRecordTargetDomainNameOrAttachable<ParentT> extends WithPtrRecordTargetDomainName<ParentT>, WithAttach<ParentT> { } /** * The first stage of a SRV record definition. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface SrvRecordSetBlank<ParentT> extends WithSrvRecordEntry<ParentT> { } /** * The stage of the SRV record definition allowing to add first service record. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithSrvRecordEntry<ParentT> { /** * Specifies a service record for a service. * * @param target the canonical name of the target host running the service * @param port the port on which the service is bounded * @param priority the priority of the target host, lower the value higher the priority * @param weight the relative weight (preference) of the records with the same priority, higher the value more the preference * @return the next stage of the definition */ WithSrvRecordEntryOrAttachable<ParentT> withRecord(String target, int port, int priority, int weight); } /** * The stage of the SRV record set definition allowing to add additional SRV records or attach the record set * to the parent. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithSrvRecordEntryOrAttachable<ParentT> extends WithSrvRecordEntry<ParentT>, WithAttach<ParentT> { } /** * The first stage of a TXT record definition. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface TxtRecordSetBlank<ParentT> extends WithTxtRecordTextValue<ParentT> { } /** * The stage of the TXT record definition allowing to add first Txt record. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithTxtRecordTextValue<ParentT> { /** * Creates a TXT record with the given text in this record set. * * @param text the text value * @return the next stage of the definition */ WithTxtRecordTextValueOrAttachable<ParentT> withText(String text); } /** * The stage of the TXT record set definition allowing to add additional TXT records or attach the record set * to the parent. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithTxtRecordTextValueOrAttachable<ParentT> extends WithTxtRecordTextValue<ParentT>, WithAttach<ParentT> { } /** * The stage of the record set definition allowing to specify TTL for the records in this record set. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithTtl<ParentT> { /** * Specifies the TTL for the records in the record set. * * @param ttlInSeconds TTL in seconds * @return the next stage of the definition */ WithAttach<ParentT> withTimeToLive(long ttlInSeconds); } /** * The stage of the record set definition allowing to specify metadata. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithMetadata<ParentT> { /** * Adds a tag to the resource. * * @param key the key for the metadata * @param value the value for the metadata * @return the next stage of the definition */ WithAttach<ParentT> withMetadata(String key, String value); } /** * The stage of the record set definition allowing to enable ETag validation. * * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithETagCheck<ParentT> { /** * Specifies that If-None-Match header needs to set to * to prevent updating an existing record set. * * @return the next stage of the definition */ WithAttach<ParentT> withETagCheck(); } /** The final stage of the DNS zone record set definition. * <p> * At this stage, any remaining optional settings can be specified, or the DNS zone record set * definition can be attached to the parent traffic manager profile definition * using {@link DnsRecordSet.UpdateDefinitionStages.WithAttach#attach()}. * @param <ParentT> the stage of the parent definition to return to after attaching this definition */ interface WithAttach<ParentT> extends Attachable.InUpdate<ParentT>, UpdateDefinitionStages.WithTtl<ParentT>, UpdateDefinitionStages.WithMetadata<ParentT>, UpdateDefinitionStages.WithETagCheck<ParentT> { } } /** * The entirety of a record sets update as a part of parent DNS zone update. */ interface UpdateCombined extends UpdateARecordSet, UpdateAaaaRecordSet, UpdateCNameRecordSet, UpdateMXRecordSet, UpdatePtrRecordSet, UpdateNSRecordSet, UpdateSrvRecordSet, UpdateTxtRecordSet, UpdateSoaRecord, Update { } /** * The entirety of an A record set update as a part of parent DNS zone update. */ interface UpdateARecordSet extends UpdateStages.WithARecordIPv4Address, Update { } /** * The entirety of an AAAA record set update as a part of parent DNS zone update. */ interface UpdateAaaaRecordSet extends UpdateStages.WithAaaaRecordIPv6Address, Update { } /** * The entirety of CNAME record set update as part of parent DNS zone update. */ interface UpdateCNameRecordSet extends UpdateStages.WithCNameRecordAlias, Update { } /** * The entirety of a MX record set update as a part of parent DNS zone update. */ interface UpdateMXRecordSet extends UpdateStages.WithMXRecordMailExchange, Update { } /** * The entirety of a NS record set update as a part of parent DNS zone update. */ interface UpdateNSRecordSet extends UpdateStages.WithNSRecordNameServer, Update { } /** * The entirety of a PTR record set update as a part of parent DNS zone update. */ interface UpdatePtrRecordSet extends UpdateStages.WithPtrRecordTargetDomainName, Update { } /** * The entirety of a SRV record set update as a part of parent DNS zone update. */ interface UpdateSrvRecordSet extends UpdateStages.WithSrvRecordEntry, Update { } /** * The entirety of a TXT record set update as a part of parent DNS zone update. */ interface UpdateTxtRecordSet extends UpdateStages.WithTxtRecordTextValue, Update { } /** * The entirety of a SOA record update as a part of parent DNS zone update. */ interface UpdateSoaRecord extends UpdateStages.WithSoaRecordAttributes, Update { } /** * the set of configurations that can be updated for DNS record set irrespective of their type {@link RecordType}. */ interface Update extends Settable<DnsZone.Update>, UpdateStages.WithTtl, UpdateStages.WithMetadata, UpdateStages.WithETagCheck { } /** * Grouping of DNS zone record set update stages. */ interface UpdateStages { /** * The stage of the A record set update allowing to add or remove A record. */ interface WithARecordIPv4Address { /** * Creates an A record with the provided IPv4 address in the record set. * * @param ipv4Address an IPv4 address * @return the next stage of the record set update */ UpdateARecordSet withIPv4Address(String ipv4Address); /** * Removes the A record with the provided IPv4 address from the record set. * * @param ipv4Address an IPv4 address * @return the next stage of the record set update */ UpdateARecordSet withoutIPv4Address(String ipv4Address); } /** * The stage of the AAAA record set update allowing to add or remove AAAA record. */ interface WithAaaaRecordIPv6Address { /** * Creates an AAAA record with the provided IPv6 address in this record set. * * @param ipv6Address the IPv6 address * @return the next stage of the record set update */ UpdateAaaaRecordSet withIPv6Address(String ipv6Address); /** * Removes an AAAA record with the provided IPv6 address from this record set. * * @param ipv6Address the IPv6 address * @return the next stage of the record set update */ UpdateAaaaRecordSet withoutIPv6Address(String ipv6Address); } /** * The stage of the CNAME record set update allowing to update the CNAME record. */ interface WithCNameRecordAlias { /** * The new alias for the CNAME record set. * * @param alias the alias * @return the next stage of the record set update */ UpdateCNameRecordSet withAlias(String alias); } /** * The stage of the MX record set definition allowing to add or remove MX record. */ interface WithMXRecordMailExchange { /** * Creates and assigns priority to a MX record with the provided mail exchange server in this record set. * * @param mailExchangeHostName the host name of the mail exchange server * @param priority the priority for the mail exchange host, lower the value higher the priority * @return the next stage of the record set update */ UpdateMXRecordSet withMailExchange(String mailExchangeHostName, int priority); /** * Removes MX record with the provided mail exchange server and priority from this record set. * * @param mailExchangeHostName the host name of the mail exchange server * @param priority the priority for the mail exchange host, lower the value higher the priority * @return the next stage of the record set update */ UpdateMXRecordSet withoutMailExchange(String mailExchangeHostName, int priority); } /** * The stage of the NS record set definition allowing to add or remove a NS record. */ interface WithNSRecordNameServer { /** * Creates a NS record with the provided name server in this record set. * * @param nameServerHostName the name server host name * @return the next stage of the record set update */ UpdateNSRecordSet withNameServer(String nameServerHostName); /** * Rmoves a NS record with the provided name server from this record set. * * @param nameServerHostName the name server host name * @return the next stage of the record set update */ UpdateNSRecordSet withoutNameServer(String nameServerHostName); } /** * The stage of the CName record set definition allowing to add or remove CName record. */ interface WithPtrRecordTargetDomainName { /** * Creates a CName record with the provided canonical name in this record set. * * @param targetDomainName the target domain name * @return the next stage of the record set update */ UpdatePtrRecordSet withTargetDomainName(String targetDomainName); /** * Removes the CName record with the provided canonical name from this record set. * * @param targetDomainName the target domain name * @return the next stage of the record set update */ UpdatePtrRecordSet withoutTargetDomainName(String targetDomainName); } /** * The stage of the SRV record definition allowing to add or remove service record. */ interface WithSrvRecordEntry { /** * Specifies a service record for a service. * * @param target the canonical name of the target host running the service * @param port the port on which the service is bounded * @param priority the priority of the target host, lower the value higher the priority * @param weight the relative weight (preference) of the records with the same priority, higher the value more the preference * @return the next stage of the record set update */ UpdateSrvRecordSet withRecord(String target, int port, int priority, int weight); /** * Removes a service record for a service. * * @param target the canonical name of the target host running the service * @param port the port on which the service is bounded * @param priority the priority of the target host * @param weight the relative weight (preference) of the records * @return the next stage of the record set update */ UpdateSrvRecordSet withoutRecord(String target, int port, int priority, int weight); } /** * The stage of the SRV record definition allowing to add or remove TXT record. */ interface WithTxtRecordTextValue { /** * Creates a Txt record with the given text in this record set. * * @param text the text value * @return the next stage of the record set update */ UpdateTxtRecordSet withText(String text); /** * Removes a Txt record with the given text from this record set. * * @param text the text value * @return the next stage of the record set update */ UpdateTxtRecordSet withoutText(String text); /** * Removes a Txt record with the given text (split into 255 char chunks) from this record set. * * @param textChunks the text value as list * @return the next stage of the record set update */ UpdateTxtRecordSet withoutText(List<String> textChunks); } /** * The stage of the SOA record definition allowing to update its attributes. */ interface WithSoaRecordAttributes { /** * Specifies the email server associated with the SOA record. * * @param emailServerHostName the email server * @return the next stage of the record set update */ UpdateSoaRecord withEmailServer(String emailServerHostName); /** * Specifies time in seconds that a secondary name server should wait before trying to contact the * the primary name server for a zone file update. * * @param refreshTimeInSeconds the refresh time in seconds * @return the next stage of the record set update */ UpdateSoaRecord withRefreshTimeInSeconds(long refreshTimeInSeconds); /** * Specifies the time in seconds that a secondary name server should wait before trying to contact * the primary name server again after a failed attempt to check for a zone file update. * * @param refreshTimeInSeconds the retry time in seconds * @return the next stage of the record set update */ UpdateSoaRecord withRetryTimeInSeconds(long refreshTimeInSeconds); /** * Specifies the time in seconds that a secondary name server will treat its cached zone file as valid * when the primary name server cannot be contacted. * * @param expireTimeInSeconds the expire time in seconds * @return the next stage of the record set update */ UpdateSoaRecord withExpireTimeInSeconds(long expireTimeInSeconds); /** * Specifies the time in seconds that any name server or resolver should cache a negative response. * * @param negativeCachingTimeToLive the TTL for cached negative response * @return the next stage of the record set update */ UpdateSoaRecord withNegativeResponseCachingTimeToLiveInSeconds(long negativeCachingTimeToLive); /** * Specifies the serial number for the zone file. * * @param serialNumber the serial number * @return the next stage of the record set update */ UpdateSoaRecord withSerialNumber(long serialNumber); } /** * The stage of the record set update allowing to specify TTL for the records in this record set. */ interface WithTtl { /** * Specifies the TTL for the records in the record set. * * @param ttlInSeconds TTL in seconds * @return the next stage of the record set update */ Update withTimeToLive(long ttlInSeconds); } /** * An update allowing metadata to be modified for the resource. */ interface WithMetadata { /** * Adds a metadata to the record set. * * @param key the key for the metadata * @param value the value for the metadata * @return the next stage of the record set update */ Update withMetadata(String key, String value); /** * Removes a metadata from the record set. * * @param key the key of the metadata to remove * @return the next stage of the record set update */ Update withoutMetadata(String key); } /** * The stage of the record set update allowing to enable ETag validation. */ interface WithETagCheck { /** * Specifies that If-Match header needs to set to the current eTag value associated * with the record set. * * @return the next stage of the update */ Update withETagCheck(); /** * Specifies that if-Match header needs to set to the given eTag value. * * @param eTagValue the eTag value * @return the next stage of the update */ Update withETagCheck(String eTagValue); } } }
mit
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2019_02_01/src/main/java/com/microsoft/azure/management/network/v2019_02_01/implementation/NatGatewayImpl.java
3871
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2019_02_01.implementation; import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl; import com.microsoft.azure.management.network.v2019_02_01.NatGateway; import rx.Observable; import com.microsoft.azure.management.network.v2019_02_01.NatGatewaySku; import java.util.List; import com.microsoft.azure.SubResource; class NatGatewayImpl extends GroupableResourceCoreImpl<NatGateway, NatGatewayInner, NatGatewayImpl, NetworkManager> implements NatGateway, NatGateway.Definition, NatGateway.Update { NatGatewayImpl(String name, NatGatewayInner inner, NetworkManager manager) { super(name, inner, manager); } @Override public Observable<NatGateway> createResourceAsync() { NatGatewaysInner client = this.manager().inner().natGateways(); return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()) .map(innerToFluentMap(this)); } @Override public Observable<NatGateway> updateResourceAsync() { NatGatewaysInner client = this.manager().inner().natGateways(); return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()) .map(innerToFluentMap(this)); } @Override protected Observable<NatGatewayInner> getInnerAsync() { NatGatewaysInner client = this.manager().inner().natGateways(); return client.getByResourceGroupAsync(this.resourceGroupName(), this.name()); } @Override public boolean isInCreateMode() { return this.inner().id() == null; } @Override public String etag() { return this.inner().etag(); } @Override public Integer idleTimeoutInMinutes() { return this.inner().idleTimeoutInMinutes(); } @Override public String provisioningState() { return this.inner().provisioningState(); } @Override public List<SubResource> publicIpAddresses() { return this.inner().publicIpAddresses(); } @Override public List<SubResource> publicIpPrefixes() { return this.inner().publicIpPrefixes(); } @Override public String resourceGuid() { return this.inner().resourceGuid(); } @Override public NatGatewaySku sku() { return this.inner().sku(); } @Override public List<SubResource> subnets() { return this.inner().subnets(); } @Override public NatGatewayImpl withEtag(String etag) { this.inner().withEtag(etag); return this; } @Override public NatGatewayImpl withIdleTimeoutInMinutes(Integer idleTimeoutInMinutes) { this.inner().withIdleTimeoutInMinutes(idleTimeoutInMinutes); return this; } @Override public NatGatewayImpl withProvisioningState(String provisioningState) { this.inner().withProvisioningState(provisioningState); return this; } @Override public NatGatewayImpl withPublicIpAddresses(List<SubResource> publicIpAddresses) { this.inner().withPublicIpAddresses(publicIpAddresses); return this; } @Override public NatGatewayImpl withPublicIpPrefixes(List<SubResource> publicIpPrefixes) { this.inner().withPublicIpPrefixes(publicIpPrefixes); return this; } @Override public NatGatewayImpl withResourceGuid(String resourceGuid) { this.inner().withResourceGuid(resourceGuid); return this; } @Override public NatGatewayImpl withSku(NatGatewaySku sku) { this.inner().withSku(sku); return this; } }
mit
sonatype/emma-maven-plugin
src/main/java/org/sonatype/maven/plugin/emma/EmmaUtils.java
3339
// EMMA plugin for Maven 2 // Copyright (c) 2007 Alexandre ROMAN and contributors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // $Id: EmmaUtils.java 6585 2008-03-28 10:45:54Z bentmann $ package org.sonatype.maven.plugin.emma; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.FileUtils; /** * Utilities. * * @author <a href="mailto:alexandre.roman@gmail.com">Alexandre ROMAN</a> */ class EmmaUtils { private EmmaUtils() { } /** * Fix EMMA data file locations. EMMA generates data files in wrong locations: this method moves these files to * valid locations. * * @param project * current Maven project * @param dataFiles * to fix * @return new data file locations */ public static File[] fixDataFileLocations( MavenProject project, File[] dataFiles ) { final List newDataFiles = new ArrayList(); for ( int i = 0; i < dataFiles.length; ++i ) { final File src = dataFiles[i]; if ( !src.exists() ) { // if the file does not exist, we cannot use it continue; } if ( src.getParentFile().equals( project.getBasedir() ) ) { // EMMA generates coverage data files in project root // (as it is actually the current directory): // move these files to the "target" directory final File dst = new File( project.getBuild().getDirectory(), "coverage-" + i + ".ec" ); try { FileUtils.rename( src, dst ); } catch ( IOException e ) { throw new IllegalStateException( "Failed to move coverage data file: " + src.getAbsolutePath(), e ); } newDataFiles.add( dst ); } else { newDataFiles.add( src ); } } return (File[]) newDataFiles.toArray( new File[newDataFiles.size()] ); } }
mit
sdgdsffdsfff/duducat_sdk_android
duducat/src/com/duducat/activeconfig/FileHelper.java
1748
package com.duducat.activeconfig; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import android.content.Context; class FileHelper { static void saveFile(String key, byte[] content) { File folder = ActiveConfig.context.getDir("duducat", Context.MODE_PRIVATE); File f = new File(folder, key); try { FileOutputStream out = new FileOutputStream(f); out.write(content); out.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } static boolean isExist(String key) { File folder = ActiveConfig.context.getDir("duducat", Context.MODE_PRIVATE); File f = new File(folder, key); return f.exists(); } static byte[] getBytesFromInputStream(InputStream is) { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] buffer = new byte[0xFFFF]; for (int len; (len = is.read(buffer)) != -1;) os.write(buffer, 0, len); os.flush(); return os.toByteArray(); } catch (IOException e) { return null; } } static byte[] readFile(String key) { byte[] content = null; File folder = ActiveConfig.context.getDir("duducat", Context.MODE_PRIVATE); File f = new File(folder, key); try { FileInputStream inputStream = new FileInputStream(f); content = getBytesFromInputStream(inputStream); inputStream.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return content; } static boolean deleteFile(String key) { File folder = ActiveConfig.context.getDir("duducat", Context.MODE_PRIVATE); File f = new File(folder, key); return f.delete(); } }
mit
gonzalob/sift-java
src/main/java/com/mcac0006/siftscience/types/serializer/DateSerializer.java
534
/** * */ package com.mcac0006.siftscience.types.serializer; import java.io.IOException; import java.util.Calendar; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.map.JsonSerializer; import org.codehaus.jackson.map.SerializerProvider; /** * @author matthew.cachia * */ public class DateSerializer extends JsonSerializer<Calendar> { @Override public void serialize(Calendar date, JsonGenerator gen, SerializerProvider pro) throws IOException { gen.writeNumber(date.getTimeInMillis() / 1000); } }
mit
solita/datatree
src/main/java/fi/solita/datatree/xml/XmlSchema.java
2717
// Copyright © 2013 Solita Oy <www.solita.fi> // This software is released under the MIT License. // The license text is at http://opensource.org/licenses/MIT package fi.solita.datatree.xml; import fi.solita.datatree.*; import java.net.URL; import java.util.*; import static fi.solita.datatree.Tree.*; public class XmlSchema { public static final URL XSD = XmlSchema.class.getResource("XMLSchema.xsd"); public static Tree schema(Object... body) { return tree("xs:schema", meta("xmlns:xs", "http://www.w3.org/2001/XMLSchema"), body); } // Elements public static Tree element(String name, Object... body) { return tree("xs:element", meta("name", name), body); } public static Tree all(Object... body) { return tree("xs:all", body); } public static Tree sequence(Object... body) { return tree("xs:sequence", body); } public static final int UNBOUNDED = Integer.MAX_VALUE; public static Meta maxOccurs(int n) { return meta("maxOccurs", n == UNBOUNDED ? "unbounded" : String.valueOf(n)); } public static Meta minOccurs(int n) { return meta("minOccurs", String.valueOf(n)); } // Attributes public static Tree attribute(String name, Object... body) { return tree("xs:attribute", meta("name", name), body); } public static Meta required() { return meta("use", "required"); } public static Meta type(String type) { return meta("type", type); } // Types public static Tree simpleType(Object... body) { return tree("xs:simpleType", body); } public static Tree complexType(Object... body) { return tree("xs:complexType", body); } public static Tree simpleContent(Object... body) { return tree("xs:simpleContent", body); } public static Tree restriction(String base, Object... body) { return tree("xs:restriction", meta("base", base), body); } public static Tree extension(String base, Object... body) { return tree("xs:extension", meta("base", base), body); } public static Meta ignoreWhitespace() { return mixed(false); } public static Meta mixed(boolean b) { return meta("mixed", String.valueOf(b)); } // Restrictions public static List<Tree> enumeration(String... values) { List<Tree> enumeration = new ArrayList<>(values.length); for (String value : values) { enumeration.add(tree("xs:enumeration", meta("value", value))); } return enumeration; } public static Tree pattern(String value) { return tree("xs:pattern", meta("value", value)); } }
mit
keinfarbton/Chabu
java/org.chabu.test/src/org/chabu/ByteBufferTest.java
1700
package org.chabu; import java.nio.ByteBuffer; import java.util.Random; /** * Test the bandwidth of a java.nio.ByteBuffer * * @author Frank Benoit */ public class ByteBufferTest { static PseudoRandom rndXmit = new PseudoRandom(44); static PseudoRandom rndRecv = new PseudoRandom(44); static ByteBuffer q = ByteBuffer.allocate( 1000 ); final static int LEN = 300_000_000; static Runnable sender = new Runnable(){ public void run() { int remaining = LEN; Random rnd = new Random(); byte[] buf = new byte[q.capacity()]; while( remaining > 0 ){ synchronized(ByteBufferTest.class){ int rm = q.remaining(); if( rm == 0 ){ continue; } int sz = Math.min(remaining, rnd.nextInt( rm ) + 1); //rndXmit.nextBytes(buf, 0, sz); q.put( buf, 0, sz ); remaining -= sz; } } System.out.println("xmit completed"); } }; public static void main(String[] args) { Thread t = new Thread(sender); t.start(); int remaining = LEN; Random rnd = new Random(); byte[] buf = new byte[q.capacity()]; long ts1 = System.nanoTime(); while( remaining > 0 ){ synchronized(ByteBufferTest.class){ if( q.position() == 0 ){ continue; } q.flip(); int sz = Math.min(remaining, rnd.nextInt( q.remaining() ) + 1); q.get( buf, 0, sz ); //rndRecv.nextBytesVerify(buf, 0, sz); q.compact(); remaining -= sz; } } long ts2 = System.nanoTime(); System.out.println("recv completed"); double durMs = (ts2-ts1)/1e9; double bandwidth = LEN / durMs; System.out.printf("Bandwidth %sMB/s, dur %sms", Math.round(bandwidth*1e-6), Math.round( durMs*1000) ); } }
mit
magomi/wiquery
src/main/java/org/odlabs/wiquery/core/commons/CoreJavaScriptHeaderContributor.java
2106
/* * Copyright (c) 2009 WiQuery team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.odlabs.wiquery.core.commons; import org.apache.wicket.ResourceReference; import org.apache.wicket.markup.html.IHeaderContributor; import org.apache.wicket.markup.html.IHeaderResponse; /** * $Id: CoreJavaScriptHeaderContributor.java 81 2009-05-28 20:05:12Z * lionel.armanet $ * <p> * Imports the JQuery Core {@link ResourceReference} needed to use WiQuery * components. * </p> * * @author Lionel Armanet * @see CoreJavaScriptResourceReference * @see IHeaderContributor * @since 0.6 */ public class CoreJavaScriptHeaderContributor implements IHeaderContributor { private static final long serialVersionUID = -6914698941241719406L; /* * (non-Javadoc) * * @see org.apache.wicket.markup.html.IHeaderContributor#renderHead(org.apache.wicket.markup.html.IHeaderResponse) */ public void renderHead(IHeaderResponse response) { // just simply renders the reference response.renderJavascriptReference(CoreJavaScriptResourceReference .get()); } }
mit
darshanhs90/Java-InterviewPrep
src/Nov2020_FBPrep/_016ProductOfArrayExceptSelf.java
730
package Nov2020_FBPrep; import java.util.Arrays; public class _016ProductOfArrayExceptSelf { public static void main(String[] args) { System.out.println(Arrays.toString(productExceptSelf(new int[] { 1, 2, 3, 4 }))); } public static int[] productExceptSelf(int[] nums) { if (nums == null || nums.length == 0) return nums; int[] res1 = new int[nums.length]; int[] res2 = new int[nums.length]; res1[0] = 1; for (int i = 1; i < nums.length; i++) { res1[i] = res1[i - 1] * nums[i - 1]; } res2[nums.length - 1] = 1; for (int i = nums.length - 2; i >= 0; i--) { res2[i] = res2[i + 1] * nums[i + 1]; } for (int i = 0; i < nums.length; i++) { nums[i] = res1[i] * res2[i]; } return nums; } }
mit
Lambda-3/indra
indra-service/src/test/java/org/lambda3/indra/service/test/VectorResourceImplTest.java
3116
package org.lambda3.indra.service.test; /*- * ==========================License-Start============================= * Indra Web Service Module * -------------------------------------------------------------------- * Copyright (C) 2016 - 2017 Lambda^3 * -------------------------------------------------------------------- * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * ==========================License-End=============================== */ import org.lambda3.indra.core.IndraDriver; import org.lambda3.indra.core.test.IndraDriverTest; import org.lambda3.indra.core.translation.TranslatorFactory; import org.lambda3.indra.core.vs.VectorSpaceFactory; import org.lambda3.indra.request.VectorRequest; import org.lambda3.indra.response.DenseVectorResponse; import org.lambda3.indra.response.VectorResponse; import org.lambda3.indra.service.impl.VectorResourceImpl; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Arrays; import java.util.List; import java.util.Map; public class VectorResourceImplTest { @Test(enabled = false) public void generalTest() { VectorSpaceFactory vectorSpaceFactory = IndraDriverTest.createVectorSpaceFactory(); TranslatorFactory translatorFactory = IndraDriverTest.createTranslatorFactory(); IndraDriver driver = new IndraDriver(vectorSpaceFactory, translatorFactory); VectorResourceImpl impl = new VectorResourceImpl(driver); List<String> terms = Arrays.asList("love", "mother", "father"); VectorRequest request = new VectorRequest().language("EN").corpus("simple").model("dense").mt(false).terms(terms); VectorResponse response = impl.getVector(request); Assert.assertNotNull(response); Assert.assertTrue(response instanceof DenseVectorResponse); Map<String, double[]> vectors = ((DenseVectorResponse) response).getTerms(); Assert.assertNotNull(vectors); Assert.assertEquals(vectors.size(), 3); for (double[] array : vectors.values()) { Assert.assertTrue(array.length > 0); } } }
mit
AyranIsTheNewRaki/Herodot
Mobile/ANDROID/Herdot/app/src/main/java/com/ayranisthenewraki/heredot/herdot/MapsActivity.java
18928
package com.ayranisthenewraki.heredot.herdot; import android.Manifest; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.location.Location; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.ayranisthenewraki.heredot.herdot.model.Center; import com.ayranisthenewraki.heredot.herdot.model.ShapeDetail; import com.ayranisthenewraki.heredot.herdot.model.ShapeIdentifier; import com.ayranisthenewraki.heredot.herdot.model.TimeLocationCouple; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.places.AutocompleteFilter; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.ui.PlaceSelectionListener; import com.google.android.gms.location.places.ui.SupportPlaceAutocompleteFragment; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private GoogleMap mMap; SupportMapFragment mapFrag; LocationRequest mLocationRequest; GoogleApiClient mGoogleApiClient; Location mLastLocation; Marker mCurrLocationMarker; boolean putMarkerEnabled = false; boolean cirlceSelected = false; boolean cirlceAdded = false; LatLng selectedPoint; Double radius = 50.0; String timeLocationName = ""; String timeText = ""; String timeResolution = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFrag.getMapAsync(this); final Button markerToggle = (Button) findViewById(R.id.pinDropper); markerToggle.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ if(putMarkerEnabled){ putMarkerEnabled = false; int image_resid = getApplicationContext().getResources().getIdentifier("pin", "drawable", getApplicationContext().getPackageName()); markerToggle.setBackgroundResource(image_resid); } else{ putMarkerEnabled = true; int image_resid = getApplicationContext().getResources().getIdentifier("pin_selected", "drawable", getApplicationContext().getPackageName()); markerToggle.setBackgroundResource(image_resid); } } }); final EditText nameInput = (EditText) findViewById(R.id.dateTimeName); final EditText timeInput = (EditText) findViewById(R.id.timeString); final Spinner timeResDropdown = (Spinner)findViewById(R.id.timeResSpinner); String[] timeItems = new String[]{"Century", "Decade", "Year", "Date"}; ArrayAdapter<String> timeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, timeItems); timeResDropdown.setAdapter(timeAdapter); timeResDropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { if(timeResDropdown.getSelectedItemPosition()==0) timeInput.setHint("19th"); else if(timeResDropdown.getSelectedItemPosition()==1) timeInput.setHint("1970s"); else if(timeResDropdown.getSelectedItemPosition()==2) timeInput.setHint("2015"); else if(timeResDropdown.getSelectedItemPosition()==3) timeInput.setHint("27/03/2016"); } @Override public void onNothingSelected(AdapterView<?> parentView) { // your code here } }); final Button addTimeLocationButton = (Button) findViewById(R.id.addTimeLocationCouple); addTimeLocationButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ timeLocationName = nameInput.getText().toString(); timeText = timeInput.getText().toString(); timeResolution = timeResDropdown.getSelectedItem().toString(); if(timeLocationName.length()==0 || timeText.length()==0){ android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(MapsActivity.this).create(); alertDialog.setTitle("Alert"); alertDialog.setMessage("Please fill all fields to continue"); alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.show(); } else{ TimeLocationCouple tlc = new TimeLocationCouple(); tlc.setName(timeLocationName); tlc.setTime(timeText); tlc.setTimeType(timeResolution); ShapeIdentifier shapeId = new ShapeIdentifier(); shapeId.setLng(selectedPoint.longitude); shapeId.setLat(selectedPoint.latitude); if(cirlceAdded){ shapeId.setType(0); ShapeDetail shape = new ShapeDetail(); shape.setRadius(radius); Center center = new Center(); center.setLat(selectedPoint.latitude); center.setLng(selectedPoint.longitude); shape.setCenter(center); shapeId.setShape(shape); }else{ shapeId.setType(1); } tlc.setShape(shapeId); goBackToAddItemView(view, tlc); } } }); } public void goBackToAddItemView(View view, TimeLocationCouple tlc) { Intent intent = new Intent(); intent.putExtra("userToken", intent.getStringExtra("userToken")); Bundle bundle = new Bundle(); bundle.putSerializable("timeLocation", tlc); intent.putExtras(bundle); setResult(RESULT_OK, intent); finish(); } private void drawCircle(){ // Instantiating CircleOptions to draw a circle around the marker CircleOptions circleOptions = new CircleOptions(); // Specifying the center of the circle circleOptions.center(selectedPoint); // Radius of the circle circleOptions.radius(radius); // Border color of the circle circleOptions.strokeColor(Color.BLACK); // Fill color of the circle circleOptions.fillColor(0x30ff0000); // Border width of the circle circleOptions.strokeWidth(2); // Adding the circle to the GoogleMap mMap.addCircle(circleOptions); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { //Location Permission already granted buildGoogleApiClient(); mMap.setMyLocationEnabled(true); } else { //Request Location Permission checkLocationPermission(); } } else { buildGoogleApiClient(); mMap.setMyLocationEnabled(true); } // Add a marker in Sydney and move the camera selectedPoint = new LatLng(41.085, 29.046666666666667); mMap.addMarker(new MarkerOptions().position(selectedPoint).title("Selection")); mMap.moveCamera(CameraUpdateFactory.newLatLng(selectedPoint)); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(selectedPoint, 15)); final Button circleTool = (Button) findViewById(R.id.circleTool); final Button increaseRadius = (Button) findViewById(R.id.increaseRadius); final Button decreaseRadius = (Button) findViewById(R.id.decreaseRadius); circleTool.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ if(cirlceSelected){ cirlceSelected = false; int image_resid = getApplicationContext().getResources().getIdentifier("circle", "drawable", getApplicationContext().getPackageName()); circleTool.setBackgroundResource(image_resid); increaseRadius.setVisibility(View.INVISIBLE); decreaseRadius.setVisibility(View.INVISIBLE); } else{ cirlceSelected = true; int image_resid = getApplicationContext().getResources().getIdentifier("circle_selected", "drawable", getApplicationContext().getPackageName()); circleTool.setBackgroundResource(image_resid); if(!cirlceAdded){ radius = 50.0; drawCircle(); cirlceAdded = true; } increaseRadius.setVisibility(View.VISIBLE); decreaseRadius.setVisibility(View.VISIBLE); } } }); increaseRadius.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ mMap.clear(); mMap.addMarker(new MarkerOptions().position(selectedPoint)); radius += 10; drawCircle(); } }); decreaseRadius.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ mMap.clear(); mMap.addMarker(new MarkerOptions().position(selectedPoint)); if(radius>10){ radius -= 10; } else if(radius == 10){ radius = 0.0; cirlceAdded = false; } drawCircle(); } }); mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { @Override public void onMapClick(LatLng point) { if(putMarkerEnabled){ mMap.clear(); selectedPoint = point; cirlceAdded = false; mMap.addMarker(new MarkerOptions().position(point)); } } }); SupportPlaceAutocompleteFragment autocompleteFragment = (SupportPlaceAutocompleteFragment) getSupportFragmentManager().findFragmentById(R.id.place_autocomplete_fragment); autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() { @Override public void onPlaceSelected(Place place) { mMap.clear(); selectedPoint = place.getLatLng(); mMap.moveCamera(CameraUpdateFactory.newLatLng(selectedPoint)); mMap.addMarker(new MarkerOptions().position(selectedPoint)); EditText name = (EditText) findViewById(R.id.dateTimeName); name.setText(place.getName()); } @Override public void onError(Status status) { // TODO: Handle the error. System.out.println("An error occurred: " + status); } }); } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); } public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; private void checkLocationPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. new AlertDialog.Builder(this) .setTitle("Location Permission Needed") .setMessage("This app needs the Location permission, please accept to use location functionality") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //Prompt the user once explanation has been shown ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION ); } }) .create() .show(); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION ); } } } @Override public void onPause() { super.onPause(); //stop location updates when Activity is no longer active if (mGoogleApiClient != null) { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); } } @Override public void onConnected(@Nullable Bundle bundle) { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(1000); mLocationRequest.setFastestInterval(1000); mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the // location-related task you need to do. if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (mGoogleApiClient == null) { buildGoogleApiClient(); } mMap.setMyLocationEnabled(true); } } else { // permission denied, boo! Disable the // functionality that depends on this permission. Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show(); } return; } // other 'case' lines to check for other // permissions this app might request } } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } @Override public void onLocationChanged(Location location) { } }
mit
EnSoftCorp/purity-toolbox
com.ensoftcorp.open.immutability/src/com/ensoftcorp/open/immutability/analysis/codegen/XGreaterThanEqualYMethodAdaptZConstraintSolverGenerator.java
7820
package com.ensoftcorp.open.immutability.analysis.codegen; import java.util.ArrayList; import java.util.EnumSet; import java.util.Set; import com.ensoftcorp.open.immutability.analysis.ImmutabilityTypes; public class XGreaterThanEqualYMethodAdaptZConstraintSolverGenerator { // all possible sets, 3 choose 3, 3 choose 2, and 3 choose 1 private static final EnumSet<ImmutabilityTypes> SET1 = EnumSet.of(ImmutabilityTypes.MUTABLE, ImmutabilityTypes.POLYREAD, ImmutabilityTypes.READONLY); private static final EnumSet<ImmutabilityTypes> SET2 = EnumSet.of(ImmutabilityTypes.POLYREAD, ImmutabilityTypes.READONLY); private static final EnumSet<ImmutabilityTypes> SET3 = EnumSet.of(ImmutabilityTypes.MUTABLE, ImmutabilityTypes.POLYREAD); private static final EnumSet<ImmutabilityTypes> SET4 = EnumSet.of(ImmutabilityTypes.MUTABLE, ImmutabilityTypes.READONLY); private static final EnumSet<ImmutabilityTypes> SET5 = EnumSet.of(ImmutabilityTypes.READONLY); private static final EnumSet<ImmutabilityTypes> SET6 = EnumSet.of(ImmutabilityTypes.POLYREAD); private static final EnumSet<ImmutabilityTypes> SET7 = EnumSet.of(ImmutabilityTypes.MUTABLE); private static final ArrayList<EnumSet<ImmutabilityTypes>> sets = new ArrayList<EnumSet<ImmutabilityTypes>>(); public static void main(String[] args){ sets.add(SET1); sets.add(SET2); sets.add(SET3); sets.add(SET4); sets.add(SET5); sets.add(SET6); sets.add(SET7); int[] allSets = new int[]{1,2,3,4,5,6,7}; System.out.println("boolean xTypesChanged = false;"); System.out.println("boolean yTypesChanged = false;"); System.out.println("boolean zTypesChanged = false;"); System.out.println("short input = getCase(xTypes, yTypes, zTypes);"); System.out.println("switch (input) {"); for(int x : allSets){ for(int y : allSets){ for(int z : allSets){ // for each reference there are 7 possible sets (3 choose 3 + 3 choose 2 + 3 choose 1) // to represent 7 cases we need 3 bits per reference // for 3 references x,y,z we need 9 bits, so a short is needed // format: 0000000xxxyyyzzz // in total there are 1*7*7*7=343 possible 3 reference set inputs EnumSet<ImmutabilityTypes> xTypes = sets.get(x-1); EnumSet<ImmutabilityTypes> yTypes = sets.get(y-1); EnumSet<ImmutabilityTypes> zTypes = sets.get(z-1); short input = getCase(xTypes, yTypes, zTypes); String result = getResult(sets.get(x-1), sets.get(y-1), sets.get(z-1)); if(!result.equals("")){ System.out.println("case " + input + ":" + " // xTypes=" + xTypes.toString() + ", yTypes=" + yTypes.toString() + ", zTypes=" + zTypes.toString()); System.out.println(result); } else { throw new RuntimeException("empty result"); } } } } System.out.println("default:"); System.out.println("throw new IllegalArgumentException(\"Unhandled case: xTypes=\" + xTypes.toString() + \", yTypes=\" + yTypes.toString() + \", zTypes=\" + zTypes.toString());"); System.out.println("}"); } private static short getCase(EnumSet<ImmutabilityTypes> xTypes, EnumSet<ImmutabilityTypes> yTypes, EnumSet<ImmutabilityTypes> zTypes) { short input = 0; int setID = 0; for(EnumSet<ImmutabilityTypes> set : sets){ if(xTypes.equals(set)){ break; } else { setID++; } } input |= setID; input <<= 3; setID = 0; for(EnumSet<ImmutabilityTypes> set : sets){ if(yTypes.equals(set)){ break; } else { setID++; } } input |= setID; input <<= 3; setID = 0; for(EnumSet<ImmutabilityTypes> set : sets){ if(zTypes.equals(set)){ break; } else { setID++; } } input |= setID; return input; } private static String getResult(EnumSet<ImmutabilityTypes> xTypes, EnumSet<ImmutabilityTypes> yTypes, EnumSet<ImmutabilityTypes> zTypes) { // process s(x) Set<ImmutabilityTypes> xTypesToRemove = EnumSet.noneOf(ImmutabilityTypes.class); for(ImmutabilityTypes xType : xTypes){ boolean isSatisfied = false; satisfied: for(ImmutabilityTypes yType : yTypes){ for(ImmutabilityTypes zType : zTypes){ ImmutabilityTypes yAdaptedZ = ImmutabilityTypes.getAdaptedMethodViewpoint(yType, zType); if(xType.compareTo(yAdaptedZ) >= 0){ isSatisfied = true; break satisfied; } } } if(!isSatisfied){ xTypesToRemove.add(xType); } } // process s(y) Set<ImmutabilityTypes> yTypesToRemove = EnumSet.noneOf(ImmutabilityTypes.class); for(ImmutabilityTypes yType : yTypes){ boolean isSatisfied = false; satisfied: for(ImmutabilityTypes xType : xTypes){ for(ImmutabilityTypes zType : zTypes){ ImmutabilityTypes yAdaptedZ = ImmutabilityTypes.getAdaptedMethodViewpoint(yType, zType); if(xType.compareTo(yAdaptedZ) >= 0){ isSatisfied = true; break satisfied; } } } if(!isSatisfied){ yTypesToRemove.add(yType); } } // process s(z) Set<ImmutabilityTypes> zTypesToRemove = EnumSet.noneOf(ImmutabilityTypes.class); for(ImmutabilityTypes zType : zTypes){ boolean isSatisfied = false; satisfied: for(ImmutabilityTypes xType : xTypes){ for(ImmutabilityTypes yType : yTypes){ ImmutabilityTypes yAdaptedZ = ImmutabilityTypes.getAdaptedMethodViewpoint(yType, zType); if(xType.compareTo(yAdaptedZ) >= 0){ isSatisfied = true; break satisfied; } } } if(!isSatisfied){ zTypesToRemove.add(zType); } } if(xTypesToRemove.isEmpty() && yTypesToRemove.isEmpty() && zTypesToRemove.isEmpty()){ return "return false;"; } else { if(xTypesToRemove.isEmpty() && yTypesToRemove.isEmpty()){ return "return removeTypes(z, EnumSet.of(" + getSetString(zTypesToRemove) + "));"; } else if(xTypesToRemove.isEmpty() && zTypesToRemove.isEmpty()){ return "return removeTypes(y, EnumSet.of(" + getSetString(yTypesToRemove) + "));"; } else if(yTypesToRemove.isEmpty() && zTypesToRemove.isEmpty()){ return "return removeTypes(x, EnumSet.of(" + getSetString(xTypesToRemove) + "));"; } else { if(xTypesToRemove.isEmpty()){ String result = ""; result += "yTypesChanged = removeTypes(y, EnumSet.of(" + getSetString(yTypesToRemove) + "));\n"; result += "zTypesChanged = removeTypes(z, EnumSet.of(" + getSetString(zTypesToRemove) + "));\n"; result += "return yTypesChanged || zTypesChanged;"; return result; } else if(yTypesToRemove.isEmpty()){ String result = ""; result += "xTypesChanged = removeTypes(x, EnumSet.of(" + getSetString(xTypesToRemove) + "));\n"; result += "zTypesChanged = removeTypes(z, EnumSet.of(" + getSetString(zTypesToRemove) + "));\n"; result += "return xTypesChanged || zTypesChanged;"; return result; } else if(zTypesToRemove.isEmpty()){ String result = ""; result += "xTypesChanged = removeTypes(x, EnumSet.of(" + getSetString(xTypesToRemove) + "));\n"; result += "yTypesChanged = removeTypes(y, EnumSet.of(" + getSetString(yTypesToRemove) + "));\n"; result += "return xTypesChanged || yTypesChanged;"; return result; } else { String result = ""; result += "xTypesChanged = removeTypes(x, EnumSet.of(" + getSetString(xTypesToRemove) + "));\n"; result += "yTypesChanged = removeTypes(y, EnumSet.of(" + getSetString(yTypesToRemove) + "));\n"; result += "zTypesChanged = removeTypes(z, EnumSet.of(" + getSetString(zTypesToRemove) + "));\n"; result += "return xTypesChanged || yTypesChanged || zTypesChanged;"; return result; } } } } private static String getSetString(Set<ImmutabilityTypes> xTypesToRemove){ String result = ""; String prefix = ""; for(ImmutabilityTypes type : xTypesToRemove){ result += prefix + "ImmutabilityTypes." + type.toString(); prefix = ", "; } return result; } }
mit
GlowstonePlusPlus/GlowstonePlusPlus
src/main/java/net/glowstone/inventory/crafting/GlowBannerCopyMatcher.java
1906
package net.glowstone.inventory.crafting; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BannerMeta; import java.util.ArrayList; public class GlowBannerCopyMatcher extends ItemMatcher { /* - Must be exactly two banners - 1 with no pattern, and 1 with at least one layer - Must be same colour - No other items allowed in matrix */ @Override public ItemStack getResult(ItemStack[] matrix) { ArrayList<ItemStack> banners = new ArrayList<>(); for (ItemStack item : matrix) { if (item == null) { continue; } // TODO: handle all new banner types if (item.getType() == Material.LEGACY_BANNER) { banners.add(item); continue; } return null; // Non-banner item in matrix } if (banners.size() != 2) { return null; // Must have 2 banners only } if (banners.get(0).getDurability() != banners.get(1).getDurability()) { return null; // Not same color } ItemStack original = null; ItemStack blank = null; for (ItemStack banner : banners) { BannerMeta meta = (BannerMeta) banner.getItemMeta(); if (meta.getPatterns().isEmpty()) { if (blank != null) { return null; // More than 1 blank } blank = banner; } else { if (original != null) { return null; // More than 1 original } original = banner; } } if (original == null || blank == null) { return null; // Haven't got both needed banners } return original.clone(); } //TODO: Keep banner in matrix after crafting }
mit
SafechargeBulgaria/safecharge-retail-java
src/main/java/com/safecharge/response/SafechargeResponse.java
5505
package com.safecharge.response; import com.safecharge.util.Constants; /** * Copyright (C) 2007-2017 SafeCharge International Group Limited. * <p> * Abstract class to be used as a base for all of the responses from SafeCharge's servers. * * @author <a mailto:nikolad@safecharge.com>Nikola Dichev</a> * @since 2/14/2017 */ public abstract class SafechargeResponse { private static final long serialVersionUID = 4104056768008786142L; /** * SafeCharge Internal unique request id (used for reconciliation purpose etc.). */ private Long internalRequestId; /** * The Checkout Page status of merchant request. */ private Constants.APIResponseStatus status; /** * The error code of the error occurred at the Checkout Page site. */ private Integer errCode = Constants.ERR_CODE_NO_ERROR; /** * The error reason if error occurred at the Checkout Page side. */ private String reason = ""; /** * The Merchant ID provided by SafeCharge. */ private String merchantId; /** * The Merchant Site ID provided by SafeCharge. */ private String merchantSiteId; /** * The current version of the API method */ private String version; /** * ID of the API request in merchant system. */ private String clientRequestId; /** * The session identifier returned, to be used as input parameter in all methods. UUID = Universal unique ID. */ private String sessionToken; /** * ID of the transaction in merchant system. */ private String clientUniqueId; /** * The type of the server's error */ private Constants.ErrorType errorType = null; /** * The API workflow type */ private Constants.APIType apiType; /** * If configured to use hints will returned URL pointing to more detailed error description when request fails */ private String hint; public SafechargeResponse() { } public Long getInternalRequestId() { return internalRequestId; } public void setInternalRequestId(Long internalRequestId) { this.internalRequestId = internalRequestId; } public Constants.APIResponseStatus getStatus() { return status; } public void setStatus(Constants.APIResponseStatus status) { this.status = status; } public int getErrCode() { return errCode; } public void setErrCode(int errCode) { this.errCode = errCode; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public String getMerchantId() { return merchantId; } public void setMerchantId(String merchantId) { this.merchantId = merchantId; } public String getMerchantSiteId() { return merchantSiteId; } public void setMerchantSiteId(String merchantSiteId) { this.merchantSiteId = merchantSiteId; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getClientRequestId() { return clientRequestId; } public void setClientRequestId(String clientRequestId) { this.clientRequestId = clientRequestId; } public String getSessionToken() { return sessionToken; } public void setSessionToken(String sessionToken) { this.sessionToken = sessionToken; } public String getClientUniqueId() { return clientUniqueId; } public void setClientUniqueId(String clientUniqueId) { this.clientUniqueId = clientUniqueId; } public Constants.ErrorType getErrorType() { return errorType; } public void setErrorType(Constants.ErrorType errorType) { this.errorType = errorType; } public Constants.APIType getApiType() { return apiType; } public void setApiType(Constants.APIType apiType) { this.apiType = apiType; } public String getHint() { return hint; } public void setHint(String hint) { this.hint = hint; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("internalRequestId=") .append(internalRequestId); sb.append(", status=") .append(status); sb.append(", errCode=") .append(errCode); sb.append(", reason='") .append(reason) .append('\''); sb.append(", merchantId='") .append(merchantId) .append('\''); sb.append(", merchantSiteId='") .append(merchantSiteId) .append('\''); sb.append(", version='") .append(version) .append('\''); sb.append(", clientRequestId='") .append(clientRequestId) .append('\''); sb.append(", sessionToken='") .append(sessionToken) .append('\''); sb.append(", clientUniqueId='") .append(clientUniqueId) .append('\''); sb.append(", errorType=") .append(errorType); sb.append(", apiType=") .append(apiType); sb.append(", hint=").append(hint); return sb.toString(); } }
mit
harbourfy/newjiaxiaotong
app/src/main/java/com/app/jiaxiaotong/im/model/GroupRemoveListener.java
1224
package com.app.jiaxiaotong.im.model; import com.easemob.EMGroupChangeListener; /** * 群组被解散或者被T监听 * */ public abstract class GroupRemoveListener implements EMGroupChangeListener{ @Override public void onInvitationReceived(String groupId, String groupName, String inviter, String reason) { // TODO Auto-generated method stub } @Override public void onApplicationReceived(String groupId, String groupName, String applyer, String reason) { // TODO Auto-generated method stub } @Override public void onApplicationAccept(String groupId, String groupName, String accepter) { // TODO Auto-generated method stub } @Override public void onApplicationDeclined(String groupId, String groupName, String decliner, String reason) { // TODO Auto-generated method stub } @Override public void onInvitationAccpted(String groupId, String inviter, String reason) { // TODO Auto-generated method stub } @Override public void onInvitationDeclined(String groupId, String invitee, String reason) { // TODO Auto-generated method stub } }
epl-1.0
akurtakov/Pydev
plugins/org.python.pydev/src/org/python/pydev/editor/codecompletion/PyContentAssistant.java
1365
/** * Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Eclipse Public License (EPL). * Please see the license.txt included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ /* * Created on Aug 25, 2004 * * @author Fabio Zadrozny */ package org.python.pydev.editor.codecompletion; import org.python.copiedfromeclipsesrc.JDTNotAvailableException; import org.python.pydev.shared_ui.content_assist.DefaultContentAssist; /** * @author Fabio Zadrozny */ public class PyContentAssistant extends DefaultContentAssist { public PyContentAssistant() { super(); enableColoredLabels(true); ContentAssistHackingAroundBugs.fixAssistBugs(this); } /** * Shows the completions available and sets the lastAutoActivated flag * and updates the lastActivationCount. */ @Override public String showPossibleCompletions() { try { return super.showPossibleCompletions(); } catch (RuntimeException e) { Throwable e1 = e; while (e1.getCause() != null) { e1 = e1.getCause(); } if (e1 instanceof JDTNotAvailableException) { return e1.getMessage(); } throw e; } } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/csi/SessionKeyFactoryImpl.java
1507
/******************************************************************************* * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ejs.csi; import com.ibm.websphere.csi.StatefulSessionKey; import com.ibm.websphere.csi.StatefulSessionKeyFactory; import com.ibm.ws.util.UUID; /** * This class provides a simple factory for keys for stateful session beans. */ public class SessionKeyFactoryImpl implements StatefulSessionKeyFactory { /** * Return newly created <code>StatefulSessionKey</code> instance. * Note, the returned object will be for a key that is unique * within a cluster. */ @Override public StatefulSessionKey create() { UUID uuid = new UUID(); // d204278 return new StatefulSessionKeyImpl(uuid); } /** * Create using bytes from a previously generated unique UUID. * * @param bytes are the bytes from the unique UUID. */ @Override public StatefulSessionKey create(byte[] bytes) { return new StatefulSessionKeyImpl(new UUID(bytes)); } } // SessionKeyFactoryImpl
epl-1.0
rrimmana/birt-1
data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/ExprManager.java
4697
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.data.engine.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.birt.core.script.ScriptContext; import org.eclipse.birt.data.engine.api.IBaseExpression; import org.eclipse.birt.data.engine.api.IBaseQueryDefinition; import org.eclipse.birt.data.engine.api.IBinding; import org.eclipse.birt.data.engine.api.IScriptExpression; import org.eclipse.birt.data.engine.api.querydefn.Binding; import org.eclipse.birt.data.engine.core.DataException; /** * */ public class ExprManager { private List bindingExprs; private Map autoBindingExprMap; //TODO enhance me. The auto binding should be done at preparation phrase rather than //execution phrase. private Map autoBindingMap; private int entryLevel; private IBaseQueryDefinition baseQueryDefn; private ScriptContext context; public final static int OVERALL_GROUP = 0; //private Context cx; /** * An exprManager object is to manipulate all available column bindings for * specified query definition. */ public ExprManager( IBaseQueryDefinition baseQueryDefn, ScriptContext cx ) { bindingExprs = new ArrayList( ); autoBindingExprMap = new HashMap( ); entryLevel = OVERALL_GROUP; this.baseQueryDefn = baseQueryDefn; this.autoBindingMap = new HashMap( ); this.context = cx; } /** * @param resultsExprMap * @param groupLevel */ public void addBindingExpr( String groupKey, Map resultsExprMap, int groupLevel ) { if ( resultsExprMap == null ) return; bindingExprs.add( new GroupBindingColumn( groupKey, groupLevel, resultsExprMap ) ); } /** * @param name * @param baseExpr */ void addAutoBindingExpr( String name, IBaseExpression baseExpr ) { autoBindingExprMap.put( name, baseExpr ); this.autoBindingMap.put( name, new Binding( name, baseExpr ) ); } /** * @param name * @return expression for specified name * @throws DataException */ public IBaseExpression getExpr( String name ) throws DataException { IBaseExpression baseExpr = getBindingExpr( name ); if ( baseExpr == null ) baseExpr = getAutoBindingExpr( name ); return baseExpr; } /** * * @param name * @return * @throws DataException */ public IBinding getBinding( String name ) throws DataException { for ( int i = 0; i < bindingExprs.size( ); i++ ) { GroupBindingColumn gcb = (GroupBindingColumn) bindingExprs.get( i ); if ( entryLevel != OVERALL_GROUP ) { if ( gcb.getGroupLevel( ) > entryLevel ) continue; } if( gcb.getBinding( name )!= null ) return gcb.getBinding( name ); } if ( this.autoBindingMap.containsKey( name )) { return (IBinding)this.autoBindingMap.get( name ); } return null; } /** * @param name * @return * @throws DataException */ private IBaseExpression getBindingExpr( String name ) throws DataException { for ( int i = 0; i < bindingExprs.size( ); i++ ) { GroupBindingColumn gcb = (GroupBindingColumn) bindingExprs.get( i ); if ( entryLevel != OVERALL_GROUP ) { if ( gcb.getGroupLevel( ) > entryLevel ) continue; } Object o = gcb.getExpression( name ); if ( o != null ) return (IBaseExpression) o; } return null; } /** * @param name * @return auto binding expression for specified name */ IScriptExpression getAutoBindingExpr( String name ) { return (IScriptExpression) this.autoBindingExprMap.get( name ); } /** * TODO: remove me * @return */ public List getBindingExprs( ) { return this.bindingExprs; } /** * TODO: remove me * @return */ public Map getAutoBindingExprMap( ) { return this.autoBindingExprMap; } /** * TODO: remove me * * Set the entry group level of the expr manager. The column bindings of * groups with group level greater than the given key will not be visible to * outside. * * @param i */ void setEntryGroupLevel( int i ) { this.entryLevel = i; } /** * @throws DataException */ public void validateColumnBinding( ) throws DataException { ExprManagerUtil.validateColumnBinding( this, baseQueryDefn, context ); } }
epl-1.0
openhab/openhab
bundles/binding/org.openhab.binding.velux/src/main/java/org/openhab/binding/velux/bridge/comm/BCgetLANConfig.java
4961
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.velux.bridge.comm; import java.util.HashMap; import java.util.Map; import org.openhab.binding.velux.bridge.VeluxBridge; /** * Specific bridge communication message supported by the Velux bridge. * <P> * Message semantic: Retrieval of LAN configuration. * <P> * * It defines informations how to send query and receive answer through the * {@link org.openhab.binding.velux.bridge.VeluxBridgeProvider VeluxBridgeProvider} * as described by the {@link org.openhab.binding.velux.bridge.comm.BridgeCommunicationProtocol * BridgeCommunicationProtocol}. * * @author Guenther Schreiner - Initial contribution. * @since 1.13.0 */ @Deprecated public class BCgetLANConfig implements BridgeCommunicationProtocol<BCgetLANConfig.Response> { public static String url = "/api/v1/lan"; public BCgetLANConfig() { } /* * Message Objects */ /** * Bridge I/O Request message used by {@link VeluxBridge} for serializing: * <P> * Resulting JSON: * * <pre> * {"action":"get","params":{}} * </pre> */ public static class Request { @SuppressWarnings("unused") private String action; @SuppressWarnings("unused") private Map<String, String> params; public Request() { this.action = "get"; this.params = new HashMap<String, String>(); } } /** * Bridge Communication Structure containing the version of the firmware. * <P> * Used within structure {@link BCgetLANConfig} to describe the network connectivity of the Bridge. */ public static class BCLANConfig { /* * {"ipAddress":"192.168.45.9","subnetMask":"255.255.255.0","defaultGateway":"192.168.45.129","dhcp":false} */ private String ipAddress; private String subnetMask; private String defaultGateway; private boolean dhcp; public String getIPAddress() { return this.ipAddress; } public String getSubnetMask() { return this.subnetMask; } public String getDefaultGateway() { return this.defaultGateway; } public boolean getDHCP() { return this.dhcp; } @Override public String toString() { return String.format("ipAddress=%s,subnetMask=%s,defaultGateway=%s,dhcp=%s", this.ipAddress, this.subnetMask, this.defaultGateway, this.dhcp ? "on" : "off"); } } /** * Bridge I/O Response message used by {@link VeluxBridge} for unmarshelling with including component access methods * <P> * Expected JSON (sample): * * <pre> * { * "token":"RHIKGlJyZhidI/JSK0a2RQ==", * "result":true, * "deviceStatus":"IDLE", * "data":"ipAddress":"192.168.45.9","subnetMask":"255.255.255.0","defaultGateway":"192.168.45.129","dhcp":false}, * "errors":[] * } * </pre> */ public static class Response { private String token; private boolean result; private String deviceStatus; private BCLANConfig data; private String[] errors; public String getToken() { return token; } public boolean getResult() { return result; } public String getDeviceStatus() { return deviceStatus; } public BCLANConfig getLANConfig() { return data; } public String[] getErrors() { return errors; } } /* * =========================================================== * Methods required for interface {@link BridgeCommunicationProtocol}. */ @Override public String name() { return "get LAN configuration"; } @Override public String getURL() { return url; } @Override public boolean isCommunicationSuccessful(Response response) { return response.getResult(); } @Override public Class<Response> getClassOfResponse() { return Response.class; } @Override public Object getObjectOfRequest() { return new Request(); } @Override public String getAuthToken(Response response) { return response.getToken(); } @Override public String getDeviceStatus(Response response) { return response.getDeviceStatus(); } @Override public String[] getErrors(Response response) { return response.getErrors(); } }
epl-1.0
MikeJMajor/openhab2-addons-dlinksmarthome
bundles/org.openhab.binding.evohome/src/main/java/org/openhab/binding/evohome/internal/api/models/v2/response/ZoneStatus.java
1433
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.evohome.internal.api.models.v2.response; import java.util.List; import com.google.gson.annotations.SerializedName; /** * Response model for zone status * * @author Jasper van Zuijlen - Initial contribution * */ public class ZoneStatus { @SerializedName("zoneId") private String zoneId; @SerializedName("name") private String name; @SerializedName("temperatureStatus") private TemperatureStatus temperature; @SerializedName("setpointStatus") private HeatSetpointStatus heatSetpoint; @SerializedName("activeFaults") private List<ActiveFault> activeFaults; public String getZoneId() { return zoneId; } public TemperatureStatus getTemperature() { return temperature; } public HeatSetpointStatus getHeatSetpoint() { return heatSetpoint; } public boolean hasActiveFaults() { return !activeFaults.isEmpty(); } public ActiveFault getActiveFault(int index) { return activeFaults.get(index); } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.feature.cmdline/src/com/ibm/ws/kernel/feature/internal/generator/FeatureListWriter.java
3349
/******************************************************************************* * Copyright (c) 2013, 2018 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.kernel.feature.internal.generator; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Map; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; public class FeatureListWriter { private final XMLStreamWriter writer; private final Indenter i; public FeatureListWriter(FeatureListUtils utils) throws XMLStreamException, UnsupportedEncodingException { this.writer = utils.getXMLStreamWriter(); this.i = utils.getIndenter(); } public void writeTextElement(String nodeName, String text) throws IOException, XMLStreamException { i.indent(2); writer.writeStartElement(nodeName); writer.writeCharacters(text); writer.writeEndElement(); } public void writeTextElementWithAttributes(String nodeName, String text, Map<String, String> attrs) throws IOException, XMLStreamException { i.indent(2); writer.writeStartElement(nodeName); for (Map.Entry<String, String> attr : attrs.entrySet()) { String rawKey = attr.getKey(); String key = rawKey.endsWith(":") ? rawKey.substring(0, rawKey.length() -1) : rawKey; writer.writeAttribute(key, attr.getValue()); } writer.writeCharacters(text); writer.writeEndElement(); } public void startFeature(String nodeName, String name) throws IOException, XMLStreamException { i.indent(1); writer.writeStartElement(nodeName); if (name != null) { writer.writeAttribute("name", name); } } public void endFeature() throws IOException, XMLStreamException { i.indent(1); writer.writeEndElement(); } /** * @param nodeName * @throws XMLStreamException * @throws IOException */ public void startFeature(String nodeName) throws IOException, XMLStreamException { startFeature(nodeName, null); } public void writeIncludeFeature(String preferred, List<String> tolerates, String shortName) throws IOException, XMLStreamException { i.indent(2); writer.writeStartElement("include"); writer.writeAttribute("symbolicName", preferred); if (shortName != null) writer.writeAttribute("shortName", shortName); if (tolerates != null) { StringBuilder toleratesValue = new StringBuilder(); for (String tolerate : tolerates) { if (toleratesValue.length() > 0) { toleratesValue.append(','); } toleratesValue.append(tolerate); } writer.writeAttribute("tolerates", toleratesValue.toString()); } writer.writeEndElement(); } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.javaee.dd/src/com/ibm/ws/javaee/dd/jsf/FacesConfigNavigationRule.java
714
/******************************************************************************* * Copyright (c) 2012,2020 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.javaee.dd.jsf; import com.ibm.ws.javaee.dd.common.DescriptionGroup; public interface FacesConfigNavigationRule extends DescriptionGroup { // EMPTY }
epl-1.0
SiriusLab/SiriusAnimator
trace/generator/plugins/org.eclipse.gemoc.trace.metamodel.generator/src/base/Steps/SpecificStep.java
945
/******************************************************************************* * Copyright (c) 2017 Inria and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Inria - initial API and implementation *******************************************************************************/ /** */ package base.Steps; import base.States.SpecificState; import org.eclipse.gemoc.trace.commons.model.trace.Step; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Specific Step</b></em>'. * <!-- end-user-doc --> * * * @see base.Steps.StepsPackage#getSpecificStep() * @model abstract="true" * @generated */ public interface SpecificStep extends Step<SpecificState> { } // SpecificStep
epl-1.0
OpenLiberty/open-liberty
dev/io.openliberty.ws.jaxws.global.handler.internal_fat/fat/src/com/ibm/ws/webservices/handler/fat/AbstractJaxWsTransportSecurityTest.java
21432
/******************************************************************************* * Copyright (c) 2021 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.webservices.handler.fat; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Rule; import org.junit.rules.TestName; import com.ibm.websphere.simplicity.RemoteFile; import com.ibm.websphere.simplicity.ShrinkHelper; import com.ibm.websphere.simplicity.ShrinkHelper.DeployOptions; import com.ibm.websphere.simplicity.log.Log; import componenttest.annotation.Server; import componenttest.topology.impl.LibertyFileManager; import componenttest.topology.impl.LibertyServer; import componenttest.topology.impl.LibertyServerFactory; import componenttest.topology.utils.HttpUtils; /** * The basic test class for all the transport security test cases classes */ abstract public class AbstractJaxWsTransportSecurityTest { private static final int REQUEST_TIMEOUT = 10; private static final int WAIT_TIME_OUT = 10 * 1000; private static final Set<String> SERVER_CONFIG_WITH_SSL = new HashSet<String>(); private static final Set<String> SERVER_CONFIG_WITHOUT_SSL = new HashSet<String>(); protected static String lastServerConfig; @Server("JaxWsTransportSecurityServer") public static LibertyServer server = LibertyServerFactory.getLibertyServer("JaxWsTransportSecurityServer"); protected static final String SERVER_TMP_DIR = "tmp"; protected static final String WEB_XML_IN_PROVIDER_WAR = "apps/TransportSecurityProvider.ear/TransportSecurityProvider.war/WEB-INF/web.xml"; protected static final String CUSTOMIZE_BND_FILE = "apps/TransportSecurityClient.war/WEB-INF/ibm-ws-bnd.xml"; protected String SERVLET_PATH = "/TransportSecurityClient/TestTransportSecurityServlet"; // the value is use to switch whether need use dynamic update the server.xml and applications, // now, using false as the http chain for ssl is not stable. // if is false, will start and stop server for every test case. protected static boolean dynamicUpdate = false; static { SERVER_CONFIG_WITHOUT_SSL.add("serverConfigs/basicAuthWithoutSSL.xml"); SERVER_CONFIG_WITHOUT_SSL.add("serverConfigs/noAppSecurityFeature.xml"); SERVER_CONFIG_WITHOUT_SSL.add("serverConfigs/noSSLConfiguration.xml"); SERVER_CONFIG_WITH_SSL.add("serverConfigs/basicAuthWithSSL.xml"); SERVER_CONFIG_WITH_SSL.add("serverConfigs/clientCertFailOverToBasicAuthConfiguration.xml"); SERVER_CONFIG_WITH_SSL.add("serverConfigs/customizeSSLConfiguration.xml"); SERVER_CONFIG_WITH_SSL.add("serverConfigs/defaultClientCertConfiguration.xml"); SERVER_CONFIG_WITH_SSL.add("serverConfigs/defaultSSLConfiguration.xml"); SERVER_CONFIG_WITH_SSL.add("serverConfigs/noTrustStoreInCustomizeSSLConfiguration.xml"); SERVER_CONFIG_WITH_SSL.add("serverConfigs/noTrustStoreInDefaultSSLConfiguration.xml"); SERVER_CONFIG_WITH_SSL.add("serverConfigs/noValidTrustCertInCustomizeSSLConfiguration.xml"); SERVER_CONFIG_WITH_SSL.add("serverConfigs/patchyServerTrustStoreConfiguration.xml"); SERVER_CONFIG_WITH_SSL.add("serverConfigs/sslRefInSSLDefaultConfiguration.xml"); SERVER_CONFIG_WITH_SSL.add("serverConfigs/withAliasClientCertConfiguration.xml"); } @Rule public TestName testName = new TestName(); /** * Start server * * @param serverLog * @param serverConfigFile * @param providerWebXMLFile * @param clientBindingFile * @throws Exception */ protected static void startServer(String serverLog, String serverConfigFile, String providerWebXMLFile, String clientBindingFile) throws Exception { // update server.xml if (null != serverConfigFile) { tryUpdateServerRootFile("server.xml", serverConfigFile); } // update web.xml in provider application tryUpdateServerRootFile(WEB_XML_IN_PROVIDER_WAR, providerWebXMLFile); // update ibm-ws-bnd.xml in client application tryUpdateServerRootFile(CUSTOMIZE_BND_FILE, clientBindingFile); server.startServer(serverLog); server.setMarkToEndOfLog(); assertNotNull("The server JaxWsTransportSecurityServer did not appear to have started", server.waitForStringInLog("CWWKF0011I.*JaxWsTransportSecurityServer")); } /** * Try to update the file under server root * * @param oldFile the relative path to ${wlp.user.output} * @param newFile the relative path to publish/files/JaxWsTransportSecurityServer/ * @return * @throws Exception */ protected static boolean tryUpdateServerRootFile(String oldFile, String newFile) throws Exception { if (null == newFile) { // try to delete the web.xml try { RemoteFile file = server.getFileFromLibertyServerRoot(oldFile); int count = 0; boolean success = false; // try delete file 5 times, the wait time is 1s while (!(success = file.delete()) && count < 5) { Thread.sleep(1000); ++count; Log.info(AbstractJaxWsTransportSecurityTest.class, "tryUpdateServerFile", "try delete " + oldFile + " in " + count + " times"); } if (!success) { Log.warning(AbstractJaxWsTransportSecurityTest.class, "Could not delete file: " + oldFile); return false; } else { Log.info(AbstractJaxWsTransportSecurityTest.class, "tryUpdateServerFile", "Successfully delete file:" + oldFile); } } catch (FileNotFoundException e) { // if no file, need not update the file, so just return false Log.info(AbstractJaxWsTransportSecurityTest.class, "tryUpdateServerFile", "The file is inexistent:" + oldFile); return false; } } else { updateSingleFileInServerRoot(oldFile, newFile); } return true; } /** * Update the the web.xml in provider application * * @param newWebXML the relative path to publish/files/JaxWsTransportSecurityServer/ * @throws Exception */ protected static void updateProviderWEBXMLFile(WebArchive webApp, String newWebXML) throws Exception { updateProviderWEBXMLFile(webApp, newWebXML, true); } /** * Update the the web.xml in provider application * * @param newWebXML * @param warningWhenFail just log the warning message when the update operation is failed * @throws Exception */ protected static void updateProviderWEBXMLFile(WebArchive webApp, String newWebXML, boolean warningWhenFail) throws Exception { server.setMarkToEndOfLog(); //if (!tryUpdateServerRootFile(WEB_XML_IN_PROVIDER_WAR, newWebXML)) { // return; //} webApp.addAsWebInfResource(new File("lib/LibertyFATTestFiles", newWebXML), "web.xml"); ShrinkHelper.exportAppToServer(server, webApp, DeployOptions.OVERWRITE); // wait for app started/updated message boolean isFound = null != server.waitForStringInLogUsingMark("CWWKZ0001I.*TransportSecurityProvider | CWWKZ0003I.*TransportSecurityProvider", WAIT_TIME_OUT); if (!isFound) { if (warningWhenFail) { Log.warning(AbstractJaxWsTransportSecurityTest.class, "The application TransportSecurityProvider did not appear to have updated."); return; } fail("The application TransportSecurityProvider did not appear to have updated"); } } /** * Update the binding file in client application * * @param newBndFile the relative path to publish/files/JaxWsTransportSecurityServer/ * @throws Exception */ protected static void updateClientBndFile(WebArchive webApp, String newBndFile) throws Exception { updateClientBndFile(webApp, newBndFile, true); } /** * Update the binding file in client application * * @param newBndFile * @param warningWhenFail just log the warning message when the update operation is failed * @throws Exception */ protected static void updateClientBndFile(WebArchive webApp, String newBndFile, boolean warningWhenFail) throws Exception { server.setMarkToEndOfLog(); //if (!tryUpdateServerRootFile(CUSTOMIZE_BND_FILE, newBndFile)) { // return; //} webApp.addAsWebInfResource(new File("lib/LibertyFATTestFiles", newBndFile), "ibm-ws-bnd.xml"); ShrinkHelper.exportAppToServer(server, webApp, DeployOptions.OVERWRITE); // wait for app started/updated message boolean isFound = null != server.waitForStringInLogUsingMark("CWWKZ0001I.*TransportSecurityClient | CWWKZ0003I.*TransportSecurityClient", WAIT_TIME_OUT); if (!isFound) { if (warningWhenFail) { Log.warning(AbstractJaxWsTransportSecurityTest.class, "The application TransportSecurityClient did not appear to have updated."); return; } fail("The application TransportSecurityClient did not appear to have updated."); } } /** * Update the server.xml * * @param newServerConfigFile the relative path to publish/files/JaxWsTransportSecurityServer/ * @throws Exception */ protected static void updateServerConfigFile(String newServerConfigFile) throws Exception { updateServerConfigFile(newServerConfigFile, true); } /** * Update the server.xml * * @param newServerConfigFile * @param checkAppUpdate only check for Provider app update when specified * @throws Exception */ protected static void updateServerConfigFile(String newServerConfigFile, boolean checkAppUpdate) throws Exception { // just log the warning message when the update operation is failed boolean warningWhenFail = true; if (null == newServerConfigFile) { Log.warning(AbstractJaxWsTransportSecurityTest.class, "The server configuration could not be updated as the new configuration file is Null."); return; } try { updateSingleFileInServerRoot("server.xml", newServerConfigFile); boolean isFound = null != server.waitForStringInLogUsingMark("CWWKG0017I.* | CWWKG0018I.*"); if (!isFound) { if (warningWhenFail) { Log.warning(AbstractJaxWsTransportSecurityTest.class, "The server configuration does not update."); } else { fail("The server configuration does not update."); } } if (null == lastServerConfig) {// The first time to update server config file // Make sure the TransportSecurityProvider app is started/updated server.waitForStringInLogUsingMark("CWWKZ0001I.*TransportSecurityProvider | CWWKZ0003I.*TransportSecurityProvider", WAIT_TIME_OUT); // Current configuration has SSL feature, check if the ssl port is opened if (SERVER_CONFIG_WITH_SSL.contains(newServerConfigFile)) { Log.info(AbstractJaxWsTransportSecurityTest.class, "updateServerConfigFile", "Wait for ssl port open."); isFound = null != server.waitForStringInLogUsingMark("CWWKO0219I:.*-ssl"); } } else if (!newServerConfigFile.equals(lastServerConfig)) {// The last server config file is not the same as the current one Log.info(AbstractJaxWsTransportSecurityTest.class, "updateServerConfigFile", "old: -" + lastServerConfig + "-, new: -" + newServerConfigFile + "-"); if (checkAppUpdate) { // Make sure the TransportSecurityProvider app is started/updated when changing config server.waitForStringInLogUsingMark("CWWKZ0001I.*TransportSecurityProvider | CWWKZ0003I.*TransportSecurityProvider", WAIT_TIME_OUT); } // Current configuration has SSL feature, but last configuration has no SSL feature, should check if the ssl port is opened. if (SERVER_CONFIG_WITH_SSL.contains(newServerConfigFile) && SERVER_CONFIG_WITHOUT_SSL.contains(lastServerConfig)) { Log.info(AbstractJaxWsTransportSecurityTest.class, "updateServerConfigFile", "Wait for ssl port open."); isFound = null != server.waitForStringInLogUsingMark("CWWKO0219I:.*-ssl"); } } if (!isFound) { if (warningWhenFail) { Log.warning(AbstractJaxWsTransportSecurityTest.class, "The SSL port is not opened!"); } else { fail("The SSL port is not opened!"); } } } finally { Log.info(AbstractJaxWsTransportSecurityTest.class, "updateServerConfigFile", "The last sever configuration file is: " + lastServerConfig); lastServerConfig = newServerConfigFile; } } /** * Update the file in the server root * * @param destFilePath the relative path to server root, such as "dropins/test.war.xml" * @param originFilePath the relative path to publish/files/JaxWsTransportSecurityServer/ * @throws Exception */ protected static void updateSingleFileInServerRoot(String destFilePath, String originFilePath) throws Exception { server.copyFileToLibertyServerRoot(SERVER_TMP_DIR, "JaxWsTransportSecurityServer/" + originFilePath); RemoteFile tmpAbsFile = null; try { int index = originFilePath.lastIndexOf("/"); if (index >= 0) { originFilePath = originFilePath.substring(index + 1); } tmpAbsFile = server.getFileFromLibertyServerRoot(SERVER_TMP_DIR + "/" + originFilePath); LibertyFileManager.moveFileIntoLiberty(server.getMachine(), server.getServerRoot(), destFilePath, tmpAbsFile.getAbsolutePath()); } finally { if (null != tmpAbsFile) { tmpAbsFile.delete(); } } } /** * Run test * * @param params the request parameters * @param expectedResp the expected response from connection * @param expectedServerInfos the expected server output in log, the info's order is very important * @throws ProtocolException * @throws MalformedURLException * @throws IOException */ protected void runTest(RequestParams params, String expectedResp, List<String> expectedServerInfos) throws Exception, ProtocolException, MalformedURLException, IOException { List<String> expectedResps = new ArrayList<String>(1); expectedResps.add(expectedResp); runTest(params, expectedResps, expectedServerInfos); } /** * Run test * * @param params the request parameters * @param expectedResponses the expected responses from connection * @param expectedServerInfos the expected server output in log, the info's order is very important * @throws ProtocolException * @throws MalformedURLException * @throws IOException */ protected void runTest(RequestParams params, List<String> expectedResponses, List<String> expectedServerInfos) throws Exception, ProtocolException, MalformedURLException, IOException { server.setMarkToEndOfLog(); StringBuilder urlBuilder = new StringBuilder("http://") .append(server.getHostname()) .append(":") .append(server.getHttpDefaultPort()) .append(SERVLET_PATH) .append("?user=").append(params.userName) .append("&serviceType=").append(params.serviceType) .append("&schema=").append(params.schema) .append("&port=").append(params.port) .append("&path=").append(params.path) .append("&testMethod=").append(testName.getMethodName()); if (null != params.testMode) { urlBuilder.append("&testMode=").append(params.testMode.getVale()); } if (null != expectedResponses) { assertTrue(printExpectedResponses(expectedResponses, false), checkExpectedResponses(urlBuilder.toString(), expectedResponses, false)); } if (null != expectedServerInfos) { for (String info : expectedServerInfos) { assertNotNull("The expected output in server log is " + info, server.waitForStringInLogUsingMark(info)); } } } private boolean checkExpectedResponses(String servletUrl, List<String> expectedResponses, boolean exact) throws IOException { Log.info(this.getClass(), testName.getMethodName(), "Calling Application with URL=" + servletUrl); HttpURLConnection con = HttpUtils.getHttpConnection(new URL(servletUrl), HttpURLConnection.HTTP_OK, REQUEST_TIMEOUT); StringBuilder sb = new StringBuilder(); BufferedReader br = null; try { br = HttpUtils.getConnectionStream(con); String line = br.readLine(); while (line != null) { sb.append(line); line = br.readLine(); } } finally { if (br != null) { br.close(); } } String responseContent = sb.toString(); Log.info(AbstractJaxWsTransportSecurityTest.class, "checkExpectedResponses", "responseContent = " + responseContent); if (exact) { //the response content must contain all the expect strings for (String expectStr : expectedResponses) { if (!responseContent.contains(expectStr)) { return false; } } return true; } else { //the response content could contain one of the expect strings for (String expectStr : expectedResponses) { if (responseContent.contains(expectStr)) { return true; } } return false; } } private String printExpectedResponses(List<String> expectedResponses, boolean exact) { StringBuilder sb = new StringBuilder("The expected output in server log is "); if (!exact && expectedResponses.size() > 1) { sb.append("one of "); } sb.append("["); for (int i = 0; i < expectedResponses.size(); i++) { if (i > 0) { sb.append(","); } sb.append("\"" + expectedResponses.get(i) + "\""); } sb.append("]"); return sb.toString(); } protected static class RequestParams { protected String userName; protected TestMode testMode; protected String serviceType; protected String schema; protected int port; protected String path; /** * @param userName * @param serviceType * @param schema * @param port * @param path */ public RequestParams(String userName, String serviceType, String schema, int port, String path) { super(); this.userName = userName; this.serviceType = serviceType; this.schema = schema; this.port = port; this.path = path; } /** * @param userName * @param testMode * @param serviceType * @param schema * @param port * @param path */ public RequestParams(String userName, TestMode testMode, String serviceType, String schema, int port, String path) { super(); this.userName = userName; this.testMode = testMode; this.serviceType = serviceType; this.schema = schema; this.port = port; this.path = path; } } protected enum TestMode { PORT("port"), DISPATCH("dispatch"); private final String innerValue; private TestMode(String value) { this.innerValue = value; } public String getVale() { return this.innerValue; } } }
epl-1.0
devjunix/libjt400-java
jtopenlite/com/ibm/jtopenlite/database/jdbc/JDBCColumnMetaData.java
2832
/////////////////////////////////////////////////////////////////////////////// // // JTOpenLite // // Filename: JDBCColumnMetaData.java // // The source code contained herein is licensed under the IBM Public License // Version 1.0, which has been approved by the Open Source Initiative. // Copyright (C) 2011-2012 International Business Machines Corporation and // others. All rights reserved. // /////////////////////////////////////////////////////////////////////////////// package com.ibm.jtopenlite.database.jdbc; import java.sql.SQLException; import java.sql.Types; import com.ibm.jtopenlite.database.DB2Type; /* * Utility class to get metadata information from columns and parameters */ public class JDBCColumnMetaData { public static int getPrecision(Column column) { /* The JDBC notion of precision and scale do not match what is returned in the 0x3812 -- Super extended data format. */ int precision = 0; switch(0xFFFE & column.getType()) { case DB2Type.CHAR: case DB2Type.VARCHAR: case DB2Type.LONGVARCHAR: case DB2Type.DATALINK: case DB2Type.BINARY: case DB2Type.VARBINARY: case DB2Type.LONGVARGRAPHIC: case DB2Type.VARGRAPHIC: case DB2Type.GRAPHIC: precision = column.getScale(); break; case DB2Type.FLOATINGPOINT: if (column.getLength() == 4) { return 24; } else { return 53; } case DB2Type.CLOB: case DB2Type.BLOB: precision = column.getLength() - 4; break; case DB2Type.DBCLOB: precision = (column.getLength() - 4) / 2; break; case DB2Type.INTEGER: precision = 10; break; case DB2Type.SMALLINT: precision = 5; break; case DB2Type.DATE: precision = 10; break; case DB2Type.TIME: precision = 8; break; case DB2Type.TIMESTAMP: precision = 26; break; case DB2Type.BLOB_LOCATOR: case DB2Type.CLOB_LOCATOR: case DB2Type.DBCLOB_LOCATOR: precision = column.getLobMaxSize(); break; case DB2Type.XML_LOCATOR: case DB2Type.XML: precision = 2147483647; break; default: precision = column.getPrecision(); } return precision; } public static int getScale(Column column) throws SQLException { switch(column.getSQLType()) { case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: case Types.DATE: case Types.TIME: case Types.DATALINK: case Types.BINARY: case Types.VARBINARY: case DB2Type.LONGVARGRAPHIC: case DB2Type.VARGRAPHIC: case DB2Type.GRAPHIC: return 0; case Types.TIMESTAMP: return 6; } return column.getScale(); } }
epl-1.0
marwensaid/SimpleFunctionalTest
sft-core/src/test/java/sft/integration/use/sut/decorators/subUseCase/SubUseCaseToc2b.java
358
package sft.integration.use.sut.decorators.subUseCase; import org.junit.Ignore; import org.junit.Test; import sft.FixturesHelper; public class SubUseCaseToc2b { @FixturesHelper private SftFixturesHelper sftFixturesHelper = new SftFixturesHelper(); @Test @Ignore public void scenario2b_1(){ sftFixturesHelper.success(); } }
epl-1.0
gavinying/vorto
bundles/org.eclipse.vorto.perspective/src/org/eclipse/vorto/perspective/dnd/dropaction/CreateProjectDropAction.java
5751
package org.eclipse.vorto.perspective.dnd.dropaction; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.vorto.codegen.api.context.IModelProjectContext; import org.eclipse.vorto.codegen.api.tasks.Generated; import org.eclipse.vorto.codegen.api.tasks.ICodeGeneratorTask; import org.eclipse.vorto.codegen.api.tasks.IOutputter; import org.eclipse.vorto.codegen.ui.display.MessageDisplayFactory; import org.eclipse.vorto.codegen.ui.progresstask.IProgressTask; import org.eclipse.vorto.codegen.ui.progresstask.ProgressTaskExecutionService; import org.eclipse.vorto.core.api.repository.IModelRepository; import org.eclipse.vorto.core.api.repository.ModelRepositoryFactory; import org.eclipse.vorto.core.api.repository.ModelResource; import org.eclipse.vorto.core.model.IModelProject; import org.eclipse.vorto.core.model.ModelId; import org.eclipse.vorto.core.model.ModelType; import org.eclipse.vorto.core.model.nature.FbDatatypeProjectNature; import org.eclipse.vorto.core.model.nature.InformationModelProjectNature; import org.eclipse.vorto.core.model.nature.IoTProjectNature; import org.eclipse.vorto.core.service.IModelProjectService; import org.eclipse.vorto.core.service.ModelProjectServiceFactory; import org.eclipse.vorto.perspective.dnd.IDropAction; import org.eclipse.vorto.wizard.ProjectCreationTask; import com.google.common.base.Function; import com.google.common.base.Functions; public class CreateProjectDropAction implements IDropAction { private IModelRepository modelRepo = ModelRepositoryFactory.getModelRepository(); private Function<ModelType, String> modelTypeToSuffix = Functions.forMap(modelTypeToSuffix()); private Function<ModelType, String[]> modelTypeToNature = Functions.forMap(modelTypeToNature()); private IModelProjectService projectService = ModelProjectServiceFactory.getDefault(); @Override public boolean performDrop(IModelProject receivingProject, Object droppedObject) { if (droppedObject == null || !(droppedObject instanceof ModelResource)) { throw new IllegalArgumentException("Dropped object should not be null and should be a ModelResource"); } ModelResource model = (ModelResource) droppedObject; IModelProjectContext context = getModelProjectContext(model); ProgressTaskExecutionService progressTaskExecutionService = ProgressTaskExecutionService .getProgressTaskExecutionService(); progressTaskExecutionService.syncRun(getProjectCreationTask(context, model)); return false; } private IProgressTask getProjectCreationTask(final IModelProjectContext context, final ModelResource model) { return new ProjectCreationTask(context) { @Override public IModelProject getIotproject(IProject project) { return ModelProjectServiceFactory.getDefault().getProjectFromEclipseProject(project); } @Override protected ICodeGeneratorTask< IModelProjectContext> getCodeGeneratorTask() { return new SharedModelCodeGenerationTask(model); } @Override protected String[] getProjectNature() { return modelTypeToNature.apply(model.getId().getModelType()); } }; } private class SharedModelCodeGenerationTask implements ICodeGeneratorTask<IModelProjectContext> { private ModelResource modelResource; public SharedModelCodeGenerationTask(ModelResource modelResource) { this.modelResource = modelResource; } public void generate(IModelProjectContext ctx, IOutputter outputter) { generateModel(outputter, IModelProjectService.MODELS_DIR, modelResource); } private void generateModel(IOutputter outputter, String modelDir, ModelResource model) { ModelId id = model.getId(); String content = new String(modelRepo.downloadContent(id), StandardCharsets.UTF_8); Generated generated = new Generated(id.getName() + modelTypeToSuffix.apply(id.getModelType()), modelDir, content); outputter.output(generated); for(ModelId referenceId : model.getReferences()) { ModelResource referenceModel = modelRepo.getModel(referenceId); generateModel(outputter, IModelProjectService.SHARED_MODELS_DIR, referenceModel); } } } private Map<ModelType, String> modelTypeToSuffix() { Map<ModelType, String> modelTypeSuffixMap = new HashMap<ModelType, String>(); modelTypeSuffixMap.put(ModelType.InformationModel, IModelProjectService.INFOMODEL_EXT); modelTypeSuffixMap.put(ModelType.Functionblock, IModelProjectService.FBMODEL_EXT); modelTypeSuffixMap.put(ModelType.Datatype, IModelProjectService.TYPE_EXT); return modelTypeSuffixMap; } private Map<ModelType, String[]> modelTypeToNature() { Map<ModelType, String[]> modelTypeNatureMap = new HashMap<ModelType, String[]>(); modelTypeNatureMap.put(ModelType.InformationModel, new String[] { InformationModelProjectNature.NATURE_ID }); modelTypeNatureMap.put(ModelType.Functionblock, new String[] { IoTProjectNature.NATURE_ID }); modelTypeNatureMap.put(ModelType.Datatype, new String[] { FbDatatypeProjectNature.NATURE_ID }); return modelTypeNatureMap; } private IModelProjectContext getModelProjectContext(final ModelResource model) { return new IModelProjectContext() { @Override public String getProjectName() { return model.getId().getName(); } @Override public String getWorkspaceLocation() { return ResourcesPlugin.getWorkspace().getRoot().getLocation().toString(); } @Override public String getModelName() { return model.getId().getName(); } @Override public String getModelVersion() { return model.getId().getVersion(); } @Override public String getModelDescription() { return model.getDescription(); } }; } }
epl-1.0
ossmeter/ossmeter
web/org-ossmeter-webapp/app/com/googlecode/pongo/runtime/PrimitiveListIterator.java
459
package com.googlecode.pongo.runtime; import java.util.Iterator; public class PrimitiveListIterator<T> implements Iterator<T> { protected Iterator<?> iterator = null; public PrimitiveListIterator(Iterator<?> iterator) { this.iterator = iterator; } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { return (T) iterator.next(); } @Override public void remove() { iterator.remove(); } }
epl-1.0
ModelWriter/WP3
Source/eu.modelwriter.visualization.jgrapx/src/eu/modelwriter/visualization/model/GraphBuilder.java
14929
package eu.modelwriter.visualization.model; import java.awt.Color; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import com.mxgraph.io.mxCodecRegistry; import com.mxgraph.io.mxObjectCodec; import com.mxgraph.model.mxCell; import com.mxgraph.util.mxConstants; import com.mxgraph.util.mxUtils; import com.mxgraph.view.mxMultiplicity; import eu.modelwriter.model.Atom; import eu.modelwriter.model.ModelElement; import eu.modelwriter.model.ModelElement.BOUND; import eu.modelwriter.model.ModelManager; import eu.modelwriter.model.RelationSet; import eu.modelwriter.model.Tuple; import eu.modelwriter.model.exception.InvalidArityException; import eu.modelwriter.model.exception.NoSuchModelElementException; import eu.modelwriter.model.observer.Observer; import eu.modelwriter.model.observer.Subject; import eu.modelwriter.model.observer.UpdateType; import eu.modelwriter.visualization.editor.Graph; import eu.modelwriter.visualization.editor.StaticEditorManager; import eu.modelwriter.visualization.editor.util.EdgeUtil; /** * {@link GraphBuilder#build() Builds} {@link Graph graph} with data which taken from * {@link ModelManager manager}. <br> * Implements {@link Observer} and be notified by {@link ModelManager} with {@link UpdateType * updates} which are occured in manager. So {@link GraphBuilder#update(Subject, Object) updates} * {@link Graph graph} according to notification. * */ public class GraphBuilder implements Observer { private final ModelManager manager; /** * Map for each {@linkplain Atom#getID() atomId} to {@linkplain mxCell vertex} <br> */ private final Map<String, mxCell> atomId2Vertex = new TreeMap<>(); /** * Map for each relation name to specific color. */ private final Map<String, Color> relName2Color = new TreeMap<>(); /** * List for each relation which has same target and source as unordered. */ private final List<Object> parallelRelation = new ArrayList<>(); /** * List for each {@linkplain mxCell vertex} which have self edges. */ private final List<Object> selfEdges = new ArrayList<>(); /** * List of unary relation names. */ private final List<String> unaryRelationNames = new ArrayList<>(); /** * List of n'ary relation names. */ private final List<String> n_aryRelationNames = new ArrayList<>(); private Object parent; /** * Sets the manager and then {@link ModelManager#addObserver(Observer) adds} itself to manager as * {@link Observer}. * * @param manager */ public GraphBuilder(final ModelManager manager) { this.manager = manager; this.manager.addObserver(this); } public void addAtom(final List<String> relationSetsNames, final Serializable data, final BOUND bound) { try { final Atom atom = this.manager.addAtom(this.manager.getRelationSets(relationSetsNames), data, bound); this.createVertex(atom); } catch (final InvalidArityException e) { e.printStackTrace(); } } public void addTuple(final String relationSetName, final Serializable data, final BOUND bound, final int arity, final Atom... atoms) { try { final Tuple tuple = this.manager.addTuple(this.manager.getRelationSet(relationSetName), data, bound, arity, atoms); this.createEdge(tuple); } catch (final InvalidArityException e) { } } /** * Assigns given color to style which is named styleName. * * @param styleName * @param color */ private void assignColor2EdgeStyle(final String styleName, final Color color) { final Map<String, Object> specificEdgeStyle = StaticEditorManager.graph.getStylesheet().getCellStyle(styleName, null); specificEdgeStyle.put(mxConstants.STYLE_STROKECOLOR, mxUtils.getHexColorString(color)); StaticEditorManager.graph.getStylesheet().putCellStyle(styleName, specificEdgeStyle); } /** * Takes {@linkplain RelationSet relationSets} from {@linkplain ModelManager manager} and then * <br> * Creates {@linkplain Graph#insertVertex(Object, String, Object) vertices} for each * {@linkplain Atom atom} and {@linkplain Graph#insertEdge(Object, String, Object, Object, Object) * edges} for each {@linkplain Tuple tuple}. <br> * Sets style and color of each edge. */ public void build() { this.setDefaultEdgeStyle(); this.parent = StaticEditorManager.graph.getDefaultParent(); final List<Atom> atoms = this.manager.getAllAtoms(); final List<Tuple> tuples = this.manager.getAllTuples(); this.unaryRelationNames.addAll(this.manager.getUnaryRelationSetNames()); this.n_aryRelationNames.addAll(this.manager.getNaryRelationSetNames()); mxCodecRegistry.addPackage("eu.modelwriter.model"); mxCodecRegistry.register(new mxObjectCodec(new eu.modelwriter.model.ModelElement())); for (final Atom atom : atoms) { this.createVertex(atom); } for (final Tuple tuple : tuples) { if (tuple.getArity() == 2) { this.createEdge(tuple); } } StaticEditorManager.graph.getModel().beginUpdate(); try { for (final String edgeStyleName : this.n_aryRelationNames) { this.createSpecificEdgeStyle(edgeStyleName); } this.specifyEdgeStyle(); this.specificEdgeStylesWithRandomColor(); } finally { StaticEditorManager.graph.getModel().endUpdate(); } } public void changeAtomType(final mxCell vertex, final List<String> selectedValuesList) { StaticEditorManager.graph.getModel().beginUpdate(); try { final Atom atom = (Atom) vertex.getValue(); this.manager.changeRelationSetsOfAtom(atom.getID(), selectedValuesList); StaticEditorManager.graph.removeCells(StaticEditorManager.graph.getEdges(vertex)); } catch (final InvalidArityException | NoSuchModelElementException e) { e.printStackTrace(); } finally { StaticEditorManager.graph.getModel().endUpdate(); } } private void createEdge(final Tuple tuple) { StaticEditorManager.graph.getModel().beginUpdate(); try { final String relationSetName = tuple.getRelationSetsNames().get(0); final ModelElement sourceAtom = tuple.getAtom(0); final mxCell sourceVertex = this.atomId2Vertex.get(sourceAtom.getID()); final ModelElement targetAtom = tuple.getAtom(1); final mxCell targetVertex = this.atomId2Vertex.get(targetAtom.getID()); boolean hasParallel = false; for (final Object object : StaticEditorManager.graph.getEdgesBetween(sourceVertex, targetVertex)) { final String edgeName = EdgeUtil.getInstance().getEdgeName((mxCell) object); if (edgeName.equals(relationSetName)) { this.parallelRelation.add(object); this.n_aryRelationNames.add(relationSetName + "$headed"); hasParallel = true; break; } } if (!hasParallel) { final Object edge = StaticEditorManager.graph.insertEdge(this.parent, tuple.getID(), tuple, sourceVertex, targetVertex, relationSetName); if (sourceVertex.equals(targetVertex)) { this.selfEdges.add(edge); } } } finally { StaticEditorManager.graph.getModel().endUpdate(); } } @SuppressWarnings("unused") private mxMultiplicity[] createMultiplicities() { final mxMultiplicity[] multiplicities = new mxMultiplicity[3]; multiplicities[0] = new mxMultiplicity(true, "Alias", null, null, 0, String.valueOf(Integer.MAX_VALUE), Arrays.asList(new String[] {"Word"}), null, "Alias Must Connect to Word", true); multiplicities[1] = new mxMultiplicity(true, "Directory", null, null, 0, String.valueOf(Integer.MAX_VALUE), Arrays.asList(new String[] {"Word", "Alias", "Directory", "Root"}), null, "Directory Must Connect to Object", true); multiplicities[2] = new mxMultiplicity(true, "Root", null, null, 0, String.valueOf(Integer.MAX_VALUE), Arrays.asList(new String[] {"Word", "Alias", "Directory", "Root"}), null, "final Directory Must Connect final to Object", true); multiplicities[2] = new mxMultiplicity(true, "Word", null, null, 0, "0", null, "Word can not connect to any other", null, true); return multiplicities; } /** * Creates specific edge style with given unique style name. * * @param styleName must be unique. * @param headed * @param headed */ private void createSpecificEdgeStyle(final String styleName) { final Hashtable<String, Object> specificEdgeStyle = new Hashtable<>(StaticEditorManager.graph.getStylesheet().getDefaultEdgeStyle()); StaticEditorManager.graph.getStylesheet().putCellStyle(styleName, specificEdgeStyle); } private void createVertex(final Atom atom) { StaticEditorManager.graph.getModel().beginUpdate(); try { final String atomID = atom.getID(); mxCell vertex = this.atomId2Vertex.get(atomID); if (vertex == null) { vertex = (mxCell) StaticEditorManager.graph.insertVertex(this.parent, null, atom, 0, 0, 0, 0); this.atomId2Vertex.put(atomID, vertex); } } finally { StaticEditorManager.graph.getModel().endUpdate(); } } public Map<String, mxCell> getAtomId2Vertex() { return this.atomId2Vertex; } public ModelManager getManager() { return this.manager; } /** * @return {@link GraphBuilder#n_aryRelationNames n_aryRelationNames} */ public List<String> getN_aryRelationNames() { return this.n_aryRelationNames; } /** * @return {@linkplain GraphBuilder#relName2Color relName2Color} */ public Map<String, Color> getRelName2Color() { return this.relName2Color; } /** * @return {@link GraphBuilder#unaryRelationNames unaryRelationNames} */ public List<String> getUnaryRelationNames() { return this.unaryRelationNames; } /** * Generates random unique color for given relation name. * * @param relationName * @return generated random unique color. */ private Color randomColor4Relation(final String relationName) { final Color oldColor = this.relName2Color.get(relationName); final Color color = UniqueColor.randomColor(); this.relName2Color.put(relationName, color); if (oldColor != null) { UniqueColor.get(oldColor).setUsed(false); } return color; } /** * Sets default edge style with some required parameters. */ private void setDefaultEdgeStyle() { final Hashtable<String, Object> style = new Hashtable<>(StaticEditorManager.graph.getStylesheet().getDefaultEdgeStyle()); style.put(mxConstants.STYLE_MOVABLE, "0"); style.put(mxConstants.STYLE_ROUNDED, "1"); style.put(mxConstants.STYLE_ENTRY_X, "0.5"); style.put(mxConstants.STYLE_EXIT_X, "0.5"); style.put(mxConstants.STYLE_ENTRY_Y, "0.5"); style.put(mxConstants.STYLE_EXIT_Y, "0.5"); style.put(mxConstants.STYLE_ARCSIZE, "100"); style.put(mxConstants.STYLE_STROKEWIDTH, "2"); style.put(mxConstants.STYLE_ALIGN, mxConstants.ALIGN_LEFT); StaticEditorManager.graph.getStylesheet().setDefaultEdgeStyle(style); } /** * Gives all edges specific edge style with random color, according to relation name. */ public void specificEdgeStylesWithRandomColor() { for (final String edgeStyleName : this.n_aryRelationNames) { final Color color = this.randomColor4Relation(edgeStyleName); this.assignColor2EdgeStyle(edgeStyleName, color); } } private void specifyEdgeStyle() { StaticEditorManager.graph.setCellStyles(mxConstants.STYLE_STARTARROW, mxConstants.ARROW_CLASSIC, this.parallelRelation.toArray()); StaticEditorManager.graph.setCellStyles(mxConstants.STYLE_DIRECTION, mxConstants.DIRECTION_EAST, this.selfEdges.toArray()); StaticEditorManager.graph.setCellStyles(mxConstants.STYLE_ALIGN, mxConstants.ALIGN_RIGHT, this.selfEdges.toArray()); StaticEditorManager.graph.setCellStyles(mxConstants.STYLE_BENDABLE, "0", this.selfEdges.toArray()); } /** * If there is any update on the model, {@link ModelManager} class * {@linkplain ModelManager#notifyAllObservers(Object) notifies} {@linkplain GraphBuilder this} * {@linkplain Observer observer} class about {@linkplain UpdateType update type} */ @Override public void update(final Object updatedObject, final Object updateType) { switch ((UpdateType) updateType) { case ADD_RELATION: System.out.println("ADD_RELATION : " + updatedObject.toString()); break; case REMOVE_RELATION: System.out.println("REMOVE_RELATION : " + updatedObject.toString()); break; case ADD_TUPLE: System.out.println("ADD_TUPLE : " + updatedObject.toString()); break; case REMOVE_TUPLE: System.out.println("REMOVE_TUPLE : " + updatedObject.toString()); break; case ADD_ATOM: System.out.println("ADD_ATOM : " + updatedObject.toString()); break; case REMOVE_ATOM: System.out.println("REMOVE_ATOM : " + updatedObject.toString()); break; case UPPER_BOUND: System.out.println("MOVE_TO_UPPER : " + updatedObject.toString()); break; case LOWER_BOUND: System.out.println("MOVE_TO_LOWER : " + updatedObject.toString()); break; case CHANGE_RELATION_SETS: System.out.println("CHANGE_RELATION_SETS : " + updatedObject.toString()); break; default: break; } } /** * Writes given xmlDocument to xml file. * * @param xmlDocument */ @SuppressWarnings("unused") private void writeXml(final Document xmlDocument) { Transformer transformer; try { transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3"); final DOMSource source = new DOMSource(xmlDocument); // final StreamResult console = // new StreamResult(new File("C:/Users/emre.kirmizi/Desktop/out.xml")); final StreamResult console = new StreamResult(new File("C:/Users/anil.ozturk/Desktop/out.xml")); transformer.transform(source, console); } catch (TransformerFactoryConfigurationError | TransformerException e) { e.printStackTrace(); } } }
epl-1.0
opendaylight/controller
opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/UpdateStrategy.java
611
/* * Copyright (c) 2016 Ericsson India Global Services Pvt Ltd. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.blueprint.ext; /** * Enumerates possible strategies when a component is updated. * * @author Vishal Thapar */ public enum UpdateStrategy { /* * Restart container */ RELOAD, /* * Don't do anything */ NONE }
epl-1.0
ModelWriter/Tarski
Source/eu.modelwriter.visualization.jgrapx/src/com/mxgraph/swing/handler/mxGraphTransferHandler.java
10714
/** * Copyright (c) 2008, Gaudenz Alder */ package com.mxgraph.swing.handler; import java.awt.Color; import java.awt.Image; import java.awt.Point; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.TransferHandler; import com.mxgraph.swing.mxGraphComponent; import com.mxgraph.swing.util.mxGraphTransferable; import com.mxgraph.util.mxCellRenderer; import com.mxgraph.util.mxPoint; import com.mxgraph.util.mxRectangle; import com.mxgraph.view.mxGraph; /** * */ public class mxGraphTransferHandler extends TransferHandler { /** * */ private static final long serialVersionUID = -6443287704811197675L; /** * Boolean that specifies if an image of the cells should be created for each transferable. * Default is true. */ public static boolean DEFAULT_TRANSFER_IMAGE_ENABLED = true; /** * Specifies the background color of the transfer image. If no color is given here then the * background color of the enclosing graph component is used. Default is Color.WHITE. */ public static Color DEFAULT_BACKGROUNDCOLOR = Color.WHITE; /** * Reference to the original cells for removal after a move. */ protected Object[] originalCells; /** * Reference to the last imported cell array. */ protected Transferable lastImported; /** * Sets the value for the initialImportCount. Default is 1. Updated in exportDone to contain 0 * after a cut and 1 after a copy. */ protected int initialImportCount = 1; /** * Counter for the last imported cell array. */ protected int importCount = 0; /** * Specifies if a transfer image should be created for the transferable. Default is * DEFAULT_TRANSFER_IMAGE. */ protected boolean transferImageEnabled = DEFAULT_TRANSFER_IMAGE_ENABLED; /** * Specifies the background color for the transfer image. Default is DEFAULT_BACKGROUNDCOLOR. */ protected Color transferImageBackground = DEFAULT_BACKGROUNDCOLOR; /** * */ protected Point location; /** * */ protected Point offset; /** * */ public int getImportCount() { return importCount; } /** * */ public void setImportCount(int value) { importCount = value; } /** * */ public void setTransferImageEnabled(boolean transferImageEnabled) { this.transferImageEnabled = transferImageEnabled; } /** * */ public boolean isTransferImageEnabled() { return this.transferImageEnabled; } /** * */ public void setTransferImageBackground(Color transferImageBackground) { this.transferImageBackground = transferImageBackground; } /** * */ public Color getTransferImageBackground() { return this.transferImageBackground; } /** * Returns true if the DnD operation started from this handler. */ public boolean isLocalDrag() { return originalCells != null; } /** * */ public void setLocation(Point value) { location = value; } /** * */ public void setOffset(Point value) { offset = value; } /** * */ public boolean canImport(JComponent comp, DataFlavor[] flavors) { for (int i = 0; i < flavors.length; i++) { if (flavors[i] != null && flavors[i].equals(mxGraphTransferable.dataFlavor)) { return true; } } return false; } /** * (non-Javadoc) * * @see javax.swing.TransferHandler#createTransferable(javax.swing.JComponent) */ public Transferable createTransferable(JComponent c) { if (c instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) c; mxGraph graph = graphComponent.getGraph(); if (!graph.isSelectionEmpty()) { originalCells = graphComponent.getExportableCells(graph.getSelectionCells()); if (originalCells.length > 0) { ImageIcon icon = (transferImageEnabled) ? createTransferableImage(graphComponent, originalCells) : null; return createGraphTransferable(graphComponent, originalCells, icon); } } } return null; } /** * */ public mxGraphTransferable createGraphTransferable(mxGraphComponent graphComponent, Object[] cells, ImageIcon icon) { mxGraph graph = graphComponent.getGraph(); mxPoint tr = graph.getView().getTranslate(); double scale = graph.getView().getScale(); mxRectangle bounds = graph.getPaintBounds(cells); // Removes the scale and translation from the bounds bounds.setX(bounds.getX() / scale - tr.getX()); bounds.setY(bounds.getY() / scale - tr.getY()); bounds.setWidth(bounds.getWidth() / scale); bounds.setHeight(bounds.getHeight() / scale); return createGraphTransferable(graphComponent, cells, bounds, icon); } /** * */ public mxGraphTransferable createGraphTransferable(mxGraphComponent graphComponent, Object[] cells, mxRectangle bounds, ImageIcon icon) { return new mxGraphTransferable(graphComponent.getGraph().cloneCells(cells), bounds, icon); } /** * */ public ImageIcon createTransferableImage(mxGraphComponent graphComponent, Object[] cells) { ImageIcon icon = null; Color bg = (transferImageBackground != null) ? transferImageBackground : graphComponent.getBackground(); Image img = mxCellRenderer.createBufferedImage(graphComponent.getGraph(), cells, 1, bg, graphComponent.isAntiAlias(), null, graphComponent.getCanvas()); if (img != null) { icon = new ImageIcon(img); } return icon; } /** * */ public void exportDone(JComponent c, Transferable data, int action) { initialImportCount = 1; if (c instanceof mxGraphComponent && data instanceof mxGraphTransferable) { // Requires that the graph handler resets the location to null if the drag leaves the // component. This is the condition to identify a cross-component move. boolean isLocalDrop = location != null; if (action == TransferHandler.MOVE && !isLocalDrop) { removeCells((mxGraphComponent) c, originalCells); initialImportCount = 0; } } originalCells = null; location = null; offset = null; } /** * */ protected void removeCells(mxGraphComponent graphComponent, Object[] cells) { graphComponent.getGraph().removeCells(cells); } /** * */ public int getSourceActions(JComponent c) { return COPY_OR_MOVE; } /** * Checks if the mxGraphTransferable data flavour is supported and calls importGraphTransferable * if possible. */ public boolean importData(JComponent c, Transferable t) { boolean result = false; if (isLocalDrag()) { // Enables visual feedback on the Mac result = true; } else { try { updateImportCount(t); if (c instanceof mxGraphComponent) { mxGraphComponent graphComponent = (mxGraphComponent) c; if (graphComponent.isEnabled() && t.isDataFlavorSupported(mxGraphTransferable.dataFlavor)) { mxGraphTransferable gt = (mxGraphTransferable) t.getTransferData(mxGraphTransferable.dataFlavor); if (gt.getCells() != null) { result = importGraphTransferable(graphComponent, gt); } } } } catch (Exception ex) { ex.printStackTrace(); } } return result; } /** * Counts the number of times that the given transferable has been imported. */ protected void updateImportCount(Transferable t) { if (lastImported != t) { importCount = initialImportCount; } else { importCount++; } lastImported = t; } /** * Returns true if the cells have been imported using importCells. */ protected boolean importGraphTransferable(mxGraphComponent graphComponent, mxGraphTransferable gt) { boolean result = false; try { mxGraph graph = graphComponent.getGraph(); double scale = graph.getView().getScale(); mxRectangle bounds = gt.getBounds(); double dx = 0, dy = 0; // Computes the offset for the placement of the imported cells if (location != null && bounds != null) { mxPoint translate = graph.getView().getTranslate(); dx = location.getX() - (bounds.getX() + translate.getX()) * scale; dy = location.getY() - (bounds.getY() + translate.getY()) * scale; // Keeps the cells aligned to the grid dx = graph.snap(dx / scale); dy = graph.snap(dy / scale); } else { int gs = graph.getGridSize(); dx = importCount * gs; dy = importCount * gs; } if (offset != null) { dx += offset.x; dy += offset.y; } importCells(graphComponent, gt, dx, dy); location = null; offset = null; result = true; // Requests the focus after an import graphComponent.requestFocus(); } catch (Exception e) { e.printStackTrace(); } return result; } /** * Returns the drop target for the given transferable and location. */ protected Object getDropTarget(mxGraphComponent graphComponent, mxGraphTransferable gt) { Object[] cells = gt.getCells(); Object target = null; // Finds the target cell at the given location and checks if the // target is not already the parent of the first imported cell if (location != null) { target = graphComponent.getGraph().getDropTarget(cells, location, graphComponent.getCellAt(location.x, location.y)); if (cells.length > 0 && graphComponent.getGraph().getModel().getParent(cells[0]) == target) { target = null; } } return target; } /** * Gets a drop target using getDropTarget and imports the cells using mxGraph.splitEdge or * mxGraphComponent.importCells depending on the drop target and the return values of * mxGraph.isSplitEnabled and mxGraph.isSplitTarget. Selects and returns the cells that have been * imported. */ protected Object[] importCells(mxGraphComponent graphComponent, mxGraphTransferable gt, double dx, double dy) { Object target = getDropTarget(graphComponent, gt); mxGraph graph = graphComponent.getGraph(); Object[] cells = gt.getCells(); cells = graphComponent.getImportableCells(cells); if (graph.isSplitEnabled() && graph.isSplitTarget(target, cells)) { graph.splitEdge(target, cells, dx, dy); } else { cells = graphComponent.importCells(cells, dx, dy, target, location); graph.setSelectionCells(cells); } return cells; } }
epl-1.0
Cooperate-Project/Cooperate
bundles/de.cooperateproject.modeling.textual.xtext.runtime/src/de/cooperateproject/modeling/textual/xtext/runtime/resources/observer/ResourceChangeObserverFactory.java
684
package de.cooperateproject.modeling.textual.xtext.runtime.resources.observer; import org.eclipse.emf.cdo.eresource.CDOResource; import org.eclipse.emf.ecore.resource.Resource; import com.google.common.base.Optional; public class ResourceChangeObserverFactory { public static Optional<IResourceChangeObserver> create(Resource r, ResourceChangeHandler changeHandler) { if (r instanceof CDOResource) { return Optional.fromNullable(new CDOResourceChangeObserver((CDOResource)r, changeHandler)); } else if (r.getURI().isPlatformResource()) { return Optional.fromNullable(new FileResourceChangeObserver(r, changeHandler)); } else { return Optional.absent(); } } }
epl-1.0
Limitart/Gigas_Java
GigasEVA/src/org/gigas/chat/message/proto/ChatMessageFactory.java
44575
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Chat.proto package org.gigas.chat.message.proto; public final class ChatMessageFactory { private ChatMessageFactory() { } public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) { } public interface ChatInfoOrBuilder extends com.google.protobuf.MessageLiteOrBuilder { // optional string content = 1; /** * <code>optional string content = 1;</code> * * <pre> * 聊天内容 * </pre> */ boolean hasContent(); /** * <code>optional string content = 1;</code> * * <pre> * 聊天内容 * </pre> */ java.lang.String getContent(); /** * <code>optional string content = 1;</code> * * <pre> * 聊天内容 * </pre> */ com.google.protobuf.ByteString getContentBytes(); // optional int64 number = 2; /** * <code>optional int64 number = 2;</code> * * <pre> * 发送者编号 * </pre> */ boolean hasNumber(); /** * <code>optional int64 number = 2;</code> * * <pre> * 发送者编号 * </pre> */ long getNumber(); // repeated int32 integerList = 3; /** * <code>repeated int32 integerList = 3;</code> * * <pre> * 整型数组 * </pre> */ java.util.List<java.lang.Integer> getIntegerListList(); /** * <code>repeated int32 integerList = 3;</code> * * <pre> * 整型数组 * </pre> */ int getIntegerListCount(); /** * <code>repeated int32 integerList = 3;</code> * * <pre> * 整型数组 * </pre> */ int getIntegerList(int index); // optional .RoleChatInfo roleChatInfo = 4; /** * <code>optional .RoleChatInfo roleChatInfo = 4;</code> * * <pre> * roleChatInfo * </pre> */ boolean hasRoleChatInfo(); /** * <code>optional .RoleChatInfo roleChatInfo = 4;</code> * * <pre> * roleChatInfo * </pre> */ org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo getRoleChatInfo(); } /** * Protobuf type {@code ChatInfo} * * <pre> * 聊天消息 * </pre> */ public static final class ChatInfo extends com.google.protobuf.GeneratedMessageLite implements ChatInfoOrBuilder { // Use ChatInfo.newBuilder() to construct. private ChatInfo(com.google.protobuf.GeneratedMessageLite.Builder builder) { super(builder); } private ChatInfo(boolean noInit) { } private static final ChatInfo defaultInstance; public static ChatInfo getDefaultInstance() { return defaultInstance; } public ChatInfo getDefaultInstanceForType() { return defaultInstance; } private ChatInfo(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, extensionRegistry, tag)) { done = true; } break; } case 10: { bitField0_ |= 0x00000001; content_ = input.readBytes(); break; } case 16: { bitField0_ |= 0x00000002; number_ = input.readInt64(); break; } case 24: { if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) { integerList_ = new java.util.ArrayList<java.lang.Integer>(); mutable_bitField0_ |= 0x00000004; } integerList_.add(input.readInt32()); break; } case 26: { int length = input.readRawVarint32(); int limit = input.pushLimit(length); if (!((mutable_bitField0_ & 0x00000004) == 0x00000004) && input.getBytesUntilLimit() > 0) { integerList_ = new java.util.ArrayList<java.lang.Integer>(); mutable_bitField0_ |= 0x00000004; } while (input.getBytesUntilLimit() > 0) { integerList_.add(input.readInt32()); } input.popLimit(limit); break; } case 34: { org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo.Builder subBuilder = null; if (((bitField0_ & 0x00000004) == 0x00000004)) { subBuilder = roleChatInfo_.toBuilder(); } roleChatInfo_ = input.readMessage(org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(roleChatInfo_); roleChatInfo_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000004; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e.getMessage()).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) { integerList_ = java.util.Collections.unmodifiableList(integerList_); } makeExtensionsImmutable(); } } public static com.google.protobuf.Parser<ChatInfo> PARSER = new com.google.protobuf.AbstractParser<ChatInfo>() { public ChatInfo parsePartialFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ChatInfo(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<ChatInfo> getParserForType() { return PARSER; } private int bitField0_; // optional string content = 1; public static final int CONTENT_FIELD_NUMBER = 1; private java.lang.Object content_; /** * <code>optional string content = 1;</code> * * <pre> * 聊天内容 * </pre> */ public boolean hasContent() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional string content = 1;</code> * * <pre> * 聊天内容 * </pre> */ public java.lang.String getContent() { java.lang.Object ref = content_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { content_ = s; } return s; } } /** * <code>optional string content = 1;</code> * * <pre> * 聊天内容 * </pre> */ public com.google.protobuf.ByteString getContentBytes() { java.lang.Object ref = content_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); content_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional int64 number = 2; public static final int NUMBER_FIELD_NUMBER = 2; private long number_; /** * <code>optional int64 number = 2;</code> * * <pre> * 发送者编号 * </pre> */ public boolean hasNumber() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional int64 number = 2;</code> * * <pre> * 发送者编号 * </pre> */ public long getNumber() { return number_; } // repeated int32 integerList = 3; public static final int INTEGERLIST_FIELD_NUMBER = 3; private java.util.List<java.lang.Integer> integerList_; /** * <code>repeated int32 integerList = 3;</code> * * <pre> * 整型数组 * </pre> */ public java.util.List<java.lang.Integer> getIntegerListList() { return integerList_; } /** * <code>repeated int32 integerList = 3;</code> * * <pre> * 整型数组 * </pre> */ public int getIntegerListCount() { return integerList_.size(); } /** * <code>repeated int32 integerList = 3;</code> * * <pre> * 整型数组 * </pre> */ public int getIntegerList(int index) { return integerList_.get(index); } // optional .RoleChatInfo roleChatInfo = 4; public static final int ROLECHATINFO_FIELD_NUMBER = 4; private org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo roleChatInfo_; /** * <code>optional .RoleChatInfo roleChatInfo = 4;</code> * * <pre> * roleChatInfo * </pre> */ public boolean hasRoleChatInfo() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional .RoleChatInfo roleChatInfo = 4;</code> * * <pre> * roleChatInfo * </pre> */ public org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo getRoleChatInfo() { return roleChatInfo_; } private void initFields() { content_ = ""; number_ = 0L; integerList_ = java.util.Collections.emptyList(); roleChatInfo_ = org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo.getDefaultInstance(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, getContentBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeInt64(2, number_); } for (int i = 0; i < integerList_.size(); i++) { output.writeInt32(3, integerList_.get(i)); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeMessage(4, roleChatInfo_); } } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream.computeBytesSize(1, getContentBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream.computeInt64Size(2, number_); } { int dataSize = 0; for (int i = 0; i < integerList_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream.computeInt32SizeNoTag(integerList_.get(i)); } size += dataSize; size += 1 * getIntegerListList().size(); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, roleChatInfo_); } memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo parseFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo parseDelimitedFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo parseFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } /** * Protobuf type {@code ChatInfo} * * <pre> * 聊天消息 * </pre> */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo, Builder> implements org.gigas.chat.message.proto.ChatMessageFactory.ChatInfoOrBuilder { // Construct using // org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); content_ = ""; bitField0_ = (bitField0_ & ~0x00000001); number_ = 0L; bitField0_ = (bitField0_ & ~0x00000002); integerList_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); roleChatInfo_ = org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo.getDefaultInstance(); bitField0_ = (bitField0_ & ~0x00000008); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo getDefaultInstanceForType() { return org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo.getDefaultInstance(); } public org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo build() { org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo buildPartial() { org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo result = new org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.content_ = content_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.number_ = number_; if (((bitField0_ & 0x00000004) == 0x00000004)) { integerList_ = java.util.Collections.unmodifiableList(integerList_); bitField0_ = (bitField0_ & ~0x00000004); } result.integerList_ = integerList_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000004; } result.roleChatInfo_ = roleChatInfo_; result.bitField0_ = to_bitField0_; return result; } public Builder mergeFrom(org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo other) { if (other == org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo.getDefaultInstance()) return this; if (other.hasContent()) { bitField0_ |= 0x00000001; content_ = other.content_; } if (other.hasNumber()) { setNumber(other.getNumber()); } if (!other.integerList_.isEmpty()) { if (integerList_.isEmpty()) { integerList_ = other.integerList_; bitField0_ = (bitField0_ & ~0x00000004); } else { ensureIntegerListIsMutable(); integerList_.addAll(other.integerList_); } } if (other.hasRoleChatInfo()) { mergeRoleChatInfo(other.getRoleChatInfo()); } return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.gigas.chat.message.proto.ChatMessageFactory.ChatInfo) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // optional string content = 1; private java.lang.Object content_ = ""; /** * <code>optional string content = 1;</code> * * <pre> * 聊天内容 * </pre> */ public boolean hasContent() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional string content = 1;</code> * * <pre> * 聊天内容 * </pre> */ public java.lang.String getContent() { java.lang.Object ref = content_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); content_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>optional string content = 1;</code> * * <pre> * 聊天内容 * </pre> */ public com.google.protobuf.ByteString getContentBytes() { java.lang.Object ref = content_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); content_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string content = 1;</code> * * <pre> * 聊天内容 * </pre> */ public Builder setContent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; content_ = value; return this; } /** * <code>optional string content = 1;</code> * * <pre> * 聊天内容 * </pre> */ public Builder clearContent() { bitField0_ = (bitField0_ & ~0x00000001); content_ = getDefaultInstance().getContent(); return this; } /** * <code>optional string content = 1;</code> * * <pre> * 聊天内容 * </pre> */ public Builder setContentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; content_ = value; return this; } // optional int64 number = 2; private long number_; /** * <code>optional int64 number = 2;</code> * * <pre> * 发送者编号 * </pre> */ public boolean hasNumber() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional int64 number = 2;</code> * * <pre> * 发送者编号 * </pre> */ public long getNumber() { return number_; } /** * <code>optional int64 number = 2;</code> * * <pre> * 发送者编号 * </pre> */ public Builder setNumber(long value) { bitField0_ |= 0x00000002; number_ = value; return this; } /** * <code>optional int64 number = 2;</code> * * <pre> * 发送者编号 * </pre> */ public Builder clearNumber() { bitField0_ = (bitField0_ & ~0x00000002); number_ = 0L; return this; } // repeated int32 integerList = 3; private java.util.List<java.lang.Integer> integerList_ = java.util.Collections.emptyList(); private void ensureIntegerListIsMutable() { if (!((bitField0_ & 0x00000004) == 0x00000004)) { integerList_ = new java.util.ArrayList<java.lang.Integer>(integerList_); bitField0_ |= 0x00000004; } } /** * <code>repeated int32 integerList = 3;</code> * * <pre> * 整型数组 * </pre> */ public java.util.List<java.lang.Integer> getIntegerListList() { return java.util.Collections.unmodifiableList(integerList_); } /** * <code>repeated int32 integerList = 3;</code> * * <pre> * 整型数组 * </pre> */ public int getIntegerListCount() { return integerList_.size(); } /** * <code>repeated int32 integerList = 3;</code> * * <pre> * 整型数组 * </pre> */ public int getIntegerList(int index) { return integerList_.get(index); } /** * <code>repeated int32 integerList = 3;</code> * * <pre> * 整型数组 * </pre> */ public Builder setIntegerList(int index, int value) { ensureIntegerListIsMutable(); integerList_.set(index, value); return this; } /** * <code>repeated int32 integerList = 3;</code> * * <pre> * 整型数组 * </pre> */ public Builder addIntegerList(int value) { ensureIntegerListIsMutable(); integerList_.add(value); return this; } /** * <code>repeated int32 integerList = 3;</code> * * <pre> * 整型数组 * </pre> */ public Builder addAllIntegerList(java.lang.Iterable<? extends java.lang.Integer> values) { ensureIntegerListIsMutable(); super.addAll(values, integerList_); return this; } /** * <code>repeated int32 integerList = 3;</code> * * <pre> * 整型数组 * </pre> */ public Builder clearIntegerList() { integerList_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); return this; } // optional .RoleChatInfo roleChatInfo = 4; private org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo roleChatInfo_ = org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo.getDefaultInstance(); /** * <code>optional .RoleChatInfo roleChatInfo = 4;</code> * * <pre> * roleChatInfo * </pre> */ public boolean hasRoleChatInfo() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>optional .RoleChatInfo roleChatInfo = 4;</code> * * <pre> * roleChatInfo * </pre> */ public org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo getRoleChatInfo() { return roleChatInfo_; } /** * <code>optional .RoleChatInfo roleChatInfo = 4;</code> * * <pre> * roleChatInfo * </pre> */ public Builder setRoleChatInfo(org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo value) { if (value == null) { throw new NullPointerException(); } roleChatInfo_ = value; bitField0_ |= 0x00000008; return this; } /** * <code>optional .RoleChatInfo roleChatInfo = 4;</code> * * <pre> * roleChatInfo * </pre> */ public Builder setRoleChatInfo(org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo.Builder builderForValue) { roleChatInfo_ = builderForValue.build(); bitField0_ |= 0x00000008; return this; } /** * <code>optional .RoleChatInfo roleChatInfo = 4;</code> * * <pre> * roleChatInfo * </pre> */ public Builder mergeRoleChatInfo(org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo value) { if (((bitField0_ & 0x00000008) == 0x00000008) && roleChatInfo_ != org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo.getDefaultInstance()) { roleChatInfo_ = org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo.newBuilder(roleChatInfo_).mergeFrom(value).buildPartial(); } else { roleChatInfo_ = value; } bitField0_ |= 0x00000008; return this; } /** * <code>optional .RoleChatInfo roleChatInfo = 4;</code> * * <pre> * roleChatInfo * </pre> */ public Builder clearRoleChatInfo() { roleChatInfo_ = org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo.getDefaultInstance(); bitField0_ = (bitField0_ & ~0x00000008); return this; } // @@protoc_insertion_point(builder_scope:ChatInfo) } static { defaultInstance = new ChatInfo(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:ChatInfo) } public interface RoleChatInfoOrBuilder extends com.google.protobuf.MessageLiteOrBuilder { // optional int64 roleId = 1; /** * <code>optional int64 roleId = 1;</code> * * <pre> * 角色ID * </pre> */ boolean hasRoleId(); /** * <code>optional int64 roleId = 1;</code> * * <pre> * 角色ID * </pre> */ long getRoleId(); // optional string name = 2; /** * <code>optional string name = 2;</code> * * <pre> * 角色名 * </pre> */ boolean hasName(); /** * <code>optional string name = 2;</code> * * <pre> * 角色名 * </pre> */ java.lang.String getName(); /** * <code>optional string name = 2;</code> * * <pre> * 角色名 * </pre> */ com.google.protobuf.ByteString getNameBytes(); // optional int32 level = 3; /** * <code>optional int32 level = 3;</code> * * <pre> * 等级 * </pre> */ boolean hasLevel(); /** * <code>optional int32 level = 3;</code> * * <pre> * 等级 * </pre> */ int getLevel(); // optional bool sex = 4; /** * <code>optional bool sex = 4;</code> * * <pre> * 性别 * </pre> */ boolean hasSex(); /** * <code>optional bool sex = 4;</code> * * <pre> * 性别 * </pre> */ boolean getSex(); } /** * Protobuf type {@code RoleChatInfo} * * <pre> * 玩家简要信息 * </pre> */ public static final class RoleChatInfo extends com.google.protobuf.GeneratedMessageLite implements RoleChatInfoOrBuilder { // Use RoleChatInfo.newBuilder() to construct. private RoleChatInfo(com.google.protobuf.GeneratedMessageLite.Builder builder) { super(builder); } private RoleChatInfo(boolean noInit) { } private static final RoleChatInfo defaultInstance; public static RoleChatInfo getDefaultInstance() { return defaultInstance; } public RoleChatInfo getDefaultInstanceForType() { return defaultInstance; } private RoleChatInfo(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; roleId_ = input.readInt64(); break; } case 18: { bitField0_ |= 0x00000002; name_ = input.readBytes(); break; } case 24: { bitField0_ |= 0x00000004; level_ = input.readInt32(); break; } case 32: { bitField0_ |= 0x00000008; sex_ = input.readBool(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e.getMessage()).setUnfinishedMessage(this); } finally { makeExtensionsImmutable(); } } public static com.google.protobuf.Parser<RoleChatInfo> PARSER = new com.google.protobuf.AbstractParser<RoleChatInfo>() { public RoleChatInfo parsePartialFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new RoleChatInfo(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<RoleChatInfo> getParserForType() { return PARSER; } private int bitField0_; // optional int64 roleId = 1; public static final int ROLEID_FIELD_NUMBER = 1; private long roleId_; /** * <code>optional int64 roleId = 1;</code> * * <pre> * 角色ID * </pre> */ public boolean hasRoleId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional int64 roleId = 1;</code> * * <pre> * 角色ID * </pre> */ public long getRoleId() { return roleId_; } // optional string name = 2; public static final int NAME_FIELD_NUMBER = 2; private java.lang.Object name_; /** * <code>optional string name = 2;</code> * * <pre> * 角色名 * </pre> */ public boolean hasName() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional string name = 2;</code> * * <pre> * 角色名 * </pre> */ public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { name_ = s; } return s; } } /** * <code>optional string name = 2;</code> * * <pre> * 角色名 * </pre> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } // optional int32 level = 3; public static final int LEVEL_FIELD_NUMBER = 3; private int level_; /** * <code>optional int32 level = 3;</code> * * <pre> * 等级 * </pre> */ public boolean hasLevel() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional int32 level = 3;</code> * * <pre> * 等级 * </pre> */ public int getLevel() { return level_; } // optional bool sex = 4; public static final int SEX_FIELD_NUMBER = 4; private boolean sex_; /** * <code>optional bool sex = 4;</code> * * <pre> * 性别 * </pre> */ public boolean hasSex() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>optional bool sex = 4;</code> * * <pre> * 性别 * </pre> */ public boolean getSex() { return sex_; } private void initFields() { roleId_ = 0L; name_ = ""; level_ = 0; sex_ = false; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeInt64(1, roleId_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, getNameBytes()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeInt32(3, level_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { output.writeBool(4, sex_); } } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream.computeInt64Size(1, roleId_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream.computeBytesSize(2, getNameBytes()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, level_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(4, sex_); } memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo parseFrom(com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo parseFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo parseDelimitedFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo parseFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } /** * Protobuf type {@code RoleChatInfo} * * <pre> * 玩家简要信息 * </pre> */ public static final class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo, Builder> implements org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfoOrBuilder { // Construct using // org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); roleId_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); name_ = ""; bitField0_ = (bitField0_ & ~0x00000002); level_ = 0; bitField0_ = (bitField0_ & ~0x00000004); sex_ = false; bitField0_ = (bitField0_ & ~0x00000008); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo getDefaultInstanceForType() { return org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo.getDefaultInstance(); } public org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo build() { org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo buildPartial() { org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo result = new org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.roleId_ = roleId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.name_ = name_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.level_ = level_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.sex_ = sex_; result.bitField0_ = to_bitField0_; return result; } public Builder mergeFrom(org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo other) { if (other == org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo.getDefaultInstance()) return this; if (other.hasRoleId()) { setRoleId(other.getRoleId()); } if (other.hasName()) { bitField0_ |= 0x00000002; name_ = other.name_; } if (other.hasLevel()) { setLevel(other.getLevel()); } if (other.hasSex()) { setSex(other.getSex()); } return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.gigas.chat.message.proto.ChatMessageFactory.RoleChatInfo) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // optional int64 roleId = 1; private long roleId_; /** * <code>optional int64 roleId = 1;</code> * * <pre> * 角色ID * </pre> */ public boolean hasRoleId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional int64 roleId = 1;</code> * * <pre> * 角色ID * </pre> */ public long getRoleId() { return roleId_; } /** * <code>optional int64 roleId = 1;</code> * * <pre> * 角色ID * </pre> */ public Builder setRoleId(long value) { bitField0_ |= 0x00000001; roleId_ = value; return this; } /** * <code>optional int64 roleId = 1;</code> * * <pre> * 角色ID * </pre> */ public Builder clearRoleId() { bitField0_ = (bitField0_ & ~0x00000001); roleId_ = 0L; return this; } // optional string name = 2; private java.lang.Object name_ = ""; /** * <code>optional string name = 2;</code> * * <pre> * 角色名 * </pre> */ public boolean hasName() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional string name = 2;</code> * * <pre> * 角色名 * </pre> */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { java.lang.String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * <code>optional string name = 2;</code> * * <pre> * 角色名 * </pre> */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string name = 2;</code> * * <pre> * 角色名 * </pre> */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; name_ = value; return this; } /** * <code>optional string name = 2;</code> * * <pre> * 角色名 * </pre> */ public Builder clearName() { bitField0_ = (bitField0_ & ~0x00000002); name_ = getDefaultInstance().getName(); return this; } /** * <code>optional string name = 2;</code> * * <pre> * 角色名 * </pre> */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; name_ = value; return this; } // optional int32 level = 3; private int level_; /** * <code>optional int32 level = 3;</code> * * <pre> * 等级 * </pre> */ public boolean hasLevel() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional int32 level = 3;</code> * * <pre> * 等级 * </pre> */ public int getLevel() { return level_; } /** * <code>optional int32 level = 3;</code> * * <pre> * 等级 * </pre> */ public Builder setLevel(int value) { bitField0_ |= 0x00000004; level_ = value; return this; } /** * <code>optional int32 level = 3;</code> * * <pre> * 等级 * </pre> */ public Builder clearLevel() { bitField0_ = (bitField0_ & ~0x00000004); level_ = 0; return this; } // optional bool sex = 4; private boolean sex_; /** * <code>optional bool sex = 4;</code> * * <pre> * 性别 * </pre> */ public boolean hasSex() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * <code>optional bool sex = 4;</code> * * <pre> * 性别 * </pre> */ public boolean getSex() { return sex_; } /** * <code>optional bool sex = 4;</code> * * <pre> * 性别 * </pre> */ public Builder setSex(boolean value) { bitField0_ |= 0x00000008; sex_ = value; return this; } /** * <code>optional bool sex = 4;</code> * * <pre> * 性别 * </pre> */ public Builder clearSex() { bitField0_ = (bitField0_ & ~0x00000008); sex_ = false; return this; } // @@protoc_insertion_point(builder_scope:RoleChatInfo) } static { defaultInstance = new RoleChatInfo(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:RoleChatInfo) } static { } // @@protoc_insertion_point(outer_class_scope) }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.cdi.2.0_fat/fat/src/com/ibm/ws/cdi20/fat/tests/FATSuite.java
972
/******************************************************************************* * Copyright (c) 2017, 2020 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.cdi20.fat.tests; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ AsyncEventsTest.class, BasicCdi20Tests.class, BuiltinAnnoLiteralsTest.class, CDIContainerConfigTest.class, SecureAsyncEventsTest.class }) public class FATSuite { }
epl-1.0
adimova/smarthome
bundles/core/org.eclipse.smarthome.core.test/src/test/java/org/eclipse/smarthome/core/library/types/ArithmeticGroupFunctionTest.java
8044
/** * Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.smarthome.core.library.types; import static org.junit.Assert.assertEquals; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.smarthome.core.items.GenericItem; import org.eclipse.smarthome.core.items.GroupFunction; import org.eclipse.smarthome.core.items.Item; import org.eclipse.smarthome.core.library.items.DimmerItem; import org.eclipse.smarthome.core.library.items.SwitchItem; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.State; import org.eclipse.smarthome.core.types.UnDefType; import org.junit.Before; import org.junit.Test; /** * @author Thomas.Eichstaedt-Engelen */ public class ArithmeticGroupFunctionTest { private GroupFunction function; private Set<Item> items; @Before public void init() { items = new HashSet<Item>(); } @Test public void testOrFunction() { items.add(new TestItem("TestItem1", OpenClosedType.CLOSED)); items.add(new TestItem("TestItem2", UnDefType.UNDEF)); items.add(new TestItem("TestItem3", OpenClosedType.OPEN)); items.add(new TestItem("TestItem4", OpenClosedType.CLOSED)); items.add(new TestItem("TestItem5", UnDefType.UNDEF)); function = new ArithmeticGroupFunction.Or(OpenClosedType.OPEN, OpenClosedType.CLOSED); State state = function.calculate(items); assertEquals(OpenClosedType.OPEN, state); } @Test public void testOrFunction_negative() { items.add(new TestItem("TestItem1", OpenClosedType.CLOSED)); items.add(new TestItem("TestItem2", UnDefType.UNDEF)); items.add(new TestItem("TestItem3", OpenClosedType.CLOSED)); items.add(new TestItem("TestItem4", OpenClosedType.CLOSED)); items.add(new TestItem("TestItem5", UnDefType.UNDEF)); function = new ArithmeticGroupFunction.Or(OpenClosedType.OPEN, OpenClosedType.CLOSED); State state = function.calculate(items); assertEquals(OpenClosedType.CLOSED, state); } @Test public void testOrFunction_justsOneItem() { items.add(new TestItem("TestItem1", UnDefType.UNDEF)); function = new ArithmeticGroupFunction.Or(OpenClosedType.OPEN, OpenClosedType.CLOSED); State state = function.calculate(items); assertEquals(OpenClosedType.CLOSED, state); } @Test public void testOrFunction_differntTypes() { DimmerItem dimmer1 = new DimmerItem("TestDimmer1"); dimmer1.setState(new PercentType("42")); DimmerItem dimmer2 = new DimmerItem("TestDimmer2"); dimmer2.setState(new DecimalType("0")); SwitchItem switch1 = new SwitchItem("TestSwitch1"); switch1.setState(OnOffType.ON); SwitchItem switch2 = new SwitchItem("TestSwitch2"); switch2.setState(OnOffType.OFF); items.add(dimmer1); items.add(dimmer2); items.add(switch1); items.add(switch2); function = new ArithmeticGroupFunction.Or(OnOffType.ON, OnOffType.OFF); State state = function.calculate(items); State decimalState = function.getStateAs(items, DecimalType.class); assertEquals(OnOffType.ON, state); assertEquals(new DecimalType("2"), decimalState); } @Test public void testNOrFunction() { items.add(new TestItem("TestItem1", OpenClosedType.CLOSED)); items.add(new TestItem("TestItem2", UnDefType.UNDEF)); items.add(new TestItem("TestItem3", OpenClosedType.OPEN)); items.add(new TestItem("TestItem4", OpenClosedType.CLOSED)); items.add(new TestItem("TestItem5", UnDefType.UNDEF)); function = new ArithmeticGroupFunction.NOr(OpenClosedType.OPEN, OpenClosedType.CLOSED); State state = function.calculate(items); assertEquals(OpenClosedType.CLOSED, state); } @Test public void testNOrFunction_negative() { items.add(new TestItem("TestItem1", OpenClosedType.CLOSED)); items.add(new TestItem("TestItem2", UnDefType.UNDEF)); items.add(new TestItem("TestItem3", OpenClosedType.CLOSED)); items.add(new TestItem("TestItem4", OpenClosedType.CLOSED)); items.add(new TestItem("TestItem5", UnDefType.UNDEF)); function = new ArithmeticGroupFunction.NOr(OpenClosedType.OPEN, OpenClosedType.CLOSED); State state = function.calculate(items); assertEquals(OpenClosedType.OPEN, state); } @Test public void testAndFunction() { items.add(new TestItem("TestItem1", OpenClosedType.OPEN)); items.add(new TestItem("TestItem2", OpenClosedType.OPEN)); items.add(new TestItem("TestItem3", OpenClosedType.OPEN)); function = new ArithmeticGroupFunction.And(OpenClosedType.OPEN, OpenClosedType.CLOSED); State state = function.calculate(items); assertEquals(OpenClosedType.OPEN, state); } @Test public void testAndFunction_negative() { items.add(new TestItem("TestItem1", OpenClosedType.OPEN)); items.add(new TestItem("TestItem2", UnDefType.UNDEF)); items.add(new TestItem("TestItem3", OpenClosedType.OPEN)); items.add(new TestItem("TestItem4", OpenClosedType.OPEN)); items.add(new TestItem("TestItem5", UnDefType.UNDEF)); function = new ArithmeticGroupFunction.And(OpenClosedType.OPEN, OpenClosedType.CLOSED); State state = function.calculate(items); assertEquals(OpenClosedType.CLOSED, state); } @Test public void testAndFunction_justsOneItem() { items.add(new TestItem("TestItem1", UnDefType.UNDEF)); function = new ArithmeticGroupFunction.And(OpenClosedType.OPEN, OpenClosedType.CLOSED); State state = function.calculate(items); assertEquals(OpenClosedType.CLOSED, state); } @Test public void testNAndFunction() { items.add(new TestItem("TestItem1", OpenClosedType.OPEN)); items.add(new TestItem("TestItem2", OpenClosedType.OPEN)); items.add(new TestItem("TestItem3", OpenClosedType.OPEN)); function = new ArithmeticGroupFunction.NAnd(OpenClosedType.OPEN, OpenClosedType.CLOSED); State state = function.calculate(items); assertEquals(OpenClosedType.CLOSED, state); } @Test public void testNAndFunction_negative() { items.add(new TestItem("TestItem1", OpenClosedType.OPEN)); items.add(new TestItem("TestItem2", OpenClosedType.OPEN)); items.add(new TestItem("TestItem3", OpenClosedType.CLOSED)); function = new ArithmeticGroupFunction.NAnd(OpenClosedType.OPEN, OpenClosedType.CLOSED); State state = function.calculate(items); assertEquals(OpenClosedType.OPEN, state); } @Test public void testSumFunction() { items.add(new TestItem("TestItem1", new DecimalType("23.54"))); items.add(new TestItem("TestItem2", UnDefType.NULL)); items.add(new TestItem("TestItem3", new DecimalType("89"))); items.add(new TestItem("TestItem4", UnDefType.UNDEF)); items.add(new TestItem("TestItem5", new DecimalType("122.41"))); function = new ArithmeticGroupFunction.Sum(); State state = function.calculate(items); assertEquals(new DecimalType("234.95"), state); } class TestItem extends GenericItem { public TestItem(String name, State state) { super("Test", name); setState(state); } @Override public List<Class<? extends State>> getAcceptedDataTypes() { return null; } @Override public List<Class<? extends Command>> getAcceptedCommandTypes() { return null; } } }
epl-1.0
OpenLiberty/open-liberty
dev/io.openliberty.ws.jaxws.global.handler.internal_fat/test-applications/testHandlerClient/src/com/ibm/samples/jaxws/client/SayHelloService.java
783
/******************************************************************************* * Copyright (c) 2021 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.samples.jaxws.client; import javax.jws.WebService; /** * */ @WebService(name = "SayHello", targetNamespace = "http://jaxws.samples.ibm.com.handler/") public interface SayHelloService { public String sayHello(String name); }
epl-1.0
mrkakos/blog
stat4j/src/net/sourceforge/stat4j/calculators/Count.java
1217
/* * Copyright 2005 stat4j.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 net.sourceforge.stat4j.calculators; import java.util.Properties; import net.sourceforge.stat4j.Metric; /** * Name: Count.java * Date: Aug 29, 2004 * Description: * * * @author Lara D'Abreo */ public class Count extends CalculatorAdapter { protected long count; public Count() { reset(); } public void applyMetric(Metric metric) { setTimestamp(metric.getTimestamp()); count = count + 1; } public double getResult() { return count; } public void reset() { this.count = 0; } public void init(String name,Properties properties) { super.init(name); } }
epl-1.0
Maarc/windup-as-a-service
windup_0_7/windup-metadata/src/main/java/org/jboss/windup/metadata/decoration/archetype/JVMBuildVersionResult.java
812
/* * Copyright (c) 2013 Red Hat, Inc. and/or its affiliates. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Brad Davis - bradsdavis@gmail.com - Initial API and implementation */ package org.jboss.windup.metadata.decoration.archetype; import org.jboss.windup.metadata.decoration.AbstractDecoration; public class JVMBuildVersionResult extends AbstractDecoration { private String jdkBuildVersion; public String getJdkBuildVersion() { return jdkBuildVersion; } public void setJdkBuildVersion(String jdkBuildVersion) { this.jdkBuildVersion = jdkBuildVersion; } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.javaee.ddmodel/src/com/ibm/ws/javaee/ddmodel/common/EnvEntryType.java
4015
/******************************************************************************* * Copyright (c) 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.ws.javaee.ddmodel.common; import java.util.Collections; import java.util.List; import com.ibm.ws.javaee.dd.common.Description; import com.ibm.ws.javaee.dd.common.EnvEntry; import com.ibm.ws.javaee.ddmodel.DDParser; import com.ibm.ws.javaee.ddmodel.DDParser.ParsableListImplements; import com.ibm.ws.javaee.ddmodel.DDParser.ParseException; /* <xsd:complexType name="env-entryType"> <xsd:sequence> <xsd:element name="description" type="javaee:descriptionType" minOccurs="0" maxOccurs="unbounded"/> <xsd:element name="env-entry-name" type="javaee:jndi-nameType"> </xsd:element> <xsd:element name="env-entry-type" type="javaee:env-entry-type-valuesType" minOccurs="0"> </xsd:element> <xsd:element name="env-entry-value" type="javaee:xsdStringType" minOccurs="0"> </xsd:element> <xsd:group ref="javaee:resourceGroup"/> </xsd:sequence> <xsd:attribute name="id" type="xsd:ID"/> </xsd:complexType> */ public class EnvEntryType extends ResourceGroup implements EnvEntry { public static class ListType extends ParsableListImplements<EnvEntryType, EnvEntry> { @Override public EnvEntryType newInstance(DDParser parser) { return new EnvEntryType(); } } @Override public List<Description> getDescriptions() { if (description != null) { return description.getList(); } else { return Collections.emptyList(); } } @Override public String getTypeName() { return env_entry_type != null ? env_entry_type.getValue() : null; } @Override public String getValue() { return env_entry_value != null ? env_entry_value.getValue() : null; } // elements DescriptionType.ListType description; XSDTokenType env_entry_type; XSDStringType env_entry_value; // ResourceGroup fields appear here in sequence public EnvEntryType() { super("env-entry-name"); } @Override public boolean isIdAllowed() { return true; } @Override public boolean handleChild(DDParser parser, String localName) throws ParseException { if (super.handleChild(parser, localName)) { return true; } if ("description".equals(localName)) { DescriptionType description = new DescriptionType(); parser.parse(description); addDescription(description); return true; } if ("env-entry-type".equals(localName)) { XSDTokenType env_entry_type = new XSDTokenType(); parser.parse(env_entry_type); this.env_entry_type = env_entry_type; return true; } if ("env-entry-value".equals(localName)) { XSDStringType env_entry_value = new XSDStringType(true); parser.parse(env_entry_value); this.env_entry_value = env_entry_value; return true; } return false; } private void addDescription(DescriptionType description) { if (this.description == null) { this.description = new DescriptionType.ListType(); } this.description.add(description); } @Override public void describe(DDParser.Diagnostics diag) { diag.describeIfSet("description", description); diag.describeIfSet("env-entry-type", env_entry_type); diag.describeIfSet("env-entry-value", env_entry_value); super.describe(diag); } }
epl-1.0
Mark-Booth/daq-eclipse
uk.ac.diamond.org.apache.activemq/org/fusesource/hawtbuf/codec/VarSignedIntegerCodec.java
1701
/** * 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.fusesource.hawtbuf.codec; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; /** * Implementation of a variable length Codec for a signed Integer * */ public class VarSignedIntegerCodec extends VarIntegerCodec { public static final VarSignedIntegerCodec INSTANCE = new VarSignedIntegerCodec(); public void encode(Integer value, DataOutput dataOut) throws IOException { super.encode(encodeZigZag(value), dataOut); } public Integer decode(DataInput dataIn) throws IOException { return decodeZigZag(super.decode(dataIn)); } private static int decodeZigZag(int n) { return (n >>> 1) ^ -(n & 1); } private static int encodeZigZag(int n) { return (n << 1) ^ (n >> 31); } public int estimatedSize(Integer value) { return super.estimatedSize(encodeZigZag(value)); } }
epl-1.0
xen-0/dawnsci
org.eclipse.dawnsci.nexus/src/org/eclipse/dawnsci/nexus/builder/data/impl/AxisFieldModel.java
1754
package org.eclipse.dawnsci.nexus.builder.data.impl; import java.util.Arrays; import org.eclipse.dawnsci.nexus.NXdata; /** * A model for how the dimensions of a data field correspond to the dimensions * of the primary data field (i.e. the <code>@signal</code> field ) of an {@link NXdata} group. */ public class AxisFieldModel extends DataFieldModel { private Integer defaultAxisDimension = null; private int[] dimensionMappings = null; public AxisFieldModel(String sourceFieldName, int fieldRank) { super(sourceFieldName, fieldRank); } /** * Sets the default axis dimension for this data field to the given value. * This is the dimension of the default data field of the {@link NXdata} group * for which this field provides a default axis when plotting the data. * @param defaultAxisDimension default axis dimension index */ public void setDefaultAxisDimension(Integer defaultAxisDimension) { this.defaultAxisDimension = defaultAxisDimension; } public Integer getDefaultAxisDimension() { return defaultAxisDimension; } /** * Sets the dimension mappings for the given field to the given value. * This is the mapping from the dimensions of this field to the dimensions * of the default data field of the {@link NXdata} group. * @param dimensionMappings dimension mappings */ public void setDimensionMappings(int... dimensionMappings) { this.dimensionMappings = dimensionMappings; } public int[] getDimensionMappings() { return dimensionMappings; } @Override protected void appendMemberFields(StringBuilder sb) { super.appendMemberFields(sb); sb.append(", defaultAxisDimension = " + defaultAxisDimension); sb.append(", dimensionMappings = " + Arrays.toString(dimensionMappings)); } }
epl-1.0
zzzzgc/ZGC4Obj
Admin/src/main/java/xinxing/boss/admin/boss/other/cmd/BossOvertimeOrderRecordCmd.java
7917
package xinxing.boss.admin.boss.other.cmd; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import xinxing.boss.admin.boss.order.domain.OrderInfo; import xinxing.boss.admin.boss.order.service.OrderInfoService; import xinxing.boss.admin.boss.other.domain.BossOvertimeOrderRecord; import xinxing.boss.admin.boss.other.service.BossOvertimeOrderRecordService; import xinxing.boss.admin.common.excel.ExcelUtils; import xinxing.boss.admin.common.persistence.Page; import xinxing.boss.admin.common.persistence.PropertyFilter; import xinxing.boss.admin.common.utils.http.HttpUtils; import xinxing.boss.admin.common.utils.json.JsonUtils; import xinxing.boss.admin.common.utils.parameter.ParameterListener; import xinxing.boss.admin.common.utils.string.StringUtils; import xinxing.boss.admin.common.utils.time.DateUtils; import xinxing.boss.admin.common.web.BaseController; import xinxing.boss.admin.system.user.utils.UserUtil; @Controller @RequestMapping(value = "boss/bossOvertimeOrderRecord") public class BossOvertimeOrderRecordCmd extends BaseController { private static Logger log = LoggerFactory.getLogger(BossOvertimeOrderRecordCmd.class); @Autowired private BossOvertimeOrderRecordService bossOvertimeOrderRecordService; @Autowired private OrderInfoService orderInfoService; // 弹出框的方法 @RequestMapping(value = "alertWindow") @ResponseBody public String alertWindow(HttpServletRequest req, BossOvertimeOrderRecord bossOvertimeOrderRecord, Integer[] ids, String method) { Map<String, String> reqParams = HttpUtils.getReqParams(req); if (reqParams == null) { reqParams = new HashMap<String, String>(); } log.info("reqParams:" + JsonUtils.obj2Json(reqParams)); return "success"; } // 额外的方法 @RequestMapping(value = "updateStatus", method = RequestMethod.POST) @ResponseBody public String updateStatus(HttpServletRequest req, Integer[] ids, Integer status) { Map<String, String> reqParams = HttpUtils.getReqParams(req); if (reqParams == null) { reqParams = new HashMap<String, String>(); } log.info("reqParams:" + JsonUtils.obj2Json(reqParams)); // if (status!=null&&status >= 0 && status <= 2){ // for (Integer id : ids) { // BossOvertimeOrderRecord bossOvertimeOrderRecord = bossOvertimeOrderRecordService.get(id); // bossOvertimeOrderRecord.setStatus(status); // update(bossOvertimeOrderRecord); // } // } return "success"; } // 获取数据到页面 @RequestMapping(value = "bossOvertimeOrderRecordList") @ResponseBody public Map<String, Object> getConfigList(HttpServletRequest req) { Page<BossOvertimeOrderRecord> page = getPage(req); List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(req); page = bossOvertimeOrderRecordService.search(page, filters); return getEasyUIData(page); } // 跳转页面 @RequestMapping(value = "list", method = RequestMethod.GET) public String list(HttpServletRequest req, Integer id, BossOvertimeOrderRecord bossOvertimeOrderRecord, Model model) { Map<String, String> reqMap = HttpUtils.getReqParams(req); if (reqMap == null) { reqMap = new HashMap<String, String>(); } String page = reqMap.get("page"); if (StringUtils.isEmpty(page)) { page = "List"; } if (id != null) { bossOvertimeOrderRecord = bossOvertimeOrderRecordService.get(id); } model.addAttribute("reqMap", reqMap); model.addAttribute("action", (id != null ? "update" : "add")); model.addAttribute("bossOvertimeOrderRecord", bossOvertimeOrderRecord); return "boss/bossOvertimeOrderRecord/bossOvertimeOrderRecord" + page; } // 添加 @RequiresPermissions("boss:bossOvertimeOrderRecord:add") @RequestMapping(value = "add", method = RequestMethod.POST) @ResponseBody public String add(@Valid BossOvertimeOrderRecord bossOvertimeOrderRecord, Model model, String batchs, HttpServletRequest req) { String addIds = ""; // bossOvertimeOrderRecord.addAndUpdateTimeAndUserId(); bossOvertimeOrderRecord.setAddTime(new Date()); bossOvertimeOrderRecord.setAddUser(UserUtil.getCurrentUser().getName()); if (StringUtils.isNotEmpty(batchs)) {// 批量添加 String[] split = batchs.split(","); for (String change : split) { BossOvertimeOrderRecord obj = JsonUtils.json2Obj(JsonUtils.obj2Json(bossOvertimeOrderRecord), BossOvertimeOrderRecord.class); // change内容修改 obj.setId(null); bossOvertimeOrderRecordService.save(obj); addIds = obj.getId() + " "; } } else {// 单个添加 bossOvertimeOrderRecordService.save(bossOvertimeOrderRecord); addIds = bossOvertimeOrderRecord.getId() + " "; } ParameterListener.refresh("bossOvertimeOrderRecord"); // ParameterListener.flushStatus("bossOvertimeOrderRecord"); log.info("bossOvertimeOrderRecord add:" + addIds); return "success"; } // 修改 @RequiresPermissions("boss:bossOvertimeOrderRecord:update") @RequestMapping(value = "update", method = RequestMethod.POST) @ResponseBody public String update(@Valid @ModelAttribute @RequestBody BossOvertimeOrderRecord bossOvertimeOrderRecord) { // bossOvertimeOrderRecord.updateTimeAndUserId(); bossOvertimeOrderRecordService.update(bossOvertimeOrderRecord); ParameterListener.refresh("bossOvertimeOrderRecord"); // ParameterListener.flushStatus("bossOvertimeOrderRecord"); return "success"; } // 批量删除 @RequiresPermissions("boss:bossOvertimeOrderRecord:delete") @RequestMapping(value = "delete") @ResponseBody public String delete(Integer[] ids) { if (ids != null && ids.length > 0) { for (Integer id : ids) { bossOvertimeOrderRecordService.delete(id); log.info("bossOvertimeOrderRecord delete:" + id); } ParameterListener.refresh("bossOvertimeOrderRecord"); // ParameterListener.flushStatus("bossOvertimeOrderRecord"); } return "success"; } // 导出excel @RequiresPermissions("boss:bossOvertimeOrderRecord:exportExcel") @RequestMapping("exportExcel") public void createExcel(HttpServletRequest req, HttpServletResponse resp) throws Exception, InterruptedException { Integer maxNumber = 100000; Page<BossOvertimeOrderRecord> page = getPage(req); page.setPageNo(1); page.setPageSize(maxNumber); List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(req); page = bossOvertimeOrderRecordService.exportSearch(page, filters, maxNumber); if (page.getTotalCount() > maxNumber) { ExcelUtils.writeErrorMsg(resp, page.getTotalCount(), "导出数据不能超过10万条"); return; } List<BossOvertimeOrderRecord> list = page.getResult();// 获取数据 List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>(); for (BossOvertimeOrderRecord bossOvertimeOrderRecord : list) { Map<String, Object> beanToMap = ExcelUtils.beanToMap(bossOvertimeOrderRecord); // ExcelUtils.showValue(beanToMap, "status", ParameterListener.freezeStr); mapList.add(beanToMap); } String title = ""; String[] hearders = new String[] { "", "", "",// }; String[] fields = new String[] { "orderId", "addTime", "addUser",// }; ExcelUtils.productExcel(resp, mapList, title, hearders, fields, log); } }
epl-1.0
dmacvicar/spacewalk
java/code/src/com/redhat/rhn/frontend/events/test/RestartSatelliteActionTest.java
2017
/** * Copyright (c) 2009--2010 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package com.redhat.rhn.frontend.events.test; import com.redhat.rhn.common.validator.ValidatorError; import com.redhat.rhn.domain.role.RoleFactory; import com.redhat.rhn.domain.user.User; import com.redhat.rhn.frontend.events.RestartSatelliteAction; import com.redhat.rhn.frontend.events.RestartSatelliteEvent; import com.redhat.rhn.manager.satellite.RestartCommand; import com.redhat.rhn.testing.BaseTestCaseWithUser; public class RestartSatelliteActionTest extends BaseTestCaseWithUser { private TestRestartCommand command; public void testAction() throws Exception { user.addPermanentRole(RoleFactory.SAT_ADMIN); command = new TestRestartCommand(user); RestartSatelliteEvent event = new RestartSatelliteEvent(user); RestartSatelliteAction action = new RestartSatelliteAction() { protected RestartCommand getCommand(User currentUser) { return command; } }; action.execute(event); assertTrue(command.stored); } public class TestRestartCommand extends RestartCommand { private boolean stored = false; public TestRestartCommand(User userIn) { super(userIn); } /** * {@inheritDoc} */ public ValidatorError[] storeConfiguration() { stored = true; return null; } } }
gpl-2.0
skyHALud/codenameone
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/jndi/src/main/java/javax/naming/ldap/Rdn.java
11698
/* * 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 javax.naming.ldap; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import javax.naming.InvalidNameException; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttribute; import javax.naming.directory.BasicAttributes; import org.apache.harmony.jndi.internal.nls.Messages; import org.apache.harmony.jndi.internal.parser.LdapRdnParser; import org.apache.harmony.jndi.internal.parser.LdapTypeAndValueList; /** * TODO: JavaDoc */ public class Rdn implements Serializable, Comparable<Object> { private static final long serialVersionUID = -5994465067210009656L; public static String escapeValue(Object val) { if (val == null) { throw new NullPointerException("val " + Messages.getString("ldap.00")); } return LdapRdnParser.escapeValue(val); } public static Object unescapeValue(String val) { if (val == null) { throw new NullPointerException("val " + Messages.getString("ldap.00")); } return LdapRdnParser.unescapeValue(val); } private transient List<Attribute> list; private transient LdapRdnParser parser; public Rdn(Attributes attrSet) throws InvalidNameException { if (attrSet == null) { throw new NullPointerException("attrSet " + Messages.getString("ldap.00")); } if (attrSet.size() == 0) { throw new InvalidNameException("atrrSet " + Messages.getString("ldap.03")); } // check all the elements to follow RI's behavior NamingEnumeration<? extends Attribute> ne = attrSet.getAll(); while (ne.hasMoreElements()) { Attribute at = ne.nextElement(); try { at.get(); } catch (NamingException e) { } } list = convertToAttributeArrayList(attrSet); } public Rdn(Rdn rdn) { if (rdn == null) { throw new NullPointerException("rdn " + Messages.getString("ldap.00")); } list = convertToAttributeArrayList(rdn.toAttributes()); } public Rdn(String rdnString) throws InvalidNameException { if (rdnString == null) { throw new NullPointerException("rdnString " + Messages.getString("ldap.00")); } if (rdnString.length() != 0) { parser = new LdapRdnParser(rdnString); list = parser.getList(); } else { list = new ArrayList<Attribute>(); } } public Rdn(String type, Object value) throws InvalidNameException { if (type == null) { throw new NullPointerException("type " + Messages.getString("ldap.00")); } if (value == null) { throw new NullPointerException("value " + Messages.getString("ldap.00")); } if (type.length() == 0) { throw new InvalidNameException("type " + Messages.getString("ldap.04")); } if (value instanceof String && ((String) value).length() == 0) { throw new InvalidNameException("value " + Messages.getString("ldap.04")); } list = convertToAttributeArrayList(new BasicAttributes(type, value, true)); } public int compareTo(Object obj) { if (!(obj instanceof Rdn)) { throw new ClassCastException(Messages.getString("ldap.06")); //$NON-NLS-1$ } Rdn rdn = (Rdn) obj; String s1 = ""; //$NON-NLS-1$ String s2 = ""; //$NON-NLS-1$ for (Enumeration<?> iter = toAttributes().getAll(); iter .hasMoreElements();) { s1 = s1 + escapeValue(iter.nextElement().toString()); /* * this one does not seem necessary. Spec does not require it, if * there are apps that depend on commas, uncomment it */ // if (iter.hasMoreElements()) { // s1 = s1 + ","; // } } for (Enumeration<?> iter = rdn.toAttributes().getAll(); iter .hasMoreElements();) { s2 = s2 + escapeValue(iter.nextElement().toString()); /* * this one does not seem necessary. Spec does not require it, if * there are apps that depend on commas, uncomment it */ // if (iter.hasMoreElements()) { // s2 = s2 + ","; // } } return s1.toLowerCase().compareTo(s2.toLowerCase()); } private List<Attribute> convertToAttributeArrayList(Attributes attrList) { LdapTypeAndValueList myList = new LdapTypeAndValueList(); NamingEnumeration<? extends Attribute> ne = attrList.getAll(); try { while (ne.hasMoreElements()) { Attribute attr = ne.nextElement(); myList.put(attr.getID(), attr.get()); } } catch (NamingException e) { } return myList.toAttributeList(); } public boolean equals(Object obj) { if (!(obj instanceof Rdn) || this.size() != ((Rdn) obj).size()) { return false; } if (this == obj) { return true; } NamingEnumeration<? extends Attribute> iter1 = toAttributes().getAll(); NamingEnumeration<? extends Attribute> iter2 = ((Rdn) obj) .toAttributes().getAll(); while (iter1.hasMoreElements()) { Attribute a1 = iter1.nextElement(); Attribute a2 = iter2.nextElement(); if (!(a1.getID().toLowerCase().equals(a2.getID().toLowerCase())) || a1.size() != a2.size()) { return false; } Enumeration<?> en1 = null; Enumeration<?> en2 = null; try { en1 = a1.getAll(); en2 = a2.getAll(); } catch (NamingException e) { // what is the correct way for this? return false; } while (en1.hasMoreElements()) { Object o1 = en1.nextElement(); String s1 = (o1 instanceof String) ? (String) o1 : escapeValue(o1); Object o2 = en2.nextElement(); String s2 = (o2 instanceof String) ? (String) o2 : escapeValue(o2); if (!(s1.toLowerCase().equals(s2.toLowerCase()))) { return false; } } } return true; } public String getType() { return list.get(0).getID(); } public Object getValue() { Object a = null; try { a = list.get(0).get(); } catch (NamingException e) { } catch (NullPointerException e) { } return a; } public int hashCode() { int sum = 0; for (Iterator<Attribute> attr = list.iterator(); attr.hasNext();) { Attribute a = attr.next(); NamingEnumeration<?> en = null; sum += a.getID().toLowerCase().hashCode(); try { en = a.getAll(); } catch (NamingException e) { continue; } while (en.hasMoreElements()) { Object obj = en.nextElement(); if (obj instanceof byte[]) { obj = new String((byte[]) obj); } try { String s = (String) obj; sum += escapeValue(s.toLowerCase()).hashCode(); } catch (ClassCastException e) { sum += obj.hashCode(); } } } return sum; } public int size() { int result = 0; for (Iterator<Attribute> iter = list.iterator(); iter.hasNext();) { result += iter.next().size(); } return result; } public Attributes toAttributes() { BasicAttributes bas = new BasicAttributes(true); for (Iterator<Attribute> iter = list.iterator(); iter.hasNext();) { Attribute attr = iter.next(); BasicAttribute ba = new BasicAttribute(attr.getID(), false); try { NamingEnumeration nameEnum = attr.getAll(); while (nameEnum.hasMore()) { ba.add(nameEnum.next()); } } catch (NamingException ne) { } bas.put(ba); } return bas; } public String toString() { StringBuilder sb = new StringBuilder(); for (Iterator<Attribute> iter = list.iterator(); iter.hasNext();) { Attribute element = iter.next(); NamingEnumeration<?> ne = null; try { ne = element.getAll(); } catch (NamingException e) { } while (ne.hasMoreElements()) { sb.append(element.getID()); sb.append('='); sb.append(escapeValue(ne.nextElement())); if (ne.hasMoreElements()) { sb.append('+'); } } if (iter.hasNext()) { sb.append('+'); } } return sb.toString(); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException, InvalidNameException { ois.defaultReadObject(); String rdnString = (String) ois.readObject(); if (rdnString == null) { throw new NullPointerException("rdnString " + Messages.getString("ldap.00")); } if (rdnString.length() != 0) { parser = new LdapRdnParser(rdnString); list = parser.getList(); } else { list = new ArrayList<Attribute>(); } } private void writeObject(ObjectOutputStream oos) throws IOException { oos.defaultWriteObject(); oos.writeObject(this.toString()); } }
gpl-2.0
md-5/jdk10
test/hotspot/jtreg/gc/class_unloading/TestClassUnloadingDisabled.java
6037
/* * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package gc.class_unloading; /* * @test TestClassUnloadingDisabledSerial * @key gc * @bug 8114823 * @requires vm.opt.ExplicitGCInvokesConcurrent != true * @requires vm.opt.ClassUnloading != true * @requires vm.gc.Serial * @library /test/lib * @modules java.base/jdk.internal.misc * java.management * @build sun.hotspot.WhiteBox * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission * * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI * -XX:-ClassUnloading -XX:+UseSerialGC gc.class_unloading.TestClassUnloadingDisabled * */ /* * @test TestClassUnloadingDisabledParallel * @key gc * @bug 8114823 * @requires vm.opt.ExplicitGCInvokesConcurrent != true * @requires vm.opt.ClassUnloading != true * @requires vm.gc.Parallel * @library /test/lib * @modules java.base/jdk.internal.misc * java.management * @build sun.hotspot.WhiteBox * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission * * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI * -XX:-ClassUnloading -XX:+UseParallelGC gc.class_unloading.TestClassUnloadingDisabled * */ /* * @test TestClassUnloadingDisabledG1 * @key gc * @bug 8114823 * @requires vm.opt.ExplicitGCInvokesConcurrent != true * @requires vm.opt.ClassUnloading != true * @requires vm.gc.G1 * @library /test/lib * @modules java.base/jdk.internal.misc * java.management * @build sun.hotspot.WhiteBox * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission * * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI * -XX:-ClassUnloading -XX:+UseG1GC gc.class_unloading.TestClassUnloadingDisabled * */ /* * @test TestClassUnloadingDisabledShenandoah * @key gc * @bug 8114823 * @comment Graal does not support Shenandoah * @requires vm.gc.Shenandoah & !vm.graal.enabled * @requires vm.opt.ExplicitGCInvokesConcurrent != true * @requires vm.opt.ClassUnloading != true * @library /test/lib * @modules java.base/jdk.internal.misc * java.management * @build sun.hotspot.WhiteBox * @run driver ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI * -XX:-ClassUnloading -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC gc.class_unloading.TestClassUnloadingDisabled */ import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import sun.hotspot.WhiteBox; import static jdk.test.lib.Asserts.*; public class TestClassUnloadingDisabled { public static void main(String args[]) throws Exception { final WhiteBox wb = WhiteBox.getWhiteBox(); // Fetch the dir where the test class and the class // to be loaded resides. String classDir = TestClassUnloadingDisabled.class.getProtectionDomain().getCodeSource().getLocation().getPath(); String className = "gc.class_unloading.ClassToLoadUnload"; // can not use ClassToLoadUnload.class.getName() as that would load the class assertFalse(wb.isClassAlive(className), "Should not be loaded yet"); // The NoPDClassLoader handles loading classes in the test directory // and loads them without a protection domain, which in some cases // keeps the class live regardless of marking state. NoPDClassLoader nopd = new NoPDClassLoader(classDir); nopd.loadClass(className); assertTrue(wb.isClassAlive(className), "Class should be loaded"); // Clear the class-loader, class and object references to make // class unloading possible. nopd = null; System.gc(); assertTrue(wb.isClassAlive(className), "Class should not have ben unloaded"); } } class NoPDClassLoader extends ClassLoader { String path; NoPDClassLoader(String path) { this.path = path; } public Class<?> loadClass(String name) throws ClassNotFoundException { byte[] cls = null; File f = new File(path,name + ".class"); // Delegate class loading if class not present in the given // directory. if (!f.exists()) { return super.loadClass(name); } try { Path path = Paths.get(f.getAbsolutePath()); cls = Files.readAllBytes(path); } catch (IOException e) { throw new ClassNotFoundException(name); } // Define class with no protection domain and resolve it. return defineClass(name, cls, 0, cls.length, null); } } class ClassToLoadUnload { }
gpl-2.0
plgucm/practica4
src/maquinap/instrucciones/memoria/Espacio.java
1039
package maquinap.instrucciones.memoria; public class Espacio { private int dir_com, tam; private boolean libre; public Espacio(int dir, int tam, boolean libre) { this.dir_com = dir; this.libre = libre; this.tam = tam; } public boolean isLibre() { return libre; } public void setLibre(boolean libre) { this.libre = libre; } public int getDir_com() { return dir_com; } public void setDir_com(int dir_com) { this.dir_com = dir_com; } public int getTam() { return tam; } public void setTam(int tam) { this.tam = tam; } public int compareTo(Espacio e2) { if (this.dir_com < e2.dir_com){ return 1; } else if (this.dir_com > e2.dir_com){ return -1; } return 0; } public boolean estaEnEsteEspacioDeDirecciones(Integer dir) { return dir_com <= dir && dir_com+tam >= dir; } public boolean superaElTamanio(Integer dir, Integer cantidad) { return dir+tam<dir+cantidad; } public boolean loLiberaExacto(Integer dir, Integer cantidad) { return dir_com+tam==dir+cantidad; } }
gpl-2.0
isaacl/openjdk-jdk
test/java/awt/Mixing/AWT_Mixing/OverlappingTestBase.java
31291
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.awt.*; import java.awt.event.*; import java.awt.peer.ComponentPeer; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import javax.swing.*; import sun.awt.*; import java.io.*; import test.java.awt.regtesthelpers.Util; /** * <p>This class provides basis for AWT Mixing testing. * <p>It provides all standard test machinery and should be used by * extending and overriding next methods: * <li> {@link OverlappingTestBase#prepareControls()} - setup UI components * <li> {@link OverlappingTestBase#performTest()} - run particular test * Those methods would be run in the loop for each AWT component. * <p>Current AWT component should be added to the tested UI by {@link OverlappingTestBase#propagateAWTControls(java.awt.Container) ()}. * There AWT components are prepared to be tested as being overlayed by other (e.g. Swing) components - they are colored to * {@link OverlappingTestBase#AWT_BACKGROUND_COLOR} and throws failure on catching mouse event. * <p> Validation of component being overlayed should be tested by {@link OverlappingTestBase#clickAndBlink(java.awt.Robot, java.awt.Point) } * See each method javadoc for more details. * * <p>Due to test machinery limitations all test should be run from their own main() by calling next coe * <code> * public static void main(String args[]) throws InterruptedException { * instance = new YourTestInstance(); * OverlappingTestBase.doMain(args); * } * </code> * * @author Sergey Grinev */ public abstract class OverlappingTestBase { // working variables private static volatile boolean wasHWClicked = false; private static volatile boolean passed = true; // constants /** * Default color for AWT component used for validate correct drawing of overlapping. <b>Never</b> use it for lightweight components. */ protected static final Color AWT_BACKGROUND_COLOR = new Color(21, 244, 54); protected static Color AWT_VERIFY_COLOR = AWT_BACKGROUND_COLOR; protected static final int ROBOT_DELAY = 500; private static final String[] simpleAwtControls = {"Button", "Checkbox", "Label", "TextArea"}; /** * Generic strings array. To be used for population of List based controls. */ protected static final String[] petStrings = {"Bird", "Cat", "Dog", "Rabbit", "Rhynocephalia Granda", "Bear", "Tiger", "Mustang"}; // "properties" /** * Tests customization. Set this variable to test only control from java.awt * <p>Usage of this variable should be marked with CR being the reason. * <p>Do not use this variable simultaneously with {@link OverlappingTestBase#skipClassNames} */ protected String onlyClassName = null; /** * For customizing tests. List classes' simple names to skip them from testings. * <p>Usage of this variable should be marked with CR being the reason. */ protected String[] skipClassNames = null; /** * Set to false to avoid event delivery validation * @see OverlappingTestBase#clickAndBlink(java.awt.Robot, java.awt.Point, boolean) */ protected boolean useClickValidation = true; /** * Set to false if test doesn't supposed to verify EmbeddedFrame */ protected boolean testEmbeddedFrame = false; /** * Set this variable to true if testing embedded frame is impossible (on Mac, for instance, for now). * The testEmbeddedFrame is explicitly set to true in dozen places. */ protected boolean skipTestingEmbeddedFrame = false; public static final boolean isMac = System.getProperty("os.name").toLowerCase().contains("os x"); private boolean isFrameBorderCalculated; private int borderShift; { if (Toolkit.getDefaultToolkit().getClass().getName().matches(".*L.*Toolkit")) { // No EmbeddedFrame in LWToolkit/LWCToolkit, yet // And it should be programmed some other way, too, in any case System.err.println("skipTestingEmbeddedFrame"); skipTestingEmbeddedFrame = true; }else { System.err.println("do not skipTestingEmbeddedFrame"); } } protected int frameBorderCounter() { if (!isFrameBorderCalculated) { try { new FrameBorderCounter(); // force compilation by jtreg String JAVA_HOME = System.getProperty("java.home"); Process p = Runtime.getRuntime().exec(JAVA_HOME + "/bin/java FrameBorderCounter"); try { p.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); throw new RuntimeException(e); } if (p.exitValue() != 0) { throw new RuntimeException("FrameBorderCounter exited with not null code!\n" + readInputStream(p.getErrorStream())); } borderShift = Integer.parseInt(readInputStream(p.getInputStream()).trim()); isFrameBorderCalculated = true; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Problem calculating a native border size"); } } return borderShift; } public void getVerifyColor() { try { final int size = 200; final SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); final Point[] p = new Point[1]; SwingUtilities.invokeAndWait(new Runnable() { public void run(){ JFrame frame = new JFrame("set back"); frame.getContentPane().setBackground(AWT_BACKGROUND_COLOR); frame.setSize(size, size); frame.setUndecorated(true); frame.setVisible(true); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); p[0] = frame.getLocation(); } }); Robot robot = new Robot(); toolkit.realSync(); Thread.sleep(ROBOT_DELAY); AWT_VERIFY_COLOR = robot.getPixelColor(p[0].x+size/2, p[0].y+size/2); System.out.println("Color will be compared with " + AWT_VERIFY_COLOR + " instead of " + AWT_BACKGROUND_COLOR); } catch (Exception e) { System.err.println("Cannot get verify color: "+e.getMessage()); } } private String readInputStream(InputStream is) throws IOException { byte[] buffer = new byte[4096]; int len = 0; StringBuilder sb = new StringBuilder(); try (InputStreamReader isr = new InputStreamReader(is)) { while ((len = is.read(buffer)) > 0) { sb.append(new String(buffer, 0, len)); } } return sb.toString(); } private void setupControl(final Component control) { if (useClickValidation) { control.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { System.err.println("ERROR: " + control.getClass() + " received mouse click."); wasHWClicked = true; } }); } control.setBackground(AWT_BACKGROUND_COLOR); control.setForeground(AWT_BACKGROUND_COLOR); control.setPreferredSize(new Dimension(150, 150)); control.setFocusable(false); } private void addAwtControl(java.util.List<Component> container, final Component control) { String simpleName = control.getClass().getSimpleName(); if (onlyClassName != null && !simpleName.equals(onlyClassName)) { return; } if (skipClassNames != null) { for (String skipMe : skipClassNames) { if (simpleName.equals(skipMe)) { return; } } } setupControl(control); container.add(control); } private void addSimpleAwtControl(java.util.List<Component> container, String className) { try { Class definition = Class.forName("java.awt." + className); Constructor constructor = definition.getConstructor(new Class[]{String.class}); java.awt.Component component = (java.awt.Component) constructor.newInstance(new Object[]{"AWT Component " + className}); addAwtControl(container, component); } catch (Exception ex) { System.err.println(ex.getMessage()); fail("Setup error, this jdk doesn't have awt conrol " + className); } } /** * Adds current AWT control to container * <p>N.B.: if testEmbeddedFrame == true this method will also add EmbeddedFrame over Canvas * and it should be called <b>after</b> Frame.setVisible(true) call * @param container container to hold AWT component */ protected final void propagateAWTControls(Container container) { if (currentAwtControl != null) { container.add(currentAwtControl); } else { // embedded frame try { //create embedder Canvas embedder = new Canvas(); embedder.setBackground(Color.RED); embedder.setPreferredSize(new Dimension(150, 150)); container.add(embedder); container.setVisible(true); // create peer long frameWindow = 0; String getWindowMethodName = "getHWnd"; if (Toolkit.getDefaultToolkit().getClass().getName().contains("XToolkit")) { getWindowMethodName = "getWindow"; } ComponentPeer peer = embedder.getPeer(); // System.err.println("Peer: " + peer); Method getWindowMethod = peer.getClass().getMethod(getWindowMethodName); frameWindow = (Long) getWindowMethod.invoke(peer); // System.err.println("frame peer ID: " + frameWindow); String eframeClassName = "sun.awt.windows.WEmbeddedFrame"; if (Toolkit.getDefaultToolkit().getClass().getName().contains("XToolkit")) { eframeClassName = "sun.awt.X11.XEmbeddedFrame"; } Class eframeClass = Class.forName(eframeClassName); Constructor eframeCtor = eframeClass.getConstructor(long.class); EmbeddedFrame eframe = (EmbeddedFrame) eframeCtor.newInstance(frameWindow); setupControl(eframe); eframe.setSize(new Dimension(150, 150)); eframe.setVisible(true); // System.err.println(eframe.getSize()); } catch (Exception ex) { ex.printStackTrace(); fail("Failed to instantiate EmbeddedFrame: " + ex.getMessage()); } } } private static final Font hugeFont = new Font("Arial", Font.BOLD, 70); private java.util.List<Component> getAWTControls() { java.util.List<Component> components = new ArrayList<Component>(); for (String clazz : simpleAwtControls) { addSimpleAwtControl(components, clazz); } TextField tf = new TextField(); tf.setFont(hugeFont); addAwtControl(components, tf); // more complex controls Choice c = new Choice(); for (int i = 0; i < petStrings.length; i++) { c.add(petStrings[i]); } addAwtControl(components, c); c.setPreferredSize(null); c.setFont(hugeFont); // to make control bigger as setPrefferedSize don't do his job here List l = new List(petStrings.length); for (int i = 0; i < petStrings.length; i++) { l.add(petStrings[i]); } addAwtControl(components, l); Canvas canvas = new Canvas(); canvas.setSize(100, 200); addAwtControl(components, canvas); Scrollbar sb = new Scrollbar(Scrollbar.VERTICAL, 500, 1, 0, 500); addAwtControl(components, sb); Scrollbar sb2 = new Scrollbar(Scrollbar.HORIZONTAL, 500, 1, 0, 500); addAwtControl(components, sb2); return components; } /** * Default shift for {@link OverlappingTestBase#clickAndBlink(java.awt.Robot, java.awt.Point) } */ protected static Point shift = new Point(16, 16); /** * Verifies point using specified AWT Robot. Supposes <code>defaultShift == true</code> for {@link OverlappingTestBase#clickAndBlink(java.awt.Robot, java.awt.Point, boolean) }. * This method is used to verify controls by providing just their plain screen coordinates. * @param robot AWT Robot. Usually created by {@link Util#createRobot() } * @param lLoc point to verify * @see OverlappingTestBase#clickAndBlink(java.awt.Robot, java.awt.Point, boolean) */ protected void clickAndBlink(Robot robot, Point lLoc) { clickAndBlink(robot, lLoc, true); } /** * Default failure message for color check * @see OverlappingTestBase#performTest() */ protected String failMessageColorCheck = "The LW component did not pass pixel color check and is overlapped"; /** * Default failure message event check * @see OverlappingTestBase#performTest() */ protected String failMessage = "The LW component did not received the click."; private static boolean isValidForPixelCheck(Component component) { if ((component instanceof java.awt.Scrollbar) || isMac && (component instanceof java.awt.Button)) { return false; } return true; } /** * Preliminary validation - should be run <b>before</b> overlapping happens to ensure test is correct. * @param robot AWT Robot. Usually created by {@link Util#createRobot() } * @param lLoc point to validate to be <b>of</b> {@link OverlappingTestBase#AWT_BACKGROUND_COLOR} * @param component tested component, should be pointed out as not all components are valid for pixel check. */ protected void pixelPreCheck(Robot robot, Point lLoc, Component component) { if (isValidForPixelCheck(component)) { int tries = 10; Color c = null; while (tries-- > 0) { c = robot.getPixelColor(lLoc.x, lLoc.y); System.out.println("Precheck. color: "+c+" compare with "+AWT_VERIFY_COLOR); if (c.equals(AWT_VERIFY_COLOR)) { return; } try { Thread.sleep(100); } catch (InterruptedException e) { } } System.err.println(lLoc + ": " + c); fail("Dropdown test setup failure, colored part of AWT component is not located at click area"); } } /** * Verifies point using specified AWT Robot. * <p>Firstly, verifies point by color pixel check * <p>Secondly, verifies event delivery by mouse click * @param robot AWT Robot. Usually created by {@link Util#createRobot() } * @param lLoc point to verify * @param defaultShift if true verified position will be shifted by {@link OverlappingTestBase#shift }. */ protected void clickAndBlink(Robot robot, Point lLoc, boolean defaultShift) { Point loc = lLoc.getLocation(); //check color Util.waitForIdle(robot); try{ Thread.sleep(500); }catch(Exception exx){ exx.printStackTrace(); } if (defaultShift) { loc.translate(shift.x, shift.y); } if (!(System.getProperty("os.name").toLowerCase().contains("os x"))) { Color c = robot.getPixelColor(loc.x, loc.y); System.out.println("C&B. color: "+c+" compare with "+AWT_VERIFY_COLOR); if (c.equals(AWT_VERIFY_COLOR)) { fail(failMessageColorCheck); passed = false; } // perform click Util.waitForIdle(robot); } robot.mouseMove(loc.x, loc.y); robot.mousePress(InputEvent.BUTTON1_MASK); robot.mouseRelease(InputEvent.BUTTON1_MASK); Util.waitForIdle(robot); } /** * This method should be overriden with code which setups UI for testing. * Code in this method <b>will</b> be called only from AWT thread so Swing operations can be called directly. * * @see {@link OverlappingTestBase#propagateAWTControls(java.awt.Container) } for instructions about adding tested AWT control to UI */ protected abstract void prepareControls(); /** * This method should be overriden with test execution. It will <b>not</b> be called from AWT thread so all Swing operations should be treated accordingly. * @return true if test passed. Otherwise fail with default fail message. * @see {@link OverlappingTestBase#failMessage} default fail message */ protected abstract boolean performTest(); /** * This method can be overriden with cleanup routines. It will be called from AWT thread so all Swing operations should be treated accordingly. */ protected void cleanup() { // intentionally do nothing } /** * Currect tested AWT Control. Usually shouldn't be accessed directly. * * @see {@link OverlappingTestBase#propagateAWTControls(java.awt.Container) } for instructions about adding tested AWT control to UI */ protected Component currentAwtControl; private void testComponent(Component component) throws InterruptedException, InvocationTargetException { currentAwtControl = component; System.out.println("Testing " + currentAwtControl.getClass().getSimpleName()); SwingUtilities.invokeAndWait(new Runnable() { public void run() { prepareControls(); } }); if (component != null) { Util.waitTillShown(component); } Util.waitForIdle(null); try { Thread.sleep(500); // wait for graphic effects on systems like Win7 } catch (InterruptedException ex) { } if (!instance.performTest()) { fail(failMessage); passed = false; } SwingUtilities.invokeAndWait(new Runnable() { public void run() { cleanup(); } }); } private void testEmbeddedFrame() throws InvocationTargetException, InterruptedException { System.out.println("Testing EmbeddedFrame"); currentAwtControl = null; SwingUtilities.invokeAndWait(new Runnable() { public void run() { prepareControls(); } }); Util.waitForIdle(null); try { Thread.sleep(500); // wait for graphic effects on systems like Win7 } catch (InterruptedException ex) { } if (!instance.performTest()) { fail(failMessage); passed = false; } SwingUtilities.invokeAndWait(new Runnable() { public void run() { cleanup(); } }); } private void testAwtControls() throws InterruptedException { try { for (Component component : getAWTControls()) { testComponent(component); } if (testEmbeddedFrame && !skipTestingEmbeddedFrame) { testEmbeddedFrame(); } } catch (InvocationTargetException ex) { ex.printStackTrace(); fail(ex.getMessage()); } } /** * Used by standard test machinery. See usage at {@link OverlappingTestBase } */ protected static OverlappingTestBase instance; protected OverlappingTestBase() { getVerifyColor(); } /***************************************************** * Standard Test Machinery Section * DO NOT modify anything in this section -- it's a * standard chunk of code which has all of the * synchronisation necessary for the test harness. * By keeping it the same in all tests, it is easier * to read and understand someone else's test, as * well as insuring that all tests behave correctly * with the test harness. * There is a section following this for test- * classes ******************************************************/ private static void init() throws InterruptedException { //*** Create instructions for the user here *** //System.setProperty("sun.awt.disableMixing", "true"); String[] instructions = { "This is an AUTOMATIC test, simply wait until it is done.", "The result (passed or failed) will be shown in the", "message window below." }; Sysout.createDialog(); Sysout.printInstructions(instructions); instance.testAwtControls(); if (wasHWClicked) { fail("HW component received the click."); passed = false; } if (passed) { pass(); } }//End init() private static boolean theTestPassed = false; private static boolean testGeneratedInterrupt = false; private static String failureMessage = ""; private static Thread mainThread = null; private static int sleepTime = 300000; // Not sure about what happens if multiple of this test are // instantiated in the same VM. Being static (and using // static vars), it aint gonna work. Not worrying about // it for now. /** * Starting point for test runs. See usage at {@link OverlappingTestBase } * @param args regular main args, not used. * @throws InterruptedException */ public static void doMain(String args[]) throws InterruptedException { mainThread = Thread.currentThread(); try { init(); } catch (TestPassedException e) { //The test passed, so just return from main and harness will // interepret this return as a pass return; } //At this point, neither test pass nor test fail has been // called -- either would have thrown an exception and ended the // test, so we know we have multiple threads. //Test involves other threads, so sleep and wait for them to // called pass() or fail() try { Thread.sleep(sleepTime); //Timed out, so fail the test throw new RuntimeException("Timed out after " + sleepTime / 1000 + " seconds"); } catch (InterruptedException e) { //The test harness may have interrupted the test. If so, rethrow the exception // so that the harness gets it and deals with it. if (!testGeneratedInterrupt) { throw e; } //reset flag in case hit this code more than once for some reason (just safety) testGeneratedInterrupt = false; if (theTestPassed == false) { throw new RuntimeException(failureMessage); } } }//main /** * Test will fail if not passed after this timeout. Default timeout is 300 seconds. * @param seconds timeout in seconds */ public static synchronized void setTimeoutTo(int seconds) { sleepTime = seconds * 1000; } /** * Set test as passed. Usually shoudn't be called directly. */ public static synchronized void pass() { Sysout.println("The test passed."); Sysout.println("The test is over, hit Ctl-C to stop Java VM"); //first check if this is executing in main thread if (mainThread == Thread.currentThread()) { //Still in the main thread, so set the flag just for kicks, // and throw a test passed exception which will be caught // and end the test. theTestPassed = true; throw new TestPassedException(); } theTestPassed = true; testGeneratedInterrupt = true; mainThread.interrupt(); }//pass() /** * Fail test generic message. */ public static synchronized void fail() { //test writer didn't specify why test failed, so give generic fail("it just plain failed! :-)"); } /** * Fail test providing specific reason. * @param whyFailed reason */ public static synchronized void fail(String whyFailed) { Sysout.println("The test failed: " + whyFailed); Sysout.println("The test is over, hit Ctl-C to stop Java VM"); //check if this called from main thread if (mainThread == Thread.currentThread()) { //If main thread, fail now 'cause not sleeping throw new RuntimeException(whyFailed); } theTestPassed = false; testGeneratedInterrupt = true; failureMessage = whyFailed; mainThread.interrupt(); }//fail() }// class LWComboBox class TestPassedException extends RuntimeException { } //*********** End Standard Test Machinery Section ********** //************ Begin classes defined for the test **************** // if want to make listeners, here is the recommended place for them, then instantiate // them in init() /* Example of a class which may be written as part of a test class NewClass implements anInterface { static int newVar = 0; public void eventDispatched(AWTEvent e) { //Counting events to see if we get enough eventCount++; if( eventCount == 20 ) { //got enough events, so pass LWComboBox.pass(); } else if( tries == 20 ) { //tried too many times without getting enough events so fail LWComboBox.fail(); } }// eventDispatched() }// NewClass class */ //************** End classes defined for the test ******************* /**************************************************** Standard Test Machinery DO NOT modify anything below -- it's a standard chunk of code whose purpose is to make user interaction uniform, and thereby make it simpler to read and understand someone else's test. ****************************************************/ /** This is part of the standard test machinery. It creates a dialog (with the instructions), and is the interface for sending text messages to the user. To print the instructions, send an array of strings to Sysout.createDialog WithInstructions method. Put one line of instructions per array entry. To display a message for the tester to see, simply call Sysout.println with the string to be displayed. This mimics System.out.println but works within the test harness as well as standalone. */ class Sysout { private static TestDialog dialog; public static void createDialogWithInstructions(String[] instructions) { dialog = new TestDialog(new Frame(), "Instructions"); dialog.printInstructions(instructions); //dialog.setVisible(true); println("Any messages for the tester will display here."); } public static void createDialog() { dialog = new TestDialog(new Frame(), "Instructions"); String[] defInstr = {"Instructions will appear here. ", ""}; dialog.printInstructions(defInstr); //dialog.setVisible(true); println("Any messages for the tester will display here."); } public static void printInstructions(String[] instructions) { dialog.printInstructions(instructions); } public static void println(String messageIn) { dialog.displayMessage(messageIn); System.out.println(messageIn); } }// Sysout class /** This is part of the standard test machinery. It provides a place for the test instructions to be displayed, and a place for interactive messages to the user to be displayed. To have the test instructions displayed, see Sysout. To have a message to the user be displayed, see Sysout. Do not call anything in this dialog directly. */ class TestDialog extends Dialog { TextArea instructionsText; TextArea messageText; int maxStringLength = 80; //DO NOT call this directly, go through Sysout public TestDialog(Frame frame, String name) { super(frame, name); int scrollBoth = TextArea.SCROLLBARS_BOTH; instructionsText = new TextArea("", 15, maxStringLength, scrollBoth); add("North", instructionsText); messageText = new TextArea("", 5, maxStringLength, scrollBoth); add("Center", messageText); pack(); //setVisible(true); }// TestDialog() //DO NOT call this directly, go through Sysout public void printInstructions(String[] instructions) { //Clear out any current instructions instructionsText.setText(""); //Go down array of instruction strings String printStr, remainingStr; for (int i = 0; i < instructions.length; i++) { //chop up each into pieces maxSringLength long remainingStr = instructions[i]; while (remainingStr.length() > 0) { //if longer than max then chop off first max chars to print if (remainingStr.length() >= maxStringLength) { //Try to chop on a word boundary int posOfSpace = remainingStr.lastIndexOf(' ', maxStringLength - 1); if (posOfSpace <= 0) { posOfSpace = maxStringLength - 1; } printStr = remainingStr.substring(0, posOfSpace + 1); remainingStr = remainingStr.substring(posOfSpace + 1); } //else just print else { printStr = remainingStr; remainingStr = ""; } instructionsText.append(printStr + "\n"); }// while }// for }//printInstructions() //DO NOT call this directly, go through Sysout public void displayMessage(String messageIn) { messageText.append(messageIn + "\n"); System.out.println(messageIn); } }// TestDialog class
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest11568.java
2375
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details * * @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest11568") public class BenchmarkTest11568 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = ""; java.util.Enumeration<String> names = request.getParameterNames(); if (names.hasMoreElements()) { param = names.nextElement(); // just grab first element } String bar = new Test().doSomething(param); String sql = "SELECT * from USERS where USERNAME='foo' and PASSWORD='"+ bar +"'"; try { java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement(); java.sql.ResultSet rs = statement.executeQuery( sql ); } catch (java.sql.SQLException e) { throw new ServletException(e); } } // end doPost private class Test { public String doSomething(String param) throws ServletException, IOException { String bar = org.apache.commons.lang.StringEscapeUtils.escapeHtml(param); return bar; } } // end innerclass Test } // end DataflowThruInnerClass
gpl-2.0
gaoxiaojun/dync
test/compiler/intrinsics/mathexact/sanity/SubtractExactLongTest.java
2285
/* * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @library /testlibrary /test/lib /compiler/whitebox / /compiler/testlibrary * @modules java.base/sun.misc * java.management * @build SubtractExactLongTest * @run main ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions * -XX:+IgnoreUnrecognizedVMOptions -XX:+WhiteBoxAPI -XX:+LogCompilation * -XX:CompileCommand=compileonly,MathIntrinsic*::execMathMethod * -XX:LogFile=hs_neg.log -XX:-UseMathExactIntrinsics SubtractExactLongTest * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions * -XX:+IgnoreUnrecognizedVMOptions -XX:+WhiteBoxAPI -XX:+LogCompilation * -XX:CompileCommand=compileonly,MathIntrinsic*::execMathMethod * -XX:LogFile=hs.log -XX:+UseMathExactIntrinsics SubtractExactLongTest * @run main intrinsics.Verifier hs_neg.log hs.log */ public class SubtractExactLongTest { public static void main(String[] args) throws Exception { new IntrinsicBase.LongTest(MathIntrinsic.LongIntrinsic.Subtract).test(); } }
gpl-2.0
chenjunqian/here
Marker-Global-version/Here/app/src/main/java/com/eason/marker/emchat/chatuidemo/activity/ChatRoomActivity.java
4652
/** * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.eason.marker.emchat.chatuidemo.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ListView; import com.easemob.chat.EMChatManager; import com.easemob.chat.EMChatRoom; import com.eason.marker.emchat.chatuidemo.adapter.ChatRoomAdapter; import com.eason.marker.R; import java.util.List; public class ChatRoomActivity extends BaseActivity { private ListView chatListView; protected List<EMChatRoom> roomList; private ChatRoomAdapter chatRoomAdapter; private InputMethodManager inputMethodManager; public static ChatRoomActivity instance; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_chatroom); instance = this; inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); roomList = EMChatManager.getInstance().getAllChatRooms(); chatListView = (ListView) findViewById(R.id.list); chatRoomAdapter = new ChatRoomAdapter(this, 1, roomList); chatListView.setAdapter(chatRoomAdapter); chatListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(position == 1) { // 添加公开群 startActivityForResult(new Intent(ChatRoomActivity.this, PublicChatRoomsActivity.class), 0); } else { // 进入群聊 Intent intent = new Intent(ChatRoomActivity.this, ChatActivity.class); // it is group chat intent.putExtra("chatType", ChatActivity.CHATTYPE_CHATROOM); intent.putExtra("groupId", chatRoomAdapter.getItem(position - 2).getId()); startActivityForResult(intent, 0); } } }); // TODO: we need more official UI, but for now, for test purpose chatListView.setOnItemLongClickListener(new OnItemLongClickListener(){ @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if(position > 1){ final String roomId = chatRoomAdapter.getItem(position - 2).getId(); new Thread(){ @Override public void run(){ EMChatManager.getInstance().leaveChatRoom(roomId); } }.start(); return true; } return false; } }); chatListView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) { if (getCurrentFocus() != null) inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } return false; } }); } /** * 进入公开群聊列表 */ public void onPublicGroups(View view) { } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); } @Override public void onResume() { super.onResume(); roomList = EMChatManager.getInstance().getAllChatRooms(); chatRoomAdapter = new ChatRoomAdapter(this, 1, roomList); chatListView.setAdapter(chatRoomAdapter); chatRoomAdapter.notifyDataSetChanged(); } @Override protected void onDestroy() { super.onDestroy(); instance = null; } /** * 返回 * * @param view */ public void back(View view) { finish(); } }
gpl-2.0
savermyas/JTHarnessSimpleTest
testsuite/target/tests/com/github/mesimpletest/testsuite/MyJavaTest.java
211
package com.github.mesimpletest.testsuite; import com.sun.javatest.tool.Main; public class MyJavaTest extends com.sun.javatest.tool.Main { public static void main(String[] args) { Main.main(args); } }
gpl-2.0
skyHALud/codenameone
Ports/iOSPort/xmlvm/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/GKSendDataMode.java
1076
/* Copyright (c) 2002-2011 by XMLVM.org * * Project Info: http://www.xmlvm.org * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ package org.xmlvm.iphone; import org.xmlvm.XMLVMSkeletonOnly; @XMLVMSkeletonOnly public class GKSendDataMode { public static final int Reliable = 0; public static final int Unreliable = 1; private GKSendDataMode() { } }
gpl-2.0
rkhatib/topotext
src/main/java/lb/edu/aub/cmps/WelcomeFrame.java
2203
package lb.edu.aub.cmps; import java.awt.EventQueue; import javax.swing.JFrame; import java.awt.Color; import javax.swing.JLabel; import java.awt.Font; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class WelcomeFrame { private JFrame frmWelcome; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { WelcomeFrame window = new WelcomeFrame(); window.frmWelcome.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public WelcomeFrame() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frmWelcome = new JFrame(); frmWelcome.setFont(new Font("Adobe Caslon Pro", Font.PLAIN, 20)); frmWelcome.setTitle("Welcome!"); frmWelcome.getContentPane().setBackground(new Color(176, 224, 230)); frmWelcome.getContentPane().setLayout(null); JLabel lblWelcomeToThe = new JLabel("Welcome to the Topotext Digital Tool"); lblWelcomeToThe.setForeground(new Color(51, 51, 102)); lblWelcomeToThe.setFont(new Font("Adobe Caslon Pro Bold", Font.BOLD, 40)); lblWelcomeToThe.setBounds(219, 176, 855, 83); frmWelcome.getContentPane().add(lblWelcomeToThe); JButton btnStartUp = new JButton("Start Up"); btnStartUp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { frmWelcome.setVisible(false); EventQueue.invokeLater(new Runnable() { public void run() { try { Frame frame = new Frame(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } }); btnStartUp.setForeground(new Color(51, 51, 102)); btnStartUp.setFont(new Font("Franklin Gothic Medium Cond", Font.PLAIN, 18)); btnStartUp.setBounds(517, 299, 150, 35); frmWelcome.getContentPane().add(btnStartUp); frmWelcome.setBounds(100, 100, 1200, 475); frmWelcome.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
gpl-2.0
sebastic/GpsPrune
tim/prune/threedee/TerrainCache.java
1845
package tim.prune.threedee; import tim.prune.DataStatus; import tim.prune.data.Track; /** * This abstract class acts as a singleton to store a single * terrain model (as a Track) for a given data status and terrain definition. * When the data or the definition changes, this track becomes invalid. */ public abstract class TerrainCache { /** The data status at the time this terrain was generated */ private static DataStatus _dataStatus = null; /** The definition (grid size) for this terrain */ private static TerrainDefinition _terrainDef = null; /** The generated grid of points with altitudes */ private static Track _terrainTrack = null; /** * Get the stored terrain track if it's still valid * @param inCurrStatus current data status * @param inTerrainDef currently selected terrain definition * @return stored terrain track if it's valid, null otherwise */ public static Track getTerrainTrack(DataStatus inCurrStatus, TerrainDefinition inTerrainDef) { if (_dataStatus == null || _terrainDef == null || _terrainTrack == null) { return null; // nothing stored } if (inCurrStatus == null || inTerrainDef == null || !inTerrainDef.getUseTerrain()) { return null; // nonsense requested } if (inCurrStatus.hasDataChanged(_dataStatus) || !inTerrainDef.equals(_terrainDef)) { return null; // stored track is out of date } // we have a match return _terrainTrack; } /** * Now that a terrain track has been generated, store it for possible reuse * @param inTrack terrain track to store * @param inCurrStatus current data status * @param inTerrainDef terrain definition */ public static void storeTerrainTrack(Track inTrack, DataStatus inCurrStatus, TerrainDefinition inTerrainDef) { _terrainTrack = inTrack; _dataStatus = inCurrStatus; _terrainDef = inTerrainDef; } }
gpl-2.0
ArturVasilov/AndroidNPPCourse
CodeSamples, Part 2, Client-server applications/ClientServerBasicSample/servermodule/src/main/java/ru/guar7387/servermodule/tasksfactory/LoadAllArticlesTask.java
1892
package ru.guar7387.servermodule.tasksfactory; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Map; import ru.guar7387.servermodule.callbacks.Callback; import ru.guar7387.servermodule.Logger; import ru.guar7387.servermodule.api.ConnectionManager; import ru.guar7387.servermodule.api.ConnectionRequest; import ru.guar7387.servermodule.data.Article; public class LoadAllArticlesTask extends AbstractTask { private static final String TAG = LoadAllArticlesTask.class.getSimpleName(); private final Map<Integer, Article> mArticles; public LoadAllArticlesTask(int requestCode, ConnectionRequest request, ConnectionManager connectionManager, Callback callback, Map<Integer, Article> articles) { super(requestCode, request, connectionManager, callback); this.mArticles = articles; } @Override public void parseJson(JSONObject answer) { Logger.log(TAG, "answer - " + answer); try { JSONArray articles = answer.getJSONObject("response").getJSONArray("answer"); for (int i = 0; i < articles.length(); i++) { try { JSONArray array = articles.getJSONArray(i); int id = array.getInt(0); String title = array.getString(1); String description = array.getString(2); String url = array.getString(3); String date = array.getString(4); //noinspection ObjectAllocationInLoop Article article = new Article(id, title, description, url, date); mArticles.put(id, article); } catch (JSONException ignored) { } } } catch (JSONException ignored) { } } }
gpl-2.0
rac021/blazegraph_1_5_3_cluster_2_nodes
bigdata/src/java/com/bigdata/counters/ActiveProcess.java
6145
/* Copyright (C) SYSTAP, LLC 2006-2015. All rights reserved. Contact: SYSTAP, LLC 2501 Calvert ST NW #106 Washington, DC 20008 licenses@systap.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * Created on Mar 26, 2008 */ package com.bigdata.counters; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.log4j.Logger; import com.bigdata.util.concurrent.DaemonThreadFactory; /** * Command manages the execution and termination of a native process and an * object reading the output of that process. * * @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a> * @version $Id$ */ public class ActiveProcess { static protected final Logger log = Logger.getLogger(ActiveProcess.class); /** * Used to read {@link #is} and aggregate the performance data reported * by the {@link #process}. */ protected final ExecutorService readService = Executors .newSingleThreadExecutor(new DaemonThreadFactory(getClass() .getName() + ".readService")); protected Process process = null; protected InputStream is = null; protected volatile Future readerFuture; /** * * @param command * The command to be executed. See * {@link ProcessBuilder#command(List)}. * @param collector */ public ActiveProcess(List<String> command, AbstractProcessCollector collector) { if (command == null) throw new IllegalArgumentException(); if (command.isEmpty()) throw new IllegalArgumentException(); if (collector == null) throw new IllegalArgumentException(); // log the command that will be run. { StringBuilder sb = new StringBuilder(); for (String s : command) { sb.append( s +" "); } if (log.isInfoEnabled()) log.info("command:\n" + sb); } try { ProcessBuilder tmp = new ProcessBuilder(command); collector.setEnvironment(tmp.environment()); process = tmp.start(); } catch (IOException e) { throw new RuntimeException(e); } /* * Note: Process is running but the reader on the process output has * not been started yet! */ } /** * Attaches the reader to the process, which was started by the ctor and * is already running. * * @param processReader * The reader. */ public void start(AbstractProcessReader processReader) { log.info(""); if (processReader == null) throw new IllegalArgumentException(); if (readerFuture != null) throw new IllegalStateException(); is = process.getInputStream(); assert is != null; /* * @todo restart processes if it dies before we shut it down, but no * more than some #of tries. if the process dies then we will not have * any data for this host. * * @todo this code for monitoring processes is a mess and should * probably be re-written from scratch. the processReader task * references the readerFuture via isAlive() but the readerFuture is not * even assigned until after we submit the processReader task, which * means that it can be running before the readerFuture is set! The * concrete implementations of ProcessReaderHelper all poll isAlive() * until the readerFuture becomes available. */ if (log.isInfoEnabled()) log.info("starting process reader: " + processReader); processReader.start(is); if (log.isInfoEnabled()) log.info("submitting process reader task: "+processReader); readerFuture = readService.submit(processReader); if (log.isInfoEnabled()) log.info("readerFuture: done="+readerFuture.isDone()); } /** * Stops the process */ public void stop() { if (readerFuture == null) { // not running. return; } // attempt to cancel the reader. readerFuture.cancel(true/* mayInterruptIfRunning */); // shutdown the thread running the reader. readService.shutdownNow(); if (process != null) { // destroy the running process. process.destroy(); process = null; is = null; } readerFuture = null; } /** * Return <code>true</code> unless the process is known to be dead. */ public boolean isAlive() { if(readerFuture==null || readerFuture.isDone() || process == null || is == null) { if (log.isInfoEnabled()) log.info("Not alive: readerFuture=" + readerFuture + (readerFuture != null ? "done=" + readerFuture.isDone() : "") + ", process=" + process + ", is=" + is); return false; } return true; } }
gpl-2.0
teamfx/openjfx-10-dev-rt
tests/system/src/test/java/test/com/sun/javafx/application/SwingExitCommon.java
6351
/* * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package test.com.sun.javafx.application; import com.sun.javafx.application.PlatformImplShim; import java.awt.BorderLayout; import javax.swing.SwingUtilities; import java.awt.Dimension; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javafx.application.Platform; import javafx.embed.swing.JFXPanel; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javax.swing.JFrame; import junit.framework.AssertionFailedError; import test.util.Util; import static org.junit.Assert.*; import static test.util.Util.TIMEOUT; /** * Test program for Platform implicit exit behavior using an embedded JFXPanel. * Each of the tests must be run in a separate JVM which is why each * is in its own subclass. */ public class SwingExitCommon { // Sleep time showing/hiding window in milliseconds private static final int SLEEP_TIME = 1000; // Used to launch the application before running any test private static final CountDownLatch initialized = new CountDownLatch(1); // Value of the implicit exit flag for the given test private static volatile boolean implicitExit; private JFrame frame; private JFXPanel fxPanel; public void init() { assertTrue(SwingUtilities.isEventDispatchThread()); assertEquals(1, initialized.getCount()); assertTrue(Platform.isImplicitExit()); if (!implicitExit) { Platform.setImplicitExit(false); assertFalse(Platform.isImplicitExit()); } frame = new JFrame("JFXPanel 1"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setLayout(new BorderLayout()); // Create javafx panel fxPanel = new JFXPanel(); fxPanel.setPreferredSize(new Dimension(210, 180)); frame.getContentPane().add(fxPanel, BorderLayout.CENTER); // Create scene and add it to the panel Util.runAndWait(() -> { Group root = new Group(); Scene scene = new Scene(root); scene.setFill(Color.LIGHTYELLOW); fxPanel.setScene(scene); }); // show frame frame.setLocationRelativeTo(null); frame.pack(); frame.setVisible(true); initialized.countDown(); assertEquals(0, initialized.getCount()); } private void doTestCommon(boolean implicitExit, boolean reEnableImplicitExit, boolean appShouldExit) { SwingExitCommon.implicitExit = implicitExit; final Throwable[] testError = new Throwable[1]; final Thread testThread = Thread.currentThread(); // Start the Application SwingUtilities.invokeLater(() -> { try { init(); } catch (Throwable th) { testError[0] = th; testThread.interrupt(); } }); try { if (!initialized.await(TIMEOUT, TimeUnit.MILLISECONDS)) { throw new AssertionFailedError("Timeout waiting for JFXPanel to launch and initialize"); } Thread.sleep(SLEEP_TIME); try { SwingUtilities.invokeAndWait(() -> { frame.setVisible(false); frame.dispose(); }); } catch (InvocationTargetException ex) { AssertionFailedError err = new AssertionFailedError("Exception while disposing JFrame"); err.initCause(ex.getCause()); throw err; } final CountDownLatch exitLatch = PlatformImplShim.test_getPlatformExitLatch(); if (reEnableImplicitExit) { Thread.sleep(SLEEP_TIME); assertEquals(1, exitLatch.getCount()); assertFalse(Platform.isImplicitExit()); Platform.setImplicitExit(true); assertTrue(Platform.isImplicitExit()); } if (!appShouldExit) { Thread.sleep(SLEEP_TIME); assertEquals(1, exitLatch.getCount()); Platform.exit(); } if (!exitLatch.await(TIMEOUT, TimeUnit.MILLISECONDS)) { throw new AssertionFailedError("Timeout waiting for Platform to exit"); } } catch (InterruptedException ex) { Util.throwError(testError[0]); } } // ========================== TEST CASES ========================== // Implementation of SingleImplicitTest.testImplicitExit public void doTestImplicitExit() { // implicitExit, no re-enable, should exit doTestCommon(true, false, true); } // Implementation of testExplicitExit public void doTestExplicitExit() { // no implicitExit, no re-enable, should not exit doTestCommon(false, false, false); } // Implementation of testExplicitExitReEnable public void doTestExplicitExitReEnable() { // no implicitExit, re-enable, should exit doTestCommon(false, true, true); } }
gpl-2.0
jbachorik/btrace
btrace-instr/src/test/btrace/onmethod/InstanceofBefore.java
2066
/* * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the Classpath exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package traces.onmethod; import static org.openjdk.btrace.core.BTraceUtils.*; import org.openjdk.btrace.core.annotations.BTrace; import org.openjdk.btrace.core.annotations.Kind; import org.openjdk.btrace.core.annotations.Location; import org.openjdk.btrace.core.annotations.OnMethod; import org.openjdk.btrace.core.annotations.ProbeClassName; import org.openjdk.btrace.core.annotations.Self; import org.openjdk.btrace.core.annotations.TargetInstance; import org.openjdk.btrace.core.types.AnyType; /** @author Jaroslav Bachorik */ @BTrace public class InstanceofBefore { @OnMethod( clazz = "/.*\\.OnMethodTest/", method = "casts", location = @Location(value = Kind.INSTANCEOF)) public static void args( @Self Object self, @ProbeClassName String pcn, String type, @TargetInstance AnyType target) { println("args"); } }
gpl-2.0
petterreinholdtsen/cinelerra-hv
thirdparty/OpenCV-2.3.1/modules/java/android_test/src/org/opencv/test/features2d/PyramidSTARFeatureDetectorTest.java
876
package org.opencv.test.features2d; import junit.framework.TestCase; public class PyramidSTARFeatureDetectorTest extends TestCase { public void testCreate() { fail("Not yet implemented"); } public void testDetectListOfMatListOfListOfKeyPoint() { fail("Not yet implemented"); } public void testDetectListOfMatListOfListOfKeyPointListOfMat() { fail("Not yet implemented"); } public void testDetectMatListOfKeyPoint() { fail("Not yet implemented"); } public void testDetectMatListOfKeyPointMat() { fail("Not yet implemented"); } public void testEmpty() { fail("Not yet implemented"); } public void testRead() { fail("Not yet implemented"); } public void testWrite() { fail("Not yet implemented"); } }
gpl-2.0
EHJ-52n/SOS
spring/common-controller/src/main/java/org/n52/sos/web/common/auth/AuthenticationFailureListener.java
1801
/* * Copyright (C) 2012-2021 52°North Spatial Information Research GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public * License version 2 and the aforementioned licenses. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. */ package org.n52.sos.web.common.auth; import org.springframework.context.ApplicationListener; import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent; public class AuthenticationFailureListener extends AbstractAuthenticationEventListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> { public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) { getService().loginFailed(getRemoteAddress(event)); } }
gpl-2.0
formeppe/NewAge-JGrass
grass/src/main/java/org/osgeo/grass/r/r__in__poly.java
1602
package org.osgeo.grass.r; import org.jgrasstools.grass.utils.ModuleSupporter; import oms3.annotations.Author; import oms3.annotations.Documentation; import oms3.annotations.Label; import oms3.annotations.Description; import oms3.annotations.Execute; import oms3.annotations.In; import oms3.annotations.UI; import oms3.annotations.Keywords; import oms3.annotations.License; import oms3.annotations.Name; import oms3.annotations.Out; import oms3.annotations.Status; @Description("Creates raster maps from ASCII polygon/line/point data files.") @Author(name = "Grass Developers Community", contact = "http://grass.osgeo.org") @Keywords("raster, import") @Label("Grass/Raster Modules") @Name("r__in__poly") @Status(Status.CERTIFIED) @License("General Public License Version >=2)") public class r__in__poly { @Description("Name of input file; or \"-\" to read from stdin") @In public String $$inputPARAMETER; @UI("outfile,grassfile") @Description("Name for output raster map") @In public String $$outputPARAMETER; @Description("Title for resultant raster map (optional)") @In public String $$titlePARAMETER; @Description("Number of rows to hold in memory (optional)") @In public String $$rowsPARAMETER = "4096"; @Description("Allow output files to overwrite existing files") @In public boolean $$overwriteFLAG = false; @Description("Verbose module output") @In public boolean $$verboseFLAG = false; @Description("Quiet module output") @In public boolean $$quietFLAG = false; @Execute public void process() throws Exception { ModuleSupporter.processModule(this); } }
gpl-2.0
jreadstone/zsyproject
src/org/g4studio/system/admin/web/UserAction.java
7374
package org.g4studio.system.admin.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.g4studio.core.json.JsonHelper; import org.g4studio.core.metatype.Dto; import org.g4studio.core.metatype.impl.BaseDto; import org.g4studio.core.mvc.xstruts.action.ActionForm; import org.g4studio.core.mvc.xstruts.action.ActionForward; import org.g4studio.core.mvc.xstruts.action.ActionMapping; import org.g4studio.core.util.G4Utils; import org.g4studio.core.web.BizAction; import org.g4studio.core.web.CommonActionForm; import org.g4studio.core.web.util.WebUtils; import org.g4studio.system.admin.service.OrganizationService; import org.g4studio.system.admin.service.UserService; import org.g4studio.system.common.dao.vo.UserInfoVo; import org.g4studio.system.common.util.SystemConstants; /** * 用户管理与授权 * * @author XiongChun * @since 2010-04-21 * @see BizAction */ public class UserAction extends BizAction { private UserService userService = (UserService) super.getService("userService"); private OrganizationService organizationService = (OrganizationService) super.getService("organizationService"); /** * 用户管理与授权页面初始化 * * @param * @return */ public ActionForward userInit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { super.removeSessionAttribute(request, "deptid"); Dto inDto = new BaseDto(); String deptid = super.getSessionContainer(request).getUserInfo().getDeptid(); inDto.put("deptid", deptid); Dto outDto = organizationService.queryDeptinfoByDeptid(inDto); request.setAttribute("rootDeptid", outDto.getAsString("deptid")); request.setAttribute("rootDeptname", outDto.getAsString("deptname")); UserInfoVo userInfoVo = getSessionContainer(request).getUserInfo(); request.setAttribute("login_account", userInfoVo.getAccount()); return mapping.findForward("manageUserView"); } /** * 部门管理树初始化 * * @param * @return */ public ActionForward departmentTreeInit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Dto dto = new BaseDto(); String nodeid = request.getParameter("node"); dto.put("parentid", nodeid); Dto outDto = organizationService.queryDeptItems(dto); write(outDto.getAsString("jsonString"), response); return mapping.findForward(null); } /** * 查询用户列表 * * @param * @return */ public ActionForward queryUsersForManage(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CommonActionForm aForm = (CommonActionForm)form; Dto dto = aForm.getParamAsDto(request); String deptid = request.getParameter("deptid"); if (G4Utils.isNotEmpty(deptid)) { setSessionAttribute(request, "deptid", deptid); } if (!G4Utils.isEmpty(request.getParameter("firstload"))) { dto.put("deptid", super.getSessionContainer(request).getUserInfo().getDeptid()); } else { dto.put("deptid", super.getSessionAttribute(request, "deptid")); } dto.put("usertype", SystemConstants.USERTYPE_ADMIN); UserInfoVo userInfoVo = getSessionContainer(request).getUserInfo(); if (WebUtils.getParamValue("DEFAULT_ADMIN_ACCOUNT", request).equals(userInfoVo.getAccount())) { dto.remove("usertype"); } if (WebUtils.getParamValue("DEFAULT_DEVELOP_ACCOUNT", request).equals(userInfoVo.getAccount())) { dto.remove("usertype"); } List userList = g4Reader.queryForPage("User.queryUsersForManage", dto); Integer pageCount = (Integer) g4Reader.queryForObject("User.queryUsersForManageForPageCount", dto); String jsonString = JsonHelper.encodeList2PageJson(userList, pageCount, null); write(jsonString, response); return mapping.findForward(null); } /** * 保存用户 * * @param * @return */ public ActionForward saveUserItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CommonActionForm aForm = (CommonActionForm) form; Dto inDto = aForm.getParamAsDto(request); Dto outDto = userService.saveUserItem(inDto); String jsonString = JsonHelper.encodeObject2Json(outDto); write(jsonString, response); return mapping.findForward(null); } /** * 删除用户 * * @param * @return */ public ActionForward deleteUserItems(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String strChecked = request.getParameter("strChecked"); Dto inDto = new BaseDto(); inDto.put("strChecked", strChecked); userService.deleteUserItems(inDto); setOkTipMsg("用户数据删除成功", response); return mapping.findForward(null); } /** * 修改用户 * * @param * @return */ public ActionForward updateUserItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CommonActionForm aForm = (CommonActionForm) form; Dto inDto = aForm.getParamAsDto(request); userService.updateUserItem(inDto); setOkTipMsg("用户数据修改成功", response); return mapping.findForward(null); } /** * 用户授权页面初始化:选择角色 * * @param * @return */ public ActionForward userGrantInit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { super.removeSessionAttribute(request, "USERID_USERACTION"); String userid = request.getParameter("userid"); super.setSessionAttribute(request, "USERID_USERACTION", userid); return mapping.findForward("selectRoleTreeView"); } /** * 用户授权页面初始化:选择菜单 * * @param * @return */ public ActionForward selectMenuInit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.findForward("selectMenuTreeView"); } /** * 保存用户角色关联信息 * * @param * @return */ public ActionForward saveSelectedRole(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Dto inDto = new BaseDto(); inDto.put("roleid", request.getParameter("roleid")); inDto.put("userid", super.getSessionAttribute(request, "USERID_USERACTION")); userService.saveSelectedRole(inDto); setOkTipMsg("您选择的人员角色关联数据保存成功", response); return mapping.findForward(null); } /** * 保存用户菜单关联信息 * * @param * @return */ public ActionForward saveSelectedMenu(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Dto inDto = new BaseDto(); inDto.put("menuid", request.getParameter("menuid")); inDto.put("userid", super.getSessionAttribute(request, "USERID_USERACTION")); userService.saveSelectedMenu(inDto); setOkTipMsg("您选择的人员菜单关联数据保存成功", response); return mapping.findForward(null); } }
gpl-2.0
SpoonLabs/astor
examples/math_57/src/test/java/org/apache/commons/math/dfp/DfpTest.java
61516
/* * 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.commons.math.dfp; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class DfpTest { private DfpField field; private Dfp pinf; private Dfp ninf; private Dfp nan; private Dfp snan; private Dfp qnan; @Before public void setUp() { // Some basic setup. Define some constants and clear the status flags field = new DfpField(20); pinf = field.newDfp("1").divide(field.newDfp("0")); ninf = field.newDfp("-1").divide(field.newDfp("0")); nan = field.newDfp("0").divide(field.newDfp("0")); snan = field.newDfp((byte)1, Dfp.SNAN); qnan = field.newDfp((byte)1, Dfp.QNAN); ninf.getField().clearIEEEFlags(); } @After public void tearDown() { field = null; pinf = null; ninf = null; nan = null; snan = null; qnan = null; } // Generic test function. Takes params x and y and tests them for // equality. Then checks the status flags against the flags argument. // If the test fail, it prints the desc string private void test(Dfp x, Dfp y, int flags, String desc) { boolean b = x.equals(y); if (!x.equals(y) && !x.unequal(y)) // NaNs involved b = (x.toString().equals(y.toString())); if (x.equals(field.newDfp("0"))) // distinguish +/- zero b = (b && (x.toString().equals(y.toString()))); b = (b && x.getField().getIEEEFlags() == flags); if (!b) Assert.assertTrue("assersion failed "+desc+" x = "+x.toString()+" flags = "+x.getField().getIEEEFlags(), b); x.getField().clearIEEEFlags(); } @Test public void testByteConstructor() { Assert.assertEquals("0.", new Dfp(field, (byte) 0).toString()); Assert.assertEquals("1.", new Dfp(field, (byte) 1).toString()); Assert.assertEquals("-1.", new Dfp(field, (byte) -1).toString()); Assert.assertEquals("-128.", new Dfp(field, Byte.MIN_VALUE).toString()); Assert.assertEquals("127.", new Dfp(field, Byte.MAX_VALUE).toString()); } @Test public void testIntConstructor() { Assert.assertEquals("0.", new Dfp(field, 0).toString()); Assert.assertEquals("1.", new Dfp(field, 1).toString()); Assert.assertEquals("-1.", new Dfp(field, -1).toString()); Assert.assertEquals("1234567890.", new Dfp(field, 1234567890).toString()); Assert.assertEquals("-1234567890.", new Dfp(field, -1234567890).toString()); Assert.assertEquals("-2147483648.", new Dfp(field, Integer.MIN_VALUE).toString()); Assert.assertEquals("2147483647.", new Dfp(field, Integer.MAX_VALUE).toString()); } @Test public void testLongConstructor() { Assert.assertEquals("0.", new Dfp(field, 0l).toString()); Assert.assertEquals("1.", new Dfp(field, 1l).toString()); Assert.assertEquals("-1.", new Dfp(field, -1l).toString()); Assert.assertEquals("1234567890.", new Dfp(field, 1234567890l).toString()); Assert.assertEquals("-1234567890.", new Dfp(field, -1234567890l).toString()); Assert.assertEquals("-9223372036854775808.", new Dfp(field, Long.MIN_VALUE).toString()); Assert.assertEquals("9223372036854775807.", new Dfp(field, Long.MAX_VALUE).toString()); } /* * Test addition */ @Test public void testAdd() { test(field.newDfp("1").add(field.newDfp("1")), // Basic tests 1+1 = 2 field.newDfp("2"), 0, "Add #1"); test(field.newDfp("1").add(field.newDfp("-1")), // 1 + (-1) = 0 field.newDfp("0"), 0, "Add #2"); test(field.newDfp("-1").add(field.newDfp("1")), // (-1) + 1 = 0 field.newDfp("0"), 0, "Add #3"); test(field.newDfp("-1").add(field.newDfp("-1")), // (-1) + (-1) = -2 field.newDfp("-2"), 0, "Add #4"); // rounding mode is round half even test(field.newDfp("1").add(field.newDfp("1e-16")), // rounding on add field.newDfp("1.0000000000000001"), 0, "Add #5"); test(field.newDfp("1").add(field.newDfp("1e-17")), // rounding on add field.newDfp("1"), DfpField.FLAG_INEXACT, "Add #6"); test(field.newDfp("0.90999999999999999999").add(field.newDfp("0.1")), // rounding on add field.newDfp("1.01"), DfpField.FLAG_INEXACT, "Add #7"); test(field.newDfp(".10000000000000005000").add(field.newDfp(".9")), // rounding on add field.newDfp("1."), DfpField.FLAG_INEXACT, "Add #8"); test(field.newDfp(".10000000000000015000").add(field.newDfp(".9")), // rounding on add field.newDfp("1.0000000000000002"), DfpField.FLAG_INEXACT, "Add #9"); test(field.newDfp(".10000000000000014999").add(field.newDfp(".9")), // rounding on add field.newDfp("1.0000000000000001"), DfpField.FLAG_INEXACT, "Add #10"); test(field.newDfp(".10000000000000015001").add(field.newDfp(".9")), // rounding on add field.newDfp("1.0000000000000002"), DfpField.FLAG_INEXACT, "Add #11"); test(field.newDfp(".11111111111111111111").add(field.newDfp("11.1111111111111111")), // rounding on add field.newDfp("11.22222222222222222222"), DfpField.FLAG_INEXACT, "Add #12"); test(field.newDfp(".11111111111111111111").add(field.newDfp("1111111111111111.1111")), // rounding on add field.newDfp("1111111111111111.2222"), DfpField.FLAG_INEXACT, "Add #13"); test(field.newDfp(".11111111111111111111").add(field.newDfp("11111111111111111111")), // rounding on add field.newDfp("11111111111111111111"), DfpField.FLAG_INEXACT, "Add #14"); test(field.newDfp("9.9999999999999999999e131071").add(field.newDfp("-1e131052")), // overflow on add field.newDfp("9.9999999999999999998e131071"), 0, "Add #15"); test(field.newDfp("9.9999999999999999999e131071").add(field.newDfp("1e131052")), // overflow on add pinf, DfpField.FLAG_OVERFLOW, "Add #16"); test(field.newDfp("-9.9999999999999999999e131071").add(field.newDfp("-1e131052")), // overflow on add ninf, DfpField.FLAG_OVERFLOW, "Add #17"); test(field.newDfp("-9.9999999999999999999e131071").add(field.newDfp("1e131052")), // overflow on add field.newDfp("-9.9999999999999999998e131071"), 0, "Add #18"); test(field.newDfp("1e-131072").add(field.newDfp("1e-131072")), // underflow on add field.newDfp("2e-131072"), 0, "Add #19"); test(field.newDfp("1.0000000000000001e-131057").add(field.newDfp("-1e-131057")), // underflow on add field.newDfp("1e-131073"), DfpField.FLAG_UNDERFLOW, "Add #20"); test(field.newDfp("1.1e-131072").add(field.newDfp("-1e-131072")), // underflow on add field.newDfp("1e-131073"), DfpField.FLAG_UNDERFLOW, "Add #21"); test(field.newDfp("1.0000000000000001e-131072").add(field.newDfp("-1e-131072")), // underflow on add field.newDfp("1e-131088"), DfpField.FLAG_UNDERFLOW, "Add #22"); test(field.newDfp("1.0000000000000001e-131078").add(field.newDfp("-1e-131078")), // underflow on add field.newDfp("0"), DfpField.FLAG_UNDERFLOW, "Add #23"); test(field.newDfp("1.0").add(field.newDfp("-1e-20")), // loss of precision on alignment? field.newDfp("0.99999999999999999999"), 0, "Add #23.1"); test(field.newDfp("-0.99999999999999999999").add(field.newDfp("1")), // proper normalization? field.newDfp("0.00000000000000000001"), 0, "Add #23.2"); test(field.newDfp("1").add(field.newDfp("0")), // adding zeros field.newDfp("1"), 0, "Add #24"); test(field.newDfp("0").add(field.newDfp("0")), // adding zeros field.newDfp("0"), 0, "Add #25"); test(field.newDfp("-0").add(field.newDfp("0")), // adding zeros field.newDfp("0"), 0, "Add #26"); test(field.newDfp("0").add(field.newDfp("-0")), // adding zeros field.newDfp("0"), 0, "Add #27"); test(field.newDfp("-0").add(field.newDfp("-0")), // adding zeros field.newDfp("-0"), 0, "Add #28"); test(field.newDfp("1e-20").add(field.newDfp("0")), // adding zeros field.newDfp("1e-20"), 0, "Add #29"); test(field.newDfp("1e-40").add(field.newDfp("0")), // adding zeros field.newDfp("1e-40"), 0, "Add #30"); test(pinf.add(ninf), // adding infinities nan, DfpField.FLAG_INVALID, "Add #31"); test(ninf.add(pinf), // adding infinities nan, DfpField.FLAG_INVALID, "Add #32"); test(ninf.add(ninf), // adding infinities ninf, 0, "Add #33"); test(pinf.add(pinf), // adding infinities pinf, 0, "Add #34"); test(pinf.add(field.newDfp("0")), // adding infinities pinf, 0, "Add #35"); test(pinf.add(field.newDfp("-1e131071")), // adding infinities pinf, 0, "Add #36"); test(pinf.add(field.newDfp("1e131071")), // adding infinities pinf, 0, "Add #37"); test(field.newDfp("0").add(pinf), // adding infinities pinf, 0, "Add #38"); test(field.newDfp("-1e131071").add(pinf), // adding infinities pinf, 0, "Add #39"); test(field.newDfp("1e131071").add(pinf), // adding infinities pinf, 0, "Add #40"); test(ninf.add(field.newDfp("0")), // adding infinities ninf, 0, "Add #41"); test(ninf.add(field.newDfp("-1e131071")), // adding infinities ninf, 0, "Add #42"); test(ninf.add(field.newDfp("1e131071")), // adding infinities ninf, 0, "Add #43"); test(field.newDfp("0").add(ninf), // adding infinities ninf, 0, "Add #44"); test(field.newDfp("-1e131071").add(ninf), // adding infinities ninf, 0, "Add #45"); test(field.newDfp("1e131071").add(ninf), // adding infinities ninf, 0, "Add #46"); test(field.newDfp("9.9999999999999999999e131071").add(field.newDfp("5e131051")), // overflow pinf, DfpField.FLAG_OVERFLOW, "Add #47"); test(field.newDfp("9.9999999999999999999e131071").add(field.newDfp("4.9999999999999999999e131051")), // overflow field.newDfp("9.9999999999999999999e131071"), DfpField.FLAG_INEXACT, "Add #48"); test(nan.add(field.newDfp("1")), nan, 0, "Add #49"); test(field.newDfp("1").add(nan), nan, 0, "Add #50"); test(field.newDfp("12345678123456781234").add(field.newDfp("0.12345678123456781234")), field.newDfp("12345678123456781234"), DfpField.FLAG_INEXACT, "Add #51"); test(field.newDfp("12345678123456781234").add(field.newDfp("123.45678123456781234")), field.newDfp("12345678123456781357"), DfpField.FLAG_INEXACT, "Add #52"); test(field.newDfp("123.45678123456781234").add(field.newDfp("12345678123456781234")), field.newDfp("12345678123456781357"), DfpField.FLAG_INEXACT, "Add #53"); test(field.newDfp("12345678123456781234").add(field.newDfp(".00001234567812345678")), field.newDfp("12345678123456781234"), DfpField.FLAG_INEXACT, "Add #54"); test(field.newDfp("12345678123456781234").add(field.newDfp(".00000000123456781234")), field.newDfp("12345678123456781234"), DfpField.FLAG_INEXACT, "Add #55"); test(field.newDfp("-0").add(field.newDfp("-0")), field.newDfp("-0"), 0, "Add #56"); test(field.newDfp("0").add(field.newDfp("-0")), field.newDfp("0"), 0, "Add #57"); test(field.newDfp("-0").add(field.newDfp("0")), field.newDfp("0"), 0, "Add #58"); test(field.newDfp("0").add(field.newDfp("0")), field.newDfp("0"), 0, "Add #59"); } //////////////////////////////////////////////////////////////////////////////////////////////////////// // Test comparisons // utility function to help test comparisons private void cmptst(Dfp a, Dfp b, String op, boolean result, double num) { if (op == "equal") if (a.equals(b) != result) Assert.fail("assersion failed. "+op+" compare #"+num); if (op == "unequal") if (a.unequal(b) != result) Assert.fail("assersion failed. "+op+" compare #"+num); if (op == "lessThan") if (a.lessThan(b) != result) Assert.fail("assersion failed. "+op+" compare #"+num); if (op == "greaterThan") if (a.greaterThan(b) != result) Assert.fail("assersion failed. "+op+" compare #"+num); } @Test public void testCompare() { // test equal() comparison // check zero vs. zero field.clearIEEEFlags(); cmptst(field.newDfp("0"), field.newDfp("0"), "equal", true, 1); // 0 == 0 cmptst(field.newDfp("0"), field.newDfp("-0"), "equal", true, 2); // 0 == -0 cmptst(field.newDfp("-0"), field.newDfp("-0"), "equal", true, 3); // -0 == -0 cmptst(field.newDfp("-0"), field.newDfp("0"), "equal", true, 4); // -0 == 0 // check zero vs normal numbers cmptst(field.newDfp("0"), field.newDfp("1"), "equal", false, 5); // 0 == 1 cmptst(field.newDfp("1"), field.newDfp("0"), "equal", false, 6); // 1 == 0 cmptst(field.newDfp("-1"), field.newDfp("0"), "equal", false, 7); // -1 == 0 cmptst(field.newDfp("0"), field.newDfp("-1"), "equal", false, 8); // 0 == -1 cmptst(field.newDfp("0"), field.newDfp("1e-131072"), "equal", false, 9); // 0 == 1e-131072 // check flags if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0"), field.newDfp("1e-131078"), "equal", false, 10); // 0 == 1e-131078 // check flags -- underflow should be set if (field.getIEEEFlags() != DfpField.FLAG_UNDERFLOW) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); cmptst(field.newDfp("0"), field.newDfp("1e+131071"), "equal", false, 11); // 0 == 1e+131071 // check zero vs infinities cmptst(field.newDfp("0"), pinf, "equal", false, 12); // 0 == pinf cmptst(field.newDfp("0"), ninf, "equal", false, 13); // 0 == ninf cmptst(field.newDfp("-0"), pinf, "equal", false, 14); // -0 == pinf cmptst(field.newDfp("-0"), ninf, "equal", false, 15); // -0 == ninf cmptst(pinf, field.newDfp("0"), "equal", false, 16); // pinf == 0 cmptst(ninf, field.newDfp("0"), "equal", false, 17); // ninf == 0 cmptst(pinf, field.newDfp("-0"), "equal", false, 18); // pinf == -0 cmptst(ninf, field.newDfp("-0"), "equal", false, 19); // ninf == -0 cmptst(ninf, pinf, "equal", false, 19.10); // ninf == pinf cmptst(pinf, ninf, "equal", false, 19.11); // pinf == ninf cmptst(pinf, pinf, "equal", true, 19.12); // pinf == pinf cmptst(ninf, ninf, "equal", true, 19.13); // ninf == ninf // check some normal numbers cmptst(field.newDfp("1"), field.newDfp("1"), "equal", true, 20); // 1 == 1 cmptst(field.newDfp("1"), field.newDfp("-1"), "equal", false, 21); // 1 == -1 cmptst(field.newDfp("-1"), field.newDfp("-1"), "equal", true, 22); // -1 == -1 cmptst(field.newDfp("1"), field.newDfp("1.0000000000000001"), "equal", false, 23); // 1 == 1.0000000000000001 // The tests below checks to ensure that comparisons don't set FLAG_INEXACT // 100000 == 1.0000000000000001 cmptst(field.newDfp("1e20"), field.newDfp("1.0000000000000001"), "equal", false, 24); if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0.000001"), field.newDfp("1e-6"), "equal", true, 25); // check some nans -- nans shouldnt equal anything cmptst(snan, snan, "equal", false, 27); cmptst(qnan, qnan, "equal", false, 28); cmptst(snan, qnan, "equal", false, 29); cmptst(qnan, snan, "equal", false, 30); cmptst(qnan, field.newDfp("0"), "equal", false, 31); cmptst(snan, field.newDfp("0"), "equal", false, 32); cmptst(field.newDfp("0"), snan, "equal", false, 33); cmptst(field.newDfp("0"), qnan, "equal", false, 34); cmptst(qnan, pinf, "equal", false, 35); cmptst(snan, pinf, "equal", false, 36); cmptst(pinf, snan, "equal", false, 37); cmptst(pinf, qnan, "equal", false, 38); cmptst(qnan, ninf, "equal", false, 39); cmptst(snan, ninf, "equal", false, 40); cmptst(ninf, snan, "equal", false, 41); cmptst(ninf, qnan, "equal", false, 42); cmptst(qnan, field.newDfp("-1"), "equal", false, 43); cmptst(snan, field.newDfp("-1"), "equal", false, 44); cmptst(field.newDfp("-1"), snan, "equal", false, 45); cmptst(field.newDfp("-1"), qnan, "equal", false, 46); cmptst(qnan, field.newDfp("1"), "equal", false, 47); cmptst(snan, field.newDfp("1"), "equal", false, 48); cmptst(field.newDfp("1"), snan, "equal", false, 49); cmptst(field.newDfp("1"), qnan, "equal", false, 50); cmptst(snan.negate(), snan, "equal", false, 51); cmptst(qnan.negate(), qnan, "equal", false, 52); // // Tests for un equal -- do it all over again // cmptst(field.newDfp("0"), field.newDfp("0"), "unequal", false, 1); // 0 == 0 cmptst(field.newDfp("0"), field.newDfp("-0"), "unequal", false, 2); // 0 == -0 cmptst(field.newDfp("-0"), field.newDfp("-0"), "unequal", false, 3); // -0 == -0 cmptst(field.newDfp("-0"), field.newDfp("0"), "unequal", false, 4); // -0 == 0 // check zero vs normal numbers cmptst(field.newDfp("0"), field.newDfp("1"), "unequal", true, 5); // 0 == 1 cmptst(field.newDfp("1"), field.newDfp("0"), "unequal", true, 6); // 1 == 0 cmptst(field.newDfp("-1"), field.newDfp("0"), "unequal", true, 7); // -1 == 0 cmptst(field.newDfp("0"), field.newDfp("-1"), "unequal", true, 8); // 0 == -1 cmptst(field.newDfp("0"), field.newDfp("1e-131072"), "unequal", true, 9); // 0 == 1e-131072 // check flags if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0"), field.newDfp("1e-131078"), "unequal", true, 10); // 0 == 1e-131078 // check flags -- underflow should be set if (field.getIEEEFlags() != DfpField.FLAG_UNDERFLOW) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); cmptst(field.newDfp("0"), field.newDfp("1e+131071"), "unequal", true, 11); // 0 == 1e+131071 // check zero vs infinities cmptst(field.newDfp("0"), pinf, "unequal", true, 12); // 0 == pinf cmptst(field.newDfp("0"), ninf, "unequal", true, 13); // 0 == ninf cmptst(field.newDfp("-0"), pinf, "unequal", true, 14); // -0 == pinf cmptst(field.newDfp("-0"), ninf, "unequal", true, 15); // -0 == ninf cmptst(pinf, field.newDfp("0"), "unequal", true, 16); // pinf == 0 cmptst(ninf, field.newDfp("0"), "unequal", true, 17); // ninf == 0 cmptst(pinf, field.newDfp("-0"), "unequal", true, 18); // pinf == -0 cmptst(ninf, field.newDfp("-0"), "unequal", true, 19); // ninf == -0 cmptst(ninf, pinf, "unequal", true, 19.10); // ninf == pinf cmptst(pinf, ninf, "unequal", true, 19.11); // pinf == ninf cmptst(pinf, pinf, "unequal", false, 19.12); // pinf == pinf cmptst(ninf, ninf, "unequal", false, 19.13); // ninf == ninf // check some normal numbers cmptst(field.newDfp("1"), field.newDfp("1"), "unequal", false, 20); // 1 == 1 cmptst(field.newDfp("1"), field.newDfp("-1"), "unequal", true, 21); // 1 == -1 cmptst(field.newDfp("-1"), field.newDfp("-1"), "unequal", false, 22); // -1 == -1 cmptst(field.newDfp("1"), field.newDfp("1.0000000000000001"), "unequal", true, 23); // 1 == 1.0000000000000001 // The tests below checks to ensure that comparisons don't set FLAG_INEXACT // 100000 == 1.0000000000000001 cmptst(field.newDfp("1e20"), field.newDfp("1.0000000000000001"), "unequal", true, 24); if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0.000001"), field.newDfp("1e-6"), "unequal", false, 25); // check some nans -- nans shouldnt be unequal to anything cmptst(snan, snan, "unequal", false, 27); cmptst(qnan, qnan, "unequal", false, 28); cmptst(snan, qnan, "unequal", false, 29); cmptst(qnan, snan, "unequal", false, 30); cmptst(qnan, field.newDfp("0"), "unequal", false, 31); cmptst(snan, field.newDfp("0"), "unequal", false, 32); cmptst(field.newDfp("0"), snan, "unequal", false, 33); cmptst(field.newDfp("0"), qnan, "unequal", false, 34); cmptst(qnan, pinf, "unequal", false, 35); cmptst(snan, pinf, "unequal", false, 36); cmptst(pinf, snan, "unequal", false, 37); cmptst(pinf, qnan, "unequal", false, 38); cmptst(qnan, ninf, "unequal", false, 39); cmptst(snan, ninf, "unequal", false, 40); cmptst(ninf, snan, "unequal", false, 41); cmptst(ninf, qnan, "unequal", false, 42); cmptst(qnan, field.newDfp("-1"), "unequal", false, 43); cmptst(snan, field.newDfp("-1"), "unequal", false, 44); cmptst(field.newDfp("-1"), snan, "unequal", false, 45); cmptst(field.newDfp("-1"), qnan, "unequal", false, 46); cmptst(qnan, field.newDfp("1"), "unequal", false, 47); cmptst(snan, field.newDfp("1"), "unequal", false, 48); cmptst(field.newDfp("1"), snan, "unequal", false, 49); cmptst(field.newDfp("1"), qnan, "unequal", false, 50); cmptst(snan.negate(), snan, "unequal", false, 51); cmptst(qnan.negate(), qnan, "unequal", false, 52); if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare unequal flags = "+field.getIEEEFlags()); // // Tests for lessThan -- do it all over again // cmptst(field.newDfp("0"), field.newDfp("0"), "lessThan", false, 1); // 0 < 0 cmptst(field.newDfp("0"), field.newDfp("-0"), "lessThan", false, 2); // 0 < -0 cmptst(field.newDfp("-0"), field.newDfp("-0"), "lessThan", false, 3); // -0 < -0 cmptst(field.newDfp("-0"), field.newDfp("0"), "lessThan", false, 4); // -0 < 0 // check zero vs normal numbers cmptst(field.newDfp("0"), field.newDfp("1"), "lessThan", true, 5); // 0 < 1 cmptst(field.newDfp("1"), field.newDfp("0"), "lessThan", false, 6); // 1 < 0 cmptst(field.newDfp("-1"), field.newDfp("0"), "lessThan", true, 7); // -1 < 0 cmptst(field.newDfp("0"), field.newDfp("-1"), "lessThan", false, 8); // 0 < -1 cmptst(field.newDfp("0"), field.newDfp("1e-131072"), "lessThan", true, 9); // 0 < 1e-131072 // check flags if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0"), field.newDfp("1e-131078"), "lessThan", true, 10); // 0 < 1e-131078 // check flags -- underflow should be set if (field.getIEEEFlags() != DfpField.FLAG_UNDERFLOW) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); cmptst(field.newDfp("0"), field.newDfp("1e+131071"), "lessThan", true, 11); // 0 < 1e+131071 // check zero vs infinities cmptst(field.newDfp("0"), pinf, "lessThan", true, 12); // 0 < pinf cmptst(field.newDfp("0"), ninf, "lessThan", false, 13); // 0 < ninf cmptst(field.newDfp("-0"), pinf, "lessThan", true, 14); // -0 < pinf cmptst(field.newDfp("-0"), ninf, "lessThan", false, 15); // -0 < ninf cmptst(pinf, field.newDfp("0"), "lessThan", false, 16); // pinf < 0 cmptst(ninf, field.newDfp("0"), "lessThan", true, 17); // ninf < 0 cmptst(pinf, field.newDfp("-0"), "lessThan", false, 18); // pinf < -0 cmptst(ninf, field.newDfp("-0"), "lessThan", true, 19); // ninf < -0 cmptst(ninf, pinf, "lessThan", true, 19.10); // ninf < pinf cmptst(pinf, ninf, "lessThan", false, 19.11); // pinf < ninf cmptst(pinf, pinf, "lessThan", false, 19.12); // pinf < pinf cmptst(ninf, ninf, "lessThan", false, 19.13); // ninf < ninf // check some normal numbers cmptst(field.newDfp("1"), field.newDfp("1"), "lessThan", false, 20); // 1 < 1 cmptst(field.newDfp("1"), field.newDfp("-1"), "lessThan", false, 21); // 1 < -1 cmptst(field.newDfp("-1"), field.newDfp("-1"), "lessThan", false, 22); // -1 < -1 cmptst(field.newDfp("1"), field.newDfp("1.0000000000000001"), "lessThan", true, 23); // 1 < 1.0000000000000001 // The tests below checks to ensure that comparisons don't set FLAG_INEXACT // 100000 < 1.0000000000000001 cmptst(field.newDfp("1e20"), field.newDfp("1.0000000000000001"), "lessThan", false, 24); if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0.000001"), field.newDfp("1e-6"), "lessThan", false, 25); // check some nans -- nans shouldnt be lessThan to anything cmptst(snan, snan, "lessThan", false, 27); cmptst(qnan, qnan, "lessThan", false, 28); cmptst(snan, qnan, "lessThan", false, 29); cmptst(qnan, snan, "lessThan", false, 30); cmptst(qnan, field.newDfp("0"), "lessThan", false, 31); cmptst(snan, field.newDfp("0"), "lessThan", false, 32); cmptst(field.newDfp("0"), snan, "lessThan", false, 33); cmptst(field.newDfp("0"), qnan, "lessThan", false, 34); cmptst(qnan, pinf, "lessThan", false, 35); cmptst(snan, pinf, "lessThan", false, 36); cmptst(pinf, snan, "lessThan", false, 37); cmptst(pinf, qnan, "lessThan", false, 38); cmptst(qnan, ninf, "lessThan", false, 39); cmptst(snan, ninf, "lessThan", false, 40); cmptst(ninf, snan, "lessThan", false, 41); cmptst(ninf, qnan, "lessThan", false, 42); cmptst(qnan, field.newDfp("-1"), "lessThan", false, 43); cmptst(snan, field.newDfp("-1"), "lessThan", false, 44); cmptst(field.newDfp("-1"), snan, "lessThan", false, 45); cmptst(field.newDfp("-1"), qnan, "lessThan", false, 46); cmptst(qnan, field.newDfp("1"), "lessThan", false, 47); cmptst(snan, field.newDfp("1"), "lessThan", false, 48); cmptst(field.newDfp("1"), snan, "lessThan", false, 49); cmptst(field.newDfp("1"), qnan, "lessThan", false, 50); cmptst(snan.negate(), snan, "lessThan", false, 51); cmptst(qnan.negate(), qnan, "lessThan", false, 52); //lessThan compares with nans should raise FLAG_INVALID if (field.getIEEEFlags() != DfpField.FLAG_INVALID) Assert.fail("assersion failed. compare lessThan flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); // // Tests for greaterThan -- do it all over again // cmptst(field.newDfp("0"), field.newDfp("0"), "greaterThan", false, 1); // 0 > 0 cmptst(field.newDfp("0"), field.newDfp("-0"), "greaterThan", false, 2); // 0 > -0 cmptst(field.newDfp("-0"), field.newDfp("-0"), "greaterThan", false, 3); // -0 > -0 cmptst(field.newDfp("-0"), field.newDfp("0"), "greaterThan", false, 4); // -0 > 0 // check zero vs normal numbers cmptst(field.newDfp("0"), field.newDfp("1"), "greaterThan", false, 5); // 0 > 1 cmptst(field.newDfp("1"), field.newDfp("0"), "greaterThan", true, 6); // 1 > 0 cmptst(field.newDfp("-1"), field.newDfp("0"), "greaterThan", false, 7); // -1 > 0 cmptst(field.newDfp("0"), field.newDfp("-1"), "greaterThan", true, 8); // 0 > -1 cmptst(field.newDfp("0"), field.newDfp("1e-131072"), "greaterThan", false, 9); // 0 > 1e-131072 // check flags if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0"), field.newDfp("1e-131078"), "greaterThan", false, 10); // 0 > 1e-131078 // check flags -- underflow should be set if (field.getIEEEFlags() != DfpField.FLAG_UNDERFLOW) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); cmptst(field.newDfp("0"), field.newDfp("1e+131071"), "greaterThan", false, 11); // 0 > 1e+131071 // check zero vs infinities cmptst(field.newDfp("0"), pinf, "greaterThan", false, 12); // 0 > pinf cmptst(field.newDfp("0"), ninf, "greaterThan", true, 13); // 0 > ninf cmptst(field.newDfp("-0"), pinf, "greaterThan", false, 14); // -0 > pinf cmptst(field.newDfp("-0"), ninf, "greaterThan", true, 15); // -0 > ninf cmptst(pinf, field.newDfp("0"), "greaterThan", true, 16); // pinf > 0 cmptst(ninf, field.newDfp("0"), "greaterThan", false, 17); // ninf > 0 cmptst(pinf, field.newDfp("-0"), "greaterThan", true, 18); // pinf > -0 cmptst(ninf, field.newDfp("-0"), "greaterThan", false, 19); // ninf > -0 cmptst(ninf, pinf, "greaterThan", false, 19.10); // ninf > pinf cmptst(pinf, ninf, "greaterThan", true, 19.11); // pinf > ninf cmptst(pinf, pinf, "greaterThan", false, 19.12); // pinf > pinf cmptst(ninf, ninf, "greaterThan", false, 19.13); // ninf > ninf // check some normal numbers cmptst(field.newDfp("1"), field.newDfp("1"), "greaterThan", false, 20); // 1 > 1 cmptst(field.newDfp("1"), field.newDfp("-1"), "greaterThan", true, 21); // 1 > -1 cmptst(field.newDfp("-1"), field.newDfp("-1"), "greaterThan", false, 22); // -1 > -1 cmptst(field.newDfp("1"), field.newDfp("1.0000000000000001"), "greaterThan", false, 23); // 1 > 1.0000000000000001 // The tests below checks to ensure that comparisons don't set FLAG_INEXACT // 100000 > 1.0000000000000001 cmptst(field.newDfp("1e20"), field.newDfp("1.0000000000000001"), "greaterThan", true, 24); if (field.getIEEEFlags() != 0) Assert.fail("assersion failed. compare flags = "+field.getIEEEFlags()); cmptst(field.newDfp("0.000001"), field.newDfp("1e-6"), "greaterThan", false, 25); // check some nans -- nans shouldnt be greaterThan to anything cmptst(snan, snan, "greaterThan", false, 27); cmptst(qnan, qnan, "greaterThan", false, 28); cmptst(snan, qnan, "greaterThan", false, 29); cmptst(qnan, snan, "greaterThan", false, 30); cmptst(qnan, field.newDfp("0"), "greaterThan", false, 31); cmptst(snan, field.newDfp("0"), "greaterThan", false, 32); cmptst(field.newDfp("0"), snan, "greaterThan", false, 33); cmptst(field.newDfp("0"), qnan, "greaterThan", false, 34); cmptst(qnan, pinf, "greaterThan", false, 35); cmptst(snan, pinf, "greaterThan", false, 36); cmptst(pinf, snan, "greaterThan", false, 37); cmptst(pinf, qnan, "greaterThan", false, 38); cmptst(qnan, ninf, "greaterThan", false, 39); cmptst(snan, ninf, "greaterThan", false, 40); cmptst(ninf, snan, "greaterThan", false, 41); cmptst(ninf, qnan, "greaterThan", false, 42); cmptst(qnan, field.newDfp("-1"), "greaterThan", false, 43); cmptst(snan, field.newDfp("-1"), "greaterThan", false, 44); cmptst(field.newDfp("-1"), snan, "greaterThan", false, 45); cmptst(field.newDfp("-1"), qnan, "greaterThan", false, 46); cmptst(qnan, field.newDfp("1"), "greaterThan", false, 47); cmptst(snan, field.newDfp("1"), "greaterThan", false, 48); cmptst(field.newDfp("1"), snan, "greaterThan", false, 49); cmptst(field.newDfp("1"), qnan, "greaterThan", false, 50); cmptst(snan.negate(), snan, "greaterThan", false, 51); cmptst(qnan.negate(), qnan, "greaterThan", false, 52); //greaterThan compares with nans should raise FLAG_INVALID if (field.getIEEEFlags() != DfpField.FLAG_INVALID) Assert.fail("assersion failed. compare greaterThan flags = "+field.getIEEEFlags()); field.clearIEEEFlags(); } // // Test multiplication // @Test public void testMultiply() { test(field.newDfp("1").multiply(field.newDfp("1")), // Basic tests 1*1 = 1 field.newDfp("1"), 0, "Multiply #1"); test(field.newDfp("1").multiply(1), // Basic tests 1*1 = 1 field.newDfp("1"), 0, "Multiply #2"); test(field.newDfp("-1").multiply(field.newDfp("1")), // Basic tests -1*1 = -1 field.newDfp("-1"), 0, "Multiply #3"); test(field.newDfp("-1").multiply(1), // Basic tests -1*1 = -1 field.newDfp("-1"), 0, "Multiply #4"); // basic tests with integers test(field.newDfp("2").multiply(field.newDfp("3")), field.newDfp("6"), 0, "Multiply #5"); test(field.newDfp("2").multiply(3), field.newDfp("6"), 0, "Multiply #6"); test(field.newDfp("-2").multiply(field.newDfp("3")), field.newDfp("-6"), 0, "Multiply #7"); test(field.newDfp("-2").multiply(3), field.newDfp("-6"), 0, "Multiply #8"); test(field.newDfp("2").multiply(field.newDfp("-3")), field.newDfp("-6"), 0, "Multiply #9"); test(field.newDfp("-2").multiply(field.newDfp("-3")), field.newDfp("6"), 0, "Multiply #10"); //multiply by zero test(field.newDfp("-2").multiply(field.newDfp("0")), field.newDfp("-0"), 0, "Multiply #11"); test(field.newDfp("-2").multiply(0), field.newDfp("-0"), 0, "Multiply #12"); test(field.newDfp("2").multiply(field.newDfp("0")), field.newDfp("0"), 0, "Multiply #13"); test(field.newDfp("2").multiply(0), field.newDfp("0"), 0, "Multiply #14"); test(field.newDfp("2").multiply(pinf), pinf, 0, "Multiply #15"); test(field.newDfp("2").multiply(ninf), ninf, 0, "Multiply #16"); test(field.newDfp("-2").multiply(pinf), ninf, 0, "Multiply #17"); test(field.newDfp("-2").multiply(ninf), pinf, 0, "Multiply #18"); test(ninf.multiply(field.newDfp("-2")), pinf, 0, "Multiply #18.1"); test(field.newDfp("5e131071").multiply(2), pinf, DfpField.FLAG_OVERFLOW, "Multiply #19"); test(field.newDfp("5e131071").multiply(field.newDfp("1.999999999999999")), field.newDfp("9.9999999999999950000e131071"), 0, "Multiply #20"); test(field.newDfp("-5e131071").multiply(2), ninf, DfpField.FLAG_OVERFLOW, "Multiply #22"); test(field.newDfp("-5e131071").multiply(field.newDfp("1.999999999999999")), field.newDfp("-9.9999999999999950000e131071"), 0, "Multiply #23"); test(field.newDfp("1e-65539").multiply(field.newDfp("1e-65539")), field.newDfp("1e-131078"), DfpField.FLAG_UNDERFLOW, "Multiply #24"); test(field.newDfp("1").multiply(nan), nan, 0, "Multiply #25"); test(nan.multiply(field.newDfp("1")), nan, 0, "Multiply #26"); test(nan.multiply(pinf), nan, 0, "Multiply #27"); test(pinf.multiply(nan), nan, 0, "Multiply #27"); test(pinf.multiply(field.newDfp("0")), nan, DfpField.FLAG_INVALID, "Multiply #28"); test(field.newDfp("0").multiply(pinf), nan, DfpField.FLAG_INVALID, "Multiply #29"); test(pinf.multiply(pinf), pinf, 0, "Multiply #30"); test(ninf.multiply(pinf), ninf, 0, "Multiply #31"); test(pinf.multiply(ninf), ninf, 0, "Multiply #32"); test(ninf.multiply(ninf), pinf, 0, "Multiply #33"); test(pinf.multiply(1), pinf, 0, "Multiply #34"); test(pinf.multiply(0), nan, DfpField.FLAG_INVALID, "Multiply #35"); test(nan.multiply(1), nan, 0, "Multiply #36"); test(field.newDfp("1").multiply(10000), // out of range nan, DfpField.FLAG_INVALID, "Multiply #37"); test(field.newDfp("1").multiply(-1), // out of range nan, DfpField.FLAG_INVALID, "Multiply #38"); } @Test public void testDivide() { test(field.newDfp("1").divide(nan), // divide by NaN = NaN nan, 0, "Divide #1"); test(nan.divide(field.newDfp("1")), // NaN / number = NaN nan, 0, "Divide #2"); test(pinf.divide(field.newDfp("1")), pinf, 0, "Divide #3"); test(pinf.divide(field.newDfp("-1")), ninf, 0, "Divide #4"); test(pinf.divide(pinf), nan, DfpField.FLAG_INVALID, "Divide #5"); test(ninf.divide(pinf), nan, DfpField.FLAG_INVALID, "Divide #6"); test(pinf.divide(ninf), nan, DfpField.FLAG_INVALID, "Divide #7"); test(ninf.divide(ninf), nan, DfpField.FLAG_INVALID, "Divide #8"); test(field.newDfp("0").divide(field.newDfp("0")), nan, DfpField.FLAG_DIV_ZERO, "Divide #9"); test(field.newDfp("1").divide(field.newDfp("0")), pinf, DfpField.FLAG_DIV_ZERO, "Divide #10"); test(field.newDfp("1").divide(field.newDfp("-0")), ninf, DfpField.FLAG_DIV_ZERO, "Divide #11"); test(field.newDfp("-1").divide(field.newDfp("0")), ninf, DfpField.FLAG_DIV_ZERO, "Divide #12"); test(field.newDfp("-1").divide(field.newDfp("-0")), pinf, DfpField.FLAG_DIV_ZERO, "Divide #13"); test(field.newDfp("1").divide(field.newDfp("3")), field.newDfp("0.33333333333333333333"), DfpField.FLAG_INEXACT, "Divide #14"); test(field.newDfp("1").divide(field.newDfp("6")), field.newDfp("0.16666666666666666667"), DfpField.FLAG_INEXACT, "Divide #15"); test(field.newDfp("10").divide(field.newDfp("6")), field.newDfp("1.6666666666666667"), DfpField.FLAG_INEXACT, "Divide #16"); test(field.newDfp("100").divide(field.newDfp("6")), field.newDfp("16.6666666666666667"), DfpField.FLAG_INEXACT, "Divide #17"); test(field.newDfp("1000").divide(field.newDfp("6")), field.newDfp("166.6666666666666667"), DfpField.FLAG_INEXACT, "Divide #18"); test(field.newDfp("10000").divide(field.newDfp("6")), field.newDfp("1666.6666666666666667"), DfpField.FLAG_INEXACT, "Divide #19"); test(field.newDfp("1").divide(field.newDfp("1")), field.newDfp("1"), 0, "Divide #20"); test(field.newDfp("1").divide(field.newDfp("-1")), field.newDfp("-1"), 0, "Divide #21"); test(field.newDfp("-1").divide(field.newDfp("1")), field.newDfp("-1"), 0, "Divide #22"); test(field.newDfp("-1").divide(field.newDfp("-1")), field.newDfp("1"), 0, "Divide #23"); test(field.newDfp("1e-65539").divide(field.newDfp("1e65539")), field.newDfp("1e-131078"), DfpField.FLAG_UNDERFLOW, "Divide #24"); test(field.newDfp("1e65539").divide(field.newDfp("1e-65539")), pinf, DfpField.FLAG_OVERFLOW, "Divide #24"); test(field.newDfp("2").divide(field.newDfp("1.5")), // test trial-divisor too high field.newDfp("1.3333333333333333"), DfpField.FLAG_INEXACT, "Divide #25"); test(field.newDfp("2").divide(pinf), field.newDfp("0"), 0, "Divide #26"); test(field.newDfp("2").divide(ninf), field.newDfp("-0"), 0, "Divide #27"); test(field.newDfp("0").divide(field.newDfp("1")), field.newDfp("0"), 0, "Divide #28"); } @Test public void testDivideInt() { test(nan.divide(1), // NaN / number = NaN nan, 0, "DivideInt #1"); test(pinf.divide(1), pinf, 0, "DivideInt #2"); test(field.newDfp("0").divide(0), nan, DfpField.FLAG_DIV_ZERO, "DivideInt #3"); test(field.newDfp("1").divide(0), pinf, DfpField.FLAG_DIV_ZERO, "DivideInt #4"); test(field.newDfp("-1").divide(0), ninf, DfpField.FLAG_DIV_ZERO, "DivideInt #5"); test(field.newDfp("1").divide(3), field.newDfp("0.33333333333333333333"), DfpField.FLAG_INEXACT, "DivideInt #6"); test(field.newDfp("1").divide(6), field.newDfp("0.16666666666666666667"), DfpField.FLAG_INEXACT, "DivideInt #7"); test(field.newDfp("10").divide(6), field.newDfp("1.6666666666666667"), DfpField.FLAG_INEXACT, "DivideInt #8"); test(field.newDfp("100").divide(6), field.newDfp("16.6666666666666667"), DfpField.FLAG_INEXACT, "DivideInt #9"); test(field.newDfp("1000").divide(6), field.newDfp("166.6666666666666667"), DfpField.FLAG_INEXACT, "DivideInt #10"); test(field.newDfp("10000").divide(6), field.newDfp("1666.6666666666666667"), DfpField.FLAG_INEXACT, "DivideInt #20"); test(field.newDfp("1").divide(1), field.newDfp("1"), 0, "DivideInt #21"); test(field.newDfp("1e-131077").divide(10), field.newDfp("1e-131078"), DfpField.FLAG_UNDERFLOW, "DivideInt #22"); test(field.newDfp("0").divide(1), field.newDfp("0"), 0, "DivideInt #23"); test(field.newDfp("1").divide(10000), nan, DfpField.FLAG_INVALID, "DivideInt #24"); test(field.newDfp("1").divide(-1), nan, DfpField.FLAG_INVALID, "DivideInt #25"); } @Test public void testNextAfter() { test(field.newDfp("1").nextAfter(pinf), field.newDfp("1.0000000000000001"), 0, "NextAfter #1"); test(field.newDfp("1.0000000000000001").nextAfter(ninf), field.newDfp("1"), 0, "NextAfter #1.5"); test(field.newDfp("1").nextAfter(ninf), field.newDfp("0.99999999999999999999"), 0, "NextAfter #2"); test(field.newDfp("0.99999999999999999999").nextAfter(field.newDfp("2")), field.newDfp("1"), 0, "NextAfter #3"); test(field.newDfp("-1").nextAfter(ninf), field.newDfp("-1.0000000000000001"), 0, "NextAfter #4"); test(field.newDfp("-1").nextAfter(pinf), field.newDfp("-0.99999999999999999999"), 0, "NextAfter #5"); test(field.newDfp("-0.99999999999999999999").nextAfter(field.newDfp("-2")), field.newDfp("-1"), 0, "NextAfter #6"); test(field.newDfp("2").nextAfter(field.newDfp("2")), field.newDfp("2"), 0, "NextAfter #7"); test(field.newDfp("0").nextAfter(field.newDfp("0")), field.newDfp("0"), 0, "NextAfter #8"); test(field.newDfp("-2").nextAfter(field.newDfp("-2")), field.newDfp("-2"), 0, "NextAfter #9"); test(field.newDfp("0").nextAfter(field.newDfp("1")), field.newDfp("1e-131092"), DfpField.FLAG_UNDERFLOW, "NextAfter #10"); test(field.newDfp("0").nextAfter(field.newDfp("-1")), field.newDfp("-1e-131092"), DfpField.FLAG_UNDERFLOW, "NextAfter #11"); test(field.newDfp("-1e-131092").nextAfter(pinf), field.newDfp("-0"), DfpField.FLAG_UNDERFLOW|DfpField.FLAG_INEXACT, "Next After #12"); test(field.newDfp("1e-131092").nextAfter(ninf), field.newDfp("0"), DfpField.FLAG_UNDERFLOW|DfpField.FLAG_INEXACT, "Next After #13"); test(field.newDfp("9.9999999999999999999e131078").nextAfter(pinf), pinf, DfpField.FLAG_OVERFLOW|DfpField.FLAG_INEXACT, "Next After #14"); } @Test public void testToString() { Assert.assertEquals("toString #1", "Infinity", pinf.toString()); Assert.assertEquals("toString #2", "-Infinity", ninf.toString()); Assert.assertEquals("toString #3", "NaN", nan.toString()); Assert.assertEquals("toString #4", "NaN", field.newDfp((byte) 1, Dfp.QNAN).toString()); Assert.assertEquals("toString #5", "NaN", field.newDfp((byte) 1, Dfp.SNAN).toString()); Assert.assertEquals("toString #6", "1.2300000000000000e100", field.newDfp("1.23e100").toString()); Assert.assertEquals("toString #7", "-1.2300000000000000e100", field.newDfp("-1.23e100").toString()); Assert.assertEquals("toString #8", "12345678.1234", field.newDfp("12345678.1234").toString()); Assert.assertEquals("toString #9", "0.00001234", field.newDfp("0.00001234").toString()); } @Test public void testRound() { field.setRoundingMode(DfpField.RoundingMode.ROUND_DOWN); // Round down test(field.newDfp("12345678901234567890").add(field.newDfp("0.9")), field.newDfp("12345678901234567890"), DfpField.FLAG_INEXACT, "Round #1"); test(field.newDfp("12345678901234567890").add(field.newDfp("0.99999999")), field.newDfp("12345678901234567890"), DfpField.FLAG_INEXACT, "Round #2"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.99999999")), field.newDfp("-12345678901234567890"), DfpField.FLAG_INEXACT, "Round #3"); field.setRoundingMode(DfpField.RoundingMode.ROUND_UP); // Round up test(field.newDfp("12345678901234567890").add(field.newDfp("0.1")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #4"); test(field.newDfp("12345678901234567890").add(field.newDfp("0.0001")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #5"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.1")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #6"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.0001")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #7"); field.setRoundingMode(DfpField.RoundingMode.ROUND_HALF_UP); // Round half up test(field.newDfp("12345678901234567890").add(field.newDfp("0.4999")), field.newDfp("12345678901234567890"), DfpField.FLAG_INEXACT, "Round #8"); test(field.newDfp("12345678901234567890").add(field.newDfp("0.5000")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #9"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.4999")), field.newDfp("-12345678901234567890"), DfpField.FLAG_INEXACT, "Round #10"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.5000")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #11"); field.setRoundingMode(DfpField.RoundingMode.ROUND_HALF_DOWN); // Round half down test(field.newDfp("12345678901234567890").add(field.newDfp("0.5001")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #12"); test(field.newDfp("12345678901234567890").add(field.newDfp("0.5000")), field.newDfp("12345678901234567890"), DfpField.FLAG_INEXACT, "Round #13"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.5001")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #14"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.5000")), field.newDfp("-12345678901234567890"), DfpField.FLAG_INEXACT, "Round #15"); field.setRoundingMode(DfpField.RoundingMode.ROUND_HALF_ODD); // Round half odd test(field.newDfp("12345678901234567890").add(field.newDfp("0.5000")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #16"); test(field.newDfp("12345678901234567891").add(field.newDfp("0.5000")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #17"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.5000")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #18"); test(field.newDfp("-12345678901234567891").add(field.newDfp("-0.5000")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #19"); field.setRoundingMode(DfpField.RoundingMode.ROUND_CEIL); // Round ceil test(field.newDfp("12345678901234567890").add(field.newDfp("0.0001")), field.newDfp("12345678901234567891"), DfpField.FLAG_INEXACT, "Round #20"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.9999")), field.newDfp("-12345678901234567890"), DfpField.FLAG_INEXACT, "Round #21"); field.setRoundingMode(DfpField.RoundingMode.ROUND_FLOOR); // Round floor test(field.newDfp("12345678901234567890").add(field.newDfp("0.9999")), field.newDfp("12345678901234567890"), DfpField.FLAG_INEXACT, "Round #22"); test(field.newDfp("-12345678901234567890").add(field.newDfp("-0.0001")), field.newDfp("-12345678901234567891"), DfpField.FLAG_INEXACT, "Round #23"); field.setRoundingMode(DfpField.RoundingMode.ROUND_HALF_EVEN); // reset } @Test public void testCeil() { test(field.newDfp("1234.0000000000000001").ceil(), field.newDfp("1235"), DfpField.FLAG_INEXACT, "Ceil #1"); } @Test public void testFloor() { test(field.newDfp("1234.9999999999999999").floor(), field.newDfp("1234"), DfpField.FLAG_INEXACT, "Floor #1"); } @Test public void testRint() { test(field.newDfp("1234.50000000001").rint(), field.newDfp("1235"), DfpField.FLAG_INEXACT, "Rint #1"); test(field.newDfp("1234.5000").rint(), field.newDfp("1234"), DfpField.FLAG_INEXACT, "Rint #2"); test(field.newDfp("1235.5000").rint(), field.newDfp("1236"), DfpField.FLAG_INEXACT, "Rint #3"); } @Test public void testCopySign() { test(Dfp.copysign(field.newDfp("1234."), field.newDfp("-1")), field.newDfp("-1234"), 0, "CopySign #1"); test(Dfp.copysign(field.newDfp("-1234."), field.newDfp("-1")), field.newDfp("-1234"), 0, "CopySign #2"); test(Dfp.copysign(field.newDfp("-1234."), field.newDfp("1")), field.newDfp("1234"), 0, "CopySign #3"); test(Dfp.copysign(field.newDfp("1234."), field.newDfp("1")), field.newDfp("1234"), 0, "CopySign #4"); } @Test public void testIntValue() { Assert.assertEquals("intValue #1", 1234, field.newDfp("1234").intValue()); Assert.assertEquals("intValue #2", -1234, field.newDfp("-1234").intValue()); Assert.assertEquals("intValue #3", 1234, field.newDfp("1234.5").intValue()); Assert.assertEquals("intValue #4", 1235, field.newDfp("1234.500001").intValue()); Assert.assertEquals("intValue #5", 2147483647, field.newDfp("1e1000").intValue()); Assert.assertEquals("intValue #6", -2147483648, field.newDfp("-1e1000").intValue()); } @Test public void testLog10K() { Assert.assertEquals("log10K #1", 1, field.newDfp("123456").log10K()); Assert.assertEquals("log10K #2", 2, field.newDfp("123456789").log10K()); Assert.assertEquals("log10K #3", 0, field.newDfp("2").log10K()); Assert.assertEquals("log10K #3", 0, field.newDfp("1").log10K()); Assert.assertEquals("log10K #4", -1, field.newDfp("0.1").log10K()); } @Test public void testPower10K() { Dfp d = field.newDfp(); test(d.power10K(0), field.newDfp("1"), 0, "Power10 #1"); test(d.power10K(1), field.newDfp("10000"), 0, "Power10 #2"); test(d.power10K(2), field.newDfp("100000000"), 0, "Power10 #3"); test(d.power10K(-1), field.newDfp("0.0001"), 0, "Power10 #4"); test(d.power10K(-2), field.newDfp("0.00000001"), 0, "Power10 #5"); test(d.power10K(-3), field.newDfp("0.000000000001"), 0, "Power10 #6"); } @Test public void testLog10() { Assert.assertEquals("log10 #1", 1, field.newDfp("12").log10()); Assert.assertEquals("log10 #2", 2, field.newDfp("123").log10()); Assert.assertEquals("log10 #3", 3, field.newDfp("1234").log10()); Assert.assertEquals("log10 #4", 4, field.newDfp("12345").log10()); Assert.assertEquals("log10 #5", 5, field.newDfp("123456").log10()); Assert.assertEquals("log10 #6", 6, field.newDfp("1234567").log10()); Assert.assertEquals("log10 #6", 7, field.newDfp("12345678").log10()); Assert.assertEquals("log10 #7", 8, field.newDfp("123456789").log10()); Assert.assertEquals("log10 #8", 9, field.newDfp("1234567890").log10()); Assert.assertEquals("log10 #9", 10, field.newDfp("12345678901").log10()); Assert.assertEquals("log10 #10", 11, field.newDfp("123456789012").log10()); Assert.assertEquals("log10 #11", 12, field.newDfp("1234567890123").log10()); Assert.assertEquals("log10 #12", 0, field.newDfp("2").log10()); Assert.assertEquals("log10 #13", 0, field.newDfp("1").log10()); Assert.assertEquals("log10 #14", -1, field.newDfp("0.12").log10()); Assert.assertEquals("log10 #15", -2, field.newDfp("0.012").log10()); } @Test public void testPower10() { Dfp d = field.newDfp(); test(d.power10(0), field.newDfp("1"), 0, "Power10 #1"); test(d.power10(1), field.newDfp("10"), 0, "Power10 #2"); test(d.power10(2), field.newDfp("100"), 0, "Power10 #3"); test(d.power10(3), field.newDfp("1000"), 0, "Power10 #4"); test(d.power10(4), field.newDfp("10000"), 0, "Power10 #5"); test(d.power10(5), field.newDfp("100000"), 0, "Power10 #6"); test(d.power10(6), field.newDfp("1000000"), 0, "Power10 #7"); test(d.power10(7), field.newDfp("10000000"), 0, "Power10 #8"); test(d.power10(8), field.newDfp("100000000"), 0, "Power10 #9"); test(d.power10(9), field.newDfp("1000000000"), 0, "Power10 #10"); test(d.power10(-1), field.newDfp(".1"), 0, "Power10 #11"); test(d.power10(-2), field.newDfp(".01"), 0, "Power10 #12"); test(d.power10(-3), field.newDfp(".001"), 0, "Power10 #13"); test(d.power10(-4), field.newDfp(".0001"), 0, "Power10 #14"); test(d.power10(-5), field.newDfp(".00001"), 0, "Power10 #15"); test(d.power10(-6), field.newDfp(".000001"), 0, "Power10 #16"); test(d.power10(-7), field.newDfp(".0000001"), 0, "Power10 #17"); test(d.power10(-8), field.newDfp(".00000001"), 0, "Power10 #18"); test(d.power10(-9), field.newDfp(".000000001"), 0, "Power10 #19"); test(d.power10(-10), field.newDfp(".0000000001"), 0, "Power10 #20"); } @Test public void testRemainder() { test(field.newDfp("10").remainder(field.newDfp("3")), field.newDfp("1"), DfpField.FLAG_INEXACT, "Remainder #1"); test(field.newDfp("9").remainder(field.newDfp("3")), field.newDfp("0"), 0, "Remainder #2"); test(field.newDfp("-9").remainder(field.newDfp("3")), field.newDfp("-0"), 0, "Remainder #3"); } @Test public void testSqrt() { test(field.newDfp("0").sqrt(), field.newDfp("0"), 0, "Sqrt #1"); test(field.newDfp("-0").sqrt(), field.newDfp("-0"), 0, "Sqrt #2"); test(field.newDfp("1").sqrt(), field.newDfp("1"), 0, "Sqrt #3"); test(field.newDfp("2").sqrt(), field.newDfp("1.4142135623730950"), DfpField.FLAG_INEXACT, "Sqrt #4"); test(field.newDfp("3").sqrt(), field.newDfp("1.7320508075688773"), DfpField.FLAG_INEXACT, "Sqrt #5"); test(field.newDfp("5").sqrt(), field.newDfp("2.2360679774997897"), DfpField.FLAG_INEXACT, "Sqrt #6"); test(field.newDfp("500").sqrt(), field.newDfp("22.3606797749978970"), DfpField.FLAG_INEXACT, "Sqrt #6.2"); test(field.newDfp("50000").sqrt(), field.newDfp("223.6067977499789696"), DfpField.FLAG_INEXACT, "Sqrt #6.3"); test(field.newDfp("-1").sqrt(), nan, DfpField.FLAG_INVALID, "Sqrt #7"); test(pinf.sqrt(), pinf, 0, "Sqrt #8"); test(field.newDfp((byte) 1, Dfp.QNAN).sqrt(), nan, 0, "Sqrt #9"); test(field.newDfp((byte) 1, Dfp.SNAN).sqrt(), nan, DfpField.FLAG_INVALID, "Sqrt #9"); } }
gpl-2.0
oscarservice/oscar-old
src/main/java/oscar/util/Pager.java
3356
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package oscar.util; import java.util.ResourceBundle; public class Pager { private static int MAX_PAGE_INDEX = 15; private static String HEADER = "Result page"; private static ResourceBundle prop = ResourceBundle.getBundle("oscarResources"); static { prop = ResourceBundle.getBundle("oscarResources"); try { HEADER = prop.getString("pager.header.title"); } catch (Exception e) { } try { MAX_PAGE_INDEX = Integer.parseInt(prop.getString( "pager.max.page.index")); } catch (Exception e) { } } public static String generate(int offset, int length, int size, String url) { if (length > size) { String pref; if (url.indexOf("?") > -1) { pref = "&"; } else { pref = "?"; } String header = "<font face='Helvetica' size='-1'>" + HEADER + ": "; if (offset > 0) { header += ("&nbsp;<a href=\"" + url + pref + "pager.offset=" + (offset - size) + "\">" + prop.getString("pager.prev.desc") + "</a>\n"); } int start; int radius = MAX_PAGE_INDEX / 2 * size; if (offset < radius) { start = 0; } else if (offset < (length - radius)) { start = offset - radius; } else { start = ((length / size) - MAX_PAGE_INDEX) * size; } for (int i = start; (i < length) && (i < (start + (MAX_PAGE_INDEX * size))); i += size) { if (i == offset) { header += ("<b>" + ((i / size) + 1) + "</b>\n"); } else { header += ("&nbsp;<a href=\"" + url + pref + "pager.offset=" + i + "\">" + ((i / size) + 1) + "</a>\n"); } } if (offset < (length - size)) { header += ("&nbsp;<a href=\"" + url + pref + "pager.offset=" + (offset + size) + "\">" + prop.getString("pager.next.desc") + "</a>\n"); } header += "</font>"; return header; } else { return ""; } } }
gpl-2.0
karianna/jdk8_tl
jdk/src/share/classes/sun/security/jgss/krb5/MessageToken.java
26251
/* * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.security.jgss.krb5; import org.ietf.jgss.*; import sun.security.jgss.*; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.ByteArrayInputStream; import java.security.MessageDigest; /** * This class is a base class for other token definitions that pertain to * per-message GSS-API calls. Conceptually GSS-API has two types of * per-message tokens: WrapToken and MicToken. They differ in the respect * that a WrapToken carries additional plaintext or ciphertext application * data besides just the sequence number and checksum. This class * encapsulates the commonality in the structure of the WrapToken and the * MicToken. This structure can be represented as: * <p> * <pre> * 0..1 TOK_ID Identification field. * 01 01 - Mic token * 02 01 - Wrap token * 2..3 SGN_ALG Checksum algorithm indicator. * 00 00 - DES MAC MD5 * 01 00 - MD2.5 * 02 00 - DES MAC * 04 00 - HMAC SHA1 DES3-KD * 11 00 - RC4-HMAC * 4..5 SEAL_ALG ff ff - none * 00 00 - DES * 02 00 - DES3-KD * 10 00 - RC4-HMAC * 6..7 Filler Contains ff ff * 8..15 SND_SEQ Encrypted sequence number field. * 16..s+15 SGN_CKSUM Checksum of plaintext padded data, * calculated according to algorithm * specified in SGN_ALG field. * s+16..last Data encrypted or plaintext padded data * </pre> * Where "s" indicates the size of the checksum. * <p> * As always, this is preceeded by a GSSHeader. * * @author Mayank Upadhyay * @author Ram Marti * @see sun.security.jgss.GSSHeader */ abstract class MessageToken extends Krb5Token { /* Fields in header minus checksum size */ private static final int TOKEN_NO_CKSUM_SIZE = 16; /** * Filler data as defined in the specification of the Kerberos v5 GSS-API * Mechanism. */ private static final int FILLER = 0xffff; // Signing algorithm values (for the SNG_ALG field) // From RFC 1964 /* Use a DES MAC MD5 checksum */ static final int SGN_ALG_DES_MAC_MD5 = 0x0000; /* Use DES MAC checksum. */ static final int SGN_ALG_DES_MAC = 0x0200; // From draft-raeburn-cat-gssapi-krb5-3des-00 /* Use a HMAC SHA1 DES3 -KD checksum */ static final int SGN_ALG_HMAC_SHA1_DES3_KD = 0x0400; // Sealing algorithm values (for the SEAL_ALG field) // RFC 1964 /** * A value for the SEAL_ALG field that indicates that no encryption was * used. */ static final int SEAL_ALG_NONE = 0xffff; /* Use DES CBC encryption algorithm. */ static final int SEAL_ALG_DES = 0x0000; // From draft-raeburn-cat-gssapi-krb5-3des-00 /** * Use DES3-KD sealing algorithm. (draft-raeburn-cat-gssapi-krb5-3des-00) * This algorithm uses triple-DES with key derivation, with a usage * value KG_USAGE_SEAL. Padding is still to 8-byte multiples, and the * IV for encrypting application data is zero. */ static final int SEAL_ALG_DES3_KD = 0x0200; // draft draft-brezak-win2k-krb-rc4-hmac-04.txt static final int SEAL_ALG_ARCFOUR_HMAC = 0x1000; static final int SGN_ALG_HMAC_MD5_ARCFOUR = 0x1100; private static final int TOKEN_ID_POS = 0; private static final int SIGN_ALG_POS = 2; private static final int SEAL_ALG_POS = 4; private int seqNumber; private boolean confState = true; private boolean initiator = true; private int tokenId = 0; private GSSHeader gssHeader = null; private MessageTokenHeader tokenHeader = null; private byte[] checksum = null; private byte[] encSeqNumber = null; private byte[] seqNumberData = null; /* cipher instance used by the corresponding GSSContext */ CipherHelper cipherHelper = null; /** * Constructs a MessageToken from a byte array. If there are more bytes * in the array than needed, the extra bytes are simply ignroed. * * @param tokenId the token id that should be contained in this token as * it is read. * @param context the Kerberos context associated with this token * @param tokenBytes the byte array containing the token * @param tokenOffset the offset where the token begins * @param tokenLen the length of the token * @param prop the MessageProp structure in which the properties of the * token should be stored. * @throws GSSException if there is a problem parsing the token */ MessageToken(int tokenId, Krb5Context context, byte[] tokenBytes, int tokenOffset, int tokenLen, MessageProp prop) throws GSSException { this(tokenId, context, new ByteArrayInputStream(tokenBytes, tokenOffset, tokenLen), prop); } /** * Constructs a MessageToken from an InputStream. Bytes will be read on * demand and the thread might block if there are not enough bytes to * complete the token. * * @param tokenId the token id that should be contained in this token as * it is read. * @param context the Kerberos context associated with this token * @param is the InputStream from which to read * @param prop the MessageProp structure in which the properties of the * token should be stored. * @throws GSSException if there is a problem reading from the * InputStream or parsing the token */ MessageToken(int tokenId, Krb5Context context, InputStream is, MessageProp prop) throws GSSException { init(tokenId, context); try { gssHeader = new GSSHeader(is); if (!gssHeader.getOid().equals((Object)OID)) { throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1, getTokenName(tokenId)); } if (!confState) { prop.setPrivacy(false); } tokenHeader = new MessageTokenHeader(is, prop); encSeqNumber = new byte[8]; readFully(is, encSeqNumber); // debug("\n\tRead EncSeq#=" + // getHexBytes(encSeqNumber, encSeqNumber.length)); checksum = new byte[cipherHelper.getChecksumLength()]; readFully(is, checksum); // debug("\n\tRead checksum=" + // getHexBytes(checksum, checksum.length)); // debug("\nLeaving MessageToken.Cons\n"); } catch (IOException e) { throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1, getTokenName(tokenId) + ":" + e.getMessage()); } } /** * Used to obtain the GSSHeader that was at the start of this * token. */ public final GSSHeader getGSSHeader() { return gssHeader; } /** * Used to obtain the token id that was contained in this token. * @return the token id in the token */ public final int getTokenId() { return tokenId; } /** * Used to obtain the encrypted sequence number in this token. * @return the encrypted sequence number in the token */ public final byte[] getEncSeqNumber() { return encSeqNumber; } /** * Used to obtain the checksum that was contained in this token. * @return the checksum in the token */ public final byte[] getChecksum() { return checksum; } /** * Used to determine if this token contains any encrypted data. * @return true if it contains any encrypted data, false if there is only * plaintext data or if there is no data. */ public final boolean getConfState() { return confState; } /** * Generates the checksum field and the encrypted sequence number * field. The encrypted sequence number uses the 8 bytes of the checksum * as an initial vector in a fixed DesCbc algorithm. * * @param prop the MessageProp structure that determines what sort of * checksum and sealing algorithm should be used. The lower byte * of qop determines the checksum algorithm while the upper byte * determines the signing algorithm. * Checksum values are: * 0 - default (DES_MAC) * 1 - MD5 * 2 - DES_MD5 * 3 - DES_MAC * 4 - HMAC_SHA1 * Sealing values are: * 0 - default (DES) * 1 - DES * 2 - DES3-KD * * @param optionalHeader an optional header that will be processed first * during checksum calculation * * @param data the application data to checksum * @param offset the offset where the data starts * @param len the length of the data * * @param optionalTrailer an optional trailer that will be processed * last during checksum calculation. e.g., padding that should be * appended to the application data * * @throws GSSException if an error occurs in the checksum calculation or * encryption sequence number calculation. */ public void genSignAndSeqNumber(MessageProp prop, byte[] optionalHeader, byte[] data, int offset, int len, byte[] optionalTrailer) throws GSSException { // debug("Inside MessageToken.genSignAndSeqNumber:\n"); int qop = prop.getQOP(); if (qop != 0) { qop = 0; prop.setQOP(qop); } if (!confState) { prop.setPrivacy(false); } // Create a token header with the correct sign and seal algorithm // values. tokenHeader = new MessageTokenHeader(tokenId, prop.getPrivacy(), qop); // Calculate SGN_CKSUM checksum = getChecksum(optionalHeader, data, offset, len, optionalTrailer); // debug("\n\tCalc checksum=" + // getHexBytes(checksum, checksum.length)); // Calculate SND_SEQ seqNumberData = new byte[8]; // When using this RC4 based encryption type, the sequence number is // always sent in big-endian rather than little-endian order. if (cipherHelper.isArcFour()) { writeBigEndian(seqNumber, seqNumberData); } else { // for all other etypes writeLittleEndian(seqNumber, seqNumberData); } if (!initiator) { seqNumberData[4] = (byte)0xff; seqNumberData[5] = (byte)0xff; seqNumberData[6] = (byte)0xff; seqNumberData[7] = (byte)0xff; } encSeqNumber = cipherHelper.encryptSeq(checksum, seqNumberData, 0, 8); // debug("\n\tCalc seqNum=" + // getHexBytes(seqNumberData, seqNumberData.length)); // debug("\n\tCalc encSeqNum=" + // getHexBytes(encSeqNumber, encSeqNumber.length)); } /** * Verifies that the checksum field and sequence number direction bytes * are valid and consistent with the application data. * * @param optionalHeader an optional header that will be processed first * during checksum calculation. * * @param data the application data * @param offset the offset where the data begins * @param len the length of the application data * * @param optionalTrailer an optional trailer that will be processed last * during checksum calculation. e.g., padding that should be appended to * the application data * * @throws GSSException if an error occurs in the checksum calculation or * encryption sequence number calculation. */ public final boolean verifySignAndSeqNumber(byte[] optionalHeader, byte[] data, int offset, int len, byte[] optionalTrailer) throws GSSException { // debug("\tIn verifySign:\n"); // debug("\t\tchecksum: [" + getHexBytes(checksum) + "]\n"); byte[] myChecksum = getChecksum(optionalHeader, data, offset, len, optionalTrailer); // debug("\t\tmychecksum: [" + getHexBytes(myChecksum) +"]\n"); // debug("\t\tchecksum: [" + getHexBytes(checksum) + "]\n"); if (MessageDigest.isEqual(checksum, myChecksum)) { seqNumberData = cipherHelper.decryptSeq( checksum, encSeqNumber, 0, 8); // debug("\t\tencSeqNumber: [" + getHexBytes(encSeqNumber) // + "]\n"); // debug("\t\tseqNumberData: [" + getHexBytes(seqNumberData) // + "]\n"); /* * The token from the initiator has direction bytes 0x00 and * the token from the acceptor has direction bytes 0xff. */ byte directionByte = 0; if (initiator) directionByte = (byte) 0xff; // Received token from acceptor if ((seqNumberData[4] == directionByte) && (seqNumberData[5] == directionByte) && (seqNumberData[6] == directionByte) && (seqNumberData[7] == directionByte)) return true; } return false; } public final int getSequenceNumber() { int sequenceNum = 0; if (cipherHelper.isArcFour()) { sequenceNum = readBigEndian(seqNumberData, 0, 4); } else { sequenceNum = readLittleEndian(seqNumberData, 0, 4); } return sequenceNum; } /** * Computes the checksum based on the algorithm stored in the * tokenHeader. * * @param optionalHeader an optional header that will be processed first * during checksum calculation. * * @param data the application data * @param offset the offset where the data begins * @param len the length of the application data * * @param optionalTrailer an optional trailer that will be processed last * during checksum calculation. e.g., padding that should be appended to * the application data * * @throws GSSException if an error occurs in the checksum calculation. */ private byte[] getChecksum(byte[] optionalHeader, byte[] data, int offset, int len, byte[] optionalTrailer) throws GSSException { // debug("Will do getChecksum:\n"); /* * For checksum calculation the token header bytes i.e., the first 8 * bytes following the GSSHeader, are logically prepended to the * application data to bind the data to this particular token. * * Note: There is no such requirement wrt adding padding to the * application data for checksumming, although the cryptographic * algorithm used might itself apply some padding. */ byte[] tokenHeaderBytes = tokenHeader.getBytes(); byte[] existingHeader = optionalHeader; byte[] checksumDataHeader = tokenHeaderBytes; if (existingHeader != null) { checksumDataHeader = new byte[tokenHeaderBytes.length + existingHeader.length]; System.arraycopy(tokenHeaderBytes, 0, checksumDataHeader, 0, tokenHeaderBytes.length); System.arraycopy(existingHeader, 0, checksumDataHeader, tokenHeaderBytes.length, existingHeader.length); } return cipherHelper.calculateChecksum(tokenHeader.getSignAlg(), checksumDataHeader, optionalTrailer, data, offset, len, tokenId); } /** * Constructs an empty MessageToken for the local context to send to * the peer. It also increments the local sequence number in the * Krb5Context instance it uses after obtaining the object lock for * it. * * @param tokenId the token id that should be contained in this token * @param context the Kerberos context associated with this token */ MessageToken(int tokenId, Krb5Context context) throws GSSException { /* debug("\n============================"); debug("\nMySessionKey=" + getHexBytes(context.getMySessionKey().getBytes())); debug("\nPeerSessionKey=" + getHexBytes(context.getPeerSessionKey().getBytes())); debug("\n============================\n"); */ init(tokenId, context); this.seqNumber = context.incrementMySequenceNumber(); } private void init(int tokenId, Krb5Context context) throws GSSException { this.tokenId = tokenId; // Just for consistency check in Wrap this.confState = context.getConfState(); this.initiator = context.isInitiator(); this.cipherHelper = context.getCipherHelper(null); // debug("In MessageToken.Cons"); } /** * Encodes a GSSHeader and this token onto an OutputStream. * * @param os the OutputStream to which this should be written * @throws GSSException if an error occurs while writing to the OutputStream */ public void encode(OutputStream os) throws IOException, GSSException { gssHeader = new GSSHeader(OID, getKrb5TokenSize()); gssHeader.encode(os); tokenHeader.encode(os); // debug("Writing seqNumber: " + getHexBytes(encSeqNumber)); os.write(encSeqNumber); // debug("Writing checksum: " + getHexBytes(checksum)); os.write(checksum); } /** * Obtains the size of this token. Note that this excludes the size of * the GSSHeader. * @return token size */ protected int getKrb5TokenSize() throws GSSException { return getTokenSize(); } protected final int getTokenSize() throws GSSException { return TOKEN_NO_CKSUM_SIZE + cipherHelper.getChecksumLength(); } protected static final int getTokenSize(CipherHelper ch) throws GSSException { return TOKEN_NO_CKSUM_SIZE + ch.getChecksumLength(); } /** * Obtains the conext key that is associated with this token. * @return the context key */ /* public final byte[] getContextKey() { return contextKey; } */ /** * Obtains the encryption algorithm that should be used in this token * given the state of confidentiality the application requested. * Requested qop must be consistent with negotiated session key. * @param confRequested true if the application desired confidentiality * on this token, false otherwise * @param qop the qop requested by the application * @throws GSSException if qop is incompatible with the negotiated * session key */ protected abstract int getSealAlg(boolean confRequested, int qop) throws GSSException; // ******************************************* // // I N N E R C L A S S E S F O L L O W // ******************************************* // /** * This inner class represents the initial portion of the message token * and contains information about the checksum and encryption algorithms * that are in use. It constitutes the first 8 bytes of the * message token: * <pre> * 0..1 TOK_ID Identification field. * 01 01 - Mic token * 02 01 - Wrap token * 2..3 SGN_ALG Checksum algorithm indicator. * 00 00 - DES MAC MD5 * 01 00 - MD2.5 * 02 00 - DES MAC * 04 00 - HMAC SHA1 DES3-KD * 11 00 - RC4-HMAC * 4..5 SEAL_ALG ff ff - none * 00 00 - DES * 02 00 - DES3-KD * 10 00 - RC4-HMAC * 6..7 Filler Contains ff ff * </pre> */ class MessageTokenHeader { private int tokenId; private int signAlg; private int sealAlg; private byte[] bytes = new byte[8]; /** * Constructs a MessageTokenHeader for the specified token type with * appropriate checksum and encryption algorithms fields. * * @param tokenId the token id for this mesage token * @param conf true if confidentiality will be resuested with this * message token, false otherwise. * @param qop the value of the quality of protection that will be * desired. */ public MessageTokenHeader(int tokenId, boolean conf, int qop) throws GSSException { this.tokenId = tokenId; signAlg = MessageToken.this.getSgnAlg(qop); sealAlg = MessageToken.this.getSealAlg(conf, qop); bytes[0] = (byte) (tokenId >>> 8); bytes[1] = (byte) (tokenId); bytes[2] = (byte) (signAlg >>> 8); bytes[3] = (byte) (signAlg); bytes[4] = (byte) (sealAlg >>> 8); bytes[5] = (byte) (sealAlg); bytes[6] = (byte) (MessageToken.FILLER >>> 8); bytes[7] = (byte) (MessageToken.FILLER); } /** * Constructs a MessageTokenHeader by reading it from an InputStream * and sets the appropriate confidentiality and quality of protection * values in a MessageProp structure. * * @param is the InputStream to read from * @param prop the MessageProp to populate * @throws IOException is an error occurs while reading from the * InputStream */ public MessageTokenHeader(InputStream is, MessageProp prop) throws IOException { readFully(is, bytes); tokenId = readInt(bytes, TOKEN_ID_POS); signAlg = readInt(bytes, SIGN_ALG_POS); sealAlg = readInt(bytes, SEAL_ALG_POS); // debug("\nMessageTokenHeader read tokenId=" + // getHexBytes(bytes) + "\n"); // XXX compare to FILLER int temp = readInt(bytes, SEAL_ALG_POS + 2); // debug("SIGN_ALG=" + signAlg); switch (sealAlg) { case SEAL_ALG_DES: case SEAL_ALG_DES3_KD: case SEAL_ALG_ARCFOUR_HMAC: prop.setPrivacy(true); break; default: prop.setPrivacy(false); } prop.setQOP(0); // default } /** * Encodes this MessageTokenHeader onto an OutputStream * @param os the OutputStream to write to * @throws IOException is an error occurs while writing */ public final void encode(OutputStream os) throws IOException { os.write(bytes); } /** * Returns the token id for the message token. * @return the token id * @see sun.security.jgss.krb5.Krb5Token#MIC_ID * @see sun.security.jgss.krb5.Krb5Token#WRAP_ID */ public final int getTokenId() { return tokenId; } /** * Returns the sign algorithm for the message token. * @return the sign algorithm * @see sun.security.jgss.krb5.MessageToken#SIGN_DES_MAC * @see sun.security.jgss.krb5.MessageToken#SIGN_DES_MAC_MD5 */ public final int getSignAlg() { return signAlg; } /** * Returns the seal algorithm for the message token. * @return the seal algorithm * @see sun.security.jgss.krb5.MessageToken#SEAL_ALG_DES * @see sun.security.jgss.krb5.MessageToken#SEAL_ALG_NONE */ public final int getSealAlg() { return sealAlg; } /** * Returns the bytes of this header. * @return 8 bytes that form this header */ public final byte[] getBytes() { return bytes; } } // end of class MessageTokenHeader /** * Determine signing algorithm based on QOP. */ protected int getSgnAlg(int qop) throws GSSException { // QOP ignored return cipherHelper.getSgnAlg(); } }
gpl-2.0
SDX2000/freeplane
freeplane/src/org/freeplane/features/ui/ToggleMenubarAction.java
1723
/* * Freeplane - mind map editor * Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev * * This file is modified by Dimitry Polivaev in 2008. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.freeplane.features.ui; import java.awt.event.ActionEvent; import org.freeplane.core.ui.AFreeplaneAction; import org.freeplane.core.ui.SelectableAction; @SelectableAction(checkOnPopup = true) class ToggleMenubarAction extends AFreeplaneAction { static final String NAME = "toggleMenubar"; /** * */ private static final long serialVersionUID = 1L; final private ViewController controller; ToggleMenubarAction( final ViewController viewController) { super("ToggleMenubarAction"); this.controller = viewController; } public void actionPerformed(final ActionEvent event) { controller.setMenubarVisible(!controller.isMenubarVisible()); } @Override public void setSelected() { setSelected(controller.isMenubarVisible()); } @Override public void afterMapChange(final Object newMap) { } }
gpl-2.0
formeppe/NewAge-JGrass
hortonmachine/src/main/java/org/jgrasstools/hortonmachine/modules/statistics/kerneldensity/OmsKernelDensity.java
7215
/* * This file is part of JGrasstools (http://www.jgrasstools.org) * (C) HydroloGIS - www.hydrologis.com * * JGrasstools is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jgrasstools.hortonmachine.modules.statistics.kerneldensity; import static org.jgrasstools.gears.libs.modules.JGTConstants.isNovalue; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSKERNELDENSITY_AUTHORCONTACTS; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSKERNELDENSITY_AUTHORNAMES; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSKERNELDENSITY_DESCRIPTION; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSKERNELDENSITY_KEYWORDS; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSKERNELDENSITY_LABEL; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSKERNELDENSITY_LICENSE; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSKERNELDENSITY_NAME; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSKERNELDENSITY_STATUS; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSKERNELDENSITY_doConstant_DESCRIPTION; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSKERNELDENSITY_inMap_DESCRIPTION; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSKERNELDENSITY_outDensity_DESCRIPTION; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSKERNELDENSITY_pKernel_DESCRIPTION; import static org.jgrasstools.hortonmachine.i18n.HortonMessages.OMSKERNELDENSITY_pRadius_DESCRIPTION; import java.awt.image.RenderedImage; import java.awt.image.WritableRaster; import javax.media.jai.KernelJAI; import javax.media.jai.iterator.RandomIter; import javax.media.jai.iterator.RandomIterFactory; import javax.media.jai.iterator.WritableRandomIter; import oms3.annotations.Author; import oms3.annotations.Description; import oms3.annotations.Execute; import oms3.annotations.In; import oms3.annotations.Keywords; import oms3.annotations.Label; import oms3.annotations.License; import oms3.annotations.Name; import oms3.annotations.Out; import oms3.annotations.Status; import org.geotools.coverage.grid.GridCoverage2D; import org.jaitools.media.jai.kernel.KernelFactory; import org.jaitools.media.jai.kernel.KernelFactory.ValueType; import org.jgrasstools.gears.libs.modules.JGTConstants; import org.jgrasstools.gears.libs.modules.JGTModel; import org.jgrasstools.gears.utils.RegionMap; import org.jgrasstools.gears.utils.coverage.CoverageUtilities; @Description(OMSKERNELDENSITY_DESCRIPTION) @Author(name = OMSKERNELDENSITY_AUTHORNAMES, contact = OMSKERNELDENSITY_AUTHORCONTACTS) @Keywords(OMSKERNELDENSITY_KEYWORDS) @Label(OMSKERNELDENSITY_LABEL) @Name(OMSKERNELDENSITY_NAME) @Status(OMSKERNELDENSITY_STATUS) @License(OMSKERNELDENSITY_LICENSE) public class OmsKernelDensity extends JGTModel { @Description(OMSKERNELDENSITY_inMap_DESCRIPTION) @In public GridCoverage2D inMap = null; @Description(OMSKERNELDENSITY_pKernel_DESCRIPTION) @In public int pKernel = 3; @Description(OMSKERNELDENSITY_pRadius_DESCRIPTION) @In public int pRadius = 10; @Description(OMSKERNELDENSITY_doConstant_DESCRIPTION) @In public boolean doConstant = false; @Description(OMSKERNELDENSITY_outDensity_DESCRIPTION) @Out public GridCoverage2D outDensity = null; @SuppressWarnings("nls") @Execute public void process() throws Exception { checkNull(inMap); RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inMap); int cols = regionMap.getCols(); int rows = regionMap.getRows(); ValueType type = KernelFactory.ValueType.EPANECHNIKOV; switch( pKernel ) { case 0: type = KernelFactory.ValueType.BINARY; break; case 1: type = KernelFactory.ValueType.COSINE; break; case 2: type = KernelFactory.ValueType.DISTANCE; break; case 4: type = KernelFactory.ValueType.GAUSSIAN; break; case 5: type = KernelFactory.ValueType.INVERSE_DISTANCE; break; case 6: type = KernelFactory.ValueType.QUARTIC; break; case 7: type = KernelFactory.ValueType.TRIANGULAR; break; case 8: type = KernelFactory.ValueType.TRIWEIGHT; break; } KernelJAI kernel = KernelFactory.createCircle(pRadius, type); RenderedImage inImg = inMap.getRenderedImage(); RandomIter inIter = RandomIterFactory.create(inImg, null); WritableRaster outWR = CoverageUtilities.createDoubleWritableRaster(cols, rows, null, null, JGTConstants.doubleNovalue); WritableRandomIter outIter = RandomIterFactory.createWritable(outWR, null); float[] kernelData = kernel.getKernelData(); pm.beginTask("Estimating kernel density...", cols - 2 * pRadius); for( int c = pRadius; c < cols - pRadius; c++ ) { for( int r = pRadius; r < rows - pRadius; r++ ) { double inputValue = inIter.getSampleDouble(c, r, 0); if (isNovalue(inputValue)) { continue; } if (doConstant) inputValue = 1.0; int k = 0; for( int kc = -pRadius; kc <= pRadius; kc++ ) { for( int kr = -pRadius; kr <= pRadius; kr++, k++ ) { // data[gridCoords.y + j][gridCoords.x + i] += cdata[k] * centreValue; double outputValue = outIter.getSampleDouble(c + kc, r + kr, 0); if (isNovalue(outputValue)) { outputValue = 0; } outputValue = outputValue + kernelData[k] * inputValue; outIter.setSample(c + kc, r + kr, 0, outputValue); } } } pm.worked(1); } pm.done(); pm.beginTask("Finalizing...", cols); for( int c = 0; c < cols; c++ ) { for( int r = 0; r < rows; r++ ) { double outputValue = outIter.getSampleDouble(c, r, 0); if (isNovalue(outputValue)) { outIter.setSample(c, r, 0, 0.0); } } pm.worked(1); } pm.done(); outDensity = CoverageUtilities.buildCoverage("kerneldensity", outWR, regionMap, inMap.getCoordinateReferenceSystem()); } }
gpl-2.0
klst-com/metasfresh
de.metas.payment.sepa/src/main/java/de/metas/payment/sepa/api/impl/BBANStructureEntryBuilder.java
2507
/** * */ package de.metas.payment.sepa.api.impl; /* * #%L * de.metas.payment.sepa * %% * Copyright (C) 2015 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import de.metas.payment.sepa.api.IBBANStructureBuilder; import de.metas.payment.sepa.api.IBBANStructureEntryBuilder; import de.metas.payment.sepa.wrapper.BBANStructure; import de.metas.payment.sepa.wrapper.BBANStructureEntry; import de.metas.payment.sepa.wrapper.BBANStructureEntry.BBANCodeEntryType; import de.metas.payment.sepa.wrapper.BBANStructureEntry.EntryCharacterType; /** * @author cg * */ public class BBANStructureEntryBuilder implements IBBANStructureEntryBuilder { private BBANCodeEntryType codeType; private EntryCharacterType characterType; private int length; private String seqNo; private IBBANStructureBuilder parent; private BBANStructureEntry entry; public BBANStructureEntryBuilder(BBANStructureBuilder parent) { this.parent = parent; entry = new BBANStructureEntry(); } @Override public BBANStructureEntry create() { entry.setCharacterType(characterType); entry.setCodeType(codeType); entry.setLength(length); entry.setSeqNo(seqNo); return entry; } @Override public IBBANStructureEntryBuilder setCodeType(BBANCodeEntryType codeType) { this.codeType = codeType; return this; } @Override public IBBANStructureEntryBuilder setCharacterType(EntryCharacterType characterType) { this.characterType = characterType; return this; } @Override public IBBANStructureEntryBuilder setLength(int length) { this.length = length; return this; } @Override public IBBANStructureEntryBuilder setSeqNo(String seqNo) { this.seqNo = seqNo; return this; } public void create(BBANStructure _BBANStructure) { _BBANStructure.addEntry(entry); } public final IBBANStructureBuilder getParent() { return parent; } }
gpl-2.0
oscarservice/oscar-old
src/main/java/org/oscarehr/decisionSupport/web/TestActionW.java
2322
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.oscarehr.decisionSupport.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.oscarehr.decisionSupport.service.DSService; import org.oscarehr.util.MiscUtils; /** * * @author apavel */ public class TestActionW extends Action { private static Logger log = MiscUtils.getLogger(); private DSService dsService; public TestActionW() { } public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String demographic_no = request.getParameter("demographic_no"); if (demographic_no == null) demographic_no = "1"; response.getWriter().println(dsService.evaluateAndGetConsequences(demographic_no, (String) request.getSession().getAttribute("user"))); return null; } public void setDsService(DSService dsService) { this.dsService = dsService; } }
gpl-2.0
akipta/freedomotic
clients/freedomotic-gwt/src/com/furiousbob/jms/client/ConnectionCallback.java
496
package com.furiousbob.jms.client; /** * * @author Vinicius Carvalho * */ public interface ConnectionCallback { /** * Called on connection to the JMS broker */ void onConnect(); /** * Called on an error or disconnection from the broker * * @param cause - the reason behind the error */ void onError(String cause); /** * Called on a disconnection initiated from the client */ void onDisconnect(); }
gpl-2.0
mohlerm/hotspot_cached_profiles
test/compiler/compilercontrol/share/pool/MethodHolder.java
4573
/* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package pool; import jdk.test.lib.Pair; import java.lang.reflect.Executable; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; /** * Represents a holder that contains test methods */ public abstract class MethodHolder { /** * Helper method to get executable for the specified method * * @param holder class that holds specified method * @param name method name * @param parameterTypes parameter types of the specified method * @return {@link Method} instance */ public Method getMethod(MethodHolder holder, String name, Class<?>... parameterTypes) { try { return holder.getClass().getDeclaredMethod(name, parameterTypes); } catch (NoSuchMethodException e) { throw new Error("TESTBUG: Can't get method " + name, e); } } /** * Gets all test methods * * @return pairs of Executable and appropriate Callable */ public List<Pair<Executable, Callable<?>>> getAllMethods() { Class<?> aClass = this.getClass(); Object classInstance; try { classInstance = aClass.newInstance(); } catch (ReflectiveOperationException e) { throw new Error("TESTBUG: unable to get new instance", e); } List<Pair<Executable, Callable<?>>> pairs = new ArrayList<>(); { Method method = getMethod(this, "method", int.class, String[].class, Integer.class, byte[].class, double[][].class); Pair<Executable, Callable<?>> pair = new Pair<>(method, () -> { // Make args int a = 0; String[] ss = {"a", "b", "c", "d"}; Integer i = 1; byte[] bb = {1, 2}; double[][] dd = { {1.618033, 3.141592}, {2.718281, 0.007874} }; // Invoke method method.invoke(classInstance, a, ss, i, bb, dd); return true; }); pairs.add(pair); } { Method method = getMethod(this, "method"); Pair<Executable, Callable<?>> pair = new Pair<>(method, () -> { method.invoke(classInstance); return true; }); pairs.add(pair); } { Method method = getMethod(this, "smethod"); Pair<Executable, Callable<?>> pair = new Pair<>(method, () -> method.invoke(classInstance)); pairs.add(pair); } { Method method = getMethod(this, "smethod", int.class, int[].class); Pair<Executable, Callable<?>> pair = new Pair<>(method, () -> { int[] array = {1, 2, 3}; return method.invoke(classInstance, 42, array); }); pairs.add(pair); } { Method method = getMethod(this, "smethod", Integer.class); Pair<Executable, Callable<?>> pair = new Pair<>(method, () -> method.invoke(classInstance, 100)); pairs.add(pair); } return pairs; } }
gpl-2.0
arodchen/MaxSim
maxine/com.oracle.max.vm/src/com/sun/max/vm/heap/gcx/OutgoingReferenceChecker.java
3961
/* * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.max.vm.heap.gcx; import static com.sun.max.vm.heap.gcx.HeapFreeChunk.*; import com.sun.max.unsafe.*; import com.sun.max.vm.*; import com.sun.max.vm.actor.holder.*; import com.sun.max.vm.heap.*; import com.sun.max.vm.layout.*; /** * A simple tool that counts (and print to the log) references that escapes a particular heap account. * References to the boot image aren't counted as escaping. * The tools is currently used to verify that no references escape the {@link HeapRegionManager}'s heap account. */ class OutgoingReferenceChecker extends PointerIndexVisitor implements CellVisitor { private final Object accountOwner; private final RegionTable regionTable; private long outgoingReferenceCount = 0L; /** * @param heapAccount */ OutgoingReferenceChecker(HeapAccount<?> heapAccount) { accountOwner = heapAccount.owner(); regionTable = RegionTable.theRegionTable(); } void reset() { outgoingReferenceCount = 0L; } private void checkReference(Pointer refHolder, int wordIndex) { Pointer cell = refHolder.getReference(wordIndex).toOrigin(); if (!cell.isZero()) { final HeapRegionInfo rinfo = regionTable.regionInfo(cell); if (rinfo.owner() != accountOwner && !Heap.bootHeapRegion.contains(cell)) { Log.print("outgoing ref: "); Log.print(refHolder); Log.print(" [ "); Log.print(wordIndex); Log.print(" ] = "); Log.println(cell); outgoingReferenceCount++; } } } @Override public Pointer visitCell(Pointer cell) { final Pointer origin = Layout.cellToOrigin(cell); final Hub hub = Layout.getHub(origin); if (hub == heapFreeChunkHub()) { return cell.plus(toHeapFreeChunk(origin).size); } checkReference(origin, Layout.hubIndex()); final SpecificLayout specificLayout = hub.specificLayout; if (specificLayout.isTupleLayout()) { TupleReferenceMap.visitReferences(hub, origin, this); return cell.plus(hub.tupleSize); } else if (specificLayout.isHybridLayout()) { TupleReferenceMap.visitReferences(hub, origin, this); } else if (specificLayout.isReferenceArrayLayout()) { final int length = Layout.firstElementIndex() + Layout.readArrayLength(origin); for (int index = Layout.firstElementIndex(); index < length; index++) { checkReference(origin, index); } } Size size = Layout.size(origin); return cell.plus(size); } @Override public void visit(Pointer pointer, int wordIndex) { checkReference(pointer, wordIndex); } public long outgoingReferenceCount() { return outgoingReferenceCount; } }
gpl-2.0
creechy/henplus
src/henplus/commands/properties/PropertyCommand.java
2322
/* * This is free software, licensed under the Gnu Public License (GPL) get a copy from <http://www.gnu.org/licenses/gpl.html> $Id: * PropertyCommand.java,v 1.4 2005-11-27 16:20:28 hzeller Exp $ author: Henner Zeller <H.Zeller@acm.org> */ package henplus.commands.properties; import henplus.HenPlus; import henplus.PropertyRegistry; import henplus.io.ConfigurationContainer; import henplus.property.PropertyHolder; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * Set global HenPlus properties. */ public class PropertyCommand extends AbstractPropertyCommand { private static final String SETTINGS_FILENAME = "properties"; private final HenPlus _henplus; private final PropertyRegistry _registry; private final ConfigurationContainer _config; public PropertyCommand(final HenPlus henplus, final PropertyRegistry registry) { _henplus = henplus; _registry = registry; _config = _henplus.createConfigurationContainer(SETTINGS_FILENAME); } @Override protected String getSetCommand() { return "set-property"; } @Override protected String getHelpHeader() { return "global HenPlus"; } @Override protected PropertyRegistry getRegistry() { return _registry; } @Override public boolean requiresValidSession(final String cmd) { return false; } public void load() { final Map<String,String> props = _config.readProperties(); for (Entry<String,String> entry : props.entrySet()) { try { _registry.setProperty(entry.getKey(), entry.getValue()); } catch (final Exception e) { // don't care. silently ignore errornous entries. } } } @Override public void shutdown() { final Map<String,String> writeMap = new HashMap<String,String>(); for (Map.Entry<String, PropertyHolder> entry : _registry.getPropertyMap().entrySet()) { final PropertyHolder holder = entry.getValue(); writeMap.put(entry.getKey(), holder.getValue()); } _config.storeProperties(writeMap, true, "user properties"); } } /* * Local variables: c-basic-offset: 4 compile-command: * "ant -emacs -find build.xml" End: */
gpl-2.0
bjorn/tiled-java
src/tiled/mapeditor/util/TileSelectionListener.java
659
/* * Tiled Map Editor, (c) 2004-2006 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Adam Turk <aturk@biggeruniverse.com> * Bjorn Lindeijer <bjorn@lindeijer.nl> */ package tiled.mapeditor.util; import java.util.EventListener; /** * @version $Id$ */ public interface TileSelectionListener extends EventListener { public void tileSelected(TileSelectionEvent e); public void tileRegionSelected(TileRegionSelectionEvent e); }
gpl-2.0
dc914337/PSD
PSD/app/src/main/java/anon/psd/models/HistoryList.java
508
package anon.psd.models; import java.util.ArrayList; import java.util.Date; import anon.psd.models.gui.PrettyDate; /** * Created by Dmitry on 24.07.2015. */ public class HistoryList extends ArrayList<PrettyDate> { public Date getLastDate() { if (this.size() == 0) return null; Date lastDate = this.get(0); for (Date currDate : this) { if (currDate.after(lastDate)) lastDate = currDate; } return lastDate; } }
gpl-2.0
mur47x111/GraalVM
graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/calc/UnsignedDivNode.java
3383
/* * Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.nodes.calc; import jdk.internal.jvmci.code.*; import com.oracle.graal.compiler.common.type.*; import com.oracle.graal.graph.*; import com.oracle.graal.graph.spi.*; import com.oracle.graal.nodeinfo.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.spi.*; @NodeInfo(shortName = "|/|") public class UnsignedDivNode extends FixedBinaryNode implements Lowerable, LIRLowerable { public static final NodeClass<UnsignedDivNode> TYPE = NodeClass.create(UnsignedDivNode.class); public UnsignedDivNode(ValueNode x, ValueNode y) { this(TYPE, x, y); } protected UnsignedDivNode(NodeClass<? extends UnsignedDivNode> c, ValueNode x, ValueNode y) { super(c, x.stamp().unrestricted(), x, y); } @Override public ValueNode canonical(CanonicalizerTool tool, ValueNode forX, ValueNode forY) { int bits = ((IntegerStamp) stamp()).getBits(); if (forX.isConstant() && forY.isConstant()) { long yConst = CodeUtil.zeroExtend(forY.asJavaConstant().asLong(), bits); if (yConst == 0) { return this; // this will trap, cannot canonicalize } return ConstantNode.forIntegerStamp(stamp(), UnsignedMath.divide(CodeUtil.zeroExtend(forX.asJavaConstant().asLong(), bits), yConst)); } else if (forY.isConstant()) { long c = CodeUtil.zeroExtend(forY.asJavaConstant().asLong(), bits); if (c == 1) { return forX; } if (CodeUtil.isPowerOf2(c)) { return new UnsignedRightShiftNode(forX, ConstantNode.forInt(CodeUtil.log2(c))); } } return this; } @Override public void lower(LoweringTool tool) { tool.getLowerer().lower(this, tool); } @Override public void generate(NodeLIRBuilderTool gen) { gen.setResult(this, gen.getLIRGeneratorTool().emitUDiv(gen.operand(getX()), gen.operand(getY()), gen.state(this))); } @Override public boolean canDeoptimize() { return !(getY().stamp() instanceof IntegerStamp) || ((IntegerStamp) getY().stamp()).contains(0); } @NodeIntrinsic public static native int unsignedDivide(int a, int b); @NodeIntrinsic public static native long unsignedDivide(long a, long b); }
gpl-2.0
du-lab/mzmine2
src/main/java/net/sf/mzmine/modules/peaklistmethods/peakpicking/deconvolution/ResolvedPeak.java
11286
/* * Copyright 2006-2018 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 is free software; you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along with MZmine 2; if not, * write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package net.sf.mzmine.modules.peaklistmethods.peakpicking.deconvolution; import java.util.Arrays; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.google.common.collect.Range; import net.sf.mzmine.datamodel.DataPoint; import net.sf.mzmine.datamodel.Feature; import net.sf.mzmine.datamodel.IsotopePattern; import net.sf.mzmine.datamodel.RawDataFile; import net.sf.mzmine.datamodel.Scan; import net.sf.mzmine.datamodel.impl.SimpleDataPoint; import net.sf.mzmine.datamodel.impl.SimplePeakInformation; import net.sf.mzmine.util.PeakUtils; import net.sf.mzmine.util.maths.CenterFunction; import net.sf.mzmine.util.scans.ScanUtils; /** * ResolvedPeak * */ public class ResolvedPeak implements Feature { private SimplePeakInformation peakInfo; // Data file of this chromatogram private RawDataFile dataFile; // Chromatogram m/z, RT, height, area private double mz, rt, height, area; private Double fwhm = null, tf = null, af = null; // Scan numbers private int scanNumbers[]; // We store the values of data points as double[] arrays in order to save // memory, which would be wasted by keeping a lot of instances of // SimpleDataPoint (each instance takes 16 or 32 bytes of extra memory) private double dataPointMZValues[], dataPointIntensityValues[]; // Top intensity scan, fragment scan private int representativeScan, fragmentScan; // All MS2 fragment scan numbers private int[] allMS2FragmentScanNumbers; // Ranges of raw data points private Range<Double> rawDataPointsIntensityRange, rawDataPointsMZRange, rawDataPointsRTRange; // Isotope pattern. Null by default but can be set later by deisotoping // method. private IsotopePattern isotopePattern = null; private int charge = 0; // PeakListRow.ID of the chromatogram where this feature is detected. Null by default but can be // set by // chromatogram deconvolution method. private Integer parentChromatogramRowID = null; /** * Initializes this peak using data points from a given chromatogram - regionStart marks the index * of the first data point (inclusive), regionEnd marks the index of the last data point * (inclusive). The selected region MUST NOT contain any zero-intensity data points, otherwise * exception is thrown. */ public ResolvedPeak(Feature chromatogram, int regionStart, int regionEnd, CenterFunction mzCenterFunction, double msmsRange, double RTRangeMSMS) { assert regionEnd > regionStart; this.dataFile = chromatogram.getDataFile(); // Make an array of scan numbers of this peak scanNumbers = new int[regionEnd - regionStart + 1]; int chromatogramScanNumbers[] = chromatogram.getScanNumbers(); System.arraycopy(chromatogramScanNumbers, regionStart, scanNumbers, 0, regionEnd - regionStart + 1); dataPointMZValues = new double[regionEnd - regionStart + 1]; dataPointIntensityValues = new double[regionEnd - regionStart + 1]; // Set raw data point ranges, height, rt and representative scan height = Double.MIN_VALUE; double mzValue = chromatogram.getMZ(); for (int i = 0; i < scanNumbers.length; i++) { dataPointMZValues[i] = mzValue; DataPoint dp = chromatogram.getDataPoint(scanNumbers[i]); if (dp == null) { continue; /* * String error = * "Cannot create a resolved peak in a region with missing data points: chromatogram " + * chromatogram + " scans " + chromatogramScanNumbers[regionStart] + "-" + * chromatogramScanNumbers[regionEnd] + ", missing data point in scan " + scanNumbers[i]; * * throw new IllegalArgumentException(error); */ } dataPointMZValues[i] = dp.getMZ(); dataPointIntensityValues[i] = dp.getIntensity(); if (rawDataPointsIntensityRange == null) { rawDataPointsIntensityRange = Range.singleton(dp.getIntensity()); rawDataPointsRTRange = Range.singleton(dataFile.getScan(scanNumbers[i]).getRetentionTime()); rawDataPointsMZRange = Range.singleton(dp.getMZ()); } else { rawDataPointsRTRange = rawDataPointsRTRange .span(Range.singleton(dataFile.getScan(scanNumbers[i]).getRetentionTime())); rawDataPointsIntensityRange = rawDataPointsIntensityRange.span(Range.singleton(dp.getIntensity())); rawDataPointsMZRange = rawDataPointsMZRange.span(Range.singleton(dp.getMZ())); } if (height < dp.getIntensity()) { height = dp.getIntensity(); rt = dataFile.getScan(scanNumbers[i]).getRetentionTime(); representativeScan = scanNumbers[i]; } } // Calculate m/z as median, average or weighted-average mz = mzCenterFunction.calcCenter(dataPointMZValues, dataPointIntensityValues); // Update area area = 0; for (int i = 1; i < scanNumbers.length; i++) { // For area calculation, we use retention time in seconds double previousRT = dataFile.getScan(scanNumbers[i - 1]).getRetentionTime() * 60d; double currentRT = dataFile.getScan(scanNumbers[i]).getRetentionTime() * 60d; double previousHeight = dataPointIntensityValues[i - 1]; double currentHeight = dataPointIntensityValues[i]; area += (currentRT - previousRT) * (currentHeight + previousHeight) / 2; } // Update fragment scan double lowerBound = rawDataPointsMZRange.lowerEndpoint(); double upperBound = rawDataPointsMZRange.upperEndpoint(); double mid = (upperBound + lowerBound) / 2; lowerBound = mid - msmsRange / 2; upperBound = mid + msmsRange / 2; if (lowerBound < 0) { lowerBound = 0; } Range<Double> searchingRange = Range.closed(lowerBound, upperBound); double lowerBoundRT = rawDataPointsRTRange.lowerEndpoint(); double upperBoundRT = rawDataPointsRTRange.upperEndpoint(); double midRT = (upperBoundRT + lowerBoundRT) / 2; lowerBoundRT = midRT - RTRangeMSMS / 2; upperBoundRT = midRT + RTRangeMSMS / 2; if (lowerBound < 0) { lowerBound = 0; } Range<Double> searchingRangeRT = Range.closed(lowerBoundRT, upperBoundRT); if (msmsRange == 0) searchingRange = rawDataPointsMZRange; if (RTRangeMSMS == 0) searchingRangeRT = rawDataPointsRTRange; fragmentScan = ScanUtils.findBestFragmentScan(dataFile, searchingRangeRT, searchingRange); allMS2FragmentScanNumbers = ScanUtils.findAllMS2FragmentScans(dataFile, searchingRangeRT, searchingRange); if (fragmentScan > 0) { Scan fragmentScanObject = dataFile.getScan(fragmentScan); int precursorCharge = fragmentScanObject.getPrecursorCharge(); if (precursorCharge > 0) this.charge = precursorCharge; } } /** * This method returns a representative datapoint of this peak in a given scan */ @Override public DataPoint getDataPoint(int scanNumber) { int index = Arrays.binarySearch(scanNumbers, scanNumber); if (index < 0) return null; SimpleDataPoint dp = new SimpleDataPoint(dataPointMZValues[index], dataPointIntensityValues[index]); return dp; } /** * This method returns m/z value of the chromatogram */ @Override public double getMZ() { return mz; } /** * This method returns a string with the basic information that defines this peak * * @return String information */ @Override public String toString() { return PeakUtils.peakToString(this); } @Override public double getArea() { return area; } @Override public double getHeight() { return height; } @Override public int getMostIntenseFragmentScanNumber() { return fragmentScan; } @Override public int[] getAllMS2FragmentScanNumbers() { return allMS2FragmentScanNumbers; } @Override public @Nonnull FeatureStatus getFeatureStatus() { return FeatureStatus.DETECTED; } @Override public double getRT() { return rt; } @Override public @Nonnull Range<Double> getRawDataPointsIntensityRange() { return rawDataPointsIntensityRange; } @Override public @Nonnull Range<Double> getRawDataPointsMZRange() { return rawDataPointsMZRange; } @Override public @Nonnull Range<Double> getRawDataPointsRTRange() { return rawDataPointsRTRange; } @Override public int getRepresentativeScanNumber() { return representativeScan; } @Override public @Nonnull int[] getScanNumbers() { return scanNumbers; } @Override public @Nonnull RawDataFile getDataFile() { return dataFile; } @Override public IsotopePattern getIsotopePattern() { return isotopePattern; } @Override public void setIsotopePattern(@Nonnull IsotopePattern isotopePattern) { this.isotopePattern = isotopePattern; } @Override public int getCharge() { return charge; } @Override public void setCharge(int charge) { this.charge = charge; } @Override public Double getFWHM() { return fwhm; } @Override public void setFWHM(Double fwhm) { this.fwhm = fwhm; } @Override public Double getTailingFactor() { return tf; } @Override public void setTailingFactor(Double tf) { this.tf = tf; } @Override public Double getAsymmetryFactor() { return af; } @Override public void setAsymmetryFactor(Double af) { this.af = af; } // dulab Edit @Override public void outputChromToFile() { int nothing = -1; } @Override public void setPeakInformation(SimplePeakInformation peakInfoIn) { this.peakInfo = peakInfoIn; } @Override public SimplePeakInformation getPeakInformation() { return peakInfo; } // End dulab Edit public void setParentChromatogramRowID(@Nullable Integer id) { this.parentChromatogramRowID = id; } @Override @Nullable public Integer getParentChromatogramRowID() { return this.parentChromatogramRowID; } @Override public void setFragmentScanNumber(int fragmentScanNumber) { this.fragmentScan = fragmentScanNumber; } @Override public void setAllMS2FragmentScanNumbers(int[] allMS2FragmentScanNumbers) { this.allMS2FragmentScanNumbers = allMS2FragmentScanNumbers; // also set best scan by TIC int best = -1; double tic = 0; if (allMS2FragmentScanNumbers != null) { for (int i : allMS2FragmentScanNumbers) { if (tic < dataFile.getScan(i).getTIC()) best = i; } } setFragmentScanNumber(best); } }
gpl-2.0
VytautasBoznis/l2.skilas.lt
aCis_gameserver/java/net/sf/l2j/gameserver/datatables/HerbDropTable.java
3976
/* * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.l2j.gameserver.datatables; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import net.sf.l2j.gameserver.model.item.DropCategory; import net.sf.l2j.gameserver.model.item.DropData; import net.sf.l2j.gameserver.xmlfactory.XMLDocumentFactory; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; /** * This class loads herbs drop rules. */ public class HerbDropTable { private static Logger _log = Logger.getLogger(HerbDropTable.class.getName()); private final Map<Integer, List<DropCategory>> _herbGroups = new HashMap<>(); public static HerbDropTable getInstance() { return SingletonHolder._instance; } protected HerbDropTable() { try { File file = new File("./data/xml/herbs_droplist.xml"); Document doc = XMLDocumentFactory.getInstance().loadDocument(file); Node n = doc.getFirstChild(); for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) { if ("group".equalsIgnoreCase(d.getNodeName())) { NamedNodeMap attrs = d.getAttributes(); int groupId = Integer.parseInt(attrs.getNamedItem("id").getNodeValue()); List<DropCategory> category; if (_herbGroups.containsKey(groupId)) category = _herbGroups.get(groupId); else { category = new ArrayList<>(); _herbGroups.put(groupId, category); } for (Node cd = d.getFirstChild(); cd != null; cd = cd.getNextSibling()) { DropData dropDat = new DropData(); if ("item".equalsIgnoreCase(cd.getNodeName())) { attrs = cd.getAttributes(); int id = Integer.parseInt(attrs.getNamedItem("id").getNodeValue()); int categoryType = Integer.parseInt(attrs.getNamedItem("category").getNodeValue()); int chance = Integer.parseInt(attrs.getNamedItem("chance").getNodeValue()); dropDat.setItemId(id); dropDat.setMinDrop(1); dropDat.setMaxDrop(1); dropDat.setChance(chance); if (ItemTable.getInstance().getTemplate(dropDat.getItemId()) == null) { _log.warning("HerbDropTable: Herb data for undefined item template! GroupId: " + groupId + ", itemId: " + dropDat.getItemId()); continue; } boolean catExists = false; for (DropCategory cat : category) { // if the category exists, add the drop to this category. if (cat.getCategoryType() == categoryType) { cat.addDropData(dropDat, false); catExists = true; break; } } // if the category doesn't exit, create it and add the drop if (!catExists) { DropCategory cat = new DropCategory(categoryType); cat.addDropData(dropDat, false); category.add(cat); } } } } } } catch (Exception e) { _log.warning("HerbDropTable: Error while creating table: " + e); } _log.info("HerbDropTable: Loaded " + _herbGroups.size() + " herbs groups."); } public List<DropCategory> getHerbDroplist(int groupId) { return _herbGroups.get(groupId); } private static class SingletonHolder { protected static final HerbDropTable _instance = new HerbDropTable(); } }
gpl-2.0
midaboghetich/netnumero
src/com/numhero/client/util/ClientDialogUtils.java
3735
package com.numhero.client.util; public class ClientDialogUtils { // current user utils ----------------------------------------- // public static boolean isGranted(GrantType grant, RoleType userRole) { // boolean forEverybody = userRole == null && grant == // GrantType.FOR_EVERYBODY; // boolean specificForUser = userRole != null && userRole.isGranted(grant); // return forEverybody || specificForUser; // } // dialog & header messages ----------------------------------------- public static void showMessageDialog(String message) { // SC.say(message); } public static void showWarningDialog(String message) { // SC.warn(message, null); } public static void showMessageDialog(String message, String largeContent) { // MessageDialog dialog = new MessageDialog("Message", 600, 400); // dialog.setMessage(message); // dialog.setLargeContent(largeContent); // dialog.show(); } public static void showServerDownErrorMessage() { // showMessageDialog(constants.ServerCommunicationFailed()); } public static void showGenericErrorMessage() { // showMessageDialog(constants.GenericException()); } public static void showErrorMessage(String message) { showWarningDialog(message); } // public static void showGenericErrorMessage(ApplicationException ae) { // showApplicationError(ae); // } // // private static void showApplicationError(ApplicationException ae) { // final Dialog dialog = new Dialog(); // dialog.setShowShadow(true); // dialog.setIsModal(true); // dialog.setShowModalMask(true); // dialog.setShadowDepth(5); // dialog.setWidth(600); // dialog.setHeight(400); // dialog.setShowMinimizeButton(false); // dialog.setShowCloseButton(false); // dialog.setIsModal(true); // dialog.centerInPage(); // dialog.setTitle("Application error"); // dialog.setShowTitle(false); // dialog.setBackgroundColor("ligthblue"); // // SectionStack sectionStack = new SectionStack(); // sectionStack.setHeight(350); // sectionStack.setVisibilityMode(VisibilityMode.MULTIPLE); // // SectionStackSection errorMessageSection = new // SectionStackSection("Error message"); // errorMessageSection.setExpanded(true); // errorMessageSection.setCanCollapse(false); // String message = "Error comunicating with server: " + ae.getMessage(); // final Label messageLabel = new Label(message); // messageLabel.setWidth100(); // messageLabel.setHeight(25); // messageLabel.setAlign(Alignment.CENTER); // errorMessageSection.addItem(messageLabel); // sectionStack.addSection(errorMessageSection); // // Button closeButton = new Button("Close"); // closeButton.setAlign(Alignment.CENTER); // closeButton.addClickHandler(new ClickHandler() { // public void onClick(ClickEvent arg0) { // dialog.destroy(); // } // }); // // TextArea errorDetails = new TextArea(); // errorDetails.setWidth("580"); // errorDetails.setHeight("280"); // errorDetails.setText(ae.getFormattedStackTrace()); // Canvas errorDetailsCanvas = new HLayout(); // errorDetailsCanvas.addChild(errorDetails); // // SectionStackSection errorDetailsSection = new // SectionStackSection("Error details"); // errorDetailsSection.setExpanded(false); // errorDetailsSection.setCanCollapse(true); // errorDetailsSection.addItem(errorDetailsCanvas); // sectionStack.addSection(errorDetailsSection); // // dialog.addMember(sectionStack); // dialog.addMember(closeButton); // // dialog.show(); // } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/langtools/test/tools/javac/processing/warnings/TestSourceVersionWarnings.java
3965
/* * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ /* * @test * @bug 6376083 6376084 6458819 * @summary Test that warnings about source versions are output as expected. * @author Joseph D. Darcy * @compile TestSourceVersionWarnings.java * @compile/ref=gold_0.out -XDrawDiagnostics -XDstdout -processor TestSourceVersionWarnings -proc:only -source 1.5 HelloWorld.java * @compile/ref=gold_sv_warn_0_2.out -XDrawDiagnostics -XDstdout -processor TestSourceVersionWarnings -proc:only -ASourceVersion=RELEASE_0 -source 1.2 HelloWorld.java * @compile/ref=gold_sv_none.out -XDrawDiagnostics -XDstdout -processor TestSourceVersionWarnings -proc:only -ASourceVersion=RELEASE_2 -source 1.2 HelloWorld.java * @compile/ref=gold_sv_warn_2_3.out -XDrawDiagnostics -XDstdout -processor TestSourceVersionWarnings -proc:only -ASourceVersion=RELEASE_2 -source 1.3 HelloWorld.java * @compile/ref=gold_sv_none.out -XDrawDiagnostics -XDstdout -processor TestSourceVersionWarnings -proc:only -ASourceVersion=RELEASE_5 -source 1.5 HelloWorld.java * @compile/ref=gold_sv_warn_5_6.out -XDrawDiagnostics -XDstdout -processor TestSourceVersionWarnings -proc:only -ASourceVersion=RELEASE_5 -source 1.6 HelloWorld.java * @compile/ref=gold_sv_none.out -XDrawDiagnostics -XDstdout -processor TestSourceVersionWarnings -proc:only -ASourceVersion=RELEASE_6 -source 1.6 HelloWorld.java * @compile/ref=gold_unsp_warn.out -XDrawDiagnostics -XDstdout -processor TestSourceVersionWarnings -proc:only -ASourceVersion=RELEASE_6 -source 1.6 -Aunsupported HelloWorld.java * @compile/ref=gold_sv_none.out -XDrawDiagnostics -XDstdout -processor TestSourceVersionWarnings -proc:only -ASourceVersion=RELEASE_7 -source 1.7 HelloWorld.java */ import java.util.Set; import java.util.HashSet; import java.util.Arrays; import javax.annotation.processing.*; import javax.lang.model.SourceVersion; import static javax.lang.model.SourceVersion.*; import javax.lang.model.element.*; import javax.lang.model.util.*; import static javax.tools.Diagnostic.Kind.*; /** * This processor returns the supported source level as indicated by * the "SourceLevel" option. */ @SupportedAnnotationTypes("*") @SupportedOptions("SourceVersion") public class TestSourceVersionWarnings extends AbstractProcessor { @Override public SourceVersion getSupportedSourceVersion() { String sourceVersion = processingEnv.getOptions().get("SourceVersion"); if (sourceVersion == null) { processingEnv.getMessager().printMessage(WARNING, "No SourceVersion option given"); return SourceVersion.RELEASE_6; } else { return SourceVersion.valueOf(sourceVersion); } } public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnvironment) { return true; } }
gpl-2.0
macGRID-SRN/hitchBOT
app/Android App v3.1/hitchBOT/src/TransitionModels/SpeechPack.java
1124
package TransitionModels; import org.json.JSONException; import org.json.JSONObject; import com.example.hitchbot.Config; import com.google.gson.Gson; public class SpeechPack extends InfoPack { public String Said; public String Heard; public String Person; public String Notes; public String MatchedLineLabel; // These are optional public int MatchAccuracy; public int GoogleRecognitionScore; public double RmsDecibalLevel; public SpeechPack(String said, String heard, String matchedLine, int matchAccuracy, int recognitionScore, double decibalLevel) { this.Said = said; this.Heard = heard; //These parameters don't make sense in the production version this.MatchedLineLabel = matchedLine; this.MatchAccuracy = matchAccuracy; this.GoogleRecognitionScore = recognitionScore; this.RmsDecibalLevel = decibalLevel; } protected SpeechPack() { } @Override public JSONObject toJson() { Gson gs = new Gson(); String json = gs.toJson(this); JSONObject jO; try { jO = new JSONObject(json); } catch (JSONException e) { e.printStackTrace(); return null; } return jO; } }
gpl-2.0
acsid/stendhal
src/games/stendhal/server/core/engine/dbcommand/WriteReachedAchievementCommand.java
2301
/* $Id$ */ /*************************************************************************** * (C) Copyright 2003-2010 - Stendhal * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.server.core.engine.dbcommand; import games.stendhal.server.core.engine.db.AchievementDAO; import games.stendhal.server.core.rp.achievement.Category; import java.io.IOException; import java.sql.SQLException; import marauroa.server.db.DBTransaction; import marauroa.server.db.command.AbstractDBCommand; import marauroa.server.game.db.DAORegister; /** * command to log a reached achievement to the database * * @author madmetzger */ public class WriteReachedAchievementCommand extends AbstractDBCommand { private final Integer id; private final String playerName; /** * Create a new command. * * @param id database id of the achievement * @param title achievement title * @param category achievement category * @param playerName name of player who has reached it */ public WriteReachedAchievementCommand(Integer id, String title, Category category, String playerName) { this.id = id; this.playerName = playerName; } @Override public void execute(DBTransaction transaction) throws SQLException, IOException { AchievementDAO dao = DAORegister.get().get(AchievementDAO.class); dao.saveReachedAchievement(transaction, id, playerName); } /** * returns a string suitable for debug output of this DBCommand. * * @return debug string */ @Override public String toString() { return "WriteReachedAchievementCommand [id=" + id + ", playerName=" + playerName + "]"; } }
gpl-2.0
jbjonesjr/geoproponis
external/odfdom-java-0.8.10-incubating-sources/org/odftoolkit/odfdom/dom/element/table/TableDatabaseSourceSqlElement.java
5890
/************************************************************************ * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved. * * Use is subject to license terms. * * 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. You can also * obtain a copy of the License at http://odftoolkit.org/docs/license.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * ************************************************************************/ /* * This file is automatically generated. * Don't edit manually. */ package org.odftoolkit.odfdom.dom.element.table; import org.odftoolkit.odfdom.pkg.OdfElement; import org.odftoolkit.odfdom.pkg.ElementVisitor; import org.odftoolkit.odfdom.pkg.OdfFileDom; import org.odftoolkit.odfdom.pkg.OdfName; import org.odftoolkit.odfdom.dom.OdfDocumentNamespace; import org.odftoolkit.odfdom.dom.DefaultElementVisitor; import org.odftoolkit.odfdom.dom.attribute.table.TableDatabaseNameAttribute; import org.odftoolkit.odfdom.dom.attribute.table.TableParseSqlStatementAttribute; import org.odftoolkit.odfdom.dom.attribute.table.TableSqlStatementAttribute; /** * DOM implementation of OpenDocument element {@odf.element table:database-source-sql}. * */ public class TableDatabaseSourceSqlElement extends OdfElement { public static final OdfName ELEMENT_NAME = OdfName.newName(OdfDocumentNamespace.TABLE, "database-source-sql"); /** * Create the instance of <code>TableDatabaseSourceSqlElement</code> * * @param ownerDoc The type is <code>OdfFileDom</code> */ public TableDatabaseSourceSqlElement(OdfFileDom ownerDoc) { super(ownerDoc, ELEMENT_NAME); } /** * Get the element name * * @return return <code>OdfName</code> the name of element {@odf.element table:database-source-sql}. */ public OdfName getOdfName() { return ELEMENT_NAME; } /** * Receives the value of the ODFDOM attribute representation <code>TableDatabaseNameAttribute</code> , See {@odf.attribute table:database-name} * * Attribute is mandatory. * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getTableDatabaseNameAttribute() { TableDatabaseNameAttribute attr = (TableDatabaseNameAttribute) getOdfAttribute(OdfDocumentNamespace.TABLE, "database-name"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>TableDatabaseNameAttribute</code> , See {@odf.attribute table:database-name} * * @param tableDatabaseNameValue The type is <code>String</code> */ public void setTableDatabaseNameAttribute(String tableDatabaseNameValue) { TableDatabaseNameAttribute attr = new TableDatabaseNameAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(tableDatabaseNameValue); } /** * Receives the value of the ODFDOM attribute representation <code>TableParseSqlStatementAttribute</code> , See {@odf.attribute table:parse-sql-statement} * * @return - the <code>Boolean</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public Boolean getTableParseSqlStatementAttribute() { TableParseSqlStatementAttribute attr = (TableParseSqlStatementAttribute) getOdfAttribute(OdfDocumentNamespace.TABLE, "parse-sql-statement"); if (attr != null) { return Boolean.valueOf(attr.booleanValue()); } return Boolean.valueOf(TableParseSqlStatementAttribute.DEFAULT_VALUE); } /** * Sets the value of ODFDOM attribute representation <code>TableParseSqlStatementAttribute</code> , See {@odf.attribute table:parse-sql-statement} * * @param tableParseSqlStatementValue The type is <code>Boolean</code> */ public void setTableParseSqlStatementAttribute(Boolean tableParseSqlStatementValue) { TableParseSqlStatementAttribute attr = new TableParseSqlStatementAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setBooleanValue(tableParseSqlStatementValue.booleanValue()); } /** * Receives the value of the ODFDOM attribute representation <code>TableSqlStatementAttribute</code> , See {@odf.attribute table:sql-statement} * * Attribute is mandatory. * * @return - the <code>String</code> , the value or <code>null</code>, if the attribute is not set and no default value defined. */ public String getTableSqlStatementAttribute() { TableSqlStatementAttribute attr = (TableSqlStatementAttribute) getOdfAttribute(OdfDocumentNamespace.TABLE, "sql-statement"); if (attr != null) { return String.valueOf(attr.getValue()); } return null; } /** * Sets the value of ODFDOM attribute representation <code>TableSqlStatementAttribute</code> , See {@odf.attribute table:sql-statement} * * @param tableSqlStatementValue The type is <code>String</code> */ public void setTableSqlStatementAttribute(String tableSqlStatementValue) { TableSqlStatementAttribute attr = new TableSqlStatementAttribute((OdfFileDom) this.ownerDocument); setOdfAttribute(attr); attr.setValue(tableSqlStatementValue); } @Override public void accept(ElementVisitor visitor) { if (visitor instanceof DefaultElementVisitor) { DefaultElementVisitor defaultVisitor = (DefaultElementVisitor) visitor; defaultVisitor.visit(this); } else { visitor.visit(this); } } }
gpl-2.0
marylinh/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest00797.java
6471
/** * OWASP Benchmark Project v1.2beta * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest00797") public class BenchmarkTest00797 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String queryString = request.getQueryString(); String paramval = "vector"+"="; int paramLoc = -1; if (queryString != null) paramLoc = queryString.indexOf(paramval); if (paramLoc == -1) { response.getWriter().println("getQueryString() couldn't find expected parameter '" + "vector" + "' in query string."); return; } String param = queryString.substring(paramLoc + paramval.length()); // 1st assume "vector" param is last parameter in query string. // And then check to see if its in the middle of the query string and if so, trim off what comes after. int ampersandLoc = queryString.indexOf("&", paramLoc); if (ampersandLoc != -1) { param = queryString.substring(paramLoc + paramval.length(), ampersandLoc); } param = java.net.URLDecoder.decode(param, "UTF-8"); org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing(); String bar = thing.doSomething(param); // Code based on example from: // http://examples.javacodegeeks.com/core-java/crypto/encrypt-decrypt-file-stream-with-des/ // 8-byte initialization vector byte[] iv = { (byte)0xB2, (byte)0x12, (byte)0xD5, (byte)0xB2, (byte)0x44, (byte)0x21, (byte)0xC3, (byte)0xC3033 }; try { java.util.Properties benchmarkprops = new java.util.Properties(); benchmarkprops.load(this.getClass().getClassLoader().getResourceAsStream("benchmark.properties")); String algorithm = benchmarkprops.getProperty("cryptoAlg2", "AES/ECB/PKCS5Padding"); javax.crypto.Cipher c = javax.crypto.Cipher.getInstance(algorithm); // Prepare the cipher to encrypt javax.crypto.SecretKey key = javax.crypto.KeyGenerator.getInstance("DESede").generateKey(); java.security.spec.AlgorithmParameterSpec paramSpec = new javax.crypto.spec.IvParameterSpec(iv); // c.init(javax.crypto.Cipher.ENCRYPT_MODE, key, paramSpec); c.init(javax.crypto.Cipher.ENCRYPT_MODE, key); // encrypt and store the results byte[] input = { (byte)'?' }; Object inputParam = bar; if (inputParam instanceof String) input = ((String) inputParam).getBytes(); if (inputParam instanceof java.io.InputStream) { byte[] strInput = new byte[1000]; int i = ((java.io.InputStream) inputParam).read(strInput); if (i == -1) { response.getWriter().println("This input source requires a POST, not a GET. Incompatible UI for the InputStream source."); return; } input = java.util.Arrays.copyOf(strInput, i); } byte[] result = c.doFinal(input); java.io.File fileTarget = new java.io.File( new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir),"passwordFile.txt"); java.io.FileWriter fw = new java.io.FileWriter(fileTarget,true); //the true will append the new data fw.write("secret_value=" + org.owasp.esapi.ESAPI.encoder().encodeForBase64(result, true) + "\n"); fw.close(); response.getWriter().println("Sensitive value: '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(input)) + "' encrypted and stored<br/>"); } catch (java.security.NoSuchAlgorithmException e) { response.getWriter().println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (javax.crypto.NoSuchPaddingException e) { response.getWriter().println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (javax.crypto.IllegalBlockSizeException e) { response.getWriter().println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (javax.crypto.BadPaddingException e) { response.getWriter().println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (java.security.InvalidKeyException e) { response.getWriter().println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); // } catch (java.security.InvalidAlgorithmParameterException e) { // response.getWriter().println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); // e.printStackTrace(response.getWriter()); // throw new ServletException(e); } response.getWriter().println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String) executed"); } }
gpl-2.0