repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
ifnul/ums-backend
is-lnu-persistence/src/test/java/org/lnu/is/dao/builder/job/type/JobTypeQueryBuilderTest.java
3758
package org.lnu.is.dao.builder.job.type; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.lnu.is.dao.builder.job.type.JobTypeQueryBuilder; import org.lnu.is.domain.job.type.JobType; import org.lnu.is.pagination.MultiplePagedSearch; public class JobTypeQueryBuilderTest { private JobTypeQueryBuilder unit = new JobTypeQueryBuilder(); private Boolean active = true; private Boolean security = true; @Before public void setup() { unit.setActive(active); unit.setSecurity(security); } @Test public void testBuild() throws Exception { // Given JobType context = new JobType(); String expectedQuery = "SELECT e FROM JobType e WHERE e.status=:status AND e.crtUserGroup IN (:userGroups) "; MultiplePagedSearch<JobType> pagedSearch = new MultiplePagedSearch<>(); pagedSearch.setEntity(context); // When String actualQuery = unit.build(pagedSearch); // Then assertEquals(expectedQuery, actualQuery); } @Test public void testBuildWithDisabledSecurityConstraint() throws Exception { // Given unit.setSecurity(false); JobType context = new JobType(); String expectedQuery = "SELECT e FROM JobType e WHERE e.status=:status "; MultiplePagedSearch<JobType> pagedSearch = new MultiplePagedSearch<>(); pagedSearch.setEntity(context); // When String actualQuery = unit.build(pagedSearch); // Then assertEquals(expectedQuery, actualQuery); } @Test public void testBuildWithDisabledStatusConstraint() throws Exception { // Given unit.setActive(false); JobType context = new JobType(); String expectedQuery = "SELECT e FROM JobType e WHERE e.crtUserGroup IN (:userGroups) "; MultiplePagedSearch<JobType> pagedSearch = new MultiplePagedSearch<>(); pagedSearch.setEntity(context); // When String actualQuery = unit.build(pagedSearch); // Then assertEquals(expectedQuery, actualQuery); } @Test public void testBuildWithDisabledDefaultCOnstraints() throws Exception { // Given unit.setActive(false); unit.setSecurity(false); JobType context = new JobType(); String expectedQuery = "SELECT e FROM JobType e "; MultiplePagedSearch<JobType> pagedSearch = new MultiplePagedSearch<>(); pagedSearch.setEntity(context); // When String actualQuery = unit.build(pagedSearch); // Then assertEquals(expectedQuery, actualQuery); } @Test public void testBuildWithParameters() throws Exception { // Given String abbrName = "LieToMe"; String name = "fdsfds"; JobType context = new JobType(); context.setAbbrName(abbrName); context.setName(name); String expectedQuery = "SELECT e FROM JobType e WHERE ( e.name LIKE CONCAT('%',:name,'%') AND e.abbrName LIKE CONCAT('%',:abbrName,'%') ) AND e.status=:status AND e.crtUserGroup IN (:userGroups) "; MultiplePagedSearch<JobType> pagedSearch = new MultiplePagedSearch<>(); pagedSearch.setEntity(context); // When String actualQuery = unit.build(pagedSearch); // Then assertEquals(expectedQuery, actualQuery); } @Test public void testBuildWithParametersAndDisabledDefaultConstraint() throws Exception { // Given unit.setActive(false); unit.setSecurity(false); String abbrName = "LieToMe"; String name = "fdsfds"; JobType context = new JobType(); context.setAbbrName(abbrName); context.setName(name); String expectedQuery = "SELECT e FROM JobType e WHERE ( e.name LIKE CONCAT('%',:name,'%') AND e.abbrName LIKE CONCAT('%',:abbrName,'%') ) "; MultiplePagedSearch<JobType> pagedSearch = new MultiplePagedSearch<>(); pagedSearch.setEntity(context); // When String actualQuery = unit.build(pagedSearch); // Then assertEquals(expectedQuery, actualQuery); } }
apache-2.0
xbib/content
content-resource/src/main/java/org/xbib/content/resource/text/CodepointIterator.java
11995
package org.xbib.content.resource.text; import java.util.Iterator; import java.util.NoSuchElementException; /** * Provides an iterator over Unicode Codepoints. */ public abstract class CodepointIterator implements Iterator<Codepoint> { protected int position = -1; protected int limit = -1; /** * Get a CodepointIterator for the specified char array. * @param array char array * @return code point iterator */ public static CodepointIterator forCharArray(char[] array) { return new CharArrayCodepointIterator(array); } /** * Get a CodepointIterator for the specified CharSequence. * @param seq char sequence * @return code point iterator */ public static CodepointIterator forCharSequence(CharSequence seq) { return new CharSequenceCodepointIterator(seq); } public static CodepointIterator restrict(CodepointIterator ci, Filter filter) { return new RestrictedCodepointIterator(ci, filter, false); } public static CodepointIterator restrict(CodepointIterator ci, Filter filter, boolean scanning) { return new RestrictedCodepointIterator(ci, filter, scanning); } public static CodepointIterator restrict(CodepointIterator ci, Filter filter, boolean scanning, boolean invert) { return new RestrictedCodepointIterator(ci, filter, scanning, invert); } public CodepointIterator restrict(Filter filter) { return restrict(this, filter); } public CodepointIterator restrict(Filter filter, boolean scanning) { return restrict(this, filter, scanning); } public CodepointIterator restrict(Filter filter, boolean scanning, boolean invert) { return restrict(this, filter, scanning, invert); } /** * Get the next char. * @return char */ protected abstract char get(); /** * Get the specified char. * @param index index * @return char */ protected abstract char get(int index); /** * Checks if there are codepoints remaining. * @return true if there are codepoints remaining */ @Override public boolean hasNext() { return remaining() > 0; } /** * Return the final index position. * @return final index position */ public int lastPosition() { int p = position(); return (p > -1) ? (p >= limit()) ? p : p - 1 : -1; } /** * Return the next chars. If the codepoint is not supplemental, the char array will have a single member. If the * codepoint is supplemental, the char array will have two members, representing the high and low surrogate chars. * @return next chars */ public char[] nextChars(){ if (hasNext()) { if (isNextSurrogate()) { char c1 = get(); if (CharUtils.isHighSurrogate(c1) && position() < limit()) { char c2 = get(); if (CharUtils.isLowSurrogate(c2)) { return new char[]{c1, c2}; } else { throw new InvalidCharacterException(c2); } } else if (CharUtils.isLowSurrogate(c1) && position() > 0) { char c2 = get(position() - 2); if (CharUtils.isHighSurrogate(c2)) { return new char[]{c1, c2}; } else { throw new InvalidCharacterException(c2); } } } return new char[]{get()}; } return null; } /** * Peek the next chars in the iterator. If the codepoint is not supplemental, the char array will have a single * member. If the codepoint is supplemental, the char array will have two members, representing the high and low * surrogate chars. * @return chars */ public char[] peekChars() { return peekChars(position()); } /** * Peek the specified chars in the iterator. If the codepoint is not supplemental, the char array will have a single * member. If the codepoint is supplemental, the char array will have two members, representing the high and low * surrogate chars. * @return chars */ private char[] peekChars(int pos) { if (pos < 0 || pos >= limit()) { return null; } char c1 = get(pos); if (CharUtils.isHighSurrogate(c1) && pos < limit()) { char c2 = get(pos + 1); if (CharUtils.isLowSurrogate(c2)) { return new char[]{c1, c2}; } else { throw new InvalidCharacterException(c2); } } else if (CharUtils.isLowSurrogate(c1) && pos > 1) { char c2 = get(pos - 1); if (CharUtils.isHighSurrogate(c2)) { return new char[]{c2, c1}; } else { throw new InvalidCharacterException(c2); } } else { return new char[]{c1}; } } /** * Return the next codepoint. * @return code point */ @Override public Codepoint next() { if (remaining() > 0) { return toCodepoint(nextChars()); } else { throw new NoSuchElementException(); } } /** * Peek the next codepoint. * @return code point */ public Codepoint peek() { return toCodepoint(peekChars()); } /** * Peek the specified codepoint. * @param index index * @return code point */ public Codepoint peek(int index) { return toCodepoint(peekChars(index)); } private Codepoint toCodepoint(char[] chars) { return (chars == null) ? null : (chars.length == 1) ? new Codepoint(chars[0]) : CharUtils .toSupplementary(chars[0], chars[1]); } /** * Set the iterator position. * @param n iterator position */ public void position(int n) { if (n < 0 || n > limit()) { throw new ArrayIndexOutOfBoundsException(n); } position = n; } /** * Get the iterator position. * @return position */ public int position() { return position; } /** * Return the iterator limit. * @return limit */ public int limit() { return limit; } /** * Return the remaining iterator size. * @return remaining size */ public int remaining() { return limit - position(); } private boolean isNextSurrogate() { if (!hasNext()) { return false; } char c = get(position()); return CharUtils.isHighSurrogate(c) || CharUtils.isLowSurrogate(c); } /** * Returns true if the char at the specified index is a high surrogate. * @param index index * @return true if the char at the specified index is a high surrogate */ public boolean isHigh(int index) { if (index < 0 || index > limit()) { throw new ArrayIndexOutOfBoundsException(index); } return CharUtils.isHighSurrogate(get(index)); } /** * Returns true if the char at the specified index is a low surrogate. * @param index index * @return true if the char at the specified index is a low surrogate */ public boolean isLow(int index) { if (index < 0 || index > limit()) { throw new ArrayIndexOutOfBoundsException(index); } return CharUtils.isLowSurrogate(get(index)); } @Override public void remove() { throw new UnsupportedOperationException(); } private static class CharArrayCodepointIterator extends CodepointIterator { protected char[] buffer; CharArrayCodepointIterator(char[] buffer) { this(buffer, 0, buffer.length); } CharArrayCodepointIterator(char[] buffer, int n, int e) { this.buffer = buffer; this.position = n; this.limit = Math.min(buffer.length - n, e); } @Override protected char get() { return (position < limit) ? buffer[position++] : (char) -1; } @Override protected char get(int index) { if (index < 0 || index >= limit) { throw new ArrayIndexOutOfBoundsException(index); } return buffer[index]; } } private static class CharSequenceCodepointIterator extends CodepointIterator { private CharSequence buffer; CharSequenceCodepointIterator(CharSequence buffer) { this(buffer, 0, buffer.length()); } CharSequenceCodepointIterator(CharSequence buffer, int n, int e) { this.buffer = buffer; this.position = n; this.limit = Math.min(buffer.length() - n, e); } @Override protected char get() { return buffer.charAt(position++); } @Override protected char get(int index) { return buffer.charAt(index); } } private static class RestrictedCodepointIterator extends DelegatingCodepointIterator { private final Filter filter; private final boolean scanningOnly; private final boolean notset; RestrictedCodepointIterator(CodepointIterator internal, Filter filter, boolean scanningOnly) { this(internal, filter, scanningOnly, false); } RestrictedCodepointIterator(CodepointIterator internal, Filter filter, boolean scanningOnly, boolean notset) { super(internal); this.filter = filter; this.scanningOnly = scanningOnly; this.notset = notset; } @Override public boolean hasNext() { boolean b = super.hasNext(); if (scanningOnly) { try { int cp = super.peek(super.position()).getValue(); if (b && cp != -1 && check(cp)) { return false; } } catch (InvalidCharacterException e) { return false; } } return b; } @Override public Codepoint next() { Codepoint cp = super.next(); int v = cp.getValue(); if (v != -1 && check(v)) { if (scanningOnly) { super.position(super.position() - 1); return null; } else { throw new InvalidCharacterException(v); } } return cp; } private boolean check(int cp) { return notset == !filter.accept(cp); } @Override public char[] nextChars() { char[] chars = super.nextChars(); if (chars != null && chars.length > 0) { if (chars.length == 1 && check(chars[0])) { if (scanningOnly) { super.position(super.position() - 1); return null; } else { throw new InvalidCharacterException(chars[0]); } } else if (chars.length == 2) { int cp = CharUtils.toSupplementary(chars[0], chars[1]).getValue(); if (check(cp)) { if (scanningOnly) { super.position(super.position() - 2); return null; } else { throw new InvalidCharacterException(cp); } } } } return chars; } } }
apache-2.0
Radomiej/JavityEngine
javity-engine/src/main/java/org/javity/components/reflection/GameObjectsMonoReference.java
2737
package org.javity.components.reflection; import java.util.UUID; import org.javity.engine.Component; import org.javity.engine.CustomScene; import org.javity.engine.GameObjectProxy; import org.javity.engine.JGameObject; import org.javity.engine.JGameObjectImpl; import org.javity.engine.JScene; import com.badlogic.gdx.Gdx; import pl.silver.reflection.ReflectionBean; import pl.silver.reflection.SilverField; import pl.silver.reflection.SilverReflectionUtills; public class GameObjectsMonoReference { private CustomScene scene; public GameObjectsMonoReference(CustomScene scene) { this.scene = scene; } public void procces() { scene.getLoadSceneObjects().clear(); for (JGameObject gameObject : scene.getGameObjects()) { UUID uuid = UUID.fromString(gameObject.getObjectId()); scene.getLoadSceneObjects().put(uuid, gameObject); } for (JGameObject go : scene.getGameObjects()) { for (Component component : go.getAllComponents()) { ReflectionBean componentBean = SilverReflectionUtills.createReflectionBean(component.getClass()); for (SilverField field : componentBean.getPublicAccesFields()) { if (field.getFieldName().equals("gameObject")) continue; if (field.getFieldValueClass().equals(JGameObject.class)) { JGameObject gameObject = field.getFieldValue(component, JGameObject.class); if (gameObject == null) continue; UUID uuid = UUID.fromString(gameObject.getObjectId()); if (scene.getLoadSceneObjects().containsKey(uuid)) { JGameObject existGameObject = scene.getLoadSceneObjects().get(uuid); field.setFieldValue(component, existGameObject); // gameObject = field.getFieldValue(component, JGameObjectImpl.class); } else { // scene.getLoadSceneObjects().put(uuid, // gameObject); Gdx.app.error("GameObjectsMonoReference", "Proxy to non exist object! " + gameObject); } } } } } } public void proxyProcces() { for (JGameObject go : scene.getGameObjects()) { for (Component component : go.getAllComponents()) { ReflectionBean componentBean = SilverReflectionUtills.createReflectionBean(component.getClass()); for (SilverField field : componentBean.getPublicAccesFields()) { if (field.getFieldName().equals("gameObject")) continue; if (field.getFieldValueClass().equals(JGameObject.class)) { JGameObject gameObject = field.getFieldValue(component, JGameObject.class); if (gameObject == null) continue; GameObjectProxy proxyGameObject = new GameObjectProxy(gameObject); field.setFieldValue(component, proxyGameObject); } } } } } }
apache-2.0
xhujinjun/driver-school
project/drivers/drivers-weixin/src/main/java/com/drivers/weixin/service/WxApiService.java
638
package com.drivers.weixin.service; import com.drivers.weixin.common.bean.WxPayBaseIn; import com.drivers.weixin.common.bean.WxpayUnifiedOrderIn; import com.drivers.weixin.common.bean.WxpayUnifiedOrderOut; /** * Created by xhuji on 2016/10/12. */ public interface WxApiService { /** * 统一下单: https://api.mch.weixin.qq.com/pay/unifiedorder * 不需要证书 参考https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1 * * @param in * @return */ public WxpayUnifiedOrderOut unifiedorder(WxpayUnifiedOrderIn in); public String createWxSign(WxPayBaseIn in, String partnerKey); }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-frauddetector/src/main/java/com/amazonaws/services/frauddetector/model/ExternalModelSummary.java
6110
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.frauddetector.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * The Amazon SageMaker model. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/frauddetector-2019-11-15/ExternalModelSummary" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ExternalModelSummary implements Serializable, Cloneable, StructuredPojo { /** * <p> * The endpoint of the Amazon SageMaker model. * </p> */ private String modelEndpoint; /** * <p> * The source of the model. * </p> */ private String modelSource; /** * <p> * The endpoint of the Amazon SageMaker model. * </p> * * @param modelEndpoint * The endpoint of the Amazon SageMaker model. */ public void setModelEndpoint(String modelEndpoint) { this.modelEndpoint = modelEndpoint; } /** * <p> * The endpoint of the Amazon SageMaker model. * </p> * * @return The endpoint of the Amazon SageMaker model. */ public String getModelEndpoint() { return this.modelEndpoint; } /** * <p> * The endpoint of the Amazon SageMaker model. * </p> * * @param modelEndpoint * The endpoint of the Amazon SageMaker model. * @return Returns a reference to this object so that method calls can be chained together. */ public ExternalModelSummary withModelEndpoint(String modelEndpoint) { setModelEndpoint(modelEndpoint); return this; } /** * <p> * The source of the model. * </p> * * @param modelSource * The source of the model. * @see ModelSource */ public void setModelSource(String modelSource) { this.modelSource = modelSource; } /** * <p> * The source of the model. * </p> * * @return The source of the model. * @see ModelSource */ public String getModelSource() { return this.modelSource; } /** * <p> * The source of the model. * </p> * * @param modelSource * The source of the model. * @return Returns a reference to this object so that method calls can be chained together. * @see ModelSource */ public ExternalModelSummary withModelSource(String modelSource) { setModelSource(modelSource); return this; } /** * <p> * The source of the model. * </p> * * @param modelSource * The source of the model. * @return Returns a reference to this object so that method calls can be chained together. * @see ModelSource */ public ExternalModelSummary withModelSource(ModelSource modelSource) { this.modelSource = modelSource.toString(); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getModelEndpoint() != null) sb.append("ModelEndpoint: ").append(getModelEndpoint()).append(","); if (getModelSource() != null) sb.append("ModelSource: ").append(getModelSource()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ExternalModelSummary == false) return false; ExternalModelSummary other = (ExternalModelSummary) obj; if (other.getModelEndpoint() == null ^ this.getModelEndpoint() == null) return false; if (other.getModelEndpoint() != null && other.getModelEndpoint().equals(this.getModelEndpoint()) == false) return false; if (other.getModelSource() == null ^ this.getModelSource() == null) return false; if (other.getModelSource() != null && other.getModelSource().equals(this.getModelSource()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getModelEndpoint() == null) ? 0 : getModelEndpoint().hashCode()); hashCode = prime * hashCode + ((getModelSource() == null) ? 0 : getModelSource().hashCode()); return hashCode; } @Override public ExternalModelSummary clone() { try { return (ExternalModelSummary) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.frauddetector.model.transform.ExternalModelSummaryMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
equella/Equella
Installer/src/com/dytech/installer/controls/GEditBox.java
1561
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Apache License, * Version 2.0, (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dytech.installer.controls; import com.dytech.devlib.PropBagEx; import com.dytech.installer.InstallerException; import com.dytech.installer.Item; import java.awt.Dimension; import javax.swing.JComponent; import javax.swing.JTextField; public class GEditBox extends GuiControl { protected JTextField field; public GEditBox(PropBagEx controlBag) throws InstallerException { super(controlBag); } @Override public String getSelection() { return field.getText(); } @Override public JComponent generateControl() { field = new JTextField(); field.setMaximumSize(new Dimension(Short.MAX_VALUE, 20)); if (items.size() >= 1) { field.setText(((Item) items.get(0)).getValue()); } return field; } }
apache-2.0
hejingit/Skybird-WorkSpace
coffeeframe/src/main/java/com/coffee/common/persistence/interceptor/PreparePaginationInterceptor.java
3780
/** * Copyright &copy; 2016-2018 <a href="www.coffee-ease.com/">coffee-ease</a> All rights reserved. */ package com.coffee.common.persistence.interceptor; import org.apache.ibatis.executor.statement.BaseStatementHandler; import org.apache.ibatis.executor.statement.RoutingStatementHandler; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.plugin.Intercepts; import org.apache.ibatis.plugin.Invocation; import org.apache.ibatis.plugin.Plugin; import org.apache.ibatis.plugin.Signature; import com.coffee.common.persistence.Page; import com.coffee.common.utils.Reflections; import java.sql.Connection; import java.util.Properties; /** * Mybatis数据库分页插件,拦截StatementHandler的prepare方法 * @author poplar.yfyang / coffee * @version 2013-8-28 */ @Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class}) }) public class PreparePaginationInterceptor extends BaseInterceptor { private static final long serialVersionUID = 1L; public PreparePaginationInterceptor() { super(); } @Override public Object intercept(Invocation ivk) throws Throwable { if (ivk.getTarget().getClass().isAssignableFrom(RoutingStatementHandler.class)) { final RoutingStatementHandler statementHandler = (RoutingStatementHandler) ivk.getTarget(); final BaseStatementHandler delegate = (BaseStatementHandler) Reflections.getFieldValue(statementHandler, DELEGATE); final MappedStatement mappedStatement = (MappedStatement) Reflections.getFieldValue(delegate, MAPPED_STATEMENT); // //拦截需要分页的SQL //// if (mappedStatement.getId().matches(_SQL_PATTERN)) { // if (StringUtils.indexOfIgnoreCase(mappedStatement.getId(), _SQL_PATTERN) != -1) { BoundSql boundSql = delegate.getBoundSql(); //分页SQL<select>中parameterType属性对应的实体参数,即Mapper接口中执行分页方法的参数,该参数不得为空 Object parameterObject = boundSql.getParameterObject(); if (parameterObject == null) { log.error("参数未实例化"); throw new NullPointerException("parameterObject尚未实例化!"); } else { final Connection connection = (Connection) ivk.getArgs()[0]; final String sql = boundSql.getSql(); //记录统计 final int count = SQLHelper.getCount(sql, connection, mappedStatement, parameterObject, boundSql, log); Page<Object> page = null; page = convertParameter(parameterObject, page); page.setCount(count); String pagingSql = SQLHelper.generatePageSql(sql, page, DIALECT); if (log.isDebugEnabled()) { log.debug("PAGE SQL:" + pagingSql); } //将分页sql语句反射回BoundSql. Reflections.setFieldValue(boundSql, "sql", pagingSql); } if (boundSql.getSql() == null || "".equals(boundSql.getSql())){ return null; } } // } return ivk.proceed(); } @Override public Object plugin(Object o) { return Plugin.wrap(o, this); } @Override public void setProperties(Properties properties) { initProperties(properties); } }
apache-2.0
MSaifAsif/sample-skeleton-projects
web-api/EJBHelloWorld/src/main/java/com/sample/beans/SampleStatefulBean.java
832
package com.sample.beans; import javax.ejb.Stateful; import java.util.List; import java.util.Vector; /** * A stateful bean that will maintain its values until the end of the application run * * @author saifasif */ @Stateful public class SampleStatefulBean implements SampleBean { private List<String> entityList; public SampleStatefulBean() { System.out.println("Creating entityList for stateful bean"); entityList = new Vector<String>(); } @Override public void addEntity(String o) { System.out.println("Adding entity to stateful bean" + o.toString()); entityList.add(o); } @Override public List<String> getEntity() { System.out.println("Retreiving values for stateful bean from list of : " + entityList.size()); return entityList; } }
apache-2.0
aleo72/ww-ceem-radar
src/main/java/gov/nasa/worldwind/symbology/milstd2525/graphics/areas/AttackByFirePosition.java
12932
/* * Copyright (C) 2012 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration. * All Rights Reserved. */ package gov.nasa.worldwind.symbology.milstd2525.graphics.areas; import gov.nasa.worldwind.WorldWind; import gov.nasa.worldwind.avlist.AVKey; import gov.nasa.worldwind.geom.*; import gov.nasa.worldwind.globes.Globe; import gov.nasa.worldwind.render.*; import gov.nasa.worldwind.symbology.TacticalGraphicUtil; import gov.nasa.worldwind.symbology.milstd2525.AbstractMilStd2525TacticalGraphic; import gov.nasa.worldwind.symbology.milstd2525.graphics.TacGrpSidc; import gov.nasa.worldwind.util.Logging; import java.util.*; /** * Implementation of the Attack By Fire Position graphic (2.X.2.5.3.3). * * @author pabercrombie * @version $Id: AttackByFirePosition.java 555 2012-04-25 18:59:29Z pabercrombie $ */ public class AttackByFirePosition extends AbstractMilStd2525TacticalGraphic { /** Default length of the arrowhead, as a fraction of the total line length. */ public final static double DEFAULT_ARROWHEAD_LENGTH = 0.2; /** Default angle of the arrowhead. */ public final static Angle DEFAULT_ARROWHEAD_ANGLE = Angle.fromDegrees(70.0); /** * Default length of the legs of the graphic's base, as a fraction of the distance between the control points the * define the base. */ public final static double DEFAULT_LEG_LENGTH = 0.25; /** Length of the arrowhead from base to tip, as a fraction of the total line length. */ protected Angle arrowAngle = DEFAULT_ARROWHEAD_ANGLE; /** Angle of the arrowhead. */ protected double arrowLength = DEFAULT_ARROWHEAD_LENGTH; /** * Length of the legs on the graphic's base, as a fraction of the distance between the control points that define * the base. */ protected double legLength = DEFAULT_LEG_LENGTH; /** First control point. */ protected Position position1; /** Second control point. */ protected Position position2; /** Third control point. */ protected Position position3; /** Path used to render the graphic. */ protected Path[] paths; /** * Indicates the graphics supported by this class. * * @return List of masked SIDC strings that identify graphics that this class supports. */ public static List<String> getSupportedGraphics() { return Arrays.asList(TacGrpSidc.C2GM_OFF_ARS_AFP); } /** * Create a new arrow graphic. * * @param sidc Symbol code the identifies the graphic. */ public AttackByFirePosition(String sidc) { super(sidc); } /** * Indicates the angle of the arrowhead. * * @return Angle of the arrowhead in the graphic. */ public Angle getArrowAngle() { return this.arrowAngle; } /** * Specifies the angle of the arrowhead in the graphic. * * @param arrowAngle The angle of the arrowhead. Must be greater than zero degrees and less than 90 degrees. */ public void setArrowAngle(Angle arrowAngle) { if (arrowAngle == null) { String msg = Logging.getMessage("nullValue.AngleIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } if (arrowAngle.degrees <= 0 || arrowAngle.degrees >= 90) { String msg = Logging.getMessage("generic.AngleOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } this.arrowAngle = arrowAngle; } /** * Indicates the length of the arrowhead. * * @return The length of the arrowhead as a fraction of the total line length. */ public double getArrowLength() { return this.arrowLength; } /** * Specifies the length of the arrowhead. * * @param arrowLength Length of the arrowhead as a fraction of the total line length. If the arrowhead length is * 0.25, then the arrowhead length will be one quarter of the total line length. */ public void setArrowLength(double arrowLength) { if (arrowLength < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } this.arrowLength = arrowLength; } /** * Indicates the length of legs of the graphic's base. * * @return The length of the legs of the base, as a fraction of the distance between the control points that define * the base. */ public double getLegLength() { return this.arrowLength; } /** * Specifies the length of the legs of the graphic's base. * * @param legLength Length of the legs of the graphic's base, as a fraction of the distance between the control * points that define the base. */ public void setLegLength(double legLength) { if (legLength < 0) { String msg = Logging.getMessage("generic.ArgumentOutOfRange"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } this.legLength = legLength; } /** * {@inheritDoc} * * @param positions Control points that orient the graphic. Must provide at least three points. */ public void setPositions(Iterable<? extends Position> positions) { if (positions == null) { String message = Logging.getMessage("nullValue.PositionsListIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } try { Iterator<? extends Position> iterator = positions.iterator(); this.position1 = iterator.next(); this.position2 = iterator.next(); this.position3 = iterator.next(); } catch (NoSuchElementException e) { String message = Logging.getMessage("generic.InsufficientPositions"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.paths = null; // Need to recompute path for the new control points } /** {@inheritDoc} */ public Iterable<? extends Position> getPositions() { return Arrays.asList(this.position1, this.position2, this.position3); } /** {@inheritDoc} */ public Position getReferencePosition() { return this.position1; } /** {@inheritDoc} */ protected void doRenderGraphic(DrawContext dc) { if (this.paths == null) { this.createShapes(dc); } for (Path path : this.paths) { path.render(dc); } } /** {@inheritDoc} */ protected void applyDelegateOwner(Object owner) { if (this.paths == null) return; for (Path path : this.paths) { path.setDelegateOwner(owner); } } /** * Create the paths required to draw the graphic. * * @param dc Current draw context. */ protected void createShapes(DrawContext dc) { this.paths = new Path[3]; Position baseMidpoint = new Position(LatLon.interpolate(0.5, this.position2, this.position3), 0); // Create a path for the line part of the arrow this.paths[0] = this.createPath(Arrays.asList(baseMidpoint, this.position1)); // Create the arrowhead List<Position> positions = this.computeArrowheadPositions(dc, baseMidpoint, this.position1); this.paths[1] = createPath(positions); positions = this.computeBasePositions(dc, this.position2, this.position3, this.position1); this.paths[2] = createPath(positions); } /** * Determine the positions that make up the base of the graphic (a trapezoid missing one side). * * @param dc Current draw context. * @param position1 The first control point that defines the graphic base. * @param position2 The second control point that defines the graphic base. * @param orientationPos A point on the arrow head side of the graphic. The legs of the base will point away from * this position. * * @return Positions that define the graphic's base. */ protected List<Position> computeBasePositions(DrawContext dc, Position position1, Position position2, Position orientationPos) { Globe globe = dc.getGlobe(); // A \ // \ // | B // | x Orientation position // | C // / // D / Vec4 pB = globe.computePointFromPosition(position1); Vec4 pC = globe.computePointFromPosition(position2); // Find vector in the direction of the arrow Vec4 vBC = pC.subtract3(pB); double legLength = vBC.getLength3() * this.getLegLength(); Vec4 normal = globe.computeSurfaceNormalAtPoint(pB); // Compute a vector perpendicular to the segment and the normal vector Vec4 perpendicular = vBC.cross3(normal); // Compute a vector parallel to the base. We will find points A and D by adding parallel and perpendicular // components to the control points. Vec4 parallel = vBC.normalize3().multiply3(legLength); // Determine which side of the line BC the orientation point falls on. We want the legs of the base to point // away from the orientation position, so set the direction of the perpendicular component according to the // sign of the scalar triple product. Vec4 vOrientation = globe.computePointFromPosition(orientationPos).subtract3(pB); double tripleProduct = perpendicular.dot3(vOrientation); double sign = (tripleProduct > 0) ? -1 : 1; perpendicular = perpendicular.normalize3().multiply3(legLength * sign); // Find point A Vec4 pA = pB.add3(perpendicular).subtract3(parallel); // Find Point D normal = globe.computeSurfaceNormalAtPoint(pB); perpendicular = vBC.cross3(normal); perpendicular = perpendicular.normalize3().multiply3(legLength * sign); Vec4 pD = pC.add3(perpendicular).add3(parallel); return TacticalGraphicUtil.asPositionList(globe, pA, pB, pC, pD); } /** * Determine the positions that make up the arrowhead. * * @param dc Current draw context. * @param base Position of the arrow's starting point. * @param tip Position of the arrow head tip. * * @return Positions that define the arrowhead. */ protected List<Position> computeArrowheadPositions(DrawContext dc, Position base, Position tip) { Globe globe = dc.getGlobe(); // _ // A\ | 1/2 width // Pt. 1________B\ _| // / // C/ // | | // Length Vec4 p1 = globe.computePointFromPosition(base); Vec4 pB = globe.computePointFromPosition(tip); // Find vector in the direction of the arrow Vec4 vB1 = p1.subtract3(pB); double arrowLengthFraction = this.getArrowLength(); // Find the point at the base of the arrowhead Vec4 arrowBase = pB.add3(vB1.multiply3(arrowLengthFraction)); Vec4 normal = globe.computeSurfaceNormalAtPoint(arrowBase); // Compute the length of the arrowhead double arrowLength = vB1.getLength3() * arrowLengthFraction; double arrowHalfWidth = arrowLength * this.getArrowAngle().tanHalfAngle(); // Compute a vector perpendicular to the segment and the normal vector Vec4 perpendicular = vB1.cross3(normal); perpendicular = perpendicular.normalize3().multiply3(arrowHalfWidth); // Find points A and C Vec4 pA = arrowBase.add3(perpendicular); Vec4 pC = arrowBase.subtract3(perpendicular); return TacticalGraphicUtil.asPositionList(globe, pA, pB, pC); } /** * Create and configure the Path used to render this graphic. * * @param positions Positions that define the path. * * @return New path configured with defaults appropriate for this type of graphic. */ protected Path createPath(List<Position> positions) { Path path = new Path(positions); path.setFollowTerrain(true); path.setPathType(AVKey.GREAT_CIRCLE); path.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); path.setDelegateOwner(this.getActiveDelegateOwner()); path.setAttributes(this.getActiveShapeAttributes()); return path; } }
apache-2.0
deathknight0718/foliage
src/foliage-scout/foliage-scout-embedder/src/main/java/org/foliage/scout/cli/ScoutCliManager.java
2142
/***************************************************************************** * PROJECT: FOLIAGE PROJECT. * SUPPLIER: FOLIAGE TEAM. ***************************************************************************** * FILE: ScoutCliManager.java * (C) Copyright Foliage Team 2017, All Rights Reserved. *****************************************************************************/ package org.foliage.scout.cli; import java.io.PrintStream; import java.io.PrintWriter; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; /** * Scout Command Line Manager. * * @author deathknight0718@qq.com * @version 1.0.0 */ @SuppressWarnings("static-access") public class ScoutCliManager { public static final char HELP = 'h'; public static final char VERSION = 'v'; // ------------------------------------------------------------------------ private Options options; // ------------------------------------------------------------------------ public ScoutCliManager() { options = new Options(); options.addOption(OptionBuilder.withLongOpt("help").withDescription("显示帮助信息.").create(HELP)); } // ------------------------------------------------------------------------ public CommandLine parse(String[] args) throws ParseException { CommandLineParser parser = new GnuParser(); return parser.parse(options, args); } // ------------------------------------------------------------------------ public void displayHelp(PrintStream stream) { stream.println(); PrintWriter writer = new PrintWriter(stream); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(writer, HelpFormatter.DEFAULT_WIDTH, "scout [options]", "\nOptions:", options, HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD, "\n", false); writer.flush(); } }
apache-2.0
neo4j/neo4j-java-driver
driver/src/main/java/org/neo4j/driver/internal/value/LocalDateTimeValue.java
1228
/* * Copyright (c) "Neo4j" * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neo4j.driver.internal.value; import java.time.LocalDateTime; import org.neo4j.driver.internal.types.InternalTypeSystem; import org.neo4j.driver.types.Type; public class LocalDateTimeValue extends ObjectValueAdapter<LocalDateTime> { public LocalDateTimeValue( LocalDateTime localDateTime ) { super( localDateTime ); } @Override public LocalDateTime asLocalDateTime() { return asObject(); } @Override public Type type() { return InternalTypeSystem.TYPE_SYSTEM.LOCAL_DATE_TIME(); } }
apache-2.0
r24mille/CanadianCensusDemographics
src/main/java/ca/uwaterloo/iss4e/demographics/dao/geography/mapper/CensusPolygonMapper.java
551
package ca.uwaterloo.iss4e.demographics.dao.geography.mapper; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import ca.uwaterloo.iss4e.demographics.model.geography.CensusPolygon; public class CensusPolygonMapper implements RowMapper<CensusPolygon> { public CensusPolygon mapRow(ResultSet rs, int rowNum) throws SQLException { CensusPolygon censusPolygon = new CensusPolygon(); censusPolygon.setPolygonPatchId(rs.getInt("polygon_patch.polygon_patch_id")); return censusPolygon; } }
apache-2.0
stori-es/stori_es
dashboard/src/main/java/org/consumersunion/stories/server/api/rest/mapper/NotLoggedInExceptionMapper.java
989
package org.consumersunion.stories.server.api.rest.mapper; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.consumersunion.stories.common.shared.dto.ErrorApiResponse; import org.consumersunion.stories.server.exception.NotLoggedInException; import org.springframework.stereotype.Component; @Provider @Component public class NotLoggedInExceptionMapper implements ExceptionMapper<NotLoggedInException> { private static final Logger LOGGER = Logger.getLogger(NotLoggedInExceptionMapper.class.getName()); @Override public Response toResponse(NotLoggedInException exception) { LOGGER.log(Level.SEVERE, exception.getMessage(), exception); return Response.status(Status.UNAUTHORIZED) .entity(new ErrorApiResponse(exception.getMessage())) .build(); } }
apache-2.0
mediascape/discovery-self
complements/discovery-agent-REST/discovery-agent-REST-android/src/com/example/discoveryagentrest/BluetoothService.java
8084
/* Long Library Name: ** ServiceBoot Class ** ** Acronym and its version: ** ServiceBoot v1.0 ** ** Copyright claim: ** Copyright ( C ) 2013-2014 Vicomtech-IK4 ( http://www.vicomtech.org/ ), ** all rights reserved. ** ** Authors (in alphabetical order): ** Angel Martin <amartin@vicomtech.org>, ** Iñigo Tamayo <itamayo@vicomteh.org>, ** Ion Alberdi <ialberdi@vicomtech.org> ** ** Description: ** The ServiceBoot class extends Service and boots the different services used for the publication of ** UPnP information. The class boots RestFul and UPnP services and implements necessary ** subclasses like BrowseRegistryListener and DeviceDisplay. ** ** Development Environment: ** The software has been implemented in Java, and tested in Chrome ** browsers and Android 4.3 OS devices. ** ** Dependencies: ** As ServiceBoot class depends on other libraries, the user must adhere to and ** keep in place any Licencing terms of those libraries: ** Android v4.4.2 (http://developer.android.com/) ** Restlet v2.1 (http://restlet.com/) ** Cling v2.0-alpha3 (http://4thline.org/projects/cling/) ** ** Licenses dependencies: ** License Agreement for Restlet: ** Apachev2 license (http://opensource.org/licenses/apache-2.0) ** GNU LGPLv3 license (http://opensource.org/licenses/lgpl-3.0) ** GNU LGPLv2.1 license (http://opensource.org/licenses/lgpl-2.1) ** CDDLv1 license (http://opensource.org/licenses/cddl1) ** EPLv1 license (http://opensource.org/licenses/eclipse-1.0) ** License Agreement for Cling: ** GNU LGPLv3 (http://www.gnu.org/licenses/lgpl.html) ** */ package com.example.discoveryagentrest; import java.util.Set; import java.util.UUID; import java.util.Vector; import android.annotation.SuppressLint; import android.app.Service; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Handler; import android.os.IBinder; import android.os.ParcelUuid; import android.os.Parcelable; import android.util.Log; public class BluetoothService extends Service{ //variables for the different sensors. public static Context context; public static final int REQUEST_ENABLE_BT = 1; public static BluetoothAdapter bluetoothSensor = null; public static Vector<BluetoothDevice> listBluetooth; public static Vector<Parcelable> listBluetoothServices; private BroadcastReceiver mBluetoothInfoReceiver = new BroadcastReceiver(){ public void onReceive(Context ctxt, Intent intent) { if(intent.getAction().equals(BluetoothDevice.ACTION_FOUND)) { Log.d("MyApp", "ACTION_FOUND"); BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Log.d("MyApp", "contains: "+listBluetooth.contains(device)); if (!listBluetooth.contains(device)) { Log.d("MyApp", "Add Device: "+device.getName()+" "+device.getType()+" "+device.getAddress()+" "+device.getBondState()+" "+device.getBluetoothClass()); listBluetooth.add(device); //device.fetchUuidsWithSdp(); } Set<BluetoothDevice> pairedDevices = bluetoothSensor.getBondedDevices(); // If there are paired devices Log.d("MyApp", "PairedDevices: "+pairedDevices.size()); if (pairedDevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device1 : pairedDevices) { // Add the name and address to an array adapter to show in a ListView Log.d("MyApp", "Paired Devices:"); Log.d("MyApp", device1.getName()+", "+device1.getType()+", "+device1.getAddress()); } } Log.d("MyApp", "BluetoothList: "+listBluetooth.toString()); }else if(intent.getAction().equals(BluetoothDevice.ACTION_UUID)) { Log.d("MyApp", "ACTION_UUID"); BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID); Log.d("MyApp", "Device: "+device.getName()); if(uuidExtra!=null){ for (Parcelable parcelable : uuidExtra) { Log.d("MyApp", "Service: "+parcelable.toString()); ParcelUuid parcelUuid = (ParcelUuid) parcelable; listBluetoothServices.add(parcelUuid); UUID uuid = parcelUuid.getUuid(); Log.d("MyApp", "Service: "+uuid); } } }else if(intent.getAction().equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)){ Log.d("MyApp", "Discovery Start"); listBluetooth.clear(); listBluetoothServices.clear(); }else if(intent.getAction().equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){ if(!bluetoothSensor.isDiscovering()){ for (int i=0; i<listBluetooth.size(); i++) { listBluetooth.get(i).fetchUuidsWithSdp(); } Log.d("MyApp", "Discovery Finished"); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if(bluetoothSensor.isEnabled()) bluetoothSensor.startDiscovery(); } }, 60000); } }else if(intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)){ final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); listBluetooth.clear(); listBluetoothServices.clear(); switch (state) { case BluetoothAdapter.STATE_OFF: Log.d("MyApp", "Bluetooth Off"); if(bluetoothSensor.isDiscovering()) bluetoothSensor.cancelDiscovery(); break; case BluetoothAdapter.STATE_ON: Log.d("MyApp", "Bluetooth On"); if(bluetoothSensor.isEnabled()) bluetoothSensor.startDiscovery(); break; } } } }; @SuppressLint("InlinedApi") @Override public void onCreate() { super.onCreate(); listBluetooth= new Vector<BluetoothDevice>(); listBluetoothServices= new Vector<Parcelable>(); context = this; IntentFilter filterBluetooth = new IntentFilter(); filterBluetooth.addAction(BluetoothDevice.ACTION_FOUND); filterBluetooth.addAction(BluetoothDevice.ACTION_UUID); filterBluetooth.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); filterBluetooth.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); filterBluetooth.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); this.registerReceiver(this.mBluetoothInfoReceiver , filterBluetooth); bluetoothSensor = BluetoothAdapter.getDefaultAdapter(); if (bluetoothSensor == null) { // Device does not support Bluetooth Log.d("MyApp", "Bluetooth Sensor : False"); }else{ if (!bluetoothSensor.isEnabled()) Log.d("MyApp", "Bluetooth Enabled : False"); else if(bluetoothSensor.isEnabled()){ if(bluetoothSensor.isDiscovering()) bluetoothSensor.cancelDiscovery(); bluetoothSensor.startDiscovery(); Log.d("MyApp", "Bluetooth Enabled : True"); } } Log.d("MyApp", "Bluetooth Service created"); } @Override public void onDestroy() { Log.d("MyApp", "onDestroy"); super.onDestroy(); //Unbind UPnP service if (bluetoothSensor.isDiscovering()) { bluetoothSensor.cancelDiscovery(); } Log.d("MyApp", "Bluetooth Service destroyed"); } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d("MyApp", "onStartCommandBluetooth"); // TODO Auto-generated method stub return super.onStartCommand(intent, flags, startId); } }
apache-2.0
davidfrigola/pfc
wfe/wfe-core/src/main/java/org/wfe/core/model/permissions/IPermission.java
583
/** * */ package org.wfe.core.model.permissions; import org.wfe.commons.base.IIdentificable; import org.wfe.commons.base.INameable; /** * The interface of a permission entity. * @author daviz * */ public interface IPermission extends IIdentificable<Long>,INameable{ /** * Sets the description of the permission. * * @param description The string description. */ void setDescription(String description); /** * Gets the description of the permission. * * @return The string description. */ String getDescription(); }
apache-2.0
tinyvampirepudge/Android_Basis_Demo
Android_Basis_Demo/app/src/main/java/com/tiny/demo/firstlinecode/uicomponents/bottomnaviview/BottomNavigationViewHelper.java
1574
package com.tiny.demo.firstlinecode.uicomponents.bottomnaviview; import android.support.design.internal.BottomNavigationItemView; import android.support.design.internal.BottomNavigationMenuView; import android.support.design.widget.BottomNavigationView; import com.tiny.demo.firstlinecode.common.utils.LogUtils; import java.lang.reflect.Field; /** * Desc: * Created by tiny on 2017/11/20. * Version: */ public class BottomNavigationViewHelper { public static void disableShiftMode(BottomNavigationView view) { BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0); try { Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode"); shiftingMode.setAccessible(true); shiftingMode.setBoolean(menuView, false); shiftingMode.setAccessible(false); for (int i = 0; i < menuView.getChildCount(); i++) { BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i); //noinspection RestrictedApi item.setShiftingMode(false); // set once again checked value, so view will be updated //noinspection RestrictedApi item.setChecked(item.getItemData().isChecked()); } } catch (NoSuchFieldException e) { LogUtils.e("BNVHelper", "Unable to get shift mode field", e); } catch (IllegalAccessException e) { LogUtils.e("BNVHelper", "Unable to change value of shift mode", e); } } }
apache-2.0
noobyang/AndroidStudy
utils/src/main/java/com/lee/utils/file/FolderUtil.java
626
package com.lee.utils.file; import android.os.Environment; import java.io.File; /** * Folder Util * </p> * Created by LiYang on 2017/6/30. */ public class FolderUtil { public static final String ROOT_FOLDER_PATH = Environment.getExternalStorageDirectory() + File.separator + "lee" + File.separator; public static final String LOG_FOLDER_PATH = ROOT_FOLDER_PATH + "logs" + File.separator; public static final String DOWNLOAD_FOLDER_PATH = ROOT_FOLDER_PATH + "downloads" + File.separator; public static final String UPLOAD_FOLDER_PATH = ROOT_FOLDER_PATH + "uploads" + File.separator; }
apache-2.0
adamjshook/accumulo
test/src/test/java/org/apache/accumulo/harness/TestingKdc.java
7496
/* * 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.accumulo.harness; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.net.InetAddress; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.apache.accumulo.cluster.ClusterUser; import org.apache.hadoop.minikdc.MiniKdc; import org.junit.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Creates a {@link MiniKdc} for tests to use to exercise secure Accumulo */ public class TestingKdc { private static final Logger log = LoggerFactory.getLogger(TestingKdc.class); public static final int NUM_USERS = 10; public static final long MAX_TICKET_LIFETIME_MILLIS = 86400000; // one day protected MiniKdc kdc = null; protected ClusterUser accumuloServerUser = null, accumuloAdmin = null; protected List<ClusterUser> clientPrincipals = null; public final String ORG_NAME = "EXAMPLE", ORG_DOMAIN = "COM"; private String hostname; private File keytabDir; private boolean started = false; public TestingKdc() throws Exception { this(computeKdcDir(), computeKeytabDir(), MAX_TICKET_LIFETIME_MILLIS); } public static File computeKdcDir() { File targetDir = new File(System.getProperty("user.dir"), "target"); Assert.assertTrue("Could not find Maven target directory: " + targetDir, targetDir.exists() && targetDir.isDirectory()); // Create the directories: target/kerberos/minikdc File kdcDir = new File(new File(targetDir, "kerberos"), "minikdc"); assertTrue(kdcDir.mkdirs() || kdcDir.isDirectory()); return kdcDir; } public static File computeKeytabDir() { File targetDir = new File(System.getProperty("user.dir"), "target"); Assert.assertTrue("Could not find Maven target directory: " + targetDir, targetDir.exists() && targetDir.isDirectory()); // Create the directories: target/kerberos/keytabs File keytabDir = new File(new File(targetDir, "kerberos"), "keytabs"); assertTrue(keytabDir.mkdirs() || keytabDir.isDirectory()); return keytabDir; } public TestingKdc(File kdcDir, File keytabDir) throws Exception { this(kdcDir, keytabDir, MAX_TICKET_LIFETIME_MILLIS); } public TestingKdc(File kdcDir, File keytabDir, long maxTicketLifetime) throws Exception { requireNonNull(kdcDir, "KDC directory was null"); requireNonNull(keytabDir, "Keytab directory was null"); checkArgument(maxTicketLifetime > 0, "Ticket lifetime must be positive"); this.keytabDir = keytabDir; this.hostname = InetAddress.getLocalHost().getCanonicalHostName(); log.debug("Starting MiniKdc in {} with keytabs in {}", kdcDir, keytabDir); Properties kdcConf = MiniKdc.createConf(); kdcConf.setProperty(MiniKdc.ORG_NAME, ORG_NAME); kdcConf.setProperty(MiniKdc.ORG_DOMAIN, ORG_DOMAIN); kdcConf.setProperty(MiniKdc.MAX_TICKET_LIFETIME, Long.toString(maxTicketLifetime)); // kdcConf.setProperty(MiniKdc.DEBUG, "true"); kdc = new MiniKdc(kdcConf, kdcDir); } /** * Starts the KDC and creates the principals and their keytabs */ public synchronized void start() throws Exception { checkArgument(!started, "KDC was already started"); kdc.start(); Thread.sleep(1000); // Create the identity for accumulo servers File accumuloKeytab = new File(keytabDir, "accumulo.keytab"); String accumuloPrincipal = String.format("accumulo/%s", hostname); log.info("Creating Kerberos principal {} with keytab {}", accumuloPrincipal, accumuloKeytab); kdc.createPrincipal(accumuloKeytab, accumuloPrincipal); accumuloServerUser = new ClusterUser(qualifyUser(accumuloPrincipal), accumuloKeytab); // Create the identity for the "root" user String rootPrincipal = "root"; File rootKeytab = new File(keytabDir, rootPrincipal + ".keytab"); log.info("Creating Kerberos principal {} with keytab {}", rootPrincipal, rootKeytab); kdc.createPrincipal(rootKeytab, rootPrincipal); accumuloAdmin = new ClusterUser(qualifyUser(rootPrincipal), rootKeytab); clientPrincipals = new ArrayList<>(NUM_USERS); // Create a number of unprivileged users for tests to use for (int i = 1; i <= NUM_USERS; i++) { String clientPrincipal = "client" + i; File clientKeytab = new File(keytabDir, clientPrincipal + ".keytab"); log.info("Creating Kerberos principal {} with keytab {}", clientPrincipal, clientKeytab); kdc.createPrincipal(clientKeytab, clientPrincipal); clientPrincipals.add(new ClusterUser(qualifyUser(clientPrincipal), clientKeytab)); } started = true; } public synchronized void stop() throws Exception { checkArgument(started, "KDC is not started"); kdc.stop(); started = false; } /** * A directory where the automatically-created keytab files are written */ public File getKeytabDir() { return keytabDir; } /** * A {@link ClusterUser} for Accumulo server processes to use */ public ClusterUser getAccumuloServerUser() { checkArgument(started, "The KDC is not started"); return accumuloServerUser; } /** * A {@link ClusterUser} which is the Accumulo "root" user */ public ClusterUser getRootUser() { checkArgument(started, "The KDC is not started"); return accumuloAdmin; } /** * The {@link ClusterUser} corresponding to the given offset. Represents an unprivileged user. * * @param offset * The offset to fetch credentials for, valid through {@link #NUM_USERS} */ public ClusterUser getClientPrincipal(int offset) { checkArgument(started, "Client principal is not initialized, is the KDC started?"); checkArgument(offset >= 0 && offset < NUM_USERS, "Offset is invalid, must be non-negative and less than " + NUM_USERS); return clientPrincipals.get(offset); } /** * @see MiniKdc#createPrincipal(File, String...) */ public void createPrincipal(File keytabFile, String... principals) throws Exception { checkArgument(started, "KDC is not started"); kdc.createPrincipal(keytabFile, principals); } /** * @return the name for the realm */ public String getOrgName() { return ORG_NAME; } /** * @return the domain for the realm */ public String getOrgDomain() { return ORG_DOMAIN; } /** * Qualify a username (only the primary from the kerberos principal) with the proper realm * * @param primary * The primary or primary and instance */ public String qualifyUser(String primary) { return String.format("%s@%s.%s", primary, getOrgName(), getOrgDomain()); } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-health/src/main/java/com/amazonaws/services/health/model/transform/EventDescriptionJsonUnmarshaller.java
2764
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.health.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.health.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * EventDescription JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class EventDescriptionJsonUnmarshaller implements Unmarshaller<EventDescription, JsonUnmarshallerContext> { public EventDescription unmarshall(JsonUnmarshallerContext context) throws Exception { EventDescription eventDescription = new EventDescription(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("latestDescription", targetDepth)) { context.nextToken(); eventDescription.setLatestDescription(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return eventDescription; } private static EventDescriptionJsonUnmarshaller instance; public static EventDescriptionJsonUnmarshaller getInstance() { if (instance == null) instance = new EventDescriptionJsonUnmarshaller(); return instance; } }
apache-2.0
mengchen2/SeLion_Demo
client/src/test/java/com/paypal/selion/platform/html/TextFieldTest.java
6904
/*-------------------------------------------------------------------------------------------------------------------*\ | Copyright (C) 2014 eBay Software Foundation | | | | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance | | with the License. | | | | You may obtain a copy of the License at | | | | http://www.apache.org/licenses/LICENSE-2.0 | | | | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed | | on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for | | the specific language governing permissions and limitations under the License. | \*-------------------------------------------------------------------------------------------------------------------*/ package com.paypal.selion.platform.html; import static com.paypal.selion.platform.asserts.SeLionAsserts.assertFalse; import static com.paypal.selion.platform.asserts.SeLionAsserts.assertTrue; import static org.testng.Assert.assertEquals; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.paypal.selion.annotations.WebTest; import com.paypal.selion.configuration.Config; import com.paypal.selion.platform.grid.Grid; import com.paypal.test.utilities.server.TestServerUtils; /** * This class test the TextField class methods */ public class TextFieldTest { static final String sTest = "TestString"; TextField normalTextField = new TextField(TestObjectRepository.TEXTFIELD_LOCATOR.getValue()); TextField disabledTextField = new TextField(TestObjectRepository.TEXTFIELD_DISABLED_LOCATOR.getValue(), "disabled_text"); @BeforeClass(groups = { "browser-tests" }) public void setUp() { Config.setConfigProperty(Config.ConfigProperty.ENABLE_GUI_LOGGING, Boolean.TRUE.toString()); } @Test(groups = { "browser-tests" }) @WebTest public void txtFieldTestTypeText() { Grid.driver().get(TestServerUtils.getTestEditableURL()); normalTextField.type(sTest); assertTrue(normalTextField.getText().matches(sTest), "Validate SetText method"); } @Test(groups = { "browser-tests" }) @WebTest public void txtFieldTestGetText() { Grid.driver().get(TestServerUtils.getTestEditableURL()); normalTextField.type(sTest); assertTrue(normalTextField.getText().contains(sTest), "Vlaidate GetText method"); } @Test(groups = { "browser-tests" }) @WebTest public void txtFieldTestClearText() { Grid.driver().get(TestServerUtils.getTestEditableURL()); normalTextField.type(sTest); assertTrue(normalTextField.getText().matches(sTest), "Validate Type method"); normalTextField.clear(); assertTrue(normalTextField.getText().length() == 0, "Validate ClearText method"); } @Test(groups = { "browser-tests" }) @WebTest public void txtFieldTestisEditable() { Grid.driver().get(TestServerUtils.getTestEditableURL()); assertTrue(normalTextField.isEditable(), "Validate isEditable method"); } @Test(groups = { "browser-tests" }) @WebTest public void txtFieldTesGetControlName() { Grid.driver().get(TestServerUtils.getTestEditableURL()); assertEquals(disabledTextField.getControlName(), "disabled_text", "Validate GetControlName method"); } @Test(groups = { "browser-tests" }) @WebTest public void txtFieldTesGetParent() { Container dummyParent = new Container(TestObjectRepository.TEXTFIELD_DISABLED_LOCATOR.getValue()); TextField dummyTextField = new TextField(dummyParent, TestObjectRepository.TEXTFIELD_LOCATOR.getValue()); Grid.driver().get(TestServerUtils.getTestEditableURL()); assertEquals(dummyTextField.getParent().hashCode(), dummyParent.hashCode(), "Validate GetParent method"); } @Test(groups = { "browser-tests" }) @WebTest public void txtFieldTestIsElementPresent() { Grid.driver().get(TestServerUtils.getTestEditableURL()); assertTrue(normalTextField.isElementPresent(), "Validate IsElementPresent method"); } @Test(groups = { "browser-tests" }) @WebTest public void txtFieldTestIsVisible() { Grid.driver().get(TestServerUtils.getTestEditableURL()); assertTrue(normalTextField.isVisible(), "Validate IsVisible method"); } @Test(groups = { "browser-tests" }) @WebTest public void txtFieldTestIsEnabled() { Grid.driver().get(TestServerUtils.getTestEditableURL()); assertTrue(normalTextField.isEnabled(), "Validate IsEnabled method"); assertFalse(disabledTextField.isEnabled(), "Validate IsEnabled method"); } @Test(groups = { "browser-tests" }) @WebTest public void txtFieldTestGetSetProperty() { Grid.driver().get(TestServerUtils.getTestEditableURL()); TextField dummyTextField = new TextField(TestObjectRepository.TEXTFIELD_LOCATOR.getValue()); dummyTextField.setProperty("name", "dummyTextField"); assertEquals(dummyTextField.getProperty("name"), "dummyTextField", "Validate Get/SetProperty"); } @Test(groups = { "browser-tests" }) @WebTest public void txtFieldTestTypeTextKeepExistingText() { Grid.driver().get(TestServerUtils.getTestEditableURL()); normalTextField.type("Test1"); assertTrue(normalTextField.getText().matches("Test1"), "Validate Type() method"); normalTextField.type("Test2", false); assertTrue(normalTextField.getText().matches("Test2"), "Validate Type(value, isKeepExistingText) method"); normalTextField.type("Test3", true); assertTrue(normalTextField.getText().matches("Test2Test3"), "Validate Type(value, isKeepExistingText) method"); } @AfterClass(alwaysRun = true) public void tearDown() { Config.setConfigProperty(Config.ConfigProperty.ENABLE_GUI_LOGGING, Boolean.FALSE.toString()); } }
apache-2.0
axbaretto/beam
sdks/java/extensions/sql/src/main/java/org/apache/beam/sdk/extensions/sql/zetasql/ZetaSQLQueryPlanner.java
6540
/* * 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.beam.sdk.extensions.sql.zetasql; import com.google.zetasql.Value; import java.util.Collections; import java.util.Map; import org.apache.beam.sdk.extensions.sql.impl.JdbcConnection; import org.apache.beam.sdk.extensions.sql.impl.ParseException; import org.apache.beam.sdk.extensions.sql.impl.QueryPlanner; import org.apache.beam.sdk.extensions.sql.impl.SqlConversionException; import org.apache.beam.sdk.extensions.sql.impl.rel.BeamLogicalConvention; import org.apache.beam.sdk.extensions.sql.impl.rel.BeamRelNode; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.config.CalciteConnectionConfig; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.jdbc.CalciteSchema; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.plan.Contexts; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.plan.ConventionTraitDef; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.plan.RelTraitDef; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.plan.RelTraitSet; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.prepare.CalciteCatalogReader; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.rel.RelRoot; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.schema.SchemaPlus; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlNode; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlOperatorTable; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.fun.SqlStdOperatorTable; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.parser.SqlParser; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.parser.SqlParserImplFactory; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.util.ChainedSqlOperatorTable; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.tools.FrameworkConfig; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.tools.Frameworks; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.tools.RelConversionException; import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.tools.RuleSet; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList; /** ZetaSQLQueryPlanner. */ public class ZetaSQLQueryPlanner implements QueryPlanner { private final ZetaSQLPlannerImpl plannerImpl; public ZetaSQLQueryPlanner(FrameworkConfig config) { plannerImpl = new ZetaSQLPlannerImpl(config); } public ZetaSQLQueryPlanner(JdbcConnection jdbcConnection, RuleSet[] ruleSets) { plannerImpl = new ZetaSQLPlannerImpl(defaultConfig(jdbcConnection, ruleSets)); } @Override public BeamRelNode convertToBeamRel(String sqlStatement) throws ParseException, SqlConversionException { try { return parseQuery(sqlStatement); } catch (RelConversionException e) { throw new SqlConversionException(e.getCause()); } } @Override public SqlNode parse(String sqlStatement) throws ParseException { return null; } public BeamRelNode convertToBeamRel(String sqlStatement, Map<String, Value> queryParams) throws ParseException, SqlConversionException { try { return parseQuery(sqlStatement, queryParams); } catch (RelConversionException e) { throw new SqlConversionException(e.getCause()); } } public BeamRelNode parseQuery(String sql) throws RelConversionException { return parseQuery(sql, Collections.emptyMap()); } public BeamRelNode parseQuery(String sql, Map<String, Value> queryParams) throws RelConversionException { RelRoot root = plannerImpl.rel(sql, queryParams); RelTraitSet desiredTraits = root.rel .getTraitSet() .replace(BeamLogicalConvention.INSTANCE) .replace(root.collation) .simplify(); BeamRelNode beamRelNode = (BeamRelNode) plannerImpl.transform(0, desiredTraits, root.rel); return beamRelNode; } private FrameworkConfig defaultConfig(JdbcConnection connection, RuleSet[] ruleSets) { final CalciteConnectionConfig config = connection.config(); final SqlParser.ConfigBuilder parserConfig = SqlParser.configBuilder() .setQuotedCasing(config.quotedCasing()) .setUnquotedCasing(config.unquotedCasing()) .setQuoting(config.quoting()) .setConformance(config.conformance()) .setCaseSensitive(config.caseSensitive()); final SqlParserImplFactory parserFactory = config.parserFactory(SqlParserImplFactory.class, null); if (parserFactory != null) { parserConfig.setParserFactory(parserFactory); } final SchemaPlus schema = connection.getRootSchema(); final SchemaPlus defaultSchema = connection.getCurrentSchemaPlus(); final ImmutableList<RelTraitDef> traitDefs = ImmutableList.of(ConventionTraitDef.INSTANCE); final CalciteCatalogReader catalogReader = new CalciteCatalogReader( CalciteSchema.from(schema), ImmutableList.of(defaultSchema.getName()), connection.getTypeFactory(), connection.config()); final SqlOperatorTable opTab0 = connection.config().fun(SqlOperatorTable.class, SqlStdOperatorTable.instance()); return Frameworks.newConfigBuilder() .parserConfig(parserConfig.build()) .defaultSchema(defaultSchema) .traitDefs(traitDefs) .context(Contexts.of(connection.config())) .ruleSets(ruleSets) .costFactory(null) .typeSystem(connection.getTypeFactory().getTypeSystem()) .operatorTable(ChainedSqlOperatorTable.of(opTab0, catalogReader)) .build(); } }
apache-2.0
plekhotkindmytro/Linkedin-oAuth2.0
src/main/java/dmytro/filter/LinkedinFilter.java
2708
package dmytro.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.scribe.model.OAuthConstants; import org.scribe.model.Token; import dmytro.service.linkedin.LinkedinService; /** * Servlet Filter implementation class LinkedinFilter */ public class LinkedinFilter implements Filter { private LinkedinService linkedinService; /** * Default constructor. */ public LinkedinFilter() { linkedinService = new LinkedinService(); } /** * @see Filter#destroy() */ public void destroy() { // TODO Auto-generated method stub } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; HttpSession session = httpRequest.getSession(); Token accessToken = (Token) session.getAttribute(OAuthConstants.ACCESS_TOKEN); if (accessToken == null) { String code = request.getParameter("code"); if (code == null) { String authUrl = linkedinService.getAuthorizationUrl(); // Store authUrl to check "state" query parameter to be the same // after response from authUrl // More info here: https://developer.linkedin.com/docs/oauth2 session.setAttribute("authUrl", authUrl); httpResponse.sendRedirect(authUrl); return; } else { // Implement CSRF attack defense using state // More info here: https://developer.linkedin.com/docs/oauth2 String state = request.getParameter("state"); String authUrl = (String) session.getAttribute("authUrl"); final boolean fromOriginalUser = authUrl.contains("state=" + state); if (fromOriginalUser) { accessToken = linkedinService.getAccessToken(code); session.setAttribute(OAuthConstants.ACCESS_TOKEN, accessToken); // pass the request along the filter chain chain.doFilter(request, response); } else { httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } } } else { // pass the request along the filter chain chain.doFilter(request, response); } } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub } }
apache-2.0
wuhighway/DailyStudy
recyclerviewdm/src/main/java/study/highway/com/stady/recyclerview/CityBean.java
1151
package study.highway.com.stady.recyclerview; import android.text.TextUtils; import com.github.promeg.pinyinhelper.Pinyin; /** * @author JH * @date 2017/4/17 */ public class CityBean { private String tag;//所属的分类(城市的汉语拼音首字母) private String city; private String pinyin; public CityBean(String city) { if (!TextUtils.isEmpty(city)) { char[] chars = city.toCharArray(); StringBuilder ctpy = new StringBuilder(); for (int i = 0; i < chars.length; i++) { ctpy.append(Pinyin.toPinyin(chars[i])); } this.pinyin = ctpy.toString(); this.tag = pinyin.substring(0, 1); } this.city = city; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getPinyin() { return pinyin; } public void setPinyin(String pinyin) { this.pinyin = pinyin; } }
apache-2.0
CognizantOneDevOps/Insights
PlatformService/src/main/java/com/cognizant/devops/platformservice/traceabilitydashboard/util/TraceabilitySummaryUtil.java
11536
/******************************************************************************* * Copyright 2017 Cognizant Technology Solutions * * 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.cognizant.devops.platformservice.traceabilitydashboard.util; import java.text.DateFormat; import java.text.MessageFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.Predicate; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.apache.commons.text.StringSubstitutor; import com.cognizant.devops.platformcommons.core.util.InsightsUtils; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; public class TraceabilitySummaryUtil { static Logger log = LogManager.getLogger(TraceabilitySummaryUtil.class); static final String PATTERN ="[\\[\\](){}\"\\\"\"]"; public static String calTimeDiffrence(String operandName, List<JsonObject> toolRespPayload, String message) throws ParseException { int totalCount = toolRespPayload.size(); // Check if total node count is greater than 0 and payload has both timestamp and author as mandatory properties if (totalCount >= 0 && toolRespPayload.stream().allMatch(predicate->(predicate.has(operandName) && predicate.has("author")))) { int numOfUniqueAuthers = (int) toolRespPayload.stream() .filter(distinctByKey(payload -> payload.get("author").getAsString())).count(); String firstCommitTime = toolRespPayload.get(0).get(operandName).getAsString(); String lastCommitTime = toolRespPayload.get(totalCount - 1).get(operandName).getAsString(); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss"); Date firstDate = sdf.parse(epochToHumanDate(firstCommitTime)); Date secondDate = sdf.parse(epochToHumanDate(lastCommitTime)); long diffInMillies = Math.abs(firstDate.getTime() - secondDate.getTime()); String duration = InsightsUtils.getDateTimeFromEpoch(diffInMillies); MessageFormat mf = new MessageFormat(message); return mf.format(new Object[] { duration, numOfUniqueAuthers }); } return ""; } public static String calSUM(String operandName, JsonArray operandValue, List<JsonObject> toolRespPayload, String message) { try { int totalCount = toolRespPayload.size(); List<String> statusList = new ArrayList<>(); for (JsonElement values : operandValue) { statusList.add(values.getAsString()); } if (totalCount >= 0 && toolRespPayload.stream().anyMatch(predicate->predicate.has(operandName))) { int count = (int) toolRespPayload.stream() .filter(payload -> payload.has(operandName) && statusList.contains(payload.get(operandName).getAsString())).count(); int rem = totalCount - count; MessageFormat mf = new MessageFormat(message); return mf.format(new Object[] { count, rem }); } } catch (Exception e) { log.error(e); } return ""; } public static String calCount(String operandName, JsonArray operandValue, List<JsonObject> toolRespPayload, String message) { String returnMessage = ""; try { int totalCount = toolRespPayload.size(); Map<String,Integer> valueMap = new HashMap<>(); List<String> operanValueList = StreamSupport.stream(operandValue.spliterator(), false) .map(e -> e.getAsString()) .collect(Collectors.toList()); if (totalCount >= 0 ) { for (int i=0; i<operanValueList.size(); i++) { String operandSingleValue =operanValueList.get(i); int count = (int) toolRespPayload.stream() .filter(payload -> payload.has(operandName) && operandSingleValue.contains(payload.get(operandName).getAsString())).count(); valueMap.put(String.valueOf(i), count); } StringSubstitutor sub = new StringSubstitutor(valueMap, "{", "}"); returnMessage = sub.replace(message); } }catch (Exception e) { log.error(e); } return returnMessage; } public static String calPropertyCount(String operandName, JsonArray operandValue, List<JsonObject> toolRespPayload, String message) { String returnMessage = ""; try { int totalCount = toolRespPayload.size(); Map<String,Integer> valueMap = new HashMap<>(); List<String> operanValueList = StreamSupport.stream(toolRespPayload.spliterator(), false) .filter(payload -> payload.has(operandName) ) .filter( distinctByKey(payload ->payload.get(operandName).getAsString()) ) .map(payload -> payload.get(operandName).getAsString()) .collect( Collectors.toList() ); if (totalCount >= 0 ) { for (int i=0; i<operanValueList.size(); i++) { String operandSingleValue =operanValueList.get(i); int count = (int) toolRespPayload.stream() .filter(payload -> payload.has(operandName) && operandSingleValue.contains(payload.get(operandName).getAsString())).count(); valueMap.put(operandSingleValue, count); } String mapAsString = valueMap.entrySet().stream() .map(entry -> entry.getValue() + " " + entry.getKey()) .collect(Collectors.joining(", ")); MessageFormat mf = new MessageFormat(message); return mf.format(new Object[] { mapAsString }); } }catch (Exception e) { log.error(e); } return returnMessage; } public static String calDistinctCount(String operandName, JsonArray operandValue, List<JsonObject> toolRespPayload, String message) { try { int totalCount = toolRespPayload.size(); List<String> statusList = new ArrayList<>(); for (JsonElement values : operandValue) { statusList.add(values.getAsString()); } if (totalCount >= 0 && toolRespPayload.stream().anyMatch(predicate->predicate.has(operandName))) { List<JsonObject> Names = toolRespPayload.stream() .filter(payload -> payload.has(operandName) ) .filter( distinctByKey(payload ->payload.get(operandName)) ) .collect( Collectors.toList() ); MessageFormat mf = new MessageFormat(message); return mf.format(new Object[] { Names.size() }); } } catch (Exception e) { log.error(e); } return ""; } public static String calPercentage(String operandName, JsonArray operandValue, List<JsonObject> toolRespPayload, String message) { int totalCount = toolRespPayload.size(); List<String> statusList = new ArrayList<>(); for (JsonElement values : operandValue) { statusList.add(values.getAsString()); } if (totalCount >= 0 && toolRespPayload.get(0).has(operandName)) { int count = (int) toolRespPayload.stream() .filter(payload ->statusList.contains(payload.get(operandName).getAsString())).count(); int perc = (count * 100) / totalCount; MessageFormat mf = new MessageFormat(message); return mf.format(new Object[] { perc, totalCount }); } return ""; } public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) { Map<Object, Boolean> map = new ConcurrentHashMap<>(); return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; } private static String epochToHumanDate(String epochtime) { Long epoch = Long.valueOf(epochtime.split("\\.", 2)[0]); Date date = new Date(epoch * 1000L); DateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); return format.format(date); } public static JsonObject timelag(HashMap<String, List<JsonObject>> map, JsonObject dataModel) { HashMap<String, Long> timelagMap = new HashMap<>(); JsonObject timelagObject = new JsonObject(); map.forEach(new BiConsumer<String, List<JsonObject>>() { public void accept(String toolName, List<JsonObject> payload) { JsonObject toolJson = dataModel.get(toolName).getAsJsonObject(); if (toolJson.has("timelagParam")) { JsonArray timelagArray = toolJson.get("timelagParam").getAsJsonArray(); int timelagArraySize = timelagArray.size(); if (timelagArraySize == 1) { String timelagParam = timelagArray.get(0).toString().replaceAll(PATTERN, "") .split(",")[0]; if (calTimelag(timelagParam, payload) != -1) timelagMap.put(toolName, calTimelag(timelagParam, payload)); } else if (timelagArraySize == 2) { String timelagParam1 = timelagArray.get(0).toString().replaceAll(PATTERN, "") .split(":")[0]; String timelagParam2 = timelagArray.get(1).toString().replaceAll(PATTERN, "") .split(":")[0]; if (calTimelag(timelagParam1, timelagParam2, payload) != -1) timelagMap.put(toolName, calTimelag(timelagParam1, timelagParam2, payload)); } } } }); timelagMap.forEach( (toolName, time) -> timelagObject.addProperty(toolName, InsightsUtils.getDateTimeFromEpoch(time))); return timelagObject; } public static long calTimelag(String timelagParam1, String timelagParam2, List<JsonObject> payload) { List<Long> epoch = new ArrayList<>(); String startTime = ""; String endTime = ""; for (JsonObject eachObject : payload) { if (eachObject.has(timelagParam1)) { startTime = eachObject.get(timelagParam1).getAsString(); } if (eachObject.has(timelagParam2)) { endTime = eachObject.get(timelagParam2).getAsString(); } if (!startTime.equals("") && !endTime.equals("")) { Long timeDiff = InsightsUtils.getEpochTime(endTime) - InsightsUtils.getEpochTime(startTime); epoch.add(timeDiff); } } int size = epoch.size(); List<Long> epochTimeList = new ArrayList<>(); for (int i = 0; i < size; i++) { if (i != size - 1) { long firstElement = epoch.get(i); long secondElement = epoch.get(i + 1); epochTimeList.add(Math.abs(firstElement - secondElement)); } } if (!epochTimeList.isEmpty()) { return (long) epochTimeList.stream().mapToLong(val -> val).average().getAsDouble(); } return -1; } public static long calTimelag(String timelagParam, List<JsonObject> payload) { List<Long> epoch = new ArrayList<>(); for (JsonObject eachObject : payload) { if (eachObject.has(timelagParam)) { String commitTime = eachObject.get(timelagParam).getAsString(); epoch.add(InsightsUtils.getEpochTime(commitTime)); } } int size = epoch.size(); List<Long> epochTimeList = new ArrayList<>(); for (int i = 0; i < size; i++) { if (i != size - 1) { long firstElement = epoch.get(i); long secondElement = epoch.get(i + 1); epochTimeList.add(firstElement - secondElement); } } if (!epochTimeList.isEmpty()) { return (long) epochTimeList.stream().mapToLong(val -> val).average().getAsDouble(); } return -1; } }
apache-2.0
openwide-java/owsi-core-parent
owsi-core/owsi-core-components/owsi-core-component-jpa-migration/src/main/java/fr/openwide/core/jpa/migration/util/IPreloadAwareMigrationInformation.java
702
package fr.openwide.core.jpa.migration.util; import java.util.Map; import fr.openwide.core.jpa.business.generic.model.GenericEntity; public interface IPreloadAwareMigrationInformation { /* * String used in the IN() clause of the SQL query */ String getParameterIds(); /* * Map used to preload entities to speed up the migration. * The key is the class of the entities to preload. * The value is: * - either the associated SQL query * - or null if the entities are already preloaded. In this case, it's sufficient * to call the listEntitiesByIds method of AbstractEntityMigrationService */ Map<Class<? extends GenericEntity<Long, ?>>, String> getPreloadRequests(); }
apache-2.0
matrix-org/matrix-android-sdk
matrix-sdk/src/main/java/org/matrix/androidsdk/rest/model/bingrules/EventMatchCondition.java
3499
/* * Copyright 2014 OpenMarket Ltd * Copyright 2018 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.matrix.androidsdk.rest.model.bingrules; import android.text.TextUtils; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import org.matrix.androidsdk.rest.model.Event; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; public class EventMatchCondition extends Condition { public String key; public String pattern; private static Map<String, Pattern> mPatternByRule = null; public EventMatchCondition() { kind = Condition.KIND_EVENT_MATCH; } @Override public String toString() { return "EventMatchCondition{" + "key='" + key + ", pattern=" + pattern + '}'; } /** * Returns whether the given event satisfies the condition. * * @param event the event * @return true if the event satisfies the condition */ public boolean isSatisfied(Event event) { String fieldVal = null; // some information are in the decrypted event (like type) if (event.isEncrypted() && (null != event.getClearEvent())) { JsonObject eventJson = event.getClearEvent().toJsonObject(); fieldVal = extractField(eventJson, key); } if (TextUtils.isEmpty(fieldVal)) { JsonObject eventJson = event.toJsonObject(); fieldVal = extractField(eventJson, key); } if (TextUtils.isEmpty(fieldVal)) { return false; } if (TextUtils.equals(pattern, fieldVal)) { return true; } if (null == mPatternByRule) { mPatternByRule = new HashMap<>(); } Pattern patternEx = mPatternByRule.get(pattern); if (null == patternEx) { patternEx = Pattern.compile(globToRegex(pattern), Pattern.CASE_INSENSITIVE); mPatternByRule.put(pattern, patternEx); } return patternEx.matcher(fieldVal).matches(); } private String extractField(JsonObject jsonObject, String fieldPath) { String[] fieldParts = fieldPath.split("\\."); JsonElement jsonElement = null; for (String field : fieldParts) { jsonElement = jsonObject.get(field); if (jsonElement == null) { return null; } if (jsonElement.isJsonObject()) { jsonObject = (JsonObject) jsonElement; } } return (jsonElement == null) ? null : jsonElement.getAsString(); } private String globToRegex(String glob) { String res = glob.replace("*", ".*").replace("?", "."); // If no special characters were found (detected here by no replacements having been made), // add asterisks and boundaries to both sides if (res.equals(glob)) { res = "(^|.*\\W)" + res + "($|\\W.*)"; } return res; } }
apache-2.0
EmmanuelSantanaISA/HidroApp
app/src/test/java/com/example/emman/hidroapp/ExampleUnitTest.java
319
package com.example.emman.hidroapp; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
apache-2.0
nate-rcl/irplus
ir_core/src/edu/ur/ir/item/ExtentTypeService.java
2626
/** Copyright 2008 University of Rochester 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 edu.ur.ir.item; import java.io.Serializable; import java.util.List; /** * Extent type service interface for creating and getting extent types. * * @author Sharmila Ranganathan * */ public interface ExtentTypeService extends Serializable{ /** * Get extent types sorted according to order information . * * @param rowStart - start position in paged set * @param numberOfResultsToShow - number of results to get * @param sortType - Order by asc/desc * * @return extent types found */ public List<ExtentType> getExtentTypesOrderByName(final int rowStart, final int numberOfResultsToShow, final String sortType); /** * Get a count of extent types . * * @return - the number of extent types found */ public Long getExtentTypesCount(); /** * Delete a extent type with the specified name. * * @param id */ public boolean deleteExtentType(Long id); /** * Delete the extent type with the specified name. * * @param name */ public boolean deleteExtentType(String name); /** * Get a extent type by name. * * @param name - name of the extent type. * @return - the found extent type or null if the extent type is not found. */ public ExtentType getExtentType(String name); /** * Get a extent type by id * * @param id - unique id of the extent type. * @param lock - upgrade the lock on the data * @return - the found extent type or null if the extent type is not found. */ public ExtentType getExtentType(Long id, boolean lock); /** * Save the extent type. * * @param extentType */ public void saveExtentType(ExtentType extentType); /** * Get all extent types * * @return List of all extent types */ public List<ExtentType> getAllExtentTypes(); }
apache-2.0
fhanik/spring-security
core/src/test/java/org/springframework/security/access/vote/AbstractAccessDecisionManagerTests.java
4474
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.access.vote; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Vector; import org.junit.Test; import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.core.Authentication; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link AbstractAccessDecisionManager}. * * @author Ben Alex */ @SuppressWarnings("unchecked") public class AbstractAccessDecisionManagerTests { @Test public void testAllowIfAccessDecisionManagerDefaults() { List list = new Vector(); DenyAgainVoter denyVoter = new DenyAgainVoter(); list.add(denyVoter); MockDecisionManagerImpl mock = new MockDecisionManagerImpl(list); assertThat(!mock.isAllowIfAllAbstainDecisions()).isTrue(); // default mock.setAllowIfAllAbstainDecisions(true); assertThat(mock.isAllowIfAllAbstainDecisions()).isTrue(); // changed } @Test public void testDelegatesSupportsClassRequests() { List list = new Vector(); list.add(new DenyVoter()); list.add(new MockStringOnlyVoter()); MockDecisionManagerImpl mock = new MockDecisionManagerImpl(list); assertThat(mock.supports(String.class)).isTrue(); assertThat(!mock.supports(Integer.class)).isTrue(); } @Test public void testDelegatesSupportsRequests() { List list = new Vector(); DenyVoter voter = new DenyVoter(); DenyAgainVoter denyVoter = new DenyAgainVoter(); list.add(voter); list.add(denyVoter); MockDecisionManagerImpl mock = new MockDecisionManagerImpl(list); ConfigAttribute attr = new SecurityConfig("DENY_AGAIN_FOR_SURE"); assertThat(mock.supports(attr)).isTrue(); ConfigAttribute badAttr = new SecurityConfig("WE_DONT_SUPPORT_THIS"); assertThat(!mock.supports(badAttr)).isTrue(); } @Test public void testProperlyStoresListOfVoters() { List list = new Vector(); DenyVoter voter = new DenyVoter(); DenyAgainVoter denyVoter = new DenyAgainVoter(); list.add(voter); list.add(denyVoter); MockDecisionManagerImpl mock = new MockDecisionManagerImpl(list); assertThat(mock.getDecisionVoters()).hasSize(list.size()); } @Test public void testRejectsEmptyList() { assertThatIllegalArgumentException().isThrownBy(() -> new MockDecisionManagerImpl(Collections.emptyList())); } @Test public void testRejectsNullVotersList() { assertThatIllegalArgumentException().isThrownBy(() -> new MockDecisionManagerImpl(null)); } @Test public void testRoleVoterAlwaysReturnsTrueToSupports() { RoleVoter rv = new RoleVoter(); assertThat(rv.supports(String.class)).isTrue(); } @Test public void testWillNotStartIfDecisionVotersNotSet() { assertThatIllegalArgumentException().isThrownBy(() -> new MockDecisionManagerImpl(null)); } private class MockDecisionManagerImpl extends AbstractAccessDecisionManager { protected MockDecisionManagerImpl(List<AccessDecisionVoter<? extends Object>> decisionVoters) { super(decisionVoters); } @Override public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) { } } private class MockStringOnlyVoter implements AccessDecisionVoter<Object> { @Override public boolean supports(Class<?> clazz) { return String.class.isAssignableFrom(clazz); } @Override public boolean supports(ConfigAttribute attribute) { throw new UnsupportedOperationException("mock method not implemented"); } @Override public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) { throw new UnsupportedOperationException("mock method not implemented"); } } }
apache-2.0
leopardoooo/cambodia
ycsoft-lib/src/main/java/com/ycsoft/business/dto/core/prod/CProdDto.java
5074
package com.ycsoft.business.dto.core.prod; import com.ycsoft.beans.core.prod.CProd; public class CProdDto extends CProd { /** * */ private static final long serialVersionUID = -2590105154516096344L; private String is_invalid_tariff; private String is_zero_tariff;// 是否零资费 private String allow_pay;// 是否可以续费 private String tariff_name; // 产品资费名称 private String next_tariff_name; // 产品资费名称 private String package_name; private Integer tariff_rent; private String billing_type; private Integer billing_cycle; private Integer owe_fee;//累计欠费 private Integer real_bill;//本月欠费 private Integer all_balance;//余额active_balance+order_balance private String stb_id; private String card_id; private String modem_mac; private String has_dyn; //是否有动态资源('T','F') private String is_pause="F"; //是否能暂停(默认不能暂停) private Integer inactive_balance; private String month_rent_cal_type; private Integer real_balance; private Integer active_balance; private Integer real_fee; private String p_bank_pay; public String getMonth_rent_cal_type() { return month_rent_cal_type; } public void setMonth_rent_cal_type(String month_rent_cal_type) { this.month_rent_cal_type = month_rent_cal_type; } public String getTariff_name() { return tariff_name; } public void setTariff_name(String tariff_name) { this.tariff_name = tariff_name; } public String getStb_id() { return stb_id; } public void setStb_id(String stbId) { stb_id = stbId; } public String getCard_id() { return card_id; } public void setCard_id(String cardId) { card_id = cardId; } public String getModem_mac() { return modem_mac; } public void setModem_mac(String modemMac) { modem_mac = modemMac; } public Integer getBilling_cycle() { return billing_cycle; } public void setBilling_cycle(Integer billingCycle) { billing_cycle = billingCycle; } public String getNext_tariff_name() { return next_tariff_name; } public void setNext_tariff_name(String next_tariff_name) { this.next_tariff_name = next_tariff_name; } public String getIs_zero_tariff() { return is_zero_tariff; } public void setIs_zero_tariff(String is_zero_tariff) { this.is_zero_tariff = is_zero_tariff; } public String getAllow_pay() { return allow_pay; } public void setAllow_pay(String allow_pay) { this.allow_pay = allow_pay; } public String getPackage_name() { return package_name; } public void setPackage_name(String package_name) { this.package_name = package_name; } public Integer getTariff_rent() { return tariff_rent; } public void setTariff_rent(Integer tariff_rent) { this.tariff_rent = tariff_rent; } public String getBilling_type() { return billing_type; } public String getIs_invalid_tariff() { return is_invalid_tariff; } public void setIs_invalid_tariff(String is_invalid_tariff) { this.is_invalid_tariff = is_invalid_tariff; } public void setBilling_type(String billingType) { billing_type = billingType; } public Integer getOwe_fee() { return owe_fee; } public void setOwe_fee(Integer owe_fee) { this.owe_fee = owe_fee; } public Integer getAll_balance() { return all_balance; } public void setAll_balance(Integer all_balance) { this.all_balance = all_balance; } public Integer getReal_bill() { return real_bill; } public void setReal_bill(Integer real_bill) { this.real_bill = real_bill; } public String getHas_dyn() { return has_dyn; } public void setHas_dyn(String has_dyn) { this.has_dyn = has_dyn; } public String getIs_pause() { return is_pause; } public void setIs_pause(String is_pause) { this.is_pause = is_pause; } public Integer getInactive_balance() { return inactive_balance; } public void setInactive_balance(Integer inactive_balance) { this.inactive_balance = inactive_balance; } /** * @return the real_balance */ public Integer getReal_balance() { return real_balance; } /** * @param real_balance the real_balance to set */ public void setReal_balance(Integer real_balance) { this.real_balance = real_balance; } /** * @return the active_balance */ public Integer getActive_balance() { return active_balance; } /** * @param active_balance the active_balance to set */ public void setActive_balance(Integer active_balance) { this.active_balance = active_balance; } /** * @return the real_fee */ public Integer getReal_fee() { return real_fee; } /** * @param real_fee the real_fee to set */ public void setReal_fee(Integer real_fee) { this.real_fee = real_fee; } public String getP_bank_pay() { return p_bank_pay; } public void setP_bank_pay(String p_bank_pay) { this.p_bank_pay = p_bank_pay; } }
apache-2.0
ernestp/consulo
platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProfileManager.java
3324
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.profile.codeInspection; import com.intellij.openapi.Disposable; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.components.StoragePathMacros; import com.intellij.openapi.diagnostic.Logger; import com.intellij.profile.ApplicationProfileManager; import com.intellij.profile.Profile; import com.intellij.profile.ProfileChangeAdapter; import com.intellij.profile.ProfileEx; import com.intellij.psi.search.scope.packageSet.NamedScope; import com.intellij.util.containers.ContainerUtil; import org.jdom.JDOMException; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.util.List; /** * User: anna * Date: 29-Nov-2005 */ public abstract class InspectionProfileManager extends ApplicationProfileManager implements SeverityProvider { @NonNls public static final String INSPECTION_DIR = "inspection"; @NonNls protected static final String FILE_SPEC = StoragePathMacros.ROOT_CONFIG + '/' + INSPECTION_DIR; private final List<ProfileChangeAdapter> myProfileChangeAdapters = ContainerUtil.createLockFreeCopyOnWriteList(); protected static final Logger LOG = Logger.getInstance("#com.intellij.profile.DefaultProfileManager"); public static InspectionProfileManager getInstance() { return ServiceManager.getService(InspectionProfileManager.class); } public InspectionProfileManager() { } protected abstract void initProfiles(); public abstract Profile loadProfile(@NotNull String path) throws IOException, JDOMException; @Override public void addProfileChangeListener(@NotNull final ProfileChangeAdapter listener) { myProfileChangeAdapters.add(listener); } @Override public void addProfileChangeListener(@NotNull ProfileChangeAdapter listener, @NotNull Disposable parentDisposable) { ContainerUtil.add(listener, myProfileChangeAdapters, parentDisposable); } @Override public void removeProfileChangeListener(@NotNull final ProfileChangeAdapter listener) { myProfileChangeAdapters.remove(listener); } @Override public void fireProfileChanged(final Profile profile) { if (profile instanceof ProfileEx) { ((ProfileEx)profile).profileChanged(); } for (ProfileChangeAdapter adapter : myProfileChangeAdapters) { adapter.profileChanged(profile); } } @Override public void fireProfileChanged(final Profile oldProfile, final Profile profile, final NamedScope scope) { for (ProfileChangeAdapter adapter : myProfileChangeAdapters) { adapter.profileActivated(oldProfile, profile); } } @Override public Profile getProfile(@NotNull final String name) { return getProfile(name, true); } }
apache-2.0
hamboomger/hackanton
src/main/java/com/hackanton/crossweb/CrosswebScanJob.java
1655
package com.hackanton.crossweb; import com.hackanton.crossweb.scrapping.CrosswebScannerService; import com.hackanton.event.Event; import com.hackanton.event.EventsSearchConfiguration; import com.hackanton.event.filter.EventFilterService; import com.hackanton.event.filter.IEventsFilter; import com.hackanton.user.User; import com.hackanton.user.UserService; import com.hackanton.user.email.EmailService; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; @Component public class CrosswebScanJob { private final UserService userService; private final CrosswebScannerService crosswebScannerService; private final EventFilterService eventFilterService; private final EmailService emailService; public CrosswebScanJob(UserService userService, CrosswebScannerService crosswebScannerService, EventFilterService eventFilterService, EmailService emailService) { this.userService = userService; this.crosswebScannerService = crosswebScannerService; this.eventFilterService = eventFilterService; this.emailService = emailService; } // @Scheduled public void scan() throws IOException { List<Event> events = crosswebScannerService.scanNewEvents(); List<User> users = userService.getAllUsers(); for (User user : users) { EventsSearchConfiguration searchConfig = user.getSearchConfiguration(); IEventsFilter filter = eventFilterService.createFilter(searchConfig); List<Event> filteredEvents = events.stream() .filter(filter::apply) .collect(Collectors.toList()); emailService.sendNewEvents(user, filteredEvents); } } }
apache-2.0
yesterdaylike/DailyLady
src/com/yesterday/like/PullToRefresh/library/internal/EmptyViewMethodAccessor.java
1389
/******************************************************************************* * Copyright 2011, 2012 Chris Banes. * * 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.yesterday.like.PullToRefresh.library.internal; import android.view.View; /** * Interface that allows PullToRefreshBase to hijack the call to * AdapterView.setEmptyView() * * @author chris */ public interface EmptyViewMethodAccessor { /** * Calls upto AdapterView.setEmptyView() * * @param emptyView - to set as Empty View */ public void setEmptyViewInternal(View emptyView); /** * Should call PullToRefreshBase.setEmptyView() which will then * automatically call through to setEmptyViewInternal() * * @param emptyView - to set as Empty View */ public void setEmptyView(View emptyView); }
apache-2.0
Talend/data-prep
dataprep-backend-service/src/main/java/org/talend/dataprep/dataset/LocalStoreLocationMapping.java
594
package org.talend.dataprep.dataset; import org.springframework.stereotype.Component; import org.talend.dataprep.api.dataset.DataSetLocation; import org.talend.dataprep.api.dataset.json.DataSetLocationMapping; import org.talend.dataprep.api.dataset.location.LocalStoreLocation; @Component public class LocalStoreLocationMapping implements DataSetLocationMapping { @Override public String getLocationType() { return LocalStoreLocation.NAME; } @Override public Class<? extends DataSetLocation> getLocationClass() { return LocalStoreLocation.class; } }
apache-2.0
florianerhard/gedi
GediCore/src/jline/internal/Ansi.java
1575
/** * * Copyright 2017 Florian Erhard * * 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. * */ /* * Copyright (c) 2002-2015, the original author or authors. * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. * * http://www.opensource.org/licenses/bsd-license.php */ package jline.internal; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.fusesource.jansi.AnsiOutputStream; /** * Ansi support. * * @author <a href="mailto:gnodet@gmail.com">Guillaume Nodet</a> * @since 2.13 */ public class Ansi { public static String stripAnsi(String str) { if (str == null) return ""; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); AnsiOutputStream aos = new AnsiOutputStream(baos); aos.write(str.getBytes()); aos.close(); return baos.toString(); } catch (IOException e) { return str; } } }
apache-2.0
servicefabric/servicefabric
services-transport-parent/services-transport-rsocket/src/main/java/io/scalecube/services/transport/rsocket/RSocketClientTransportFactory.java
3176
package io.scalecube.services.transport.rsocket; import io.netty.channel.ChannelOption; import io.rsocket.transport.ClientTransport; import io.rsocket.transport.netty.client.TcpClientTransport; import io.rsocket.transport.netty.client.WebsocketClientTransport; import io.scalecube.net.Address; import java.util.function.Function; import reactor.netty.http.client.HttpClient; import reactor.netty.resources.ConnectionProvider; import reactor.netty.resources.LoopResources; import reactor.netty.tcp.TcpClient; public interface RSocketClientTransportFactory { /** * Returns default rsocket tcp client transport factory. * * @see TcpClientTransport * @return factory function for {@link RSocketClientTransportFactory} */ static Function<LoopResources, RSocketClientTransportFactory> tcp() { return tcp(false); } /** * Returns default rsocket tcp client transport factory. * * @see TcpClientTransport * @param isSecured is client transport secured * @return factory function for {@link RSocketClientTransportFactory} */ static Function<LoopResources, RSocketClientTransportFactory> tcp(boolean isSecured) { return (LoopResources loopResources) -> (RSocketClientTransportFactory) address -> { TcpClient tcpClient = TcpClient.newConnection() .runOn(loopResources) .host(address.host()) .port(address.port()) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.SO_REUSEADDR, true); return TcpClientTransport.create(isSecured ? tcpClient.secure() : tcpClient); }; } /** * Returns default rsocket websocket client transport factory. * * @see WebsocketClientTransport * @return factory function for {@link RSocketClientTransportFactory} */ static Function<LoopResources, RSocketClientTransportFactory> websocket() { return websocket(false); } /** * Returns default rsocket websocket client transport factory. * * @see WebsocketClientTransport * @param isSecured is client transport secured * @return factory function for {@link RSocketClientTransportFactory} */ static Function<LoopResources, RSocketClientTransportFactory> websocket(boolean isSecured) { return (LoopResources loopResources) -> (RSocketClientTransportFactory) address -> { HttpClient httpClient = HttpClient.create(ConnectionProvider.newConnection()) .runOn(loopResources) .host(address.host()) .port(address.port()) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.SO_REUSEADDR, true); httpClient = isSecured ? httpClient.secure() : httpClient; return WebsocketClientTransport.create(httpClient, "/"); }; } ClientTransport clientTransport(Address address); }
apache-2.0
erichwang/presto
presto-tests/src/test/java/io/prestosql/execution/TestGrantOnSchema.java
6874
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.execution; import com.google.common.collect.ImmutableList; import io.prestosql.Session; import io.prestosql.connector.Grants; import io.prestosql.connector.MockConnectorFactory; import io.prestosql.connector.MockConnectorPlugin; import io.prestosql.connector.MutableGrants; import io.prestosql.spi.connector.SchemaTableName; import io.prestosql.spi.security.Identity; import io.prestosql.spi.security.PrestoPrincipal; import io.prestosql.spi.security.Privilege; import io.prestosql.sql.query.QueryAssertions; import io.prestosql.testing.DataProviders; import io.prestosql.testing.DistributedQueryRunner; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.EnumSet; import static io.prestosql.common.Randoms.randomUsername; import static io.prestosql.spi.security.PrincipalType.USER; import static io.prestosql.testing.TestingSession.testSessionBuilder; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class TestGrantOnSchema { private final Session admin = sessionOf("admin"); private final Grants<String> schemaGrants = new MutableGrants<>(); private DistributedQueryRunner queryRunner; private QueryAssertions assertions; @BeforeClass public void initClass() throws Exception { queryRunner = DistributedQueryRunner.builder(admin).build(); MockConnectorFactory connectorFactory = MockConnectorFactory.builder() .withListSchemaNames(session -> ImmutableList.of("information_schema", "default")) .withListTables((session, schema) -> "default".equalsIgnoreCase(schema) ? ImmutableList.of(new SchemaTableName(schema, "table_one")) : ImmutableList.of()) .withSchemaGrants(schemaGrants) .build(); queryRunner.installPlugin(new MockConnectorPlugin(connectorFactory)); queryRunner.createCatalog("local", "mock"); assertions = new QueryAssertions(queryRunner); schemaGrants.grant(new PrestoPrincipal(USER, admin.getUser()), "default", EnumSet.allOf(Privilege.class), true); } @AfterClass(alwaysRun = true) public void teardown() { assertions.close(); assertions = null; } @Test(dataProviderClass = DataProviders.class, dataProvider = "trueFalse") public void testExistingGrants(boolean grantOption) { String username = randomUsername(); Session user = sessionOf(username); schemaGrants.grant(new PrestoPrincipal(USER, user.getUser()), "default", EnumSet.allOf(Privilege.class), grantOption); assertThat(assertions.query(admin, "SHOW SCHEMAS FROM local")).matches("VALUES (VARCHAR 'information_schema'), (VARCHAR 'default')"); assertThat(assertions.query(user, "SHOW SCHEMAS FROM local")).matches("VALUES (VARCHAR 'information_schema'), (VARCHAR 'default')"); assertThat(assertions.query(admin, "SHOW TABLES FROM default")).matches("VALUES (VARCHAR 'table_one')"); assertThat(assertions.query(user, "SHOW TABLES FROM default")).matches("VALUES (VARCHAR 'table_one')"); } @Test(dataProvider = "privileges") public void testValidGrant(String privilege) { String username = randomUsername(); Session user = sessionOf(username); queryRunner.execute(admin, format("GRANT %s ON SCHEMA default TO %s", privilege, username)); assertThat(assertions.query(user, "SHOW SCHEMAS FROM local")).matches("VALUES (VARCHAR 'information_schema'), (VARCHAR 'default')"); assertThat(assertions.query(admin, "SHOW TABLES FROM default")).matches("VALUES (VARCHAR 'table_one')"); assertThat(assertions.query(user, "SHOW TABLES FROM default")).matches("VALUES (VARCHAR 'table_one')"); } @Test(dataProvider = "privileges") public void testValidGrantWithGrantOption(String privilege) { String username = randomUsername(); Session user = sessionOf(username); queryRunner.execute(admin, format("GRANT %s ON SCHEMA default TO %s WITH GRANT OPTION", privilege, username)); assertThat(assertions.query(user, "SHOW SCHEMAS FROM local")).matches("VALUES (VARCHAR 'information_schema'), (VARCHAR 'default')"); assertThat(assertions.query(user, format("GRANT %s ON SCHEMA default TO %s", privilege, randomUsername()))).matches("VALUES (BOOLEAN 'TRUE')"); assertThat(assertions.query(user, format("GRANT %s ON SCHEMA default TO %s WITH GRANT OPTION", privilege, randomUsername()))).matches("VALUES (BOOLEAN 'TRUE')"); } @Test(dataProvider = "privileges") public void testGrantOnNonExistingCatalog(String privilege) { assertThatThrownBy(() -> queryRunner.execute(admin, format("GRANT %s ON SCHEMA missing_catalog.missing_schema TO %s", privilege, randomUsername()))) .hasMessageContaining("Schema 'missing_catalog.missing_schema' does not exist"); } @Test(dataProvider = "privileges") public void testGrantOnNonExistingSchema(String privilege) { assertThatThrownBy(() -> queryRunner.execute(admin, format("GRANT %s ON SCHEMA missing_schema TO %s", privilege, randomUsername()))) .hasMessageContaining("Schema 'local.missing_schema' does not exist"); } @Test(dataProvider = "privileges") public void testAccessDenied(String privilege) { assertThatThrownBy(() -> queryRunner.execute(sessionOf(randomUsername()), format("GRANT %s ON SCHEMA default TO %s", privilege, randomUsername()))) .hasMessageContaining("Access Denied: Cannot grant privilege SELECT on schema default"); } @DataProvider(name = "privileges") public static Object[][] privileges() { return new Object[][] { {"SELECT"}, {"ALL PRIVILEGES"} }; } private static Session sessionOf(String username) { return testSessionBuilder() .setIdentity(Identity.ofUser(username)) .setCatalog("local") .setSchema("default") .build(); } }
apache-2.0
mdewilde/chart
src/main/java/be/ceau/chart/enums/package-info.java
660
/* Copyright 2020 Marceau Dewilde <m@ceau.be> 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. */ /** * Enums used in data and options objects. */ package be.ceau.chart.enums;
apache-2.0
SharedHealth/SHR-Datasense
src/main/java/org/sharedhealth/datasense/aqs/CallableAqsQuery.java
2834
package org.sharedhealth.datasense.aqs; import org.apache.log4j.Logger; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CallableAqsQuery implements Callable<HashMap<String, List<Map<String, Object>>>> { private NamedParameterJdbcTemplate jdbcTemplate; private QueryDefinition queryDefinition; private Map<String, Object> params; private static final Logger logger = Logger.getLogger(CallableAqsQuery.class); public CallableAqsQuery(NamedParameterJdbcTemplate jdbcTemplate, QueryDefinition queryDefinition, Map<String, Object> params) { this.jdbcTemplate = jdbcTemplate; this.queryDefinition = queryDefinition; this.params = params; } @Override public HashMap<String, List<Map<String, Object>>> call() throws Exception { String queryString = queryDefinition.getQueryString(); Pattern p = Pattern.compile("\\:(.*?)\\:"); Matcher m = p.matcher(queryDefinition.getQueryString()); while (m.find()) { String paramName = m.group(1); Object paramValue = params.get(paramName); if (paramValue == null) { String message = "Could not find value for query parameter:" + paramName; logger.error(message); throw new RuntimeException(message); } queryString = queryString.replace(String.format(":%s:", paramName), String.format("%s", paramValue)); } logger.info("Executing query"); logger.debug(queryString); List<Map<String, Object>> queryResults = jdbcTemplate.query(queryString, new RowMapper<Map<String, Object>>() { @Override public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException { Map<String, Object> rowMap = new HashMap<String, Object>(); ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); for (int colIdx = 1; colIdx <= columnCount; colIdx++) { String columnName = metaData.getColumnName(colIdx); Object columnValue = rs.getObject(columnName); rowMap.put(columnName, columnValue); } return rowMap; } }); HashMap<String, List<Map<String, Object>>> results = new HashMap<>(); results.put(queryDefinition.getQueryName(), queryResults); return results; } }
apache-2.0
joewalnes/idea-community
plugins/InspectionGadgets/src/com/siyeh/ig/global/MethodReturnAlwaysIgnoredInspection.java
8805
/* * Copyright 2006 Dave Griffith * * 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.siyeh.ig.global; import com.intellij.analysis.AnalysisScope; import com.intellij.codeInsight.daemon.GroupNames; import com.intellij.codeInspection.*; import com.intellij.codeInspection.reference.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import com.intellij.psi.*; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseGlobalInspection; import com.siyeh.ig.psiutils.MethodInheritanceUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Set; public class MethodReturnAlwaysIgnoredInspection extends BaseGlobalInspection { private static final Logger LOG = Logger.getInstance("MethodReturnAlwaysIgnoredInspection"); private static final Key<Boolean> ALWAYS_IGNORED = Key.create("ALWAYS_IGNORED_METHOD"); @NotNull public String getGroupDisplayName() { return GroupNames.CLASSLAYOUT_GROUP_NAME; } @Nullable public RefGraphAnnotator getAnnotator(RefManager refManager) { return new MethodIgnoredAnnotator(); } public CommonProblemDescriptor[] checkElement(RefEntity refEntity, AnalysisScope scope, InspectionManager manager, GlobalInspectionContext globalContext) { final CommonProblemDescriptor[] originalProblemDescriptors = super.checkElement(refEntity, scope, manager, globalContext); if (!(refEntity instanceof RefMethod)) { return null; } final RefMethod refMethod = (RefMethod) refEntity; if (methodReturnUsed(refMethod)) { markSiblings(refMethod); return originalProblemDescriptors; } if(!(refMethod.getElement() instanceof PsiMethod)) { return originalProblemDescriptors; } final PsiMethod method = (PsiMethod) refMethod.getElement(); if (method == null) { return originalProblemDescriptors; } if (MethodInheritanceUtils.inheritsFromLibraryMethod(method)) { markSiblings(refMethod); return originalProblemDescriptors; } final ProblemDescriptor descriptor = manager.createProblemDescriptor(method, InspectionGadgetsBundle.message("method.return.always.ignored.problem.descriptor"), false, (LocalQuickFix []) null, ProblemHighlightType.GENERIC_ERROR_OR_WARNING); if (originalProblemDescriptors == null) { return new ProblemDescriptor[]{descriptor}; } else { final int numDescriptors = originalProblemDescriptors.length; final ProblemDescriptor[] descriptors = new ProblemDescriptor[numDescriptors + 1]; System.arraycopy(originalProblemDescriptors, 0, numDescriptors + 1, 0, numDescriptors); descriptors[numDescriptors] = descriptor; return descriptors; } } private void markSiblings(RefMethod refMethod) { final Set<RefMethod> siblingMethods = MethodInheritanceUtils.calculateSiblingMethods(refMethod); for (RefMethod siblingMethod : siblingMethods) { siblingMethod.putUserData(ALWAYS_IGNORED, false); } } private static boolean methodReturnUsed(RefMethod refMethod) { final Boolean alwaysIgnored = refMethod.getUserData(ALWAYS_IGNORED); return alwaysIgnored == null || !alwaysIgnored; } protected boolean queryExternalUsagesRequests(final RefManager manager, final GlobalJavaInspectionContext context, final ProblemDescriptionsProcessor descriptionsProcessor) { manager.iterate(new RefJavaVisitor() { @Override public void visitMethod(final RefMethod refMethod) { if (methodReturnUsed(refMethod)) { return; } final GlobalJavaInspectionContext.UsagesProcessor usagesProcessor = new GlobalJavaInspectionContext.UsagesProcessor() { public boolean process(PsiReference psiReference) { final PsiElement psiReferenceExpression = psiReference.getElement(); final PsiElement parent = psiReferenceExpression.getParent(); if (parent instanceof PsiMethodCallExpression && !isIgnoredMethodCall((PsiCallExpression) parent)) { descriptionsProcessor.ignoreElement(refMethod); } return false; } }; context.enqueueMethodUsagesProcessor(refMethod, usagesProcessor); } }); return false; } private static boolean isIgnoredMethodCall (PsiCallExpression methodExpression) { final PsiElement parent = methodExpression.getParent(); return parent instanceof PsiExpressionStatement; } private static class MethodIgnoredAnnotator extends RefGraphAnnotator { public void onInitialize(RefElement refElement) { super.onInitialize(refElement); if (!(refElement instanceof RefMethod)) { return; } final RefMethod refMethod = (RefMethod) refElement; final PsiElement element = refElement.getElement(); if (!(element instanceof PsiMethod)) { return; } final PsiMethod method = (PsiMethod) element; final PsiType returnType = method.getReturnType(); if (PsiType.VOID.equals(returnType)) { return; } LOG.info("onInitialize:" + refMethod.getName()); refElement.putUserData(ALWAYS_IGNORED, true); } public void onMarkReferenced(RefElement refWhat, RefElement refFrom, boolean referencedFromClassInitializer) { super.onMarkReferenced(refWhat, refFrom, referencedFromClassInitializer); if (!(refWhat instanceof RefMethod)) { return; } final RefMethod refMethod = (RefMethod) refWhat; if (methodReturnUsed(refMethod)) { return; } final PsiElement psiElement = refMethod.getElement(); if (!(psiElement instanceof PsiMethod)) { return; } final PsiMethod psiMethod = (PsiMethod) psiElement; LOG.info("onMarkReferenced:" + refMethod.getName()); final PsiElement element = refFrom.getElement(); element.accept(new JavaRecursiveElementVisitor() { @Override public void visitMethodCallExpression(PsiMethodCallExpression call) { if (methodReturnUsed(refMethod)) { return; } super.visitMethodCallExpression(call); if (isIgnoredMethodCall(call)) { return; } final PsiReferenceExpression methodExpression = call.getMethodExpression(); if (methodExpression.isReferenceTo(psiMethod)) { refMethod.putUserData(ALWAYS_IGNORED, false); } } @Override public void visitNewExpression(PsiNewExpression call) { if (methodReturnUsed(refMethod)) { return; } super.visitNewExpression(call); if (isIgnoredMethodCall(call)) { return; } final PsiMethod referedMethod = call.resolveMethod(); if (psiMethod.equals(referedMethod)) { refMethod.putUserData(ALWAYS_IGNORED, false); } } }); } } }
apache-2.0
consulo/consulo-dotnet
msil-psi-impl/src/main/java/consulo/msil/lang/psi/impl/elementType/stub/MsilTypeListStub.java
1248
/* * Copyright 2013-2014 must-be.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 consulo.msil.lang.psi.impl.elementType.stub; import javax.annotation.Nonnull; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubBase; import com.intellij.psi.stubs.StubElement; import consulo.dotnet.psi.DotNetTypeList; /** * @author VISTALL * @since 22.05.14 */ public class MsilTypeListStub extends StubBase<DotNetTypeList> { private final String[] myReferences; public MsilTypeListStub(StubElement parent, IStubElementType elementType, String[] references) { super(parent, elementType); myReferences = references; } @Nonnull public String[] geShortReferences() { return myReferences; } }
apache-2.0
eturka/eturka
chapter_001/src/test/java/ru/job4j/array/RotateArrayTest.java
973
package ru.job4j.array; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Test. * * @author Ekaterina Turka (mailto:ekaterina2rka@gmail.com) * @version $Id$ * @since 0.1 */ public class RotateArrayTest { /** * Test rotate. */ @Test public void whenRotateTwoRowTwoColArrayThenRotatedArray() { RotateArray array = new RotateArray(); int[][] result = array.rotate(new int[][]{{1, 2}, {3, 4}}); int[][] expected = new int[][]{{3, 1}, {4, 2}}; assertThat(result, is(expected)); } /** * Test rotate. */ @Test public void whenRotateThreeRowThreeColArrayThenRotatedArray() { RotateArray array = new RotateArray(); int[][] result = array.rotate(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}); int[][] expected = new int[][]{{7, 4, 1}, {8, 5, 2}, {9, 6, 3}}; assertThat(result, is(expected)); } }
apache-2.0
ZhakyMing/OpenMDMServer
src/main/java/com/jiangge/pojo/Command.java
2233
package com.jiangge.pojo; import java.io.Serializable; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity() @Table(name = "command") public class Command implements Serializable{ private static final long serialVersionUID = -7048625537017892345L; @Id private String id; /**设备编号(和Device主键对应)**/ private String deviceId; /**发送的命令**/ private String command; /**是否执行(3:失败,2:已成功,1:已执行,0:未执行)**/ private String doIt; /**注册时间**/ private Timestamp createTime = new Timestamp(System.currentTimeMillis()); /**命令类型**/ private String ctype; /**类型值**/ private String cvalue; /**执行结果**/ @Column(length = 65535) private String result; /**回调地址**/ private String callBack; public String getCtype() { return ctype; } public void setCtype(String ctype) { this.ctype = ctype; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDeviceId() { return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } public Timestamp getCreateTime() { return createTime; } public void setCreateTime(Timestamp createTime) { this.createTime = createTime; } public String getCommand() { return command; } public void setCommand(String command) { this.command = command; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public String getDoIt() { return doIt; } public void setDoIt(String doIt) { this.doIt = doIt; } public String getCvalue() { return cvalue; } public void setCvalue(String cvalue) { this.cvalue = cvalue; } public String getCallBack() { return callBack; } public void setCallBack(String callBack) { this.callBack = callBack; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-lakeformation/src/main/java/com/amazonaws/services/lakeformation/model/GetLFTagRequest.java
6363
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.lakeformation.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lakeformation-2017-03-31/GetLFTag" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetLFTagRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata * store. It contains database definitions, table definitions, and other control information to manage your Lake * Formation environment. * </p> */ private String catalogId; /** * <p> * The key-name for the LF-tag. * </p> */ private String tagKey; /** * <p> * The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata * store. It contains database definitions, table definitions, and other control information to manage your Lake * Formation environment. * </p> * * @param catalogId * The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent * metadata store. It contains database definitions, table definitions, and other control information to * manage your Lake Formation environment. */ public void setCatalogId(String catalogId) { this.catalogId = catalogId; } /** * <p> * The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata * store. It contains database definitions, table definitions, and other control information to manage your Lake * Formation environment. * </p> * * @return The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent * metadata store. It contains database definitions, table definitions, and other control information to * manage your Lake Formation environment. */ public String getCatalogId() { return this.catalogId; } /** * <p> * The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent metadata * store. It contains database definitions, table definitions, and other control information to manage your Lake * Formation environment. * </p> * * @param catalogId * The identifier for the Data Catalog. By default, the account ID. The Data Catalog is the persistent * metadata store. It contains database definitions, table definitions, and other control information to * manage your Lake Formation environment. * @return Returns a reference to this object so that method calls can be chained together. */ public GetLFTagRequest withCatalogId(String catalogId) { setCatalogId(catalogId); return this; } /** * <p> * The key-name for the LF-tag. * </p> * * @param tagKey * The key-name for the LF-tag. */ public void setTagKey(String tagKey) { this.tagKey = tagKey; } /** * <p> * The key-name for the LF-tag. * </p> * * @return The key-name for the LF-tag. */ public String getTagKey() { return this.tagKey; } /** * <p> * The key-name for the LF-tag. * </p> * * @param tagKey * The key-name for the LF-tag. * @return Returns a reference to this object so that method calls can be chained together. */ public GetLFTagRequest withTagKey(String tagKey) { setTagKey(tagKey); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getCatalogId() != null) sb.append("CatalogId: ").append(getCatalogId()).append(","); if (getTagKey() != null) sb.append("TagKey: ").append(getTagKey()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetLFTagRequest == false) return false; GetLFTagRequest other = (GetLFTagRequest) obj; if (other.getCatalogId() == null ^ this.getCatalogId() == null) return false; if (other.getCatalogId() != null && other.getCatalogId().equals(this.getCatalogId()) == false) return false; if (other.getTagKey() == null ^ this.getTagKey() == null) return false; if (other.getTagKey() != null && other.getTagKey().equals(this.getTagKey()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getCatalogId() == null) ? 0 : getCatalogId().hashCode()); hashCode = prime * hashCode + ((getTagKey() == null) ? 0 : getTagKey().hashCode()); return hashCode; } @Override public GetLFTagRequest clone() { return (GetLFTagRequest) super.clone(); } }
apache-2.0
square/duktape-android
sample-octane/src/main/java/com/example/duktape/octane/Engine.java
1427
/* * Copyright (C) 2019 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.duktape.octane; import com.squareup.duktape.Duktape; import com.squareup.quickjs.QuickJs; import java.io.Closeable; public enum Engine { // Keep order (and thus ordinal) in sync with strings.xml 'engines' array. DUKTAPE { @Override Closeable create() { return Duktape.create(); } @Override Object evaluate(Object instance, String script, String fileName) { return ((Duktape) instance).evaluate(script, fileName); } }, QUICK_JS { @Override Closeable create() { return QuickJs.create(); } @Override Object evaluate(Object instance, String script, String fileName) { return ((QuickJs) instance).evaluate(script, fileName); } }; abstract Closeable create(); abstract Object evaluate(Object instance, String script, String fileName); }
apache-2.0
robsoncardosoti/flowable-engine
modules/flowable-engine/src/test/java/org/flowable/engine/test/json/JsonTest.java
10910
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flowable.engine.test.json; import java.util.HashMap; import java.util.List; import java.util.Map; import org.flowable.engine.history.HistoricVariableInstance; import org.flowable.engine.impl.history.HistoryLevel; import org.flowable.engine.impl.test.HistoryTestHelper; import org.flowable.engine.impl.test.PluggableFlowableTestCase; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.engine.task.Task; import org.flowable.engine.test.Deployment; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; /** * @author Tijs Rademakers * @author Tim Stephenson */ public class JsonTest extends PluggableFlowableTestCase { public static final String MY_JSON_OBJ = "myJsonObj"; public static final String BIG_JSON_OBJ = "bigJsonObj"; protected ObjectMapper objectMapper = new ObjectMapper(); @Override protected void setUp() throws Exception { super.setUp(); } @Deployment public void testJsonObjectAvailable() { Map<String, Object> vars = new HashMap<String, Object>(); ObjectNode varNode = objectMapper.createObjectNode(); varNode.put("var", "myValue"); vars.put(MY_JSON_OBJ, varNode); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testJsonAvailableProcess", vars); // Check JSON has been parsed as expected ObjectNode value = (ObjectNode) runtimeService.getVariable(processInstance.getId(), MY_JSON_OBJ); assertNotNull(value); assertEquals("myValue", value.get("var").asText()); ObjectNode var2Node = objectMapper.createObjectNode(); var2Node.put("var", "myValue"); var2Node.put("var2", "myOtherValue"); runtimeService.setVariable(processInstance.getId(), MY_JSON_OBJ, var2Node); // Check JSON has been updated as expected value = (ObjectNode) runtimeService.getVariable(processInstance.getId(), MY_JSON_OBJ); assertNotNull(value); assertEquals("myValue", value.get("var").asText()); assertEquals("myOtherValue", value.get("var2").asText()); Task task = taskService.createTaskQuery().active().singleResult(); assertNotNull(task); ObjectNode var3Node = objectMapper.createObjectNode(); var3Node.put("var", "myValue"); var3Node.put("var2", "myOtherValue"); var3Node.put("var3", "myThirdValue"); vars = new HashMap<String, Object>(); vars.put(MY_JSON_OBJ, var3Node); vars.put(BIG_JSON_OBJ, createBigJsonObject()); taskService.complete(task.getId(), vars); value = (ObjectNode) runtimeService.getVariable(processInstance.getId(), MY_JSON_OBJ); assertNotNull(value); assertEquals("myValue", value.get("var").asText()); assertEquals("myOtherValue", value.get("var2").asText()); assertEquals("myThirdValue", value.get("var3").asText()); value = (ObjectNode) runtimeService.getVariable(processInstance.getId(), BIG_JSON_OBJ); assertNotNull(value); assertEquals(createBigJsonObject().toString(), value.toString()); task = taskService.createTaskQuery().active().singleResult(); assertNotNull(task); assertEquals("userTaskSuccess", task.getTaskDefinitionKey()); if (HistoryTestHelper.isHistoryLevelAtLeast(HistoryLevel.AUDIT, processEngineConfiguration)) { List<HistoricVariableInstance> historicVariableInstances = historyService.createHistoricVariableInstanceQuery() .processInstanceId(processInstance.getProcessInstanceId()).orderByVariableName().asc().list(); assertEquals(2, historicVariableInstances.size()); assertEquals(BIG_JSON_OBJ, historicVariableInstances.get(0).getVariableName()); value = (ObjectNode) historicVariableInstances.get(0).getValue(); assertNotNull(value); assertEquals(createBigJsonObject().toString(), value.toString()); assertEquals(MY_JSON_OBJ, historicVariableInstances.get(1).getVariableName()); value = (ObjectNode) historicVariableInstances.get(1).getValue(); assertNotNull(value); assertEquals("myValue", value.get("var").asText()); assertEquals("myOtherValue", value.get("var2").asText()); assertEquals("myThirdValue", value.get("var3").asText()); } // It should be possible do remove a json variable runtimeService.removeVariable(processInstance.getId(), MY_JSON_OBJ); assertNull(runtimeService.getVariable(processInstance.getId(), MY_JSON_OBJ)); // It should be possible do remove a longJson variable runtimeService.removeVariable(processInstance.getId(), BIG_JSON_OBJ); assertNull(runtimeService.getVariable(processInstance.getId(), BIG_JSON_OBJ)); } @Deployment public void testDirectJsonPropertyAccess() { Map<String, Object> vars = new HashMap<String, Object>(); ObjectNode varNode = objectMapper.createObjectNode(); varNode.put("var", "myValue"); vars.put("myJsonObj", varNode); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testJsonAvailableProcess", vars); // Check JSON has been parsed as expected ObjectNode value = (ObjectNode) runtimeService.getVariable(processInstance.getId(), "myJsonObj"); assertNotNull(value); assertEquals("myValue", value.get("var").asText()); Task task = taskService.createTaskQuery().active().singleResult(); assertNotNull(task); ObjectNode var3Node = objectMapper.createObjectNode(); var3Node.put("var", "myValue"); var3Node.put("var2", "myOtherValue"); var3Node.put("var3", "myThirdValue"); vars.put("myJsonObj", var3Node); taskService.complete(task.getId(), vars); value = (ObjectNode) runtimeService.getVariable(processInstance.getId(), "myJsonObj"); assertNotNull(value); assertEquals("myValue", value.get("var").asText()); assertEquals("myOtherValue", value.get("var2").asText()); assertEquals("myThirdValue", value.get("var3").asText()); task = taskService.createTaskQuery().active().singleResult(); assertNotNull(task); assertEquals("userTaskSuccess", task.getTaskDefinitionKey()); } @Deployment public void testJsonArrayAvailable() { Map<String, Object> vars = new HashMap<String, Object>(); ArrayNode varArray = objectMapper.createArrayNode(); ObjectNode varNode = objectMapper.createObjectNode(); varNode.put("var", "myValue"); varArray.add(varNode); vars.put("myJsonArr", varArray); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("testJsonAvailableProcess", vars); // Check JSON has been parsed as expected ArrayNode value = (ArrayNode) runtimeService.getVariable(processInstance.getId(), "myJsonArr"); assertNotNull(value); assertEquals("myValue", value.get(0).get("var").asText()); ArrayNode varArray2 = objectMapper.createArrayNode(); varNode = objectMapper.createObjectNode(); varNode.put("var", "myValue"); varArray2.add(varNode); varNode = objectMapper.createObjectNode(); varNode.put("var", "myOtherValue"); varArray2.add(varNode); runtimeService.setVariable(processInstance.getId(), "myJsonArr", varArray2); // Check JSON has been updated as expected value = (ArrayNode) runtimeService.getVariable(processInstance.getId(), "myJsonArr"); assertNotNull(value); assertEquals("myValue", value.get(0).get("var").asText()); assertEquals("myOtherValue", value.get(1).get("var").asText()); Task task = taskService.createTaskQuery().active().singleResult(); assertNotNull(task); ArrayNode varArray3 = objectMapper.createArrayNode(); varNode = objectMapper.createObjectNode(); varNode.put("var", "myValue"); varArray3.add(varNode); varNode = objectMapper.createObjectNode(); varNode.put("var", "myOtherValue"); varArray3.add(varNode); varNode = objectMapper.createObjectNode(); varNode.put("var", "myThirdValue"); varArray3.add(varNode); vars = new HashMap<String, Object>(); vars.put("myJsonArr", varArray3); taskService.complete(task.getId(), vars); value = (ArrayNode) runtimeService.getVariable(processInstance.getId(), "myJsonArr"); assertNotNull(value); assertEquals("myValue", value.get(0).get("var").asText()); assertEquals("myOtherValue", value.get(1).get("var").asText()); assertEquals("myThirdValue", value.get(2).get("var").asText()); task = taskService.createTaskQuery().active().singleResult(); assertNotNull(task); assertEquals("userTaskSuccess", task.getTaskDefinitionKey()); if (HistoryTestHelper.isHistoryLevelAtLeast(HistoryLevel.AUDIT, processEngineConfiguration)) { HistoricVariableInstance historicVariableInstance = historyService.createHistoricVariableInstanceQuery() .processInstanceId(processInstance.getProcessInstanceId()).singleResult(); value = (ArrayNode) historicVariableInstance.getValue(); assertNotNull(value); assertEquals("myValue", value.get(0).get("var").asText()); assertEquals("myOtherValue", value.get(1).get("var").asText()); assertEquals("myThirdValue", value.get(2).get("var").asText()); } } protected ObjectNode createBigJsonObject() { ObjectNode valueNode = objectMapper.createObjectNode(); for (int i = 0; i < 1000; i++) { ObjectNode childNode = objectMapper.createObjectNode(); childNode.put("test", "this is a simple test text"); childNode.put("test2", "this is a simple test2 text"); childNode.put("test3", "this is a simple test3 text"); childNode.put("test4", "this is a simple test4 text"); valueNode.set("var" + i, childNode); } return valueNode; } }
apache-2.0
yoctopus/smartbet
cac/src/main/java/me/yoctopus/cac/notif/NDialog.java
6474
/* * Copyright 2017, Peter Vincent * Licensed under the Apache License, Version 2.0, Wallet. * 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 me.yoctopus.cac.notif; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.support.annotation.StringRes; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.EditText; import android.widget.LinearLayout; import me.yoctopus.cac.util.Func; public class NDialog extends AlertDialog { private String title, message; private DButton positive, negative, neutral; private CListener cListener; private OnAnswer listener; public NDialog(Context context, String title, String message, DButton positive, DButton negative, DButton neutral) { super(context); this.title = title; this.message = message; this.positive = positive; this.negative = negative; this.neutral = neutral; requestWindowFeature(Window.FEATURE_SWIPE_TO_DISMISS); requestWindowFeature(Window.FEATURE_NO_TITLE); setCanceledOnTouchOutside(true); } public NDialog(Context context, String title, String message, DButton positive, DButton negative, DButton neutral, OnAnswer listener) { this(context, title,message, positive, negative, neutral); this.listener = listener; } public void setcListener(CListener cListener) { this.cListener = cListener; } public NDialog(Context context, @StringRes int title, @StringRes int message, DButton positive, DButton negative, DButton neutral) { this(context, context.getResources().getString(title), context.getResources().getString(message), positive, negative, neutral); } @Override public void show() { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle(title); builder.setMessage(message); if (positive != null) { builder.setPositiveButton(positive.getText(), new OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { positive.getListener().onClick(null); } }); } if (negative != null) { builder.setNegativeButton(negative.getText(), new OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { negative.getListener().onClick(null); } }); } if (neutral != null) { builder.setNeutralButton(neutral.getText(), new OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { neutral.getListener().onClick(null); } }); } if (cListener != null && listener == null) { builder.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialogInterface) { cListener.onCancel(dialogInterface); } }); } if (listener != null) { final EditText editText = new EditText(getContext()); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); params.setMargins(Func.dpToPx(50, getContext().getResources()), Func.dpToPx(0, getContext().getResources()), Func.dpToPx(50, getContext().getResources()), Func.dpToPx(0, getContext().getResources())); editText.setLayoutParams(params); builder.setView(editText); if (positive != null) { builder.setPositiveButton(positive.getText(), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { listener.onAnswer(editText.getText().toString()); } }); } } builder.show(); } public static class DButton { private String text; private BListener listener; public DButton(String text, BListener listener) { this.text = text; this.listener = listener; } public String getText() { return text; } public void setText(String text) { this.text = text; } public BListener getListener() { return listener; } public void setListener(BListener listener) { this.listener = listener; } public interface BListener { void onClick(View v); } } public interface CListener { void onCancel(DialogInterface dialogInterface); } public interface OnAnswer { void onAnswer(String t); } }
apache-2.0
bpedersen2/gerrit-verify-status-reporter-plugin
src/main/java/com/urswolfer/gerrit/client/rest/http/changes/VerifyStatusApiRestClient.java
1611
// Copyright (C) 2016 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.urswolfer.gerrit.client.rest.http.changes; import com.google.gerrit.extensions.api.changes.*; import com.google.gerrit.extensions.restapi.RestApiException; import com.urswolfer.gerrit.client.rest.http.GerritRestClient; public class VerifyStatusApiRestClient extends VerifyStatusApi.NotImplemented implements VerifyStatusApi { private final GerritRestClient gerritRestClient; private final RevisionApiRestClient revisionApiRestClient; public VerifyStatusApiRestClient(GerritRestClient gerritRestClient, RevisionApiRestClient revisionApiRestClient) { this.gerritRestClient = gerritRestClient; this.revisionApiRestClient = revisionApiRestClient; } @Override public void verifications(VerifyInput verifyInput) throws RestApiException { String request = revisionApiRestClient.getRequestPath() + "/verify-status~verifications"; String json = gerritRestClient.getGson().toJson(verifyInput); gerritRestClient.postRequest(request, json); } }
apache-2.0
sabriarabacioglu/engerek
infra/util/src/main/java/com/evolveum/midpoint/util/MiscUtil.java
11064
/* * Copyright (c) 2010-2013 Evolveum * * 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.evolveum.midpoint.util; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import java.util.Set; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import org.apache.commons.collections.CollectionUtils; /** * @author semancik * */ public class MiscUtil { private static final int BUFFER_SIZE = 2048; private static DatatypeFactory df = null; static { try { df = DatatypeFactory.newInstance(); } catch (DatatypeConfigurationException dce) { throw new IllegalStateException("Exception while obtaining Datatype Factory instance", dce); } } public static <T> Collection<T> union(Collection<T>... sets) { Set<T> resultSet = new HashSet<T>(); for (Collection<T> set: sets) { if (set != null) { resultSet.addAll(set); } } return resultSet; } public static <T> Collection<? extends T> unionExtends(Collection<? extends T>... sets) { Set<T> resultSet = new HashSet<T>(); for (Collection<? extends T> set: sets) { if (set != null) { resultSet.addAll(set); } } return resultSet; } public static boolean unorderedCollectionEquals(Collection a, Collection b) { Comparator<?> comparator = new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { return o1.equals(o2) ? 0 : 1; } }; return unorderedCollectionEquals(a, b, comparator); } /** * Only zero vs non-zero value of comparator is important. */ public static boolean unorderedCollectionEquals(Collection a, Collection b, Comparator comparator) { if (a == null && b == null) { return true; } if (a == null || b == null) { return false; } Collection outstanding = new ArrayList(b.size()); outstanding.addAll(b); for (Object ao: a) { boolean found = false; Iterator iterator = outstanding.iterator(); while(iterator.hasNext()) { Object oo = iterator.next(); if (comparator.compare(ao, oo) == 0) { iterator.remove(); found = true; } } if (!found) { return false; } } if (!outstanding.isEmpty()) { return false; } return true; } public static int unorderedCollectionHashcode(Collection collection) { // Stupid implmentation, just add all the hashcodes int hashcode = 0; for (Object item: collection) { hashcode += item.hashCode(); } return hashcode; } public static String readFile(File file) throws IOException { StringBuffer fileData = new StringBuffer(BUFFER_SIZE); BufferedReader reader = new BufferedReader(new FileReader(file)); char[] buf = new char[BUFFER_SIZE]; int numRead=0; while((numRead=reader.read(buf)) != -1){ String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[BUFFER_SIZE]; } reader.close(); return fileData.toString(); } public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } /** * Copy a directory and its contents. * * @param src * The name of the directory to copy. * @param dst * The name of the destination directory. * @throws IOException * If the directory could not be copied. */ public static void copyDirectory(File src, File dst) throws IOException { if (src.isDirectory()) { // Create the destination directory if it does not exist. if (!dst.exists()) { dst.mkdirs(); } // Recursively copy sub-directories and files. for (String child : src.list()) { copyDirectory(new File(src, child), new File(dst, child)); } } else { MiscUtil.copyFile(src, dst); } } public static <T> Collection<T> createCollection(T... items) { Collection<T> collection = new ArrayList<T>(items.length); for (T item: items) { collection.add(item); } return collection; } /** * n-ary and that ignores null values. */ public static Boolean and(Boolean... operands) { Boolean result = null; for (Boolean operand: operands) { if (operand == null) { continue; } if (!operand) { return false; } result = true; } return result; } public static boolean equals(Object a, Object b) { if (a == null && b == null) { return true; } if (a == null || b == null) { return false; } return a.equals(b); } /** * Converts a java.util.Date into an instance of XMLGregorianCalendar * * @param date Instance of java.util.Date or a null reference * @return XMLGregorianCalendar instance whose value is based upon the * value in the date parameter. If the date parameter is null then * this method will simply return null. */ public static XMLGregorianCalendar asXMLGregorianCalendar(java.util.Date date) { if (date == null) { return null; } else { GregorianCalendar gc = new GregorianCalendar(); gc.setTimeInMillis(date.getTime()); return df.newXMLGregorianCalendar(gc); } } /** * Converts an XMLGregorianCalendar to an instance of java.util.Date * * @param xgc Instance of XMLGregorianCalendar or a null reference * @return java.util.Date instance whose value is based upon the * value in the xgc parameter. If the xgc parameter is null then * this method will simply return null. */ public static java.util.Date asDate(XMLGregorianCalendar xgc) { if (xgc == null) { return null; } else { return xgc.toGregorianCalendar().getTime(); } } public static java.util.Date asDate(int year, int month, int date, int hrs, int min, int sec) { Calendar cal = Calendar.getInstance(); cal.set(year, month - 1, date, hrs, min, sec); return cal.getTime(); } public static <T> void carthesian(Collection<Collection<T>> dimensions, Processor<Collection<T>> processor) { List<Collection<T>> dimensionList = new ArrayList<Collection<T>>(dimensions.size()); dimensionList.addAll(dimensions); carthesian(new ArrayList<T>(dimensions.size()), dimensionList, 0, processor); } private static <T> void carthesian(List<T> items, List<Collection<T>> dimensions, int dimensionNum, Processor<Collection<T>> processor) { Collection<T> myDimension = dimensions.get(dimensionNum); for (T item: myDimension) { items.add(item); if (dimensionNum < dimensions.size() - 1) { carthesian(items, dimensions, dimensionNum + 1, processor); } else { processor.process(items); } items.remove(items.size() - 1); } } public static String concat(Collection<String> stringCollection) { StringBuilder sb = new StringBuilder(); for (String s: stringCollection) { sb.append(s); } return sb.toString(); } public static boolean isAllNull(Collection<?> collection) { for (Object o: collection) { if (o != null) { return false; } } return true; } public static String getValueWithClass(Object object) { if (object == null) { return "null"; } return "("+object.getClass().getSimpleName() + ")" + object; } public static boolean isNoValue(Collection<?> collection) { if (collection == null) return true; if (collection.isEmpty()) return true; for (Object val : collection) { if (val == null) continue; if (val instanceof String && ((String) val).isEmpty()) continue; return false; } return true; } public static boolean hasNoValue(Collection<?> collection) { if (collection == null) return true; if (collection.isEmpty()) return true; for (Object val : collection) { if (val == null) return true; if (val instanceof String && ((String) val).isEmpty()) return true; } return false; } /** * Shallow clone */ public static <K,V> Map<K,V> cloneMap(Map<K, V> orig) { if (orig == null) { return null; } Map<K,V> clone = new HashMap<K, V>(); for (Entry<K, V> origEntry: orig.entrySet()) { clone.put(origEntry.getKey(), origEntry.getValue()); } return clone; } public static String toString(Object o) { if (o == null) { return "null"; } return o.toString(); } public static List<String> splitLines(String string) { List<String> lines = new ArrayList<String>(); Scanner scanner = new Scanner(string); while (scanner.hasNextLine()) { lines.add(scanner.nextLine()); } return lines; } public static boolean isBetween(XMLGregorianCalendar date, XMLGregorianCalendar start, XMLGregorianCalendar end) { return (date.compare(start) == DatatypeConstants.GREATER || date.compare(start) == DatatypeConstants.EQUAL) && (date.compare(end) == DatatypeConstants.LESSER || date.compare(end) == DatatypeConstants.EQUAL); } public static <T> boolean contains(T element, T[] array) { for (T aElement: array) { if (equals(element, aElement)) { return true; } } return false; } public static String stripHtmlMarkup(String htmlString) { if (htmlString == null) { return null; } return htmlString.replaceAll("<[^>]*>", ""); } }
apache-2.0
msiddalingaiah/MRViewer
src/com/madhu/mr/TextFileReader.java
1400
/* * Copyright 2014 Madhu Siddalingaiah * * 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.madhu.mr; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class TextFileReader extends KeyValueFileReader { private BufferedReader br; private int lineNumber; public TextFileReader(File file) throws Exception { setFile(file); } public TextFileReader() { } public void setFile(File file) throws Exception { br = new BufferedReader(new FileReader(file)); lineNumber = 0; } @Override public KeyValuePair read() throws Exception { String line = br.readLine(); if (line == null) { return null; } KeyValuePair kv = new KeyValuePair(lineNumber, line); lineNumber += 1; return kv; } @Override public void close() throws Exception { br.close(); } @Override public String toString() { return "Text"; } }
apache-2.0
StateStrategyPOC/Server
src/main/java/server_store/ServerGroupResolver.java
1839
package server_store; import server_side_policies.*; import server_state_policies.*; /** * Represents a mapper between {@link common.StoreAction#actionIdentifier} and {@link PolicyCouple} */ public class ServerGroupResolver extends Resolver { @Override protected void fillPoliciesMap() { this.policiesMap.put("@SERVER_GAME_JOIN_GAME", new PolicyCouple(new GameJoinGameStatePolicy(),null)); this.policiesMap.put("@SERVER_GAME_MAKE_ACTION", new PolicyCouple(new GameMakeActionStatePolicy(), new GameMakeActionSidePolicy())); this.policiesMap.put("@SERVER_GAME_ON_DEMAND_START", new PolicyCouple(null, new GameOnDemandStartSidePolicy())); this.policiesMap.put("@SERVER_GAME_POST_MSG", new PolicyCouple(null, new GamePostChatMsgSidePolicy())); this.policiesMap.put("@SERVER_GAMES_ADD_GAME", new PolicyCouple(new GamesAddGameStatePolicy(), null)); this.policiesMap.put("@SERVER_GAMES_END_GAME", new PolicyCouple(new GamesEndGameStatePolicy(),null)); this.policiesMap.put("@SERVER_GAME_STARTABLE_GAME", new PolicyCouple(null, new GameStartableGameSidePolicy())); this.policiesMap.put("@SERVER_GAME_START_GAME", new PolicyCouple(new GameStartGameStatePolicy(), new GameStartGameSidePolicy())); this.policiesMap.put("@SERVER_GAME_TURNTIMEOUT_EXPIRED", new PolicyCouple(new GameTurnTimeoutStatePolicy(), new GameTurnTimeoutSidePolicy())); this.policiesMap.put("@SERVER_GAME_SET_PS", new PolicyCouple(new GameSetPSHandlerStatePolicy(), new GameSetPSHandlerSidePolicy())); this.policiesMap.put("@SERVER_GAME_REMOVE_PLAYER",new PolicyCouple(new GameRemovePlayerStatePolicy(),null)); } }
apache-2.0
dodola/SimpleSmali
src/dodola/flower/dex/LocalInfo.java
788
package dodola.flower.dex; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Created by baidu on 2017/2/25. */ public class LocalInfo { private HashMap<Integer, String> infos = new HashMap<>(20); public String getName(int reg) { return infos.get(reg); } public void setName(int reg, String name) { infos.put(reg, name); } @Override public String toString() { StringBuilder sb = new StringBuilder(); Set<Map.Entry<Integer, String>> entries = infos.entrySet(); for (Map.Entry<Integer, String> entry : entries) { sb.append(" regsiter:" + entry.getKey() + ",name:" + entry.getValue()); } return "LocalInfo{" + "infos=" + sb.toString() + '}'; } }
apache-2.0
lextract/messenger-backend-java
src/java/co/edu/unal/arqsoft/messenger/model/Message.java
4394
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.edu.unal.arqsoft.messenger.model; import java.io.Serializable; import java.util.Collection; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author alex */ @Entity @Table(name = "Message") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Message.findAll", query = "SELECT m FROM Message m") , @NamedQuery(name = "Message.findById", query = "SELECT m FROM Message m WHERE m.id = :id") , @NamedQuery(name = "Message.findByText", query = "SELECT m FROM Message m WHERE m.text = :text") , @NamedQuery(name = "Message.findByDate", query = "SELECT m FROM Message m WHERE m.date = :date")}) public class Message implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "Id") private Integer id; @Basic(optional = false) @NotNull @Size(min = 1, max = 45) @Column(name = "Text") private String text; @Basic(optional = false) @NotNull @Column(name = "Date") @Temporal(TemporalType.TIMESTAMP) private Date date; @JoinColumn(name = "IdConversation", referencedColumnName = "Id") @ManyToOne(optional = false, fetch = FetchType.LAZY) private Conversation idConversation; @JoinColumn(name = "IdUser", referencedColumnName = "Id") @ManyToOne(optional = false, fetch = FetchType.LAZY) private User idUser; @OneToMany(mappedBy = "idLastMessage", fetch = FetchType.LAZY) private Collection<Conversation> conversationCollection; public Message() { } public Message(Integer id) { this.id = id; } public Message(Integer id, String text, Date date) { this.id = id; this.text = text; this.date = date; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Conversation getIdConversation() { return idConversation; } public void setIdConversation(Conversation idConversation) { this.idConversation = idConversation; } public User getIdUser() { return idUser; } public void setIdUser(User idUser) { this.idUser = idUser; } @XmlTransient public Collection<Conversation> getConversationCollection() { return conversationCollection; } public void setConversationCollection(Collection<Conversation> conversationCollection) { this.conversationCollection = conversationCollection; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Message)) { return false; } Message other = (Message) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "co.edu.unal.arqsoft.messenger.model.Message[ id=" + id + " ]"; } }
apache-2.0
egojit8/MaterialEasyAndroid
lib/src/main/java/com/egojit/android/drawable/LineMorphingDrawable.java
19236
package com.egojit.android.drawable; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.xmlpull.v1.XmlPullParser; import android.content.Context; import android.content.res.TypedArray; import android.content.res.XmlResourceParser; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Animatable; import android.graphics.drawable.Drawable; import android.os.SystemClock; import android.support.v4.text.TextUtilsCompat; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.view.View; import android.view.animation.AccelerateInterpolator; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; import com.egojit.android.R; import com.egojit.android.util.ThemeUtil; import com.egojit.android.util.ViewUtil; public class LineMorphingDrawable extends Drawable implements Animatable{ private boolean mRunning = false; private Paint mPaint; private int mPaddingLeft = 12; private int mPaddingTop = 12; private int mPaddingRight = 12; private int mPaddingBottom = 12; private RectF mDrawBound; private int mPrevState; private int mCurState; private long mStartTime; private float mAnimProgress; private int mAnimDuration; private Interpolator mInterpolator; private int mStrokeSize; private int mStrokeColor; private boolean mClockwise; private Paint.Cap mStrokeCap; private Paint.Join mStrokeJoin; private boolean mIsRtl; private Path mPath; private State[] mStates; private LineMorphingDrawable(State[] states, int curState, int paddingLeft, int paddingTop, int paddingRight, int paddingBottom, int animDuration, Interpolator interpolator, int strokeSize, int strokeColor, Paint.Cap strokeCap, Paint.Join strokeJoin, boolean clockwise, boolean isRtl){ mStates = states; mPaddingLeft = paddingLeft; mPaddingTop = paddingTop; mPaddingRight = paddingRight; mPaddingBottom = paddingBottom; mAnimDuration = animDuration; mInterpolator = interpolator; mStrokeSize = strokeSize; mStrokeColor = strokeColor; mStrokeCap = strokeCap; mStrokeJoin = strokeJoin; mClockwise = clockwise; mIsRtl = isRtl; mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeCap(mStrokeCap); mPaint.setStrokeJoin(mStrokeJoin); mPaint.setColor(mStrokeColor); mPaint.setStrokeWidth(mStrokeSize); mDrawBound = new RectF(); mPath = new Path(); switchLineState(curState, false); } @Override public void draw(Canvas canvas) { int restoreCount = canvas.save(); float degrees = (mClockwise ? 180 : -180) * ((mPrevState < mCurState ? 0f : 1f) + mAnimProgress); if(mIsRtl) canvas.scale(-1f, 1f, mDrawBound.centerX(), mDrawBound.centerY()); canvas.rotate(degrees, mDrawBound.centerX(), mDrawBound.centerY()); canvas.drawPath(mPath, mPaint); canvas.restoreToCount(restoreCount); } @Override public void setAlpha(int alpha) { mPaint.setAlpha(alpha); } @Override public void setColorFilter(ColorFilter cf) { mPaint.setColorFilter(cf); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override protected void onBoundsChange(Rect bounds) { super.onBoundsChange(bounds); mDrawBound.left = bounds.left + mPaddingLeft; mDrawBound.top = bounds.top + mPaddingTop; mDrawBound.right = bounds.right - mPaddingRight; mDrawBound.bottom = bounds.bottom - mPaddingBottom; updatePath(); } public void switchLineState(int state, boolean animation){ if(mCurState != state){ mPrevState = mCurState; mCurState = state; if(animation) start(); else{ mAnimProgress = 1f; updatePath(); } } else if(!animation){ mAnimProgress = 1f; updatePath(); } } public boolean setLineState(int state, float progress){ if(mCurState != state){ mPrevState = mCurState; mCurState = state; mAnimProgress = progress; updatePath(); return true; } else if(mAnimProgress != progress){ mAnimProgress = progress; updatePath(); return true; } return false; } public int getLineState(){ return mCurState; } public int getLineStateCount(){ return mStates == null ? 0 : mStates.length; } public float getAnimProgress(){ return mAnimProgress; } private void updatePath(){ mPath.reset(); if(mStates == null) return; if(mAnimProgress == 0f || (mStates[mPrevState].links != null && mAnimProgress < 0.05f)) updatePathWithState(mPath, mStates[mPrevState]); else if(mAnimProgress == 1f || (mStates[mCurState].links != null && mAnimProgress >0.95f)) updatePathWithState(mPath, mStates[mCurState]); else updatePathBetweenStates(mPath, mStates[mPrevState], mStates[mCurState], mInterpolator.getInterpolation(mAnimProgress)); invalidateSelf(); } private void updatePathWithState(Path path, State state){ if(state.links != null){ for(int i = 0; i < state.links.length; i+= 2){ int index1 = state.links[i] * 4; int index2 = state.links[i + 1] * 4; float x1 = getX(state.points[index1]); float y1 = getY(state.points[index1 + 1]); float x2 = getX(state.points[index1 + 2]); float y2 = getY(state.points[index1 + 3]); float x3 = getX(state.points[index2]); float y3 = getY(state.points[index2 + 1]); float x4 = getX(state.points[index2 + 2]); float y4 = getY(state.points[index2 + 3]); if(x1 == x3 && y1 == y3){ path.moveTo(x2, y2); path.lineTo(x1, y1); path.lineTo(x4, y4); } else if(x1 == x4 && y1 == y4){ path.moveTo(x2, y2); path.lineTo(x1, y1); path.lineTo(x3, y3); } else if(x2 == x3 && y2 == y3){ path.moveTo(x1, y1); path.lineTo(x2, y2); path.lineTo(x4, y4); } else{ path.moveTo(x1, y1); path.lineTo(x2, y2); path.lineTo(x3, y3); } } for(int i = 0, count = state.points.length / 4; i < count; i ++){ boolean exist = false; for(int j = 0; j < state.links.length; j++) if(state.links[j] == i){ exist = true; break; } if(exist) continue; int index = i * 4; path.moveTo(getX(state.points[index]), getY(state.points[index + 1])); path.lineTo(getX(state.points[index + 2]), getY(state.points[index + 3])); } } else{ for(int i = 0, count = state.points.length / 4; i < count; i ++){ int index = i * 4; path.moveTo(getX(state.points[index]), getY(state.points[index + 1])); path.lineTo(getX(state.points[index + 2]), getY(state.points[index + 3])); } } } private void updatePathBetweenStates(Path path, State prev, State cur, float progress){ int count = Math.max(prev.points.length, cur.points.length) / 4; for(int i = 0; i < count; i++){ int index = i * 4; float x1; float y1; float x2; float y2; if(index >= prev.points.length){ x1 = 0.5f; y1 = 0.5f; x2 = 0.5f; y2 = 0.5f; } else{ x1 = prev.points[index]; y1 = prev.points[index + 1]; x2 = prev.points[index + 2]; y2 = prev.points[index + 3]; } float x3; float y3; float x4; float y4; if(index >= cur.points.length){ x3 = 0.5f; y3 = 0.5f; x4 = 0.5f; y4 = 0.5f; } else{ x3 = cur.points[index]; y3 = cur.points[index + 1]; x4 = cur.points[index + 2]; y4 = cur.points[index + 3]; } mPath.moveTo(getX(x1 + (x3 - x1) * progress), getY(y1 + (y3 - y1) * progress)); mPath.lineTo(getX(x2 + (x4 - x2) * progress), getY(y2 + (y4 - y2) * progress)); } } private float getX(float value){ return mDrawBound.left + mDrawBound.width() * value; } private float getY(float value){ return mDrawBound.top + mDrawBound.height() * value; } //Animation: based on http://cyrilmottier.com/2012/11/27/actionbar-on-the-move/ private void resetAnimation(){ mStartTime = SystemClock.uptimeMillis(); mAnimProgress = 0f; } @Override public void start() { resetAnimation(); scheduleSelf(mUpdater, SystemClock.uptimeMillis() + ViewUtil.FRAME_DURATION); invalidateSelf(); } @Override public void stop() { if(!isRunning()) return; mRunning = false; unscheduleSelf(mUpdater); invalidateSelf(); } @Override public boolean isRunning() { return mRunning; } @Override public void scheduleSelf(Runnable what, long when) { mRunning = true; super.scheduleSelf(what, when); } private final Runnable mUpdater = new Runnable() { @Override public void run() { update(); } }; private void update(){ long curTime = SystemClock.uptimeMillis(); float value = Math.min(1f, (float)(curTime - mStartTime) / mAnimDuration); if(value == 1f){ setLineState(mCurState, 1f); mRunning = false; } else setLineState(mCurState, mInterpolator.getInterpolation(value)); if(isRunning()) scheduleSelf(mUpdater, SystemClock.uptimeMillis() + ViewUtil.FRAME_DURATION); } public static class State{ float[] points; int[] links; public State(){} public State(float[] points, int[] links){ this.points = points; this.links = links; } } public static class Builder{ private int mCurState; private int mPaddingLeft; private int mPaddingTop; private int mPaddingRight; private int mPaddingBottom; private int mAnimDuration; private Interpolator mInterpolator; private int mStrokeSize; private int mStrokeColor; private boolean mClockwise; private Paint.Cap mStrokeCap; private Paint.Join mStrokeJoin; private boolean mIsRtl; private State[] mStates; private static final String TAG_STATE_LIST = "state-list"; private static final String TAG_STATE = "state"; private static final String TAG_POINTS = "points"; private static final String TAG_LINKS = "links"; private static final String TAG_ITEM = "item"; public Builder(){} public Builder(Context context, int defStyleRes){ this(context, null, 0, defStyleRes); } public Builder(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){ TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LineMorphingDrawable, defStyleAttr, defStyleRes); int resId; if((resId = a.getResourceId(R.styleable.LineMorphingDrawable_lmd_state, 0)) != 0) states(readStates(context, resId)); curState(a.getInteger(R.styleable.LineMorphingDrawable_lmd_curState, 0)); padding(a.getDimensionPixelSize(R.styleable.LineMorphingDrawable_lmd_padding, 0)); paddingLeft(a.getDimensionPixelSize(R.styleable.LineMorphingDrawable_lmd_paddingLeft, mPaddingLeft)); paddingTop(a.getDimensionPixelSize(R.styleable.LineMorphingDrawable_lmd_paddingTop, mPaddingTop)); paddingRight(a.getDimensionPixelSize(R.styleable.LineMorphingDrawable_lmd_paddingRight, mPaddingRight)); paddingBottom(a.getDimensionPixelSize(R.styleable.LineMorphingDrawable_lmd_paddingBottom, mPaddingBottom)); animDuration(a.getInteger(R.styleable.LineMorphingDrawable_lmd_animDuration, context.getResources().getInteger(android.R.integer.config_mediumAnimTime))); if((resId = a.getResourceId(R.styleable.LineMorphingDrawable_lmd_interpolator, 0)) != 0) interpolator(AnimationUtils.loadInterpolator(context, resId)); strokeSize(a.getDimensionPixelSize(R.styleable.LineMorphingDrawable_lmd_strokeSize, ThemeUtil.dpToPx(context, 3))); strokeColor(a.getColor(R.styleable.LineMorphingDrawable_lmd_strokeColor, 0xFFFFFFFF)); int cap = a.getInteger(R.styleable.LineMorphingDrawable_lmd_strokeCap, 0); if(cap == 0) strokeCap(Paint.Cap.BUTT); else if(cap == 1) strokeCap(Paint.Cap.ROUND); else strokeCap(Paint.Cap.SQUARE); int join = a.getInteger(R.styleable.LineMorphingDrawable_lmd_strokeJoin, 0); if(join == 0) strokeJoin(Paint.Join.MITER); else if(join == 1) strokeJoin(Paint.Join.ROUND); else strokeJoin(Paint.Join.BEVEL); clockwise(a.getBoolean(R.styleable.LineMorphingDrawable_lmd_clockwise, true)); int direction = a.getInteger(R.styleable.LineMorphingDrawable_lmd_layoutDirection, View.LAYOUT_DIRECTION_LTR); if(direction == View.LAYOUT_DIRECTION_LOCALE) rtl(TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == ViewCompat.LAYOUT_DIRECTION_RTL); else rtl(direction == View.LAYOUT_DIRECTION_RTL); a.recycle(); } private State[] readStates(Context context, int id){ XmlResourceParser parser = null; List<State> states = new ArrayList<>(); try { parser = context.getResources().getXml(id); int eventType = parser.getEventType(); String tagName; boolean lookingForEndOfUnknownTag = false; String unknownTagName = null; // This loop will skip to the state-list start tag do { if (eventType == XmlPullParser.START_TAG) { tagName = parser.getName(); if (tagName.equals(TAG_STATE_LIST)) { eventType = parser.next(); break; } throw new RuntimeException("Expecting menu, got " + tagName); } eventType = parser.next(); } while (eventType != XmlPullParser.END_DOCUMENT); boolean reachedEndOfStateList = false; State state = null; List<String> array = new ArrayList<>(); StringBuilder currentValue = new StringBuilder(); while (!reachedEndOfStateList) { switch (eventType) { case XmlPullParser.START_TAG: if (lookingForEndOfUnknownTag) break; tagName = parser.getName(); switch (tagName) { case TAG_STATE: state = new State(); break; case TAG_POINTS: case TAG_LINKS: array.clear(); break; case TAG_ITEM: currentValue.delete(0, currentValue.length()); break; default: lookingForEndOfUnknownTag = true; unknownTagName = tagName; break; } break; case XmlPullParser.END_TAG: tagName = parser.getName(); if (lookingForEndOfUnknownTag && tagName.equals(unknownTagName)) { lookingForEndOfUnknownTag = false; unknownTagName = null; } switch (tagName) { case TAG_STATE_LIST: reachedEndOfStateList = true; break; case TAG_STATE: states.add(state); break; case TAG_POINTS: state.points = new float[array.size()]; for (int i = 0; i < state.points.length; i++) state.points[i] = Float.parseFloat(array.get(i)); break; case TAG_LINKS: state.links = new int[array.size()]; for (int i = 0; i < state.links.length; i++) state.links[i] = Integer.parseInt(array.get(i)); break; case TAG_ITEM: array.add(currentValue.toString()); break; } break; case XmlPullParser.TEXT: currentValue.append(parser.getText()); break; case XmlPullParser.END_DOCUMENT: reachedEndOfStateList = true; break; } eventType = parser.next(); } } catch (Exception e) {} finally { if(parser != null) parser.close(); } if(states.isEmpty()) return null; return states.toArray(new State[states.size()]); } public LineMorphingDrawable build(){ if(mStrokeCap == null) mStrokeCap = Paint.Cap.BUTT; if(mStrokeJoin == null) mStrokeJoin = Paint.Join.MITER; if(mInterpolator == null) mInterpolator = new AccelerateInterpolator(); return new LineMorphingDrawable(mStates, mCurState, mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom, mAnimDuration, mInterpolator, mStrokeSize, mStrokeColor, mStrokeCap, mStrokeJoin, mClockwise, mIsRtl); } public Builder states(State... states){ mStates = states; return this; } public Builder curState(int state){ mCurState = state; return this; } public Builder padding(int padding){ mPaddingLeft = padding; mPaddingTop = padding; mPaddingRight = padding; mPaddingBottom = padding; return this; } public Builder paddingLeft(int padding){ mPaddingLeft = padding; return this; } public Builder paddingTop(int padding){ mPaddingTop = padding; return this; } public Builder paddingRight(int padding){ mPaddingRight = padding; return this; } public Builder paddingBottom(int padding){ mPaddingBottom = padding; return this; } public Builder animDuration(int duration){ mAnimDuration = duration; return this; } public Builder interpolator(Interpolator interpolator){ mInterpolator = interpolator; return this; } public Builder strokeSize(int size){ mStrokeSize = size; return this; } public Builder strokeColor(int strokeColor){ mStrokeColor = strokeColor; return this; } public Builder strokeCap(Paint.Cap cap){ mStrokeCap = cap; return this; } public Builder strokeJoin(Paint.Join join){ mStrokeJoin = join; return this; } public Builder clockwise(boolean clockwise){ mClockwise = clockwise; return this; } public Builder rtl(boolean rtl){ mIsRtl = rtl; return this; } } }
apache-2.0
xuchenCN/hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/EncryptionZoneManager.java
12114
/** * 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.hadoop.hdfs.server.namenode; import java.io.IOException; import java.util.EnumSet; import java.util.List; import java.util.NavigableMap; import java.util.TreeMap; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.crypto.CipherSuite; import org.apache.hadoop.crypto.CryptoProtocolVersion; import org.apache.hadoop.fs.UnresolvedLinkException; import org.apache.hadoop.fs.XAttr; import org.apache.hadoop.fs.XAttrSetFlag; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.XAttrHelper; import org.apache.hadoop.hdfs.protocol.EncryptionZone; import org.apache.hadoop.hdfs.protocol.SnapshotAccessControlException; import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos; import org.apache.hadoop.hdfs.protocolPB.PBHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.hadoop.fs.BatchedRemoteIterator.BatchedListEntries; import static org.apache.hadoop.hdfs.server.common.HdfsServerConstants .CRYPTO_XATTR_ENCRYPTION_ZONE; /** * Manages the list of encryption zones in the filesystem. * <p/> * The EncryptionZoneManager has its own lock, but relies on the FSDirectory * lock being held for many operations. The FSDirectory lock should not be * taken if the manager lock is already held. */ public class EncryptionZoneManager { public static Logger LOG = LoggerFactory.getLogger(EncryptionZoneManager .class); /** * EncryptionZoneInt is the internal representation of an encryption zone. The * external representation of an EZ is embodied in an EncryptionZone and * contains the EZ's pathname. */ private static class EncryptionZoneInt { private final long inodeId; private final CipherSuite suite; private final CryptoProtocolVersion version; private final String keyName; EncryptionZoneInt(long inodeId, CipherSuite suite, CryptoProtocolVersion version, String keyName) { Preconditions.checkArgument(suite != CipherSuite.UNKNOWN); Preconditions.checkArgument(version != CryptoProtocolVersion.UNKNOWN); this.inodeId = inodeId; this.suite = suite; this.version = version; this.keyName = keyName; } long getINodeId() { return inodeId; } CipherSuite getSuite() { return suite; } CryptoProtocolVersion getVersion() { return version; } String getKeyName() { return keyName; } } private final TreeMap<Long, EncryptionZoneInt> encryptionZones; private final FSDirectory dir; private final int maxListEncryptionZonesResponses; /** * Construct a new EncryptionZoneManager. * * @param dir Enclosing FSDirectory */ public EncryptionZoneManager(FSDirectory dir, Configuration conf) { this.dir = dir; encryptionZones = new TreeMap<Long, EncryptionZoneInt>(); maxListEncryptionZonesResponses = conf.getInt( DFSConfigKeys.DFS_NAMENODE_LIST_ENCRYPTION_ZONES_NUM_RESPONSES, DFSConfigKeys.DFS_NAMENODE_LIST_ENCRYPTION_ZONES_NUM_RESPONSES_DEFAULT ); Preconditions.checkArgument(maxListEncryptionZonesResponses >= 0, DFSConfigKeys.DFS_NAMENODE_LIST_ENCRYPTION_ZONES_NUM_RESPONSES + " " + "must be a positive integer." ); } /** * Add a new encryption zone. * <p/> * Called while holding the FSDirectory lock. * * @param inodeId of the encryption zone * @param keyName encryption zone key name */ void addEncryptionZone(Long inodeId, CipherSuite suite, CryptoProtocolVersion version, String keyName) { assert dir.hasWriteLock(); unprotectedAddEncryptionZone(inodeId, suite, version, keyName); } /** * Add a new encryption zone. * <p/> * Does not assume that the FSDirectory lock is held. * * @param inodeId of the encryption zone * @param keyName encryption zone key name */ void unprotectedAddEncryptionZone(Long inodeId, CipherSuite suite, CryptoProtocolVersion version, String keyName) { final EncryptionZoneInt ez = new EncryptionZoneInt( inodeId, suite, version, keyName); encryptionZones.put(inodeId, ez); } /** * Remove an encryption zone. * <p/> * Called while holding the FSDirectory lock. */ void removeEncryptionZone(Long inodeId) { assert dir.hasWriteLock(); encryptionZones.remove(inodeId); } /** * Returns true if an IIP is within an encryption zone. * <p/> * Called while holding the FSDirectory lock. */ boolean isInAnEZ(INodesInPath iip) throws UnresolvedLinkException, SnapshotAccessControlException { assert dir.hasReadLock(); return (getEncryptionZoneForPath(iip) != null); } /** * Returns the path of the EncryptionZoneInt. * <p/> * Called while holding the FSDirectory lock. */ private String getFullPathName(EncryptionZoneInt ezi) { assert dir.hasReadLock(); return dir.getInode(ezi.getINodeId()).getFullPathName(); } /** * Get the key name for an encryption zone. Returns null if <tt>iip</tt> is * not within an encryption zone. * <p/> * Called while holding the FSDirectory lock. */ String getKeyName(final INodesInPath iip) { assert dir.hasReadLock(); EncryptionZoneInt ezi = getEncryptionZoneForPath(iip); if (ezi == null) { return null; } return ezi.getKeyName(); } /** * Looks up the EncryptionZoneInt for a path within an encryption zone. * Returns null if path is not within an EZ. * <p/> * Must be called while holding the manager lock. */ private EncryptionZoneInt getEncryptionZoneForPath(INodesInPath iip) { assert dir.hasReadLock(); Preconditions.checkNotNull(iip); List<INode> inodes = iip.getReadOnlyINodes(); for (int i = inodes.size() - 1; i >= 0; i--) { final INode inode = inodes.get(i); if (inode != null) { final EncryptionZoneInt ezi = encryptionZones.get(inode.getId()); if (ezi != null) { return ezi; } } } return null; } /** * Returns an EncryptionZone representing the ez for a given path. * Returns an empty marker EncryptionZone if path is not in an ez. * * @param iip The INodesInPath of the path to check * @return the EncryptionZone representing the ez for the path. */ EncryptionZone getEZINodeForPath(INodesInPath iip) { final EncryptionZoneInt ezi = getEncryptionZoneForPath(iip); if (ezi == null) { return null; } else { return new EncryptionZone(ezi.getINodeId(), getFullPathName(ezi), ezi.getSuite(), ezi.getVersion(), ezi.getKeyName()); } } /** * Throws an exception if the provided path cannot be renamed into the * destination because of differing encryption zones. * <p/> * Called while holding the FSDirectory lock. * * @param srcIIP source IIP * @param dstIIP destination IIP * @param src source path, used for debugging * @throws IOException if the src cannot be renamed to the dst */ void checkMoveValidity(INodesInPath srcIIP, INodesInPath dstIIP, String src) throws IOException { assert dir.hasReadLock(); final EncryptionZoneInt srcEZI = getEncryptionZoneForPath(srcIIP); final EncryptionZoneInt dstEZI = getEncryptionZoneForPath(dstIIP); final boolean srcInEZ = (srcEZI != null); final boolean dstInEZ = (dstEZI != null); if (srcInEZ) { if (!dstInEZ) { throw new IOException( src + " can't be moved from an encryption zone."); } } else { if (dstInEZ) { throw new IOException( src + " can't be moved into an encryption zone."); } } if (srcInEZ) { if (srcEZI != dstEZI) { final String srcEZPath = getFullPathName(srcEZI); final String dstEZPath = getFullPathName(dstEZI); final StringBuilder sb = new StringBuilder(src); sb.append(" can't be moved from encryption zone "); sb.append(srcEZPath); sb.append(" to encryption zone "); sb.append(dstEZPath); sb.append("."); throw new IOException(sb.toString()); } } } /** * Create a new encryption zone. * <p/> * Called while holding the FSDirectory lock. */ XAttr createEncryptionZone(String src, CipherSuite suite, CryptoProtocolVersion version, String keyName) throws IOException { assert dir.hasWriteLock(); final INodesInPath srcIIP = dir.getINodesInPath4Write(src, false); if (dir.isNonEmptyDirectory(srcIIP)) { throw new IOException( "Attempt to create an encryption zone for a non-empty directory."); } if (srcIIP != null && srcIIP.getLastINode() != null && !srcIIP.getLastINode().isDirectory()) { throw new IOException("Attempt to create an encryption zone for a file."); } EncryptionZoneInt ezi = getEncryptionZoneForPath(srcIIP); if (ezi != null) { throw new IOException("Directory " + src + " is already in an " + "encryption zone. (" + getFullPathName(ezi) + ")"); } final HdfsProtos.ZoneEncryptionInfoProto proto = PBHelper.convert(suite, version, keyName); final XAttr ezXAttr = XAttrHelper .buildXAttr(CRYPTO_XATTR_ENCRYPTION_ZONE, proto.toByteArray()); final List<XAttr> xattrs = Lists.newArrayListWithCapacity(1); xattrs.add(ezXAttr); // updating the xattr will call addEncryptionZone, // done this way to handle edit log loading FSDirXAttrOp.unprotectedSetXAttrs(dir, src, xattrs, EnumSet.of(XAttrSetFlag.CREATE)); return ezXAttr; } /** * Cursor-based listing of encryption zones. * <p/> * Called while holding the FSDirectory lock. */ BatchedListEntries<EncryptionZone> listEncryptionZones(long prevId) throws IOException { assert dir.hasReadLock(); NavigableMap<Long, EncryptionZoneInt> tailMap = encryptionZones.tailMap (prevId, false); final int numResponses = Math.min(maxListEncryptionZonesResponses, tailMap.size()); final List<EncryptionZone> zones = Lists.newArrayListWithExpectedSize(numResponses); int count = 0; for (EncryptionZoneInt ezi : tailMap.values()) { /* Skip EZs that are only present in snapshots. Re-resolve the path to see if the path's current inode ID matches EZ map's INode ID. INode#getFullPathName simply calls getParent recursively, so will return the INode's parents at the time it was snapshotted. It will not contain a reference INode. */ final String pathName = getFullPathName(ezi); INodesInPath iip = dir.getINodesInPath(pathName, false); INode lastINode = iip.getLastINode(); if (lastINode == null || lastINode.getId() != ezi.getINodeId()) { continue; } // Add the EZ to the result list zones.add(new EncryptionZone(ezi.getINodeId(), pathName, ezi.getSuite(), ezi.getVersion(), ezi.getKeyName())); count++; if (count >= numResponses) { break; } } final boolean hasMore = (numResponses < tailMap.size()); return new BatchedListEntries<EncryptionZone>(zones, hasMore); } }
apache-2.0
kohii/smoothcsv
smoothcsv-framework/src/main/java/com/smoothcsv/framework/component/SCTabbedPaneUI.java
6355
/* * Copyright 2016 kohii * * 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.smoothcsv.framework.component; import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.RenderingHints; import javax.swing.JComponent; import javax.swing.JTabbedPane; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicTabbedPaneUI; import com.smoothcsv.swing.utils.SwingUtils; /** * @author kohii */ public class SCTabbedPaneUI extends BasicTabbedPaneUI { private static final Insets TAB_INSETS = new Insets(1, 0, 0, 0); /** * The color to use to fill in the background */ private Color selectedColor; /** * The color to use to fill in the background */ private Color unselectedColor; private Color tabBorderColor; // ------------------------------------------------------------------------------------------------------------------ // Custom installation methods // ------------------------------------------------------------------------------------------------------------------ public static ComponentUI createUI(JComponent c) { return new SCTabbedPaneUI(); } protected void installDefaults() { super.installDefaults(); tabBorderColor = SwingUtils.alpha(Color.BLACK, tabPane.getBackground(), 77); tabInsets = new Insets(7, 1, 7, 0); // tabAreaInsets.left = (calculateTabHeight(0, 0, tabPane.getFont().getSize()) / 4) + 1; selectedTabPadInsets = new Insets(0, 0, 0, 0); selectedColor = tabPane.getBackground(); unselectedColor = SwingUtils.alpha(Color.BLACK, tabPane.getBackground(), 20); tabAreaInsets = new Insets(0, 2, 4, 0); } // ------------------------------------------------------------------------------------------------------------------ // Custom sizing methods // ------------------------------------------------------------------------------------------------------------------ public int getTabRunCount(JTabbedPane pane) { return 1; } protected Insets getContentBorderInsets(int tabPlacement) { return TAB_INSETS; } protected int calculateTabHeight(int tabPlacement, int tabIndex, int fontHeight) { int vHeight = fontHeight + 6; if (vHeight % 2 == 0) { vHeight += 1; } return vHeight; } protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) { return super.calculateTabWidth(tabPlacement, tabIndex, metrics) + metrics.getHeight(); } protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { Graphics2D g2D = (Graphics2D) g; g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int[] xp = new int[]{x - 4, x - 1, x + 3, x + 4, x + 6, x + w - 6, x + w - 4, x + w - 3, x + w + 1, x + w + 4}; int[] yp = new int[]{y + h, y + h - 2, y + 3, y + 1, y, y, y + 1, y + 3, y + h - 2, y + h}; Polygon shape = new Polygon(xp, yp, xp.length); if (isSelected) { g2D.setColor(selectedColor); } else { g2D.setColor(unselectedColor); } g2D.fill(shape); g2D.setColor(tabBorderColor); g2D.draw(shape); if (isSelected) { g2D.setColor(selectedColor); g2D.fillRect(x + 1, y + h - 2, w, 2); g2D.fillRect(x - 1, y + h - 1, w + 2, 3); } // g2D.fill(shape); // // if (runCount > 1) { // g2D.fill(shape); // } } protected void paintTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { // Do nothing } protected void paintContentBorderTopEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) { g.setColor(tabBorderColor); g.drawLine(x, y, x + w, y); // Rectangle selRect = selectedIndex < 0 ? null : getTabBounds(selectedIndex, calcRect); // g.setColor(tabBorderColor); // if (selRect != null) { // g.drawLine(x, y, x + w, y); // g.setColor(Color.BLUE); // g.drawLine(selRect.x, y, selRect.x + selRect.width, y); // } else { // g.drawLine(x, y, x + w, y); // } // g.drawLine(x, y, selRect.x - 1, y); // g.drawLine(x, y, x + w, y); // g.setColor(Color.BLUE); // g.drawLine(selRect.x, y, selRect.x + selRect.width, y); // g.drawLine(selectedRect.x + selectedRect.width + (selectedRect.height / 4), y, x + w, y); // g.setColor(selectedColor); // g.drawLine(selectedRect.x - (selectedRect.height / 4) + 1, y, selectedRect.x // + selectedRect.width + (selectedRect.height / 4) - 1, y); } protected void paintContentBorderRightEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) { // Do nothing } protected void paintContentBorderLeftEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) { // Do nothing } protected void paintContentBorderBottomEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) { // Do nothing } protected void paintFocusIndicator(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect, boolean isSelected) { // Do nothing } protected int getTabLabelShiftY(int tabPlacement, int tabIndex, boolean isSelected) { return 0; } @Override protected void installKeyboardActions() {} @Override protected void uninstallKeyboardActions() {} }
apache-2.0
aleo72/ww-ceem-radar
src/main/java/gov/nasa/worldwind/render/markers/BasicMarkerAttributes.java
9639
/* * Copyright (C) 2012 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration. * All Rights Reserved. */ package gov.nasa.worldwind.render.markers; import gov.nasa.worldwind.render.*; import gov.nasa.worldwind.util.Logging; import javax.media.opengl.*; /** * @author tag * @version $Id: BasicMarkerAttributes.java 1171 2013-02-11 21:45:02Z dcollins $ */ public class BasicMarkerAttributes implements MarkerAttributes { private Material material = Material.WHITE; private Material headingMaterial = Material.RED; protected double headingScale = 3; private String shapeType = BasicMarkerShape.SPHERE; private double opacity = 1d; private double markerPixels = 8d; private double minMarkerSize = 3d; private double maxMarkerSize = Double.MAX_VALUE; public BasicMarkerAttributes() { } public BasicMarkerAttributes(Material material, String shapeType, double opacity) { if (material == null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (shapeType == null) { String message = Logging.getMessage("nullValue.Shape"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.material = material; this.shapeType = shapeType; this.opacity = opacity; } public BasicMarkerAttributes(Material material, String shapeType, double opacity, double markerPixels, double minMarkerSize) { if (material == null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (shapeType == null) { String message = Logging.getMessage("nullValue.Shape"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (opacity < 0) { String message = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (markerPixels < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", markerPixels); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (minMarkerSize < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", minMarkerSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.material = material; this.shapeType = shapeType; this.opacity = opacity; this.markerPixels = markerPixels; this.minMarkerSize = minMarkerSize; } public BasicMarkerAttributes(Material material, String shapeType, double opacity, double markerPixels, double minMarkerSize, double maxMarkerSize) { if (material == null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (shapeType == null) { String message = Logging.getMessage("nullValue.Shape"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (opacity < 0) { String message = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (markerPixels < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", markerPixels); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (minMarkerSize < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", minMarkerSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (maxMarkerSize < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", maxMarkerSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.material = material; this.shapeType = shapeType; this.opacity = opacity; this.markerPixels = markerPixels; this.minMarkerSize = minMarkerSize; this.maxMarkerSize = maxMarkerSize; } public BasicMarkerAttributes(BasicMarkerAttributes that) { if (that == null) { String message = Logging.getMessage("nullValue.AttributesIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.material = that.material; this.headingMaterial = that.headingMaterial; this.headingScale = that.headingScale; this.shapeType = that.shapeType; this.opacity = that.opacity; this.markerPixels = that.markerPixels; this.minMarkerSize = that.minMarkerSize; this.maxMarkerSize = that.maxMarkerSize; } public Material getMaterial() { return material; } public void setMaterial(Material material) { if (material == null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.material = material; } public Material getHeadingMaterial() { return headingMaterial; } public void setHeadingMaterial(Material headingMaterial) { if (material == null) { String message = Logging.getMessage("nullValue.MaterialIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.headingMaterial = headingMaterial; } public double getHeadingScale() { return headingScale; } public void setHeadingScale(double headingScale) { if (headingScale < 0) { String message = Logging.getMessage("generic.ScaleOutOfRange", headingScale); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.headingScale = headingScale; } public String getShapeType() { return shapeType; } public void setShapeType(String shapeType) { if (shapeType == null) { String message = Logging.getMessage("nullValue.ShapeType"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.shapeType = shapeType; } public MarkerShape getShape(DrawContext dc) { MarkerShape shape = (MarkerShape) dc.getValue(this.shapeType); if (shape == null) { shape = BasicMarkerShape.createShapeInstance(this.shapeType); dc.setValue(this.shapeType, shape); } return shape; } public double getOpacity() { return opacity; } public void setOpacity(double opacity) { if (opacity < 0) { String message = Logging.getMessage("generic.OpacityOutOfRange", opacity); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.opacity = opacity; } public double getMarkerPixels() { return markerPixels; } public void setMarkerPixels(double markerPixels) { if (markerPixels < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", markerPixels); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.markerPixels = markerPixels; } public double getMinMarkerSize() { return minMarkerSize; } public void setMinMarkerSize(double minMarkerSize) { if (minMarkerSize < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", minMarkerSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.minMarkerSize = minMarkerSize; } public double getMaxMarkerSize() { return maxMarkerSize; } public void setMaxMarkerSize(double markerSize) { if (markerSize < 0) { String message = Logging.getMessage("generic.SizeOutOfRange", markerSize); Logging.logger().severe(message); throw new IllegalArgumentException(message); } this.maxMarkerSize = markerSize; } public void apply(DrawContext dc) { if (!dc.isPickingMode() && this.material != null) { GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility. if (this.opacity < 1) this.material.apply(gl, GL2.GL_FRONT, (float) this.opacity); else this.material.apply(gl, GL2.GL_FRONT); } } }
apache-2.0
yuanhuan2005/idmcli
src/main/java/com/tcl/idm/model/GroupPolicy.java
493
package com.tcl.idm.model; /** * * * @author yuanhuan * 2014Äê4ÔÂ14ÈÕ ÏÂÎç3:12:48 */ public class GroupPolicy extends PolicyBase { private String groupId; public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } @Override public String toString() { return "GroupPolicy [groupId=" + groupId + ", policyId=" + policyId + ", policyName=" + policyName + ", policyDocument=" + policyDocument + "]"; } }
apache-2.0
ceylon/ceylon
compiler-java/src/org/eclipse/ceylon/ceylondoc/Util.java
25025
/* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * 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 distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.eclipse.ceylon.ceylondoc; import java.io.IOException; import java.io.StringReader; import java.text.BreakIterator; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.regex.Pattern; import javax.swing.text.MutableAttributeSet; import javax.swing.text.html.HTML.Tag; import javax.swing.text.html.HTMLEditorKit.ParserCallback; import javax.swing.text.html.parser.DTD; import javax.swing.text.html.parser.DocumentParser; import javax.swing.text.html.parser.ParserDelegator; import org.eclipse.ceylon.compiler.java.codegen.Decl; import org.eclipse.ceylon.compiler.typechecker.context.PhasedUnit; import org.eclipse.ceylon.model.typechecker.model.Annotated; import org.eclipse.ceylon.model.typechecker.model.Annotation; import org.eclipse.ceylon.model.typechecker.model.Class; import org.eclipse.ceylon.model.typechecker.model.Declaration; import org.eclipse.ceylon.model.typechecker.model.Import; import org.eclipse.ceylon.model.typechecker.model.ModelUtil; import org.eclipse.ceylon.model.typechecker.model.Module; import org.eclipse.ceylon.model.typechecker.model.ModuleImport; import org.eclipse.ceylon.model.typechecker.model.Package; import org.eclipse.ceylon.model.typechecker.model.Referenceable; import org.eclipse.ceylon.model.typechecker.model.Type; import org.eclipse.ceylon.model.typechecker.model.TypeDeclaration; import org.eclipse.ceylon.model.typechecker.model.TypedDeclaration; import org.eclipse.ceylon.model.typechecker.model.Unit; import org.eclipse.ceylon.model.typechecker.model.Value; import com.github.rjeschke.txtmark.BlockEmitter; import com.github.rjeschke.txtmark.Configuration; import com.github.rjeschke.txtmark.Processor; import com.github.rjeschke.txtmark.SpanEmitter; public class Util { private static final Pattern WHITESPACE_PATTERN = Pattern.compile("(?: |\\u00A0|\\s|[\\s&&[^ ]])\\s*"); private static final Set<String> ABBREVIATED_TYPES = new HashSet<String>(); static { ABBREVIATED_TYPES.add("ceylon.language::Callable"); ABBREVIATED_TYPES.add("ceylon.language::Empty"); ABBREVIATED_TYPES.add("ceylon.language::Entry"); ABBREVIATED_TYPES.add("ceylon.language::Sequence"); ABBREVIATED_TYPES.add("ceylon.language::Sequential"); ABBREVIATED_TYPES.add("ceylon.language::Iterable"); } public static String normalizeSpaces(String str) { if (str == null) { return null; } return WHITESPACE_PATTERN.matcher(str).replaceAll(" "); } public static boolean isAbbreviatedType(Declaration decl) { return ABBREVIATED_TYPES.contains(decl.getQualifiedNameString()); } public static String join(String separator, List<String> parts) { StringBuilder stringBuilder = new StringBuilder(); Iterator<String> iterator = parts.iterator(); while(iterator.hasNext()){ stringBuilder.append(iterator.next()); if(iterator.hasNext()) stringBuilder.append(separator); } return stringBuilder.toString(); } private static final int FIRST_LINE_MAX_SIZE = 120; public static String getDoc(Declaration decl, LinkRenderer linkRenderer) { return wikiToHTML(getRawDoc(decl), linkRenderer.useScope(decl)); } public static String getDoc(Module module, LinkRenderer linkRenderer) { return wikiToHTML(getRawDoc(module.getUnit(), module.getAnnotations()), linkRenderer.useScope(module)); } public static String getDoc(ModuleImport moduleImport, LinkRenderer linkRenderer) { return wikiToHTML(getRawDoc(moduleImport.getModule().getUnit(), moduleImport.getAnnotations()), linkRenderer); } public static String getDoc(Package pkg, LinkRenderer linkRenderer) { return wikiToHTML(getRawDoc(pkg.getUnit(), pkg.getAnnotations()), linkRenderer.useScope(pkg)); } public static String getDocFirstLine(Declaration decl, LinkRenderer linkRenderer) { return getDocFirstLine(getRawDoc(decl), linkRenderer.useScope(decl)); } public static String getDocFirstLine(Package pkg, LinkRenderer linkRenderer) { return getDocFirstLine(getRawDoc(pkg.getUnit(), pkg.getAnnotations()), linkRenderer.useScope(pkg)); } public static String getDocFirstLine(Module module, LinkRenderer linkRenderer) { return getDocFirstLine(getRawDoc(module.getUnit(), module.getAnnotations()), linkRenderer.useScope(module)); } public static String getDocFirstLine(String text, LinkRenderer linkRenderer) { String html = wikiToHTML(text, linkRenderer); FirstLineParser parser = new FirstLineParser(); return parser.parseFirstLine(html); } private static class FirstLineParser extends DocumentParser { private boolean done = false; private boolean dots = false; private int lastPosition = 0; private List<Tag> impliedTags = new ArrayList<Tag>(); private List<Tag> openedTags = new ArrayList<Tag>(); private StringBuilder textBuilder = new StringBuilder(); private class FirstLineParserCallback extends ParserCallback { @Override public void handleStartTag(Tag t, MutableAttributeSet a, int pos) { if( done ) { return; } if (a.isDefined(IMPLIED)) { impliedTags.add(t); return; } if( t.isBlock() && textBuilder.length() > 0 ) { done = true; return; } openedTags.add(t); lastPosition = getCurrentPos(); } @Override public void handleEndTag(Tag t, int pos) { if( done ) { return; } if( impliedTags.contains(t) ) { impliedTags.remove(t); return; } int lastIndexOf = openedTags.lastIndexOf(t); if( lastIndexOf != -1 ) { openedTags.remove(lastIndexOf); } lastPosition = getCurrentPos(); } @Override public void handleSimpleTag(Tag t, MutableAttributeSet a, int pos) { if( done ) { return; } lastPosition = getCurrentPos(); } @Override public void handleText(char[] data, int pos) { if( done ) { return; } textBuilder.append(data); String text = textBuilder.toString().replaceAll("\\s*$", ""); String firstLine = trimFirstLine(text); if( !text.equals(firstLine) ) { done = true; lastPosition += data.length - (text.length() - firstLine.length()); return; } lastPosition = getCurrentPos(); } private String trimFirstLine(String text) { // be lenient for Package and Module if(text == null) return ""; // First try to get the first sentence BreakIterator breaker = BreakIterator.getSentenceInstance(); breaker.setText(text); breaker.first(); int dot = breaker.next(); // First sentence is sufficiently short if (dot != BreakIterator.DONE && dot <= FIRST_LINE_MAX_SIZE) { return text.substring(0, dot).replaceAll("\\s*$", ""); } if (text.length() <= FIRST_LINE_MAX_SIZE) { return text; } // First sentence is really long, to try to break on a word breaker = BreakIterator.getWordInstance(); breaker.setText(text); int pos = breaker.first(); while (pos < FIRST_LINE_MAX_SIZE && pos != BreakIterator.DONE) { pos = breaker.next(); } if (pos != BreakIterator.DONE && breaker.previous() != BreakIterator.DONE) { dots = true; return text.substring(0, breaker.current()).replaceAll("\\s*$", ""); } dots = true; return text.substring(0, FIRST_LINE_MAX_SIZE-1); } }; private static DTD getDTD() { try { new ParserDelegator(); // initialize DTD return DTD.getDTD("html32"); } catch (IOException e) { throw new RuntimeException(e); } } private FirstLineParser() { super(getDTD()); } private String parseFirstLine(String html) { try { parse(new StringReader(html), new FirstLineParserCallback(), true); } catch (IOException e) { throw new RuntimeException(e); } StringBuilder result = new StringBuilder(); result.append(html.substring(0, lastPosition).replaceAll("\\s*$", "")); if( dots ) { result.append("…"); } if( !openedTags.isEmpty() ) { Collections.reverse(openedTags); for(Tag t : openedTags) { result.append("</").append(t).append(">"); } } return result.toString(); } } public static <T extends Referenceable & Annotated> List<String> getTags(T decl) { List<String> tags = new ArrayList<String>(); Annotation tagged = Util.getAnnotation(decl.getUnit(), decl.getAnnotations(), "tagged"); if (tagged != null) { tags.addAll(tagged.getPositionalArguments()); } return tags; } public static String wikiToHTML(String text, LinkRenderer linkRenderer) { if( text == null || text.length() == 0 ) { return text; } Configuration config = Configuration.builder() .forceExtentedProfile() .setCodeBlockEmitter(CeylondocBlockEmitter.INSTANCE) .setSpecialLinkEmitter(new CeylondocSpanEmitter(linkRenderer)) .build(); return Processor.process(text, config); } private static String getRawDoc(Declaration decl) { Annotation a = findAnnotation(decl, "doc"); if (a != null) { return a.getPositionalArguments().get(0); } return ""; } public static String getRawDoc(Unit unit, List<Annotation> anns) { Annotation a = getAnnotation(unit, anns, "doc"); if (a != null && a.getPositionalArguments() != null && !a.getPositionalArguments().isEmpty()) { return a.getPositionalArguments().get(0); } return ""; } public static Annotation getAnnotation(ModuleImport moduleImport, String name) { return getAnnotation(moduleImport.getModule().getUnit(), moduleImport.getAnnotations(), name); } public static Annotation getAnnotation(Unit unit, List<Annotation> annotations, String name) { String aliasedName = resolveAliasedName(unit, name); // check that documentation annotation is not hidden by custom annotation if( name.equals(aliasedName) && unit != null ) { Declaration importedDeclaration = unit.getImportedDeclaration(name, null, false); if( importedDeclaration != null && !importedDeclaration.getNameAsString().startsWith("ceylon.language::") ) { return null; } } if (annotations != null) { for (Annotation a : annotations) { if (a.getName().equals(aliasedName)) return a; } } return null; } public static Annotation findAnnotation(Declaration decl, String name) { Annotation a = getAnnotation(decl.getUnit(), decl.getAnnotations(), name); if (a == null && decl.isActual() && decl.getRefinedDeclaration() != decl) { // keep looking up a = findAnnotation(decl.getRefinedDeclaration(), name); } return a; } private static String resolveAliasedName(Unit unit, String name) { if (unit != null) { for (Import i : unit.getImports()) { if (!i.isAmbiguous() && i.getDeclaration().getQualifiedNameString().equals("ceylon.language::" + name)) { return i.getAlias(); } } } return name; } public static String capitalize(String text) { char[] buffer = text.toCharArray(); boolean capitalizeNext = true; for (int i = 0; i < buffer.length; i++) { char ch = buffer[i]; if (Character.isWhitespace(ch)) { capitalizeNext = true; } else if (capitalizeNext) { buffer[i] = Character.toTitleCase(ch); capitalizeNext = false; } } return new String(buffer); } public static String getModifiers(Declaration d) { StringBuilder modifiers = new StringBuilder(); if (d.isShared()) { modifiers.append("shared "); } if (d.isStatic()) { modifiers.append("static "); } if (d.isFormal()) { modifiers.append("formal "); } else { if (d.isActual()) { modifiers.append("actual "); } if (d.isDefault()) { modifiers.append("default "); } } if (Decl.isValue(d)) { Value v = (Value) d; if (v.isVariable()) { modifiers.append("variable "); } } else if (d instanceof Class) { Class c = (Class) d; if (c.isAbstract()) { modifiers.append("abstract "); } if (c.isFinal() && !c.isAnonymous()) { modifiers.append("final "); } if (c.isSealed()) { modifiers.append("sealed "); } } return modifiers.toString().trim(); } public static List<TypeDeclaration> getAncestors(TypeDeclaration decl) { List<TypeDeclaration> ancestors = new ArrayList<TypeDeclaration>(); Type ancestor = decl.getExtendedType(); while (ancestor != null) { ancestors.add(ancestor.getDeclaration()); ancestor = ancestor.getExtendedType(); } return ancestors; } public static List<TypeDeclaration> getSuperInterfaces(TypeDeclaration decl) { Set<TypeDeclaration> superInterfaces = new HashSet<TypeDeclaration>(); for (Type satisfiedType : decl.getSatisfiedTypes()) { superInterfaces.add(satisfiedType.getDeclaration()); superInterfaces.addAll(getSuperInterfaces(satisfiedType.getDeclaration())); } List<TypeDeclaration> list = new ArrayList<TypeDeclaration>(); list.addAll(superInterfaces); removeDuplicates(list); return list; } private static void removeDuplicates(List<TypeDeclaration> superInterfaces) { OUTER: for (int i = 0; i < superInterfaces.size(); i++) { TypeDeclaration decl1 = superInterfaces.get(i); // compare it with each type after it for (int j = i + 1; j < superInterfaces.size(); j++) { TypeDeclaration decl2 = superInterfaces.get(j); if (decl1.equals(decl2)) { if (decl1.getType().isSubtypeOf(decl2.getType())) { // we keep the first one because it is more specific superInterfaces.remove(j); } else { // we keep the second one because it is more specific superInterfaces.remove(i); // since we removed the first type we need to stay at // the same index i--; } // go to next type continue OUTER; } } } } public static boolean isEmpty(String s) { return s == null || s.isEmpty(); } public static boolean isEmpty(Collection<?> c) { return c == null || c.isEmpty(); } public static boolean isThrowable(TypeDeclaration c) { return c.inherits(c.getUnit().getThrowableDeclaration()); } public static String getUnitPackageName(PhasedUnit unit) { // WARNING: TypeChecker VFS alyways uses '/' chars and not platform-dependent ones String path = unit.getPathRelativeToSrcDir(); String file = unit.getUnitFile().getName(); if(!path.endsWith(file)){ throw new RuntimeException("Unit relative path does not end with unit file name: "+path+" and "+file); } path = path.substring(0, path.length() - file.length()); if(path.endsWith("/")) path = path.substring(0, path.length() - 1); return path.replace('/', '.'); } public static String getQuotedFQN(String pkgName, org.eclipse.ceylon.compiler.typechecker.tree.Tree.Declaration decl) { String name = decl.getIdentifier().getText(); // no need to quote the name itself as java keywords are lower-cased and we append a _ to every // lower-case toplevel so they can never be java keywords return pkgName.isEmpty() ? name : org.eclipse.ceylon.compiler.java.util.Util.quoteJavaKeywords(pkgName) + "." + name; } public static Declaration findBottomMostRefinedDeclaration(TypedDeclaration d) { if (d.getContainer() instanceof TypeDeclaration) { Queue<TypeDeclaration> queue = new LinkedList<TypeDeclaration>(); queue.add((TypeDeclaration) d.getContainer()); return findBottomMostRefinedDeclaration(d, queue); } return null; } private static Declaration findBottomMostRefinedDeclaration(TypedDeclaration d, Queue<TypeDeclaration> queue) { TypeDeclaration type = queue.poll(); if (type != null) { if (type != d.getContainer()) { Declaration member = type.getDirectMember(d.getName(), null, false); if (member != null && member.isActual()) { return member; } } if (type.getExtendedType() != null) { queue.add(type.getExtendedType().getDeclaration()); } for (Type satisfiedType: type.getSatisfiedTypes()) { queue.add(satisfiedType.getDeclaration()); } return findBottomMostRefinedDeclaration(d, queue); } return null; } public static String getNameWithContainer(Declaration d) { return "<code><span class='type-identifier'>" + ((TypeDeclaration)d.getContainer()).getName() + "</span>.<span class='" + (d instanceof TypeDeclaration ? "type-identifier" : "identifier") + "'>" + d.getName() + "</span></code>"; } private static class CeylondocBlockEmitter implements BlockEmitter { private static final CeylondocBlockEmitter INSTANCE = new CeylondocBlockEmitter(); @Override public void emitBlock(StringBuilder out, List<String> lines, String meta) { if (lines.isEmpty()) return; if( meta == null || meta.length() == 0 ) { out.append("<pre><code data-language=\"ceylon\">"); } else { out.append("<pre><code data-language=\"").append(meta).append("\">"); } for (final String s : lines) { for (int i = 0; i < s.length(); i++) { final char c = s.charAt(i); switch (c) { case '&': out.append("&amp;"); break; case '<': out.append("&lt;"); break; case '>': out.append("&gt;"); break; default: out.append(c); break; } } out.append('\n'); } out.append("</code></pre>\n"); } } private static class CeylondocSpanEmitter implements SpanEmitter { private final LinkRenderer linkRenderer; public CeylondocSpanEmitter(LinkRenderer linkRenderer) { this.linkRenderer = linkRenderer; } @Override public void emitSpan(StringBuilder out, String content) { int pipeIndex = content.indexOf("|"); String customText = pipeIndex != -1 ? content.substring(0, pipeIndex) : null; String link = new LinkRenderer(linkRenderer). to(content). withinText(true). useCustomText(customText). printTypeParameters(false). printWikiStyleLinks(true). getLink(); out.append(link); } } public static class ReferenceableComparatorByName implements Comparator<Referenceable> { public static final ReferenceableComparatorByName INSTANCE = new ReferenceableComparatorByName(); @Override public int compare(Referenceable a, Referenceable b) { return nullSafeCompare(a.getNameAsString(), b.getNameAsString()); } }; public static class TypeComparatorByName implements Comparator<Type> { public static final TypeComparatorByName INSTANCE = new TypeComparatorByName(); @Override public int compare(Type a, Type b) { return nullSafeCompare(a.getDeclaration().getName(), b.getDeclaration().getName()); } }; public static class ModuleImportComparatorByName implements Comparator<ModuleImport> { public static final ModuleImportComparatorByName INSTANCE = new ModuleImportComparatorByName(); @Override public int compare(ModuleImport a, ModuleImport b) { return nullSafeCompare(a.getModule().getNameAsString(), b.getModule().getNameAsString()); } } static int nullSafeCompare(final String s1, final String s2) { if (s1 == s2) { return 0; } else if (s1 == null) { return -1; } else if (s2 == null) { return 1; } return s1.compareTo(s2); } public static boolean isEnumerated(TypeDeclaration klass) { return klass.getCaseTypes() != null && klass.getSelfType() == null && !klass.getCaseTypes().isEmpty(); } public static String getDeclarationName(Declaration decl) { String name = decl.getName(); if( decl.isConstructor() && name == null ) { name = ((TypeDeclaration)decl.getContainer()).getName(); } return name; } }
apache-2.0
lasanthafdo/siddhi
modules/siddhi-extensions/string/src/main/java/org/wso2/siddhi/extension/string/HexFunctionExtension.java
3342
/* * Copyright (c) 2005-2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.siddhi.extension.string; import org.wso2.siddhi.core.config.ExecutionPlanContext; import org.wso2.siddhi.core.exception.ExecutionPlanRuntimeException; import org.wso2.siddhi.core.executor.ExpressionExecutor; import org.wso2.siddhi.core.executor.function.FunctionExecutor; import org.wso2.siddhi.query.api.definition.Attribute; import org.wso2.siddhi.query.api.exception.ExecutionPlanValidationException; /** * hex(a) * Returns a hexadecimal string representation of str, * where each byte of each character in str is converted to two hexadecimal digits. * Accept Type(s): STRING * Return Type(s): STRING */ public class HexFunctionExtension extends FunctionExecutor { @Override protected void init(ExpressionExecutor[] attributeExpressionExecutors, ExecutionPlanContext executionPlanContext) { if (attributeExpressionExecutors.length != 1) { throw new ExecutionPlanValidationException("Invalid no of arguments passed to str:hex() function, " + "required 1, but found " + attributeExpressionExecutors.length); } Attribute.Type attributeType = attributeExpressionExecutors[0].getReturnType(); if (attributeType != Attribute.Type.STRING) { throw new ExecutionPlanValidationException("Invalid parameter type found for the argument of str:hex() function, " + "required " + Attribute.Type.STRING + "but found " + attributeType.toString()); } } @Override protected Object execute(Object[] data) { return null; //Since the hex function takes in only 1 parameter, this method does not get called. Hence, not implemented. } @Override protected Object execute(Object data) { if (data != null) { char[] chars = ((String) data).toCharArray(); StringBuilder sb = new StringBuilder(); for(char c: chars){ sb.append(Integer.toHexString((int)c)); } return sb.toString(); } else { throw new ExecutionPlanRuntimeException("Input to the str:hex() function cannot be null"); } } @Override public void start() { //Nothing to start. } @Override public void stop() { //Nothing to stop. } @Override public Attribute.Type getReturnType() { return Attribute.Type.STRING; } @Override public Object[] currentState() { return null; //No need to maintain state. } @Override public void restoreState(Object[] state) { //Since there's no need to maintain a state, nothing needs to be done here. } }
apache-2.0
gbif/gbif-api
src/main/java/org/gbif/api/model/registry/eml/temporal/DateRange.java
2835
/* * Copyright 2020 Global Biodiversity Information Facility (GBIF) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gbif.api.model.registry.eml.temporal; import org.gbif.api.util.formatter.TemporalCoverageFormatterVisitor; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.Objects; import java.util.StringJoiner; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.gbif.api.util.PreconditionUtils.checkArgument; /** * A period of time. */ public class DateRange extends TemporalCoverage implements Serializable { private static final long serialVersionUID = -1482059589547915674L; private Date start; private Date end; public DateRange() { } public DateRange(Date start, Date end) { checkArgument(start.before(end), "start date must be before end"); this.start = start; this.end = end; } public Date getEnd() { return end; } public void setEnd(Date end) { this.end = end; } public Date getStart() { return start; } public void setStart(Date start) { this.start = start; } @Override public Collection<String> toKeywords() { StringBuilder sb = new StringBuilder(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); if (start != null) { sb.append(sdf.format(start)); } if (end != null) { if (sb.length() > 0) { sb.append("-"); } sb.append(sdf.format(end)); } return Stream.of(sb.toString()).collect(Collectors.toList()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DateRange dateRange = (DateRange) o; return Objects.equals(start, dateRange.start) && Objects.equals(end, dateRange.end); } @Override public int hashCode() { return Objects.hash(start, end); } @Override public String toString() { return new StringJoiner(", ", DateRange.class.getSimpleName() + "[", "]") .add("start=" + start) .add("end=" + end) .toString(); } @Override public String acceptFormatter(TemporalCoverageFormatterVisitor formatter) { return formatter.format(this); } }
apache-2.0
buzzcogs/AWS
Lab4.1/src/awslabs/lab41/StudentCode.java
8691
/** * Copyright 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not * use this file except in compliance with the License. A copy of the License * is located at * * http://aws.amazon.com/apache2.0/ * * or in the "LICENSE" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package awslabs.lab41; import java.util.List; import com.amazonaws.auth.BasicSessionCredentials; import com.amazonaws.regions.Region; import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClient; import com.amazonaws.services.identitymanagement.model.CreateRoleRequest; import com.amazonaws.services.identitymanagement.model.PutRolePolicyRequest; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClient; import com.amazonaws.services.securitytoken.model.Credentials; /** * Project: Lab4.1 */ public class StudentCode extends SolutionCode { /** * Find and return the ARN for the specified user. * Hint: Use the getUser() method of the client object. The ARN for the user is in the response. * * @param iamClient The IAM client object. * @param userName The name of the user to find. * @return The ARN of the specified user. */ @Override public String prepMode_GetUserArn(AmazonIdentityManagementClient iamClient, String userName) { //TODO: Replace this call to the super class with your own method implementation. return super.prepMode_GetUserArn(iamClient, userName); } /** * Create the specified role using the specified policy and trust relationship text. Return the role ARN. * * @param iamClient The IAM client object. * @param roleName The name of the role to create. * @param policyText The policy to attach to the role. * @param trustRelationshipText The policy defining who can assume the role. * @return The ARN for the newly created role. */ @Override public String prepMode_CreateRole(AmazonIdentityManagementClient iamClient, String roleName, String policyText, String trustRelationshipText) { //TODO: Replace this call to the super class with your own method implementation. //return super.prepMode_CreateRole(iamClient, roleName, policyText, trustRelationshipText); // totally cheated and looked at the answer CreateRoleRequest crr = new CreateRoleRequest().withAssumeRolePolicyDocument(trustRelationshipText).withRoleName(roleName); // grabbing the arn here String arn = iamClient.createRole(crr).getRole().getArn(); // Construct a PutRolePolicyRequest object using the provided policy for the new role. Use whatever policy name you like. PutRolePolicyRequest prpr = new PutRolePolicyRequest().withPolicyDocument(policyText).withPolicyName(roleName+"_policy").withRoleName(roleName); // Submit the request using the putRolePolicy method of the iamClient object. iamClient.putRolePolicy(prpr); // might have to sleep here a bit // to fix this catch authorization failures. If caught throw away credentials and assume the role again // this problem is caused by creating a role and automatically assuming the role. // returning the arn return arn; } /** * Assume the specified role. * Hint: Use the assumeRole() method of the client object. * Optional: You may see an eventual consistency issue here. The AssumeRole permissions may not * have propagated through the system yet which could prevent us from assuming the role. Check for * an AmazonServiceException with an ErrorCode of "AccessDenied" and retry the assume role operation * after a short wait (with exponential back-off on retries). If you decide to stop retrying, * return null. * * @param stsClient The STS client object. * @param roleArn The ARN of the role to assume. * @param roleSessionName The name to use as the role session name. * @return The role credentials, or null if there was a problem. */ @Override public Credentials appMode_AssumeRole(AWSSecurityTokenServiceClient stsClient, String roleArn, String roleSessionName) { //TODO: Replace this call to the super class with your own method implementation. return super.appMode_AssumeRole(stsClient, roleArn, roleSessionName); } /** * Create session/temporary credentials using the provided credentials (previously returned from the assumeRole() * method call), and use the session credentials to create an S3 client object. * * @param credentials The credentials to use for creating session credentials. * @param region The region endpoint to use for the client. * @return The S3 client object. */ @Override public AmazonS3Client appMode_CreateS3Client(Credentials credentials, Region region) { //TODO: Replace this call to the super class with your own method implementation. return super.appMode_CreateS3Client(credentials, region); } /** * Remove any roles that match the names of the roles we'll be creating. This will be called * by the lab controller code to clean up resources that might conflict with proper lab execution. * * @param iamClient The IAM client object. * @param roles The list of role names. */ @Override public void prepMode_RemoveRoles(AmazonIdentityManagementClient iamClient, String... roles) { //TODO: Replace this call to the super class with your own method implementation. super.prepMode_RemoveRoles(iamClient, roles); } /** * Create a bucket that will be used later in the lab. This is housekeeping code that is used to prepare the * environment for the lab exercise. * * @param s3Client The S3 client object. * @param bucketName The bucket to create. */ @Override public void prepMode_CreateBucket(AmazonS3Client s3Client, String bucketName, Region region) { //TODO: Replace this call to the super class with your own method implementation. super.prepMode_CreateBucket(s3Client, bucketName, region); } /** * Test access to the SNS service using the provided credentials by requesting a listing of the SNS topics. * You are free to test in any way you like. Submit any sort of request and watch for an exception. * * @param region The region endpoint to use for the client connection. * @param credentials The credentials to use. * @return True, if the service is accessible. False, if the credentials are rejected. */ @Override public Boolean appMode_TestSnsAccess(Region region, BasicSessionCredentials credentials) { //TODO: Replace this call to the super class with your own method implementation. return super.appMode_TestSnsAccess(region, credentials); } /** * Test access to the SQS service using the provided credentials by requesting a listing of the SQS queues. * You are free to test in any way you like. Submit any sort of request and watch for an exception. * * @param region The region endpoint to use for the client connection. * @param credentials The credentials to use. * @return True, if the service is accessible. False, if the credentials are rejected. */ @Override public Boolean appMode_TestSqsAccess(Region region, BasicSessionCredentials credentials) { //TODO: Replace this call to the super class with your own method implementation. return super.appMode_TestSqsAccess(region, credentials); } /** * Test access to the IAM service using the provided credentials by requesting a listing of the IAM users. * You are free to test in any way you like. Submit any sort of request and watch for an exception. * * @param region The region endpoint to use for the client connection. * @param credentials The credentials to use. * @return True, if the service is accessible. False, if the credentials are rejected. */ @Override public Boolean appMode_TestIamAccess(Region region, BasicSessionCredentials credentials) { //TODO: Replace this call to the super class with your own method implementation. return super.appMode_TestIamAccess(region, credentials); } /** * Cleanup/delete the buckets that were created by the lab. * * @param s3Client The S3 client object. * @param bucketNames The buckets to delete. */ @Override public void removeLabBuckets(AmazonS3Client s3Client, List<String> bucketNames) { //TODO: Replace this call to the super class with your own method implementation. super.removeLabBuckets(s3Client, bucketNames); } }
apache-2.0
stackify/stackify-log-servlet
src/test/java/com/stackify/log/servlet/QueryStringsTest.java
1330
/* * QueryStringsTest.java * Copyright 2014 Stackify */ package com.stackify.log.servlet; import java.io.UnsupportedEncodingException; import java.util.Map; import org.junit.Assert; import org.junit.Test; /** * QueryStringsTest * @author Eric Martin */ public class QueryStringsTest { /** * testToMapWithAmpersands */ @Test public void testToMapWithAmpersands() { Map<String, String> qs = QueryStrings.toMap("n1=v1&n2=v2&n1=v3"); Assert.assertNotNull(qs); Assert.assertEquals(2, qs.size()); Assert.assertEquals("v1,v3", qs.get("n1")); Assert.assertEquals("v2", qs.get("n2")); } /** * testToMapWithSemicolons */ @Test public void testToMapWithSemicolons() { Map<String, String> qs = QueryStrings.toMap("n1=v1;n2=v2;n1=v3"); Assert.assertNotNull(qs); Assert.assertEquals(2, qs.size()); Assert.assertEquals("v1,v3", qs.get("n1")); Assert.assertEquals("v2", qs.get("n2")); } /** * testToMapWithDecoding * @throws UnsupportedEncodingException */ @Test public void testToMapWithDecoding() throws UnsupportedEncodingException { Map<String, String> qs = QueryStrings.toMap("n1%3Dv1%26n2%3Dv2%26n1%3Dv3"); Assert.assertNotNull(qs); Assert.assertEquals(2, qs.size()); Assert.assertEquals("v1,v3", qs.get("n1")); Assert.assertEquals("v2", qs.get("n2")); } }
apache-2.0
millecker/storm-apps
commons/src/at/illecker/storm/commons/wordnet/WordNet.java
22768
/** * 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 at.illecker.storm.commons.wordnet; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import at.illecker.storm.commons.Configuration; import at.illecker.storm.commons.util.io.IOUtils; import edu.mit.jwi.IRAMDictionary; import edu.mit.jwi.RAMDictionary; import edu.mit.jwi.data.ILoadPolicy; import edu.mit.jwi.item.IIndexWord; import edu.mit.jwi.item.ISenseEntry; import edu.mit.jwi.item.ISynset; import edu.mit.jwi.item.ISynsetID; import edu.mit.jwi.item.IWord; import edu.mit.jwi.item.IWordID; import edu.mit.jwi.item.POS; import edu.mit.jwi.item.Pointer; import edu.mit.jwi.morph.WordnetStemmer; import edu.stanford.nlp.ling.TaggedWord; public class WordNet { public static final int MAX_DEPTH_OF_HIERARCHY = 16; private static final Logger LOG = LoggerFactory.getLogger(WordNet.class); private static final WordNet INSTANCE = new WordNet(); private IRAMDictionary m_dict; private File m_wordNetDir; private WordnetStemmer m_wordnetStemmer; private WordNet() { try { String wordNetDictPath = Configuration.getWordNetDict(); LOG.info("WordNet Dictionary: " + wordNetDictPath); m_wordNetDir = new File(Configuration.TEMP_DIR_PATH + File.separator + "dict"); LOG.info("WordNet Extract Location: " + m_wordNetDir.getAbsolutePath()); // check if extract location does exist if (m_wordNetDir.exists()) { IOUtils.delete(m_wordNetDir); } // extract tar.gz file IOUtils.extractTarGz(wordNetDictPath, m_wordNetDir.getParent()); m_dict = new RAMDictionary(m_wordNetDir, ILoadPolicy.NO_LOAD); m_dict.open(); // load into memory long t = System.currentTimeMillis(); m_dict.load(true); LOG.info("Loaded Wordnet into memory in " + (System.currentTimeMillis() - t) + " msec"); m_wordnetStemmer = new WordnetStemmer(m_dict); } catch (IOException e) { LOG.error("IOException: " + e.getMessage()); } catch (InterruptedException e) { LOG.error("InterruptedException: " + e.getMessage()); } } public static WordNet getInstance() { return INSTANCE; } public void close() { if (m_dict != null) { m_dict.close(); } try { IOUtils.delete(m_wordNetDir); } catch (IOException e) { LOG.error("IOException: " + e.getMessage()); } } public boolean contains(String word) { for (POS pos : POS.values()) { for (String stem : m_wordnetStemmer.findStems(word, pos)) { IIndexWord indexWord = m_dict.getIndexWord(stem, pos); if (indexWord != null) return true; } } return false; } public boolean isNoun(String word) { return m_dict.getIndexWord(word, POS.NOUN) != null; } public boolean isAdjective(String word) { return m_dict.getIndexWord(word, POS.ADJECTIVE) != null; } public boolean isAdverb(String word) { return m_dict.getIndexWord(word, POS.ADVERB) != null; } public boolean isVerb(String word) { return m_dict.getIndexWord(word, POS.VERB) != null; } public synchronized POS findPOS(String word) { int maxCount = 0; POS mostLikelyPOS = null; for (POS pos : POS.values()) { // From JavaDoc: The surface form may or may not contain whitespace or // underscores, and may be in mixed case. word = word.replaceAll("\\s", "").replaceAll("_", ""); List<String> stems = m_wordnetStemmer.findStems(word, pos); for (String stem : stems) { IIndexWord indexWord = m_dict.getIndexWord(stem, pos); if (indexWord != null) { int count = 0; for (IWordID wordId : indexWord.getWordIDs()) { IWord aWord = m_dict.getWord(wordId); ISenseEntry senseEntry = m_dict.getSenseEntry(aWord.getSenseKey()); count += senseEntry.getTagCount(); } if (count > maxCount) { maxCount = count; mostLikelyPOS = pos; } } } } return mostLikelyPOS; } public List<String> findStems(String word, POS pos) { return m_wordnetStemmer.findStems(word, pos); } public IIndexWord getIndexWord(String word, POS pos) { List<String> stems = findStems(word, pos); if (stems != null) { if (stems.size() > 1) { LOG.info("Be careful the word '" + word + "' has several lemmatized forms."); } for (String stem : stems) { return m_dict.getIndexWord(stem, pos); // return first stem } } return null; } public String getLemma(ISynset synset) { return synset.getWord(0).getLemma(); } public String getLemma(ISynsetID synsetID) { return getLemma(m_dict.getSynset(synsetID)); } public Set<IIndexWord> getAllIndexWords(String word) { Set<IIndexWord> indexWords = new HashSet<IIndexWord>(); for (POS pos : POS.values()) { IIndexWord indexWord = m_dict.getIndexWord(word, pos); if (indexWord != null) { indexWords.add(indexWord); } } return indexWords; } public ISynset getSynset(String word, POS pos) { IIndexWord indexWord = m_dict.getIndexWord(word, pos); if (indexWord != null) { IWordID wordID = indexWord.getWordIDs().get(0); // use first WordID return m_dict.getWord(wordID).getSynset(); } return null; } public Set<ISynset> getSynsets(IIndexWord indexWord) { Set<ISynset> synsets = new HashSet<ISynset>(); for (IWordID wordID : indexWord.getWordIDs()) { synsets.add(m_dict.getSynset(wordID.getSynsetID())); } return synsets; } public Set<ISynset> getSynsets(Set<IIndexWord> indexWords) { Set<ISynset> synsets = new HashSet<ISynset>(); for (IIndexWord indexWord : indexWords) { for (IWordID wordID : indexWord.getWordIDs()) { synsets.add(m_dict.getSynset(wordID.getSynsetID())); } } return synsets; } public List<ISynsetID> getAncestors(ISynset synset) { List<ISynsetID> list = new ArrayList<ISynsetID>(); list.addAll(synset.getRelatedSynsets(Pointer.HYPERNYM)); list.addAll(synset.getRelatedSynsets(Pointer.HYPERNYM_INSTANCE)); return list; } public List<ISynsetID> getChildren(ISynset synset) { List<ISynsetID> list = new ArrayList<ISynsetID>(); list.addAll(synset.getRelatedSynsets(Pointer.HYPONYM)); list.addAll(synset.getRelatedSynsets(Pointer.HYPONYM_INSTANCE)); return list; } public List<List<ISynset>> getPathsToRoot(ISynset synset) { List<List<ISynset>> pathsToRoot = null; List<ISynsetID> ancestors = getAncestors(synset); if (ancestors.isEmpty()) { pathsToRoot = new ArrayList<List<ISynset>>(); List<ISynset> pathToRoot = new ArrayList<ISynset>(); pathToRoot.add(synset); pathsToRoot.add(pathToRoot); } else if (ancestors.size() == 1) { pathsToRoot = getPathsToRoot(m_dict.getSynset(ancestors.get(0))); for (List<ISynset> pathToRoot : pathsToRoot) { pathToRoot.add(0, synset); } } else { pathsToRoot = new ArrayList<List<ISynset>>(); for (ISynsetID ancestor : ancestors) { ISynset ancestorSynset = m_dict.getSynset(ancestor); List<List<ISynset>> pathsToRootLocal = getPathsToRoot(ancestorSynset); for (List<ISynset> pathToRoot : pathsToRootLocal) { pathToRoot.add(0, synset); } pathsToRoot.addAll(pathsToRootLocal); } } return pathsToRoot; } private ISynset findClosestCommonParent(List<ISynset> pathToRoot1, List<ISynset> pathToRoot2) { int i = 0; int j = 0; if (pathToRoot1.size() > pathToRoot2.size()) { i = pathToRoot1.size() - pathToRoot2.size(); j = 0; } else if (pathToRoot1.size() < pathToRoot2.size()) { i = 0; j = pathToRoot2.size() - pathToRoot1.size(); } do { ISynset synset1 = pathToRoot1.get(i++); ISynset synset2 = pathToRoot2.get(j++); if (synset1.equals(synset2)) { return synset1; } } while (i < pathToRoot1.size()); return null; } public ISynset findClosestCommonParent(ISynset synset1, ISynset synset2) { if ((synset1 == null) || (synset2 == null)) { return null; } if (synset1.equals(synset2)) { return synset1; } List<List<ISynset>> pathsToRoot1 = getPathsToRoot(synset1); List<List<ISynset>> pathsToRoot2 = getPathsToRoot(synset2); ISynset resultSynset = null; int i = 0; for (List<ISynset> pathToRoot1 : pathsToRoot1) { for (List<ISynset> pathToRoot2 : pathsToRoot2) { ISynset synset = findClosestCommonParent(pathToRoot1, pathToRoot2); int j = pathToRoot1.size() - (pathToRoot1.indexOf(synset) + 1); if (j >= i) { i = j; resultSynset = synset; } } } return resultSynset; } /** * maxDepth * * @param synset * @return The length of the longest hypernym path from this synset to the * root. */ public int maxDepth(ISynset synset) { if (synset == null) { return 0; } List<ISynsetID> ancestors = getAncestors(synset); if (ancestors.isEmpty()) { return 0; } int i = 0; for (ISynsetID ancestor : ancestors) { ISynset ancestorSynset = m_dict.getSynset(ancestor); int j = maxDepth(ancestorSynset); i = (i > j) ? i : j; } return i + 1; } /** * Shortest Path Distance * * Returns the distance of the shortest path linking the two synsets (if one * exists). * * For each synset, all the ancestor nodes and their distances are recorded * and compared. The ancestor node common to both synsets that can be reached * with the minimum number of traversals is used. If no ancestor nodes are * common, null is returned. If a node is compared with itself 0 is returned. * * @param synset1 * @param synset2 * @return The number of edges in the shortest path connecting the two nodes, * or null if no path exists. */ public Integer shortestPathDistance(ISynset synset1, ISynset synset2) { Integer distance = null; if (synset1.equals(synset2)) { return 0; } ISynset ccp = findClosestCommonParent(synset1, synset2); if (ccp != null) { distance = maxDepth(synset1) + maxDepth(synset2) - 2 * maxDepth(ccp); // Debug String w1 = synset1.getWords().get(0).getLemma(); String w2 = synset2.getWords().get(0).getLemma(); String w3 = ccp.getWords().get(0).getLemma(); System.out.println("maxDepth(" + w1 + "): " + maxDepth(synset1)); System.out.println("maxDepth(" + w2 + "): " + maxDepth(synset2)); System.out.println("maxDepth(" + w3 + "): " + maxDepth(ccp)); System.out.println("distance(" + w1 + "," + w2 + "): " + distance); } return distance; } /** * Path Distance Similarity * * Return a score denoting how similar two word senses are, based on the * shortest path that connects the senses in the is-a (hypernym/hypnoym) * taxonomy. * * The score is in the range 0 to 1, except in those cases where a path cannot * be found (will only be true for verbs as there are many distinct verb * taxonomies), in which case null is returned. * * A score of 1 represents identity i.e. comparing a sense with itself will * return 1. * * @param synset1 * @param synset2 * @return A score denoting the similarity of the two ``Synset`` objects, * normally between 0 and 1. null is returned if no connecting path * could be found. 1 is returned if a ``Synset`` is compared with * itself. */ public Double pathSimilarity(ISynset synset1, ISynset synset2) { Integer distance = shortestPathDistance(synset1, synset2); Double pathSimilarity = null; if (distance != null) { if (distance < 0) { throw new IllegalArgumentException("Distance value is negative!"); } pathSimilarity = 1 / ((double) distance + 1); // Debug String w1 = synset1.getWords().get(0).getLemma(); String w2 = synset2.getWords().get(0).getLemma(); System.out.println("maxDepth(" + w1 + "): " + maxDepth(synset1)); System.out.println("maxDepth(" + w2 + "): " + maxDepth(synset2)); System.out.println("distance: " + distance); System.out.println("pathSimilarity(" + w1 + "," + w2 + "): " + pathSimilarity); } else { // TODO simulate_root=True } return pathSimilarity; } /** * Leacock Chodorow Similarity * * Return a score denoting how similar two word senses are, based on the * shortest path that connects the senses and the maximum depth of the * taxonomy in which the senses occur. The relationship is given as -log(p/2d) * where p is the shortest path length and d is the taxonomy depth. * * lch(c1,c2) = - log(minPathLength(c1,c2) / 2 * depth of the hierarchy) * lch(c1,c2) = - log(minPL(c1,c2) / 2 * depth) = log(2*depth / minPL(c1,c2)) * * minPathLength is measured in nodes, i.e. the distance of a node to itself * is 0! This would cause a logarithm error (or a division by zero)). Thus we * changed the behaviour in order to return a distance of 1, if the nodes are * equal or neighbors. * * double relatedness = Math.log( (2*depthOfHierarchy) / (pathLength + 1) ); * * @param synset1 * @param synset2 * @return A score denoting the similarity of the two ``Synset`` objects, * normally greater than 0. null is returned if no connecting path * could be found. If a ``Synset`` is compared with itself, the * maximum score is returned, which varies depending on the taxonomy * depth. */ public Double lchSimilarity(ISynset synset1, ISynset synset2) { Integer distance = shortestPathDistance(synset1, synset2); Double lchSimilarity = null; if (distance != null) { if (distance < 0) { throw new IllegalArgumentException("Distance value is negative!"); } if (distance == 0) { distance = 1; } lchSimilarity = Math.log((2 * MAX_DEPTH_OF_HIERARCHY) / ((double) distance)); // Debug String w1 = synset1.getWords().get(0).getLemma(); String w2 = synset2.getWords().get(0).getLemma(); System.out.println("lchSimilarity(" + w1 + "," + w2 + "): " + lchSimilarity); } else { // TODO simulate_root=True } return lchSimilarity; } /** * Computes a score denoting how similar two word senses are, based on the * shortest path that connects the senses in the is-a (hypernym/hypnoym) * taxonomy. * * @param indexWord1 * @param indexWord2 * @return Returns a similarity score is in the range 0 to 1. A score of 1 * represents identity i.e. comparing a sense with itself will return * 1. */ public double similarity(String word1String, POS word1POS, String word2String, POS word2POS) { IIndexWord indexWord1 = getIndexWord(word1String, word1POS); Set<ISynset> synsets1 = getSynsets(indexWord1); IIndexWord indexWord2 = getIndexWord(word2String, word2POS); Set<ISynset> synsets2 = getSynsets(indexWord2); double maxSim = 0; for (ISynset synset1 : synsets1) { for (ISynset synset2 : synsets2) { double sim = pathSimilarity(synset1, synset2); if ((sim > 0) && (sim > maxSim)) { maxSim = sim; } } } return maxSim; } public ISynset disambiguateWordSenses(List<TaggedWord> sentence, String word, POS pos) { IIndexWord indexWord = getIndexWord(word, pos); Set<ISynset> synsets = getSynsets(indexWord); ISynset resultSynset = null; double bestScore = 0; for (ISynset synset : synsets) { for (TaggedWord taggedWord : sentence) { double score = 0; IIndexWord indexWordLocal = getIndexWord(taggedWord.word(), POSTag.convertPTB(taggedWord.tag())); Set<ISynset> synsetsLocal = getSynsets(indexWordLocal); for (ISynset synsetLocal : synsetsLocal) { double sim = shortestPathDistance(synsetLocal, synset); if (sim > 0) { score += sim; } } if (score > bestScore) { bestScore = score; resultSynset = synset; } } } return resultSynset; } /** * testWordNet implementation */ public void testWordNet() { // Performance test - treking across Wordnet trek(); // ************************************************************************ // Misc Tests // ************************************************************************ System.out.println("\nwn.synsets('dog')"); Set<IIndexWord> indexWords = getAllIndexWords("dog"); for (IIndexWord indexWord : indexWords) { System.out.println("indexWords: "); for (IWordID wordID : indexWord.getWordIDs()) { IWord word = m_dict.getWord(wordID); System.out.println(word.getSynset()); } } System.out.println("\nwn.synsets('dog', pos=wn.NOUN)"); IIndexWord indexWord = m_dict.getIndexWord("dog", POS.NOUN); IWordID wordID = indexWord.getWordIDs().get(0); IWord word = m_dict.getWord(wordID); System.out.println("Id = " + wordID); System.out.println("Lemma = " + word.getLemma()); System.out.println("Gloss = " + word.getSynset().getGloss()); System.out .println("\ndog = wn.synset('dog.n.01') dog.hypernyms - ancestors"); List<ISynsetID> ancestors = getAncestors(getSynset("dog", POS.NOUN)); for (ISynsetID ancestor : ancestors) { ISynset synset = m_dict.getSynset(ancestor); System.out.println(synset); } System.out.println("\ndog = wn.synset('dog.n.01') dog.hyponyms - children"); List<ISynsetID> children = getChildren(getSynset("dog", POS.NOUN)); for (ISynsetID child : children) { ISynset synset = m_dict.getSynset(child); System.out.println(synset); } // ************************************************************************ // Test similarities // ************************************************************************ Double pathSimilarity = null; Double lchSimilarity = null; System.out.println("\nwn.path_similarity(dog, dog) = 1.0"); pathSimilarity = pathSimilarity(getSynset("dog", POS.NOUN), getSynset("dog", POS.NOUN)); System.out.println("pathSimilarity: " + pathSimilarity); System.out.println("\nwn.lch_similarity(dog, dog) = 3.63758"); lchSimilarity = lchSimilarity(getSynset("dog", POS.NOUN), getSynset("dog", POS.NOUN)); System.out.println("lchSimilarity: " + lchSimilarity); System.out.println("\nwn.path_similarity(dog, cat) = 0.2"); pathSimilarity = pathSimilarity(getSynset("dog", POS.NOUN), getSynset("cat", POS.NOUN)); System.out.println("pathSimilarity: " + pathSimilarity); System.out.println("\nwn.lch_similarity(dog, cat) = 2.02814"); lchSimilarity = lchSimilarity(getSynset("dog", POS.NOUN), getSynset("cat", POS.NOUN)); System.out.println("lchSimilarity: " + lchSimilarity); System.out.println("\nwn.path_similarity(hit, slap) = 0.14285"); pathSimilarity = pathSimilarity(getSynset("hit", POS.VERB), getSynset("slap", POS.VERB)); System.out.println("pathSimilarity: " + pathSimilarity); System.out.println("\nwn.lch_similarity(hit, slap) = 1.31218"); lchSimilarity = lchSimilarity(getSynset("hit", POS.VERB), getSynset("slap", POS.VERB)); System.out.println("lchSimilarity: " + lchSimilarity); // ************************************************************************ // Test stemming // ************************************************************************ System.out.println("\nStemming test..."); String[] stemmingWords = { "cats", "running", "ran", "cactus", "cactuses", "community", "communities", "going" }; POS[] stemmingPOS = { POS.NOUN, POS.VERB, POS.VERB, POS.NOUN, POS.NOUN, POS.NOUN, POS.NOUN, POS.VERB }; String[] stemmingResults = { "cat", "run", "run", "cactus", "cactus", "community", "community", "go" }; for (int i = 0; i < stemmingWords.length; i++) { List<String> stemResults = m_wordnetStemmer.findStems(stemmingWords[i], stemmingPOS[i]); for (String stemResult : stemResults) { System.out.println("stems of \"" + stemmingWords[i] + "\": " + stemResult); // verify result if (!stemResult.equals(stemmingResults[i])) { System.err.println("Wrong stemming result of \"" + stemmingWords[i] + "\" result: \"" + stemResult + "\" expected: \"" + stemmingResults[i] + "\""); } } } } /** * Treking across Wordnet for performance measurements * */ private void trek() { int tickNext = 0; int tickSize = 20000; int seen = 0; System.out.print("Treking across Wordnet"); long t = System.currentTimeMillis(); for (POS pos : POS.values()) { for (Iterator<IIndexWord> i = m_dict.getIndexWordIterator(pos); i .hasNext();) { for (IWordID wid : i.next().getWordIDs()) { seen += m_dict.getWord(wid).getSynset().getWords().size(); if (seen > tickNext) { System.out.print("."); tickNext = seen + tickSize; } } } } System.out.printf("done (%1d msec)\n", System.currentTimeMillis() - t); System.out.println("In my trek I saw " + seen + " words"); } public static void main(String[] args) { WordNet wordNet = WordNet.getInstance(); wordNet.testWordNet(); wordNet.close(); } }
apache-2.0
xzel23/meja
src/main/java/com/dua3/meja/io/CsvWriter.java
3558
/* * Copyright 2015 Axel Howind (axel@dua3.com). * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.dua3.meja.io; import java.io.BufferedWriter; import java.io.File; import java.io.Flushable; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import com.dua3.meja.util.Options; /** * * @author axel@dua3.com */ public class CsvWriter extends Csv implements AutoCloseable, Flushable { private static final String ALLOWED_CHARS = "!§$%&/()=?`°^'.,:;-_#'+~*<>|@ \t"; public static CsvWriter create(BufferedWriter writer, Options options) { return new CsvWriter(writer, options); } public static CsvWriter create(File file, Options options) throws IOException { return create(file.toPath(), options); } public static CsvWriter create(Path path, Options options) throws IOException { Charset cs = getCharset(options); return create(Files.newBufferedWriter(path, cs), options); } public static CsvWriter create(OutputStream out, Options options) { Charset cs = getCharset(options); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, cs)); return create(writer, options); } private final BufferedWriter out; private final String lineDelimiter; private final String separator; private final String delimiter; private int fieldsInRow = 0; public CsvWriter(BufferedWriter out, Options options) { this.separator = String.valueOf(getSeparator(options)); this.delimiter = String.valueOf(getDelimiter(options)); this.lineDelimiter = String.format("%n"); this.out = out; } public void addField(String text) throws IOException { if (fieldsInRow > 0) { out.write(separator); } out.write(quoteIfNeeded(text)); fieldsInRow++; } @Override public void close() throws IOException { if (fieldsInRow > 0) { nextRow(); } out.close(); } @Override public void flush() throws IOException { out.flush(); } private boolean isQuoteNeeded(String text) { // quote if separator or delimiter are present if (text.indexOf(separator) >= 0 || text.indexOf(delimiter) >= 0) { return true; } // also quote if unusual characters are present for (char c : text.toCharArray()) { if (!Character.isLetterOrDigit(c) && ALLOWED_CHARS.indexOf(c) == -1) { return true; } } return false; } public void nextRow() throws IOException { out.write(lineDelimiter); fieldsInRow = 0; } private String quote(String text) { return delimiter + text.replace("\"", "\"\"") + delimiter; } private String quoteIfNeeded(String text) { return isQuoteNeeded(text) ? quote(text) : text; } }
apache-2.0
yunmel/rps
src/main/java/com/yunmel/db/common/pool/HikariCPDataSourceCreator.java
6569
package com.yunmel.db.common.pool; import java.sql.SQLException; import javax.sql.DataSource; import com.yunmel.db.common.IDataSourceCreator; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; public class HikariCPDataSourceCreator implements IDataSourceCreator { private String jdbcUrl; private String username; private String password; private boolean autoCommit = true; private long connectionTimeout = 30000; private long idleTimeout = 600000; private long maxLifetime = 1800000; private String connectionTestQuery = null; private int maximumPoolSize = 10; private String poolName = null; private boolean readOnly = false; private String catalog = null; private String connectionInitSql = null; private String driverClass = null; private String transactionIsolation = null; private long validationTimeout = 5000; private long leakDetectionThreshold = 0; public HikariCPDataSourceCreator(String jdbcUrl, String username, String password) { this.jdbcUrl = jdbcUrl; this.username = username; this.password = password; } public HikariCPDataSourceCreator(String jdbcUrl, String username, String password, String driverClass) { this.jdbcUrl = jdbcUrl; this.username = username; this.password = password; this.driverClass = driverClass; } // TODO : replace config file. @Override public DataSource createDatasource() throws SQLException { HikariConfig config = new HikariConfig(); // 设定基本参数 config.setJdbcUrl(jdbcUrl); config.setUsername(username); config.setPassword(password); // 设定额外参数 config.setAutoCommit(autoCommit); config.setReadOnly(readOnly); config.setConnectionTimeout(connectionTimeout); config.setIdleTimeout(idleTimeout); config.setMaxLifetime(maxLifetime); config.setMaximumPoolSize(maximumPoolSize); config.setValidationTimeout(validationTimeout); // config.setTransactionIsolation(datasourcecfg.get); if (this.leakDetectionThreshold != 0) { config.setLeakDetectionThreshold(leakDetectionThreshold); } if (jdbcUrl.toLowerCase().contains(":mysql:")) { config.addDataSourceProperty("cachePrepStmts", "true"); config.addDataSourceProperty("useServerPrepStmts", "true"); config.addDataSourceProperty("prepStmtCacheSize", "256"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); } if (jdbcUrl.toLowerCase().contains(":postgresql:")) { if (this.readOnly) { config.addDataSourceProperty("readOnly", "true"); } config.setConnectionTimeout(0); config.addDataSourceProperty("prepareThreshold", "3"); config.addDataSourceProperty("preparedStatementCacheQueries", "128"); config.addDataSourceProperty("preparedStatementCacheSizeMiB", "4"); } return new HikariDataSource(config); /* * HikariConfig config = new HikariConfig(); config.setMaximumPoolSize(10); * config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource"); * config.addDataSourceProperty("serverName", "localhost"); * config.addDataSourceProperty("databaseName", "rps"); config.addDataSourceProperty("user", * "root"); config.addDataSourceProperty("password", "root"); * config.setInitializationFailFast(true); config.addDataSourceProperty("useUnicode", "true"); * config.addDataSourceProperty("characterEncoding", "utf8"); return new * HikariDataSource(config); */ } public String getJdbcUrl() { return jdbcUrl; } public void setJdbcUrl(String jdbcUrl) { this.jdbcUrl = jdbcUrl; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isAutoCommit() { return autoCommit; } public void setAutoCommit(boolean autoCommit) { this.autoCommit = autoCommit; } public long getConnectionTimeout() { return connectionTimeout; } public void setConnectionTimeout(long connectionTimeout) { this.connectionTimeout = connectionTimeout; } public long getIdleTimeout() { return idleTimeout; } public void setIdleTimeout(long idleTimeout) { this.idleTimeout = idleTimeout; } public long getMaxLifetime() { return maxLifetime; } public void setMaxLifetime(long maxLifetime) { this.maxLifetime = maxLifetime; } public String getConnectionTestQuery() { return connectionTestQuery; } public void setConnectionTestQuery(String connectionTestQuery) { this.connectionTestQuery = connectionTestQuery; } public int getMaximumPoolSize() { return maximumPoolSize; } public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } public String getPoolName() { return poolName; } public void setPoolName(String poolName) { this.poolName = poolName; } public boolean isReadOnly() { return readOnly; } public void setReadOnly(boolean readOnly) { this.readOnly = readOnly; } public String getCatalog() { return catalog; } public void setCatalog(String catalog) { this.catalog = catalog; } public String getConnectionInitSql() { return connectionInitSql; } public void setConnectionInitSql(String connectionInitSql) { this.connectionInitSql = connectionInitSql; } public String getDriverClass() { return driverClass; } public void setDriverClass(String driverClass) { this.driverClass = driverClass; } public String getTransactionIsolation() { return transactionIsolation; } public void setTransactionIsolation(String transactionIsolation) { this.transactionIsolation = transactionIsolation; } public long getValidationTimeout() { return validationTimeout; } public void setValidationTimeout(long validationTimeout) { this.validationTimeout = validationTimeout; } public long getLeakDetectionThreshold() { return leakDetectionThreshold; } public void setLeakDetectionThreshold(long leakDetectionThreshold) { this.leakDetectionThreshold = leakDetectionThreshold; } }
apache-2.0
gerrit-review/gerrit
java/com/google/gerrit/server/account/DeleteActive.java
2111
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.account; import com.google.gerrit.common.data.GlobalCapability; import com.google.gerrit.extensions.annotations.RequiresCapability; import com.google.gerrit.extensions.common.Input; import com.google.gerrit.extensions.restapi.ResourceConflictException; import com.google.gerrit.extensions.restapi.Response; import com.google.gerrit.extensions.restapi.RestApiException; import com.google.gerrit.extensions.restapi.RestModifyView; import com.google.gerrit.server.IdentifiedUser; import com.google.gwtorm.server.OrmException; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.Singleton; import java.io.IOException; import org.eclipse.jgit.errors.ConfigInvalidException; @RequiresCapability(GlobalCapability.MODIFY_ACCOUNT) @Singleton public class DeleteActive implements RestModifyView<AccountResource, Input> { private final Provider<IdentifiedUser> self; private final SetInactiveFlag setInactiveFlag; @Inject DeleteActive(SetInactiveFlag setInactiveFlag, Provider<IdentifiedUser> self) { this.setInactiveFlag = setInactiveFlag; this.self = self; } @Override public Response<?> apply(AccountResource rsrc, Input input) throws RestApiException, OrmException, IOException, ConfigInvalidException { if (self.get() == rsrc.getUser()) { throw new ResourceConflictException("cannot deactivate own account"); } return setInactiveFlag.deactivate(rsrc.getUser().getAccountId()); } }
apache-2.0
x-meta/xworker
xworker_explorer/src/main/java/xworker/lang/executor/NotificationExecutorActions.java
5940
package xworker.lang.executor; import java.util.Map; import org.xmeta.ActionContext; import org.xmeta.Thing; import org.xmeta.util.ActionContainer; import org.xmeta.util.UtilData; import xworker.lang.system.message.Message; import xworker.notification.Notification; import xworker.notification.NotificationManager; public class NotificationExecutorActions { private static boolean isExecuted(Map<String, Object> values) { //如果已经执行过了,则不用再做 String key = "__executed__"; if(UtilData.isTrue(values.get(key))) { return true; }else { values.put(key, true); return false; } } public static void okButtonSelection(ActionContext actionContext) { final Map<String, Object> values = actionContext.getObject("requestVariables"); if(isExecuted(values)) { return; } ActionContainer actions = actionContext.getObject("actions"); final Thing request = actionContext.getObject("request"); final ActionContext requestContext = actionContext.getObject("requestContext"); Object r = null; if(actions != null) { Object validate = actions.doAction("validate", requestContext); if(validate != null && UtilData.isTrue(validate) == false) { //校验失败 return; } //异步执行结果 r = actions.doAction("getResult", actionContext); } final Object result = r; new Thread(new Runnable() { public void run() { try { ExecutorService executorService = (ExecutorService) values.get("__executorService__"); Executor.push(executorService); requestContext.peek().putAll(values); request.doAction("ok", requestContext, "result", result); }catch(Exception e) { Executor.error("NotificationExecutor", "Execute request ok error, path=" + request.getMetadata().getPath(), e); }finally { Executor.pop(); } } }).start(); Notification notifiction = actionContext.getObject("notification"); NotificationManager.removeNotification(notifiction); } public static void cancelButtonSelection(ActionContext actionContext) { final Map<String, Object> values = actionContext.getObject("requestVariables"); if(isExecuted(values)) { return; } final Thing request = actionContext.getObject("request"); final ActionContext requestContext = actionContext.getObject("requestContext"); new Thread(new Runnable() { public void run() { try { ExecutorService executorService = (ExecutorService) values.get("__executorService__"); Executor.push(executorService); requestContext.peek().putAll(values); request.doAction("cancel", requestContext); }catch(Exception e) { Executor.error("NotificationExecutor", "Execute request cancel error, path=" + request.getMetadata().getPath(), e); } finally { Executor.pop(); } } }).start(); Notification notifiction = actionContext.getObject("notification"); NotificationManager.removeNotification(notifiction); } public static void doinit(ActionContext actionContext) { ActionContext ac = new ActionContext(); ac.put("parent", actionContext.get("requestComposite")); ac.put("request", actionContext.get("request")); ac.put("requestContext", actionContext.get("requestContext")); //把传入的变量带入到变量上下文中 Message message = actionContext.getObject("message"); if(message != null && message.getVariables() != null) { ac.putAll(message.getVariables()); } ac.put("requestVariables", actionContext.get("requestVariables")); Request request = actionContext.getObject("request"); request.create(actionContext.get("mainComposite"), "swt"); //request.doAction("createSWT", ac); //println actionContext.get("request"); actionContext.g().put("actions", ac.get("actions")); } public static Object getTimeout(ActionContext actionContext) { Request request = actionContext.getObject("request"); Thing requestThing = request.getThing(); return requestThing.doAction("getTimeout", actionContext); } public static Object getLabel(ActionContext actionContext) { Request request = actionContext.getObject("request"); Thing requestThing = request.getThing(); String label = requestThing.doAction("getLabel", actionContext); if(label == null || "".equals(label)) { return requestThing.getMetadata().getLabel(); }else { return label; } } @SuppressWarnings("unchecked") public static void onFinished(ActionContext actionContext) { /* Notification notification = actionContext.getObject("notification"); Map<String, Object> mvalues = notification.getMessage().getVariables(); final Map<String, Object> values = (Map<String, Object>) mvalues.get("requestVariables"); if(isExecuted(values)) { return; } final Thing request = (Thing) mvalues.get("request"); final ActionContext requestContext = (ActionContext) mvalues.get("requestContext"); new Thread(new Runnable() { public void run() { try { ExecutorService executorService = (ExecutorService) values.get("__executorService__"); Executor.push(executorService); requestContext.peek().putAll(values); request.doAction("cancel", requestContext); }catch(Exception e) { Executor.error("NotificationExecutor", "Execute request cancel error, path=" + request.getMetadata().getPath(), e); } finally { Executor.pop(); } } }).start(); */ } public static String getId(ActionContext actionContext) { Request request = actionContext.getObject("request"); Thing requestThing = request.getThing(); String messageId = requestThing.doAction("getMessageId", actionContext); if(messageId == null || "".equals(messageId)) { return requestThing.getMetadata().getPath(); }else { return messageId; } } }
apache-2.0
datanucleus/tests
jakarta/general/src/java/org/datanucleus/samples/types/javatime/JavaTimeSample1.java
1856
/********************************************************************** Copyright (c) 2010 Andy Jefferson and others. 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. Contributors: ... **********************************************************************/ package org.datanucleus.samples.types.javatime; import java.time.LocalDateTime; import jakarta.persistence.Basic; import jakarta.persistence.Entity; import jakarta.persistence.Id; import org.datanucleus.api.jakarta.annotations.JdbcType; /** * Sample using LocalDateTime. */ @Entity public class JavaTimeSample1 { @Id private long id; @Basic private LocalDateTime dateTime1; @Basic @JdbcType("VARCHAR") private LocalDateTime dateTime2; public JavaTimeSample1(long id, LocalDateTime dt1, LocalDateTime dt2) { this.id = id; this.dateTime1 = dt1; this.dateTime2 = dt2; } public long getId() { return id; } public void setId(long id) { this.id = id; } public LocalDateTime getDateTime1() { return dateTime1; } public void setDateTime1(LocalDateTime dt) { this.dateTime1 = dt; } public LocalDateTime getDateTime2() { return dateTime2; } public void setDateTime2(LocalDateTime dt) { this.dateTime2 = dt; } }
apache-2.0
karussell/fastutil
src/it/unimi/dsi/fastutil/doubles/AbstractDoubleList.java
19719
/* Generic definitions */ /* Assertions (useful to generate conditional code) */ /* Current type and class (and size, if applicable) */ /* Value methods */ /* Interfaces (keys) */ /* Interfaces (values) */ /* Abstract implementations (keys) */ /* Abstract implementations (values) */ /* Static containers (keys) */ /* Static containers (values) */ /* Implementations */ /* Synchronized wrappers */ /* Unmodifiable wrappers */ /* Other wrappers */ /* Methods (keys) */ /* Methods (values) */ /* Methods (keys/values) */ /* Methods that have special names depending on keys (but the special names depend on values) */ /* Equality */ /* Object/Reference-only definitions (keys) */ /* Primitive-type-only definitions (keys) */ /* Object/Reference-only definitions (values) */ /* * Copyright (C) 2002-2013 Sebastiano Vigna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package it.unimi.dsi.fastutil.doubles; import java.util.List; import java.util.Iterator; import java.util.ListIterator; import java.util.Collection; import java.util.NoSuchElementException; /** An abstract class providing basic methods for lists implementing a type-specific list interface. * * <P>As an additional bonus, this class implements on top of the list operations a type-specific stack. */ public abstract class AbstractDoubleList extends AbstractDoubleCollection implements DoubleList , DoubleStack { protected AbstractDoubleList() {} /** Ensures that the given index is nonnegative and not greater than the list size. * * @param index an index. * @throws IndexOutOfBoundsException if the given index is negative or greater than the list size. */ protected void ensureIndex( final int index ) { if ( index < 0 ) throw new IndexOutOfBoundsException( "Index (" + index + ") is negative" ); if ( index > size() ) throw new IndexOutOfBoundsException( "Index (" + index + ") is greater than list size (" + ( size() ) + ")" ); } /** Ensures that the given index is nonnegative and smaller than the list size. * * @param index an index. * @throws IndexOutOfBoundsException if the given index is negative or not smaller than the list size. */ protected void ensureRestrictedIndex( final int index ) { if ( index < 0 ) throw new IndexOutOfBoundsException( "Index (" + index + ") is negative" ); if ( index >= size() ) throw new IndexOutOfBoundsException( "Index (" + index + ") is greater than or equal to list size (" + ( size() ) + ")" ); } public void add( final int index, final double k ) { throw new UnsupportedOperationException(); } public boolean add( final double k ) { add( size(), k ); return true; } public double removeDouble( int i ) { throw new UnsupportedOperationException(); } public double set( final int index, final double k ) { throw new UnsupportedOperationException(); } public boolean addAll( int index, final Collection<? extends Double> c ) { ensureIndex( index ); int n = c.size(); if ( n == 0 ) return false; Iterator<? extends Double> i = c.iterator(); while( n-- != 0 ) add( index++, i.next() ); return true; } /** Delegates to a more generic method. */ public boolean addAll( final Collection<? extends Double> c ) { return addAll( size(), c ); } /** Delegates to the new covariantly stronger generic method. */ @Deprecated public DoubleListIterator doubleListIterator() { return listIterator(); } /** Delegates to the new covariantly stronger generic method. */ @Deprecated public DoubleListIterator doubleListIterator( final int index ) { return listIterator( index ); } public DoubleListIterator iterator() { return listIterator(); } public DoubleListIterator listIterator() { return listIterator( 0 ); } public DoubleListIterator listIterator( final int index ) { return new AbstractDoubleListIterator () { int pos = index, last = -1; public boolean hasNext() { return pos < AbstractDoubleList.this.size(); } public boolean hasPrevious() { return pos > 0; } public double nextDouble() { if ( ! hasNext() ) throw new NoSuchElementException(); return AbstractDoubleList.this.getDouble( last = pos++ ); } public double previousDouble() { if ( ! hasPrevious() ) throw new NoSuchElementException(); return AbstractDoubleList.this.getDouble( last = --pos ); } public int nextIndex() { return pos; } public int previousIndex() { return pos - 1; } public void add( double k ) { if ( last == -1 ) throw new IllegalStateException(); AbstractDoubleList.this.add( pos++, k ); last = -1; } public void set( double k ) { if ( last == -1 ) throw new IllegalStateException(); AbstractDoubleList.this.set( last, k ); } public void remove() { if ( last == -1 ) throw new IllegalStateException(); AbstractDoubleList.this.removeDouble( last ); /* If the last operation was a next(), we are removing an element *before* us, and we must decrease pos correspondingly. */ if ( last < pos ) pos--; last = -1; } }; } public boolean contains( final double k ) { return indexOf( k ) >= 0; } public int indexOf( final double k ) { final DoubleListIterator i = listIterator(); double e; while( i.hasNext() ) { e = i.nextDouble(); if ( ( (k) == (e) ) ) return i.previousIndex(); } return -1; } public int lastIndexOf( final double k ) { DoubleListIterator i = listIterator( size() ); double e; while( i.hasPrevious() ) { e = i.previousDouble(); if ( ( (k) == (e) ) ) return i.nextIndex(); } return -1; } public void size( final int size ) { int i = size(); if ( size > i ) while( i++ < size ) add( ((double)0) ); else while( i-- != size ) remove( i ); } public DoubleList subList( final int from, final int to ) { ensureIndex( from ); ensureIndex( to ); if ( from > to ) throw new IndexOutOfBoundsException( "Start index (" + from + ") is greater than end index (" + to + ")" ); return new DoubleSubList ( this, from, to ); } /** Delegates to the new covariantly stronger generic method. */ @Deprecated public DoubleList doubleSubList( final int from, final int to ) { return subList( from, to ); } /** Removes elements of this type-specific list one-by-one. * * <P>This is a trivial iterator-based implementation. It is expected that * implementations will override this method with a more optimized version. * * * @param from the start index (inclusive). * @param to the end index (exclusive). */ public void removeElements( final int from, final int to ) { ensureIndex( to ); DoubleListIterator i = listIterator( from ); int n = to - from; if ( n < 0 ) throw new IllegalArgumentException( "Start index (" + from + ") is greater than end index (" + to + ")" ); while( n-- != 0 ) { i.nextDouble(); i.remove(); } } /** Adds elements to this type-specific list one-by-one. * * <P>This is a trivial iterator-based implementation. It is expected that * implementations will override this method with a more optimized version. * * @param index the index at which to add elements. * @param a the array containing the elements. * @param offset the offset of the first element to add. * @param length the number of elements to add. */ public void addElements( int index, final double a[], int offset, int length ) { ensureIndex( index ); if ( offset < 0 ) throw new ArrayIndexOutOfBoundsException( "Offset (" + offset + ") is negative" ); if ( offset + length > a.length ) throw new ArrayIndexOutOfBoundsException( "End index (" + ( offset + length ) + ") is greater than array length (" + a.length + ")" ); while( length-- != 0 ) add( index++, a[ offset++ ] ); } public void addElements( final int index, final double a[] ) { addElements( index, a, 0, a.length ); } /** Copies element of this type-specific list into the given array one-by-one. * * <P>This is a trivial iterator-based implementation. It is expected that * implementations will override this method with a more optimized version. * * @param from the start index (inclusive). * @param a the destination array. * @param offset the offset into the destination array where to store the first element copied. * @param length the number of elements to be copied. */ public void getElements( final int from, final double a[], int offset, int length ) { DoubleListIterator i = listIterator( from ); if ( offset < 0 ) throw new ArrayIndexOutOfBoundsException( "Offset (" + offset + ") is negative" ); if ( offset + length > a.length ) throw new ArrayIndexOutOfBoundsException( "End index (" + ( offset + length ) + ") is greater than array length (" + a.length + ")" ); if ( from + length > size() ) throw new IndexOutOfBoundsException( "End index (" + ( from + length ) + ") is greater than list size (" + size() + ")" ); while( length-- != 0 ) a[ offset++ ] = i.nextDouble(); } private boolean valEquals( final Object a, final Object b ) { return a == null ? b == null : a.equals( b ); } public boolean equals( final Object o ) { if ( o == this ) return true; if ( ! ( o instanceof List ) ) return false; final List<?> l = (List<?>)o; int s = size(); if ( s != l.size() ) return false; final ListIterator<?> i1 = listIterator(), i2 = l.listIterator(); while( s-- != 0 ) if ( ! valEquals( i1.next(), i2.next() ) ) return false; return true; } /** Compares this list to another object. If the * argument is a {@link java.util.List}, this method performs a lexicographical comparison; otherwise, * it throws a <code>ClassCastException</code>. * * @param l a list. * @return if the argument is a {@link java.util.List}, a negative integer, * zero, or a positive integer as this list is lexicographically less than, equal * to, or greater than the argument. * @throws ClassCastException if the argument is not a list. */ @SuppressWarnings("unchecked") public int compareTo( final List<? extends Double> l ) { if ( l == this ) return 0; if ( l instanceof DoubleList ) { final DoubleListIterator i1 = listIterator(), i2 = ((DoubleList )l).listIterator(); int r; double e1, e2; while( i1.hasNext() && i2.hasNext() ) { e1 = i1.nextDouble(); e2 = i2.nextDouble(); if ( ( r = ( Double.compare((e1),(e2)) ) ) != 0 ) return r; } return i2.hasNext() ? -1 : ( i1.hasNext() ? 1 : 0 ); } ListIterator<? extends Double> i1 = listIterator(), i2 = l.listIterator(); int r; while( i1.hasNext() && i2.hasNext() ) { if ( ( r = ((Comparable<? super Double>)i1.next()).compareTo( i2.next() ) ) != 0 ) return r; } return i2.hasNext() ? -1 : ( i1.hasNext() ? 1 : 0 ); } /** Returns the hash code for this list, which is identical to {@link java.util.List#hashCode()}. * * @return the hash code for this list. */ public int hashCode() { DoubleIterator i = iterator(); int h = 1, s = size(); while ( s-- != 0 ) { double k = i.nextDouble(); h = 31 * h + it.unimi.dsi.fastutil.HashCommon.double2int(k); } return h; } public void push( double o ) { add( o ); } public double popDouble() { if ( isEmpty() ) throw new NoSuchElementException(); return removeDouble( size() - 1 ); } public double topDouble() { if ( isEmpty() ) throw new NoSuchElementException(); return getDouble( size() - 1 ); } public double peekDouble( int i ) { return getDouble( size() - 1 - i ); } public boolean rem( double k ) { int index = indexOf( k ); if ( index == -1 ) return false; removeDouble( index ); return true; } /** Delegates to <code>rem()</code>. */ public boolean remove( final Object o ) { return rem( ((((Double)(o)).doubleValue())) ); } /** Delegates to a more generic method. */ public boolean addAll( final int index, final DoubleCollection c ) { return addAll( index, (Collection<? extends Double>)c ); } /** Delegates to a more generic method. */ public boolean addAll( final int index, final DoubleList l ) { return addAll( index, (DoubleCollection)l ); } public boolean addAll( final DoubleCollection c ) { return addAll( size(), c ); } public boolean addAll( final DoubleList l ) { return addAll( size(), l ); } /** Delegates to the corresponding type-specific method. */ public void add( final int index, final Double ok ) { add( index, ok.doubleValue() ); } /** Delegates to the corresponding type-specific method. */ public Double set( final int index, final Double ok ) { return (Double.valueOf(set( index, ok.doubleValue() ))); } /** Delegates to the corresponding type-specific method. */ public Double get( final int index ) { return (Double.valueOf(getDouble( index ))); } /** Delegates to the corresponding type-specific method. */ public int indexOf( final Object ok) { return indexOf( ((((Double)(ok)).doubleValue())) ); } /** Delegates to the corresponding type-specific method. */ public int lastIndexOf( final Object ok ) { return lastIndexOf( ((((Double)(ok)).doubleValue())) ); } /** Delegates to the corresponding type-specific method. */ public Double remove( final int index ) { return (Double.valueOf(removeDouble( index ))); } /** Delegates to the corresponding type-specific method. */ public void push( Double o ) { push( o.doubleValue() ); } /** Delegates to the corresponding type-specific method. */ public Double pop() { return Double.valueOf( popDouble() ); } /** Delegates to the corresponding type-specific method. */ public Double top() { return Double.valueOf( topDouble() ); } /** Delegates to the corresponding type-specific method. */ public Double peek( int i ) { return Double.valueOf( peekDouble( i ) ); } public String toString() { final StringBuilder s = new StringBuilder(); final DoubleIterator i = iterator(); int n = size(); double k; boolean first = true; s.append("["); while( n-- != 0 ) { if (first) first = false; else s.append(", "); k = i.nextDouble(); s.append( String.valueOf( k ) ); } s.append("]"); return s.toString(); } public static class DoubleSubList extends AbstractDoubleList implements java.io.Serializable { private static final long serialVersionUID = -7046029254386353129L; /** The list this sublist restricts. */ protected final DoubleList l; /** Initial (inclusive) index of this sublist. */ protected final int from; /** Final (exclusive) index of this sublist. */ protected int to; private static final boolean ASSERTS = false; public DoubleSubList( final DoubleList l, final int from, final int to ) { this.l = l; this.from = from; this.to = to; } private void assertRange() { if ( ASSERTS ) { assert from <= l.size(); assert to <= l.size(); assert to >= from; } } public boolean add( final double k ) { l.add( to, k ); to++; if ( ASSERTS ) assertRange(); return true; } public void add( final int index, final double k ) { ensureIndex( index ); l.add( from + index, k ); to++; if ( ASSERTS ) assertRange(); } public boolean addAll( final int index, final Collection<? extends Double> c ) { ensureIndex( index ); to += c.size(); if ( ASSERTS ) { boolean retVal = l.addAll( from + index, c ); assertRange(); return retVal; } return l.addAll( from + index, c ); } public double getDouble( int index ) { ensureRestrictedIndex( index ); return l.getDouble( from + index ); } public double removeDouble( int index ) { ensureRestrictedIndex( index ); to--; return l.removeDouble( from + index ); } public double set( int index, double k ) { ensureRestrictedIndex( index ); return l.set( from + index, k ); } public void clear() { removeElements( 0, size() ); if ( ASSERTS ) assertRange(); } public int size() { return to - from; } public void getElements( final int from, final double[] a, final int offset, final int length ) { ensureIndex( from ); if ( from + length > size() ) throw new IndexOutOfBoundsException( "End index (" + from + length + ") is greater than list size (" + size() + ")" ); l.getElements( this.from + from, a, offset, length ); } public void removeElements( final int from, final int to ) { ensureIndex( from ); ensureIndex( to ); l.removeElements( this.from + from, this.from + to ); this.to -= ( to - from ); if ( ASSERTS ) assertRange(); } public void addElements( int index, final double a[], int offset, int length ) { ensureIndex( index ); l.addElements( this.from + index, a, offset, length ); this.to += length; if ( ASSERTS ) assertRange(); } public DoubleListIterator listIterator( final int index ) { ensureIndex( index ); return new AbstractDoubleListIterator () { int pos = index, last = -1; public boolean hasNext() { return pos < size(); } public boolean hasPrevious() { return pos > 0; } public double nextDouble() { if ( ! hasNext() ) throw new NoSuchElementException(); return l.getDouble( from + ( last = pos++ ) ); } public double previousDouble() { if ( ! hasPrevious() ) throw new NoSuchElementException(); return l.getDouble( from + ( last = --pos ) ); } public int nextIndex() { return pos; } public int previousIndex() { return pos - 1; } public void add( double k ) { if ( last == -1 ) throw new IllegalStateException(); DoubleSubList.this.add( pos++, k ); last = -1; if ( ASSERTS ) assertRange(); } public void set( double k ) { if ( last == -1 ) throw new IllegalStateException(); DoubleSubList.this.set( last, k ); } public void remove() { if ( last == -1 ) throw new IllegalStateException(); DoubleSubList.this.removeDouble( last ); /* If the last operation was a next(), we are removing an element *before* us, and we must decrease pos correspondingly. */ if ( last < pos ) pos--; last = -1; if ( ASSERTS ) assertRange(); } }; } public DoubleList subList( final int from, final int to ) { ensureIndex( from ); ensureIndex( to ); if ( from > to ) throw new IllegalArgumentException( "Start index (" + from + ") is greater than end index (" + to + ")" ); return new DoubleSubList ( this, from, to ); } public boolean rem( double k ) { int index = indexOf( k ); if ( index == -1 ) return false; to--; l.removeDouble( from + index ); if ( ASSERTS ) assertRange(); return true; } public boolean remove( final Object o ) { return rem( ((((Double)(o)).doubleValue())) ); } public boolean addAll( final int index, final DoubleCollection c ) { ensureIndex( index ); to += c.size(); if ( ASSERTS ) { boolean retVal = l.addAll( from + index, c ); assertRange(); return retVal; } return l.addAll( from + index, c ); } public boolean addAll( final int index, final DoubleList l ) { ensureIndex( index ); to += l.size(); if ( ASSERTS ) { boolean retVal = this.l.addAll( from + index, l ); assertRange(); return retVal; } return this.l.addAll( from + index, l ); } } }
apache-2.0
faisal-hameed/java-code-bank
habsoft.j2ee/habsoft.j2ee.spring/boot.admin/src/main/java/habsoft/j2ee/spring/Application.java
311
package habsoft.j2ee.spring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
apache-2.0
Ecwid/consul-api
src/main/java/com/ecwid/consul/v1/kv/model/PutParams.java
1914
package com.ecwid.consul.v1.kv.model; import com.ecwid.consul.UrlParameters; import com.ecwid.consul.Utils; import java.math.BigInteger; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Objects; /** * @author Vasily Vasilkov (vgv@ecwid.com) */ public class PutParams implements UrlParameters { private long flags; private Long cas; private String acquireSession; private String releaseSession; public long getFlags() { return flags; } public void setFlags(long flags) { this.flags = flags; } public Long getCas() { return cas; } public void setCas(Long cas) { this.cas = cas; } public String getAcquireSession() { return acquireSession; } public void setAcquireSession(String acquireSession) { this.acquireSession = acquireSession; } public String getReleaseSession() { return releaseSession; } public void setReleaseSession(String releaseSession) { this.releaseSession = releaseSession; } @Override public List<String> toUrlParameters() { List<String> params = new ArrayList<String>(); if (flags != 0) { params.add("flags=" + flags); } if (cas != null) { params.add("cas=" + cas); } if (acquireSession != null) { params.add("acquire=" + Utils.encodeValue(acquireSession)); } if (releaseSession != null) { params.add("release=" + Utils.encodeValue(releaseSession)); } return params; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof PutParams)) { return false; } PutParams putParams = (PutParams) o; return flags == putParams.flags && Objects.equals(cas, putParams.cas) && Objects.equals(acquireSession, putParams.acquireSession) && Objects.equals(releaseSession, putParams.releaseSession); } @Override public int hashCode() { return Objects.hash(flags, cas, acquireSession, releaseSession); } }
apache-2.0
wolfdog007/aruzhev
chapter_002/src/main/java/ru/job4j/chess/Board.java
3727
package ru.job4j.chess; /** * Chessboard class. * * @author Ruzhev Alexander * @since 08.05.2017 */ public class Board { /** * Constant line x. */ public static final String[] LINE_X = {"a", "b", "c", "d", "e", "f", "g", "h"}; /** * Array of figures. */ private Figure[] figures = new Figure[64]; /** * index of figures array. */ private int figureIndex = 0; /** * Add new figure. * * @param figure - new figure. * @throws OccupiedCellException Occupied cell */ public void addFigure(Figure figure) throws OccupiedCellException { for (int i = 0; i < figureIndex; i++) { if (figures[i].position.getPosition().equals(figure.position.getPosition())) { throw new OccupiedCellException("Occupied Cell"); } } figures[figureIndex++] = figure; } /** * Delete figure. * * @param figure - figure on removing. * @throws FigureNotFoundException - Figure not found */ public void deleteFigure(Figure figure) throws FigureNotFoundException { boolean flag = true; for (int i = 0; i < figureIndex; i++) { if (figures[i].position.getPosition().equals(figure.position.getPosition())) { System.arraycopy(figures, i + 1, figures, i, figures.length - i - 1); figureIndex--; flag = false; break; } if (flag) { throw new FigureNotFoundException("Figure not found"); } } } /** * This method checks the possibility of move. * * @param source cell * @param dist cell * @return boolean true or exception * @throws ImpossibleMoveException - illegal move for that figure * @throws OccupiedWayException - Occupied way * @throws FigureNotFoundException - Figure not found */ boolean move(Cell source, Cell dist) throws ImpossibleMoveException, OccupiedWayException, FigureNotFoundException { boolean flag = false; for (int i = 0; i < figureIndex; i++) { if (figures[i].position.getPosition().equals(source.getPosition())) { Cell[] arrayWay = figures[i].way(dist); for (i = 0; i < arrayWay.length; i++) { for (int j = 0; j < figureIndex; j++) { if (figures[j].position.getPosition().equals(arrayWay[i].getPosition())) { throw new OccupiedWayException("Occupied way"); } } } flag = true; break; } } if (!flag) { throw new FigureNotFoundException("Figure not found"); } return flag; } /** * @param index of figures array. * @return figure. */ public Figure getFigure(int index) { return figures[index]; } /** * Moves a figure to a new position. * * @param source cell * @param dist cell * @throws OccupiedWayException - Occupied way * @throws FigureNotFoundException - Figure not found * @throws ImpossibleMoveException - impossible move. */ public void moveFigure(Cell source, Cell dist) throws OccupiedWayException, FigureNotFoundException, ImpossibleMoveException { if (move(source, dist)) { for (int i = 0; i < figureIndex; i++) { if (figures[i].position.getPosition().equals(source.getPosition())) { figures[i] = figures[i].clone(dist); break; } } } } }
apache-2.0
hekate-io/hekate
hekate-core/src/main/java/io/hekate/network/address/AddressPattern.java
9876
/* * Copyright 2022 The Hekate Project * * The Hekate Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.hekate.network.address; import io.hekate.core.HekateException; import io.hekate.core.internal.util.AddressUtils; import io.hekate.network.NetworkServiceFactory; import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; import java.util.List; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Pattern-based implementation of {@link AddressSelector} interface. * * <p> * This implementation of {@link AddressSelector} interface scans through all available network interfaces of the local host and uses * the pattern matching logic in order to decide which address should be selected. * </p> * * <p> * The following patterns can be specified: * </p> * * <ul> * <li><b>any</b> - any non-loopback address</li> * <li><b>any-ip4</b> - any IPv4 non-loopback address</li> * <li><b>any-ip6</b> - any IPv6 non-loopback address</li> * * <li><b>ip~<i>regex</i></b> - any IP address that matches the specified regular expression</li> * <li><b>ip4~<i>regex</i></b> - any IPv4 address that matches the specified regular expression</li> * <li><b>ip6~<i>regex</i></b> - any IPv6 address that matches the specified regular expression</li> * * <li><b>!ip~<i>regex</i></b> - any IP address that does NOT match the specified regular expression</li> * <li><b>!ip4~<i>regex</i></b> - any IPv4 address that does NOT match the specified regular expression</li> * <li><b>!ip6~<i>regex</i></b> - any IPv6 address that does NOT match the specified regular expression</li> * * <li><b>net~<i>regex</i></b> - any IP address of a network interface whose {@link NetworkInterface#getName() name} matches the specified * regular expression</li> * <li><b>net4~<i>regex</i></b> - IPv4 address of a network interface whose {@link NetworkInterface#getName() name} matches the specified * regular expression</li> * <li><b>net6~<i>regex</i></b> - IPv6 address of a network interface whose {@link NetworkInterface#getName() name} matches the specified * regular expression</li> * * <li><b>!net~<i>regex</i></b> - any IP address of a network interface whose {@link NetworkInterface#getName() name} does NOT match the * specified regular expression</li> * <li><b>!net4~<i>regex</i></b> - IPv4 address of a network interface whose {@link NetworkInterface#getName() name} does NOT match the * specified regular expression</li> * <li><b>!net6~<i>regex</i></b> - IPv6 address of a network interface whose {@link NetworkInterface#getName() name} does NOT match the * specified regular expression</li> * * <li>...all other values will be treated as a directly specified address (see {@link InetAddress#getByName(String)})</li> * </ul> * * <p> * If several addresses match the specified pattern, the first one will be selected (order is not guaranteed, but preference will be given * to non-{@link NetworkInterface#isPointToPoint() P2P} addresses). * </p> * * @see AddressSelector * @see NetworkServiceFactory#setHostSelector(AddressSelector) */ public class AddressPattern implements AddressSelector { private static final Logger log = LoggerFactory.getLogger(AddressPattern.class); private static final boolean DEBUG = log.isDebugEnabled(); private final AddressPatternOpts opts; /** * Constructs a new instance with {@code 'any'} pattern. */ public AddressPattern() { this(null); } /** * Constructs a new instance. * * @param pattern Pattern (see the descriptions of this class for the list of supported patterns). */ public AddressPattern(String pattern) { this.opts = AddressPatternOpts.parse(pattern); } /** * Returns the host pattern as string. * * @return Host pattern. */ public String pattern() { return opts.toString(); } @Override public InetAddress select() throws HekateException { try { if (opts.exactAddress() != null) { if (DEBUG) { log.debug("Using the exact address [{}]", opts); } return InetAddress.getByName(opts.exactAddress()); } if (DEBUG) { log.debug("Trying to resolve address [{}]", opts); } Pattern niIncludes = regex(opts.interfaceMatch()); Pattern niExcludes = regex(opts.interfaceNotMatch()); Pattern addrIncludes = regex(opts.ipMatch()); Pattern addrExcludes = regex(opts.ipNotMatch()); List<NetworkInterface> nis = networkInterfaces(); InetAddress p2pAddr = null; String p2pNiName = null; for (NetworkInterface ni : nis) { if (!ni.isUp() || ni.isLoopback()) { continue; } String niName = ni.getName(); if (matches(true, niName, niIncludes) && matches(false, niName, niExcludes)) { Enumeration<InetAddress> addresses = ni.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (DEBUG) { log.debug("Trying address {}", address); } if (checkAddress(addrIncludes, addrExcludes, niName, address)) { if (ni.isPointToPoint()) { // If this is a P2P address then store it as a selected address in case if there are no other addresses. if (p2pAddr == null) { p2pAddr = address; p2pNiName = niName; } } else { if (DEBUG) { log.debug("Resolved address [interface={}, address={}]", niName, address); } // Returns the selected address. return address; } } } } else { if (DEBUG) { log.debug("Skipped network interface that doesn't match name pattern [name={}]", niName); } } } if (DEBUG) { log.debug("Resolved Point-to-Point address [interface={}, address={}]", p2pNiName, p2pAddr); } // Returns the first selected P2P address if we couldn't find any alternatives. return p2pAddr; } catch (IOException e) { throw new HekateException("Failed to resolve node address [" + opts + ']', e); } } // Package level for testing purposes. AddressPatternOpts opts() { return opts; } // Package level for testing purposes. List<NetworkInterface> networkInterfaces() throws SocketException { return AddressUtils.activeNetworks(); } private boolean checkAddress(Pattern addrIncludes, Pattern addrExcludes, String niName, InetAddress address) { if (address.isLinkLocalAddress()) { if (DEBUG) { log.debug("Skipped link local address [interface={}, address={}]", niName, address); } } else if (!ipVersionMatch(address)) { if (DEBUG) { log.debug("Skipped address that doesn't match IP protocol version [interface={}, address={}]", niName, address); } } else { String host = address.getHostAddress(); if (matches(true, host, addrIncludes) && matches(false, host, addrExcludes)) { return true; } else { if (DEBUG) { log.debug("Skipped address that doesn't match host pattern [interface={}, address={}]", niName, host); } } } return false; } private boolean ipVersionMatch(InetAddress addr) { if (opts.ipVersion() != null) { switch (opts.ipVersion()) { case V4: { return addr instanceof Inet4Address; } case V6: { return addr instanceof Inet6Address; } default: { throw new IllegalStateException("Unexpected IP version type: " + opts.ipVersion()); } } } return true; } private boolean matches(boolean shouldMatch, String str, Pattern pattern) { return pattern == null || pattern.matcher(str).matches() == shouldMatch; } private Pattern regex(String pattern) { if (pattern != null) { pattern = pattern.trim(); if (!pattern.isEmpty()) { return Pattern.compile(pattern); } } return null; } @Override public String toString() { return opts.toString(); } }
apache-2.0
MarkusKrug/NERDetection
neDetectionProject/src/de/uniwue/mk/kall/featuregeneratorPOS/WordLEngthFeaturegenerator.java
495
package de.uniwue.mk.kall.featuregeneratorPOS; import org.apache.uima.cas.CAS; import de.uniwue.mkrug.kall.typesystemutil.Util_impl; import de.uniwue.mkrug.nerapplication.TokenInstance; public class WordLEngthFeaturegenerator extends AFeatureGenerator { @Override public String[] generateFeature(TokenInstance instance, CAS cas, Util_impl util) { Integer length = instance.getToken().getCoveredText().length(); return new String[] { "Wordlength=" + length.toString() }; } }
apache-2.0
vschs007/buck
test/com/facebook/buck/apple/AppleBinaryIntegrationTest.java
45152
/* * Copyright 2014-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.apple; import static com.facebook.buck.cxx.CxxFlavorSanitizer.sanitize; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import com.facebook.buck.cxx.CxxDescriptionEnhancer; import com.facebook.buck.cxx.CxxStrip; import com.facebook.buck.cxx.LinkerMapMode; import com.facebook.buck.cxx.StripStyle; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargetFactory; import com.facebook.buck.model.BuildTargets; import com.facebook.buck.model.Flavor; import com.facebook.buck.model.InternalFlavor; import com.facebook.buck.testutil.MoreAsserts; import com.facebook.buck.testutil.integration.ProjectWorkspace; import com.facebook.buck.testutil.integration.TemporaryPaths; import com.facebook.buck.testutil.integration.TestDataHelper; import com.facebook.buck.util.ProcessExecutor; import com.facebook.buck.util.environment.Platform; import com.google.common.collect.ImmutableList; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; public class AppleBinaryIntegrationTest { @Rule public TemporaryPaths tmp = new TemporaryPaths(); private ProjectFilesystem filesystem; @Before public void setUp() { assumeTrue(Platform.detect() == Platform.MACOS || Platform.detect() == Platform.LINUX); filesystem = new ProjectFilesystem(tmp.getRoot()); } @Test public void testAppleBinaryBuildsBinaryWithLinkerMap() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_builds_something", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance("//Apps/TestApp:TestApp"); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); Path outputPath = workspace.getPath( BuildTargets.getGenPath( filesystem, target, "%s")); assertThat(Files.exists(outputPath), is(true)); assertThat(Files.exists(Paths.get(outputPath.toString() + "-LinkMap.txt")), is(true)); assertThat( workspace.runCommand("file", outputPath.toString()).getStdout().get(), containsString("executable")); } @Test public void testAppleBinaryBuildsBinaryWithoutLinkerMap() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_builds_something", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance("//Apps/TestApp:TestApp") .withFlavors(LinkerMapMode.NO_LINKER_MAP.getFlavor()); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); Path outputPath = workspace.getPath( BuildTargets.getGenPath( filesystem, target, "%s")); assertThat(Files.exists(outputPath), is(true)); assertThat(Files.exists(Paths.get(outputPath.toString() + "-LinkMap.txt")), is(false)); assertThat( workspace.runCommand("file", outputPath.toString()).getStdout().get(), containsString("executable")); } @Test public void testAppleBinaryUsesDefaultsFromConfig() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_with_config_default_platform", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance("//Apps/TestApp:TestApp") .withAppendedFlavors(InternalFlavor.of("iphoneos-arm64")); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); Path outputPath = workspace.getPath(BuildTargets.getGenPath(filesystem, target, "%s")); assertThat(Files.exists(outputPath), is(true)); assertThat(Files.exists(Paths.get(outputPath.toString() + "-LinkMap.txt")), is(true)); assertThat( workspace.runCommand("file", outputPath.toString()).getStdout().get(), containsString("executable")); assertThat( workspace.runCommand("otool", "-hv", outputPath.toString()).getStdout().get(), containsString("ARM64")); } @Test public void testAppleBinaryUsesDefaultsFromArgs() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_with_platform", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance("//Apps/TestApp:TestApp") .withAppendedFlavors( InternalFlavor.of("iphoneos-arm64")); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); Path outputPath = workspace.getPath(BuildTargets.getGenPath(filesystem, target, "%s")); assertThat(Files.exists(outputPath), is(true)); assertThat(Files.exists(Paths.get(outputPath.toString() + "-LinkMap.txt")), is(true)); assertThat( workspace.runCommand("file", outputPath.toString()).getStdout().get(), containsString("executable")); assertThat( workspace.runCommand("otool", "-hv", outputPath.toString()).getStdout().get(), containsString("ARM64")); } @Test public void testAppleBinaryUsesPlatformLinkerFlags() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_builds_something", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory .newInstance("//Apps/TestApp:TestAppWithNonstandardMain"); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); Path outputPath = workspace.getPath( BuildTargets.getGenPath( filesystem, target, "%s")); assertThat(Files.exists(outputPath), is(true)); assertThat( workspace.runCommand("file", outputPath.toString()).getStdout().get(), containsString("executable")); } @Test public void testAppleBinaryWithThinLTO() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_with_thinlto", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance("//Apps/TestApp:TestApp"); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); Path outputPath = workspace.getPath( BuildTargets.getGenPath( filesystem, target, "%s")); assertThat(Files.exists(outputPath), is(true)); assertThat(Files.isDirectory(Paths.get(outputPath.toString() + "-lto")), is(true)); assertThat( workspace.runCommand("file", outputPath.toString()).getStdout().get(), containsString("executable")); } @Test public void testAppleBinaryWithThinLTOWithLibraryDependency() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_with_thinlto_library_dependency", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance( "//Apps/TestApp:TestApp#app,macosx-x86_64"); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); Path outputPath = workspace.getPath( BuildTargets.getGenPath( filesystem, BuildTargetFactory.newInstance( "//Apps/TestApp:TestApp#macosx-x86_64").withAppendedFlavors( AppleDescriptions.INCLUDE_FRAMEWORKS_FLAVOR), "%s")); assertThat(Files.isDirectory(Paths.get(outputPath.toString() + "-lto")), is(true)); Path bundlePath = workspace.getPath( BuildTargets.getGenPath( filesystem, target.withAppendedFlavors( AppleDebugFormat.DWARF_AND_DSYM.getFlavor(), AppleDescriptions.INCLUDE_FRAMEWORKS_FLAVOR), "%s/TestApp.app")); assertThat(Files.exists(bundlePath), is(true)); Path binaryPath = bundlePath.resolve("Contents/MacOS/TestApp"); assertThat(Files.exists(binaryPath), is(true)); assertThat( workspace.runCommand("file", binaryPath.toString()).getStdout().get(), containsString("executable")); Path frameworkBundlePath = bundlePath.resolve("Contents/Frameworks/TestLibrary.framework"); assertThat(Files.exists(frameworkBundlePath), is(true)); Path frameworkBinaryPath = frameworkBundlePath.resolve("TestLibrary"); assertThat(Files.exists(frameworkBinaryPath), is(true)); assertThat( workspace.runCommand("file", frameworkBinaryPath.toString()).getStdout().get(), containsString("dynamically linked shared library")); } @Test public void testAppleBinaryAppBuildsAppWithDsym() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_builds_something", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance("//Apps/TestApp:TestApp#app"); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); BuildTarget appTarget = target.withFlavors( AppleBinaryDescription.APP_FLAVOR, AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR, AppleDebugFormat.DWARF_AND_DSYM.getFlavor()); Path outputPath = workspace.getPath( BuildTargets.getGenPath(filesystem, appTarget, "%s") .resolve(appTarget.getShortName() + ".app")); assertThat(Files.exists(outputPath), is(true)); assertThat(Files.exists(outputPath.resolve("Info.plist")), is(true)); Path dsymPath = workspace.getPath( BuildTargets.getGenPath(filesystem, appTarget, "%s") .resolve(appTarget.getShortName() + ".app.dSYM")); assertThat(Files.exists(dsymPath), is(true)); assertThat( workspace.runCommand( "file", outputPath.resolve(appTarget.getShortName()).toString()).getStdout().get(), containsString("executable")); } @Test public void testAppleBinaryAppBuildsAppWithoutDsym() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_builds_something", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance("//Apps/TestApp:TestApp#app,no-debug"); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); BuildTarget appTarget = target.withFlavors( AppleBinaryDescription.APP_FLAVOR, AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR, AppleDebugFormat.NONE.getFlavor()); Path outputPath = workspace.getPath( BuildTargets.getGenPath(filesystem, appTarget, "%s") .resolve(appTarget.getShortName() + ".app")); assertThat(Files.exists(outputPath), is(true)); assertThat(Files.exists(outputPath.resolve("Info.plist")), is(true)); Path dsymPath = workspace.getPath( BuildTargets.getGenPath(filesystem, appTarget, "%s") .resolve(appTarget.getShortName() + ".app.dSYM")); assertThat(Files.exists(dsymPath), is(false)); } @Test public void testAppleBinaryWithSystemFrameworksBuildsSomething() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_with_system_frameworks_builds_something", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance( "//Apps/TestApp:TestApp#macosx-x86_64"); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); Path outputPath = workspace.getPath( BuildTargets.getGenPath( filesystem, target, "%s")); assertThat(Files.exists(outputPath), is(true)); assertThat( workspace.runCommand("file", outputPath.toString()).getStdout().get(), containsString("executable")); } @Test public void testAppleBinaryWithLibraryDependencyBuildsSomething() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_with_library_dependency_builds_something", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance("//Apps/TestApp:TestApp") .withAppendedFlavors( InternalFlavor.of("macosx-x86_64")); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); Path outputPath = workspace.getPath( BuildTargets.getGenPath( filesystem, target, "%s")); assertThat(Files.exists(outputPath), is(true)); assertThat( workspace.runCommand("file", outputPath.toString()).getStdout().get(), containsString("executable")); } @Test public void testAppleBinaryWithLibraryDependencyBuildsApp() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_with_library_dependency_builds_something", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance( "//Apps/TestApp:TestApp#app,macosx-x86_64"); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); Path bundlePath = workspace.getPath( BuildTargets.getGenPath( filesystem, target.withAppendedFlavors( AppleDebugFormat.DWARF_AND_DSYM.getFlavor(), AppleDescriptions.INCLUDE_FRAMEWORKS_FLAVOR), "%s/TestApp.app")); assertThat(Files.exists(bundlePath), is(true)); Path binaryPath = bundlePath.resolve("Contents/MacOS/TestApp"); assertThat(Files.exists(binaryPath), is(true)); assertThat( workspace.runCommand("file", binaryPath.toString()).getStdout().get(), containsString("executable")); Path frameworkBundlePath = bundlePath.resolve("Contents/Frameworks/TestLibrary.framework"); assertThat(Files.exists(frameworkBundlePath), is(true)); Path frameworkBinaryPath = frameworkBundlePath.resolve("TestLibrary"); assertThat(Files.exists(frameworkBinaryPath), is(true)); assertThat( workspace.runCommand("file", frameworkBinaryPath.toString()).getStdout().get(), containsString("dynamically linked shared library")); } @Test public void testAppleBinaryWithLibraryDependencyWithSystemFrameworksBuildsSomething() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX)); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_with_library_dependency_with_system_frameworks_builds_something", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance("//Apps/TestApp:TestApp") .withAppendedFlavors( InternalFlavor.of("macosx-x86_64")); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); Path outputPath = workspace.getPath(BuildTargets.getGenPath( filesystem, target, "%s")); assertThat(Files.exists(outputPath), is(true)); assertThat( workspace.runCommand("file", outputPath.toString()).getStdout().get(), containsString("executable")); } @Test public void testAppleLibraryPropagatesExportedPlatformLinkerFlags() throws IOException, InterruptedException { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_with_library_dependency_builds_something", tmp); workspace.setUp(); ProjectWorkspace.ProcessResult buildResult = workspace.runBuckCommand("build", "//Apps/TestApp:BadTestApp"); buildResult.assertFailure(); String stderr = buildResult.getStderr(); assertTrue(stderr.contains("bad-flag")); } @Test public void testAppleBinaryHeaderSymlinkTree() throws IOException { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_header_symlink_tree", tmp); workspace.setUp(); BuildTarget buildTarget = BuildTargetFactory.newInstance("//Apps/TestApp:TestApp#default," + CxxDescriptionEnhancer.HEADER_SYMLINK_TREE_FLAVOR); ProjectWorkspace.ProcessResult result = workspace.runBuckCommand( "build", buildTarget.getFullyQualifiedName()); result.assertSuccess(); Path projectRoot = tmp.getRoot().toRealPath(); Path inputPath = projectRoot.resolve( buildTarget.getBasePath()); Path outputPath = projectRoot.resolve( BuildTargets.getGenPath(filesystem, buildTarget, "%s")); assertIsSymbolicLink( outputPath.resolve("Header.h"), inputPath.resolve("Header.h")); assertIsSymbolicLink( outputPath.resolve("TestApp/Header.h"), inputPath.resolve("Header.h")); } @Test public void testAppleBinaryWithHeaderMaps() throws Exception { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_with_header_maps", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance("//Apps/TestApp:TestApp"); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); Path outputPath = workspace.getPath( BuildTargets.getGenPath( filesystem, target, "%s")); assertThat(Files.exists(outputPath), is(true)); assertThat( workspace.runCommand("file", outputPath.toString()).getStdout().get(), containsString("executable")); } @Test public void testAppleXcodeError() throws IOException { assumeTrue(Platform.detect() == Platform.MACOS); String expectedError = "Apps/TestApp/main.c:2:3: error: use of undeclared identifier 'SomeType'\n" + " SomeType a;\n" + " ^\n"; String expectedWarning = "Apps/TestApp/main.c:3:10: warning: implicit conversion from 'double' to 'int' changes " + "value from 0.42 to 0 [-Wliteral-conversion]\n" + " return 0.42;\n" + " ~~~~~~ ^~~~\n"; String expectedSummary = "1 warning and 1 error generated.\n"; ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_xcode_error", tmp); workspace.setUp(); ProjectWorkspace.ProcessResult buildResult = workspace.runBuckCommand("build", "//Apps/TestApp:TestApp"); buildResult.assertFailure(); String stderr = buildResult.getStderr(); assertTrue( stderr.contains(expectedError) && stderr.contains(expectedWarning) && stderr.contains(expectedSummary)); } @Test public void testAppleBinaryIsHermetic() throws IOException { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_is_hermetic", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance("//Apps/TestApp:TestApp") .withAppendedFlavors( InternalFlavor.of("iphonesimulator-x86_64")); ProjectWorkspace.ProcessResult first = workspace.runBuckCommand( workspace.getPath("first"), "build", target.getFullyQualifiedName()); first.assertSuccess(); ProjectWorkspace.ProcessResult second = workspace.runBuckCommand( workspace.getPath("second"), "build", target.getFullyQualifiedName()); second.assertSuccess(); Path outputPath = BuildTargets.getGenPath( filesystem, target.withFlavors( InternalFlavor.of("iphonesimulator-x86_64"), InternalFlavor.of("compile-" + sanitize("TestClass.m.o"))), "%s/TestClass.m.o"); MoreAsserts.assertContentsEqual( workspace.getPath(Paths.get("first").resolve(outputPath)), workspace.getPath(Paths.get("second").resolve(outputPath))); outputPath = BuildTargets.getGenPath( filesystem, target, "%s"); MoreAsserts.assertContentsEqual( workspace.getPath(Paths.get("first").resolve(outputPath)), workspace.getPath(Paths.get("second").resolve(outputPath))); } private void runTestAppleBinaryWithDebugFormatIsHermetic(AppleDebugFormat debugFormat) throws IOException { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "apple_binary_is_hermetic", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance( "//Apps/TestApp:TestApp#iphonesimulator-x86_64," + debugFormat.getFlavor().getName()); ProjectWorkspace.ProcessResult first = workspace.runBuckCommand( workspace.getPath("first"), "build", target.getFullyQualifiedName()); first.assertSuccess(); ProjectWorkspace.ProcessResult second = workspace.runBuckCommand( workspace.getPath("second"), "build", target.getFullyQualifiedName()); second.assertSuccess(); Path outputPath = BuildTargets.getGenPath( filesystem, target.withFlavors( InternalFlavor.of("iphonesimulator-x86_64"), InternalFlavor.of("compile-" + sanitize("TestClass.m.o"))), "%s/TestClass.m.o"); MoreAsserts.assertContentsEqual( workspace.getPath(Paths.get("first").resolve(outputPath)), workspace.getPath(Paths.get("second").resolve(outputPath))); outputPath = BuildTargets.getGenPath( filesystem, target.withoutFlavors(AppleDebugFormat.FLAVOR_DOMAIN.getFlavors()), "%s"); MoreAsserts.assertContentsEqual( workspace.getPath(Paths.get("first").resolve(outputPath)), workspace.getPath(Paths.get("second").resolve(outputPath))); if (debugFormat != AppleDebugFormat.DWARF) { Path strippedPath = BuildTargets.getGenPath( filesystem, target .withoutFlavors(AppleDebugFormat.FLAVOR_DOMAIN.getFlavors()) .withAppendedFlavors( StripStyle.NON_GLOBAL_SYMBOLS.getFlavor(), CxxStrip.RULE_FLAVOR), "%s"); MoreAsserts.assertContentsEqual( workspace.getPath(Paths.get("first").resolve(strippedPath)), workspace.getPath(Paths.get("second").resolve(strippedPath))); } } @Test public void testAppleBinaryWithDwarfDebugFormatIsHermetic() throws IOException { runTestAppleBinaryWithDebugFormatIsHermetic(AppleDebugFormat.DWARF); } @Test public void testAppleBinaryWithDwarfAndDsymDebugFormatIsHermetic() throws IOException { runTestAppleBinaryWithDebugFormatIsHermetic(AppleDebugFormat.DWARF_AND_DSYM); } @Test public void testAppleBinaryWithNoneDebugFormatIsHermetic() throws IOException { runTestAppleBinaryWithDebugFormatIsHermetic(AppleDebugFormat.NONE); } @Test public void testAppleBinaryBuildsFatBinaries() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple_application_bundle_dwarf_and_dsym", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance( "//:DemoAppBinary#iphonesimulator-i386,iphonesimulator-x86_64,no-linkermap"); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); Path output = workspace.getPath(BuildTargets.getGenPath(filesystem, target, "%s")); assertThat(Files.exists(output), is(true)); assertThat( workspace.runCommand("file", output.toString()).getStdout().get(), containsString("executable")); ProcessExecutor.Result lipoVerifyResult = workspace.runCommand("lipo", output.toString(), "-verify_arch", "i386", "x86_64"); assertEquals( lipoVerifyResult.getStderr().orElse(""), 0, lipoVerifyResult.getExitCode()); } @Test public void testAppleBinaryBuildsFatBinariesWithDsym() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple_application_bundle_no_debug", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance( "//:DemoAppBinary#iphonesimulator-i386,iphonesimulator-x86_64,no-linkermap"); BuildTarget targetToBuild = target .withAppendedFlavors(AppleDebugFormat.DWARF_AND_DSYM.getFlavor()); BuildTarget dsymTarget = target.withAppendedFlavors(AppleDsym.RULE_FLAVOR); workspace.runBuckCommand("build", targetToBuild.getFullyQualifiedName()).assertSuccess(); Path output = workspace.getPath( AppleDsym.getDsymOutputPath(dsymTarget.withoutFlavors( LinkerMapMode.NO_LINKER_MAP.getFlavor()), filesystem)); AppleDsymTestUtil .checkDsymFileHasDebugSymbolsForMainForConcreteArchitectures( workspace, output, Optional.of(ImmutableList.of("i386", "x86_64"))); } @Test public void testFlavoredAppleBundleBuildsAndDsymFileCreatedAndBinaryIsStripped() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple_application_bundle_dwarf_and_dsym", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance("//:DemoApp#dwarf-and-dsym"); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); workspace.runBuckCommand("build", "--config", "apple.default_debug_info_format_for_binaries=none", target.getFullyQualifiedName()) .assertSuccess(); BuildTarget appTarget = target.withFlavors( AppleDebugFormat.DWARF_AND_DSYM.getFlavor(), AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR); Path output = workspace.getPath( BuildTargets.getGenPath(filesystem, appTarget, "%s") .resolve(target.getShortName() + ".app.dSYM") .resolve("Contents/Resources/DWARF") .resolve(target.getShortName())); assertThat(Files.exists(output), equalTo(true)); AppleDsymTestUtil.checkDsymFileHasDebugSymbolForMain(workspace, output); Path binaryOutput = workspace.getPath( BuildTargets.getGenPath(filesystem, appTarget, "%s") .resolve(target.getShortName() + ".app") .resolve(target.getShortName())); assertThat(Files.exists(binaryOutput), equalTo(true)); ProcessExecutor.Result hasSymbol = workspace.runCommand("nm", binaryOutput.toString()); String stdout = hasSymbol.getStdout().orElse(""); assertThat(stdout, Matchers.not(containsString("t -[AppDelegate window]"))); assertThat(stdout, containsString("U _UIApplicationMain")); } @Test public void testFlavoredAppleBundleBuildsWithDwarfDebugFormatAndBinaryIsUnstripped() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple_application_bundle_dwarf_and_dsym", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance("//:DemoApp#dwarf"); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); BuildTarget appTarget = target.withFlavors( AppleDebugFormat.DWARF.getFlavor(), AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR); Path output = workspace.getPath( BuildTargets.getGenPath(filesystem, appTarget, "%s") .resolve(target.getShortName() + ".app") .resolve(target.getShortName())); assertThat(Files.exists(output), equalTo(true)); ProcessExecutor.Result hasSymbol = workspace.runCommand("nm", output.toString()); String stdout = hasSymbol.getStdout().orElse(""); assertThat(stdout, containsString("t -[AppDelegate window]")); assertThat(stdout, containsString("U _UIApplicationMain")); } @Test public void testBuildingWithDwarfProducesAllCompileRulesOnDisk() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple_application_bundle_dwarf_and_dsym", tmp); workspace.setUp(); workspace.enableDirCache(); Flavor platformFlavor = InternalFlavor.of("iphonesimulator-x86_64"); BuildTarget target = BuildTargetFactory.newInstance("//:DemoApp") .withAppendedFlavors(AppleDebugFormat.DWARF.getFlavor()); BuildTarget binaryTarget = BuildTargetFactory.newInstance("//:DemoAppBinary") .withAppendedFlavors(platformFlavor, AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); workspace.runBuckCommand("clean").assertSuccess(); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); BuildTarget appTarget = target.withFlavors( AppleDebugFormat.DWARF.getFlavor(), AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR); Path binaryOutput = workspace.getPath( BuildTargets.getGenPath(filesystem, appTarget, "%s") .resolve(target.getShortName() + ".app") .resolve(target.getShortName())); Path delegateFileOutput = workspace.getPath( BuildTargets .getGenPath( filesystem, binaryTarget.withFlavors( platformFlavor, InternalFlavor.of("compile-" + sanitize("AppDelegate.m.o"))), "%s") .resolve("AppDelegate.m.o")); Path mainFileOutput = workspace.getPath( BuildTargets .getGenPath( filesystem, binaryTarget.withFlavors( platformFlavor, InternalFlavor.of("compile-" + sanitize("main.m.o"))), "%s") .resolve("main.m.o")); assertThat(Files.exists(binaryOutput), equalTo(true)); assertThat(Files.exists(delegateFileOutput), equalTo(true)); assertThat(Files.exists(mainFileOutput), equalTo(true)); } @Test public void testBuildingWithNoDebugDoesNotProduceAllCompileRulesOnDisk() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple_application_bundle_dwarf_and_dsym", tmp); workspace.setUp(); workspace.enableDirCache(); Flavor platformFlavor = InternalFlavor.of("iphonesimulator-x86_64"); BuildTarget target = BuildTargetFactory.newInstance("//:DemoApp") .withAppendedFlavors(AppleDebugFormat.NONE.getFlavor()); BuildTarget binaryTarget = BuildTargetFactory.newInstance("//:DemoAppBinary") .withAppendedFlavors(platformFlavor, AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); workspace.runBuckCommand("clean").assertSuccess(); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); BuildTarget appTarget = target.withFlavors( AppleDebugFormat.NONE.getFlavor(), AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR); Path binaryOutput = workspace.getPath( BuildTargets.getGenPath(filesystem, appTarget, "%s") .resolve(target.getShortName() + ".app") .resolve(target.getShortName())); Path delegateFileOutput = workspace.getPath( BuildTargets .getGenPath( filesystem, binaryTarget.withFlavors( platformFlavor, InternalFlavor.of("compile-" + sanitize("AppDelegate.m.o")), AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR), "%s") .resolve("AppDelegate.m.o")); Path mainFileOutput = workspace.getPath( BuildTargets .getGenPath( filesystem, binaryTarget.withFlavors( platformFlavor, InternalFlavor.of("compile-" + sanitize("main.m.o")), AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR), "%s") .resolve("main.m.o")); assertThat(Files.exists(binaryOutput), equalTo(true)); assertThat(Files.exists(delegateFileOutput), equalTo(false)); assertThat(Files.exists(mainFileOutput), equalTo(false)); } @Test public void testBuildingWithDwarfAndDsymDoesNotProduceAllCompileRulesOnDisk() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple_application_bundle_dwarf_and_dsym", tmp); workspace.setUp(); workspace.enableDirCache(); Flavor platformFlavor = InternalFlavor.of("iphonesimulator-x86_64"); BuildTarget target = BuildTargetFactory.newInstance("//:DemoApp") .withAppendedFlavors(AppleDebugFormat.DWARF_AND_DSYM.getFlavor()); BuildTarget binaryTarget = BuildTargetFactory.newInstance("//:DemoAppBinary") .withAppendedFlavors(platformFlavor, AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); workspace.runBuckCommand("clean").assertSuccess(); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); BuildTarget appTarget = target.withFlavors( AppleDebugFormat.DWARF_AND_DSYM.getFlavor(), AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR); Path binaryOutput = workspace.getPath( BuildTargets.getGenPath(filesystem, appTarget, "%s") .resolve(target.getShortName() + ".app") .resolve(target.getShortName())); Path delegateFileOutput = workspace.getPath( BuildTargets .getGenPath( filesystem, binaryTarget.withFlavors( platformFlavor, InternalFlavor.of("compile-" + sanitize("AppDelegate.m.o")), AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR), "%s") .resolve("AppDelegate.m.o")); Path mainFileOutput = workspace.getPath( BuildTargets .getGenPath( filesystem, binaryTarget.withFlavors( platformFlavor, InternalFlavor.of("compile-" + sanitize("main.m.o")), AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR), "%s") .resolve("main.m.o")); assertThat(Files.exists(binaryOutput), equalTo(true)); assertThat(Files.exists(delegateFileOutput), equalTo(false)); assertThat(Files.exists(mainFileOutput), equalTo(false)); } @Test public void testFlavoredAppleBundleBuildsAndDsymFileIsNotCreatedAndBinaryIsStripped() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple_application_bundle_no_debug", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance("//:DemoApp#no-debug"); workspace.runBuckCommand("build", "--config", "apple.default_debug_info_format_for_binaries=dwarf_and_dsym", target.getFullyQualifiedName()) .assertSuccess(); assertThat( Files.exists( workspace.getPath( BuildTargets.getGenPath(filesystem, target, "%s") .resolve(target.getShortName() + ".app.dSYM") .resolve("Contents/Resources/DWARF") .resolve(target.getShortName()))), equalTo(false)); assertThat( Files.exists( workspace.getPath( BuildTargets .getGenPath( filesystem, target.withFlavors(AppleDebugFormat.DWARF_AND_DSYM.getFlavor()), "%s") .resolve(target.getShortName() + ".app.dSYM") .resolve("Contents/Resources/DWARF") .resolve(target.getShortName()))), equalTo(false)); assertThat( Files.exists( workspace.getPath( BuildTargets.getGenPath(filesystem, target.withFlavors(), "%s") .resolve(target.getShortName() + ".app.dSYM") .resolve("Contents/Resources/DWARF") .resolve(target.getShortName()))), equalTo(false)); BuildTarget appTarget = target.withFlavors( AppleDebugFormat.NONE.getFlavor(), AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR); Path binaryOutput = workspace.getPath( BuildTargets.getGenPath(filesystem, appTarget, "%s") .resolve(target.getShortName() + ".app") .resolve(target.getShortName())); assertThat(Files.exists(binaryOutput), equalTo(true)); ProcessExecutor.Result hasSymbol = workspace.runCommand("nm", binaryOutput.toString()); String stdout = hasSymbol.getStdout().orElse(""); assertThat(stdout, Matchers.not(containsString("t -[AppDelegate window]"))); assertThat(stdout, containsString("U _UIApplicationMain")); } @Test public void testAppleBundleDebugFormatRespectsDefaultConfigSettingDSYM() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple_application_bundle_no_debug", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance("//:DemoApp"); workspace.runBuckCommand("build", "--config", "apple.default_debug_info_format_for_binaries=dwarf_and_dsym", target.getFullyQualifiedName()) .assertSuccess(); BuildTarget appTarget = target.withFlavors( AppleDebugFormat.DWARF_AND_DSYM.getFlavor(), AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR); Path dwarfPath = workspace.getPath( BuildTargets.getGenPath(filesystem, appTarget, "%s") .resolve(appTarget.getShortName() + ".app.dSYM") .resolve("Contents/Resources/DWARF") .resolve(appTarget.getShortName())); assertThat(Files.exists(dwarfPath), equalTo(true)); AppleDsymTestUtil.checkDsymFileHasDebugSymbolForMain(workspace, dwarfPath); } @Test public void testAppleBundleDebugFormatRespectsDefaultConfigSettingNoDebug() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "simple_application_bundle_no_debug", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance("//:DemoApp"); workspace.runBuckCommand("build", "--config", "apple.default_debug_info_format_for_binaries=none", target.getFullyQualifiedName()) .assertSuccess(); BuildTarget appTarget = target.withFlavors(AppleDebugFormat.NONE.getFlavor()); assertThat( Files.exists( workspace.getPath( BuildTargets.getGenPath(filesystem, appTarget, "%s") .resolve(appTarget.getShortName() + ".app.dSYM") .resolve("Contents/Resources/DWARF") .resolve(appTarget.getShortName()))), equalTo(false)); } @Test public void multiarchBinaryShouldCopyLinkMapOfComponents() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); BuildTarget singleArchI386Target = BuildTargetFactory.newInstance("//:DemoApp#iphonesimulator-i386"); BuildTarget singleArchX8664Target = BuildTargetFactory.newInstance("//:DemoApp#iphonesimulator-x86_64"); BuildTarget target = BuildTargetFactory.newInstance("//:DemoApp#iphonesimulator-i386,iphonesimulator-x86_64"); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "multiarch_binary_linkmap", tmp); workspace.setUp(); workspace.runBuckBuild(target.getFullyQualifiedName()).assertSuccess(); assertTrue( "Has link map for i386 arch.", Files.exists( workspace.getPath( BuildTargets.getGenPath(filesystem, target, "%s-LinkMap") .resolve( singleArchI386Target.getShortNameAndFlavorPostfix() + "-LinkMap.txt")))); assertTrue( "Has link map for x86_64 arch.", Files.exists( workspace.getPath( BuildTargets.getGenPath(filesystem, target, "%s-LinkMap") .resolve( singleArchX8664Target.getShortNameAndFlavorPostfix() + "-LinkMap.txt")))); } @Test public void testBuildEmptySourceAppleBinaryDependsOnNonEmptyAppleLibrary() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "empty_source_targets", tmp); workspace.setUp(); BuildTarget target = workspace.newBuildTarget("//:real-none2#macosx-x86_64"); ProjectWorkspace.ProcessResult result = workspace.runBuckCommand( "run", target.getFullyQualifiedName()); result.assertSuccess(); Assert.assertThat( result.getStdout(), equalTo("Hello")); } @Test public void testAppleBinaryBuildsFatBinariesWithSwift() throws Exception { assumeTrue(Platform.detect() == Platform.MACOS); ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario( this, "mixed_swift_objc_application_bundle_dwarf_and_dsym", tmp); workspace.setUp(); BuildTarget target = BuildTargetFactory.newInstance( "//:DemoAppBinary#iphonesimulator-i386,iphonesimulator-x86_64,no-linkermap"); workspace.runBuckCommand("build", target.getFullyQualifiedName()).assertSuccess(); Path output = workspace.getPath(BuildTargets.getGenPath(filesystem, target, "%s")); assertThat(Files.exists(output), is(true)); assertThat( workspace.runCommand("file", output.toString()).getStdout().get(), containsString("executable")); ProcessExecutor.Result lipoVerifyResult = workspace.runCommand("lipo", output.toString(), "-verify_arch", "i386", "x86_64"); assertEquals( lipoVerifyResult.getStderr().orElse(""), 0, lipoVerifyResult.getExitCode()); } private static void assertIsSymbolicLink( Path link, Path target) throws IOException { assertTrue(Files.isSymbolicLink(link)); assertEquals( target, Files.readSymbolicLink(link)); } }
apache-2.0
arnost-starosta/midpoint
gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/RefinedObjectTypeChoicePanel.java
3657
/** * Copyright (c) 2016 Evolveum * * 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.evolveum.midpoint.web.component.input; import java.util.ArrayList; import java.util.List; import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; import org.apache.commons.lang.StringUtils; import org.apache.wicket.markup.html.form.IChoiceRenderer; import org.apache.wicket.model.IModel; import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition; import com.evolveum.midpoint.common.refinery.RefinedResourceSchema; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; /** * @author semancik * */ public class RefinedObjectTypeChoicePanel extends DropDownChoicePanel<RefinedObjectClassDefinition> { private static final Trace LOGGER = TraceManager.getTrace(RefinedObjectTypeChoicePanel.class); public RefinedObjectTypeChoicePanel(String id, IModel<RefinedObjectClassDefinition> model, IModel<PrismObject<ResourceType>> resourceModel) { super(id, model, createChoiceModel(resourceModel), createRenderer(), false); } private static IModel<? extends List<? extends RefinedObjectClassDefinition>> createChoiceModel(final IModel<PrismObject<ResourceType>> resourceModel) { return new IModel<List<? extends RefinedObjectClassDefinition>>() { @Override public List<? extends RefinedObjectClassDefinition> getObject() { RefinedResourceSchema refinedSchema; try { refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(resourceModel.getObject()); } catch (SchemaException e) { throw new IllegalArgumentException(e.getMessage(),e); } List<? extends RefinedObjectClassDefinition> refinedDefinitions = refinedSchema.getRefinedDefinitions(); List<? extends RefinedObjectClassDefinition> defs = new ArrayList<>(); for (RefinedObjectClassDefinition rdef: refinedDefinitions) { if (rdef.getKind() != null) { ((List)defs).add(rdef); } } return defs; } @Override public void detach() { } @Override public void setObject(List<? extends RefinedObjectClassDefinition> object) { throw new UnsupportedOperationException(); } }; } private static IChoiceRenderer<RefinedObjectClassDefinition> createRenderer() { return new IChoiceRenderer<RefinedObjectClassDefinition>() { @Override public Object getDisplayValue(RefinedObjectClassDefinition object) { if (object.getDisplayName() != null) { return object.getDisplayName(); } return object.getHumanReadableName(); } @Override public String getIdValue(RefinedObjectClassDefinition object, int index) { return Integer.toString(index); } @Override public RefinedObjectClassDefinition getObject(String id, IModel<? extends List<? extends RefinedObjectClassDefinition>> choices) { return StringUtils.isNotBlank(id) ? choices.getObject().get(Integer.parseInt(id)) : null; } }; } }
apache-2.0
krazychen/kcfw
src/main/java/com/krazy/kcfw/modules/sys/entity/Role.java
6201
/** * Copyright &copy; 2012-2016 <a href="https://github.com/krazy/kcfw">kcfw</a> All rights reserved. */ package com.krazy.kcfw.modules.sys.entity; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.hibernate.validator.constraints.Length; import com.google.common.collect.Lists; import com.krazy.kcfw.common.config.Global; import com.krazy.kcfw.common.persistence.DataEntity; /** * 角色Entity * @author krazy * @version 2013-12-05 */ public class Role extends DataEntity<Role> { private static final long serialVersionUID = 1L; private Office office; // 归属机构 private String name; // 角色名称 private String enname; // 英文名称 private String roleType;// 权限类型 private String dataScope;// 数据范围 private String oldName; // 原角色名称 private String oldEnname; // 原英文名称 private String sysData; //是否是系统数据 private String useable; //是否是可用 private User user; // 根据用户ID查询角色列表 // private List<User> userList = Lists.newArrayList(); // 拥有用户列表 private List<Menu> menuList = Lists.newArrayList(); // 拥有菜单列表 private List<Office> officeList = Lists.newArrayList(); // 按明细设置数据范围 // 数据范围(1:所有数据;2:所在公司及以下数据;3:所在公司数据;4:所在部门及以下数据;5:所在部门数据;8:仅本人数据;9:按明细设置) public static final String DATA_SCOPE_ALL = "1"; public static final String DATA_SCOPE_COMPANY_AND_CHILD = "2"; public static final String DATA_SCOPE_COMPANY = "3"; public static final String DATA_SCOPE_OFFICE_AND_CHILD = "4"; public static final String DATA_SCOPE_OFFICE = "5"; public static final String DATA_SCOPE_SELF = "8"; public static final String DATA_SCOPE_CUSTOM = "9"; public Role() { super(); this.dataScope = DATA_SCOPE_SELF; this.useable=Global.YES; } public Role(String id){ super(id); } public Role(User user) { this(); this.user = user; } public String getUseable() { return useable; } public void setUseable(String useable) { this.useable = useable; } public String getSysData() { return sysData; } public void setSysData(String sysData) { this.sysData = sysData; } public Office getOffice() { return office; } public void setOffice(Office office) { this.office = office; } @Length(min=1, max=100) public String getName() { return name; } public void setName(String name) { this.name = name; } @Length(min=1, max=100) public String getEnname() { return enname; } public void setEnname(String enname) { this.enname = enname; } @Length(min=1, max=100) public String getRoleType() { return roleType; } public void setRoleType(String roleType) { this.roleType = roleType; } public String getDataScope() { return dataScope; } public void setDataScope(String dataScope) { this.dataScope = dataScope; } public String getOldName() { return oldName; } public void setOldName(String oldName) { this.oldName = oldName; } public String getOldEnname() { return oldEnname; } public void setOldEnname(String oldEnname) { this.oldEnname = oldEnname; } // public List<User> getUserList() { // return userList; // } // // public void setUserList(List<User> userList) { // this.userList = userList; // } // // public List<String> getUserIdList() { // List<String> nameIdList = Lists.newArrayList(); // for (User user : userList) { // nameIdList.add(user.getId()); // } // return nameIdList; // } // // public String getUserIds() { // return StringUtils.join(getUserIdList(), ","); // } public List<Menu> getMenuList() { return menuList; } public void setMenuList(List<Menu> menuList) { this.menuList = menuList; } public List<String> getMenuIdList() { List<String> menuIdList = Lists.newArrayList(); for (Menu menu : menuList) { menuIdList.add(menu.getId()); } return menuIdList; } public void setMenuIdList(List<String> menuIdList) { menuList = Lists.newArrayList(); for (String menuId : menuIdList) { Menu menu = new Menu(); menu.setId(menuId); menuList.add(menu); } } public String getMenuIds() { return StringUtils.join(getMenuIdList(), ","); } public void setMenuIds(String menuIds) { menuList = Lists.newArrayList(); if (menuIds != null){ String[] ids = StringUtils.split(menuIds, ","); setMenuIdList(Lists.newArrayList(ids)); } } public List<Office> getOfficeList() { return officeList; } public void setOfficeList(List<Office> officeList) { this.officeList = officeList; } public List<String> getOfficeIdList() { List<String> officeIdList = Lists.newArrayList(); for (Office office : officeList) { officeIdList.add(office.getId()); } return officeIdList; } public void setOfficeIdList(List<String> officeIdList) { officeList = Lists.newArrayList(); for (String officeId : officeIdList) { Office office = new Office(); office.setId(officeId); officeList.add(office); } } public String getOfficeIds() { return StringUtils.join(getOfficeIdList(), ","); } public void setOfficeIds(String officeIds) { officeList = Lists.newArrayList(); if (officeIds != null){ String[] ids = StringUtils.split(officeIds, ","); setOfficeIdList(Lists.newArrayList(ids)); } } /** * 获取权限字符串列表 */ public List<String> getPermissions() { List<String> permissions = Lists.newArrayList(); for (Menu menu : menuList) { if (menu.getPermission()!=null && !"".equals(menu.getPermission())){ permissions.add(menu.getPermission()); } } return permissions; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } // public boolean isAdmin(){ // return isAdmin(this.id); // } // // public static boolean isAdmin(String id){ // return id != null && "1".equals(id); // } // @Transient // public String getMenuNames() { // List<String> menuNameList = Lists.newArrayList(); // for (Menu menu : menuList) { // menuNameList.add(menu.getName()); // } // return StringUtils.join(menuNameList, ","); // } }
apache-2.0
stari4ek/ExoPlayer
library/extractor/src/test/java/com/google/android/exoplayer2/extractor/mp4/Mp4ExtractorTest.java
2742
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.extractor.mp4; import com.google.android.exoplayer2.testutil.ExtractorAsserts; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.ParameterizedRobolectricTestRunner; import org.robolectric.ParameterizedRobolectricTestRunner.Parameter; import org.robolectric.ParameterizedRobolectricTestRunner.Parameters; /** Tests for {@link Mp4Extractor}. */ @RunWith(ParameterizedRobolectricTestRunner.class) public final class Mp4ExtractorTest { @Parameters(name = "{0}") public static List<Object[]> params() { return ExtractorAsserts.configs(); } @Parameter public ExtractorAsserts.SimulationConfig simulationConfig; @Test public void mp4Sample() throws Exception { ExtractorAsserts.assertBehavior(Mp4Extractor::new, "mp4/sample.mp4", simulationConfig); } @Test public void mp4SampleWithSlowMotionMetadata() throws Exception { ExtractorAsserts.assertBehavior( Mp4Extractor::new, "mp4/sample_android_slow_motion.mp4", simulationConfig); } /** * Test case for https://github.com/google/ExoPlayer/issues/6774. The sample file contains an mdat * atom whose size indicates that it extends 8 bytes beyond the end of the file. */ @Test public void mp4SampleWithMdatTooLong() throws Exception { ExtractorAsserts.assertBehavior( Mp4Extractor::new, "mp4/sample_mdat_too_long.mp4", simulationConfig); } @Test public void mp4SampleWithAc3Track() throws Exception { ExtractorAsserts.assertBehavior(Mp4Extractor::new, "mp4/sample_ac3.mp4", simulationConfig); } @Test public void mp4SampleWithAc4Track() throws Exception { ExtractorAsserts.assertBehavior(Mp4Extractor::new, "mp4/sample_ac4.mp4", simulationConfig); } @Test public void mp4SampleWithEac3Track() throws Exception { ExtractorAsserts.assertBehavior(Mp4Extractor::new, "mp4/sample_eac3.mp4", simulationConfig); } @Test public void mp4SampleWithEac3jocTrack() throws Exception { ExtractorAsserts.assertBehavior(Mp4Extractor::new, "mp4/sample_eac3joc.mp4", simulationConfig); } }
apache-2.0
jonefeewang/armeria
core/src/test/java/com/linecorp/armeria/common/RequestContextTest.java
17406
/* * Copyright 2016 LINE Corporation * * LINE Corporation licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.linecorp.armeria.common; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import com.google.common.util.concurrent.MoreExecutors; import com.linecorp.armeria.common.http.DefaultHttpRequest; import com.linecorp.armeria.common.http.HttpMethod; import com.linecorp.armeria.common.http.HttpSessionProtocols; import com.linecorp.armeria.common.logging.RequestLog; import com.linecorp.armeria.common.logging.RequestLogBuilder; import com.linecorp.armeria.common.util.SafeCloseable; import io.netty.channel.Channel; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelPromise; import io.netty.channel.DefaultChannelPromise; import io.netty.channel.DefaultEventLoop; import io.netty.channel.EventLoop; import io.netty.util.concurrent.DefaultPromise; import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.FutureListener; import io.netty.util.concurrent.ImmediateEventExecutor; import io.netty.util.concurrent.ProgressivePromise; import io.netty.util.concurrent.Promise; public class RequestContextTest { private static final EventLoop eventLoop = new DefaultEventLoop(); @AfterClass public static void stopEventLoop() { eventLoop.shutdownGracefully(); } @Rule public MockitoRule mocks = MockitoJUnit.rule(); @Rule public ExpectedException thrown = ExpectedException.none(); @Mock private Channel channel; private final List<RequestContext> ctxStack = new ArrayList<>(); @Test public void contextAwareEventExecutor() throws Exception { when(channel.eventLoop()).thenReturn(eventLoop); RequestContext context = createContext(); Set<Integer> callbacksCalled = Collections.newSetFromMap(new ConcurrentHashMap<>()); EventExecutor executor = context.contextAwareEventLoop(); CountDownLatch latch = new CountDownLatch(18); executor.execute(() -> checkCallback(1, context, callbacksCalled, latch)); executor.schedule(() -> checkCallback(2, context, callbacksCalled, latch), 0, TimeUnit.SECONDS); executor.schedule(() -> { checkCallback(2, context, callbacksCalled, latch); return "success"; }, 0, TimeUnit.SECONDS); executor.scheduleAtFixedRate(() -> checkCallback(3, context, callbacksCalled, latch), 0, 1000, TimeUnit.SECONDS); executor.scheduleWithFixedDelay(() -> checkCallback(4, context, callbacksCalled, latch), 0, 1000, TimeUnit.SECONDS); executor.submit(() -> checkCallback(5, context, callbacksCalled, latch)); executor.submit(() -> checkCallback(6, context, callbacksCalled, latch), "success"); executor.submit(() -> { checkCallback(7, context, callbacksCalled, latch); return "success"; }); executor.invokeAll(makeTaskList(8, 10, context, callbacksCalled, latch)); executor.invokeAll(makeTaskList(11, 12, context, callbacksCalled, latch), 10000, TimeUnit.SECONDS); executor.invokeAny(makeTaskList(13, 13, context, callbacksCalled, latch)); executor.invokeAny(makeTaskList(14, 14, context, callbacksCalled, latch), 10000, TimeUnit.SECONDS); Promise<String> promise = executor.newPromise(); promise.addListener(f -> checkCallback(15, context, callbacksCalled, latch)); promise.setSuccess("success"); executor.newSucceededFuture("success") .addListener(f -> checkCallback(16, context, callbacksCalled, latch)); executor.newFailedFuture(new IllegalArgumentException()) .addListener(f -> checkCallback(17, context, callbacksCalled, latch)); ProgressivePromise<String> progressivePromise = executor.newProgressivePromise(); progressivePromise.addListener(f -> checkCallback(18, context, callbacksCalled, latch)); progressivePromise.setSuccess("success"); latch.await(); eventLoop.shutdownGracefully().sync(); assertThat(callbacksCalled).containsExactlyElementsOf(IntStream.rangeClosed(1, 18).boxed()::iterator); } @Test public void makeContextAwareExecutor() { RequestContext context = createContext(); Executor executor = context.makeContextAware(MoreExecutors.directExecutor()); AtomicBoolean callbackCalled = new AtomicBoolean(false); executor.execute(() -> { assertCurrentContext(context); assertDepth(1); callbackCalled.set(true); }); assertThat(callbackCalled.get()).isTrue(); assertDepth(0); } @Test public void makeContextAwareCallable() throws Exception { RequestContext context = createContext(); context.makeContextAware(() -> { assertCurrentContext(context); assertDepth(1); return "success"; }).call(); assertDepth(0); } @Test public void makeContextAwareRunnable() { RequestContext context = createContext(); context.makeContextAware(() -> { assertCurrentContext(context); assertDepth(1); }).run(); assertDepth(0); } @Test @SuppressWarnings("deprecation") public void makeContextAwareFutureListener() { RequestContext context = createContext(); Promise<String> promise = new DefaultPromise<>(ImmediateEventExecutor.INSTANCE); promise.addListener(context.makeContextAware((FutureListener<String>) f -> { assertCurrentContext(context); assertDepth(1); assertThat(f.getNow()).isEqualTo("success"); })); promise.setSuccess("success"); } @Test @SuppressWarnings("deprecation") public void makeContextAwareChannelFutureListener() { RequestContext context = createContext(); ChannelPromise promise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE); promise.addListener(context.makeContextAware((ChannelFutureListener) f -> { assertCurrentContext(context); assertDepth(1); assertThat(f.getNow()).isNull(); })); promise.setSuccess(null); } @Test public void makeContextAwareCompletableFutureInSameThread() throws Exception { RequestContext context = createContext(); CompletableFuture<String> originalFuture = new CompletableFuture<>(); CompletableFuture<String> contextAwareFuture = context.makeContextAware(originalFuture); CompletableFuture<String> resultFuture = contextAwareFuture.whenComplete((result, cause) -> { assertThat(result).isEqualTo("success"); assertThat(cause).isNull(); assertCurrentContext(context); assertDepth(1); }); originalFuture.complete("success"); assertDepth(0); resultFuture.get(); // this will propagate assertions. } @Test public void makeContextAwareCompletableFutureWithExecutor() throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); try { RequestContext context = createContext(); Thread testMainThread = Thread.currentThread(); AtomicReference<Thread> callbackThread = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); CompletableFuture<String> originalFuture = CompletableFuture.supplyAsync(() -> { try { // In CompletableFuture chaining, if previous callback was already completed, // next chained callback will run in same thread instead of executor's thread. // We should add callbacks before they were completed. This latch is for preventing it. latch.await(); } catch (InterruptedException e) { throw new IllegalStateException(e); } final Thread currentThread = Thread.currentThread(); callbackThread.set(currentThread); assertThat(currentThread).isNotSameAs(testMainThread); return "success"; }, executor); CompletableFuture<String> contextAwareFuture = context.makeContextAware(originalFuture); CompletableFuture<String> resultFuture = contextAwareFuture.whenComplete((result, cause) -> { final Thread currentThread = Thread.currentThread(); assertThat(currentThread).isNotSameAs(testMainThread) .isSameAs(callbackThread.get()); assertThat(result).isEqualTo("success"); assertThat(cause).isNull(); assertCurrentContext(context); assertDepth(1); }); latch.countDown(); resultFuture.get(); // this will wait and propagate assertions. } finally { executor.shutdown(); } } @Test public void makeContextAwareCompletableFutureWithAsyncChaining() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(2); try { RequestContext context = createContext(); Thread testMainThread = Thread.currentThread(); CountDownLatch latch = new CountDownLatch(1); CompletableFuture<String> originalFuture = CompletableFuture.supplyAsync(() -> { try { latch.await(); } catch (InterruptedException e) { throw new IllegalStateException(e); } final Thread currentThread = Thread.currentThread(); assertThat(currentThread).isNotSameAs(testMainThread); return "success"; }, executor); BiConsumer<String, Throwable> handler = (result, cause) -> { final Thread currentThread = Thread.currentThread(); assertThat(currentThread).isNotSameAs(testMainThread); assertThat(result).isEqualTo("success"); assertThat(cause).isNull(); assertCurrentContext(context); }; CompletableFuture<String> contextAwareFuture = context.makeContextAware(originalFuture); CompletableFuture<String> future1 = contextAwareFuture.whenCompleteAsync(handler, executor); CompletableFuture<String> future2 = future1.whenCompleteAsync(handler, executor); latch.countDown(); // fire future2.get(); // this will propagate assertions in callbacks if it failed. } finally { executor.shutdown(); } } @Test public void contextPropagationSameContextAlreadySet() { final RequestContext context = createContext(); try (SafeCloseable ignored = RequestContext.push(context, false)) { context.makeContextAware(() -> { assertCurrentContext(context); // Context was already correct, so handlers were not run (in real code they would already be // in the correct state). assertDepth(0); }).run(); } } @Test public void contextPropagationDifferentContextAlreadySet() { final RequestContext context = createContext(); final RequestContext context2 = createContext(); try (SafeCloseable ignored = RequestContext.push(context2)) { thrown.expect(IllegalStateException.class); context.makeContextAware((Runnable) Assert::fail).run(); } } @Test public void makeContextAwareRunnableNoContextAwareHandler() { RequestContext context = createContext(false); context.makeContextAware(() -> { assertCurrentContext(context); assertDepth(0); }).run(); assertDepth(0); } @Test public void nestedContexts() { final RequestContext ctx1 = createContext(true); final RequestContext ctx2 = createContext(true); final AtomicBoolean nested = new AtomicBoolean(); try (SafeCloseable ignored = RequestContext.push(ctx1)) { assertDepth(1); assertThat(ctxStack).containsExactly(ctx1); ctx1.onChild((curCtx, newCtx) -> { assertThat(curCtx).isSameAs(ctx1); assertThat(newCtx).isSameAs(ctx2); nested.set(true); newCtx.onExit(unused -> nested.set(false)); }); assertThat(nested.get()).isFalse(); try (SafeCloseable ignored2 = RequestContext.push(ctx2)) { assertDepth(2); assertThat(ctxStack).containsExactly(ctx1, ctx2); assertThat(nested.get()).isTrue(); } assertDepth(1); assertThat(ctxStack).containsExactly(ctx1); assertThat(nested.get()).isFalse(); } assertDepth(0); } @Test public void timedOut() { RequestContext ctx = createContext(); assertThat(ctx.isTimedOut()).isFalse(); ((AbstractRequestContext) ctx).setTimedOut(); assertThat(ctx.isTimedOut()).isTrue(); } private void assertDepth(int expectedDepth) { assertThat(ctxStack).hasSize(expectedDepth); } private static List<Callable<String>> makeTaskList(int startId, int endId, RequestContext context, Set<Integer> callbacksCalled, CountDownLatch latch) { return IntStream.rangeClosed(startId, endId).boxed().map(id -> (Callable<String>) () -> { checkCallback(id, context, callbacksCalled, latch); return "success"; }).collect(Collectors.toList()); } private static void checkCallback(int id, RequestContext context, Set<Integer> callbacksCalled, CountDownLatch latch) { assertCurrentContext(context); if (!callbacksCalled.contains(id)) { callbacksCalled.add(id); latch.countDown(); } } private static void assertCurrentContext(RequestContext context) { final RequestContext ctx = RequestContext.current(); assertThat(ctx).isSameAs(context); } private NonWrappingRequestContext createContext() { return createContext(true); } private NonWrappingRequestContext createContext(boolean addContextAwareHandler) { final NonWrappingRequestContext ctx = new DummyRequestContext(); if (addContextAwareHandler) { ctx.onEnter(myCtx -> { ctxStack.add(myCtx); assertThat(myCtx).isSameAs(ctx); }); ctx.onExit(myCtx -> { assertThat(ctxStack.remove(ctxStack.size() - 1)).isSameAs(myCtx); assertThat(myCtx).isSameAs(ctx); }); } return ctx; } private class DummyRequestContext extends NonWrappingRequestContext { DummyRequestContext() { super(HttpSessionProtocols.HTTP, HttpMethod.GET, "/", null, new DefaultHttpRequest()); } @Override public EventLoop eventLoop() { return channel.eventLoop(); } @Override protected Channel channel() { return channel; } @Override public RequestLog log() { throw new UnsupportedOperationException(); } @Override public RequestLogBuilder logBuilder() { throw new UnsupportedOperationException(); } } }
apache-2.0
dennishuo/hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStoreTestBase.java
39715
/** * 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.hadoop.yarn.server.resourcemanager.recovery; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import javax.crypto.SecretKey; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.ipc.CallerContext; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.delegation.DelegationKey; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.ReservationDefinition; import org.apache.hadoop.yarn.api.records.ReservationId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.impl.pb.ApplicationSubmissionContextPBImpl; import org.apache.hadoop.yarn.api.records.impl.pb.ContainerLaunchContextPBImpl; import org.apache.hadoop.yarn.api.records.impl.pb.ContainerPBImpl; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.event.Event; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.proto.YarnProtos.ReservationAllocationStateProto; import org.apache.hadoop.yarn.security.AMRMTokenIdentifier; import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; import org.apache.hadoop.yarn.server.records.Version; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.RMDTSecretManagerState; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.RMState; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.AMRMTokenSecretManagerState; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; import org.apache.hadoop.yarn.server.resourcemanager.reservation.InMemoryReservationAllocation; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationAllocation; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationSystemTestUtil; import org.apache.hadoop.yarn.server.resourcemanager.reservation.ReservationSystemUtil; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.AggregateAppResourceUsage; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptEvent; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptMetrics; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.security.AMRMTokenSecretManager; import org.apache.hadoop.yarn.server.resourcemanager.security.ClientToAMTokenSecretManagerInRM; import org.apache.hadoop.yarn.server.security.MasterKeyData; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.hadoop.yarn.util.resource.DefaultResourceCalculator; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.junit.Assert; public class RMStateStoreTestBase { public static final Log LOG = LogFactory.getLog(RMStateStoreTestBase.class); protected final long epoch = 10L; static class TestDispatcher implements Dispatcher, EventHandler<Event> { ApplicationAttemptId attemptId; boolean notified = false; @SuppressWarnings("rawtypes") @Override public void register(Class<? extends Enum> eventType, EventHandler handler) { } @Override public void handle(Event event) { if (event instanceof RMAppAttemptEvent) { RMAppAttemptEvent rmAppAttemptEvent = (RMAppAttemptEvent) event; assertEquals(attemptId, rmAppAttemptEvent.getApplicationAttemptId()); } notified = true; synchronized (this) { notifyAll(); } } @SuppressWarnings("rawtypes") @Override public EventHandler<Event> getEventHandler() { return this; } } public static class StoreStateVerifier { void afterStoreApp(RMStateStore store, ApplicationId appId) {} void afterStoreAppAttempt(RMStateStore store, ApplicationAttemptId appAttId) {} } interface RMStateStoreHelper { RMStateStore getRMStateStore() throws Exception; boolean isFinalStateValid() throws Exception; void writeVersion(Version version) throws Exception; Version getCurrentVersion() throws Exception; boolean appExists(RMApp app) throws Exception; boolean attemptExists(RMAppAttempt attempt) throws Exception; } void waitNotify(TestDispatcher dispatcher) { long startTime = System.currentTimeMillis(); while(!dispatcher.notified) { synchronized (dispatcher) { try { dispatcher.wait(1000); } catch (InterruptedException e) { e.printStackTrace(); } } if(System.currentTimeMillis() - startTime > 1000*60) { fail("Timed out attempt store notification"); } } dispatcher.notified = false; } protected RMApp storeApp(RMStateStore store, ApplicationId appId, long submitTime, long startTime) throws Exception { ApplicationSubmissionContext context = new ApplicationSubmissionContextPBImpl(); context.setApplicationId(appId); context.setAMContainerSpec(new ContainerLaunchContextPBImpl()); RMApp mockApp = mock(RMApp.class); when(mockApp.getApplicationId()).thenReturn(appId); when(mockApp.getSubmitTime()).thenReturn(submitTime); when(mockApp.getStartTime()).thenReturn(startTime); when(mockApp.getApplicationSubmissionContext()).thenReturn(context); when(mockApp.getUser()).thenReturn("test"); when(mockApp.getCallerContext()) .thenReturn(new CallerContext.Builder("context").build()); store.storeNewApplication(mockApp); return mockApp; } protected RMAppAttempt storeAttempt(RMStateStore store, ApplicationAttemptId attemptId, String containerIdStr, Token<AMRMTokenIdentifier> appToken, SecretKey clientTokenMasterKey, TestDispatcher dispatcher) throws Exception { RMAppAttemptMetrics mockRmAppAttemptMetrics = mock(RMAppAttemptMetrics.class); Container container = new ContainerPBImpl(); container.setId(ContainerId.fromString(containerIdStr)); RMAppAttempt mockAttempt = mock(RMAppAttempt.class); when(mockAttempt.getAppAttemptId()).thenReturn(attemptId); when(mockAttempt.getMasterContainer()).thenReturn(container); when(mockAttempt.getAMRMToken()).thenReturn(appToken); when(mockAttempt.getClientTokenMasterKey()) .thenReturn(clientTokenMasterKey); when(mockAttempt.getRMAppAttemptMetrics()) .thenReturn(mockRmAppAttemptMetrics); when(mockRmAppAttemptMetrics.getAggregateAppResourceUsage()) .thenReturn(new AggregateAppResourceUsage(new HashMap<>())); dispatcher.attemptId = attemptId; store.storeNewApplicationAttempt(mockAttempt); waitNotify(dispatcher); return mockAttempt; } protected void updateAttempt(RMStateStore store, TestDispatcher dispatcher, ApplicationAttemptStateData attemptState) { dispatcher.attemptId = attemptState.getAttemptId(); store.updateApplicationAttemptState(attemptState); waitNotify(dispatcher); } void testRMAppStateStore(RMStateStoreHelper stateStoreHelper) throws Exception { testRMAppStateStore(stateStoreHelper, new StoreStateVerifier()); } void testRMAppStateStore(RMStateStoreHelper stateStoreHelper, StoreStateVerifier verifier) throws Exception { long submitTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis() + 1234; Configuration conf = new YarnConfiguration(); RMStateStore store = stateStoreHelper.getRMStateStore(); TestDispatcher dispatcher = new TestDispatcher(); store.setRMDispatcher(dispatcher); RMContext rmContext = mock(RMContext.class); when(rmContext.getStateStore()).thenReturn(store); AMRMTokenSecretManager appTokenMgr = spy(new AMRMTokenSecretManager(conf, rmContext)); MasterKeyData masterKeyData = appTokenMgr.createNewMasterKey(); when(appTokenMgr.getMasterKey()).thenReturn(masterKeyData); ClientToAMTokenSecretManagerInRM clientToAMTokenMgr = new ClientToAMTokenSecretManagerInRM(); ApplicationAttemptId attemptId1 = ApplicationAttemptId.fromString( "appattempt_1352994193343_0001_000001"); ApplicationId appId1 = attemptId1.getApplicationId(); storeApp(store, appId1, submitTime, startTime); verifier.afterStoreApp(store, appId1); // create application token and client token key for attempt1 Token<AMRMTokenIdentifier> appAttemptToken1 = generateAMRMToken(attemptId1, appTokenMgr); SecretKey clientTokenKey1 = clientToAMTokenMgr.createMasterKey(attemptId1); ContainerId containerId1 = storeAttempt(store, attemptId1, "container_1352994193343_0001_01_000001", appAttemptToken1, clientTokenKey1, dispatcher) .getMasterContainer().getId(); String appAttemptIdStr2 = "appattempt_1352994193343_0001_000002"; ApplicationAttemptId attemptId2 = ApplicationAttemptId.fromString( appAttemptIdStr2); // create application token and client token key for attempt2 Token<AMRMTokenIdentifier> appAttemptToken2 = generateAMRMToken(attemptId2, appTokenMgr); SecretKey clientTokenKey2 = clientToAMTokenMgr.createMasterKey(attemptId2); ContainerId containerId2 = storeAttempt(store, attemptId2, "container_1352994193343_0001_02_000001", appAttemptToken2, clientTokenKey2, dispatcher) .getMasterContainer().getId(); ApplicationAttemptId attemptIdRemoved = ApplicationAttemptId.fromString( "appattempt_1352994193343_0002_000001"); ApplicationId appIdRemoved = attemptIdRemoved.getApplicationId(); storeApp(store, appIdRemoved, submitTime, startTime); storeAttempt(store, attemptIdRemoved, "container_1352994193343_0002_01_000001", null, null, dispatcher); verifier.afterStoreAppAttempt(store, attemptIdRemoved); RMApp mockRemovedApp = mock(RMApp.class); RMAppAttemptMetrics mockRmAppAttemptMetrics = mock(RMAppAttemptMetrics.class); HashMap<ApplicationAttemptId, RMAppAttempt> attempts = new HashMap<ApplicationAttemptId, RMAppAttempt>(); ApplicationSubmissionContext context = new ApplicationSubmissionContextPBImpl(); context.setApplicationId(appIdRemoved); when(mockRemovedApp.getSubmitTime()).thenReturn(submitTime); when(mockRemovedApp.getApplicationSubmissionContext()).thenReturn(context); when(mockRemovedApp.getAppAttempts()).thenReturn(attempts); when(mockRemovedApp.getUser()).thenReturn("user1"); RMAppAttempt mockRemovedAttempt = mock(RMAppAttempt.class); when(mockRemovedAttempt.getAppAttemptId()).thenReturn(attemptIdRemoved); when(mockRemovedAttempt.getRMAppAttemptMetrics()) .thenReturn(mockRmAppAttemptMetrics); when(mockRmAppAttemptMetrics.getAggregateAppResourceUsage()) .thenReturn(new AggregateAppResourceUsage(new HashMap<>())); attempts.put(attemptIdRemoved, mockRemovedAttempt); store.removeApplication(mockRemovedApp); // remove application directory recursively. storeApp(store, appIdRemoved, submitTime, startTime); storeAttempt(store, attemptIdRemoved, "container_1352994193343_0002_01_000001", null, null, dispatcher); store.removeApplication(mockRemovedApp); // let things settle down Thread.sleep(1000); store.close(); // give tester a chance to modify app state in the store modifyAppState(); // load state store = stateStoreHelper.getRMStateStore(); store.setRMDispatcher(dispatcher); RMState state = store.loadState(); Map<ApplicationId, ApplicationStateData> rmAppState = state.getApplicationState(); ApplicationStateData appState = rmAppState.get(appId1); // app is loaded assertNotNull(appState); // app is loaded correctly assertEquals(submitTime, appState.getSubmitTime()); assertEquals(startTime, appState.getStartTime()); // submission context is loaded correctly assertEquals(appId1, appState.getApplicationSubmissionContext().getApplicationId()); ApplicationAttemptStateData attemptState = appState.getAttempt(attemptId1); // attempt1 is loaded correctly assertNotNull(attemptState); assertEquals(attemptId1, attemptState.getAttemptId()); assertEquals(-1000, attemptState.getAMContainerExitStatus()); // attempt1 container is loaded correctly assertEquals(containerId1, attemptState.getMasterContainer().getId()); // attempt1 client token master key is loaded correctly assertArrayEquals( clientTokenKey1.getEncoded(), attemptState.getAppAttemptTokens() .getSecretKey(RMStateStore.AM_CLIENT_TOKEN_MASTER_KEY_NAME)); assertEquals("context", appState.getCallerContext().getContext()); attemptState = appState.getAttempt(attemptId2); // attempt2 is loaded correctly assertNotNull(attemptState); assertEquals(attemptId2, attemptState.getAttemptId()); // attempt2 container is loaded correctly assertEquals(containerId2, attemptState.getMasterContainer().getId()); // attempt2 client token master key is loaded correctly assertArrayEquals( clientTokenKey2.getEncoded(), attemptState.getAppAttemptTokens() .getSecretKey(RMStateStore.AM_CLIENT_TOKEN_MASTER_KEY_NAME)); //******* update application/attempt state *******// ApplicationStateData appState2 = ApplicationStateData.newInstance(appState.getSubmitTime(), appState.getStartTime(), appState.getUser(), appState.getApplicationSubmissionContext(), RMAppState.FINISHED, "appDiagnostics", 1234, appState.getCallerContext()); appState2.attempts.putAll(appState.attempts); store.updateApplicationState(appState2); ApplicationAttemptStateData oldAttemptState = attemptState; ApplicationAttemptStateData newAttemptState = ApplicationAttemptStateData.newInstance( oldAttemptState.getAttemptId(), oldAttemptState.getMasterContainer(), oldAttemptState.getAppAttemptTokens(), oldAttemptState.getStartTime(), RMAppAttemptState.FINISHED, "myTrackingUrl", "attemptDiagnostics", FinalApplicationStatus.SUCCEEDED, 100, oldAttemptState.getFinishTime(), new HashMap<>(), new HashMap<>()); store.updateApplicationAttemptState(newAttemptState); // test updating the state of an app/attempt whose initial state was not // saved. ApplicationId dummyAppId = ApplicationId.newInstance(1234, 10); ApplicationSubmissionContext dummyContext = new ApplicationSubmissionContextPBImpl(); dummyContext.setApplicationId(dummyAppId); dummyContext.setAMContainerSpec(new ContainerLaunchContextPBImpl()); ApplicationStateData dummyApp = ApplicationStateData.newInstance(appState.getSubmitTime(), appState.getStartTime(), appState.getUser(), dummyContext, RMAppState.FINISHED, "appDiagnostics", 1234, null); store.updateApplicationState(dummyApp); ApplicationAttemptId dummyAttemptId = ApplicationAttemptId.newInstance(dummyAppId, 6); ApplicationAttemptStateData dummyAttempt = ApplicationAttemptStateData.newInstance(dummyAttemptId, oldAttemptState.getMasterContainer(), oldAttemptState.getAppAttemptTokens(), oldAttemptState.getStartTime(), RMAppAttemptState.FINISHED, "myTrackingUrl", "attemptDiagnostics", FinalApplicationStatus.SUCCEEDED, 111, oldAttemptState.getFinishTime(), new HashMap<>(), new HashMap<>()); store.updateApplicationAttemptState(dummyAttempt); // let things settle down Thread.sleep(1000); store.close(); // check updated application state. store = stateStoreHelper.getRMStateStore(); store.setRMDispatcher(dispatcher); RMState newRMState = store.loadState(); Map<ApplicationId, ApplicationStateData> newRMAppState = newRMState.getApplicationState(); assertNotNull(newRMAppState.get( dummyApp.getApplicationSubmissionContext().getApplicationId())); ApplicationStateData updatedAppState = newRMAppState.get(appId1); assertEquals(appState.getApplicationSubmissionContext().getApplicationId(), updatedAppState.getApplicationSubmissionContext().getApplicationId()); assertEquals(appState.getSubmitTime(), updatedAppState.getSubmitTime()); assertEquals(appState.getStartTime(), updatedAppState.getStartTime()); assertEquals(appState.getUser(), updatedAppState.getUser()); // new app state fields assertEquals( RMAppState.FINISHED, updatedAppState.getState()); assertEquals("appDiagnostics", updatedAppState.getDiagnostics()); assertEquals(1234, updatedAppState.getFinishTime()); // check updated attempt state assertNotNull(newRMAppState.get(dummyApp.getApplicationSubmissionContext ().getApplicationId()).getAttempt(dummyAttemptId)); ApplicationAttemptStateData updatedAttemptState = updatedAppState.getAttempt(newAttemptState.getAttemptId()); assertEquals(oldAttemptState.getAttemptId(), updatedAttemptState.getAttemptId()); assertEquals(containerId2, updatedAttemptState.getMasterContainer().getId()); assertArrayEquals( clientTokenKey2.getEncoded(), attemptState.getAppAttemptTokens() .getSecretKey(RMStateStore.AM_CLIENT_TOKEN_MASTER_KEY_NAME)); // new attempt state fields assertEquals(RMAppAttemptState.FINISHED, updatedAttemptState.getState()); assertEquals("myTrackingUrl", updatedAttemptState.getFinalTrackingUrl()); assertEquals("attemptDiagnostics", updatedAttemptState.getDiagnostics()); assertEquals(100, updatedAttemptState.getAMContainerExitStatus()); assertEquals(FinalApplicationStatus.SUCCEEDED, updatedAttemptState.getFinalApplicationStatus()); // assert store is in expected state after everything is cleaned assertTrue(stateStoreHelper.isFinalStateValid()); store.close(); } public void testRMDTSecretManagerStateStore( RMStateStoreHelper stateStoreHelper) throws Exception { RMStateStore store = stateStoreHelper.getRMStateStore(); TestDispatcher dispatcher = new TestDispatcher(); store.setRMDispatcher(dispatcher); // store RM delegation token; RMDelegationTokenIdentifier dtId1 = new RMDelegationTokenIdentifier(new Text("owner1"), new Text("renewer1"), new Text("realuser1")); int sequenceNumber = 1111; dtId1.setSequenceNumber(sequenceNumber); byte[] tokenBeforeStore = dtId1.getBytes(); Long renewDate1 = new Long(System.currentTimeMillis()); store.storeRMDelegationToken(dtId1, renewDate1); modifyRMDelegationTokenState(); Map<RMDelegationTokenIdentifier, Long> token1 = new HashMap<RMDelegationTokenIdentifier, Long>(); token1.put(dtId1, renewDate1); // store delegation key; DelegationKey key = new DelegationKey(1234, 4321 , "keyBytes".getBytes()); HashSet<DelegationKey> keySet = new HashSet<DelegationKey>(); keySet.add(key); store.storeRMDTMasterKey(key); RMDTSecretManagerState secretManagerState = store.loadState().getRMDTSecretManagerState(); Assert.assertEquals(token1, secretManagerState.getTokenState()); Assert.assertEquals(keySet, secretManagerState.getMasterKeyState()); Assert.assertEquals(sequenceNumber, secretManagerState.getDTSequenceNumber()); RMDelegationTokenIdentifier tokenAfterStore = secretManagerState.getTokenState().keySet().iterator().next(); Assert.assertTrue(Arrays.equals(tokenBeforeStore, tokenAfterStore.getBytes())); // update RM delegation token; renewDate1 = new Long(System.currentTimeMillis()); store.updateRMDelegationToken(dtId1, renewDate1); token1.put(dtId1, renewDate1); RMDTSecretManagerState updateSecretManagerState = store.loadState().getRMDTSecretManagerState(); Assert.assertEquals(token1, updateSecretManagerState.getTokenState()); Assert.assertEquals(keySet, updateSecretManagerState.getMasterKeyState()); Assert.assertEquals(sequenceNumber, updateSecretManagerState.getDTSequenceNumber()); // check to delete delegationKey store.removeRMDTMasterKey(key); keySet.clear(); RMDTSecretManagerState noKeySecretManagerState = store.loadState().getRMDTSecretManagerState(); Assert.assertEquals(token1, noKeySecretManagerState.getTokenState()); Assert.assertEquals(keySet, noKeySecretManagerState.getMasterKeyState()); Assert.assertEquals(sequenceNumber, noKeySecretManagerState.getDTSequenceNumber()); // check to delete delegationToken store.removeRMDelegationToken(dtId1); RMDTSecretManagerState noKeyAndTokenSecretManagerState = store.loadState().getRMDTSecretManagerState(); token1.clear(); Assert.assertEquals(token1, noKeyAndTokenSecretManagerState.getTokenState()); Assert.assertEquals(keySet, noKeyAndTokenSecretManagerState.getMasterKeyState()); Assert.assertEquals(sequenceNumber, noKeySecretManagerState.getDTSequenceNumber()); store.close(); } protected Token<AMRMTokenIdentifier> generateAMRMToken( ApplicationAttemptId attemptId, AMRMTokenSecretManager appTokenMgr) { Token<AMRMTokenIdentifier> appToken = appTokenMgr.createAndGetAMRMToken(attemptId); appToken.setService(new Text("appToken service")); return appToken; } public void testCheckVersion(RMStateStoreHelper stateStoreHelper) throws Exception { RMStateStore store = stateStoreHelper.getRMStateStore(); store.setRMDispatcher(new TestDispatcher()); // default version Version defaultVersion = stateStoreHelper.getCurrentVersion(); store.checkVersion(); Assert.assertEquals(defaultVersion, store.loadVersion()); // compatible version Version compatibleVersion = Version.newInstance(defaultVersion.getMajorVersion(), defaultVersion.getMinorVersion() + 2); stateStoreHelper.writeVersion(compatibleVersion); Assert.assertEquals(compatibleVersion, store.loadVersion()); store.checkVersion(); // overwrite the compatible version Assert.assertEquals(defaultVersion, store.loadVersion()); // incompatible version Version incompatibleVersion = Version.newInstance(defaultVersion.getMajorVersion() + 2, defaultVersion.getMinorVersion()); stateStoreHelper.writeVersion(incompatibleVersion); try { store.checkVersion(); Assert.fail("Invalid version, should fail."); } catch (Throwable t) { Assert.assertTrue(t instanceof RMStateVersionIncompatibleException); } } public void testEpoch(RMStateStoreHelper stateStoreHelper) throws Exception { RMStateStore store = stateStoreHelper.getRMStateStore(); store.setRMDispatcher(new TestDispatcher()); long firstTimeEpoch = store.getAndIncrementEpoch(); Assert.assertEquals(epoch, firstTimeEpoch); long secondTimeEpoch = store.getAndIncrementEpoch(); Assert.assertEquals(epoch + 1, secondTimeEpoch); long thirdTimeEpoch = store.getAndIncrementEpoch(); Assert.assertEquals(epoch + 2, thirdTimeEpoch); } public void testAppDeletion(RMStateStoreHelper stateStoreHelper) throws Exception { RMStateStore store = stateStoreHelper.getRMStateStore(); store.setRMDispatcher(new TestDispatcher()); ArrayList<RMApp> appList = createAndStoreApps(stateStoreHelper, store, 5); for (RMApp app : appList) { // remove the app store.removeApplication(app); // wait for app to be removed. while (true) { if (!stateStoreHelper.appExists(app)) { break; } else { Thread.sleep(100); } } } } private ArrayList<RMApp> createAndStoreApps( RMStateStoreHelper stateStoreHelper, RMStateStore store, int numApps) throws Exception { ArrayList<RMApp> appList = new ArrayList<RMApp>(); for (int i = 0; i < numApps; i++) { ApplicationId appId = ApplicationId.newInstance(1383183338, i); RMApp app = storeApp(store, appId, 123456789, 987654321); appList.add(app); } Assert.assertEquals(numApps, appList.size()); for (RMApp app : appList) { // wait for app to be stored. while (true) { if (stateStoreHelper.appExists(app)) { break; } else { Thread.sleep(100); } } } return appList; } public void testDeleteStore(RMStateStoreHelper stateStoreHelper) throws Exception { RMStateStore store = stateStoreHelper.getRMStateStore(); ArrayList<RMApp> appList = createAndStoreApps(stateStoreHelper, store, 5); store.deleteStore(); // verify apps deleted for (RMApp app : appList) { Assert.assertFalse(stateStoreHelper.appExists(app)); } } public void testRemoveApplication(RMStateStoreHelper stateStoreHelper) throws Exception { RMStateStore store = stateStoreHelper.getRMStateStore(); int noOfApps = 2; ArrayList<RMApp> appList = createAndStoreApps(stateStoreHelper, store, noOfApps); RMApp rmApp1 = appList.get(0); store.removeApplication(rmApp1.getApplicationId()); Assert.assertFalse(stateStoreHelper.appExists(rmApp1)); RMApp rmApp2 = appList.get(1); Assert.assertTrue(stateStoreHelper.appExists(rmApp2)); } public void testRemoveAttempt(RMStateStoreHelper stateStoreHelper) throws Exception { RMStateStore store = stateStoreHelper.getRMStateStore(); TestDispatcher dispatcher = new TestDispatcher(); store.setRMDispatcher(dispatcher); ApplicationId appId = ApplicationId.newInstance(1383183339, 6); storeApp(store, appId, 123456, 564321); ApplicationAttemptId attemptId1 = ApplicationAttemptId.newInstance(appId, 1); RMAppAttempt attempt1 = storeAttempt(store, attemptId1, ContainerId.newContainerId(attemptId1, 1).toString(), null, null, dispatcher); ApplicationAttemptId attemptId2 = ApplicationAttemptId.newInstance(appId, 2); RMAppAttempt attempt2 = storeAttempt(store, attemptId2, ContainerId.newContainerId(attemptId2, 1).toString(), null, null, dispatcher); store.removeApplicationAttemptInternal(attemptId1); Assert.assertFalse(stateStoreHelper.attemptExists(attempt1)); Assert.assertTrue(stateStoreHelper.attemptExists(attempt2)); // let things settle down Thread.sleep(1000); store.close(); // load state store = stateStoreHelper.getRMStateStore(); RMState state = store.loadState(); Map<ApplicationId, ApplicationStateData> rmAppState = state.getApplicationState(); ApplicationStateData appState = rmAppState.get(appId); // app is loaded assertNotNull(appState); assertEquals(2, appState.getFirstAttemptId()); assertNull(appState.getAttempt(attemptId1)); assertNotNull(appState.getAttempt(attemptId2)); } protected void modifyAppState() throws Exception { } protected void modifyRMDelegationTokenState() throws Exception { } public void testAMRMTokenSecretManagerStateStore( RMStateStoreHelper stateStoreHelper) throws Exception { System.out.println("Start testing"); RMStateStore store = stateStoreHelper.getRMStateStore(); TestDispatcher dispatcher = new TestDispatcher(); store.setRMDispatcher(dispatcher); RMContext rmContext = mock(RMContext.class); when(rmContext.getStateStore()).thenReturn(store); Configuration conf = new YarnConfiguration(); AMRMTokenSecretManager appTokenMgr = new AMRMTokenSecretManager(conf, rmContext); //create and save the first masterkey MasterKeyData firstMasterKeyData = appTokenMgr.createNewMasterKey(); AMRMTokenSecretManagerState state1 = AMRMTokenSecretManagerState.newInstance( firstMasterKeyData.getMasterKey(), null); rmContext.getStateStore() .storeOrUpdateAMRMTokenSecretManager(state1, false); // load state store = stateStoreHelper.getRMStateStore(); when(rmContext.getStateStore()).thenReturn(store); store.setRMDispatcher(dispatcher); RMState state = store.loadState(); Assert.assertNotNull(state.getAMRMTokenSecretManagerState()); Assert.assertEquals(firstMasterKeyData.getMasterKey(), state .getAMRMTokenSecretManagerState().getCurrentMasterKey()); Assert.assertNull(state .getAMRMTokenSecretManagerState().getNextMasterKey()); //create and save the second masterkey MasterKeyData secondMasterKeyData = appTokenMgr.createNewMasterKey(); AMRMTokenSecretManagerState state2 = AMRMTokenSecretManagerState .newInstance(firstMasterKeyData.getMasterKey(), secondMasterKeyData.getMasterKey()); rmContext.getStateStore().storeOrUpdateAMRMTokenSecretManager(state2, true); // load state store = stateStoreHelper.getRMStateStore(); when(rmContext.getStateStore()).thenReturn(store); store.setRMDispatcher(dispatcher); RMState state_2 = store.loadState(); Assert.assertNotNull(state_2.getAMRMTokenSecretManagerState()); Assert.assertEquals(firstMasterKeyData.getMasterKey(), state_2 .getAMRMTokenSecretManagerState().getCurrentMasterKey()); Assert.assertEquals(secondMasterKeyData.getMasterKey(), state_2 .getAMRMTokenSecretManagerState().getNextMasterKey()); // re-create the masterKeyData based on the recovered masterkey // should have the same secretKey appTokenMgr.recover(state_2); Assert.assertEquals(appTokenMgr.getCurrnetMasterKeyData().getSecretKey(), firstMasterKeyData.getSecretKey()); Assert.assertEquals(appTokenMgr.getNextMasterKeyData().getSecretKey(), secondMasterKeyData.getSecretKey()); store.close(); } public void testReservationStateStore( RMStateStoreHelper stateStoreHelper) throws Exception { RMStateStore store = stateStoreHelper.getRMStateStore(); TestDispatcher dispatcher = new TestDispatcher(); store.setRMDispatcher(dispatcher); RMContext rmContext = mock(RMContext.class); when(rmContext.getStateStore()).thenReturn(store); long ts = System.currentTimeMillis(); ReservationId r1 = ReservationId.newInstance(ts, 1); int start = 1; int[] alloc = { 10, 10, 10, 10, 10 }; ResourceCalculator res = new DefaultResourceCalculator(); Resource minAlloc = Resource.newInstance(1024, 1); boolean hasGang = true; String planName = "dedicated"; ReservationDefinition rDef = ReservationSystemTestUtil.createSimpleReservationDefinition( start, start + alloc.length + 1, alloc.length); ReservationAllocation allocation = new InMemoryReservationAllocation( r1, rDef, "u3", planName, 0, 0 + alloc.length, ReservationSystemTestUtil.generateAllocation(0L, 1L, alloc), res, minAlloc, hasGang); ReservationAllocationStateProto allocationStateProto = ReservationSystemUtil.buildStateProto(allocation); assertAllocationStateEqual(allocation, allocationStateProto); // 1. Load empty store and verify no errors store = stateStoreHelper.getRMStateStore(); when(rmContext.getStateStore()).thenReturn(store); store.setRMDispatcher(dispatcher); RMState state = store.loadState(); Map<String, Map<ReservationId, ReservationAllocationStateProto>> reservationState = state.getReservationState(); Assert.assertNotNull(reservationState); // 2. Store single reservation and verify String reservationIdName = r1.toString(); rmContext.getStateStore().storeNewReservation( allocationStateProto, planName, reservationIdName); // load state and verify new state validateStoredReservation( stateStoreHelper, dispatcher, rmContext, r1, planName, allocation, allocationStateProto); // 3. update state test alloc = new int[]{6, 6, 6}; hasGang = false; allocation = new InMemoryReservationAllocation( r1, rDef, "u3", planName, 2, 2 + alloc.length, ReservationSystemTestUtil.generateAllocation(1L, 2L, alloc), res, minAlloc, hasGang); allocationStateProto = ReservationSystemUtil.buildStateProto(allocation); rmContext.getStateStore().removeReservation(planName, reservationIdName); rmContext.getStateStore().storeNewReservation(allocationStateProto, planName, reservationIdName); // load state and verify updated reservation validateStoredReservation( stateStoreHelper, dispatcher, rmContext, r1, planName, allocation, allocationStateProto); // 4. add a second one and remove the first one ReservationId r2 = ReservationId.newInstance(ts, 2); ReservationAllocation allocation2 = new InMemoryReservationAllocation( r2, rDef, "u3", planName, 0, 0 + alloc.length, ReservationSystemTestUtil.generateAllocation(0L, 1L, alloc), res, minAlloc, hasGang); ReservationAllocationStateProto allocationStateProto2 = ReservationSystemUtil.buildStateProto(allocation2); String reservationIdName2 = r2.toString(); rmContext.getStateStore().storeNewReservation( allocationStateProto2, planName, reservationIdName2); rmContext.getStateStore().removeReservation(planName, reservationIdName); // load state and verify r1 is removed and r2 is still there Map<ReservationId, ReservationAllocationStateProto> reservations; store = stateStoreHelper.getRMStateStore(); when(rmContext.getStateStore()).thenReturn(store); store.setRMDispatcher(dispatcher); state = store.loadState(); reservationState = state.getReservationState(); Assert.assertNotNull(reservationState); reservations = reservationState.get(planName); Assert.assertNotNull(reservations); ReservationAllocationStateProto storedReservationAllocation = reservations.get(r1); Assert.assertNull("Removed reservation should not be available in store", storedReservationAllocation); storedReservationAllocation = reservations.get(r2); assertAllocationStateEqual( allocationStateProto2, storedReservationAllocation); assertAllocationStateEqual(allocation2, storedReservationAllocation); // 5. remove last reservation removes the plan state rmContext.getStateStore().removeReservation(planName, reservationIdName2); store = stateStoreHelper.getRMStateStore(); when(rmContext.getStateStore()).thenReturn(store); store.setRMDispatcher(dispatcher); state = store.loadState(); reservationState = state.getReservationState(); Assert.assertNotNull(reservationState); reservations = reservationState.get(planName); Assert.assertNull(reservations); } private void validateStoredReservation( RMStateStoreHelper stateStoreHelper, TestDispatcher dispatcher, RMContext rmContext, ReservationId r1, String planName, ReservationAllocation allocation, ReservationAllocationStateProto allocationStateProto) throws Exception { RMStateStore store = stateStoreHelper.getRMStateStore(); when(rmContext.getStateStore()).thenReturn(store); store.setRMDispatcher(dispatcher); RMState state = store.loadState(); Map<String, Map<ReservationId, ReservationAllocationStateProto>> reservationState = state.getReservationState(); Assert.assertNotNull(reservationState); Map<ReservationId, ReservationAllocationStateProto> reservations = reservationState.get(planName); Assert.assertNotNull(reservations); ReservationAllocationStateProto storedReservationAllocation = reservations.get(r1); Assert.assertNotNull(storedReservationAllocation); assertAllocationStateEqual( allocationStateProto, storedReservationAllocation); assertAllocationStateEqual(allocation, storedReservationAllocation); } void assertAllocationStateEqual( ReservationAllocationStateProto expected, ReservationAllocationStateProto actual) { Assert.assertEquals( expected.getAcceptanceTime(), actual.getAcceptanceTime()); Assert.assertEquals(expected.getStartTime(), actual.getStartTime()); Assert.assertEquals(expected.getEndTime(), actual.getEndTime()); Assert.assertEquals(expected.getContainsGangs(), actual.getContainsGangs()); Assert.assertEquals(expected.getUser(), actual.getUser()); assertEquals( expected.getReservationDefinition(), actual.getReservationDefinition()); assertEquals(expected.getAllocationRequestsList(), actual.getAllocationRequestsList()); } void assertAllocationStateEqual( ReservationAllocation expected, ReservationAllocationStateProto actual) { Assert.assertEquals( expected.getAcceptanceTime(), actual.getAcceptanceTime()); Assert.assertEquals(expected.getStartTime(), actual.getStartTime()); Assert.assertEquals(expected.getEndTime(), actual.getEndTime()); Assert.assertEquals(expected.containsGangs(), actual.getContainsGangs()); Assert.assertEquals(expected.getUser(), actual.getUser()); assertEquals( expected.getReservationDefinition(), ReservationSystemUtil.convertFromProtoFormat( actual.getReservationDefinition())); assertEquals( expected.getAllocationRequests(), ReservationSystemUtil.toAllocations( actual.getAllocationRequestsList())); } }
apache-2.0
pflima92/workspace-builder
tools-certifiedserver/src/br/com/techfullit/certifiedserver/utils/FolderUtils.java
5344
/** Copyright - 2015 - Paulo Henrique Ferreira de Lima - TechFull IT Services Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package br.com.techfullit.certifiedserver.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; /** * The Class FolderUtils. */ public class FolderUtils { /** * Copy. * * @param origem the origem * @param destino the destino * @param overwrite the overwrite * @throws IOException Signals that an I/O exception has occurred. */ public static void copy(File origem, File destino, boolean overwrite) throws IOException { if (destino.exists() && !overwrite) { System.err.println(destino.getName() + " já existe, ignorando..."); return; } else { String stringPath = destino.getParent() + File.separator; File path = new File(stringPath); if (!path.exists()) { path.mkdirs(); } if (path.isFile()) { try { destino.createNewFile(); } catch (Exception e) { e.printStackTrace(); } } } FileInputStream fisOrigem = new FileInputStream(origem); FileOutputStream fisDestino = new FileOutputStream(destino); FileChannel fcOrigem = fisOrigem.getChannel(); FileChannel fcDestino = fisDestino.getChannel(); fcOrigem.transferTo(0, fcOrigem.size(), fcDestino); fisOrigem.close(); fisDestino.close(); } /** * Delete dir. * * @param dir * the dir * @return true, if successful */ public static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } return dir.delete(); } /** * Generate file name. * * @param extension * the extension * @return the string */ public static String generateFileName(String extension) { Calendar c = new GregorianCalendar(); String name = "BCKP-" + c.get(Calendar.DATE) + c.get(Calendar.MONTH) + c.get(Calendar.YEAR) + +c.get(Calendar.HOUR) + c.get(Calendar.MILLISECOND); return name + "." + extension; } /** * Gets the files folder. * * @param path * the path * @return the files folder */ public static File[] getFilesFolder(String path) { File file = new File(path); return file.listFiles(); } /** * Gets the folder size. * * @param path * the path * @return the folder size */ public static int getFolderSize(String path) { File folder = new File(path); int size = 0; if (folder.isDirectory()) { String[] dirList = folder.list(); if (dirList != null) { for (int i = 0; i < dirList.length; i++) { String fileName = dirList[i]; File f = new File(path, fileName); if (f.isDirectory()) { String filePath = f.getPath(); size += getFolderSize(filePath); continue; } size += f.length(); } } } return size; } /** * Gets the path files folder. * * @param file the file * @return the path files folder */ public static ArrayList<String> getPathFilesFolder(File file) { ArrayList<String> list = new ArrayList<String>(); for (int i = 0; i < file.listFiles().length; i++) { list.add(file.listFiles()[i].getAbsolutePath()); } return list; } /** * Make backup. * * @param targetPath the target path * @param pathToBackup the path to backup * @param refName the ref name * @throws IOException Signals that an I/O exception has occurred. */ public static void makeBackup(String targetPath, String pathToBackup, String refName) throws IOException { File fileTarget = new File(targetPath + File.separator + refName + "-" + generateFileName("zip")); File fileToBackup = new File(pathToBackup); if (!fileTarget.exists()) { fileTarget.createNewFile(); } ZipUtils.zip(fileToBackup, fileTarget); } /** * Verify folder. * * @param files * the files */ public static void verifyFolder(File[] files) { System.out.println("Deletando conteudo que nao faz parte do deploy..."); for (File file : files) { if (!file.getAbsolutePath().contains(".war")) { System.out.println("Deletando " + file.getAbsolutePath()); if (file.delete()) { System.out.println("Arquivo deletado com sucesso."); } else { System.out.println("Arquivo n�o delatado..."); } } } System.out.println("Fim do processo de verifica��o do diretorio"); } }
apache-2.0
trasa/aws-sdk-java
aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/DescribeRaidArraysRequest.java
9998
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.opsworks.model; import java.io.Serializable; import com.amazonaws.AmazonWebServiceRequest; /** * */ public class DescribeRaidArraysRequest extends AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The instance ID. If you use this parameter, * <code>DescribeRaidArrays</code> returns descriptions of the RAID arrays * associated with the specified instance. * </p> */ private String instanceId; /** * <p> * The stack ID. * </p> */ private String stackId; /** * <p> * An array of RAID array IDs. If you use this parameter, * <code>DescribeRaidArrays</code> returns descriptions of the specified * arrays. Otherwise, it returns a description of every array. * </p> */ private com.amazonaws.internal.SdkInternalList<String> raidArrayIds; /** * <p> * The instance ID. If you use this parameter, * <code>DescribeRaidArrays</code> returns descriptions of the RAID arrays * associated with the specified instance. * </p> * * @param instanceId * The instance ID. If you use this parameter, * <code>DescribeRaidArrays</code> returns descriptions of the RAID * arrays associated with the specified instance. */ public void setInstanceId(String instanceId) { this.instanceId = instanceId; } /** * <p> * The instance ID. If you use this parameter, * <code>DescribeRaidArrays</code> returns descriptions of the RAID arrays * associated with the specified instance. * </p> * * @return The instance ID. If you use this parameter, * <code>DescribeRaidArrays</code> returns descriptions of the RAID * arrays associated with the specified instance. */ public String getInstanceId() { return this.instanceId; } /** * <p> * The instance ID. If you use this parameter, * <code>DescribeRaidArrays</code> returns descriptions of the RAID arrays * associated with the specified instance. * </p> * * @param instanceId * The instance ID. If you use this parameter, * <code>DescribeRaidArrays</code> returns descriptions of the RAID * arrays associated with the specified instance. * @return Returns a reference to this object so that method calls can be * chained together. */ public DescribeRaidArraysRequest withInstanceId(String instanceId) { setInstanceId(instanceId); return this; } /** * <p> * The stack ID. * </p> * * @param stackId * The stack ID. */ public void setStackId(String stackId) { this.stackId = stackId; } /** * <p> * The stack ID. * </p> * * @return The stack ID. */ public String getStackId() { return this.stackId; } /** * <p> * The stack ID. * </p> * * @param stackId * The stack ID. * @return Returns a reference to this object so that method calls can be * chained together. */ public DescribeRaidArraysRequest withStackId(String stackId) { setStackId(stackId); return this; } /** * <p> * An array of RAID array IDs. If you use this parameter, * <code>DescribeRaidArrays</code> returns descriptions of the specified * arrays. Otherwise, it returns a description of every array. * </p> * * @return An array of RAID array IDs. If you use this parameter, * <code>DescribeRaidArrays</code> returns descriptions of the * specified arrays. Otherwise, it returns a description of every * array. */ public java.util.List<String> getRaidArrayIds() { if (raidArrayIds == null) { raidArrayIds = new com.amazonaws.internal.SdkInternalList<String>(); } return raidArrayIds; } /** * <p> * An array of RAID array IDs. If you use this parameter, * <code>DescribeRaidArrays</code> returns descriptions of the specified * arrays. Otherwise, it returns a description of every array. * </p> * * @param raidArrayIds * An array of RAID array IDs. If you use this parameter, * <code>DescribeRaidArrays</code> returns descriptions of the * specified arrays. Otherwise, it returns a description of every * array. */ public void setRaidArrayIds(java.util.Collection<String> raidArrayIds) { if (raidArrayIds == null) { this.raidArrayIds = null; return; } this.raidArrayIds = new com.amazonaws.internal.SdkInternalList<String>( raidArrayIds); } /** * <p> * An array of RAID array IDs. If you use this parameter, * <code>DescribeRaidArrays</code> returns descriptions of the specified * arrays. Otherwise, it returns a description of every array. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if * any). Use {@link #setRaidArrayIds(java.util.Collection)} or * {@link #withRaidArrayIds(java.util.Collection)} if you want to override * the existing values. * </p> * * @param raidArrayIds * An array of RAID array IDs. If you use this parameter, * <code>DescribeRaidArrays</code> returns descriptions of the * specified arrays. Otherwise, it returns a description of every * array. * @return Returns a reference to this object so that method calls can be * chained together. */ public DescribeRaidArraysRequest withRaidArrayIds(String... raidArrayIds) { if (this.raidArrayIds == null) { setRaidArrayIds(new com.amazonaws.internal.SdkInternalList<String>( raidArrayIds.length)); } for (String ele : raidArrayIds) { this.raidArrayIds.add(ele); } return this; } /** * <p> * An array of RAID array IDs. If you use this parameter, * <code>DescribeRaidArrays</code> returns descriptions of the specified * arrays. Otherwise, it returns a description of every array. * </p> * * @param raidArrayIds * An array of RAID array IDs. If you use this parameter, * <code>DescribeRaidArrays</code> returns descriptions of the * specified arrays. Otherwise, it returns a description of every * array. * @return Returns a reference to this object so that method calls can be * chained together. */ public DescribeRaidArraysRequest withRaidArrayIds( java.util.Collection<String> raidArrayIds) { setRaidArrayIds(raidArrayIds); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getInstanceId() != null) sb.append("InstanceId: " + getInstanceId() + ","); if (getStackId() != null) sb.append("StackId: " + getStackId() + ","); if (getRaidArrayIds() != null) sb.append("RaidArrayIds: " + getRaidArrayIds()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeRaidArraysRequest == false) return false; DescribeRaidArraysRequest other = (DescribeRaidArraysRequest) obj; if (other.getInstanceId() == null ^ this.getInstanceId() == null) return false; if (other.getInstanceId() != null && other.getInstanceId().equals(this.getInstanceId()) == false) return false; if (other.getStackId() == null ^ this.getStackId() == null) return false; if (other.getStackId() != null && other.getStackId().equals(this.getStackId()) == false) return false; if (other.getRaidArrayIds() == null ^ this.getRaidArrayIds() == null) return false; if (other.getRaidArrayIds() != null && other.getRaidArrayIds().equals(this.getRaidArrayIds()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getInstanceId() == null) ? 0 : getInstanceId().hashCode()); hashCode = prime * hashCode + ((getStackId() == null) ? 0 : getStackId().hashCode()); hashCode = prime * hashCode + ((getRaidArrayIds() == null) ? 0 : getRaidArrayIds() .hashCode()); return hashCode; } @Override public DescribeRaidArraysRequest clone() { return (DescribeRaidArraysRequest) super.clone(); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-mobile/src/main/java/com/amazonaws/services/mobile/model/UpdateProjectRequest.java
7802
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.mobile.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * <p> * Request structure used for requests to update project configuration. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/mobile-2017-07-01/UpdateProject" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateProjectRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * ZIP or YAML file which contains project configuration to be updated. This should be the contents of the file * downloaded from the URL provided in an export project operation. * </p> */ private java.nio.ByteBuffer contents; /** * <p> * Unique project identifier. * </p> */ private String projectId; /** * <p> * ZIP or YAML file which contains project configuration to be updated. This should be the contents of the file * downloaded from the URL provided in an export project operation. * </p> * <p> * The AWS SDK for Java performs a Base64 encoding on this field before sending this request to the AWS service. * Users of the SDK should not perform Base64 encoding on this field. * </p> * <p> * Warning: ByteBuffers returned by the SDK are mutable. Changes to the content or position of the byte buffer will * be seen by all objects that have a reference to this object. It is recommended to call ByteBuffer.duplicate() or * ByteBuffer.asReadOnlyBuffer() before using or reading from the buffer. This behavior will be changed in a future * major version of the SDK. * </p> * * @param contents * ZIP or YAML file which contains project configuration to be updated. This should be the contents of the * file downloaded from the URL provided in an export project operation. */ public void setContents(java.nio.ByteBuffer contents) { this.contents = contents; } /** * <p> * ZIP or YAML file which contains project configuration to be updated. This should be the contents of the file * downloaded from the URL provided in an export project operation. * </p> * <p> * {@code ByteBuffer}s are stateful. Calling their {@code get} methods changes their {@code position}. We recommend * using {@link java.nio.ByteBuffer#asReadOnlyBuffer()} to create a read-only view of the buffer with an independent * {@code position}, and calling {@code get} methods on this rather than directly on the returned {@code ByteBuffer}. * Doing so will ensure that anyone else using the {@code ByteBuffer} will not be affected by changes to the * {@code position}. * </p> * * @return ZIP or YAML file which contains project configuration to be updated. This should be the contents of the * file downloaded from the URL provided in an export project operation. */ public java.nio.ByteBuffer getContents() { return this.contents; } /** * <p> * ZIP or YAML file which contains project configuration to be updated. This should be the contents of the file * downloaded from the URL provided in an export project operation. * </p> * <p> * The AWS SDK for Java performs a Base64 encoding on this field before sending this request to the AWS service. * Users of the SDK should not perform Base64 encoding on this field. * </p> * <p> * Warning: ByteBuffers returned by the SDK are mutable. Changes to the content or position of the byte buffer will * be seen by all objects that have a reference to this object. It is recommended to call ByteBuffer.duplicate() or * ByteBuffer.asReadOnlyBuffer() before using or reading from the buffer. This behavior will be changed in a future * major version of the SDK. * </p> * * @param contents * ZIP or YAML file which contains project configuration to be updated. This should be the contents of the * file downloaded from the URL provided in an export project operation. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateProjectRequest withContents(java.nio.ByteBuffer contents) { setContents(contents); return this; } /** * <p> * Unique project identifier. * </p> * * @param projectId * Unique project identifier. */ public void setProjectId(String projectId) { this.projectId = projectId; } /** * <p> * Unique project identifier. * </p> * * @return Unique project identifier. */ public String getProjectId() { return this.projectId; } /** * <p> * Unique project identifier. * </p> * * @param projectId * Unique project identifier. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateProjectRequest withProjectId(String projectId) { setProjectId(projectId); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getContents() != null) sb.append("Contents: ").append(getContents()).append(","); if (getProjectId() != null) sb.append("ProjectId: ").append(getProjectId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UpdateProjectRequest == false) return false; UpdateProjectRequest other = (UpdateProjectRequest) obj; if (other.getContents() == null ^ this.getContents() == null) return false; if (other.getContents() != null && other.getContents().equals(this.getContents()) == false) return false; if (other.getProjectId() == null ^ this.getProjectId() == null) return false; if (other.getProjectId() != null && other.getProjectId().equals(this.getProjectId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getContents() == null) ? 0 : getContents().hashCode()); hashCode = prime * hashCode + ((getProjectId() == null) ? 0 : getProjectId().hashCode()); return hashCode; } @Override public UpdateProjectRequest clone() { return (UpdateProjectRequest) super.clone(); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-stepfunctions/src/test/java/com/amazonaws/services/stepfunctions/builder/ChoiceStateTest.java
979
/* * Copyright 2011-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.stepfunctions.builder; import com.amazonaws.SdkClientException; import org.junit.Test; public class ChoiceStateTest { @Test(expected = SdkClientException.class) public void choiceStateWithMissingCondition_ThrowsExceptionOnDeserialize() { StateMachine.fromJson(TestResourceLoader.loadAsString("ChoiceStateWithMissingCondition.json")); } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-lambda/src/main/java/com/amazonaws/services/lambda/model/transform/LayerMarshaller.java
2130
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.lambda.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.lambda.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * LayerMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class LayerMarshaller { private static final MarshallingInfo<String> ARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Arn").build(); private static final MarshallingInfo<Long> CODESIZE_BINDING = MarshallingInfo.builder(MarshallingType.LONG).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("CodeSize").build(); private static final LayerMarshaller instance = new LayerMarshaller(); public static LayerMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(Layer layer, ProtocolMarshaller protocolMarshaller) { if (layer == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(layer.getArn(), ARN_BINDING); protocolMarshaller.marshall(layer.getCodeSize(), CODESIZE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
fhanik/spring-security
ldap/src/integration-test/java/org/springframework/security/ldap/authentication/BindAuthenticatorTests.java
6263
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.ldap.authentication; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ldap.core.DirContextOperations; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.SpringSecurityMessageSource; import org.springframework.security.ldap.ApacheDsContainerConfig; import org.springframework.security.ldap.DefaultSpringSecurityContextSource; import org.springframework.security.ldap.search.FilterBasedLdapUserSearch; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link BindAuthenticator}. * * @author Luke Taylor * @author Eddú Meléndez */ @RunWith(SpringRunner.class) @ContextConfiguration(classes = ApacheDsContainerConfig.class) public class BindAuthenticatorTests { @Autowired private DefaultSpringSecurityContextSource contextSource; private BindAuthenticator authenticator; private Authentication bob; @Before public void setUp() { this.authenticator = new BindAuthenticator(this.contextSource); this.authenticator.setMessageSource(new SpringSecurityMessageSource()); this.bob = new UsernamePasswordAuthenticationToken("bob", "bobspassword"); } @Test public void emptyPasswordIsRejected() { assertThatExceptionOfType(BadCredentialsException.class) .isThrownBy(() -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("jen", ""))); } @Test public void testAuthenticationWithCorrectPasswordSucceeds() { this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people", "cn={0},ou=people" }); DirContextOperations user = this.authenticator.authenticate(this.bob); assertThat(user.getStringAttribute("uid")).isEqualTo("bob"); this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("mouse, jerry", "jerryspassword")); } @Test public void testAuthenticationWithInvalidUserNameFails() { this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" }); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.authenticator .authenticate(new UsernamePasswordAuthenticationToken("nonexistentsuser", "password"))); } @Test public void testAuthenticationWithUserSearch() throws Exception { // DirContextAdapter ctx = new DirContextAdapter(new // DistinguishedName("uid=bob,ou=people")); this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("ou=people", "(uid={0})", this.contextSource)); this.authenticator.afterPropertiesSet(); DirContextOperations result = this.authenticator.authenticate(this.bob); // ensure we are getting the same attributes back assertThat(result.getStringAttribute("cn")).isEqualTo("Bob Hamilton"); // SEC-1444 this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("ou=people", "(cn={0})", this.contextSource)); this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("mouse, jerry", "jerryspassword")); this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("slash/guy", "slashguyspassword")); // SEC-1661 this.authenticator.setUserSearch( new FilterBasedLdapUserSearch("ou=\\\"quoted people\\\"", "(cn={0})", this.contextSource)); this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("quote\"guy", "quoteguyspassword")); this.authenticator.setUserSearch(new FilterBasedLdapUserSearch("", "(cn={0})", this.contextSource)); this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("quote\"guy", "quoteguyspassword")); } /* * @Test public void messingWithEscapedChars() throws Exception { * Hashtable<String,String> env = new Hashtable<>(); * env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); * env.put(Context.PROVIDER_URL, "ldap://127.0.0.1:22389/dc=springsource,dc=com"); * env.put(Context.SECURITY_AUTHENTICATION, "simple"); * env.put(Context.SECURITY_PRINCIPAL, "cn=admin,dc=springsource,dc=com"); * env.put(Context.SECURITY_CREDENTIALS, "password"); * * InitialDirContext idc = new InitialDirContext(env); SearchControls searchControls = * new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); * DistinguishedName baseDn = new DistinguishedName("ou=\\\"quoted people\\\""); * NamingEnumeration<SearchResult> matches = idc.search(baseDn, "(cn=*)", new Object[] * {"quoteguy"}, searchControls); * * while(matches.hasMore()) { SearchResult match = matches.next(); DistinguishedName * dn = new DistinguishedName(match.getName()); System.out.println("**** Match: " + * match.getName() + " ***** " + dn); * * } } */ @Test public void testAuthenticationWithWrongPasswordFails() { this.authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" }); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy( () -> this.authenticator.authenticate(new UsernamePasswordAuthenticationToken("bob", "wrongpassword"))); } @Test public void testUserDnPatternReturnsCorrectDn() { this.authenticator.setUserDnPatterns(new String[] { "cn={0},ou=people" }); assertThat(this.authenticator.getUserDns("Joe").get(0)).isEqualTo("cn=Joe,ou=people"); } }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-gamelift/src/main/java/com/amazonaws/services/gamelift/model/CreatePlayerSessionsRequest.java
10833
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.gamelift.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * <p> * Represents the input for a request action. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/gamelift-2015-10-01/CreatePlayerSessions" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreatePlayerSessionsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * Unique identifier for the game session to add players to. * </p> */ private String gameSessionId; /** * <p> * List of unique identifiers for the players to be added. * </p> */ private java.util.List<String> playerIds; /** * <p> * Map of string pairs, each specifying a player ID and a set of developer-defined information related to the * player. Amazon GameLift does not use this data, so it can be formatted as needed for use in the game. Player data * strings for player IDs not included in the <code>PlayerIds</code> parameter are ignored. * </p> */ private java.util.Map<String, String> playerDataMap; /** * <p> * Unique identifier for the game session to add players to. * </p> * * @param gameSessionId * Unique identifier for the game session to add players to. */ public void setGameSessionId(String gameSessionId) { this.gameSessionId = gameSessionId; } /** * <p> * Unique identifier for the game session to add players to. * </p> * * @return Unique identifier for the game session to add players to. */ public String getGameSessionId() { return this.gameSessionId; } /** * <p> * Unique identifier for the game session to add players to. * </p> * * @param gameSessionId * Unique identifier for the game session to add players to. * @return Returns a reference to this object so that method calls can be chained together. */ public CreatePlayerSessionsRequest withGameSessionId(String gameSessionId) { setGameSessionId(gameSessionId); return this; } /** * <p> * List of unique identifiers for the players to be added. * </p> * * @return List of unique identifiers for the players to be added. */ public java.util.List<String> getPlayerIds() { return playerIds; } /** * <p> * List of unique identifiers for the players to be added. * </p> * * @param playerIds * List of unique identifiers for the players to be added. */ public void setPlayerIds(java.util.Collection<String> playerIds) { if (playerIds == null) { this.playerIds = null; return; } this.playerIds = new java.util.ArrayList<String>(playerIds); } /** * <p> * List of unique identifiers for the players to be added. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setPlayerIds(java.util.Collection)} or {@link #withPlayerIds(java.util.Collection)} if you want to * override the existing values. * </p> * * @param playerIds * List of unique identifiers for the players to be added. * @return Returns a reference to this object so that method calls can be chained together. */ public CreatePlayerSessionsRequest withPlayerIds(String... playerIds) { if (this.playerIds == null) { setPlayerIds(new java.util.ArrayList<String>(playerIds.length)); } for (String ele : playerIds) { this.playerIds.add(ele); } return this; } /** * <p> * List of unique identifiers for the players to be added. * </p> * * @param playerIds * List of unique identifiers for the players to be added. * @return Returns a reference to this object so that method calls can be chained together. */ public CreatePlayerSessionsRequest withPlayerIds(java.util.Collection<String> playerIds) { setPlayerIds(playerIds); return this; } /** * <p> * Map of string pairs, each specifying a player ID and a set of developer-defined information related to the * player. Amazon GameLift does not use this data, so it can be formatted as needed for use in the game. Player data * strings for player IDs not included in the <code>PlayerIds</code> parameter are ignored. * </p> * * @return Map of string pairs, each specifying a player ID and a set of developer-defined information related to * the player. Amazon GameLift does not use this data, so it can be formatted as needed for use in the game. * Player data strings for player IDs not included in the <code>PlayerIds</code> parameter are ignored. */ public java.util.Map<String, String> getPlayerDataMap() { return playerDataMap; } /** * <p> * Map of string pairs, each specifying a player ID and a set of developer-defined information related to the * player. Amazon GameLift does not use this data, so it can be formatted as needed for use in the game. Player data * strings for player IDs not included in the <code>PlayerIds</code> parameter are ignored. * </p> * * @param playerDataMap * Map of string pairs, each specifying a player ID and a set of developer-defined information related to the * player. Amazon GameLift does not use this data, so it can be formatted as needed for use in the game. * Player data strings for player IDs not included in the <code>PlayerIds</code> parameter are ignored. */ public void setPlayerDataMap(java.util.Map<String, String> playerDataMap) { this.playerDataMap = playerDataMap; } /** * <p> * Map of string pairs, each specifying a player ID and a set of developer-defined information related to the * player. Amazon GameLift does not use this data, so it can be formatted as needed for use in the game. Player data * strings for player IDs not included in the <code>PlayerIds</code> parameter are ignored. * </p> * * @param playerDataMap * Map of string pairs, each specifying a player ID and a set of developer-defined information related to the * player. Amazon GameLift does not use this data, so it can be formatted as needed for use in the game. * Player data strings for player IDs not included in the <code>PlayerIds</code> parameter are ignored. * @return Returns a reference to this object so that method calls can be chained together. */ public CreatePlayerSessionsRequest withPlayerDataMap(java.util.Map<String, String> playerDataMap) { setPlayerDataMap(playerDataMap); return this; } public CreatePlayerSessionsRequest addPlayerDataMapEntry(String key, String value) { if (null == this.playerDataMap) { this.playerDataMap = new java.util.HashMap<String, String>(); } if (this.playerDataMap.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.playerDataMap.put(key, value); return this; } /** * Removes all the entries added into PlayerDataMap. * * @return Returns a reference to this object so that method calls can be chained together. */ public CreatePlayerSessionsRequest clearPlayerDataMapEntries() { this.playerDataMap = null; return this; } /** * Returns a string representation of this object; useful for testing and debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getGameSessionId() != null) sb.append("GameSessionId: ").append(getGameSessionId()).append(","); if (getPlayerIds() != null) sb.append("PlayerIds: ").append(getPlayerIds()).append(","); if (getPlayerDataMap() != null) sb.append("PlayerDataMap: ").append(getPlayerDataMap()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreatePlayerSessionsRequest == false) return false; CreatePlayerSessionsRequest other = (CreatePlayerSessionsRequest) obj; if (other.getGameSessionId() == null ^ this.getGameSessionId() == null) return false; if (other.getGameSessionId() != null && other.getGameSessionId().equals(this.getGameSessionId()) == false) return false; if (other.getPlayerIds() == null ^ this.getPlayerIds() == null) return false; if (other.getPlayerIds() != null && other.getPlayerIds().equals(this.getPlayerIds()) == false) return false; if (other.getPlayerDataMap() == null ^ this.getPlayerDataMap() == null) return false; if (other.getPlayerDataMap() != null && other.getPlayerDataMap().equals(this.getPlayerDataMap()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getGameSessionId() == null) ? 0 : getGameSessionId().hashCode()); hashCode = prime * hashCode + ((getPlayerIds() == null) ? 0 : getPlayerIds().hashCode()); hashCode = prime * hashCode + ((getPlayerDataMap() == null) ? 0 : getPlayerDataMap().hashCode()); return hashCode; } @Override public CreatePlayerSessionsRequest clone() { return (CreatePlayerSessionsRequest) super.clone(); } }
apache-2.0
Chasego/kafka
clients/src/test/java/org/apache/kafka/clients/consumer/internals/ConsumerMetadataTest.java
8039
/* * 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.kafka.clients.consumer.internals; import org.apache.kafka.clients.consumer.OffsetResetStrategy; import org.apache.kafka.common.Node; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.internals.ClusterResourceListeners; import org.apache.kafka.common.protocol.Errors; import org.apache.kafka.common.requests.MetadataRequest; import org.apache.kafka.common.requests.MetadataResponse; import org.apache.kafka.common.requests.RequestTestUtils; import org.apache.kafka.common.utils.LogContext; import org.apache.kafka.common.utils.MockTime; import org.apache.kafka.common.utils.Time; import org.apache.kafka.common.utils.Utils; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class ConsumerMetadataTest { private final Node node = new Node(1, "localhost", 9092); private final SubscriptionState subscription = new SubscriptionState(new LogContext(), OffsetResetStrategy.EARLIEST); private final Time time = new MockTime(); @Test public void testPatternSubscriptionNoInternalTopics() { testPatternSubscription(false); } @Test public void testPatternSubscriptionIncludeInternalTopics() { testPatternSubscription(true); } private void testPatternSubscription(boolean includeInternalTopics) { subscription.subscribe(Pattern.compile("__.*"), new NoOpConsumerRebalanceListener()); ConsumerMetadata metadata = newConsumerMetadata(includeInternalTopics); MetadataRequest.Builder builder = metadata.newMetadataRequestBuilder(); assertTrue(builder.isAllTopics()); List<MetadataResponse.TopicMetadata> topics = new ArrayList<>(); topics.add(topicMetadata("__consumer_offsets", true)); topics.add(topicMetadata("__matching_topic", false)); topics.add(topicMetadata("non_matching_topic", false)); MetadataResponse response = RequestTestUtils.metadataResponse(singletonList(node), "clusterId", node.id(), topics); metadata.updateWithCurrentRequestVersion(response, false, time.milliseconds()); if (includeInternalTopics) assertEquals(Utils.mkSet("__matching_topic", "__consumer_offsets"), metadata.fetch().topics()); else assertEquals(Collections.singleton("__matching_topic"), metadata.fetch().topics()); } @Test public void testUserAssignment() { subscription.assignFromUser(Utils.mkSet( new TopicPartition("foo", 0), new TopicPartition("bar", 0), new TopicPartition("__consumer_offsets", 0))); testBasicSubscription(Utils.mkSet("foo", "bar"), Utils.mkSet("__consumer_offsets")); subscription.assignFromUser(Utils.mkSet( new TopicPartition("baz", 0), new TopicPartition("__consumer_offsets", 0))); testBasicSubscription(Utils.mkSet("baz"), Utils.mkSet("__consumer_offsets")); } @Test public void testNormalSubscription() { subscription.subscribe(Utils.mkSet("foo", "bar", "__consumer_offsets"), new NoOpConsumerRebalanceListener()); subscription.groupSubscribe(Utils.mkSet("baz", "foo", "bar", "__consumer_offsets")); testBasicSubscription(Utils.mkSet("foo", "bar", "baz"), Utils.mkSet("__consumer_offsets")); subscription.resetGroupSubscription(); testBasicSubscription(Utils.mkSet("foo", "bar"), Utils.mkSet("__consumer_offsets")); } @Test public void testTransientTopics() { subscription.subscribe(singleton("foo"), new NoOpConsumerRebalanceListener()); ConsumerMetadata metadata = newConsumerMetadata(false); metadata.updateWithCurrentRequestVersion(RequestTestUtils.metadataUpdateWith(1, singletonMap("foo", 1)), false, time.milliseconds()); assertFalse(metadata.updateRequested()); metadata.addTransientTopics(singleton("foo")); assertFalse(metadata.updateRequested()); metadata.addTransientTopics(singleton("bar")); assertTrue(metadata.updateRequested()); Map<String, Integer> topicPartitionCounts = new HashMap<>(); topicPartitionCounts.put("foo", 1); topicPartitionCounts.put("bar", 1); metadata.updateWithCurrentRequestVersion(RequestTestUtils.metadataUpdateWith(1, topicPartitionCounts), false, time.milliseconds()); assertFalse(metadata.updateRequested()); assertEquals(Utils.mkSet("foo", "bar"), new HashSet<>(metadata.fetch().topics())); metadata.clearTransientTopics(); metadata.updateWithCurrentRequestVersion(RequestTestUtils.metadataUpdateWith(1, topicPartitionCounts), false, time.milliseconds()); assertEquals(singleton("foo"), new HashSet<>(metadata.fetch().topics())); } private void testBasicSubscription(Set<String> expectedTopics, Set<String> expectedInternalTopics) { Set<String> allTopics = new HashSet<>(); allTopics.addAll(expectedTopics); allTopics.addAll(expectedInternalTopics); ConsumerMetadata metadata = newConsumerMetadata(false); MetadataRequest.Builder builder = metadata.newMetadataRequestBuilder(); assertEquals(allTopics, new HashSet<>(builder.topics())); List<MetadataResponse.TopicMetadata> topics = new ArrayList<>(); for (String expectedTopic : expectedTopics) topics.add(topicMetadata(expectedTopic, false)); for (String expectedInternalTopic : expectedInternalTopics) topics.add(topicMetadata(expectedInternalTopic, true)); MetadataResponse response = RequestTestUtils.metadataResponse(singletonList(node), "clusterId", node.id(), topics); metadata.updateWithCurrentRequestVersion(response, false, time.milliseconds()); assertEquals(allTopics, metadata.fetch().topics()); } private MetadataResponse.TopicMetadata topicMetadata(String topic, boolean isInternal) { MetadataResponse.PartitionMetadata partitionMetadata = new MetadataResponse.PartitionMetadata(Errors.NONE, new TopicPartition(topic, 0), Optional.of(node.id()), Optional.of(5), singletonList(node.id()), singletonList(node.id()), singletonList(node.id())); return new MetadataResponse.TopicMetadata(Errors.NONE, topic, isInternal, singletonList(partitionMetadata)); } private ConsumerMetadata newConsumerMetadata(boolean includeInternalTopics) { long refreshBackoffMs = 50; long expireMs = 50000; return new ConsumerMetadata(refreshBackoffMs, expireMs, includeInternalTopics, false, subscription, new LogContext(), new ClusterResourceListeners()); } }
apache-2.0
smanvi-pivotal/geode
geode-core/src/main/java/org/apache/geode/internal/admin/remote/VersionInfoRequest.java
2101
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.admin.remote; import java.io.*; import org.apache.geode.distributed.internal.*; import org.apache.geode.internal.i18n.LocalizedStrings; /** * A message that is sent to a particular distribution manager to get its current version info. * * @since GemFire 3.5 */ public class VersionInfoRequest extends AdminRequest { /** * Returns a <code>VersionInfoRequest</code>. */ public static VersionInfoRequest create() { VersionInfoRequest m = new VersionInfoRequest(); return m; } public VersionInfoRequest() { friendlyName = LocalizedStrings.VersionInfoRequest_FETCH_CURRENT_VERSION_INFORMATION.toLocalizedString(); } /** * Must return a proper response to this request. * * @param dm */ @Override protected AdminResponse createResponse(DistributionManager dm) { return VersionInfoResponse.create(dm, this.getSender()); } public int getDSFID() { return VERSION_INFO_REQUEST; } @Override public void toData(DataOutput out) throws IOException { super.toData(out); } @Override public void fromData(DataInput in) throws IOException, ClassNotFoundException { super.fromData(in); } @Override public String toString() { return "VersionInfoRequest from " + this.getSender(); } }
apache-2.0
lonnyj/liquibase-spatial
src/test/java/liquibase/ext/spatial/change/CreateSpatialIndexChangeTest.java
3353
package liquibase.ext.spatial.change; import static org.testng.Assert.*; import liquibase.change.ColumnConfig; import liquibase.database.Database; import liquibase.database.core.H2Database; import liquibase.exception.ValidationErrors; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * <code>CreateSpatialIndexChangeTest</code> tests {@link CreateSpatialIndexChange}. */ public class CreateSpatialIndexChangeTest { /** * Tests {@link CreateSpatialIndexChange#validate(liquibase.database.Database)}. * * @param catalogName * the name of the catalog. * @param schemaName * the name of the schema. * @param tablespace * the name of the tablespace. * @param tableName * the name of the table. * @param columnName * the geometry column name. * @param indexName * the name of the spatial index. * @param geometryType * the geometry type. * @param srid * the Spatial Reference System ID. * @param database * the database instance. * @param passes * indicates if the test is expected to pass. */ @Test(dataProvider = "validateTestData") public void testValidate(final String catalogName, final String schemaName, final String tablespace, final String tableName, final String columnName, final String indexName, final String geometryType, final String srid, final Database database, final boolean passes) { final CreateSpatialIndexChange change = new CreateSpatialIndexChange(); change.setCatalogName(catalogName); change.setSchemaName(schemaName); change.setTablespace(tablespace); change.setTableName(tableName); final ColumnConfig column = new ColumnConfig(); column.setName(columnName); change.addColumn(column); change.setIndexName(indexName); change.setGeometryType(geometryType); change.setSrid(srid); final ValidationErrors errors = change.validate(database); assertEquals(errors.hasErrors(), !passes, "Errors were " + (passes ? " not" : "") + "expected"); } /** * Generates the test data for * {@link #testValidate(String, String, String, String, String, String, String, String, Database, boolean)} * . * * @return the test data. */ @DataProvider public Object[][] validateTestData() { final String cat = "mycatalog"; final String sch = "myschema"; final String ts = "mytablespace"; final String tab = "test_table"; final String col = "GEOM"; final String ind = "SPATIAL_INDEX"; final String geom = "POINT"; final String srid = "4326"; final H2Database h2 = new H2Database(); return new Object[][] { new Object[] { cat, sch, ts, tab, col, ind, geom, srid, h2, true }, new Object[] { cat, sch, ts, tab, col, ind, geom, null, h2, false }, new Object[] { cat, sch, ts, tab, col, ind, geom, "bad", h2, false }, new Object[] { cat, sch, ts, tab, col, ind, geom, "4326bad", h2, false }, new Object[] { cat, sch, ts, tab, col, ind, geom, "bad4326", h2, false }, new Object[] { cat, sch, ts, tab, col, ind, geom, "b4326ad", h2, false } }; } }
apache-2.0
mikevoxcap/spring4-sample
src/main/java/com/pluralsight/orderfulfillment/config/DataConfig.java
2623
package com.pluralsight.orderfulfillment.config; import java.util.*; import javax.inject.*; import javax.persistence.*; import javax.sql.*; import org.apache.commons.dbcp.*; import org.springframework.context.annotation.*; import org.springframework.core.env.*; import org.springframework.data.jpa.repository.config.*; import org.springframework.orm.hibernate4.*; import org.springframework.orm.jpa.*; import org.springframework.orm.jpa.vendor.*; import org.springframework.transaction.*; import org.springframework.transaction.annotation.*; /** * Data configuration for repositories. * * @author Michael Hoffman * */ @Configuration @EnableJpaRepositories(basePackages = { "com.pluralsight.orderfulfillment" }) @EnableTransactionManagement public class DataConfig { @Inject private Environment environment; @Bean public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(environment.getProperty("db.driver")); dataSource.setUrl(environment.getProperty("db.url")); dataSource.setUsername(environment.getProperty("db.user")); dataSource.setPassword(environment.getProperty("db.password")); return dataSource; } @Bean public EntityManagerFactory entityManagerFactory() { final HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter(); jpaVendorAdapter.setDatabasePlatform(environment.getProperty("hibernate.dialect")); jpaVendorAdapter.setShowSql(false); final Map<String, String> jpaProperties = new HashMap<String, String>(); jpaProperties.put("hibernate.jdbc.batch_size", environment.getProperty("hibernate.jdbc.batch_size")); jpaProperties.put("hibernate.default_schema", environment.getProperty("hibernate.default_schema")); LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setPackagesToScan("com.pluralsight.orderfulfillment"); factory.setJpaVendorAdapter(jpaVendorAdapter); factory.setDataSource(dataSource()); factory.setJpaPropertyMap(jpaProperties); factory.afterPropertiesSet(); return factory.getObject(); } @Bean public PlatformTransactionManager transactionManager() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory()); return transactionManager; } @Bean public HibernateExceptionTranslator hibernateExceptionTranslator() { return new HibernateExceptionTranslator(); } }
apache-2.0
cloudera-labs/envelope
core/src/test/java/com/cloudera/labs/envelope/run/TestBatchStep.java
5645
/* * Copyright (c) 2015-2019, Cloudera, Inc. All Rights Reserved. * * Cloudera, Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"). You may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This software 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.cloudera.labs.envelope.run; import com.cloudera.labs.envelope.component.ComponentFactory; import com.cloudera.labs.envelope.spark.Contexts; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.apache.spark.sql.AnalysisException; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.junit.Test; import java.util.Map; import static com.cloudera.labs.envelope.validate.ValidationAssert.assertValidationFailures; import static org.junit.Assert.assertEquals; public class TestBatchStep { @Test public void testInputRepartition() throws Exception { Map<String, Object> configMap = Maps.newHashMap(); configMap.put(DataStep.INPUT_TYPE + "." + ComponentFactory.TYPE_CONFIG_NAME, DummyInput.class.getName()); configMap.put(DataStep.INPUT_TYPE + "." + "starting.partitions", 5); configMap.put(BatchStep.REPARTITION_NUM_PARTITIONS_PROPERTY, 10); Config config = ConfigFactory.parseMap(configMap); BatchStep batchStep = new BatchStep("test"); batchStep.configure(config); batchStep.submit(Sets.<Step>newHashSet()); Dataset<Row> df = batchStep.getData(); int numPartitions = df.javaRDD().getNumPartitions(); assertEquals(numPartitions, 10); } @Test public void testInputRepartitionColumns() throws Exception { Map<String, Object> configMap = Maps.newHashMap(); configMap.put(DataStep.INPUT_TYPE + "." + ComponentFactory.TYPE_CONFIG_NAME, DummyInput.class.getName()); configMap.put(DataStep.INPUT_TYPE + "." + "starting.partitions", 10); configMap.put(BatchStep.REPARTITION_COLUMNS_PROPERTY, Lists.newArrayList("modulo")); Config config = ConfigFactory.parseMap(configMap); BatchStep batchStep = new BatchStep("test"); batchStep.configure(config); batchStep.submit(Sets.<Step>newHashSet()); Dataset<Row> df = batchStep.getData(); int numPartitions = df.javaRDD().getNumPartitions(); assertEquals(Contexts.getSparkSession().sqlContext().getConf("spark.sql.shuffle.partitions"), Integer.toString(numPartitions)); } @Test public void testInputRepartitionColumnsAndPartitionCount() throws Exception { Map<String, Object> configMap = Maps.newHashMap(); configMap.put(BatchStep.REPARTITION_COLUMNS_PROPERTY, Lists.newArrayList("modulo")); configMap.put(BatchStep.REPARTITION_NUM_PARTITIONS_PROPERTY, 5); configMap.put(DataStep.INPUT_TYPE + "." + ComponentFactory.TYPE_CONFIG_NAME, DummyInput.class.getName()); configMap.put(DataStep.INPUT_TYPE + "." + "starting.partitions", 10); Config config = ConfigFactory.parseMap(configMap); BatchStep batchStep = new BatchStep("test"); batchStep.configure(config); batchStep.submit(Sets.<Step>newHashSet()); Dataset<Row> df = batchStep.getData(); int numPartitions = df.javaRDD().getNumPartitions(); assertEquals(5, numPartitions); } @Test (expected = AnalysisException.class) public void testInputRepartitionInvalidColumn() throws Exception { Map<String, Object> configMap = Maps.newHashMap(); configMap.put(DataStep.INPUT_TYPE + "." + ComponentFactory.TYPE_CONFIG_NAME, DummyInput.class.getName()); configMap.put(DataStep.INPUT_TYPE + "." + "starting.partitions", 10); configMap.put(BatchStep.REPARTITION_COLUMNS_PROPERTY, Lists.newArrayList("modulo == 0")); configMap.put(BatchStep.REPARTITION_NUM_PARTITIONS_PROPERTY, 5); Config config = ConfigFactory.parseMap(configMap); BatchStep batchStep = new BatchStep("test"); batchStep.configure(config); batchStep.submit(Sets.<Step>newHashSet()); batchStep.getData(); } @Test public void testInputCoalesce() throws Exception { Map<String, Object> configMap = Maps.newHashMap(); configMap.put(DataStep.INPUT_TYPE + "." + ComponentFactory.TYPE_CONFIG_NAME, DummyInput.class.getName()); configMap.put(DataStep.INPUT_TYPE + "." + "starting.partitions", 10); configMap.put(BatchStep.COALESCE_NUM_PARTITIONS_PROPERTY, 5); Config config = ConfigFactory.parseMap(configMap); BatchStep batchStep = new BatchStep("test"); batchStep.configure(config); batchStep.submit(Sets.<Step>newHashSet()); Dataset<Row> df = batchStep.getData(); int numPartitions = df.javaRDD().getNumPartitions(); assertEquals(numPartitions, 5); } @Test public void testCantRepartitionAndCoalesceInputAtOnce() { Map<String, Object> configMap = Maps.newHashMap(); configMap.put(DataStep.INPUT_TYPE + "." + ComponentFactory.TYPE_CONFIG_NAME, DummyInput.class.getName()); configMap.put(DataStep.INPUT_TYPE + "." + "starting.partitions", 5); configMap.put(BatchStep.REPARTITION_NUM_PARTITIONS_PROPERTY, 10); configMap.put(BatchStep.COALESCE_NUM_PARTITIONS_PROPERTY, 3); Config config = ConfigFactory.parseMap(configMap); BatchStep batchStep = new BatchStep("test"); assertValidationFailures(batchStep, config); } }
apache-2.0
simplelifetian/GomeOnline
jrj-TouGu/src/com/gome/haoyuangong/fragments/MyOpinionPublishedFragment.java
12919
package com.gome.haoyuangong.fragments; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.text.TextUtils.TruncateAt; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout.LayoutParams; import com.gome.haoyuangong.R; import com.gome.haoyuangong.activity.AttentionDetailActivity; import com.gome.haoyuangong.activity.InvestOpinionActivity; import com.gome.haoyuangong.layout.self.Function; /** * 我的投资观点-已发布 * @author Administrator * */ public class MyOpinionPublishedFragment extends ListViewFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onStart() { // TODO Auto-generated method stub super.onStart(); addItems(); reFresh(); } /** * 测试数据 */ private void addItems(){ for(int i=0;i<10;i++){ OpinionItem opinionItem = new OpinionItem(getActivity()); opinionItem.setInvester("李家智"); opinionItem.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent aIntent = new Intent(getActivity(), AttentionDetailActivity.class); startActivity(aIntent); } }); // _items.add(opinionItem); addItem(opinionItem); } } private class OpinionItem extends LinearLayout { OpinionHead opinionHead; TextView titleView; TextView contentView; private ImageView contentPic; private ImageView leftCornerPic; public OpinionItem(Context context) { super(context); // TODO Auto-generated constructor stub this.setOrientation(VERTICAL); this.setBackgroundColor(context.getResources().getColor(R.color.background_ECECEC)); titleView = new TextView(context); titleView.setGravity(Gravity.CENTER_VERTICAL); titleView.setText("倒N现,考验真正来临!"); titleView.setTextColor(context.getResources().getColor(R.color.font_595959)); titleView.setTextSize(TypedValue.COMPLEX_UNIT_SP,Function.px2sp(context, 50)); contentView = new TextView(context); contentView.setGravity(Gravity.CENTER_VERTICAL); contentView.setText("周一大盘低开高走,大幅调整,三连阳反弹成果被吞噬一空,勉强收复的5日线、10日线和2300点关口再次失守!"); contentView.setTextColor(context.getResources().getColor(R.color.font_727272)); contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP,Function.px2sp(context, 50)); contentView.setMaxLines(3); contentView.setEllipsize(TruncateAt.END); contentPic = new ImageView(context); contentPic.setScaleType(ScaleType.FIT_START); contentPic.setBackgroundResource(R.drawable.icon111); leftCornerPic = new ImageView(context); leftCornerPic.setScaleType(ScaleType.FIT_START); leftCornerPic.setBackgroundResource(R.drawable.opinion_mi); doLayout(); } private void doLayout(){ RelativeLayout rLayout = new RelativeLayout(getContext()); LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT); p.setMargins(0, 0, 0, Function.getFitPx(getContext(), 40)); addView(rLayout,p); RelativeLayout.LayoutParams rp = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); LinearLayout layout = new LinearLayout(getContext()); layout.setBackgroundColor(Color.WHITE); layout.setOrientation(VERTICAL); // p.setMargins(0, 0, 0, Function.getFitPx(getContext(), 40)); rLayout.addView(layout,rp); opinionHead = new OpinionHead(getContext()); p = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,opinionHead.getItemHeight()); layout.addView(opinionHead,p); p = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT); p.setMargins(Function.getFitPx(getContext(), 160), Function.getFitPx(getContext(), 36), Function.getFitPx(getContext(), 40), 0); layout.addView(titleView,p); p = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT); p.setMargins(Function.getFitPx(getContext(), 160), Function.getFitPx(getContext(), 36), Function.getFitPx(getContext(), 40), 0); layout.addView(contentView,p); //内容图 int picH = Function.getFitPx(getContext(), 220); p = new LinearLayout.LayoutParams(picH,picH); p.setMargins(Function.getFitPx(getContext(), 160), Function.getFitPx(getContext(), 36), Function.getFitPx(getContext(), 40), Function.getFitPx(getContext(), 20)); layout.addView(contentPic,p); //左下角图片 picH = Function.getFitPx(getContext(), 114); rp = new RelativeLayout.LayoutParams(picH,picH); rp.addRule(RelativeLayout.ALIGN_PARENT_LEFT); rp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); rLayout.addView(leftCornerPic,rp); } public void setInvester(String invester) { opinionHead.setInvesterName(invester); } } private class OpinionHead extends RelativeLayout { private ImageView headPic; private TextView nameText; private TextView identityText; private TextView companyText; private TextView dateText; private int headHeight; public OpinionHead(Context context) { super(context); this.setBackgroundColor(Color.WHITE); headHeight = Function.getFitPx(context, 140); initComponent(context); doLayout(); // TODO Auto-generated constructor stub } private int getItemHeight(){ return headHeight; } private void initComponent(Context context){ headPic = new ImageView(context); headPic.setScaleType(ScaleType.FIT_START); headPic.setBackgroundResource(R.drawable.icon111); nameText = new TextView(context); nameText.setTextSize(TypedValue.COMPLEX_UNIT_SP,Function.px2sp(getContext(), 40)); nameText.setTextColor(context.getResources().getColor(R.color.font_4c86c6)); // nameText.setPadding(0, Function.getFitPx(context, 20), 0, 0); // nameText.setGravity(Gravity.CENTER_VERTICAL); identityText = new TextView(context); identityText.setText("投资顾问"); identityText.setTextSize(TypedValue.COMPLEX_UNIT_SP,Function.px2sp(getContext(), 36)); identityText.setTextColor(context.getResources().getColor(R.color.font_727272)); identityText.setGravity(Gravity.CENTER_VERTICAL|Gravity.BOTTOM); companyText = new TextView(context); companyText.setText("国信证券"); companyText.setGravity(Gravity.CENTER_VERTICAL|Gravity.BOTTOM); companyText.setTextSize(TypedValue.COMPLEX_UNIT_SP,Function.px2sp(getContext(), 36)); companyText.setTextColor(context.getResources().getColor(R.color.font_727272)); dateText = new TextView(context); dateText.setText("10-17 12:10"); dateText.setGravity(Gravity.BOTTOM|Gravity.RIGHT); dateText.setTextSize(TypedValue.COMPLEX_UNIT_SP,Function.px2sp(getContext(), 36)); dateText.setTextColor(context.getResources().getColor(R.color.font_b2b2b2)); } private void doLayout(){ this.removeAllViews(); LinearLayout.LayoutParams lp = null; RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); p.setMargins(Function.getFitPx(getContext(), 40), Function.getFitPx(getContext(), 40), 0, 0); RelativeLayout pLayout = new RelativeLayout(getContext()); pLayout.setBackgroundColor(getContext().getResources().getColor(R.color.divider)); addView(pLayout,p); p = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); RelativeLayout layout = new RelativeLayout(getContext()); layout.setBackgroundColor(Color.WHITE); pLayout.addView(layout,p); p = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); p.addRule(RelativeLayout.ALIGN_PARENT_LEFT); // p.addRule(RelativeLayout.LEFT_OF,divideLayout.getId()); RelativeLayout leftLayout = new RelativeLayout(getContext()); layout.addView(leftLayout,p); //头像 LinearLayout headLayout = new LinearLayout(getContext()); headLayout.setGravity(Gravity.CENTER); headLayout.setId(1003); int picH = Function.getFitPx(getContext(), 100); p = new RelativeLayout.LayoutParams(picH,LayoutParams.MATCH_PARENT); p.addRule(RelativeLayout.ALIGN_PARENT_LEFT); leftLayout.addView(headLayout,p); lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,picH); headLayout.addView(headPic,lp); //姓名 p = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, headHeight/2); p.addRule(RelativeLayout.ALIGN_PARENT_TOP); p.addRule(RelativeLayout.RIGHT_OF,headLayout.getId()); p.setMargins(Function.getFitPx(getContext(), 20), 0, 0, 0); LinearLayout nameLayout = new LinearLayout(getContext()); nameLayout.setId(1004); leftLayout.addView(nameLayout,p); lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT); nameLayout.addView(nameText,lp); //日期 p = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, headHeight/2); p.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); p.addRule(RelativeLayout.RIGHT_OF,nameLayout.getId()); p.setMargins(Function.getFitPx(getContext(), 20), 0, Function.getFitPx(getContext(), 40), 0); LinearLayout dateLayout = new LinearLayout(getContext()); dateLayout.setGravity(Gravity.RIGHT); leftLayout.addView(dateLayout,p); lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT); dateLayout.addView(dateText,lp); //身份及公司 p = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, headHeight/2); p.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); p.addRule(RelativeLayout.RIGHT_OF,headLayout.getId()); p.setMargins(Function.getFitPx(getContext(), 20), 0, 0, 0); LinearLayout identityLayout = new LinearLayout(getContext()); identityLayout.setOrientation(LinearLayout.HORIZONTAL); leftLayout.addView(identityLayout,p); lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.MATCH_PARENT); identityLayout.addView(identityText,lp); lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.MATCH_PARENT); lp.setMargins(Function.getFitPx(getContext(), 20), 0, 0, 0); identityLayout.addView(companyText,lp); } public void setInvesterName(String name){ nameText.setText(name); } } private class OpinionFoot extends LinearLayout { public OpinionFoot(Context context) { super(context); // TODO Auto-generated constructor stub this.setOrientation(HORIZONTAL); this.setBackgroundColor(context.getResources().getColor(R.color.divider)); doLayout(); } private void doLayout(){ LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,Function.getFitPx(getContext(), 150),1); OpinionFootItem item = new OpinionFootItem(getContext()); item.setTitle("分享"); item.setImageID(R.drawable.android_icon_share); p.setMargins(0, 0, 1, 0); addView(item,p); item = new OpinionFootItem(getContext()); item.setTitle("1022"); item.setImageID(R.drawable.icon_comment); p.setMargins(0, 0, 1, 0); addView(item,p); item = new OpinionFootItem(getContext()); item.setTitle("2300"); item.setImageID(R.drawable.icon_zan); addView(item,p); } } private class OpinionFootItem extends LinearLayout { ImageView image; TextView titleText; public OpinionFootItem(Context context) { super(context); // TODO Auto-generated constructor stub this.setOrientation(HORIZONTAL); this.setGravity(Gravity.CENTER); this.setBackgroundColor(Color.WHITE); image = new ImageView(context); image.setScaleType(ScaleType.CENTER_INSIDE); titleText = new TextView(context); titleText.setTextColor(context.getResources().getColor(R.color.font_4c86c6)); titleText.setTextSize(TypedValue.COMPLEX_UNIT_SP,Function.px2sp(context, 50)); titleText.setGravity(Gravity.CENTER_VERTICAL); doLayout(); } private void doLayout(){ int picH = Function.getFitPx(getContext(), 44); LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(picH, picH); addView(image,p); p = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.MATCH_PARENT); addView(titleText,p); } public void setImageID(int resid){ image.setImageDrawable(getContext().getResources().getDrawable(resid)); } public void setTitle(String title){ titleText.setText(title); } } }
apache-2.0
AmyStorm/omnia-web
omnia-web-facade/src/main/java/com/omnia/module/user/command/interceptor/LoginInterceptor.java
1748
package com.omnia.module.user.command.interceptor; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created by khaerothe on 2015/4/5. */ public class LoginInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle request invoke--------Login"); // Object session = request.getSession().getAttribute("login"); // if(session == null){ // return false; // }else{ return super.preHandle(request, response, handler); // } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle request invoke--------Login"); super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion request invoke--------Login"); super.afterCompletion(request, response, handler, ex); } @Override public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("afterConcurrentHandlingStarted request invoke--------Login"); super.afterConcurrentHandlingStarted(request, response, handler); } }
apache-2.0
juleswhite/churn
churn/src/test/java/org/magnum/churn/ChurnApplicationTests.java
777
package org.magnum.churn; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = ChurnApplication.class) @WebAppConfiguration public class ChurnApplicationTests { @Before public void setUp(){ //load data into ES for testing } @After public void tearDown(){ // delete loaded test data from ES } @Test public void contextLoads() { } // Fangzhou, create an integration test to prove that your // controller works. }
apache-2.0
saki4510t/libcommon
common/src/main/java/com/serenegiant/media/IAudioSampler.java
10903
package com.serenegiant.media; /* * libcommon * utility/helper classes for myself * * Copyright (c) 2014-2021 saki t_saki@serenegiant.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.nio.ByteBuffer; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.TimeUnit; import android.annotation.SuppressLint; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import android.util.Log; import com.serenegiant.system.BuildCheck; import com.serenegiant.system.Time; public abstract class IAudioSampler { // private static final boolean DEBUG = false; // FIXME 実働時はfalseにすること private final String TAG = getClass().getSimpleName(); public static final int AUDIO_SOURCE_UAC = 100; @IntDef({ MediaRecorder.AudioSource.DEFAULT, MediaRecorder.AudioSource.MIC, MediaRecorder.AudioSource.CAMCORDER, MediaRecorder.AudioSource.VOICE_RECOGNITION, MediaRecorder.AudioSource.VOICE_COMMUNICATION, AUDIO_SOURCE_UAC, }) @Retention(RetentionPolicy.SOURCE) public @interface AudioSource {} @SuppressLint("NewApi") public static AudioRecord createAudioRecord( final int source, final int sampling_rate, final int channels, final int format, final int buffer_size) { @AudioSource final int[] AUDIO_SOURCES = new int[] { MediaRecorder.AudioSource.DEFAULT, // ここ(1つ目)は引数で置き換えられる MediaRecorder.AudioSource.CAMCORDER, // これにするとUSBオーディオルーティングが有効な場合でも内蔵マイクからの音になる MediaRecorder.AudioSource.MIC, MediaRecorder.AudioSource.DEFAULT, MediaRecorder.AudioSource.VOICE_COMMUNICATION, MediaRecorder.AudioSource.VOICE_RECOGNITION, }; switch (source) { case 2: AUDIO_SOURCES[0] = MediaRecorder.AudioSource.CAMCORDER; break; // 内蔵マイク case 3: AUDIO_SOURCES[0] = MediaRecorder.AudioSource.VOICE_COMMUNICATION; break; case 1: default:AUDIO_SOURCES[0] = MediaRecorder.AudioSource.MIC; break; // 自動(UACのopenに失敗した時など) } AudioRecord audioRecord = null; for (final int src: AUDIO_SOURCES) { try { if (BuildCheck.isAndroid6()) { audioRecord = new AudioRecord.Builder() .setAudioSource(src) .setAudioFormat(new AudioFormat.Builder() .setEncoding(format) .setSampleRate(sampling_rate) .setChannelMask((channels == 1 ? AudioFormat.CHANNEL_IN_MONO : AudioFormat.CHANNEL_IN_STEREO)) .build()) .setBufferSizeInBytes(buffer_size) .build(); } else { audioRecord = new AudioRecord(src, sampling_rate, (channels == 1 ? AudioFormat.CHANNEL_IN_MONO : AudioFormat.CHANNEL_IN_STEREO), format, buffer_size); } if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) { audioRecord.release(); audioRecord = null; } } catch (final Exception e) { audioRecord = null; } if (audioRecord != null) break; } return audioRecord; } /** * 音声データ取得コールバックインターフェース */ public interface SoundSamplerCallback { /** * 音声データが準備出来た時に呼び出される。 * presentationTimeUsは音声データを取得した時の時刻だが、他のコールバックでの処理によっては * 遅延して呼び出される可能性がある。任意のスレッド上で実行される。 * 可能な限り早く処理を終えること。 * @param buffer * @param size * @param presentationTimeUs */ public void onData(@NonNull final ByteBuffer buffer, final int size, final long presentationTimeUs); /** * エラーが起こった時の処理(今は未使用) * @param e */ public void onError(Exception e); } /** * バッファリング用に生成する音声データレコードの最大生成する */ private static final int MAX_POOL_SIZE = 200; /** * 音声データキューに存在できる最大音声データレコード数 * 25フレーム/秒のはずなので最大で約4秒分 */ private static final int MAX_QUEUE_SIZE = 200; // 音声データキュー用 private final MemMediaQueue mAudioQueue; // コールバック用 private CallbackThread mCallbackThread; @NonNull private final Object mCallbackSync = new Object(); @NonNull private final Set<SoundSamplerCallback> mCallbacks = new CopyOnWriteArraySet<SoundSamplerCallback>(); protected volatile boolean mIsCapturing; public IAudioSampler() { mAudioQueue = new MemMediaQueue(MAX_POOL_SIZE, MAX_POOL_SIZE, MAX_QUEUE_SIZE); } /** * 音声データのサンプリングを停止して全てのコールバックを削除する */ public void release() { // if (DEBUG) Log.v(TAG, "release:mIsCapturing=" + mIsCapturing); if (isStarted()) { stop(); } // mIsCapturing = false; // 念の為に mCallbacks.clear(); // if (DEBUG) Log.v(TAG, "release:finished"); } /** * 音声サンプリング開始 */ public synchronized void start() { // if (DEBUG) Log.v(TAG, "start:"); // コールバック用スレッドを生成&実行 synchronized (mCallbackSync) { if (mCallbackThread == null) { mIsCapturing = true; mCallbackThread = new CallbackThread(); mCallbackThread.start(); } } // if (DEBUG) Log.v(TAG, "start:finished"); } /** * 音声サンプリング終了 */ public synchronized void stop() { // if (DEBUG) Log.v(TAG, "stop:"); // new Throwable().printStackTrace(); synchronized (mCallbackSync) { final boolean capturing = mIsCapturing; mIsCapturing = false; mCallbackThread = null; if (capturing) { try { mCallbackSync.wait(); } catch (InterruptedException e) { // ignore } } } // if (DEBUG) Log.v(TAG, "stop:finished"); } /** * コールバックを追加する * @param callback */ public void addCallback(final SoundSamplerCallback callback) { if (callback != null) { mCallbacks.add(callback); } } /** * コールバックを削除する * @param callback */ public void removeCallback(final SoundSamplerCallback callback) { if (callback != null) { mCallbacks.remove(callback); } } /** * 音声データのサンプリング中かどうかを返す * @return */ public boolean isStarted() { return mIsCapturing; } /** * 音声入力ソースを返す * 100以上ならUAC * @return */ public abstract int getAudioSource(); /** * チャネル数を返す * @return */ public abstract int getChannels(); /** * サンプリング周波数を返す * @return */ public abstract int getSamplingFrequency(); /** *PCMエンコードの解像度(ビット数)を返す。8か16 * @return */ public abstract int getBitResolution(); /** * 音声データ1つ当たりのバイト数を返す * @return */ public int getBufferSize() { return mDefaultBufferSize; } /** * 音声データ取得時のコールバックを呼び出す * @param data */ private void callOnData(@NonNull final MediaData data) { @NonNull final ByteBuffer buf = data.get(); final int size = data.size(); final long pts = data.presentationTimeUs(); for (final SoundSamplerCallback callback: mCallbacks) { try { buf.clear(); buf.position(size); buf.flip(); callback.onData(buf, size, pts); } catch (final Exception e) { mCallbacks.remove(callback); Log.w(TAG, "callOnData:", e); } } } /** * エラー発生時のコールバックを呼び出す * @param e */ protected void callOnError(final Exception e) { for (final SoundSamplerCallback callback: mCallbacks) { try { callback.onError(e); } catch (final Exception e1) { mCallbacks.remove(callback); Log.w(TAG, "callOnError:", e1); } } } protected int mDefaultBufferSize = 1024; protected void init_pool(final int default_buffer_size) { mDefaultBufferSize = default_buffer_size; mAudioQueue.init(default_buffer_size); } /** * 音声データバッファをプールから取得する。 * プールがからの場合には最大MAX_POOL_SIZE個までは新規生成する * @return */ protected RecycleMediaData obtain() { // if (DEBUG) Log.v(TAG, "obtain:" + mPool.size() + ",mBufferNum=" + mBufferNum); return mAudioQueue.obtain(mDefaultBufferSize); } protected boolean addMediaData(@NonNull final RecycleMediaData data) { // if (DEBUG) Log.v(TAG, "addMediaData:" + mAudioQueue.size()); return mAudioQueue.queueFrame(data); } protected RecycleMediaData pollMediaData(final long timeout_msec) throws InterruptedException { return mAudioQueue.poll(timeout_msec, TimeUnit.MILLISECONDS); } /** * 前回MediaCodecへのエンコード時に使ったpresentationTimeUs */ private long prevInputPTSUs = -1; /** * 今回の書き込み用のpresentationTimeUs値を取得 * @return */ @SuppressLint("NewApi") protected long getInputPTSUs() { long result = Time.nanoTime() / 1000L; if (result <= prevInputPTSUs) { result = prevInputPTSUs + 9643; } prevInputPTSUs = result; return result; } /** * キューから音声データを取り出してコールバックを呼び出すためのスレッド */ private final class CallbackThread extends Thread { public CallbackThread() { super("AudioSampler"); } @Override public final void run() { // if (DEBUG) Log.i(TAG, "CallbackThread:start"); android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO); // THREAD_PRIORITY_URGENT_AUDIO RecycleMediaData data; for (; mIsCapturing ;) { try { data = pollMediaData(100); } catch (final InterruptedException e) { break; } if (data != null) { callOnData(data); // 使用済みのバッファをプールに戻して再利用する data.recycle(); } } // for (; mIsCapturing ;) synchronized (mCallbackSync) { mCallbackSync.notifyAll(); } // if (DEBUG) Log.i(TAG, "CallbackThread:finished"); } } }
apache-2.0
LaiHouWen/ProjectAll
HuaXiaApp/app/src/main/java/com/framwork/Utils/KeyBoradUtils.java
1231
package com.framwork.Utils; import android.app.Activity; import android.content.Context; import android.view.inputmethod.InputMethodManager; /** * 系统工具 * * @author wwt 2014.10.28 11:44 */ public class KeyBoradUtils { // 判断 获取输入法打开的状态 public static boolean isKeyBoardShow(Context context) { InputMethodManager imm = (InputMethodManager) context .getSystemService(Context.INPUT_METHOD_SERVICE); boolean isOpen = imm.isActive();// isOpen若返回true,则表示输入法打开 return isOpen; } // 调用隐藏系统默认的输入法 public static void getSystemInputMethod(Context context) { ((InputMethodManager) context .getSystemService(Context.INPUT_METHOD_SERVICE)) .hideSoftInputFromWindow(((Activity) (context)) .getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); // (WidgetSearchActivity是当前的Activity) } // 如果输入法在窗口上显示 public static void showInputMethod(Context context) { if (isKeyBoardShow(context)) { InputMethodManager imm = (InputMethodManager) context .getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); } } }
apache-2.0
i49/Hibiscus
hibiscus/src/main/java/com/github/i49/hibiscus/formats/Format.java
2256
package com.github.i49.hibiscus.formats; import java.util.Locale; import javax.json.JsonValue; /** * Common interface to be implemented by all format classes. * * <p> * A <i>format</i> is one of restrictions on the value spaces of the types. * Types in schema can select a format from predefined ones such as email address or IPv4 address. * This makes it unnecessary to write complex regular expressions matching email address or IPv4 address. * Most formats defined here are described by authoritative parties and considered as standard. * </p> * <p> * This package provides various kinds of format implementations, * and all these classes implement {@link Format} interface. * </p> * <p> * These formats can be obtained by static methods of {@link Formats} class. * Each format can be applied to the built-in types with help of {@link com.github.i49.hibiscus.facets.FormatFacet FormatFacet}, * which is one of <i>facets</i> provided by {@link com.github.i49.hibiscus.facets} package. * All formats currently available can be applied only to {@code string()} type. * </p> * * <p>All currently supported formats are shown in {@link com.github.i49.hibiscus.formats.Formats Formats} page.</p> * * @param <V> the type of {@link JsonValue} to be validated against this format. * * @see Formats */ public interface Format<V extends JsonValue> { /** * Returns the format name which must be unique in all formats. * @return the name of this format. * @see #getLocalizedName(Locale) */ String getName(); /** * Returns the format name which is appropriate to be displayed in specified locale. * * @param locale the locale for which the name will be localized. * @return the localized name of this format. * @see #getName() */ String getLocalizedName(Locale locale); /** * Tests whether the given value matches this format * and returns {@code true} if the value matches this format, {@code false} otherwise. * * @param jsonValue the JSON value to be tested whether it matches against this format or not. * @return {@code true} if the input argument matches the format, {@code false} otherwise. */ boolean matches(V jsonValue); }
apache-2.0
Smartlogic-Semaphore-Limited/Java-APIs
Semaphore-Model-Manipulation/src/test/java/com/smartlogic/semaphoremodel/TestModelWithOrderedConceptsBuilder.java
2194
package com.smartlogic.semaphoremodel; import java.io.File; import java.io.FileNotFoundException; import java.net.URI; import java.net.URISyntaxException; public class TestModelWithOrderedConceptsBuilder { public static void main(String[] args) throws ModelException, URISyntaxException, FileNotFoundException { Language english = Language.getLanguage("en"); Language french = Language.getLanguage("fr"); Language italian = Language.getLanguage("it"); SemaphoreModel semaphoreModel = new SemaphoreModel(); ConceptScheme conceptScheme = semaphoreModel.createConceptScheme( new URI("http://kma.com/ConceptScheme"), new Label("Concept Scheme", english), null); Concept concept1 = semaphoreModel.createConcept(new URI("http://kma.com/Concept1"), new Label("Concept1", english)); conceptScheme.addTopConcept(concept1); conceptScheme.addLabel(new Label("Concepti Schema", italian)); HasBroaderRelationshipType isPartOf = semaphoreModel.createHasBroaderRelationshipType( new URI("http://kma.com/isPartOf"), new Label("is part of", english), new URI("http://kma.com/hasPart"), new Label("has part", english)); isPartOf.addLabel(new Label("est un parte de", french)); HasNarrowerRelationshipType hasPart = semaphoreModel.getNarrowerRelationshipType(new URI("http://kma.com/hasPart")); Concept conceptC = semaphoreModel.createConcept(new URI("http://kma.com/ConceptC"), new Label("C concept that is part of cab ordering", english)); OrderedCollection orderedCollection = concept1.addOrderedCollection(OrderedCollection.Type.NARROWER, hasPart, conceptC); Concept conceptA = semaphoreModel.createConcept(new URI("http://kma.com/ConceptA"), new Label("A concept that is part of cab ordering", english)); orderedCollection.addValue(semaphoreModel.getNarrowerRelationshipType(), conceptA); Concept conceptB = semaphoreModel.createConcept(new URI("http://kma.com/ConceptB"), new Label("B concept that is part of cab ordering", english)); orderedCollection.addValue(hasPart, conceptB); semaphoreModel.write(new File("C:/temp/model.ttl")); } }
apache-2.0