repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
vaadin/designer-tutorials
emailclient-tutorial-data/src/main/java/org/vaadin/example/backend/CdiConfig.java
353
package org.vaadin.example.backend; import javax.enterprise.context.Dependent; import javax.enterprise.inject.Produces; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; public class CdiConfig { @Produces @Dependent @PersistenceContext(unitName = "tutorialdb") public EntityManager entityManager; }
apache-2.0
iSergio/gwt-cs
cesiumjs4gwt-main/src/main/java/org/cesiumjs/cs/core/projection/MapProjection.java
3935
/* * Copyright 2018 iserge. * * 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.cesiumjs.cs.core.projection; import jsinterop.annotations.JsConstructor; import jsinterop.annotations.JsMethod; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; import org.cesiumjs.cs.core.Cartesian3; import org.cesiumjs.cs.core.Cartographic; import org.cesiumjs.cs.core.Ellipsoid; /** * @author Serge Silaev aka iSergio */ @JsType(isNative = true, namespace = "Cesium", name = "MapProjection") public class MapProjection { /** * Defines how geodetic ellipsoid coordinates (Cartographic) project to a flat * map like Cesium's 2D and Columbus View modes. * * @see GeographicProjection * @see WebMercatorProjection */ @JsConstructor public MapProjection() { } /** * Gets the Ellipsoid. */ @JsProperty(name = "ellipsoid") public native Ellipsoid ellipsoid(); /** * Projects Cartographic coordinates, in radians, to projection-specific map * coordinates, in meters. * * @param cartographic The coordinates to project. * @return The projected coordinates. If the result parameter is not undefined, * the coordinates are copied there and that instance is returned. * Otherwise, a new instance is created and returned. */ @JsMethod public native Cartesian3 project(Cartographic cartographic); /** * Projects Cartographic coordinates, in radians, to projection-specific map * coordinates, in meters. * * @param cartographic The coordinates to project. * @param result An instance into which to copy the result. If this * parameter is undefined, a new instance is created and * returned. * @return The projected coordinates. If the result parameter is not undefined, * the coordinates are copied there and that instance is returned. * Otherwise, a new instance is created and returned. */ @JsMethod public native Cartesian3 project(Cartographic cartographic, Cartesian3 result); /** * Unprojects projection-specific map Cartesian3 coordinates, in meters, to * Cartographic coordinates, in radians. * * @param cartesian The Cartesian position to unproject with height (z) in * meters. * @return The unprojected coordinates. If the result parameter is not * undefined, the coordinates are copied there and that instance is * returned. Otherwise, a new instance is created and returned. */ @JsMethod public native Cartographic unproject(Cartesian3 cartesian); /** * Unprojects projection-specific map Cartesian3 coordinates, in meters, to * Cartographic coordinates, in radians. * * @param cartesian The Cartesian position to unproject with height (z) in * meters. * @param result An instance into which to copy the result. If this parameter * is undefined, a new instance is created and returned. * @return The unprojected coordinates. If the result parameter is not * undefined, the coordinates are copied there and that instance is * returned. Otherwise, a new instance is created and returned. */ @JsMethod public native Cartographic unproject(Cartesian3 cartesian, Cartographic result); }
apache-2.0
diyaren/CPEN391Motivator
app/src/main/java/com/firebase/uidemo/db/TaskDBHelper.java
981
package com.firebase.uidemo.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.firebase.uidemo.auth.TaskContract; /** * Created by Navjashan on 14/03/2017. */ public class TaskDBHelper extends SQLiteOpenHelper{ public TaskDBHelper(Context context){ super(context, TaskContract.DB_NAME, null, TaskContract.DB_VERSION); } @Override public void onCreate(SQLiteDatabase db){ String createTable = "CREATE TABLE " + TaskContract.TaskEntry.TABLE + " ( " + TaskContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + TaskContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);"; db.execSQL(createTable); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){ db.execSQL("DROP TABLE IF EXISTS " + TaskContract.TaskEntry.TABLE); onCreate(db); } }
apache-2.0
JohnCny/PCCREDIT_QZ
src/java/com/cardpay/pccredit/divisional/dao/DivisionalDao.java
3432
package com.cardpay.pccredit.divisional.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.cardpay.pccredit.divisional.filter.DivisionalFilter; import com.cardpay.pccredit.divisional.model.DivisionalTransfer; import com.cardpay.pccredit.divisional.model.DivisionalWeb; import com.cardpay.pccredit.ipad.model.UserIpad; import com.cardpay.pccredit.system.model.Dict; import com.wicresoft.jrad.base.database.model.QueryResult; import com.wicresoft.util.annotation.Mapper; /** * * @author shaoming * */ @Mapper public interface DivisionalDao { /** * 得到客户经理的id和name * @param id * @return */ public List<Dict> findCustomerManagers(@Param("id") String id); /** * 得到客户id * @param id * @return */ public String findCustomerIdById(@Param("id") String id); /** * 修改分案申请信息中的现机构id,客户经理id,分案结果 * @param id * @param customerManagerId * @param orgId * @return */ public int updateDivisional(@Param("id")String id,@Param("customerManagerId")String customerManagerId,@Param("orgId")String orgId,@Param("result")String result); /** * 得到分案最终结果 * @param id * @return */ public String findDivisionalResultById(@Param("id")String id); /** * 得到分案进度 * @param id * @return */ public String findDivisionalProcessById(@Param("id")String id); /** * 修改分案进度 * @param id * @return */ public int findDivisionalProcessById(@Param("id")String id,@Param("process") String process); /** * 修改分案进度toCardCenter * @param id * @return */ public int updateDivisionalProcessToCardCenter(@Param("id")String id,@Param("process") String process); /** * 修改分案申请 * @param id * @param result 分案结果 * @param process 分案进度 * @return */ public int updateDivisionalResultAndProcess(@Param("id") String id,@Param("result") String result,@Param("process") String process); /** * 修改分案申请 * @param id * @param orgId 现机构id * @param process 分案进度 * @return */ public int updateDivisionalProcessAndOrg(@Param("id") String id,@Param("orgId") String orgId,@Param("process") String process); /** * 得到用户名 * @param id * @return */ public String getUserNameByUserId(@Param("id") String id); /** * 统计今日分案申请数量 * @param customerManagerId 现 客户经理id * @param result 分案结果 * @param process 分案进度 * @return */ public int findDivisionalCounsToday(@Param("customerManagerId") String customerManagerId,@Param("result") String result,@Param("process") String process); public List<DivisionalWeb> findDivisional_qz(DivisionalFilter filter); public int findDivisional_qz_count(DivisionalFilter filter); public List<DivisionalTransfer> findDivisionalTransfer(DivisionalFilter filter); public int findDivisionalTransferCount(DivisionalFilter filter); public List<DivisionalWeb> findDivisionalByCustomerManager(DivisionalFilter filter); public int findDivisionalByCustomerManagerCount(DivisionalFilter filter); public List<UserIpad> getAllUsers(); //团队长退回进件 public void returnDivisional(@Param("id") String id); public void returnDivisional_bci(@Param("customerId") String customerId); }
apache-2.0
mrluo735/cas-5.1.0
core/cas-server-core-tickets/src/main/java/org/apereo/cas/ticket/registry/DefaultTicketRegistrySupport.java
2004
package org.apereo.cas.ticket.registry; import org.apereo.cas.authentication.Authentication; import org.apereo.cas.authentication.principal.Principal; import org.apereo.cas.ticket.TicketGrantingTicket; import org.springframework.transaction.annotation.Transactional; import java.util.Map; /** * This is {@link DefaultTicketRegistrySupport}. * * @author Misagh Moayyed * @author Dmitriy Kopylenko * @since 4.2.0 */ @Transactional(transactionManager = "ticketTransactionManager") public class DefaultTicketRegistrySupport implements TicketRegistrySupport { private final TicketRegistry ticketRegistry; public DefaultTicketRegistrySupport(final TicketRegistry ticketRegistry) { this.ticketRegistry = ticketRegistry; } @Override public Authentication getAuthenticationFrom(final String ticketGrantingTicketId) throws RuntimeException { final TicketGrantingTicket tgt = this.ticketRegistry.getTicket(ticketGrantingTicketId, TicketGrantingTicket.class); return tgt == null ? null : tgt.getAuthentication(); } @Override public Principal getAuthenticatedPrincipalFrom(final String ticketGrantingTicketId) throws RuntimeException { final Authentication auth = getAuthenticationFrom(ticketGrantingTicketId); return auth == null ? null : auth.getPrincipal(); } @Override public Map<String, Object> getPrincipalAttributesFrom(final String ticketGrantingTicketId) throws RuntimeException { final Principal principal = getAuthenticatedPrincipalFrom(ticketGrantingTicketId); return principal == null ? null : principal.getAttributes(); } @Override public void updateAuthentication(final String ticketGrantingTicketId, final Authentication authentication) { final TicketGrantingTicket tgt = this.ticketRegistry.getTicket(ticketGrantingTicketId, TicketGrantingTicket.class); tgt.getAuthentication().update(authentication); this.ticketRegistry.updateTicket(tgt); } }
apache-2.0
venusdrogon/feilong-spring
feilong-spring-extension/src/main/java/com/feilong/spring/web/servlet/interceptor/seo/SeoViewCommandFromAttributeValueViewCommandBuilder.java
1711
/* * Copyright (C) 2008 feilong * * 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.feilong.spring.web.servlet.interceptor.seo; import com.feilong.context.ViewCommand; import com.feilong.core.bean.PropertyUtil; /** * 提供从 {@link ViewCommand} 中提取/构造 {@link SeoViewCommand}的扩展点. * * @author <a href="http://feitianbenyue.iteye.com/">feilong</a> * @see StandardSeoInterceptor * @since 1.5.1 * @since 1.11.2 change extends to interface */ public class SeoViewCommandFromAttributeValueViewCommandBuilder implements SeoViewCommandFromAttributeValueBuilder{ /* * (non-Javadoc) * * @see com.feilong.spring.web.servlet.interceptor.seo.SeoViewCommandFromAttributeValueBuilder#build(java.lang.String, java.lang.Object) */ @Override public SeoViewCommand build(String attributeName,Object attributeValue){ if (attributeValue instanceof ViewCommand){ //级联查询 SeoViewCommand seoViewCommand = PropertyUtil.findValueOfType(attributeValue, SeoViewCommand.class); if (null != seoViewCommand){ return seoViewCommand; } } return null; } }
apache-2.0
Dempsy/dempsy-commons
dempsy-utils/src/test/java/net/dempsy/util/TestDUtils.java
1069
package net.dempsy.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.dempsy.util.io.DUtils; public class TestDUtils { private static final Logger LOGGER = LoggerFactory.getLogger(TestDUtils.class); @Test public void testSystemTmpWoProp() throws Exception { final MutableInt result = new MutableInt(0); try(@SuppressWarnings("resource") var props = new SystemPropertyManager() .remove(DUtils.SYS_PROP_WITH_TMP_DIR);) { final File f = DUtils.systemTempDir(null); result.val = f.exists() ? 1 : 0; } catch(final IllegalStateException ise) { // this will happen on windows when java.io.tmpdir is unset. result.val = 1; } assertEquals(1, result.val); } @Test public void testSystemTmp() throws Exception { assertTrue(DUtils.systemTempDir(LOGGER).exists()); } }
apache-2.0
slvrgauthier/archives
Fac/Master/IN207/Warbot/src/edu/turtlekit2/warbot/controller/Simulation.java
2806
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.turtlekit2.warbot.controller; /** * Classe permettant de recuperer la configuration de la simulation * effectuee par l'utilisateur (dans l'interface de choix des equipes). * * @author Bonnotte Jessy, Burc Pierre, Duplouy Olivier, Polizzi Mathieu * */ public class Simulation { /** * For 1 vs 1 mode */ public static final int VS = 0; /** * For tournament mode */ public static final int TOURNAMENT = 1; private int _nbExplorer = 0; private int _nbRocketLauncher = 0; private int _nbBase = 0; private int _typeSimulation; private int _foodAppearance = 0; public Simulation(int nbExplorer, int nbRocketLauncher, int nbBase, int typeSimulation, int foodApparance){ _nbExplorer = nbExplorer; _nbRocketLauncher = nbRocketLauncher; _nbBase = nbBase; _typeSimulation = typeSimulation; _foodAppearance = foodApparance; } /** * Methode permettant de renvoyer le nombre d'explorers qui * vont combattre sur le terrain. * * @return {@code int} - le nombre d'explorers qui vont combattre * sur le terrain */ public int getNbExplorer(){ return _nbExplorer; } /** * Methode permettant de renvoyer le nombre de rocket-launchers * qui combattront sur le terrain. * * @return {@code int} - le nombre de rocket-launchers * qui combattront sur le terrain */ public int getNbRocketLauncher(){ return _nbRocketLauncher; } /** * Methode permettant de renvoyer le nombre de bases qui * combattront sur le terrain. * * @return {@code int} - le nombre de bases qui * combattront sur le terrain */ public int getNbBase(){ return _nbBase; } /** * Methode permettant de renvoyer le mode choisi par * l'utilisateur: * <ul> * <li>0 pour le mode un contre un.</li> * <li>1 pour le mode tournoi.</li> * </ul> * * @return {@code int} - le numero du mode choisi */ public int getMode(){ return _typeSimulation; } /** * Methode permettant de renvoyer le pourcentage * d'apparition des ressources. * * @return {@code int} - le pourcentage d'apparition * des ressources */ public int getFoodAppearance(){ return _foodAppearance; } }
apache-2.0
VHAINNOVATIONS/Telepathology
Source/Java/ImagingRouter/main/src/java/gov/va/med/imaging/router/commands/artifacts/GetStudyOnlyArtifactResultsBySiteNumberWithCachingCommandImpl.java
4659
/** * Package: MAG - VistA Imaging WARNING: Per VHA Directive 2004-038, this routine should not be modified. Date Created: Jan 20, 2012 Site Name: Washington OI Field Office, Silver Spring, MD Developer: VHAISWWERFEJ Description: ;; +--------------------------------------------------------------------+ ;; Property of the US Government. ;; No permission to copy or redistribute this software is given. ;; Use of unreleased versions of this software requires the user ;; to execute a written test agreement with the VistA Imaging ;; Development Office of the Department of Veterans Affairs, ;; telephone (301) 734-0100. ;; ;; The Food and Drug Administration classifies this software as ;; a Class II medical device. As such, it may not be changed ;; in any way. Modifications to this software may result in an ;; adulterated medical device under 21CFR820, the use of which ;; is considered to be a violation of US Federal Statutes. ;; +--------------------------------------------------------------------+ */ package gov.va.med.imaging.router.commands.artifacts; import gov.va.med.PatientIdentifier; import gov.va.med.RoutingToken; import gov.va.med.imaging.core.interfaces.exceptions.ConnectionException; import gov.va.med.imaging.core.interfaces.exceptions.MethodException; import gov.va.med.imaging.exchange.business.ArtifactResults; import gov.va.med.imaging.exchange.business.StudyFilter; import gov.va.med.imaging.exchange.business.documents.DocumentSetResult; import gov.va.med.imaging.router.commands.documents.DocumentSetResultCache; import gov.va.med.imaging.transactioncontext.TransactionContext; import gov.va.med.imaging.transactioncontext.TransactionContextFactory; /** * This command extends GetStudyOnlyArtifactResultsBySiteNumberCommandImpl. This command handles in memory * caching of DocumentSetResult objects. It will optionally check the cache for DocumentSetResult objects * before calling the parent commands and it will ALWAYS cache DocumentSetResult information. * * @author VHAISWWERFEJ * */ public class GetStudyOnlyArtifactResultsBySiteNumberWithCachingCommandImpl extends GetStudyOnlyArtifactResultsBySiteNumberCommandImpl { private static final long serialVersionUID = 6855358318928412052L; private final boolean canGetFromCache; public GetStudyOnlyArtifactResultsBySiteNumberWithCachingCommandImpl(RoutingToken routingToken, PatientIdentifier patientIdentifier, StudyFilter filter, boolean includeRadiology, boolean includeDocuments, boolean canGetFromCache) { super(routingToken, patientIdentifier, filter, includeRadiology, includeDocuments); this.canGetFromCache = canGetFromCache; } public GetStudyOnlyArtifactResultsBySiteNumberWithCachingCommandImpl(RoutingToken routingToken, PatientIdentifier patientIdentifier, StudyFilter filter, boolean includeRadiology, boolean includeDocuments) { this(routingToken, patientIdentifier, filter, includeRadiology, includeDocuments, false); } /** * @return the canGetFromCache */ public boolean isCanGetFromCache() { return canGetFromCache; } /* (non-Javadoc) * @see gov.va.med.imaging.router.commands.artifacts.AbstractArtifactResultsBySiteNumberCommandImpl#callSynchronouslyInTransactionContext() */ @Override public ArtifactResults callSynchronouslyInTransactionContext() throws MethodException, ConnectionException { TransactionContext transactionContext = TransactionContextFactory.get(); if(isCanGetFromCache()) { DocumentSetResult result = DocumentSetResultCache.getCachedDocumentSetResult(getRoutingToken(), getPatientIdentifier()); if(result != null) { getLogger().info("Retrieved cached DocumentSetResult for patient '" + getPatientIdentifier() + "' from site '" + getRoutingToken().toRoutingTokenString() + "'."); transactionContext.setItemCached(true); return ArtifactResults.createDocumentSetResult(result); } else { getLogger().debug("Did not get DocumentSetResult from cache for patient '" + getPatientIdentifier() + "' from site '" + getRoutingToken().toRoutingTokenString() + "'."); transactionContext.setItemCached(false); } } // only caching the DocumentSet data ArtifactResults result = super.callSynchronouslyInTransactionContext(); // cache the data if(result != null && result.getDocumentSetResult() != null) { DocumentSetResultCache.cacheDocumentSetResult(getRoutingToken(), getPatientIdentifier(), result.getDocumentSetResult()); } return result; } }
apache-2.0
mnzero/Sdut-jsj-OA
src/main/java/cn/opencil/oa/core/web/test/action/PaperAction.java
4214
package cn.opencil.oa.core.web.test.action; import cn.opencil.oa.common.page.PageResult; import cn.opencil.oa.common.util.PageUtil; import cn.opencil.oa.core.base.action.BaseAction; import cn.opencil.oa.core.domain.Paper; import cn.opencil.oa.core.domain.User; import cn.opencil.oa.core.query.PaperQuery; import cn.opencil.oa.core.web.test.service.PaperService; import com.opensymphony.xwork2.ActionContext; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * Created with Sdut-jsj-OA. * Package: cn.opencil.oa.core.web.test.action * User: 张树伟 * Date: 16-11-28 * Time: 下午5:10 */ @Controller @Scope("prototype") public class PaperAction extends BaseAction<Paper> { @Autowired private PaperService paperService; public String list() { PaperQuery paperQuery = new PaperQuery(); String schoolYear = this.getModel().getSchoolYear(); Subject subject = SecurityUtils.getSubject(); if (schoolYear != null) paperQuery.setSchoolYear(schoolYear.toString()); // 根据当前用户的用户名与第一作者比对 User user = PageUtil.getUser(); paperQuery.setAuthor(user.getUserName()); if (subject.isPermitted("paper:*")) { paperQuery.setAuthor(null); } PageResult<Paper> pageResult = paperService.getPageResult(paperQuery); List<Paper> papers = pageResult.getRows(); if (papers == null) ActionContext.getContext().put("papers", new ArrayList<Paper>()); ActionContext.getContext().put("papers", papers); return LISTACTION; } public String addUI() { return "addUI"; } public String add() { Paper paper = this.getModel(); this.getModel().setUuid(UUID.randomUUID().toString()); paperService.addPaper(paper); return LISTACTION; } public String updateUI() { Paper paper = paperService.getEntryById(this.getModel().getUuid()); ActionContext.getContext().put("paper", paper); return "updateUI"; } public String update() { Paper model = this.getModel(); paperService.updatePaper(model); return LISTACTION; } public String delete() { String uuid = this.getModel().getUuid(); Paper paper = paperService.getEntryById(uuid); paperService.deleteEntry(uuid); ActionContext.getContext().put("schoolYear", paper.getSchoolYear()); return "redirect"; } public String exportExcel() { String schoolYear = this.getModel().getSchoolYear(); if (!StringUtils.isNotEmpty(schoolYear)) schoolYear = "0"; InputStream inputStream = paperService.exportExcel(schoolYear); if (inputStream != null) { String excelName = paperService.getExcelName(schoolYear); ActionContext.getContext().put("inputStream", inputStream); ActionContext.getContext().put("excelName", excelName); } else { return "listAction"; } return "excel"; } public String showAnnex() { InputStream annex = paperService.showAnnex(this.getModel().getUuid()); ActionContext.getContext().put("annex", annex); return "showAnnex"; } public String downImage() { Paper paper = paperService.downloadImage(this.getModel().getUuid()); InputStream annex = paper.getInputStream(); ActionContext.getContext().put("annex", annex); String filename = paper.getTitle() + ".jpeg"; try { filename = new String(filename.getBytes("gbk"), "iso-8859-1"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } ActionContext.getContext().put("fileName", filename); return "downImage"; } }
apache-2.0
domaframework/doma
doma-core/src/main/java/org/seasar/doma/internal/jdbc/sql/OptionalIntSingleResultParameter.java
337
package org.seasar.doma.internal.jdbc.sql; import java.util.OptionalInt; import org.seasar.doma.internal.jdbc.scalar.OptionalIntScalar; public class OptionalIntSingleResultParameter extends ScalarSingleResultParameter<Integer, OptionalInt> { public OptionalIntSingleResultParameter() { super(new OptionalIntScalar()); } }
apache-2.0
ilivoo/ilivoo
hibernate/src/main/java/com/ilivoo/hibernate/learning/map/unidirection_join/manytoone/anno/Address.java
880
package com.ilivoo.hibernate.learning.map.unidirection_join.manytoone.anno; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; @Entity @Table(uniqueConstraints={@UniqueConstraint(name="UK_Address_place", columnNames="place")}) public class Address implements Serializable{ private static final long serialVersionUID = 2050165601002862490L; @Id @GeneratedValue private Integer id; @Column(length=50, nullable=false) private String place; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPlace() { return place; } public void setPlace(String place) { this.place = place; } }
apache-2.0
elotech/SITS
src/main/java/br/com/elotech/tributacao/oxm/nfse203/EnviarLoteRpsResposta.java
832
/* * Copyright 2016 ELOTECH GESTAO PUBLICA LTDA * 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.elotech.tributacao.oxm.nfse203; import br.com.elotech.tributacao.oxm.abstractenvioresposta.AbstractEnviarLoteRpsResposta; public class EnviarLoteRpsResposta extends AbstractEnviarLoteRpsResposta { }
apache-2.0
marcusbb/bag-o-util
src/main/java/provision/util/JNDIUtilConstants.java
218
package provision.util; public class JNDIUtilConstants { public final static String JMS_COMP_ENV_ROOT = "java:comp/env/jms/"; public final static String JMS_FACTORY = "javax.jms.QueueConnectionFactory"; }
apache-2.0
dimagi/commcare-android
app/src/org/commcare/android/database/user/models/FormRecordV4.java
2656
package org.commcare.android.database.user.models; import org.commcare.android.storage.framework.Persisted; import org.commcare.models.framework.Persisting; import org.commcare.modern.database.Table; import org.commcare.modern.models.MetaField; import java.util.Date; /** * This class represents the version of a FormRecord that exists on any devices running versions * 2.39 through 2.41 of CommCare, which was deprecated in user db version 23. This class is used * to read a form record that exists in such a database, in order to run a db upgrade. */ @Table("FORMRECORDS") public class FormRecordV4 extends Persisted { public static final String META_INSTANCE_URI = "INSTANCE_URI"; @Persisting(1) @MetaField(FormRecord.META_XMLNS) private String xmlns; @Persisting(2) @MetaField(META_INSTANCE_URI) private String instanceURI; @Persisting(3) @MetaField(FormRecord.META_STATUS) private String status; @Persisting(4) private byte[] aesKey; @Persisting(value = 5, nullable = true) @MetaField(FormRecord.META_UUID) private String uuid; @Persisting(6) @MetaField(FormRecord.META_LAST_MODIFIED) private Date lastModified; @Persisting(7) @MetaField(FormRecord.META_APP_ID) private String appId; @Persisting(value = 8, nullable = true) @MetaField(FormRecord.META_SUBMISSION_ORDERING_NUMBER) private String submissionOrderingNumber; @Persisting(value = 9, nullable = true) private String quarantineReason; // Deserialization only public FormRecordV4() { } public FormRecordV4(String instanceURI, String status, String xmlns, byte[] aesKey, String uuid, Date lastModified, String appId) { this.instanceURI = instanceURI; this.status = status; this.xmlns = xmlns; this.aesKey = aesKey; this.uuid = uuid; this.lastModified = lastModified; if (lastModified == null) { this.lastModified = new Date(); } this.appId = appId; } public String getInstanceURIString() { return instanceURI; } public byte[] getAesKey() { return aesKey; } public String getStatus() { return status; } public String getInstanceID() { return uuid; } public Date lastModified() { return lastModified; } public String getFormNamespace() { return xmlns; } public String getAppId() { return this.appId; } public void setFormNumberForSubmissionOrdering(int num) { this.submissionOrderingNumber = "" + num; } }
apache-2.0
alexschimpf/joe
core/src/com/tendersaucer/joe/event/EventManager.java
2228
package com.tendersaucer.joe.event; import com.badlogic.gdx.Gdx; import java.util.ArrayList; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Manages most game events and their listeners in one consolidated place * However, some are not handled here (e.g ICollide) * <p/> * Created by Alex on 5/5/2016. */ public final class EventManager { private static final EventManager INSTANCE = new EventManager(); private final Map<Class<? extends Event>, ArrayList> eventListeners; private EventManager() { eventListeners = new ConcurrentHashMap<Class<? extends Event>, ArrayList>(); } public static EventManager getInstance() { return INSTANCE; } public <L> boolean isListening(Object object, Class<? extends Event<L>> eventClass) { return eventListeners.get(eventClass).contains(object); } public <L> void listen(Class<? extends Event<L>> eventClass, L listener) { ArrayList listeners = eventListeners.get(eventClass); if (listeners == null) { listeners = new ArrayList(); } if (!listeners.contains(listener)) { listeners.add(listener); } eventListeners.put(eventClass, listeners); } public <L> void notify(Event<L> event) { Class<Event<L>> eventClass = (Class<Event<L>>)event.getClass(); if (eventListeners.containsKey(eventClass)) { for (L listener : (ArrayList<L>)eventListeners.get(eventClass)) { event.notify(listener); } } } public <L> void postNotify(final Event<L> event) { Gdx.app.postRunnable(new Runnable() { @Override public void run() { EventManager.this.notify(event); } }); } public <L> void mute(Class<? extends Event<L>> eventClass, L listener) { ArrayList listeners = eventListeners.get(eventClass); if (listeners != null) { listeners.remove(listener); } } public <L> void clear(Class<? extends Event<L>> eventClass) { eventListeners.remove(eventClass); } public void clearAll() { eventListeners.clear(); } }
apache-2.0
sfuhrm/go-maven-poller
src/main/java/com/oneandone/go/plugin/maven/MavenRepositoryMaterial.java
10974
package com.oneandone.go.plugin.maven; import com.oneandone.go.plugin.maven.config.ConfigurationProvider; import com.oneandone.go.plugin.maven.message.*; import com.thoughtworks.go.plugin.api.AbstractGoPlugin; import com.thoughtworks.go.plugin.api.GoPluginIdentifier; import com.thoughtworks.go.plugin.api.annotation.Extension; import com.thoughtworks.go.plugin.api.logging.Logger; import com.thoughtworks.go.plugin.api.request.GoPluginApiRequest; import com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse; import com.thoughtworks.go.plugin.api.response.GoPluginApiResponse; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import static com.oneandone.go.plugin.maven.util.JsonUtil.fromJsonString; import static com.oneandone.go.plugin.maven.util.JsonUtil.toJsonString; import static com.thoughtworks.go.plugin.api.response.DefaultGoPluginApiResponse.success; /** * The Go CD Maven repository plugin. * * Take a look at the <a href="http://www.go.cd/documentation/developer/writing_go_plugins/package_material/json_message_based_package_material_extension.html">documentation</a> * for more information on package repository plugins. */ @Extension public class MavenRepositoryMaterial extends AbstractGoPlugin { /** The logging instance for this class. */ private static final Logger LOGGER = Logger.getLoggerFor(MavenRepositoryMaterial.class); /** The plugin extension type. */ public static final String EXTENSION = "package-repository"; /** Request to retrieve the repository configuration definition.*/ public static final String REQUEST_REPOSITORY_CONFIGURATION = "repository-configuration"; /** Request to retrieve the package configuration definition. */ public static final String REQUEST_PACKAGE_CONFIGURATION = "package-configuration"; /** Request to validate the repository configuration. */ public static final String REQUEST_VALIDATE_REPOSITORY_CONFIGURATION = "validate-repository-configuration"; /** Request to validate the package configuration. */ public static final String REQUEST_VALIDATE_PACKAGE_CONFIGURATION = "validate-package-configuration"; /** Request to check the repository connection. */ public static final String REQUEST_CHECK_REPOSITORY_CONNECTION = "check-repository-connection"; /** Request to check the package connection. */ public static final String REQUEST_CHECK_PACKAGE_CONNECTION = "check-package-connection"; /** Request to retrieve the latest revision. */ public static final String REQUEST_LATEST_PACKAGE_REVISION = "latest-revision"; /** Request to retrieve the latest revision since a specified revision. */ public static final String REQUEST_LATEST_PACKAGE_REVISION_SINCE = "latest-revision-since"; /** The map of message handlers. */ private final Map<String, MessageHandler> handlerMap = new LinkedHashMap<>(); /** The configuration provider for this plugin. */ private final ConfigurationProvider configurationProvider; /** The repository poller analyzes the contents of a repository and retrieves the latest revision. */ private final MavenRepositoryPoller packageRepositoryPoller; /** Constructs this plugin and initializes the message handlers. */ public MavenRepositoryMaterial() { configurationProvider = new ConfigurationProvider(); packageRepositoryPoller = new MavenRepositoryPoller(); handlerMap.put(REQUEST_REPOSITORY_CONFIGURATION, repositoryConfigurationsMessageHandler()); handlerMap.put(REQUEST_PACKAGE_CONFIGURATION, packageConfigurationMessageHandler()); handlerMap.put(REQUEST_VALIDATE_REPOSITORY_CONFIGURATION, validateRepositoryConfigurationMessageHandler()); handlerMap.put(REQUEST_VALIDATE_PACKAGE_CONFIGURATION, validatePackageConfigurationMessageHandler()); handlerMap.put(REQUEST_CHECK_REPOSITORY_CONNECTION, checkRepositoryConnectionMessageHandler()); handlerMap.put(REQUEST_CHECK_PACKAGE_CONNECTION, checkPackageConnectionMessageHandler()); handlerMap.put(REQUEST_LATEST_PACKAGE_REVISION, latestRevisionMessageHandler()); handlerMap.put(REQUEST_LATEST_PACKAGE_REVISION_SINCE, latestRevisionSinceMessageHandler()); } @Override public GoPluginApiResponse handle(final GoPluginApiRequest goPluginApiRequest) { try { if (handlerMap.containsKey(goPluginApiRequest.requestName())) { return handlerMap.get(goPluginApiRequest.requestName()).handle(goPluginApiRequest); } return DefaultGoPluginApiResponse.badRequest(String.format("Invalid request name %s", goPluginApiRequest.requestName())); } catch (final Throwable e) { LOGGER.error("could not handle request with name \"" + goPluginApiRequest.requestName() + "\" and body: " + goPluginApiRequest.requestBody(), e); return DefaultGoPluginApiResponse.error(e.getMessage()); } } @Override public GoPluginIdentifier pluginIdentifier() { return new GoPluginIdentifier(EXTENSION, Collections.singletonList("1.0")); } /** * Returns a message handler for request of type [@link REQUEST_PACKAGE_CONFIGURATION}. * * @return the message handler */ private MessageHandler packageConfigurationMessageHandler() { return new MessageHandler() { @Override public GoPluginApiResponse handle(final GoPluginApiRequest request) { return success(toJsonString(configurationProvider.getPackageConfiguration().getPropertyMap())); } }; } /** * Returns a message handler for request of type [@link REQUEST_REPOSITORY_CONFIGURATION}. * * @return the message handler */ private MessageHandler repositoryConfigurationsMessageHandler() { return new MessageHandler() { @Override public GoPluginApiResponse handle(final GoPluginApiRequest request) { return success(toJsonString(configurationProvider.getRepositoryConfiguration().getPropertyMap())); } }; } /** * Returns a message handler for request of type [@link REQUEST_VALIDATE_REPOSITORY_CONFIGURATION}. * * @return the message handler */ private MessageHandler validateRepositoryConfigurationMessageHandler() { return new MessageHandler() { @Override public GoPluginApiResponse handle(final GoPluginApiRequest request) { final ConfigurationMessage message = fromJsonString(request.requestBody(), ConfigurationMessage.class); final ValidationResultMessage validationResultMessage = configurationProvider.isRepositoryConfigurationValid(message.getRepositoryConfiguration()); if (validationResultMessage.failure()) { return success(toJsonString(validationResultMessage.getValidationErrors())); } return success(""); } }; } /** * Returns a message handler for request of type [@link REQUEST_VALIDATE_PACKAGE_CONFIGURATION}. * * @return the message handler */ private MessageHandler validatePackageConfigurationMessageHandler() { return new MessageHandler() { @Override public GoPluginApiResponse handle(final GoPluginApiRequest request) { final ConfigurationMessage message = fromJsonString(request.requestBody(), ConfigurationMessage.class); final ValidationResultMessage validationResultMessage = configurationProvider.isPackageConfigurationValid(message.getPackageConfiguration()); if (validationResultMessage.failure()) { return success(toJsonString(validationResultMessage.getValidationErrors())); } return success(""); } }; } /** * Returns a message handler for request of type [@link REQUEST_CHECK_REPOSITORY_CONNECTION}. * * @return the message handler */ private MessageHandler checkRepositoryConnectionMessageHandler() { return new MessageHandler() { @Override public GoPluginApiResponse handle(final GoPluginApiRequest request) { final ConfigurationMessage message = fromJsonString(request.requestBody(), ConfigurationMessage.class); final CheckConnectionResultMessage result = packageRepositoryPoller.checkConnectionToRepository(message.getRepositoryConfiguration()); return success(toJsonString(result)); } }; } /** * Returns a message handler for request of type [@link REQUEST_CHECK_PACKAGE_CONNECTION}. * * @return the message handler */ private MessageHandler checkPackageConnectionMessageHandler() { return new MessageHandler() { @Override public GoPluginApiResponse handle(final GoPluginApiRequest request) { final ConfigurationMessage message = fromJsonString(request.requestBody(), ConfigurationMessage.class); final CheckConnectionResultMessage result = packageRepositoryPoller.checkConnectionToPackage(message.getPackageConfiguration(), message.getRepositoryConfiguration()); return success(toJsonString(result)); } }; } /** * Returns a message handler for request of type [@link REQUEST_LATEST_PACKAGE_REVISION}. * * @return the message handler */ private MessageHandler latestRevisionMessageHandler() { return new MessageHandler() { @Override public GoPluginApiResponse handle(final GoPluginApiRequest request) { final ConfigurationMessage message = fromJsonString(request.requestBody(), ConfigurationMessage.class); final PackageRevisionMessage revision = packageRepositoryPoller.getLatestRevision(message.getPackageConfiguration(), message.getRepositoryConfiguration()); return success(toJsonString(revision)); } }; } /** * Returns a message handler for request of type [@link REQUEST_LATEST_PACKAGE_REVISION_SINCE}. * * @return the message handler */ private MessageHandler latestRevisionSinceMessageHandler() { return new MessageHandler() { @Override public GoPluginApiResponse handle(final GoPluginApiRequest request) { final ConfigurationMessage message = fromJsonString(request.requestBody(), ConfigurationMessage.class); final PackageRevisionMessage revision = packageRepositoryPoller.latestModificationSince(message.getPackageConfiguration(), message.getRepositoryConfiguration(), message.getPreviousRevision()); return success(revision == null ? null : toJsonString(revision)); } }; } }
apache-2.0
SAP/cloud-roo-gwaddon
RooAddon/src/main/java/com/sap/research/connectivity/gw/converters/GwEndpointConverter.java
2653
/* * Copyright 2012 SAP AG * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sap.research.connectivity.gw.converters; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import org.apache.commons.lang3.StringUtils; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Service; import org.springframework.roo.file.monitor.event.FileDetails; import org.springframework.roo.shell.Completion; import org.springframework.roo.shell.Converter; import org.springframework.roo.shell.MethodTarget; import com.sap.research.connectivity.gw.GWOperationsUtils; import com.sap.research.connectivity.gw.GwEndpoint; @Component @Service public class GwEndpointConverter extends GWOperationsUtils implements Converter<GwEndpoint> { public GwEndpoint convertFromText(String value, final Class<?> requiredType, final String optionContext) { return new GwEndpoint(value); } public boolean getAllPossibleValues(final List<Completion> completions, final Class<?> requiredType, String existingData, final String optionContext, final MethodTarget target) { existingData = StringUtils.stripToEmpty(existingData); // Search for all files matching the pattern *_metadata.xml (we assume that the connectivity class corresponding to the endpoint xml // contains the same name (e.g. gw1.java and gw1_metadata.xml) SortedSet<FileDetails> files = new TreeSet<FileDetails>(); if (!optionContext.isEmpty()) { files = fileManager.findMatchingAntPath(getSubPackagePath(optionContext) + SEPARATOR + "*_metadata.xml"); } String filePath = "", nameSpace = ""; for (FileDetails f : files) { filePath = f.getCanonicalPath(); nameSpace = filePath.substring(filePath.lastIndexOf(SEPARATOR) + 1, filePath.lastIndexOf("_metadata.xml")); completions.add(new Completion(nameSpace)); } return false; } public boolean supports(Class<?> requiredType, String optionContext) { return GwEndpoint.class.isAssignableFrom(requiredType); } }
apache-2.0
jjYBdx4IL/streaming-clients
src/main/java/com/github/jjYBdx4IL/streaming/clients/ChatListener.java
178
package com.github.jjYBdx4IL.streaming.clients; /** * * @author jjYBdx4IL */ public interface ChatListener { void onChatMessage(String name, String message); }
apache-2.0
jeffssss/GoodStudyWeb
src/main/java/org/jeffssss/goodstudy/main/WXApiConfig.java
636
package org.jeffssss.goodstudy.main; import com.jfinal.kit.PropKit; import com.jfinal.weixin.sdk.api.ApiConfig; /** * Created by jifeng on 16/9/15. */ public class WXApiConfig { private static ApiConfig instance= null; public static ApiConfig getInstance(){ if(null == instance){ instance = new ApiConfig(); instance.setToken(PropKit.get("token")); instance.setAppId(PropKit.get("appId")); instance.setAppSecret(PropKit.get("appSecret")); instance.setEncryptMessage(PropKit.getBoolean("encryptMessage",false)); } return instance; } }
apache-2.0
aosp-mirror/platform_frameworks_support
persistence/db-framework/src/main/java/androidx/sqlite/db/framework/FrameworkSQLiteOpenHelper.java
5556
/* * 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 androidx.sqlite.db.framework; import android.content.Context; import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Build; import androidx.sqlite.db.SupportSQLiteDatabase; import androidx.sqlite.db.SupportSQLiteOpenHelper; class FrameworkSQLiteOpenHelper implements SupportSQLiteOpenHelper { private final OpenHelper mDelegate; FrameworkSQLiteOpenHelper(Context context, String name, Callback callback) { mDelegate = createDelegate(context, name, callback); } private OpenHelper createDelegate(Context context, String name, Callback callback) { final FrameworkSQLiteDatabase[] dbRef = new FrameworkSQLiteDatabase[1]; return new OpenHelper(context, name, dbRef, callback); } @Override public String getDatabaseName() { return mDelegate.getDatabaseName(); } @Override @androidx.annotation.RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) public void setWriteAheadLoggingEnabled(boolean enabled) { mDelegate.setWriteAheadLoggingEnabled(enabled); } @Override public SupportSQLiteDatabase getWritableDatabase() { return mDelegate.getWritableSupportDatabase(); } @Override public SupportSQLiteDatabase getReadableDatabase() { return mDelegate.getReadableSupportDatabase(); } @Override public void close() { mDelegate.close(); } static class OpenHelper extends SQLiteOpenHelper { /** * This is used as an Object reference so that we can access the wrapped database inside * the constructor. SQLiteOpenHelper requires the error handler to be passed in the * constructor. */ final FrameworkSQLiteDatabase[] mDbRef; final Callback mCallback; // see b/78359448 private boolean mMigrated; OpenHelper(Context context, String name, final FrameworkSQLiteDatabase[] dbRef, final Callback callback) { super(context, name, null, callback.version, new DatabaseErrorHandler() { @Override public void onCorruption(SQLiteDatabase dbObj) { FrameworkSQLiteDatabase db = dbRef[0]; if (db != null) { callback.onCorruption(db); } } }); mCallback = callback; mDbRef = dbRef; } synchronized SupportSQLiteDatabase getWritableSupportDatabase() { mMigrated = false; SQLiteDatabase db = super.getWritableDatabase(); if (mMigrated) { // there might be a connection w/ stale structure, we should re-open. close(); return getWritableSupportDatabase(); } return getWrappedDb(db); } synchronized SupportSQLiteDatabase getReadableSupportDatabase() { mMigrated = false; SQLiteDatabase db = super.getReadableDatabase(); if (mMigrated) { // there might be a connection w/ stale structure, we should re-open. close(); return getReadableSupportDatabase(); } return getWrappedDb(db); } FrameworkSQLiteDatabase getWrappedDb(SQLiteDatabase sqLiteDatabase) { FrameworkSQLiteDatabase dbRef = mDbRef[0]; if (dbRef == null) { dbRef = new FrameworkSQLiteDatabase(sqLiteDatabase); mDbRef[0] = dbRef; } return mDbRef[0]; } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { mCallback.onCreate(getWrappedDb(sqLiteDatabase)); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { mMigrated = true; mCallback.onUpgrade(getWrappedDb(sqLiteDatabase), oldVersion, newVersion); } @Override public void onConfigure(SQLiteDatabase db) { mCallback.onConfigure(getWrappedDb(db)); } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { mMigrated = true; mCallback.onDowngrade(getWrappedDb(db), oldVersion, newVersion); } @Override public void onOpen(SQLiteDatabase db) { if (!mMigrated) { // if we've migrated, we'll re-open the db so we should not call the callback. mCallback.onOpen(getWrappedDb(db)); } } @Override public synchronized void close() { super.close(); mDbRef[0] = null; } } }
apache-2.0
bboyfeiyu/hudson.core
hudson-test-framework/src/main/java/org/jvnet/hudson/test/HudsonTestCase.java
70282
/******************************************************************************* * * Copyright (c) 2004-2009 Oracle Corporation. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * * Kohsuke Kawaguchi, Erik Ramfelt, Yahoo! Inc., Tom Huybrechts * * *******************************************************************************/ package org.jvnet.hudson.test; import com.gargoylesoftware.htmlunit.DefaultCssErrorHandler; import com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory; import com.gargoylesoftware.htmlunit.javascript.host.xml.XMLHttpRequest; import hudson.*; import hudson.Util; import hudson.model.*; import hudson.model.Queue.Executable; import hudson.security.ACL; import hudson.security.AbstractPasswordBasedSecurityRealm; import hudson.security.GroupDetails; import hudson.security.SecurityRealm; import hudson.slaves.ComputerConnector; import hudson.tasks.Builder; import hudson.tasks.Publisher; import hudson.tools.ToolProperty; import hudson.remoting.Which; import hudson.Launcher.LocalLauncher; import hudson.matrix.MatrixProject; import hudson.matrix.MatrixBuild; import hudson.matrix.MatrixRun; import hudson.security.csrf.CrumbIssuer; import hudson.slaves.CommandLauncher; import hudson.slaves.DumbSlave; import hudson.slaves.RetentionStrategy; import org.eclipse.hudson.WebAppController; import org.eclipse.hudson.WebAppController.DefaultInstallStrategy; import hudson.tasks.Mailer; import hudson.tasks.Maven; import hudson.tasks.Ant; import hudson.tasks.Ant.AntInstallation; import hudson.tasks.Maven.MavenInstallation; import hudson.util.PersistedList; import hudson.util.ReflectionUtils; import hudson.util.StreamTaskListener; import hudson.model.Node.Mode; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Arrays; import java.util.Collections; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.jar.Manifest; import java.util.logging.Filter; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.beans.PropertyDescriptor; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import junit.framework.TestCase; import net.sourceforge.htmlunit.corejs.javascript.Context; import net.sourceforge.htmlunit.corejs.javascript.ContextFactory.Listener; import org.springframework.security.AuthenticationException; import org.springframework.security.BadCredentialsException; import org.springframework.security.GrantedAuthority; import org.springframework.security.context.SecurityContextHolder; import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UsernameNotFoundException; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.io.FileUtils; import org.apache.commons.beanutils.PropertyUtils; import org.hudsonci.inject.Smoothie; import org.hudsonci.inject.SmoothieUtil; import org.hudsonci.inject.internal.SmoothieContainerBootstrap; import org.jvnet.hudson.test.HudsonHomeLoader.CopyExisting; import org.jvnet.hudson.test.recipes.Recipe; import org.jvnet.hudson.test.recipes.Recipe.Runner; import org.jvnet.hudson.test.recipes.WithPlugin; import org.jvnet.hudson.test.rhino.JavaScriptDebugger; import org.kohsuke.stapler.ClassDescriptor; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.Dispatcher; import org.kohsuke.stapler.MetaClass; import org.kohsuke.stapler.MetaClassLoader; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.Stapler; import org.mortbay.jetty.MimeTypes; import org.mortbay.jetty.Server; import org.mortbay.jetty.bio.SocketConnector; import org.mortbay.jetty.security.HashUserRealm; import org.mortbay.jetty.security.UserRealm; import org.mortbay.jetty.webapp.Configuration; import org.mortbay.jetty.webapp.WebAppContext; import org.mortbay.jetty.webapp.WebXmlConfiguration; import org.mozilla.javascript.tools.debugger.Dim; import org.mozilla.javascript.tools.shell.Global; import org.springframework.dao.DataAccessException; import org.w3c.css.sac.CSSException; import org.w3c.css.sac.CSSParseException; import org.w3c.css.sac.ErrorHandler; import org.xml.sax.SAXException; import com.gargoylesoftware.htmlunit.AjaxController; import com.gargoylesoftware.htmlunit.BrowserVersion; import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.WebRequestSettings; import com.gargoylesoftware.htmlunit.xml.XmlPage; import com.gargoylesoftware.htmlunit.html.*; import hudson.slaves.ComputerListener; import java.util.concurrent.CountDownLatch; import hudson.maven.MavenEmbedder; import hudson.maven.MavenRequest; import hudson.security.*; import hudson.util.SecurityFailedToInit; import java.nio.charset.Charset; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.AbstractArtifactResolutionException; import org.eclipse.hudson.HudsonServletContextListener; import org.eclipse.hudson.security.HudsonSecurityEntitiesHolder; import org.eclipse.hudson.security.HudsonSecurityManager; /** * Base class for all Hudson test cases. * * @see <a href="http://wiki.hudson-ci.org/display/HUDSON/Unit+Test">Wiki * article about unit testing in Hudson</a> * @author Kohsuke Kawaguchi */ public abstract class HudsonTestCase extends TestCase implements RootAction { public Hudson hudson; protected final TestEnvironment env = new TestEnvironment(this); protected HudsonHomeLoader homeLoader = HudsonHomeLoader.NEW; /** * TCP/IP port that the server is listening on. */ protected int localPort; protected Server server; /** * Where in the {@link Server} is Hudson deployed? <p> Just like * {@link ServletContext#getContextPath()}, starts with '/' but doesn't end * with '/'. */ protected String contextPath = ""; /** * {@link Runnable}s to be invoked at {@link #tearDown()}. */ protected List<LenientRunnable> tearDowns = new ArrayList<LenientRunnable>(); protected List<Runner> recipes = new ArrayList<Runner>(); /** * Remember {@link WebClient}s that are created, to release them properly. */ private List<WeakReference<WebClient>> clients = new ArrayList<WeakReference<WebClient>>(); /** * JavaScript "debugger" that provides you information about the JavaScript * call stack and the current values of the local variables in those stack * frame. * * <p> Unlike Java debugger, which you as a human interfaces directly and * interactively, this JavaScript debugger is to be interfaced by your * program (or through the expression evaluation capability of your Java * debugger.) */ protected JavaScriptDebugger jsDebugger = new JavaScriptDebugger(); /** * If this test case has additional {@link WithPlugin} annotations, set to * true. This will cause a fresh {@link PluginManager} to be created for * this test. Leaving this to false enables the test harness to use a * pre-loaded plugin manager, which runs faster. */ public boolean useLocalPluginManager = true; // FIXME: At the new smoothie container needs the real plugin manager public ComputerConnectorTester computerConnectorTester = new ComputerConnectorTester(this); protected HudsonTestCase(String name) { super(name); } protected HudsonTestCase() { } @Override public void runBare() throws Throwable { // override the thread name to make the thread dump more useful. Thread t = Thread.currentThread(); String o = getClass().getName() + '.' + t.getName(); t.setName("Executing " + getName()); try { super.runBare(); } finally { t.setName(o); } } @Override protected void setUp() throws Exception { //System.setProperty("hudson.PluginStrategy", "hudson.ClassicPluginStrategy"); env.pin(); recipe(); AbstractProject.WORKSPACE.toString(); User.clear(); // Bootstrap the container with details about our testing classes, so it can figure out what to scan/include SmoothieUtil.reset(); // force-reset, some tests may not properly hit the tear-down to reset so do it again here new SmoothieContainerBootstrap().bootstrap(getClass().getClassLoader(), Hudson.class, Smoothie.class, HudsonTestCase.class, getClass()); try { hudson = newHudson(); } catch (Exception e) { // if Hudson instance fails to initialize, it leaves the instance field non-empty and break all the rest of the tests, so clean that up. Field f = Hudson.class.getDeclaredField("theInstance"); f.setAccessible(true); f.set(null, null); throw e; } hudson.setNoUsageStatistics(true); // collecting usage stats from tests are pointless. hudson.setCrumbIssuer(new TestCrumbIssuer()); final WebAppController controller = WebAppController.get(); try { controller.setContext(hudson.servletContext); } catch (IllegalStateException e) { // handle tests which run several times inside the same JVM Field f = WebAppController.class.getDeclaredField("context"); f.setAccessible(true); f.set(controller, hudson.servletContext); } try { controller.setInstallStrategy(new DefaultInstallStrategy()); } catch (IllegalStateException e) { // strategy already set ignore } controller.install(hudson); hudson.servletContext.setAttribute("version", "?"); HudsonServletContextListener.installExpressionFactory(new ServletContextEvent(hudson.servletContext)); // set a default JDK to be the one that the harness is using. hudson.getJDKs().add(new JDK("default", System.getProperty("java.home"))); configureUpdateCenter(); // expose the test instance as a part of URL tree. // this allows tests to use a part of the URL space for itself. hudson.getActions().add(this); // cause all the descriptors to reload. // ideally we'd like to reset them to properly emulate the behavior, but that's not possible. Mailer.descriptor().setHudsonUrl(null); for (Descriptor d : hudson.getExtensionList(Descriptor.class)) { d.load(); } } /** * Configures the update center setting for the test. By default, we load * updates from local proxy to avoid network traffic as much as possible. */ protected void configureUpdateCenter() throws Exception { final String updateCenterUrl = "http://localhost:" + JavaNetReverseProxy.getInstance().localPort + "/update-center.json"; // don't waste bandwidth talking to the update center DownloadService.neverUpdate = true; UpdateSite.neverUpdate = true; PersistedList<UpdateSite> sites = hudson.getUpdateCenter().getSites(); sites.clear(); sites.add(new UpdateSite("default", updateCenterUrl)); } @Override protected void tearDown() throws Exception { try { // cancel pending asynchronous operations, although this doesn't really seem to be working for (WeakReference<WebClient> client : clients) { WebClient c = client.get(); if (c == null) { continue; } // unload the page to cancel asynchronous operations c.getPage("about:blank"); } clients.clear(); } finally { server.stop(); for (LenientRunnable r : tearDowns) { r.run(); } hudson.cleanUp(); ExtensionList.clearLegacyInstances(); DescriptorExtensionList.clearLegacyInstances(); // Force the container bits to reset SmoothieUtil.reset(); // Hudson creates ClassLoaders for plugins that hold on to file descriptors of its jar files, // but because there's no explicit dispose method on ClassLoader, they won't get GC-ed until // at some later point, leading to possible file descriptor overflow. So encourage GC now. // see http://bugs.sun.com/view_bug.do?bug_id=4950148 System.gc(); env.dispose(); } } @Override protected void runTest() throws Throwable { String testName = getClass().getSimpleName() + "." + getName(); System.out.println(">>> Starting " + testName + " >>>"); // so that test code has all the access to the system SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM); try { super.runTest(); } finally { System.out.println("<<< Finished " + testName + " <<<"); } } public String getIconFileName() { return null; } public String getDisplayName() { return null; } public String getUrlName() { return "self"; } /** * Creates a new instance of {@link Hudson}. If the derived class wants to * create it in a different way, you can override it. */ protected Hudson newHudson() throws Exception { File home = homeLoader.allocate(); // Create the Security Manager HudsonSecurityEntitiesHolder.setHudsonSecurityManager(new HudsonSecurityManager(home)); for (Runner r : recipes) { r.decorateHome(this, home); } return new Hudson(home, createWebServer(), useLocalPluginManager ? null : TestPluginManager.INSTANCE); } /** * Prepares a webapp hosting environment to get {@link ServletContext} * implementation that we need for testing. */ protected ServletContext createWebServer() throws Exception { server = new Server(); WebAppContext context = new WebAppContext(WarExploder.getExplodedDir().getPath(), contextPath); context.setClassLoader(getClass().getClassLoader()); context.setConfigurations(new Configuration[]{new WebXmlConfiguration(), new NoListenerConfiguration()}); server.setHandler(context); context.setMimeTypes(MIME_TYPES); SocketConnector connector = new SocketConnector(); server.addConnector(connector); server.addUserRealm(configureUserRealm()); server.start(); localPort = connector.getLocalPort(); return context.getServletContext(); } /** * Configures a security realm for a test. */ protected UserRealm configureUserRealm() { HashUserRealm realm = new HashUserRealm(); realm.setName("default"); // this is the magic realm name to make it effective on everywhere realm.put("alice", "alice"); realm.put("bob", "bob"); realm.put("charlie", "charlie"); realm.addUserToRole("alice", "female"); realm.addUserToRole("bob", "male"); realm.addUserToRole("charlie", "male"); return realm; } // /** // * Sets guest credentials to access java.net Subversion repo. // */ // protected void setJavaNetCredential() throws SVNException, IOException { // // set the credential to access svn.dev.java.net // hudson.getDescriptorByType(SubversionSCM.DescriptorImpl.class).postCredential("https://svn.dev.java.net/svn/hudson/","guest","",null,new PrintWriter(new NullStream())); // } /** * Returns the older default Maven, while still allowing specification of * other bundled Mavens. */ protected MavenInstallation configureDefaultMaven() throws Exception { return configureDefaultMaven("apache-maven-2.2.1", MavenInstallation.MAVEN_20); } protected MavenInstallation configureMaven3() throws Exception { MavenInstallation mvn = configureDefaultMaven("apache-maven-3.0.1", MavenInstallation.MAVEN_30); MavenInstallation m3 = new MavenInstallation("apache-maven-3.0.1", mvn.getHome(), NO_PROPERTIES); hudson.getDescriptorByType(Maven.DescriptorImpl.class).setInstallations(m3); return m3; } /** * Locates Maven2 and configure that as the only Maven in the system. */ protected MavenInstallation configureDefaultMaven(String mavenVersion, int mavenReqVersion) throws Exception { // first if we are running inside Maven, pick that Maven, if it meets the criteria we require.. // does it exists in the buildDirectory see maven-junit-plugin systemProperties // buildDirectory -> ${project.build.directory} (so no reason to be null ;-) ) String buildDirectory = System.getProperty("buildDirectory", "./target/classes/"); File mavenAlreadyInstalled = new File(buildDirectory, mavenVersion); if (mavenAlreadyInstalled.exists()) { MavenInstallation mavenInstallation = new MavenInstallation("default", mavenAlreadyInstalled.getAbsolutePath(), NO_PROPERTIES); hudson.getDescriptorByType(Maven.DescriptorImpl.class).setInstallations(mavenInstallation); return mavenInstallation; } String home = System.getProperty("maven.home"); if (home != null) { MavenInstallation mavenInstallation = new MavenInstallation("default", home, NO_PROPERTIES); if (mavenInstallation.meetsMavenReqVersion(createLocalLauncher(), mavenReqVersion)) { hudson.getDescriptorByType(Maven.DescriptorImpl.class).setInstallations(mavenInstallation); return mavenInstallation; } } // otherwise extract the copy we have. // this happens when a test is invoked from an IDE, for example. LOGGER.warning("Extracting a copy of Maven bundled in the test harness. " + "To avoid a performance hit, set the system property 'maven.home' to point to a Maven2 installation."); FilePath mvn = hudson.getRootPath().createTempFile("maven", "zip"); mvn.copyFrom(HudsonTestCase.class.getClassLoader().getResource(mavenVersion + "-bin.zip")); File mvnHome = new File(buildDirectory);//createTmpDir(); mvn.unzip(new FilePath(mvnHome)); // TODO: switch to tar that preserves file permissions more easily if (!Functions.isWindows()) { Util.chmod(new File(mvnHome, mavenVersion + "/bin/mvn"), 0755); } MavenInstallation mavenInstallation = new MavenInstallation("default", new File(mvnHome, mavenVersion).getAbsolutePath(), NO_PROPERTIES); hudson.getDescriptorByType(Maven.DescriptorImpl.class).setInstallations(mavenInstallation); return mavenInstallation; } /** * Extracts Ant and configures it. */ protected Ant.AntInstallation configureDefaultAnt() throws Exception { Ant.AntInstallation antInstallation; if (System.getenv("ANT_HOME") != null) { antInstallation = new AntInstallation("default", System.getenv("ANT_HOME"), NO_PROPERTIES); } else { LOGGER.warning("Extracting a copy of Ant bundled in the test harness. " + "To avoid a performance hit, set the environment variable ANT_HOME to point to an Ant installation."); FilePath ant = hudson.getRootPath().createTempFile("ant", "zip"); ant.copyFrom(HudsonTestCase.class.getClassLoader().getResource("apache-ant-1.8.1-bin.zip")); File antHome = createTmpDir(); ant.unzip(new FilePath(antHome)); // TODO: switch to tar that preserves file permissions more easily if (!Functions.isWindows()) { Util.chmod(new File(antHome, "apache-ant-1.8.1/bin/ant"), 0755); } antInstallation = new AntInstallation("default", new File(antHome, "apache-ant-1.8.1").getAbsolutePath(), NO_PROPERTIES); } hudson.getDescriptorByType(Ant.DescriptorImpl.class).setInstallations(antInstallation); return antInstallation; } // // Convenience methods // protected FreeStyleProject createFreeStyleProject() throws IOException { return createFreeStyleProject(createUniqueProjectName()); } protected FreeStyleProject createFreeStyleProject(String name) throws IOException { return hudson.createProject(FreeStyleProject.class, name); } protected MatrixProject createMatrixProject() throws IOException { return createMatrixProject(createUniqueProjectName()); } protected MatrixProject createMatrixProject(String name) throws IOException { return hudson.createProject(MatrixProject.class, name); } protected String createUniqueProjectName() { return "test" + hudson.getItems().size(); } /** * Creates {@link LocalLauncher}. Useful for launching processes. */ protected LocalLauncher createLocalLauncher() { return new LocalLauncher(StreamTaskListener.fromStdout()); } /** * Allocates a new temporary directory for the duration of this test. */ public File createTmpDir() throws IOException { return env.temporaryDirectoryAllocator.allocate(); } public DumbSlave createSlave() throws Exception { return createSlave("", null); } /** * Creates and launches a new slave on the local host. */ public DumbSlave createSlave(Label l) throws Exception { return createSlave(l, null); } /** * Creates a test {@link SecurityRealm} that recognizes username==password * as valid. */ public SecurityRealm createDummySecurityRealm() { return new AbstractPasswordBasedSecurityRealm() { @Override protected UserDetails authenticate(String username, String password) throws AuthenticationException { if (username.equals(password)) { return loadUserByUsername(username); } throw new BadCredentialsException(username); } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { return new org.springframework.security.userdetails.User(username, "", true, true, true, true, new GrantedAuthority[]{AUTHENTICATED_AUTHORITY}); } @Override public GroupDetails loadGroupByGroupname(String groupname) throws UsernameNotFoundException, DataAccessException { throw new UsernameNotFoundException(groupname); } }; } /** * Returns the URL of the webapp top page. URL ends with '/'. */ public URL getURL() throws IOException { return new URL("http://localhost:" + localPort + contextPath + "/"); } public DumbSlave createSlave(EnvVars env) throws Exception { return createSlave("", env); } public DumbSlave createSlave(Label l, EnvVars env) throws Exception { return createSlave(l == null ? null : l.getExpression(), env); } /** * Creates a slave with certain additional environment variables */ public DumbSlave createSlave(String labels, EnvVars env) throws Exception { synchronized (hudson) { // this synchronization block is so that we don't end up adding the same slave name more than once. int sz = hudson.getNodes().size(); DumbSlave slave = new DumbSlave("slave" + sz, "dummy", createTmpDir().getPath(), "1", Mode.NORMAL, labels == null ? "" : labels, createComputerLauncher(env), RetentionStrategy.NOOP, Collections.EMPTY_LIST); hudson.addNode(slave); return slave; } } public PretendSlave createPretendSlave(FakeLauncher faker) throws Exception { synchronized (hudson) { int sz = hudson.getNodes().size(); PretendSlave slave = new PretendSlave("slave" + sz, createTmpDir().getPath(), "", createComputerLauncher(null), faker); hudson.addNode(slave); return slave; } } /** * Creates a {@link CommandLauncher} for launching a slave locally. * * @param env Environment variables to add to the slave process. Can be * null. */ public CommandLauncher createComputerLauncher(EnvVars env) throws URISyntaxException, MalformedURLException { int sz = hudson.getNodes().size(); return new CommandLauncher( String.format("\"%s/bin/java\" %s -jar \"%s\"", System.getProperty("java.home"), SLAVE_DEBUG_PORT > 0 ? " -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=" + (SLAVE_DEBUG_PORT + sz) : "", new File(hudson.getJnlpJars("slave.jar").getURL().toURI()).getAbsolutePath()), env); } /** * Create a new slave on the local host and wait for it to come onilne * before returning. */ public DumbSlave createOnlineSlave() throws Exception { return createOnlineSlave(null); } /** * Create a new slave on the local host and wait for it to come onilne * before returning. */ public DumbSlave createOnlineSlave(Label l) throws Exception { return createOnlineSlave(l, null); } /** * Create a new slave on the local host and wait for it to come online * before returning */ public DumbSlave createOnlineSlave(Label l, EnvVars env) throws Exception { final CountDownLatch latch = new CountDownLatch(1); ComputerListener waiter = new ComputerListener() { @Override public void onOnline(Computer C, TaskListener t) { latch.countDown(); unregister(); } }; waiter.register(); DumbSlave s = createSlave(l, env); latch.await(); return s; } /** * Blocks until the ENTER key is hit. This is useful during debugging a test * so that one can inspect the state of Hudson through the web browser. */ public void interactiveBreak() throws Exception { System.out.println("Hudson is running at http://localhost:" + localPort + "/"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } /** * Returns the last item in the list. */ protected <T> T last(List<T> items) { return items.get(items.size() - 1); } /** * Pauses the execution until ENTER is hit in the console. <p> This is often * very useful so that you can interact with Hudson from an browser, while * developing a test case. */ protected void pause() throws IOException { new BufferedReader(new InputStreamReader(System.in)).readLine(); } /** * Performs a search from the search box. */ protected Page search(String q) throws Exception { return new WebClient().search(q); } /** * Hits the Hudson system configuration and submits without any * modification. */ protected void configRoundtrip() throws Exception { submit(createWebClient().goTo("configure").getFormByName("config")); } /** * Loads a configuration page and submits it without any modifications, to * perform a round-trip configuration test. <p> See * http://wiki.hudson-ci.org/display/HUDSON/Unit+Test#UnitTest-Configurationroundtriptesting */ protected <P extends Job> P configRoundtrip(P job) throws Exception { submit(createWebClient().getPage(job, "configure").getFormByName("config")); return job; } // protected <P extends Item> P configRoundtrip(P job) throws Exception { // submit(createWebClient().getPage(job,"configure").getFormByName("config")); // return job; // } /** * Performs a configuration round-trip testing for a builder. */ protected <B extends Builder> B configRoundtrip(B before) throws Exception { FreeStyleProject p = createFreeStyleProject(); p.getBuildersList().add(before); configRoundtrip(p); return (B) p.getBuildersList().get(before.getClass()); } /** * Performs a configuration round-trip testing for a publisher. */ protected <P extends Publisher> P configRoundtrip(P before) throws Exception { FreeStyleProject p = createFreeStyleProject(); p.getPublishersList().add(before); configRoundtrip(p); return (P) p.getPublishersList().get(before.getClass()); } protected <C extends ComputerConnector> C configRoundtrip(C before) throws Exception { computerConnectorTester.connector = before; submit(createWebClient().goTo("self/computerConnectorTester/configure").getFormByName("config")); return (C) computerConnectorTester.connector; } /** * Asserts that the outcome of the build is a specific outcome. */ public <R extends Run> R assertBuildStatus(Result status, R r) throws Exception { if (status == r.getResult()) { return r; } // dump the build output in failure message String msg = "unexpected build status; build log was:\n------\n" + getLog(r) + "\n------\n"; if (r instanceof MatrixBuild) { MatrixBuild mb = (MatrixBuild) r; for (MatrixRun mr : mb.getRuns()) { msg += "--- " + mr.getParent().getCombination() + " ---\n" + getLog(mr) + "\n------\n"; } } assertEquals(msg, status, r.getResult()); return r; } /** * Determines whether the specifed HTTP status code is generally "good" */ public boolean isGoodHttpStatus(int status) { if ((400 <= status) && (status <= 417)) { return false; } if ((500 <= status) && (status <= 505)) { return false; } return true; } /** * Assert that the specifed page can be served with a "good" HTTP status, * eg, the page is not missing and can be served without a server error * * @param page */ public void assertGoodStatus(Page page) { assertTrue(isGoodHttpStatus(page.getWebResponse().getStatusCode())); } public <R extends Run> R assertBuildStatusSuccess(R r) throws Exception { assertBuildStatus(Result.SUCCESS, r); return r; } public <R extends Run> R assertBuildStatusSuccess(Future<? extends R> r) throws Exception { assertNotNull("build was actually scheduled", r); return assertBuildStatusSuccess(r.get()); } public <J extends AbstractProject<J, R>, R extends AbstractBuild<J, R>> R buildAndAssertSuccess(J job) throws Exception { return assertBuildStatusSuccess(job.scheduleBuild2(0)); } /** * Avoids need for cumbersome {@code this.<J,R>buildAndAssertSuccess(...)} * type hints under JDK 7 javac (and supposedly also IntelliJ). */ public FreeStyleBuild buildAndAssertSuccess(FreeStyleProject job) throws Exception { return assertBuildStatusSuccess(job.scheduleBuild2(0)); } /** * Asserts that the console output of the build contains the given * substring. */ public void assertLogContains(String substring, Run run) throws Exception { String log = getLog(run); if (log.contains(substring)) { return; // good! } System.out.println(log); fail("Console output of " + run + " didn't contain " + substring); } /** * Get entire log file (this method is deprecated in hudson.model.Run, but * in tests it is OK to load entire log). */ protected static String getLog(Run run) throws IOException { return Util.loadFile(run.getLogFile(), run.getCharset()); } /** * Asserts that the XPath matches. */ public void assertXPath(HtmlPage page, String xpath) { assertNotNull("There should be an object that matches XPath:" + xpath, page.getDocumentElement().selectSingleNode(xpath)); } /** * Asserts that the XPath matches the contents of a DomNode page. This * variant of assertXPath(HtmlPage page, String xpath) allows us to examine * XmlPages. * * @param page * @param xpath */ public void assertXPath(DomNode page, String xpath) { List< ? extends Object> nodes = page.getByXPath(xpath); assertFalse("There should be an object that matches XPath:" + xpath, nodes.isEmpty()); } public void assertXPathValue(DomNode page, String xpath, String expectedValue) { Object node = page.getFirstByXPath(xpath); assertNotNull("no node found", node); assertTrue("the found object was not a Node " + xpath, node instanceof org.w3c.dom.Node); org.w3c.dom.Node n = (org.w3c.dom.Node) node; String textString = n.getTextContent(); assertEquals("xpath value should match for " + xpath, expectedValue, textString); } public void assertXPathValueContains(DomNode page, String xpath, String needle) { Object node = page.getFirstByXPath(xpath); assertNotNull("no node found", node); assertTrue("the found object was not a Node " + xpath, node instanceof org.w3c.dom.Node); org.w3c.dom.Node n = (org.w3c.dom.Node) node; String textString = n.getTextContent(); assertTrue("needle found in haystack", textString.contains(needle)); } public void assertXPathResultsContainText(DomNode page, String xpath, String needle) { List<? extends Object> nodes = page.getByXPath(xpath); assertFalse("no nodes matching xpath found", nodes.isEmpty()); boolean found = false; for (Object o : nodes) { if (o instanceof org.w3c.dom.Node) { org.w3c.dom.Node n = (org.w3c.dom.Node) o; String textString = n.getTextContent(); if ((textString != null) && textString.contains(needle)) { found = true; break; } } } assertTrue("needle found in haystack", found); } public void assertStringContains(String message, String haystack, String needle) { if (haystack.contains(needle)) { // good return; } else { fail(message + " (seeking '" + needle + "')"); } } public void assertStringContains(String haystack, String needle) { if (haystack.contains(needle)) { // good return; } else { fail("Could not find '" + needle + "'."); } } /** * Asserts that help files exist for the specified properties of the given * instance. * * @param type The describable class type that should have the associated * help files. * @param properties ','-separated list of properties whose help files * should exist. */ public void assertHelpExists(final Class<? extends Describable> type, final String properties) throws Exception { executeOnServer(new Callable<Object>() { public Object call() throws Exception { Descriptor d = hudson.getDescriptor(type); WebClient wc = createWebClient(); for (String property : listProperties(properties)) { String url = d.getHelpFile(property); assertNotNull("Help file for the property " + property + " is missing on " + type, url); wc.goTo(url); // make sure it successfully loads } return null; } }); } /** * Tokenizes "foo,bar,zot,-bar" and returns "foo,zot" (the token that starts * with '-' is handled as a cancellation. */ private List<String> listProperties(String properties) { List<String> props = new ArrayList<String>(Arrays.asList(properties.split(","))); for (String p : props.toArray(new String[props.size()])) { if (p.startsWith("-")) { props.remove(p); props.remove(p.substring(1)); } } return props; } /** * Submits the form. * * Plain {@link HtmlForm#submit()} doesn't work correctly due to the use of * YUI in Hudson. */ public HtmlPage submit(HtmlForm form) throws Exception { List<HtmlButton> buttons = form.getHtmlElementsByTagName("button"); if ((buttons != null) && (buttons.size() > 0)) { HtmlButton button = (HtmlButton) last(form.getHtmlElementsByTagName("button")); return (HtmlPage) form.submit(button); } else { return (HtmlPage) form.submit(); } } /** * Submits the form by clikcing the submit button of the given name. * * @param name This corresponds to the * @name of &lt;f:submit /> */ public HtmlPage submit(HtmlForm form, String name) throws Exception { for (HtmlElement e : form.getHtmlElementsByTagName("button")) { HtmlElement p = (HtmlElement) e.getParentNode().getParentNode(); if (p.getAttribute("name").equals(name)) { // To make YUI event handling work, this combo seems to be necessary // the click will trigger _onClick in buton-*.js, but it doesn't submit the form // (a comment alluding to this behavior can be seen in submitForm method) // so to complete it, submit the form later. // // Just doing form.submit() doesn't work either, because it doesn't do // the preparation work needed to pass along the name of the button that // triggered a submission (more concretely, m_oSubmitTrigger is not set.) ((HtmlButton) e).click(); return (HtmlPage) form.submit((HtmlButton) e); } } for (HtmlElement e : form.getHtmlElementsByTagName("input")) { if (e.getAttribute("name").equals(name)) { ((HtmlInput) e).click(); return (HtmlPage) form.submit((HtmlInput) e); } } throw new AssertionError("No such submit button with the name " + name); } protected HtmlInput findPreviousInputElement(HtmlElement current, String name) { return (HtmlInput) current.selectSingleNode("(preceding::input[@name='_." + name + "'])[last()]"); } protected HtmlButton getButtonByCaption(HtmlForm f, String s) { for (HtmlElement b : f.getHtmlElementsByTagName("button")) { if (b.getTextContent().trim().equals(s)) { return (HtmlButton) b; } } return null; } protected HtmlInput getInputByName(HtmlForm f, String name) { for (HtmlElement b : f.getHtmlElementsByTagName("button")) { if (b.getAttribute("name").equals(name)) { return (HtmlInput) b; } } return null; } /** * Creates a {@link TaskListener} connected to stdout. */ public TaskListener createTaskListener() { return new StreamTaskListener(new CloseProofOutputStream(System.out)); } /** * Asserts that two JavaBeans are equal as far as the given list of * properties are concerned. * * <p> This method takes two objects that have properties (getXyz, isXyz, or * just the public xyz field), and makes sure that the property values for * each given property are equals (by using * {@link #assertEquals(Object, Object)}) * * <p> Property values can be null on both objects, and that is OK, but * passing in a property that doesn't exist will fail an assertion. * * <p> This method is very convenient for comparing a large number of * properties on two objects, for example to verify that the configuration * is identical after a config screen roundtrip. * * @param lhs One of the two objects to be compared. * @param rhs The other object to be compared * @param properties ','-separated list of property names that are compared. * @since 1.297 */ public void assertEqualBeans(Object lhs, Object rhs, String properties) throws Exception { assertNotNull("lhs is null", lhs); assertNotNull("rhs is null", rhs); for (String p : properties.split(",")) { PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(lhs, p); Object lp, rp; if (pd == null) { // field? try { Field f = lhs.getClass().getField(p); lp = f.get(lhs); rp = f.get(rhs); } catch (NoSuchFieldException e) { assertNotNull("No such property " + p + " on " + lhs.getClass(), pd); return; } } else { lp = PropertyUtils.getProperty(lhs, p); rp = PropertyUtils.getProperty(rhs, p); } if (lp != null && rp != null && lp.getClass().isArray() && rp.getClass().isArray()) { // deep array equality comparison int m = Array.getLength(lp); int n = Array.getLength(rp); assertEquals("Array length is different for property " + p, m, n); for (int i = 0; i < m; i++) { assertEquals(p + "[" + i + "] is different", Array.get(lp, i), Array.get(rp, i)); } return; } assertEquals("Property " + p + " is different", lp, rp); } } /** * Works like {@link #assertEqualBeans(Object, Object, String)} but figure * out the properties via {@link DataBoundConstructor} */ public void assertEqualDataBoundBeans(Object lhs, Object rhs) throws Exception { if (lhs == null && rhs == null) { return; } if (lhs == null) { fail("lhs is null while rhs=" + rhs); } if (rhs == null) { fail("rhs is null while lhs=" + rhs); } Constructor<?> lc = findDataBoundConstructor(lhs.getClass()); Constructor<?> rc = findDataBoundConstructor(rhs.getClass()); assertEquals("Data bound constructor mismatch. Different type?", lc, rc); List<String> primitiveProperties = new ArrayList<String>(); String[] names = ClassDescriptor.loadParameterNames(lc); Class<?>[] types = lc.getParameterTypes(); assertEquals(names.length, types.length); for (int i = 0; i < types.length; i++) { Object lv = ReflectionUtils.getPublicProperty(lhs, names[i]); Object rv = ReflectionUtils.getPublicProperty(rhs, names[i]); if (Iterable.class.isAssignableFrom(types[i])) { Iterable lcol = (Iterable) lv; Iterable rcol = (Iterable) rv; Iterator ltr, rtr; for (ltr = lcol.iterator(), rtr = rcol.iterator(); ltr.hasNext() && rtr.hasNext();) { Object litem = ltr.next(); Object ritem = rtr.next(); if (findDataBoundConstructor(litem.getClass()) != null) { assertEqualDataBoundBeans(litem, ritem); } else { assertEquals(litem, ritem); } } assertFalse("collection size mismatch between " + lhs + " and " + rhs, ltr.hasNext() ^ rtr.hasNext()); } else if (findDataBoundConstructor(types[i]) != null) { // recurse into nested databound objects assertEqualDataBoundBeans(lv, rv); } else { primitiveProperties.add(names[i]); } } // compare shallow primitive properties if (!primitiveProperties.isEmpty()) { assertEqualBeans(lhs, rhs, Util.join(primitiveProperties, ",")); } } private Constructor<?> findDataBoundConstructor(Class<?> c) { for (Constructor<?> m : c.getConstructors()) { if (m.getAnnotation(DataBoundConstructor.class) != null) { return m; } } return null; } /** * Gets the descriptor instance of the current Hudson by its type. */ protected <T extends Descriptor<?>> T get(Class<T> d) { return hudson.getDescriptorByType(d); } /** * Returns true if Hudson is building something or going to build something. */ protected boolean isSomethingHappening() { if (!hudson.getQueue().isEmpty()) { return true; } for (Computer n : hudson.getComputers()) { if (!n.isIdle()) { return true; } } return false; } /** * Waits until Hudson finishes building everything, including those in the * queue. <p> This method uses a default time out to prevent infinite hang * in the automated test execution environment. */ protected void waitUntilNoActivity() throws Exception { waitUntilNoActivityUpTo(60 * 1000); } /** * Waits until Hudson finishes building everything, including those in the * queue, or fail the test if the specified timeout milliseconds is */ protected void waitUntilNoActivityUpTo(int timeout) throws Exception { long startTime = System.currentTimeMillis(); int streak = 0; while (true) { Thread.sleep(10); if (isSomethingHappening()) { streak = 0; } else { streak++; } // the system is quiet for a while if (streak > 5) { return; } if (System.currentTimeMillis() - startTime > timeout) { List<Executable> building = new ArrayList<Executable>(); for (Computer c : hudson.getComputers()) { for (Executor e : c.getExecutors()) { if (e.isBusy()) { building.add(e.getCurrentExecutable()); } } } throw new AssertionError(String.format("Hudson is still doing something after %dms: queue=%s building=%s", timeout, Arrays.asList(hudson.getQueue().getItems()), building)); } } } // // recipe methods. Control the test environments. // /** * Called during the {@link #setUp()} to give a test case an opportunity to * control the test environment in which Hudson is run. * * <p> One could override this method and call a series of {@code withXXX} * methods, or you can use the annotations with {@link Recipe} * meta-annotation. */ protected void recipe() throws Exception { recipeLoadCurrentPlugin(); // look for recipe meta-annotation try { Method runMethod = getClass().getMethod(getName()); for (final Annotation a : runMethod.getAnnotations()) { Recipe r = a.annotationType().getAnnotation(Recipe.class); if (r == null) { continue; } final Runner runner = r.value().newInstance(); recipes.add(runner); tearDowns.add(new LenientRunnable() { public void run() throws Exception { runner.tearDown(HudsonTestCase.this, a); } }); runner.setup(this, a); } } catch (NoSuchMethodException e) { // not a plain JUnit test. } } /** * If this test harness is launched for a Hudson plugin, locate the * <tt>target/test-classes/the.hpl</tt> and add a recipe to install that to * the new Hudson. * * <p> This file is created by <tt>maven-hpi-plugin</tt> at the testCompile * phase when the current packaging is <tt>hpi</tt>. */ protected void recipeLoadCurrentPlugin() throws Exception { final Enumeration<URL> e = getClass().getClassLoader().getResources("the.hpl"); if (!e.hasMoreElements()) { return; // nope } recipes.add(new Runner() { @Override public void decorateHome(HudsonTestCase testCase, File home) throws Exception { while (e.hasMoreElements()) { final URL hpl = e.nextElement(); // make the plugin itself available Manifest m = new Manifest(hpl.openStream()); String shortName = m.getMainAttributes().getValue("Short-Name"); if (shortName == null) { throw new Error(hpl + " doesn't have the Short-Name attribute"); } FileUtils.copyURLToFile(hpl, new File(home, "plugins/" + shortName + ".hpl")); // make dependency plugins available // TODO: probably better to read POM, but where to read from? // TODO: this doesn't handle transitive dependencies // Tom: plugins are now searched on the classpath first. They should be available on // the compile or test classpath. As a backup, we do a best-effort lookup in the Maven repository // For transitive dependencies, we could evaluate Plugin-Dependencies transitively. String dependencies = m.getMainAttributes().getValue("Plugin-Dependencies"); if (dependencies != null) { MavenRequest mavenRequest = MavenUtil.createMavenRequest(new StreamTaskListener(System.out,Charset.defaultCharset())); MavenEmbedder embedder = new MavenEmbedder(getClass().getClassLoader(), mavenRequest); for (String dep : dependencies.split(",")) { String[] tokens = dep.split(":"); String artifactId = tokens[0]; String version = tokens[1]; File dependencyJar = null; // need to search multiple group IDs // TODO: extend manifest to include groupID:artifactID:version Exception resolutionError = null; for (String groupId : new String[]{"org.hudsonci.plugins", "org.jvnet.hudson.plugins", "org.jvnet.hudson.main"}) { // first try to find it on the classpath. // this takes advantage of Maven POM located in POM URL dependencyPomResource = getClass().getResource("/META-INF/maven/" + groupId + "/" + artifactId + "/pom.xml"); if (dependencyPomResource != null) { // found it dependencyJar = Which.jarFile(dependencyPomResource); break; } else { Artifact a; a = embedder.createArtifact(groupId, artifactId, version, "compile"/*doesn't matter*/, "hpi"); try { embedder.resolve(a, Arrays.asList(embedder.createRepository("https://oss.sonatype.org/content/repositories/releases/", "repo")), embedder.getLocalRepository()); dependencyJar = a.getFile(); } catch (AbstractArtifactResolutionException x) { // could be a wrong groupId resolutionError = x; } } } if (dependencyJar == null) { throw new Exception("Failed to resolve plugin: " + dep, resolutionError); } File dst = new File(home, "plugins/" + artifactId + ".hpi"); if (!dst.exists() || dst.lastModified() != dependencyJar.lastModified()) { FileUtils.copyFile(dependencyJar, dst); } } } } } }); } public HudsonTestCase withNewHome() { return with(HudsonHomeLoader.NEW); } public HudsonTestCase withExistingHome(File source) throws Exception { return with(new CopyExisting(source)); } /** * Declares that this test case expects to start with one of the preset data * sets. See * https://svn.dev.java.net/svn/hudson/trunk/hudson/main/test/src/main/preset-data/ * for available datasets and what they mean. */ public HudsonTestCase withPresetData(String name) { name = "/" + name + ".zip"; URL res = getClass().getResource(name); if (res == null) { throw new IllegalArgumentException("No such data set found: " + name); } return with(new CopyExisting(res)); } public HudsonTestCase with(HudsonHomeLoader homeLoader) { this.homeLoader = homeLoader; return this; } /** * Executes the given closure on the server, by the servlet request handling * thread, in the context of an HTTP request. * * <p> In {@link HudsonTestCase}, a thread that's executing the test code is * different from the thread that carries out HTTP requests made through * {@link WebClient}. But sometimes you want to make assertions and other * calls with side-effect from within the request handling thread. * * <p> This method allows you to do just that. It is useful for testing some * methods that require {@link StaplerRequest} and {@link StaplerResponse}, * or getting the credential of the current user (via * {@link Hudson#getAuthentication()}, and so on. * * @param c The closure to be executed on the server. * @return The return value from the closure. * @throws Exception If a closure throws any exception, that exception will * be carried forward. */ public <V> V executeOnServer(final Callable<V> c) throws Exception { final Exception[] t = new Exception[1]; final List<V> r = new ArrayList<V>(1); // size 1 list ClosureExecuterAction cea = hudson.getExtensionList(RootAction.class).get(ClosureExecuterAction.class); UUID id = UUID.randomUUID(); cea.add(id, new Runnable() { public void run() { try { StaplerResponse rsp = Stapler.getCurrentResponse(); rsp.setStatus(200); rsp.setContentType("text/html"); r.add(c.call()); } catch (Exception e) { t[0] = e; } } }); createWebClient().goTo("closures/?uuid=" + id); if (t[0] != null) { throw t[0]; } return r.get(0); } /** * Sometimes a part of a test case may ends up creeping into the * serialization tree of {@link Saveable#save()}, so detect that and flag * that as an error. */ private Object writeReplace() { throw new AssertionError("HudsonTestCase " + getName() + " is not supposed to be serialized"); } /** * This is to assist Groovy test clients who are incapable of instantiating * the inner classes properly. */ public WebClient createWebClient() { return new WebClient(); } /** * Extends {@link com.gargoylesoftware.htmlunit.WebClient} and provide * convenience methods for accessing Hudson. */ public class WebClient extends com.gargoylesoftware.htmlunit.WebClient { public WebClient() { // default is IE6, but this causes 'n.doScroll('left')' to fail in event-debug.js:1907 as HtmlUnit doesn't implement such a method, // so trying something else, until we discover another problem. super(BrowserVersion.FIREFOX_3); // setJavaScriptEnabled(false); setPageCreator(HudsonPageCreator.INSTANCE); clients.add(new WeakReference<WebClient>(this)); // make ajax calls run as post-action for predictable behaviors that simplify debugging setAjaxController(new AjaxController() { public boolean processSynchron(HtmlPage page, WebRequestSettings settings, boolean async) { return false; } }); setCssErrorHandler(new ErrorHandler() { final ErrorHandler defaultHandler = new DefaultCssErrorHandler(); public void warning(CSSParseException exception) throws CSSException { if (!ignore(exception)) { defaultHandler.warning(exception); } } public void error(CSSParseException exception) throws CSSException { if (!ignore(exception)) { defaultHandler.error(exception); } } public void fatalError(CSSParseException exception) throws CSSException { if (!ignore(exception)) { defaultHandler.fatalError(exception); } } private boolean ignore(CSSParseException e) { return e.getURI().contains("/yui/"); } }); // if no other debugger is installed, install jsDebugger, // so as not to interfere with the 'Dim' class. getJavaScriptEngine().getContextFactory().addListener(new Listener() { public void contextCreated(Context cx) { if (cx.getDebugger() == null) { cx.setDebugger(jsDebugger, null); } } public void contextReleased(Context cx) { } }); } /** * Logs in to Hudson. */ public WebClient login(String username, String password) throws Exception { HtmlPage page = goTo("/login"); // page = (HtmlPage) page.getFirstAnchorByText("Login").click(); HtmlForm form = page.getFormByName("login"); form.getInputByName("j_username").setValueAttribute(username); form.getInputByName("j_password").setValueAttribute(password); form.submit(null); return this; } /** * Logs in to Hudson, by using the user name as the password. * * <p> See {@link HudsonTestCase#configureUserRealm()} for how the * container is set up with the user names and passwords. All the test * accounts have the same user name and password. */ public WebClient login(String username) throws Exception { login(username, username); return this; } public HtmlPage search(String q) throws IOException, SAXException { HtmlPage top = goTo(""); HtmlForm search = top.getFormByName("search"); search.getInputByName("q").setValueAttribute(q); return (HtmlPage) search.submit(null); } /** * Short for {@code getPage(r,"")}, to access the top page of a build. */ public HtmlPage getPage(Run r) throws IOException, SAXException { return getPage(r, ""); } /** * Accesses a page inside {@link Run}. * * @param relative Relative URL within the build URL, like "changes". * Doesn't start with '/'. Can be empty. */ public HtmlPage getPage(Run r, String relative) throws IOException, SAXException { return goTo(r.getUrl() + relative); } public HtmlPage getPage(Item item) throws IOException, SAXException { return getPage(item, ""); } public HtmlPage getPage(Item item, String relative) throws IOException, SAXException { return goTo(item.getUrl() + relative); } public HtmlPage getPage(Node item) throws IOException, SAXException { return getPage(item, ""); } public HtmlPage getPage(Node item, String relative) throws IOException, SAXException { return goTo(item.toComputer().getUrl() + relative); } public HtmlPage getPage(View view) throws IOException, SAXException { return goTo(view.getUrl()); } public HtmlPage getPage(View view, String relative) throws IOException, SAXException { return goTo(view.getUrl() + relative); } /** * @deprecated This method expects a full URL. This method is marked as * deprecated to warn you that you probably should be using * {@link #goTo(String)} method, which accepts a relative path within * the Hudson being tested. (IOW, if you really need to hit a website on * the internet, there's nothing wrong with using this method.) */ @Override public Page getPage(String url) throws IOException, FailingHttpStatusCodeException { return super.getPage(url); } /** * Requests a page within Hudson. * * @param relative Relative path within Hudson. Starts without '/'. For * example, "job/test/" to go to a job top page. */ public HtmlPage goTo(String relative) throws IOException, SAXException { Page p = goTo(relative, "text/html"); if (p instanceof HtmlPage) { return (HtmlPage) p; } else { throw new AssertionError("Expected text/html but instead the content type was " + p.getWebResponse().getContentType()); } } public Page goTo(String relative, String expectedContentType) throws IOException, SAXException { Page p = super.getPage(getContextPath() + relative); assertEquals(expectedContentType, p.getWebResponse().getContentType()); return p; } /** * Loads a page as XML. Useful for testing Hudson's xml api, in concert * with assertXPath(DomNode page, String xpath) * * @param path the path part of the url to visit * @return the XmlPage found at that url * @throws IOException * @throws SAXException */ public XmlPage goToXml(String path) throws IOException, SAXException { Page page = goTo(path, "application/xml"); if (page instanceof XmlPage) { return (XmlPage) page; } else { return null; } } /** * Returns the URL of the webapp top page. URL ends with '/'. */ public String getContextPath() throws IOException { return getURL().toExternalForm(); } /** * Adds a security crumb to the quest */ public WebRequestSettings addCrumb(WebRequestSettings req) { NameValuePair crumb[] = {new NameValuePair()}; crumb[0].setName(hudson.getCrumbIssuer().getDescriptor().getCrumbRequestField()); crumb[0].setValue(hudson.getCrumbIssuer().getCrumb(null)); req.setRequestParameters(Arrays.asList(crumb)); return req; } /** * Creates a URL with crumb parameters relative to * {{@link #getContextPath()} */ public URL createCrumbedUrl(String relativePath) throws IOException { CrumbIssuer issuer = hudson.getCrumbIssuer(); String crumbName = issuer.getDescriptor().getCrumbRequestField(); String crumb = issuer.getCrumb(null); return new URL(getContextPath() + relativePath + "?" + crumbName + "=" + crumb); } /** * Makes an HTTP request, process it with the given request handler, and * returns the response. */ public HtmlPage eval(final Runnable requestHandler) throws IOException, SAXException { ClosureExecuterAction cea = hudson.getExtensionList(RootAction.class).get(ClosureExecuterAction.class); UUID id = UUID.randomUUID(); cea.add(id, requestHandler); return goTo("closures/?uuid=" + id); } /** * Starts an interactive JavaScript debugger, and break at the next * JavaScript execution. * * <p> This is useful during debugging a test so that you can step * execute and inspect state of JavaScript. This will launch a Swing * GUI, and the method returns immediately. * * <p> Note that installing a debugger appears to make an execution of * JavaScript substantially slower. * * <p> TODO: because each script block evaluation in HtmlUnit is done in * a separate Rhino context, if you step over from one script block, the * debugger fails to kick in on the beginning of the next script block. * This makes it difficult to set a break point on arbitrary script * block in the HTML page. We need to fix this by tweaking * {@link Dim.StackFrame#onLineChange(Context, int)}. */ public Dim interactiveJavaScriptDebugger() { Global global = new Global(); HtmlUnitContextFactory cf = getJavaScriptEngine().getContextFactory(); global.init(cf); Dim dim = org.mozilla.javascript.tools.debugger.Main.mainEmbedded(cf, global, "Rhino debugger: " + getName()); // break on exceptions. this catch most of the errors dim.setBreakOnExceptions(true); return dim; } } // needs to keep reference, or it gets GC-ed. private static final Logger XML_HTTP_REQUEST_LOGGER = Logger.getLogger(XMLHttpRequest.class.getName()); static { // screen scraping relies on locale being fixed. Locale.setDefault(Locale.ENGLISH); {// enable debug assistance, since tests are often run from IDE Dispatcher.TRACE = true; MetaClass.NO_CACHE = true; // load resources from the source dir. File dir = new File("src/main/resources"); if (dir.exists() && MetaClassLoader.debugLoader == null) { try { MetaClassLoader.debugLoader = new MetaClassLoader( new URLClassLoader(new URL[]{dir.toURI().toURL()})); } catch (MalformedURLException e) { throw new AssertionError(e); } } } // suppress INFO output from Spring, which is verbose Logger.getLogger("org.springframework").setLevel(Level.WARNING); // hudson-behavior.js relies on this to decide whether it's running unit tests. Main.isUnitTest = true; // prototype.js calls this method all the time, so ignore this warning. XML_HTTP_REQUEST_LOGGER.setFilter(new Filter() { public boolean isLoggable(LogRecord record) { return !record.getMessage().contains("XMLHttpRequest.getResponseHeader() was called before the response was available."); } }); // remove the upper bound of the POST data size in Jetty. System.setProperty("org.mortbay.jetty.Request.maxFormContentSize", "-1"); } private static final Logger LOGGER = Logger.getLogger(HudsonTestCase.class.getName()); protected static final List<ToolProperty<?>> NO_PROPERTIES = Collections.<ToolProperty<?>>emptyList(); /** * Specify this to a TCP/IP port number to have slaves started with the * debugger. */ public static int SLAVE_DEBUG_PORT = Integer.getInteger(HudsonTestCase.class.getName() + ".slaveDebugPort", -1); public static final MimeTypes MIME_TYPES = new MimeTypes(); static { MIME_TYPES.addMimeMapping("js", "application/javascript"); Functions.DEBUG_YUI = true; // during the unit test, predictably releasing classloader is important to avoid // file descriptor leak. ClassicPluginStrategy.useAntClassLoader = true; // DNS multicast support takes up a lot of time during tests, so just disable it altogether // this also prevents tests from falsely advertising Hudson DNSMultiCast.disabled = true; } }
apache-2.0
Biocodr/TomP2P
replication/src/main/java/net/tomp2p/synchronization/RSync.java
8242
/* * Copyright 2013 Maxat Pernebayev, Thomas Bocek * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package net.tomp2p.synchronization; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.tomp2p.storage.DataBuffer; import net.tomp2p.utils.Utils; /** * Synchronization class is responsible for efficient and optimal * synchronization of data resources between responsible peer and replica peers. * If one of replicas goes offline, the responsible peer transfers the value * completely to the new replica peer. In case the values at responsible peer * and replica peer are the same, then no data is transmitted. If the values are * different, then only differences are sent to the replica peer. * * @author Maxat Pernebayev * @author Thomas Bocek * */ final public class RSync { /** * It returns an array of weak and strong checksums for the value. * * @param value * The value * @param size * The offset size * @return The array of checksums * @throws NoSuchAlgorithmException */ public static List<Checksum> checksums(final byte[] value, final int blockSize) { final int numberOfBlocks = (value.length + blockSize - 1) / blockSize; final ArrayList<Checksum> checksums = new ArrayList<Checksum>(numberOfBlocks); final RollingChecksum adler = new RollingChecksum(); for (int i = 0; i < numberOfBlocks; i++) { int remaining = Math.min(blockSize, value.length - (i * blockSize)); adler.reset().update(value, i * blockSize, remaining); final int weakChecksum = adler.value(); final byte[] strongChecksum = Utils.makeMD5Hash(value, i * blockSize, remaining); checksums.add(new Checksum(weakChecksum, strongChecksum)); } return checksums; } /** * It checks whether a match is found or not. If it is found returns * reference otherwise -1. * * @param wcs * The weak checksum of offset * @param offset * The offset * @param checksums * The checksums * @return either the reference or -1 */ private static int matches(int wcs, byte[] buffer, int offset, int length, List<Checksum> checksums) { int checksumSize = checksums.size(); //TODO: hashing might be a better idea, for now it works for (int i = 0; i < checksumSize; i++) { int weakChecksum = checksums.get(i).weakChecksum(); if (weakChecksum == wcs) { byte[] md5 = Utils.makeMD5Hash(buffer, offset, length); byte[] strongChecksum = checksums.get(i).strongChecksum(); if (Arrays.equals(strongChecksum, md5)) { return i; } } } // no match found, content is different return -1; } /** * It returns the sequence of instructions each of which contains either * reference to a block or literal data. * * @param array * The value at responsible peer * @param checksums * The array of checksums * @param blockSize * The block size * @return The sequence of instructions */ public static List<Instruction> instructions(byte[] array, List<Checksum> checksums, int blockSize) { final List<Instruction> result = new ArrayList<Instruction>(checksums.size()); final RollingChecksum adler = new RollingChecksum(); final int length = array.length; int offset = 0; int lastRefFound = 0; int remaining = Math.min(blockSize, length - offset); adler.update(array, offset, remaining); for (;;) { final int wcs = adler.value(); final int reference = matches(wcs, array, offset, remaining, checksums); if (reference != -1) { if (offset > lastRefFound) { result.add(new Instruction(new DataBuffer(array, lastRefFound, offset - lastRefFound))); } result.add(new Instruction(reference)); offset += remaining; lastRefFound = offset; remaining = Math.min(blockSize, length - offset); if (remaining == 0) { break; } adler.reset().update(array, offset, remaining); } else { offset++; if (blockSize > length - offset) { break; } adler.updateRolling(array); } } if (length > lastRefFound) { result.add(new Instruction(new DataBuffer(array, lastRefFound, length - lastRefFound))); } return result; } /** * It reconstructs the copy of responsible peer's value using instructions * and the replica's value. * * @param value * The value at replica * @param instructions * The sequence of instructions * @param blockSize * The offset size * @return The value which is identical to the responsible peer's value */ public static DataBuffer reconstruct(byte[] value, List<Instruction> instructions, int blockSize) { DataBuffer result = new DataBuffer(); for (Instruction instruction : instructions) { int ref = instruction.reference(); if (ref != -1) { int offset = blockSize * ref; int remaining = Math.min(blockSize, value.length - offset); result.add(new DataBuffer(value, offset, remaining)); } else { result.add(instruction.literal()); } } return result; } /** * Variation of Adler as used in Rsync. Inspired by: * * <pre> * https://github.com/epeli/rollsum/blob/master/ref/adler32.py * http://stackoverflow.com/questions/9699315/differences-in-calculation-of-adler32-rolling-checksum-python * http://de.wikipedia.org/wiki/Adler-32 * http://developer.classpath.org/doc/java/util/zip/Adler32-source.html * </pre> * * @author Thomas Bocek * */ public static class RollingChecksum { private int a = 1; private int b = 0; private int length; private int offset; /** * Resets the checksum to its initial state 1. * * @return this class */ public RollingChecksum reset() { a = 1; b = 0; return this; } /** * Iterates over the array and calculates a variation of Adler. * * @param array * The array for the checksum calculation * @param offset * The offset of the array * @param length * The length of the data to iterate over (the length of the * sliding window). Once this is set, * {@link #updateRolling(byte[])} will use the same value * @return this class */ public RollingChecksum update(final byte[] array, final int offset, final int length) { for (int i = 0; i < length; i++) { a = (a + (array[i + offset] & 0xff)) & 0xffff; b = (b + a) & 0xffff; } this.length = length; this.offset = offset; return this; } /** * @return The calculated checksum */ public int value() { return (b << 16) | a; } /** * Sets the checksum to this value. * * @param checksum * The checksum to set * @return this class */ public RollingChecksum value(final int checksum) { a = checksum & 0xffff; b = checksum >>> 16; return this; } /** * Slide the window of the array by 1. * * @param array * The array for the checksum calculation * @param offset * The offset of the array * @return this class */ public RollingChecksum updateRolling(final byte[] array) { final int removeIndex = offset; final int addIndex = offset + length; offset++; a = (a - (array[removeIndex] & 0xff) + (array[addIndex] & 0xff)) & 0xffff; b = (b - (length * (array[removeIndex] & 0xff)) + a - 1) & 0xffff; return this; } } }
apache-2.0
leebihao/leebihao_git_https
DongFengNews/src/com/lbh/dongfengnews/utils/PrefUtils.java
1122
package com.lbh.dongfengnews.utils; import android.content.Context; import android.content.SharedPreferences; /** * SharePreference封装 * * @author Kevin * */ public class PrefUtils { public static final String PREF_NAME = "config"; public static boolean getBoolean(Context ctx, String key, boolean defaultValue) { SharedPreferences sp = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); return sp.getBoolean(key, defaultValue); } public static void setBoolean(Context ctx, String key, boolean value) { SharedPreferences sp = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); sp.edit().putBoolean(key, value).commit(); } public static String getString(Context context, String key, String defaultValue) { SharedPreferences sp = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); return sp.getString(key, defaultValue); } public static void setString(Context context, String key, String value) { SharedPreferences sp = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); sp.edit().putString(key, value).commit(); } }
apache-2.0
jmptrader/Strata
modules/report/src/main/java/com/opengamma/strata/report/trade/TradeReportFormatter.java
2950
/** * Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.report.trade; import static com.opengamma.strata.collect.Guavate.toImmutableList; import java.util.List; import java.util.stream.IntStream; import com.opengamma.strata.collect.Messages; import com.opengamma.strata.collect.result.Result; import com.opengamma.strata.report.framework.format.FormatCategory; import com.opengamma.strata.report.framework.format.FormatSettings; import com.opengamma.strata.report.framework.format.ReportFormatter; import com.opengamma.strata.report.framework.format.ReportOutputFormat; import com.opengamma.strata.report.framework.format.ValueFormatters; /** * Formatter for trade reports. */ public class TradeReportFormatter extends ReportFormatter<TradeReport> { /** * The single shared instance of this report formatter. */ public static final TradeReportFormatter INSTANCE = new TradeReportFormatter(); // restricted constructor private TradeReportFormatter() { super(FormatSettings.of(FormatCategory.TEXT, ValueFormatters.UNSUPPORTED)); } //------------------------------------------------------------------------- @Override protected List<Class<?>> getColumnTypes(TradeReport report) { return IntStream.range(0, report.getColumnCount()) .mapToObj(columnIndex -> columnType(report, columnIndex)) .collect(toImmutableList()); } // TODO This would be unnecessary if measures had a data type /** * Returns the data type for the values in a column of a trade report. * <p> * The results in the column are examined and the type of the first successful value is returned. If all values * are failures then {@code Object.class} is returned. * * @param report a trade report * @param columnIndex the index of a column in the report * @return the data type of the values in the column or {@code Object.class} if all results are failures */ @SuppressWarnings({"unchecked", "rawtypes"}) private static Class<?> columnType(TradeReport report, int columnIndex) { return report.getData().rowKeySet().stream() .map(rowIndex -> report.getData().get(rowIndex, columnIndex)) .filter(Result::isSuccess) .map(Result::getValue) .map(Object::getClass) .findFirst() .orElse((Class) Object.class); // raw type needed for Eclipse } @Override protected String formatData(TradeReport report, int rowIdx, int colIdx, ReportOutputFormat format) { TradeReportColumn templateColumn = report.getColumns().get(colIdx); Result<?> result = report.getData().get(rowIdx, colIdx); if (result.isFailure()) { return templateColumn.isIgnoreFailures() ? "" : Messages.format("FAIL: {}", result.getFailure().getMessage()); } Object value = result.getValue(); return formatValue(value, format); } }
apache-2.0
hieple7985/nano-go-ubiquitous
mobile/src/main/java/com/example/android/sunshine/app/sync/SunshineWearListenerService.java
825
package com.example.android.sunshine.app.sync; import com.google.android.gms.wearable.DataEvent; import com.google.android.gms.wearable.DataEventBuffer; import com.google.android.gms.wearable.WearableListenerService; public class SunshineWearListenerService extends WearableListenerService { public static final String WEAR_SYNC_REQUEST = "/SunshineWearListenerService/Sync"; @Override public void onDataChanged(DataEventBuffer dataEvents) { for (int i = 0; i < dataEvents.getCount(); i++) { DataEvent event = dataEvents.get(i); if (event.getType() == DataEvent.TYPE_CHANGED && event.getDataItem().getUri().getPath().equals(WEAR_SYNC_REQUEST)) { SunshineSyncAdapter.syncImmediately(getApplicationContext()); } } } }
apache-2.0
mscharhag/blog-examples
spring-json-schema/src/main/java/com/mscharhag/springjsonschema/painting/Dimension.java
579
package com.mscharhag.springjsonschema.painting; public class Dimension { private float width; private float height; public float getWidth() { return width; } public void setWidth(float width) { this.width = width; } public float getHeight() { return height; } public void setHeight(float height) { this.height = height; } @Override public String toString() { return "Dimension{" + "width=" + width + ", height=" + height + '}'; } }
apache-2.0
smb510/twitterbyName
twitter4j-async/src/test/java/twitter4j/AsyncTwitterTest.java
29482
/* * Copyright 2007 Yusuke Yamamoto * * 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 twitter4j; import twitter4j.api.HelpResources; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken; import java.io.*; import java.util.Date; import java.util.List; import java.util.Map; /** * @author Yusuke Yamamoto - yusuke at mac.com */ public class AsyncTwitterTest extends TwitterTestBase implements TwitterListener { private AsyncTwitter async1 = null; private AsyncTwitter async2 = null; private AsyncTwitter async3 = null; private AsyncTwitter bestFriend1Async = null; private ResponseList<Location> locations; private ResponseList<Place> places; private Place place; private ResponseList<Category> categories; private AccountTotals totals; private AccountSettings settings; private ResponseList<Friendship> friendships; private ResponseList<UserList> userLists; private ResponseList<HelpResources.Language> languages; private TwitterAPIConfiguration apiConf; private SavedSearch savedSearch; private ResponseList<SavedSearch> savedSearches; private OEmbed oembed; public AsyncTwitterTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); AsyncTwitterFactory factory = new AsyncTwitterFactory(conf1); async1 = factory.getInstance(); async1.addListener(this); async2 = new AsyncTwitterFactory(conf2).getInstance(); async2.addListener(this); async3 = new AsyncTwitterFactory(conf3).getInstance(); async3.addListener(this); bestFriend1Async = new AsyncTwitterFactory(bestFriend1Conf).getInstance(); bestFriend1Async.addListener(this); statuses = null; users = null; messages = null; status = null; user = null; user = null; message = null; te = null; } protected void tearDown() throws Exception { super.tearDown(); } public void testShowUser() throws Exception { async1.showUser(id1.screenName); waitForResponse(); User user = this.user; assertEquals(id1.screenName, user.getScreenName()); assertTrue(0 <= user.getFavouritesCount()); assertTrue(0 <= user.getFollowersCount()); assertTrue(0 <= user.getFriendsCount()); assertTrue(0 <= user.getStatusesCount()); assertNotNull(user.getProfileBackgroundColor()); assertNotNull(user.getProfileTextColor()); assertNotNull(user.getProfileLinkColor()); assertNotNull(user.getProfileSidebarBorderColor()); assertNotNull(user.getProfileSidebarFillColor()); assertNotNull(user.getProfileTextColor()); this.user = null; } public void testSearchUser() throws TwitterException { async1.searchUsers("Doug Williams", 1); waitForResponse(); assertTrue(4 < users.size()); } public void testGetUserTimeline_Show() throws Exception { async2.getUserTimeline(); waitForResponse(); assertTrue("size", 10 < statuses.size()); async2.getUserTimeline(new Paging(999383469l)); } public void testAccountProfileImageUpdates() throws Exception { te = null; async1.updateProfileImage(getRandomlyChosenFile()); waitForResponse(); assertNull(te); // tile randomly async1.updateProfileBackgroundImage(getRandomlyChosenFile(), (5 < System.currentTimeMillis() % 5)); waitForResponse(); assertNull(te); } public void testFavorite() throws Exception { Status status = twitter1.getHomeTimeline().get(0); try { twitter2.destroyFavorite(status.getId()); } catch (TwitterException te) { } async2.createFavorite(status.getId()); waitForResponse(); assertEquals(status, this.status); this.status = null; //need to wait for a second to get it destoryable Thread.sleep(5000); async2.destroyFavorite(status.getId()); waitForResponse(); if (te != null && te.getStatusCode() == 404) { // sometimes destorying favorite fails with 404 } else { assertEquals(status, this.status); } } public void testSocialGraphMethods() throws Exception { async1.getFriendsIDs(-1); waitForResponse(); int yusuke = 4933401; assertIDExsits("twit4j is following yusuke", ids, yusuke); int ryunosukey = 48528137; async1.getFriendsIDs(ryunosukey, -1); waitForResponse(); assertEquals("ryunosukey is not following anyone", 0, ids.getIDs().length); async1.getFriendsIDs("yusuke", -1); waitForResponse(); assertIDExsits("yusukey is following ryunosukey", ids, ryunosukey); try { twitter2.createFriendship(id1.screenName); } catch (TwitterException te) { } async1.getFollowersIDs(-1); waitForResponse(); assertIDExsits("twit4j2(6377362) is following twit4j(6358482)", ids, 6377362); async1.getFollowersIDs(ryunosukey, -1); waitForResponse(); assertIDExsits("yusukey is following ryunosukey", ids, yusuke); async1.getFollowersIDs("ryunosukey", -1); waitForResponse(); assertIDExsits("yusukey is following ryunosukey", ids, yusuke); } private void assertIDExsits(String assertion, IDs ids, int idToFind) { boolean found = false; for (long id : ids.getIDs()) { if (id == idToFind) { found = true; break; } } assertTrue(assertion, found); } public void testAccountMethods() throws Exception { async1.verifyCredentials(); waitForResponse(); assertNotNull(user); assertNotNull(user.getName()); assertNotNull(user.getURL()); assertNotNull(user.getLocation()); assertNotNull(user.getDescription()); String oldName, oldURL, oldLocation, oldDescription; oldName = user.getName(); oldURL = user.getURL().toString(); oldLocation = user.getLocation(); oldDescription = user.getDescription(); String newName, newURL, newLocation, newDescription; String neu = "new"; newName = user.getName() + neu; newURL = user.getURL() + neu; newLocation = new Date().toString(); newDescription = user.getDescription() + neu; async1.updateProfile(newName, newURL, newLocation, newDescription); waitForResponse(); assertEquals(newName, user.getName()); assertEquals(newURL, user.getURL().toString()); assertEquals(newLocation, user.getLocation()); assertEquals(newDescription, user.getDescription()); //revert the profile async1.updateProfile(oldName, oldURL, oldLocation, oldDescription); waitForResponse(); async1.updateProfileColors("f00", "f0f", "0ff", "0f0", "f0f"); waitForResponse(); assertEquals("f00", user.getProfileBackgroundColor()); assertEquals("f0f", user.getProfileTextColor()); assertEquals("0ff", user.getProfileLinkColor()); assertEquals("0f0", user.getProfileSidebarFillColor()); assertEquals("f0f", user.getProfileSidebarBorderColor()); async1.updateProfileColors("f0f", "f00", "f0f", "0ff", "0f0"); waitForResponse(); assertEquals("f0f", user.getProfileBackgroundColor()); assertEquals("f00", user.getProfileTextColor()); assertEquals("f0f", user.getProfileLinkColor()); assertEquals("0ff", user.getProfileSidebarFillColor()); assertEquals("0f0", user.getProfileSidebarBorderColor()); async1.updateProfileColors("87bc44", "9ae4e8", "000000", "0000ff", "e0ff92"); waitForResponse(); assertEquals("87bc44", user.getProfileBackgroundColor()); assertEquals("9ae4e8", user.getProfileTextColor()); assertEquals("000000", user.getProfileLinkColor()); assertEquals("0000ff", user.getProfileSidebarFillColor()); assertEquals("e0ff92", user.getProfileSidebarBorderColor()); async1.updateProfileColors("f0f", null, "f0f", null, "0f0"); waitForResponse(); assertEquals("f0f", user.getProfileBackgroundColor()); assertEquals("9ae4e8", user.getProfileTextColor()); assertEquals("f0f", user.getProfileLinkColor()); assertEquals("0000ff", user.getProfileSidebarFillColor()); assertEquals("0f0", user.getProfileSidebarBorderColor()); async1.updateProfileColors(null, "f00", null, "0ff", null); waitForResponse(); assertEquals("f0f", user.getProfileBackgroundColor()); assertEquals("f00", user.getProfileTextColor()); assertEquals("f0f", user.getProfileLinkColor()); assertEquals("0ff", user.getProfileSidebarFillColor()); assertEquals("0f0", user.getProfileSidebarBorderColor()); async1.updateProfileColors("9ae4e8", "000000", "0000ff", "e0ff92", "87bc44"); waitForResponse(); assertEquals("9ae4e8", user.getProfileBackgroundColor()); assertEquals("000000", user.getProfileTextColor()); assertEquals("0000ff", user.getProfileLinkColor()); assertEquals("e0ff92", user.getProfileSidebarFillColor()); assertEquals("87bc44", user.getProfileSidebarBorderColor()); } public void testShow() throws Exception { async2.showStatus(1000l); waitForResponse(); assertEquals(52, status.getUser().getId()); assertDeserializedFormIsEqual(status); } public void testBlock() throws Exception { async2.createBlock(id1.screenName); waitForResponse(); async2.destroyBlock(id1.screenName); waitForResponse(); async1.getBlocksList(); waitForResponse(); assertEquals(1, users.size()); assertEquals(39771963, users.get(0).getId()); async1.getBlocksList(-1L); waitForResponse(); assertEquals(1, users.size()); assertEquals(39771963, users.get(0).getId()); async1.getBlocksIDs(); waitForResponse(); assertEquals(1, ids.getIDs().length); assertEquals(39771963, ids.getIDs()[0]); } public void testUpdate() throws Exception { String date = new java.util.Date().toString() + "test"; async1.updateStatus(date); waitForResponse(); assertEquals("", date, status.getText()); long id = status.getId(); async2.updateStatus(new StatusUpdate("@" + id1.screenName + " " + date).inReplyToStatusId(id)); waitForResponse(); assertEquals("", "@" + id1.screenName + " " + date, status.getText()); assertEquals("", id, status.getInReplyToStatusId()); assertEquals(twitter1.verifyCredentials().getId(), status.getInReplyToUserId()); id = status.getId(); this.status = null; async2.destroyStatus(id); waitForResponse(); assertEquals("", "@" + id1.screenName + " " + date, status.getText()); assertDeserializedFormIsEqual(status); } public void testDirectMessages() throws Exception { String expectedReturn = new Date() + ":directmessage test"; async1.sendDirectMessage(id3.id, expectedReturn); waitForResponse(); assertEquals(expectedReturn, message.getText()); async3.getDirectMessages(); waitForResponse(); assertTrue(1 <= messages.size()); } public void testCreateDestroyFriend() throws Exception { async2.destroyFriendship(id1.screenName); waitForResponse(); // twitterAPI2.destroyFriendshipAsync(id1.name); // waitForResponse(); // assertEquals(403, te.getStatusCode()); async2.createFriendship(id1.screenName, true); // the Twitter API is not returning appropriate notifications value // http://code.google.com/p/twitter-api/issues/detail?id=474 // user detail = twitterAPI2.showUser(id1.name); // assertTrue(detail.isNotificationEnabled()); waitForResponse(); assertEquals(id1.screenName, user.getScreenName()); // te = null; // twitterAPI2.createFriendshipAsync(id2.name); // waitForResponse(); // assertEquals(403, te.getStatusCode()); te = null; async2.createFriendship("doesnotexist--"); waitForResponse(); //now befriending with non-existing user returns 404 //http://groups.google.com/group/twitter-development-talk/browse_thread/thread/bd2a912b181bc39f assertEquals(404, te.getStatusCode()); assertEquals(34, te.getErrorCode()); } public void testRateLimitStatus() throws Exception { async1.getRateLimitStatus(); waitForResponse(); RateLimitStatus status = rateLimitStatus.values().iterator().next(); assertTrue(1 < status.getLimit()); assertTrue(1 < status.getRemaining()); } private ResponseList<Status> statuses = null; private ResponseList<User> users = null; private ResponseList<DirectMessage> messages = null; private Status status = null; private User user = null; private boolean test; private UserList userList; private PagableResponseList<UserList> pagableUserLists; private Relationship relationship; private DirectMessage message = null; private TwitterException te = null; private Map<String,RateLimitStatus> rateLimitStatus; private boolean exists; private QueryResult queryResult; private IDs ids; private List<Trends> trendsList; private Trends trends; private boolean blockExists; private RelatedResults relatedResults; /*Search API Methods*/ @Override public void searched(QueryResult result) { this.queryResult = result; notifyResponse(); } /*Timeline Methods*/ @Override public void gotHomeTimeline(ResponseList<Status> statuses) { this.statuses = statuses; notifyResponse(); } @Override public void gotUserTimeline(ResponseList<Status> statuses) { this.statuses = statuses; notifyResponse(); } @Override public void gotRetweetsOfMe(ResponseList<Status> statuses) { this.statuses = statuses; notifyResponse(); } @Override public void gotMentions(ResponseList<Status> statuses) { this.statuses = statuses; notifyResponse(); } /*Status Methods*/ @Override public void gotShowStatus(Status status) { this.status = status; notifyResponse(); } @Override public void updatedStatus(Status status) { this.status = status; notifyResponse(); } @Override public void destroyedStatus(Status destroyedStatus) { this.status = destroyedStatus; notifyResponse(); } /** * @since Twitter4J 2.0.10 */ @Override public void retweetedStatus(Status retweetedStatus) { this.status = retweetedStatus; notifyResponse(); } @Override public void gotOEmbed(OEmbed oembed) { this.oembed = oembed; notifyResponse(); } /** * @since Twitter4J 2.1.0 */ @Override public void gotRetweets(ResponseList<Status> retweets) { this.statuses = retweets; notifyResponse(); } /*User Methods*/ @Override public void gotUserDetail(User user) { this.user = user; notifyResponse(); } @Override public void lookedupUsers(ResponseList<User> users) { this.users = users; notifyResponse(); } @Override public void searchedUser(ResponseList<User> userList) { this.users = userList; notifyResponse(); } /** * @since Twitter4J 2.1.1 */ @Override public void gotSuggestedUserCategories(ResponseList<Category> categories) { this.categories = categories; notifyResponse(); } /** * @since Twitter4J 2.1.1 */ @Override public void gotUserSuggestions(ResponseList<User> users) { this.users = users; notifyResponse(); } /** * @since Twitter4J 2.1.9 */ @Override public void gotMemberSuggestions(ResponseList<User> users) { this.users = users; notifyResponse(); } @Override public void gotContributors(ResponseList<User> users) { notifyResponse(); } @Override public void removedProfileBanner() { notifyResponse(); } @Override public void updatedProfileBanner() { notifyResponse(); } @Override public void gotContributees(ResponseList<User> users) { notifyResponse(); } /*List Methods*/ @Override public void createdUserList(UserList userList) { this.userList = userList; notifyResponse(); } @Override public void updatedUserList(UserList userList) { this.userList = userList; notifyResponse(); } @Override public void gotUserLists(ResponseList<UserList> userLists) { this.userLists = userLists; notifyResponse(); } @Override public void gotShowUserList(UserList userList) { this.userList = userList; notifyResponse(); } @Override public void destroyedUserList(UserList userList) { this.userList = userList; notifyResponse(); } @Override public void gotUserListStatuses(ResponseList<Status> statuses) { this.statuses = statuses; notifyResponse(); } @Override public void gotUserListMemberships(PagableResponseList<UserList> userLists) { this.pagableUserLists = userLists; notifyResponse(); } @Override public void gotUserListSubscriptions(PagableResponseList<UserList> userLists) { this.pagableUserLists = userLists; notifyResponse(); } /*List Members Methods*/ @Override public void gotUserListMembers(PagableResponseList<User> users) { this.users = users; notifyResponse(); } @Override public void gotSavedSearches(ResponseList<SavedSearch> savedSearches) { this.savedSearches = savedSearches; notifyResponse(); } @Override public void gotSavedSearch(SavedSearch savedSearch) { this.savedSearch = savedSearch; notifyResponse(); } @Override public void createdSavedSearch(SavedSearch savedSearch) { this.savedSearch = savedSearch; notifyResponse(); } @Override public void destroyedSavedSearch(SavedSearch savedSearch) { this.savedSearch = savedSearch; notifyResponse(); } @Override public void createdUserListMember(UserList userList) { this.userList = userList; } @Override public void createdUserListMembers(UserList userList) { this.userList = userList; } @Override public void destroyedUserListMember(UserList userList) { this.userList = userList; } @Override public void checkedUserListMembership(User user) { this.user = user; } /*List Subscribers Methods*/ @Override public void gotUserListSubscribers(PagableResponseList<User> users) { this.users = users; } @Override public void subscribedUserList(UserList userList) { this.userList = userList; } @Override public void unsubscribedUserList(UserList userList) { this.userList = userList; } @Override public void checkedUserListSubscription(User user) { this.user = user; } /*Direct Message Methods*/ @Override public void gotDirectMessages(ResponseList<DirectMessage> messages) { this.messages = messages; notifyResponse(); } @Override public void gotSentDirectMessages(ResponseList<DirectMessage> messages) { this.messages = messages; notifyResponse(); } @Override public void sentDirectMessage(DirectMessage message) { this.message = message; notifyResponse(); } @Override public void destroyedDirectMessage(DirectMessage message) { this.message = message; notifyResponse(); } @Override public void gotDirectMessage(DirectMessage message) { this.message = message; notifyResponse(); } /*Friendship Methods*/ @Override public void createdFriendship(User user) { this.user = user; notifyResponse(); } @Override public void destroyedFriendship(User user) { this.user = user; notifyResponse(); } /** * @since Twitter4J 2.1.0 */ @Override public void gotShowFriendship(Relationship relationship) { this.relationship = relationship; notifyResponse(); } @Override public void gotFriendsList(PagableResponseList<User> users) { this.users = users; notifyResponse(); } @Override public void gotFollowersList(PagableResponseList<User> users) { this.users = users; notifyResponse(); } /** * @since Twitter4J 2.1.2 */ @Override public void gotIncomingFriendships(IDs ids) { this.ids = ids; notifyResponse(); } /** * @since Twitter4J 2.1.2 */ @Override public void gotOutgoingFriendships(IDs ids) { this.ids = ids; notifyResponse(); } /*Social Graph Methods*/ @Override public void gotFriendsIDs(IDs ids) { this.ids = ids; notifyResponse(); } @Override public void gotFollowersIDs(IDs ids) { this.ids = ids; notifyResponse(); } @Override public void lookedUpFriendships(ResponseList<Friendship> friendships) { this.friendships = friendships; notifyResponse(); } @Override public void updatedFriendship(Relationship relationship) { this.relationship = relationship; notifyResponse(); } /*Account Methods*/ @Override public void gotRateLimitStatus(Map<String ,RateLimitStatus> rateLimitStatus) { this.rateLimitStatus = rateLimitStatus; notifyResponse(); } @Override public void verifiedCredentials(User user) { this.user = user; notifyResponse(); } @Override public void updatedProfileColors(User user) { this.user = user; notifyResponse(); } @Override public void gotAccountSettings(AccountSettings settings) { this.settings = settings; notifyResponse(); } @Override public void updatedAccountSettings(AccountSettings settings) { this.settings = settings; notifyResponse(); } /** * @since Twitter4J 2.1.0 */ @Override public void updatedProfileImage(User user) { this.user = user; notifyResponse(); } /** * @since Twitter4J 2.1.0 */ @Override public void updatedProfileBackgroundImage(User user) { this.user = user; notifyResponse(); } @Override public void updatedProfile(User user) { this.user = user; notifyResponse(); } /*Favorite Methods*/ @Override public void gotFavorites(ResponseList<Status> statuses) { this.statuses = statuses; notifyResponse(); } @Override public void createdFavorite(Status status) { this.status = status; notifyResponse(); } @Override public void destroyedFavorite(Status status) { this.status = status; notifyResponse(); } /*Block Methods*/ @Override public void createdBlock(User user) { this.user = user; notifyResponse(); } @Override public void destroyedBlock(User user) { this.user = user; notifyResponse(); } @Override public void gotBlocksList(ResponseList<User> blockingUsers) { this.users = blockingUsers; notifyResponse(); } @Override public void gotBlockIDs(IDs blockingUsersIDs) { this.ids = blockingUsersIDs; notifyResponse(); } /*Spam Reporting Methods*/ @Override public void reportedSpam(User reportedSpammer) { this.user = reportedSpammer; notifyResponse(); } /*Saved Searches Methods*/ //getSavedSearches() //showSavedSearch() //createSavedSearch() //destroySavedSearch() /*Local Trends Methods*/ /** * @param locations the locations * @since Twitter4J 2.1.1 */ @Override public void gotAvailableTrends(ResponseList<Location> locations) { this.locations = locations; notifyResponse(); } @Override public void gotClosestTrends(ResponseList<Location> locations) { this.locations = locations; notifyResponse(); } /*Geo Methods*/ @Override public void searchedPlaces(ResponseList<Place> places) { this.places = places; notifyResponse(); } @Override public void gotSimilarPlaces(SimilarPlaces places) { this.places = places; notifyResponse(); } @Override public void gotReverseGeoCode(ResponseList<Place> places) { this.places = places; notifyResponse(); } @Override public void gotGeoDetails(Place place) { this.place = place; notifyResponse(); } @Override public void createdPlace(Place place) { this.place = place; notifyResponse(); } @Override public void gotPlaceTrends(Trends trends) { this.trends = trends; notifyResponse(); } /* Legal Resources */ /** * @since Twitter4J 2.1.7 */ @Override public void gotTermsOfService(String str) { notifyResponse(); } /** * @since Twitter4J 2.1.7 */ @Override public void gotPrivacyPolicy(String str) { notifyResponse(); } /* #newtwitter Methods */ /** * */ @Override public void gotRelatedResults(RelatedResults relatedResults) { this.relatedResults = relatedResults; notifyResponse(); } /*Help Methods*/ @Override public void gotAPIConfiguration(TwitterAPIConfiguration conf) { this.apiConf = conf; notifyResponse(); } @Override public void gotLanguages(ResponseList<HelpResources.Language> languages) { this.languages = languages; notifyResponse(); } /** * @param te TwitterException * @param method int */ @Override public void onException(TwitterException te, TwitterMethod method) { this.te = te; System.out.println("onexception on " + method.name()); te.printStackTrace(); notifyResponse(); } @Override public void gotOAuthRequestToken(RequestToken token) { } @Override public void gotOAuthAccessToken(AccessToken token) { } private synchronized void notifyResponse() { this.notify(); } private synchronized void waitForResponse() { try { this.wait(60000); } catch (InterruptedException e) { e.printStackTrace(); } } /** * @param obj the object to be asserted * @return the deserialized object * @throws Exception in the case the object is not (de)serializable */ public static Object assertDeserializedFormIsEqual(Object obj) throws Exception { ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(byteOutputStream); oos.writeObject(obj); byteOutputStream.close(); ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteOutputStream.toByteArray()); ObjectInputStream ois = new ObjectInputStream(byteInputStream); Object that = ois.readObject(); byteInputStream.close(); ois.close(); assertEquals(obj, that); return that; } static final String[] files = {"src/test/resources/t4j-reverse.jpeg", "src/test/resources/t4j-reverse.png", "src/test/resources/t4j-reverse.gif", "src/test/resources/t4j.jpeg", "src/test/resources/t4j.png", "src/test/resources/t4j.gif", }; private static File getRandomlyChosenFile() { int rand = (int) (System.currentTimeMillis() % 6); File file = new File(files[rand]); if (!file.exists()) { file = new File("twitter4j-core/" + files[rand]); } return file; } }
apache-2.0
freeVM/freeVM
enhanced/archive/classlib/java6/modules/swing/src/test/api/java/common/javax/swing/DefaultListSelectionModelTest.java
27477
/* * 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. */ /** * @author Anton Avtamonov * @version $Revision$ */ package javax.swing; import java.awt.event.KeyListener; import java.util.ArrayList; import java.util.List; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class DefaultListSelectionModelTest extends SwingTestCase { private DefaultListSelectionModel model; private TestListener listener; public DefaultListSelectionModelTest(final String name) { super(name); } @Override protected void setUp() throws Exception { model = new DefaultListSelectionModel(); listener = new TestListener(); } @Override protected void tearDown() throws Exception { model = null; listener = null; } public void testAddRemoveListSelectionListener() throws Exception { assertEquals(0, model.getListSelectionListeners().length); model.addListSelectionListener(new TestListener()); model.addListSelectionListener(listener); model.addListSelectionListener(new TestListener()); assertEquals(3, model.getListSelectionListeners().length); model.removeListSelectionListener(listener); assertEquals(2, model.getListSelectionListeners().length); } public void testAddSelectionInterval() throws Exception { model.addListSelectionListener(listener); model.addSelectionInterval(-1, 0); model.addSelectionInterval(-1, 10); model.addSelectionInterval(0, -1); model.addSelectionInterval(-1, -1); assertTrue(model.isSelectionEmpty()); assertEquals(0, listener.getEvents().size()); listener.reset(); model.setLeadAnchorNotificationEnabled(false); assertTrue(model.isSelectionEmpty()); model.addSelectionInterval(3, 5); checkSingleEvent(3, 5, false); assertFalse(model.isSelectedIndex(2)); checkIntervalState(3, 5, true); listener.reset(); model.addSelectionInterval(10, 7); checkSingleEvent(7, 10, false); checkIntervalState(3, 5, true); checkIntervalState(7, 10, true); listener.reset(); model.addSelectionInterval(4, 11); checkSingleEvent(6, 11, false); checkIntervalState(3, 11, true); model.clearSelection(); model.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); model.addSelectionInterval(4, 11); checkIntervalState(4, 11, true); model.addSelectionInterval(6, 8); checkIntervalState(6, 8, true); model.clearSelection(); model.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); model.addSelectionInterval(11, 4); checkIntervalState(4, 4, true); assertEquals(model.getMaxSelectionIndex(), model.getMinSelectionIndex()); } public void testClearSelectionIsSelectionEmpty() throws Exception { assertTrue(model.isSelectionEmpty()); model.addSelectionInterval(0, 5); model.addSelectionInterval(7, 9); assertFalse(model.isSelectionEmpty()); model.addListSelectionListener(listener); model.clearSelection(); checkSingleEvent(0, 9, false); assertTrue(model.isSelectionEmpty()); checkIntervalState(0, 9, false); } public void testClone() throws Exception { model.addListSelectionListener(listener); model.addSelectionInterval(2, 4); model.addSelectionInterval(7, 9); model.setLeadAnchorNotificationEnabled(false); model.setValueIsAdjusting(true); model = (DefaultListSelectionModel) model.clone(); assertEquals(0, model.getListSelectionListeners().length); checkIntervalState(0, 1, false); checkIntervalState(2, 4, true); checkIntervalState(5, 6, false); checkIntervalState(7, 9, true); assertEquals(7, model.getAnchorSelectionIndex()); assertEquals(9, model.getLeadSelectionIndex()); assertFalse(model.isLeadAnchorNotificationEnabled()); assertTrue(model.getValueIsAdjusting()); } public void testFireValueChanged() throws Exception { TestListener listener2 = new TestListener(); model.addListSelectionListener(listener); model.addListSelectionListener(listener2); model.fireValueChanged(true); assertEquals(0, listener.getEvents().size()); listener.reset(); model.setValueIsAdjusting(true); model.setAnchorSelectionIndex(5); checkSingleEvent(listener, 5, 5, true); listener.reset(); model.fireValueChanged(true); checkSingleEvent(listener, 5, 5, true); model.setSelectionInterval(3, 6); model.setSelectionInterval(9, 11); listener.reset(); model.fireValueChanged(true); checkSingleEvent(listener, 3, 11, true); listener.reset(); model.fireValueChanged(false); assertEquals(0, listener.getEvents().size()); model.setValueIsAdjusting(false); listener.reset(); listener2.reset(); model.fireValueChanged(3, 7); checkSingleEvent(listener, 3, 7, false); checkSingleEvent(listener2, 3, 7, false); listener.reset(); listener2.reset(); model.fireValueChanged(0, 5, false); checkSingleEvent(listener, 0, 5, false); checkSingleEvent(listener2, 0, 5, false); } public void testGetAnchorAndLeadSelectionIndex() throws Exception { assertEquals(-1, model.getAnchorSelectionIndex()); assertEquals(-1, model.getLeadSelectionIndex()); model.addSelectionInterval(2, 6); assertEquals(2, model.getAnchorSelectionIndex()); assertEquals(6, model.getLeadSelectionIndex()); model.setSelectionInterval(1, 4); assertEquals(1, model.getAnchorSelectionIndex()); assertEquals(4, model.getLeadSelectionIndex()); model.removeSelectionInterval(2, 7); assertEquals(2, model.getAnchorSelectionIndex()); assertEquals(7, model.getLeadSelectionIndex()); } public void testGetListeners() throws Exception { assertEquals(0, model.getListeners(ListSelectionListener.class).length); assertEquals(0, model.getListeners(KeyListener.class).length); model.addListSelectionListener(listener); assertEquals(1, model.getListeners(ListSelectionListener.class).length); assertEquals(0, model.getListeners(KeyListener.class).length); } public void testGetListSelectionListeners() throws Exception { assertEquals(0, model.getListSelectionListeners().length); model.addListSelectionListener(listener); assertEquals(1, model.getListSelectionListeners().length); } public void testGetMinAndMaxSelectionIndex() throws Exception { assertEquals(-1, model.getMinSelectionIndex()); assertEquals(-1, model.getMaxSelectionIndex()); model.addSelectionInterval(2, 6); model.addSelectionInterval(12, 9); assertEquals(2, model.getMinSelectionIndex()); assertEquals(12, model.getMaxSelectionIndex()); model.addSelectionInterval(0, 14); assertEquals(0, model.getMinSelectionIndex()); assertEquals(14, model.getMaxSelectionIndex()); } public void testGetSetSelectionMode() throws Exception { assertEquals(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION, model.getSelectionMode()); model.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); assertEquals(ListSelectionModel.SINGLE_SELECTION, model.getSelectionMode()); model.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); assertEquals(ListSelectionModel.SINGLE_INTERVAL_SELECTION, model.getSelectionMode()); try { model.setSelectionMode(100); fail("Incorrect selection model should be detected"); } catch (IllegalArgumentException iae) { } } public void testGetSetValueIsAdjusting() throws Exception { model.addListSelectionListener(listener); assertFalse(model.getValueIsAdjusting()); model.setValueIsAdjusting(true); assertEquals(0, listener.getEvents().size()); assertTrue(model.getValueIsAdjusting()); model.setSelectionInterval(2, 3); checkSingleEvent(2, 3, true); listener.reset(); model.setSelectionInterval(5, 7); checkSingleEvent(2, 7, true); listener.reset(); model.setSelectionInterval(5, 8); checkSingleEvent(7, 8, true); listener.reset(); model.setValueIsAdjusting(false); assertEquals(1, listener.getEvents().size()); assertFalse(model.getValueIsAdjusting()); checkSingleEvent(2, 8, false); } public void testInsertIndexInterval() throws Exception { model.addListSelectionListener(listener); model.setSelectionInterval(3, 5); if (isHarmony()) { listener.reset(); model.insertIndexInterval(-1, 0, true); model.insertIndexInterval(-1, 0, false); model.insertIndexInterval(-1, -1, true); model.insertIndexInterval(-1, -1, false); model.insertIndexInterval(0, -1, true); model.insertIndexInterval(0, -1, false); assertEquals(0, listener.getEvents().size()); } listener.reset(); model.insertIndexInterval(4, 10, true); checkIntervalState(0, 2, false); checkIntervalState(3, 15, true); if (isHarmony()) { checkSingleEvent(5, 15, false); } listener.reset(); model.insertIndexInterval(0, 3, true); checkIntervalState(0, 5, false); checkIntervalState(6, 18, true); checkSingleEvent(3, 18, false); model.clearSelection(); model.setSelectionInterval(3, 5); listener.reset(); model.insertIndexInterval(6, 3, true); checkIntervalState(0, 2, false); checkIntervalState(3, 5, true); checkIntervalState(6, 20, false); assertEquals(0, listener.getEvents().size()); assertEquals(3, model.getAnchorSelectionIndex()); assertEquals(5, model.getLeadSelectionIndex()); model.clearSelection(); model.setSelectionInterval(3, 5); listener.reset(); model.insertIndexInterval(6, 3, false); checkIntervalState(0, 2, false); checkIntervalState(3, 5, true); checkIntervalState(6, 20, false); assertEquals(0, listener.getEvents().size()); assertEquals(3, model.getAnchorSelectionIndex()); assertEquals(5, model.getLeadSelectionIndex()); model.clearSelection(); model.setSelectionInterval(3, 5); listener.reset(); model.insertIndexInterval(5, 3, false); checkIntervalState(0, 2, false); checkIntervalState(3, 8, true); checkIntervalState(9, 20, false); checkSingleEvent(6, 8, false); assertEquals(3, model.getAnchorSelectionIndex()); assertEquals(5, model.getLeadSelectionIndex()); model.clearSelection(); model.setSelectionInterval(3, 5); listener.reset(); model.insertIndexInterval(5, 3, true); checkIntervalState(0, 2, false); checkIntervalState(3, 8, true); checkIntervalState(9, 20, false); checkSingleEvent(5, 8, false); assertEquals(3, model.getAnchorSelectionIndex()); assertEquals(8, model.getLeadSelectionIndex()); model.clearSelection(); model.setSelectionInterval(3, 5); listener.reset(); model.insertIndexInterval(3, 3, true); checkIntervalState(0, 2, false); checkIntervalState(3, 8, true); checkIntervalState(9, 20, false); checkSingleEvent(3, 8, false); assertEquals(6, model.getAnchorSelectionIndex()); assertEquals(8, model.getLeadSelectionIndex()); model.clearSelection(); model.setSelectionInterval(1, 2); listener.reset(); model.insertIndexInterval(0, 3, true); checkIntervalState(0, 3, false); checkIntervalState(4, 5, true); checkIntervalState(6, 20, false); assertEquals(4, model.getAnchorSelectionIndex()); assertEquals(5, model.getLeadSelectionIndex()); listener.reset(); model.removeSelectionInterval(-1, 0); model.removeSelectionInterval(0, -1); model.removeSelectionInterval(-1, -1); assertEquals(0, listener.getEvents().size()); } public void testRemoveIndexInterval() throws Exception { model.setSelectionInterval(3, 8); model.addListSelectionListener(listener); model.removeSelectionInterval(-1, 10); model.removeSelectionInterval(-1, 0); model.removeSelectionInterval(0, -1); model.removeSelectionInterval(-1, -1); assertEquals(0, listener.getEvents().size()); assertEquals(3, model.getAnchorSelectionIndex()); assertEquals(8, model.getLeadSelectionIndex()); listener.reset(); model.removeIndexInterval(2, 6); checkIntervalState(0, 1, false); checkIntervalState(2, 3, true); assertEquals(1, model.getAnchorSelectionIndex()); assertEquals(3, model.getLeadSelectionIndex()); checkSingleEvent(1, 8, false); listener.reset(); model.removeIndexInterval(0, 2); checkIntervalState(0, 0, true); checkIntervalState(1, 10, false); assertEquals(-1, model.getAnchorSelectionIndex()); assertEquals(0, model.getLeadSelectionIndex()); if (isHarmony()) { checkSingleEvent(0, 3, false); } else { checkSingleEvent(-1, 3, false); } listener.reset(); model.removeIndexInterval(0, 2); checkIntervalState(0, 10, false); assertEquals(-1, model.getAnchorSelectionIndex()); if (isHarmony()) { assertEquals(-1, model.getLeadSelectionIndex()); } checkSingleEvent(0, 0, false); model.setSelectionInterval(3, 8); listener.reset(); model.removeIndexInterval(8, 8); checkIntervalState(3, 7, true); checkIntervalState(8, 8, false); assertEquals(3, model.getAnchorSelectionIndex()); assertEquals(7, model.getLeadSelectionIndex()); checkSingleEvent(7, 8, false); listener.reset(); model.removeIndexInterval(3, 3); checkIntervalState(3, 6, true); checkIntervalState(7, 8, false); assertEquals(2, model.getAnchorSelectionIndex()); assertEquals(6, model.getLeadSelectionIndex()); checkSingleEvent(2, 7, false); listener.reset(); model.removeIndexInterval(3, 6); checkIntervalState(0, 10, false); assertEquals(2, model.getAnchorSelectionIndex()); assertEquals(2, model.getLeadSelectionIndex()); checkSingleEvent(2, 6, false); } public void testIsLeadAnchorNotificationEnabled() throws Exception { model.addListSelectionListener(listener); assertTrue(model.isLeadAnchorNotificationEnabled()); model.addSelectionInterval(3, 5); checkSingleEvent(3, 5, false); listener.reset(); model.addSelectionInterval(7, 8); checkSingleEvent(3, 8, false); listener.reset(); model.setSelectionInterval(2, 6); checkSingleEvent(2, 8, false); listener.reset(); model.removeSelectionInterval(4, 11); checkSingleEvent(2, 11, false); listener.reset(); model.removeSelectionInterval(4, 11); assertEquals(0, listener.getEvents().size()); listener.reset(); model.removeSelectionInterval(5, 8); checkSingleEvent(4, 11, false); model.setLeadAnchorNotificationEnabled(false); assertFalse(model.isLeadAnchorNotificationEnabled()); listener.reset(); model.addSelectionInterval(10, 12); checkSingleEvent(10, 12, false); listener.reset(); model.removeSelectionInterval(0, 2); checkSingleEvent(2, 2, false); listener.reset(); model.removeSelectionInterval(1, 2); assertEquals(0, listener.getEvents().size()); } public void testIsSelectedIndex() throws Exception { model.setSelectionInterval(2, 4); assertFalse(model.isSelectedIndex(0)); assertTrue(model.isSelectedIndex(2)); assertFalse(model.isSelectedIndex(-1)); } public void testGetSetAnchorSelectionIndex() throws Exception { model.addListSelectionListener(listener); model.setAnchorSelectionIndex(3); assertEquals(3, model.getAnchorSelectionIndex()); checkSingleEvent(3, 3, false); listener.reset(); model.setAnchorSelectionIndex(5); assertEquals(5, model.getAnchorSelectionIndex()); checkSingleEvent(3, 5, false); listener.reset(); model.setLeadAnchorNotificationEnabled(false); model.setAnchorSelectionIndex(7); assertEquals(7, model.getAnchorSelectionIndex()); assertEquals(0, listener.getEvents().size()); listener.reset(); model.setAnchorSelectionIndex(-1); assertEquals(-1, model.getAnchorSelectionIndex()); assertEquals(0, listener.getEvents().size()); } public void testGetSetLeadSelectionIndex() throws Exception { model.addListSelectionListener(listener); model.setSelectionInterval(3, 6); listener.reset(); model.setLeadSelectionIndex(-1); assertEquals(6, model.getLeadSelectionIndex()); assertEquals(0, listener.getEvents().size()); listener.reset(); model.setLeadSelectionIndex(4); assertEquals(4, model.getLeadSelectionIndex()); checkIntervalState(3, 4, true); checkIntervalState(5, 6, false); checkSingleEvent(4, 6, false); model.setSelectionInterval(3, 6); model.setAnchorSelectionIndex(2); listener.reset(); model.setLeadSelectionIndex(8); assertEquals(8, model.getLeadSelectionIndex()); checkIntervalState(2, 8, false); checkSingleEvent(3, 8, false); assertEquals(2, model.getAnchorSelectionIndex()); assertEquals(8, model.getLeadSelectionIndex()); model.clearSelection(); assertEquals(2, model.getAnchorSelectionIndex()); assertEquals(8, model.getLeadSelectionIndex()); assertTrue(model.isSelectionEmpty()); model.setAnchorSelectionIndex(5); assertEquals(5, model.getAnchorSelectionIndex()); assertEquals(8, model.getLeadSelectionIndex()); assertTrue(model.isSelectionEmpty()); model.setLeadSelectionIndex(8); assertEquals(5, model.getAnchorSelectionIndex()); assertEquals(8, model.getLeadSelectionIndex()); assertTrue(model.isSelectionEmpty()); model.setLeadSelectionIndex(20); assertEquals(5, model.getAnchorSelectionIndex()); assertEquals(20, model.getLeadSelectionIndex()); assertTrue(model.isSelectionEmpty()); model.setAnchorSelectionIndex(1); assertEquals(1, model.getAnchorSelectionIndex()); assertEquals(20, model.getLeadSelectionIndex()); assertTrue(model.isSelectionEmpty()); model.setLeadSelectionIndex(19); assertEquals(1, model.getAnchorSelectionIndex()); assertEquals(19, model.getLeadSelectionIndex()); checkIntervalState(0, 19, false); checkIntervalState(20, 20, true); checkIntervalState(21, 100, false); model.setSelectionInterval(2, 5); assertEquals(2, model.getAnchorSelectionIndex()); assertEquals(5, model.getLeadSelectionIndex()); checkIntervalState(0, 1, false); checkIntervalState(2, 5, true); checkIntervalState(6, 10, false); model.setAnchorSelectionIndex(1); assertEquals(1, model.getAnchorSelectionIndex()); assertEquals(5, model.getLeadSelectionIndex()); checkIntervalState(0, 1, false); checkIntervalState(2, 5, true); checkIntervalState(6, 10, false); model.setLeadSelectionIndex(7); assertEquals(1, model.getAnchorSelectionIndex()); assertEquals(7, model.getLeadSelectionIndex()); checkIntervalState(0, 10, false); model.setSelectionInterval(2, 7); assertEquals(2, model.getAnchorSelectionIndex()); assertEquals(7, model.getLeadSelectionIndex()); model.setAnchorSelectionIndex(4); model.setLeadSelectionIndex(6); checkIntervalState(0, 1, false); checkIntervalState(2, 6, true); checkIntervalState(7, 10, false); model.setSelectionInterval(3, 7); assertEquals(3, model.getAnchorSelectionIndex()); assertEquals(7, model.getLeadSelectionIndex()); model.setLeadSelectionIndex(3); checkIntervalState(0, 2, false); checkIntervalState(3, 3, true); checkIntervalState(4, 10, false); model.setSelectionInterval(3, 7); assertEquals(3, model.getAnchorSelectionIndex()); assertEquals(7, model.getLeadSelectionIndex()); model.setLeadSelectionIndex(3); checkIntervalState(0, 2, false); checkIntervalState(3, 3, true); checkIntervalState(4, 10, false); model.setSelectionInterval(3, 7); assertEquals(3, model.getAnchorSelectionIndex()); assertEquals(7, model.getLeadSelectionIndex()); model.setLeadSelectionIndex(1); checkIntervalState(0, 0, false); checkIntervalState(1, 3, true); checkIntervalState(4, 10, false); model.setSelectionInterval(3, 7); assertEquals(3, model.getAnchorSelectionIndex()); assertEquals(7, model.getLeadSelectionIndex()); model.setAnchorSelectionIndex(5); model.setLeadSelectionIndex(1); checkIntervalState(0, 0, false); checkIntervalState(1, 5, true); checkIntervalState(6, 10, false); } public void testMoveLeadSelectionIndex() throws Exception { model.addListSelectionListener(listener); model.setSelectionInterval(3, 6); listener.reset(); model.moveLeadSelectionIndex(-1); assertEquals(6, model.getLeadSelectionIndex()); assertEquals(0, listener.getEvents().size()); listener.reset(); model.moveLeadSelectionIndex(2); assertEquals(2, model.getLeadSelectionIndex()); checkIntervalState(0, 2, false); checkIntervalState(3, 6, true); checkIntervalState(7, 10, false); checkSingleEvent(2, 6, false); listener.reset(); model.moveLeadSelectionIndex(8); assertEquals(8, model.getLeadSelectionIndex()); checkIntervalState(0, 2, false); checkIntervalState(3, 6, true); checkIntervalState(7, 10, false); checkSingleEvent(2, 8, false); } public void testToString() throws Exception { assertNotNull(model.toString()); } private void checkIntervalState(final int beginIndex, final int endIndex, final boolean selected) { for (int i = beginIndex; i <= endIndex; i++) { assertEquals(selected, model.isSelectedIndex(i)); } } private void checkSingleEvent(final int beginIndex, final int endIndex, final boolean isAdjusting) { checkSingleEvent(listener, beginIndex, endIndex, isAdjusting); } private void checkSingleEvent(final TestListener listener, final int beginIndex, final int endIndex, final boolean isAdjusting) { assertEquals(1, listener.getEvents().size()); ListSelectionEvent event = listener.getEvents().get(0); assertEquals(model, event.getSource()); assertEquals(beginIndex, event.getFirstIndex()); assertEquals(endIndex, event.getLastIndex()); assertEquals(isAdjusting, event.getValueIsAdjusting()); } private class TestListener implements ListSelectionListener { private List<ListSelectionEvent> events = new ArrayList<ListSelectionEvent>(); public void valueChanged(final ListSelectionEvent event) { events.add(event); } public List<ListSelectionEvent> getEvents() { return events; } public void reset() { events.clear(); } } public void testIsValidInterval() throws Exception { // regression test for HARMONY-1965 try { model.addSelectionInterval(-2, 0); fail("addSelectionInterval should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { model.addSelectionInterval(0, -2); fail("addSelectionInterval should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { model.setSelectionInterval(-2, 0); fail("setSelectionInterval should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { model.setSelectionInterval(0, -2); fail("setSelectionInterval should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { model.removeSelectionInterval(-2, 0); fail("removeSelectionInterval should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { model.removeSelectionInterval(0, -2); fail("removeSelectionInterval should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { model.insertIndexInterval(-2, 0, true); fail("insertIndexInterval should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } if (isHarmony()) { try { model.insertIndexInterval(0, -2, true); fail("insertIndexInterval should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } } try { model.removeIndexInterval(-2, 0); fail("removeIndexInterval should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } try { model.removeIndexInterval(0, -2); fail("removeIndexInterval should throw IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException e) { } } }
apache-2.0
galan/verjson
src/test/java/de/galan/verjson/samples/v2/Example2SubA.java
729
package de.galan.verjson.samples.v2; /** * Sample implementation for subtype * * @author daniel */ public class Example2SubA extends Example2Sub { public String aaa; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((aaa == null) ? 0 : aaa.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Example2SubA other = (Example2SubA)obj; if (aaa == null) { if (other.aaa != null) { return false; } } else if (!aaa.equals(other.aaa)) { return false; } return true; } }
apache-2.0
AlexeyKashintsev/PlatypusJS
application/src/components/Forms/src/com/eas/client/forms/components/DropDownButton.java
20255
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.eas.client.forms.components; import com.eas.client.forms.Forms; import com.eas.client.forms.HasComponentEvents; import com.eas.client.forms.HasJsName; import com.eas.client.forms.HorizontalPosition; import com.eas.client.forms.Widget; import com.eas.client.forms.events.ActionEvent; import com.eas.client.forms.events.ComponentEvent; import com.eas.client.forms.events.MouseEvent; import com.eas.client.forms.events.rt.ControlEventsIProxy; import com.eas.client.forms.layouts.MarginLayout; import com.eas.design.Undesignable; import com.eas.gui.JDropDownButton; import com.eas.script.AlreadyPublishedException; import com.eas.script.EventMethod; import com.eas.script.HasPublished; import com.eas.script.NoPublisherException; import com.eas.script.ScriptFunction; import com.eas.script.Scripts; import java.awt.Color; import java.awt.Cursor; import java.awt.Font; import java.awt.event.FocusEvent; import java.awt.event.KeyEvent; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JPopupMenu; import jdk.nashorn.api.scripting.JSObject; /** * * @author mg */ public class DropDownButton extends JDropDownButton implements HasPublished, HasComponentEvents, HasJsName, Widget { public DropDownButton(String aText, Icon aIcon, int aIconTextGap) { this(aText, aIcon, aIconTextGap, null); } public DropDownButton(String aText, Icon aIcon) { this(aText, aIcon, 4); } private static final String CONSTRUCTOR_JSDOC = "" + "/**\n" + "* Drop-down button component.\n" + "* @param text the text of the component (optional).\n" + "* @param icon the icon of the component (optional).\n" + "* @param iconTextGap the text gap (optional).\n" + "* @param actionPerformed the function for the action performed handler (optional).\n" + "*/"; @ScriptFunction(jsDoc = CONSTRUCTOR_JSDOC, params = {"text", "icon", "iconTextGap", "actionPerformed"}) public DropDownButton(String aText, Icon aIcon, int aIconTextGap, JSObject aActionPerformedHandler) { super(aText, aIcon); super.setIconTextGap(aIconTextGap); super.setHorizontalTextPosition(HorizontalPosition.RIGHT); setOnActionPerformed(aActionPerformedHandler); } public DropDownButton(String aText, Icon aIcon, JSObject aActionPerformedHandler) { this(aText, aIcon, 4, aActionPerformedHandler); } public DropDownButton(String aText) { this(aText, null, 4); } public DropDownButton() { this(null, null, 4); } @ScriptFunction(jsDoc = JS_NAME_DOC) @Override public String getName() { return super.getName(); } @ScriptFunction @Override public void setName(String name) { super.setName(name); } @ScriptFunction(jsDoc = GET_NEXT_FOCUSABLE_COMPONENT_JSDOC) @Override public JComponent getNextFocusableComponent() { return (JComponent) super.getNextFocusableComponent(); } @ScriptFunction @Override public void setNextFocusableComponent(JComponent aValue) { super.setNextFocusableComponent(aValue); } protected String errorMessage; @ScriptFunction(jsDoc = ERROR_JSDOC) @Override public String getError() { return errorMessage; } @ScriptFunction @Override public void setError(String aValue) { errorMessage = aValue; } @ScriptFunction(jsDoc = BACKGROUND_JSDOC) @Override public Color getBackground() { return super.getBackground(); } @ScriptFunction @Override public void setBackground(Color aValue) { super.setBackground(aValue); } @ScriptFunction(jsDoc = FOREGROUND_JSDOC) @Override public Color getForeground() { return super.getForeground(); } @ScriptFunction @Override public void setForeground(Color aValue) { super.setForeground(aValue); } @ScriptFunction(jsDoc = VISIBLE_JSDOC) @Override public boolean getVisible() { return super.isVisible(); } @ScriptFunction @Override public void setVisible(boolean aValue) { super.setVisible(aValue); } @ScriptFunction(jsDoc = FOCUSABLE_JSDOC) @Override public boolean getFocusable() { return super.isFocusable(); } @ScriptFunction @Override public void setFocusable(boolean aValue) { super.setFocusable(aValue); } @ScriptFunction(jsDoc = ENABLED_JSDOC) @Override public boolean getEnabled() { return super.isEnabled(); } @ScriptFunction @Override public void setEnabled(boolean aValue) { super.setEnabled(aValue); } @ScriptFunction(jsDoc = TOOLTIP_TEXT_JSDOC) @Override public String getToolTipText() { return super.getToolTipText(); } @ScriptFunction @Override public void setToolTipText(String aValue) { super.setToolTipText(aValue); } @ScriptFunction(jsDoc = OPAQUE_TEXT_JSDOC) @Override public boolean getOpaque() { return super.isOpaque(); } @ScriptFunction @Override public void setOpaque(boolean aValue) { super.setOpaque(aValue); } @ScriptFunction(jsDoc = COMPONENT_POPUP_MENU_JSDOC) @Override public JPopupMenu getComponentPopupMenu() { return super.getComponentPopupMenu(); } @ScriptFunction @Override public void setComponentPopupMenu(JPopupMenu aMenu) { super.setComponentPopupMenu(aMenu); } @ScriptFunction(jsDoc = FONT_JSDOC) @Override public Font getFont() { return super.getFont(); } @ScriptFunction @Override public void setFont(Font aFont) { super.setFont(aFont); } @ScriptFunction(jsDoc = CURSOR_JSDOC) @Override public Cursor getCursor() { return super.getCursor(); } @ScriptFunction @Override public void setCursor(Cursor aCursor) { super.setCursor(aCursor); } @ScriptFunction(jsDoc = LEFT_JSDOC) @Override public int getLeft() { return super.getLocation().x; } @ScriptFunction @Override public void setLeft(int aValue) { if (super.getParent() != null && super.getParent().getLayout() instanceof MarginLayout) { MarginLayout.ajustLeft(this, aValue); } super.setLocation(aValue, getTop()); } @ScriptFunction(jsDoc = TOP_JSDOC) @Override public int getTop() { return super.getLocation().y; } @ScriptFunction @Override public void setTop(int aValue) { if (super.getParent() != null && super.getParent().getLayout() instanceof MarginLayout) { MarginLayout.ajustTop(this, aValue); } super.setLocation(getLeft(), aValue); } @ScriptFunction(jsDoc = WIDTH_JSDOC) @Override public int getWidth() { return super.getWidth(); } @ScriptFunction @Override public void setWidth(int aValue) { Widget.setWidth(this, aValue); } @ScriptFunction(jsDoc = HEIGHT_JSDOC) @Override public int getHeight() { return super.getHeight(); } @ScriptFunction @Override public void setHeight(int aValue) { Widget.setHeight(this, aValue); } @ScriptFunction(jsDoc = FOCUS_JSDOC) @Override public void focus() { super.requestFocus(); } @Override public String toString() { return String.format("%s [%s]", super.getName() != null ? super.getName() : "", getClass().getSimpleName()); } // Native API @ScriptFunction(jsDoc = NATIVE_COMPONENT_JSDOC) @Undesignable @Override public JComponent getComponent() { return this; } @ScriptFunction(jsDoc = NATIVE_ELEMENT_JSDOC) @Undesignable @Override public Object getElement() { return null; } private static final String DROP_DOWN_MENU_JSDOC = "" + "/**\n" + "* <code>PopupMenu</code> for the component.\n" + "*/"; @ScriptFunction(jsDoc = DROP_DOWN_MENU_JSDOC) @Override public JPopupMenu getDropDownMenu() { return super.getDropDownMenu(); } @ScriptFunction @Override public void setDropDownMenu(JPopupMenu aMenu) { super.setDropDownMenu(aMenu); } private static final String TEXT_JSDOC = "" + "/**\n" + "* Text on the button.\n" + "*/"; @ScriptFunction(jsDoc = TEXT_JSDOC) @Override public String getText() { return super.getText(); } @ScriptFunction @Override public void setText(String aValue) { super.setText(aValue); } private static final String ICON_JSDOC = "" + "/**\n" + "* Image picture for the button.\n" + "*/"; @ScriptFunction(jsDoc = ICON_JSDOC) @Override public Icon getIcon() { return super.getIcon(); } @ScriptFunction @Override public void setIcon(Icon aValue) { super.setIcon(aValue); } private static final String ICON_TEXT_GAP_JSDOC = "" + "/**\n" + "* The amount of space between the text and the icon displayed in this button.\n" + "*/"; @ScriptFunction(jsDoc = ICON_TEXT_GAP_JSDOC) @Override public int getIconTextGap() { return super.getIconTextGap(); } @ScriptFunction @Override public void setIconTextGap(int aValue) { super.setIconTextGap(aValue); } private static final String HORIZONTAL_TEXT_POSITION_JSDOC = "" + "/**\n" + "* Horizontal position of the text relative to the icon.\n" + "*/"; @ScriptFunction(jsDoc = HORIZONTAL_TEXT_POSITION_JSDOC) @Override public int getHorizontalTextPosition() { return super.getHorizontalTextPosition(); } @ScriptFunction @Override public void setHorizontalTextPosition(int aValue) { super.setHorizontalTextPosition(aValue); } private static final String VERTICAL_TEXT_POSITION_JSDOC = "" + "/**\n" + "* Vertical position of the text relative to the icon.\n" + "*/"; @ScriptFunction(jsDoc = VERTICAL_TEXT_POSITION_JSDOC) @Override public int getVerticalTextPosition() { return super.getVerticalTextPosition(); } @ScriptFunction @Override public void setVerticalTextPosition(int aValue) { super.setVerticalTextPosition(aValue); } protected JSObject published; @Override public JSObject getPublished() { if (published == null) { JSObject publisher = Scripts.getSpace().getPublisher(this.getClass().getName()); if (publisher == null || !publisher.isFunction()) { throw new NoPublisherException(); } published = (JSObject) publisher.call(null, new Object[]{this}); } return published; } @Override public void setPublished(JSObject aValue) { if (published != null) { throw new AlreadyPublishedException(); } published = aValue; } protected ControlEventsIProxy eventsProxy = new ControlEventsIProxy(this); @ScriptFunction(jsDoc = ON_MOUSE_CLICKED_JSDOC) @EventMethod(eventClass = MouseEvent.class) @Undesignable @Override public JSObject getOnMouseClicked() { return eventsProxy.getHandlers().get(ControlEventsIProxy.mouseClicked); } @ScriptFunction @Override public void setOnMouseClicked(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.mouseClicked, aValue); } @ScriptFunction(jsDoc = ON_MOUSE_DRAGGED_JSDOC) @EventMethod(eventClass = MouseEvent.class) @Undesignable @Override public JSObject getOnMouseDragged() { return eventsProxy.getHandlers().get(ControlEventsIProxy.mouseDragged); } @ScriptFunction @Override public void setOnMouseDragged(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.mouseDragged, aValue); } @ScriptFunction(jsDoc = ON_MOUSE_ENTERED_JSDOC) @EventMethod(eventClass = MouseEvent.class) @Undesignable @Override public JSObject getOnMouseEntered() { return eventsProxy.getHandlers().get(ControlEventsIProxy.mouseEntered); } @ScriptFunction @Override public void setOnMouseEntered(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.mouseEntered, aValue); } @ScriptFunction(jsDoc = ON_MOUSE_EXITED_JSDOC) @EventMethod(eventClass = MouseEvent.class) @Undesignable @Override public JSObject getOnMouseExited() { return eventsProxy.getHandlers().get(ControlEventsIProxy.mouseExited); } @ScriptFunction @Override public void setOnMouseExited(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.mouseExited, aValue); } @ScriptFunction(jsDoc = ON_MOUSE_MOVED_JSDOC) @EventMethod(eventClass = MouseEvent.class) @Undesignable @Override public JSObject getOnMouseMoved() { return eventsProxy.getHandlers().get(ControlEventsIProxy.mouseMoved); } @ScriptFunction @Override public void setOnMouseMoved(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.mouseMoved, aValue); } @ScriptFunction(jsDoc = ON_MOUSE_PRESSED_JSDOC) @EventMethod(eventClass = MouseEvent.class) @Undesignable @Override public JSObject getOnMousePressed() { return eventsProxy.getHandlers().get(ControlEventsIProxy.mousePressed); } @ScriptFunction @Override public void setOnMousePressed(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.mousePressed, aValue); } @ScriptFunction(jsDoc = ON_MOUSE_RELEASED_JSDOC) @EventMethod(eventClass = MouseEvent.class) @Undesignable @Override public JSObject getOnMouseReleased() { return eventsProxy.getHandlers().get(ControlEventsIProxy.mouseReleased); } @ScriptFunction @Override public void setOnMouseReleased(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.mouseReleased, aValue); } @ScriptFunction(jsDoc = ON_MOUSE_WHEEL_MOVED_JSDOC) @EventMethod(eventClass = MouseEvent.class) @Undesignable @Override public JSObject getOnMouseWheelMoved() { return eventsProxy.getHandlers().get(ControlEventsIProxy.mouseWheelMoved); } @ScriptFunction @Override public void setOnMouseWheelMoved(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.mouseWheelMoved, aValue); } @ScriptFunction(jsDoc = ON_ACTION_PERFORMED_JSDOC) @EventMethod(eventClass = ActionEvent.class) @Undesignable @Override public JSObject getOnActionPerformed() { return eventsProxy.getHandlers().get(ControlEventsIProxy.actionPerformed); } @ScriptFunction @Override public void setOnActionPerformed(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.actionPerformed, aValue); } @ScriptFunction(jsDoc = ON_COMPONENT_HIDDEN_JSDOC) @EventMethod(eventClass = ComponentEvent.class) @Undesignable @Override public JSObject getOnComponentHidden() { return eventsProxy.getHandlers().get(ControlEventsIProxy.componentHidden); } @ScriptFunction @Override public void setOnComponentHidden(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.componentHidden, aValue); } @ScriptFunction(jsDoc = ON_COMPONENT_MOVED_JSDOC) @EventMethod(eventClass = ComponentEvent.class) @Undesignable @Override public JSObject getOnComponentMoved() { return eventsProxy.getHandlers().get(ControlEventsIProxy.componentMoved); } @ScriptFunction @Override public void setOnComponentMoved(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.componentMoved, aValue); } @ScriptFunction(jsDoc = ON_COMPONENT_RESIZED_JSDOC) @EventMethod(eventClass = ComponentEvent.class) @Undesignable @Override public JSObject getOnComponentResized() { return eventsProxy.getHandlers().get(ControlEventsIProxy.componentResized); } @ScriptFunction @Override public void setOnComponentResized(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.componentResized, aValue); } @ScriptFunction(jsDoc = ON_COMPONENT_SHOWN_JSDOC) @EventMethod(eventClass = ComponentEvent.class) @Undesignable @Override public JSObject getOnComponentShown() { return eventsProxy.getHandlers().get(ControlEventsIProxy.componentShown); } @ScriptFunction @Override public void setOnComponentShown(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.componentShown, aValue); } @ScriptFunction(jsDoc = ON_FOCUS_GAINED_JSDOC) @EventMethod(eventClass = FocusEvent.class) @Undesignable @Override public JSObject getOnFocusGained() { return eventsProxy.getHandlers().get(ControlEventsIProxy.focusGained); } @ScriptFunction @Override public void setOnFocusGained(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.focusGained, aValue); } @ScriptFunction(jsDoc = ON_FOCUS_LOST_JSDOC) @EventMethod(eventClass = FocusEvent.class) @Undesignable @Override public JSObject getOnFocusLost() { return eventsProxy != null ? eventsProxy.getHandlers().get(ControlEventsIProxy.focusLost) : null; } @ScriptFunction @Override public void setOnFocusLost(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.focusLost, aValue); } @ScriptFunction(jsDoc = ON_KEY_PRESSED_JSDOC) @EventMethod(eventClass = KeyEvent.class) @Undesignable @Override public JSObject getOnKeyPressed() { return eventsProxy.getHandlers().get(ControlEventsIProxy.keyPressed); } @ScriptFunction @Override public void setOnKeyPressed(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.keyPressed, aValue); } @ScriptFunction(jsDoc = ON_KEY_RELEASED_JSDOC) @EventMethod(eventClass = KeyEvent.class) @Undesignable @Override public JSObject getOnKeyReleased() { return eventsProxy.getHandlers().get(ControlEventsIProxy.keyReleased); } @ScriptFunction @Override public void setOnKeyReleased(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.keyReleased, aValue); } @ScriptFunction(jsDoc = ON_KEY_TYPED_JSDOC) @EventMethod(eventClass = KeyEvent.class) @Undesignable @Override public JSObject getOnKeyTyped() { return eventsProxy.getHandlers().get(ControlEventsIProxy.keyTyped); } @ScriptFunction @Override public void setOnKeyTyped(JSObject aValue) { eventsProxy.getHandlers().put(ControlEventsIProxy.keyTyped, aValue); } // published parent @ScriptFunction(name = "parent", jsDoc = PARENT_JSDOC) @Override public Widget getParentWidget() { return Forms.lookupPublishedParent(this); } }
apache-2.0
cdancy/artifactory-rest
src/main/java/com/cdancy/artifactory/rest/features/StorageApi.java
4064
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cdancy.artifactory.rest.features; import javax.inject.Named; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.cdancy.artifactory.rest.binders.BindListPropertiesToPath; import com.cdancy.artifactory.rest.binders.BindMapPropertiesToPath; import com.cdancy.artifactory.rest.domain.artifact.Artifact; import com.cdancy.artifactory.rest.domain.storage.FileList; import com.cdancy.artifactory.rest.domain.storage.StorageInfo; import org.jclouds.javax.annotation.Nullable; import org.jclouds.Fallbacks; import org.jclouds.Fallbacks.FalseOnNotFoundOr404; import org.jclouds.rest.annotations.*; import com.cdancy.artifactory.rest.filters.ArtifactoryAuthenticationFilter; import java.util.List; import java.util.Map; @Path("/api") @Consumes(MediaType.APPLICATION_JSON) @RequestFilters(ArtifactoryAuthenticationFilter.class) public interface StorageApi { @Named("storage:set-item-properties") @Path("/storage/{repoKey}/{itemPath}") @Fallback(FalseOnNotFoundOr404.class) @QueryParams(keys = { "recursive" }, values = { "1" }) @PUT boolean setItemProperties(@PathParam("repoKey") String repoKey, @PathParam("itemPath") String itemPath, @BinderParam(BindMapPropertiesToPath.class) Map<String, List<String>> properties); @Named("storage:get-item-properties") @Path("/storage/{repoKey}/{itemPath}") @QueryParams(keys = { "properties" }) @Fallback(Fallbacks.EmptyMapOnNotFoundOr404.class) @SelectJson({"properties"}) @GET Map<String, List<String>> getItemProperties(@PathParam("repoKey") String repoKey, @PathParam("itemPath") String itemPath); @Named("storage:delete-item-properties") @Path("/storage/{repoKey}/{itemPath}") @Fallback(FalseOnNotFoundOr404.class) @QueryParams(keys = { "recursive" }, values = { "1" }) @DELETE boolean deleteItemProperties(@PathParam("repoKey") String repoKey, @PathParam("itemPath") String itemPath, @BinderParam(BindListPropertiesToPath.class) List<String> properties); @Named("storage:info") @Path("/storageinfo") @GET StorageInfo storageInfo(); @Named("storage:file-list") @Path("/storage/{repoKey}/{itemPath}") @QueryParams(keys = { "list" }, values = { "true" }) @GET FileList fileList(@PathParam("repoKey") String repoKey, @PathParam("itemPath") String itemPath, @Nullable @QueryParam("deep") Integer deep, @Nullable @QueryParam("depth") Integer depth, @Nullable @QueryParam("listFolders") Integer listFolders, @Nullable @QueryParam("includeRootPath") Integer includeRootPath); @Named("storage:file-info") @Path("/storage/{repoKey}/{itemPath}") @Fallback(Fallbacks.NullOnNotFoundOr404.class) @GET Artifact fileInfo(@PathParam("repoKey") String repoKey, @PathParam("itemPath") String itemPath); }
apache-2.0
wuyinlei/SuperMarket
src/main/java/com/wuyin/supermarket/holder/DetailSafeHolder.java
7804
package com.wuyin.supermarket.holder; import android.animation.Animator; import android.animation.ValueAnimator; import android.graphics.Color; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.wuyin.supermarket.R; import com.wuyin.supermarket.holder.base.BaseHolder; import com.wuyin.supermarket.model.AppInfo; import com.wuyin.supermarket.uri.Constants; import com.wuyin.supermarket.utils.UIUtils; import android.view.ViewGroup.LayoutParams; import java.util.List; /** * Created by yinlong on 2016/5/11. */ public class DetailSafeHolder extends BaseHolder<AppInfo> implements View.OnClickListener { private RelativeLayout safe_layout; private LinearLayout safe_content; private ImageView safe_arrow; ImageView[] ivs; ImageView[] iv_des; TextView[] tv_des; LinearLayout[] des_layout; @Override public View initView() { View view = UIUtils.inflate(R.layout.detail_safe); initViews(view); return view; } private void initViews(View view) { ivs = new ImageView[4]; // 初始化标题栏的图片 ivs[0] = (ImageView) view.findViewById(R.id.iv_1); ivs[1] = (ImageView) view.findViewById(R.id.iv_2); ivs[2] = (ImageView) view.findViewById(R.id.iv_3); ivs[3] = (ImageView) view.findViewById(R.id.iv_4); iv_des = new ImageView[4]; // 初始化每个条目描述的图片 iv_des[0] = (ImageView) view.findViewById(R.id.des_iv_1); iv_des[1] = (ImageView) view.findViewById(R.id.des_iv_2); iv_des[2] = (ImageView) view.findViewById(R.id.des_iv_3); iv_des[3] = (ImageView) view.findViewById(R.id.des_iv_4); tv_des = new TextView[4]; // 初始化每个条目描述的文本 tv_des[0] = (TextView) view.findViewById(R.id.des_tv_1); tv_des[1] = (TextView) view.findViewById(R.id.des_tv_2); tv_des[2] = (TextView) view.findViewById(R.id.des_tv_3); tv_des[3] = (TextView) view.findViewById(R.id.des_tv_4); des_layout = new LinearLayout[4]; // 初始化条目线性布局 des_layout[0] = (LinearLayout) view.findViewById(R.id.des_layout_1); des_layout[1] = (LinearLayout) view.findViewById(R.id.des_layout_2); des_layout[2] = (LinearLayout) view.findViewById(R.id.des_layout_3); des_layout[3] = (LinearLayout) view.findViewById(R.id.des_layout_4); safe_content = (LinearLayout) view.findViewById(R.id.safe_content); safe_arrow = (ImageView) view.findViewById(R.id.safe_arrow); safe_layout = (RelativeLayout) view.findViewById(R.id.safe_layout); LayoutParams layoutParams = safe_content.getLayoutParams(); layoutParams.height=0; safe_content.setLayoutParams(layoutParams); safe_arrow.setImageResource(R.mipmap.arrow_down); } @Override public void refreshData(AppInfo data) { safe_layout.setOnClickListener(this); List<String> safeUrl = data.getSafeUrl(); List<String> safeDesUrl = data.getSafeDesUrl(); List<String> safeDes = data.getSafeDes(); List<Integer> safeDesColor = data.getSafeDesColor(); // 0 1 2 3 for (int i = 0; i < 4; i++) { if (i < safeUrl.size() && i < safeDesUrl.size() && i < safeDes.size() && i < safeDesColor.size()) { ivs[i].setVisibility(View.VISIBLE); des_layout[i].setVisibility(View.VISIBLE); Glide.with(UIUtils.getContext()).load(Constants.IMAGE_URL+safeUrl.get(i)).into(ivs[i]); Glide.with(UIUtils.getContext()).load(Constants.IMAGE_URL+safeDesUrl.get(i)).into(iv_des[i]); tv_des[i].setText(safeDes.get(i)); // 根据服务器数据显示不同的颜色 int color; int colorType = safeDesColor.get(i); if (colorType >= 1 && colorType <= 3) { color = Color.rgb(255, 153, 0); // 00 00 00 } else if (colorType == 4) { color = Color.rgb(0, 177, 62); } else { color = Color.rgb(122, 122, 122); } tv_des[i].setTextColor(color); } else { ivs[i].setVisibility(View.GONE); des_layout[i].setVisibility(View.GONE); } } } boolean flag=false; @Override public void onClick(View v) { if (v.getId() == R.id.safe_layout) { int startHeight; int targetHeight; if (!flag) { // 展开的动画 startHeight=0; targetHeight=getMeasureHeight(); flag = true; //safe_content.setVisibility(View.VISIBLE); safe_content.getMeasuredHeight(); // 0 } else { flag=false; //safe_content.setVisibility(View.GONE); startHeight=getMeasureHeight(); targetHeight=0; } // 值动画 ValueAnimator animator=ValueAnimator.ofInt(startHeight,targetHeight); final RelativeLayout.LayoutParams layoutParams = (android.widget.RelativeLayout.LayoutParams) safe_content.getLayoutParams(); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { // 监听值的变化 @Override public void onAnimationUpdate(ValueAnimator animator) { int value=(Integer) animator.getAnimatedValue();// 运行当前时间点的一个值 layoutParams.height=value; safe_content.setLayoutParams(layoutParams);// 刷新界面 } }); animator.addListener(new Animator.AnimatorListener() { // 监听动画执行 //当动画开始执行的时候调用 @Override public void onAnimationStart(Animator arg0) { // TODO Auto-generated method stub } @Override public void onAnimationRepeat(Animator arg0) { } @Override public void onAnimationEnd(Animator arg0) { if(flag){ safe_arrow.setImageResource(R.mipmap.arrow_up); }else{ safe_arrow.setImageResource(R.mipmap.arrow_down); } } @Override public void onAnimationCancel(Animator arg0) { } }); animator.setDuration(500); animator.start(); } } //onMeasure() 制定测量的规则 // measure() 实际测量 /** * 获取控件实际的高度 */ public int getMeasureHeight(){ int width = safe_content.getMeasuredWidth(); // 由于宽度不会发生变化 宽度的值取出来 safe_content.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;// 让高度包裹内容 int widthMeasureSpec= View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.EXACTLY, width); // mode+size // 参数1 测量控件mode 参数2 大小 int heightMeasureSpec= View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.AT_MOST, 1000);// 我的高度 最大是1000 // 测量规则 宽度是一个精确的值width, 高度最大是1000,以实际为准 safe_content.measure(widthMeasureSpec, heightMeasureSpec); // 通过该方法重新测量控件 return safe_content.getMeasuredHeight(); } }
apache-2.0
leangen/GraphQL-SPQR
src/main/java/io/leangen/graphql/generator/RelayMappingConfig.java
293
package io.leangen.graphql.generator; public class RelayMappingConfig { public boolean inferNodeInterface = true; public boolean strictConnectionSpec = true; public boolean relayCompliantMutations; public String wrapperFieldName; public String wrapperFieldDescription; }
apache-2.0
SENA-CEET/1349397-Trimestre-4
java/Servlets/ejemploTemplates/src/main/java/co/edu/sena/ejemplotemplates/view/frontcontroller/ObservacionGeneralController.java
6991
package co.edu.sena.ejemplotemplates.view.frontcontroller; import co.edu.sena.ejemplotemplates.model.entities.ObservacionGeneral; import co.edu.sena.ejemplotemplates.view.frontcontroller.util.JsfUtil; import co.edu.sena.ejemplotemplates.view.frontcontroller.util.JsfUtil.PersistAction; import co.edu.sena.ejemplotemplates.controller.ejbs.ObservacionGeneralFacade; import java.io.Serializable; import java.util.List; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.EJB; import javax.ejb.EJBException; import javax.inject.Named; import javax.enterprise.context.SessionScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; @Named("observacionGeneralController") @SessionScoped public class ObservacionGeneralController implements Serializable { @EJB private co.edu.sena.ejemplotemplates.controller.ejbs.ObservacionGeneralFacade ejbFacade; private List<ObservacionGeneral> items = null; private ObservacionGeneral selected; public ObservacionGeneralController() { } public ObservacionGeneral getSelected() { return selected; } public void setSelected(ObservacionGeneral selected) { this.selected = selected; } protected void setEmbeddableKeys() { selected.getObservacionGeneralPK().setGrupoCodigo(selected.getGrupoProyecto().getGrupoProyectoPK().getCodigo()); selected.getObservacionGeneralPK().setGrupoNumeroFicha(selected.getGrupoProyecto().getGrupoProyectoPK().getNumeroFicha()); } protected void initializeEmbeddableKey() { selected.setObservacionGeneralPK(new co.edu.sena.ejemplotemplates.model.entities.ObservacionGeneralPK()); } private ObservacionGeneralFacade getFacade() { return ejbFacade; } public ObservacionGeneral prepareCreate() { selected = new ObservacionGeneral(); initializeEmbeddableKey(); return selected; } public void create() { persist(PersistAction.CREATE, ResourceBundle.getBundle("/Bundle").getString("ObservacionGeneralCreated")); if (!JsfUtil.isValidationFailed()) { items = null; // Invalidate list of items to trigger re-query. } } public void update() { persist(PersistAction.UPDATE, ResourceBundle.getBundle("/Bundle").getString("ObservacionGeneralUpdated")); } public void destroy() { persist(PersistAction.DELETE, ResourceBundle.getBundle("/Bundle").getString("ObservacionGeneralDeleted")); if (!JsfUtil.isValidationFailed()) { selected = null; // Remove selection items = null; // Invalidate list of items to trigger re-query. } } public List<ObservacionGeneral> getItems() { if (items == null) { items = getFacade().findAll(); } return items; } private void persist(PersistAction persistAction, String successMessage) { if (selected != null) { setEmbeddableKeys(); try { if (persistAction != PersistAction.DELETE) { getFacade().edit(selected); } else { getFacade().remove(selected); } JsfUtil.addSuccessMessage(successMessage); } catch (EJBException ex) { String msg = ""; Throwable cause = ex.getCause(); if (cause != null) { msg = cause.getLocalizedMessage(); } if (msg.length() > 0) { JsfUtil.addErrorMessage(msg); } else { JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } catch (Exception ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } } public ObservacionGeneral getObservacionGeneral(co.edu.sena.ejemplotemplates.model.entities.ObservacionGeneralPK id) { return getFacade().find(id); } public List<ObservacionGeneral> getItemsAvailableSelectMany() { return getFacade().findAll(); } public List<ObservacionGeneral> getItemsAvailableSelectOne() { return getFacade().findAll(); } @FacesConverter(forClass = ObservacionGeneral.class) public static class ObservacionGeneralControllerConverter implements Converter { private static final String SEPARATOR = "#"; private static final String SEPARATOR_ESCAPED = "\\#"; @Override public Object getAsObject(FacesContext facesContext, UIComponent component, String value) { if (value == null || value.length() == 0) { return null; } ObservacionGeneralController controller = (ObservacionGeneralController) facesContext.getApplication().getELResolver(). getValue(facesContext.getELContext(), null, "observacionGeneralController"); return controller.getObservacionGeneral(getKey(value)); } co.edu.sena.ejemplotemplates.model.entities.ObservacionGeneralPK getKey(String value) { co.edu.sena.ejemplotemplates.model.entities.ObservacionGeneralPK key; String values[] = value.split(SEPARATOR_ESCAPED); key = new co.edu.sena.ejemplotemplates.model.entities.ObservacionGeneralPK(); key.setGrupoNumeroFicha(values[0]); key.setGrupoCodigo(Integer.parseInt(values[1])); key.setIdObservacion(Integer.parseInt(values[2])); return key; } String getStringKey(co.edu.sena.ejemplotemplates.model.entities.ObservacionGeneralPK value) { StringBuilder sb = new StringBuilder(); sb.append(value.getGrupoNumeroFicha()); sb.append(SEPARATOR); sb.append(value.getGrupoCodigo()); sb.append(SEPARATOR); sb.append(value.getIdObservacion()); return sb.toString(); } @Override public String getAsString(FacesContext facesContext, UIComponent component, Object object) { if (object == null) { return null; } if (object instanceof ObservacionGeneral) { ObservacionGeneral o = (ObservacionGeneral) object; return getStringKey(o.getObservacionGeneralPK()); } else { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), ObservacionGeneral.class.getName()}); return null; } } } }
apache-2.0
spacelan/openrasp
agent/java/engine/src/main/java/com/baidu/openrasp/plugin/checker/AttackCheckListener.java
1116
/* * Copyright 2017-2018 Baidu 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.baidu.openrasp.plugin.checker; import com.baidu.openrasp.plugin.event.CheckEventListener; import com.baidu.openrasp.plugin.info.AttackInfo; import com.baidu.openrasp.plugin.info.EventInfo; /** * Created by tyy on 17-11-22. * * 攻击检测事件监听器 */ public class AttackCheckListener implements CheckEventListener { @Override public void onCheckUpdate(EventInfo info) { if (info instanceof AttackInfo) { Checker.ATTACK_ALARM_LOGGER.info(info); } } }
apache-2.0
stevenhva/InfoLearn_OpenOLAT
src/main/java/org/olat/course/CoursefolderWebDAVNamedContainer.java
2518
/** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */ package org.olat.course; import org.olat.core.id.OLATResourceable; import org.olat.core.logging.OLog; import org.olat.core.logging.Tracing; import org.olat.core.util.resource.OresHelper; import org.olat.core.util.vfs.NamedContainerImpl; import org.olat.core.util.vfs.VFSContainer; import org.olat.core.util.vfs.filters.VFSItemFilter; /** * * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com */ class CoursefolderWebDAVNamedContainer extends NamedContainerImpl { private static final OLog log = Tracing.createLoggerFor(CoursefolderWebDAVNamedContainer.class); private OLATResourceable res; private VFSContainer parentContainer; public CoursefolderWebDAVNamedContainer(String courseTitle, OLATResourceable res) { super(courseTitle, null); this.res = OresHelper.clone(res); } @Override public void setDefaultItemFilter(VFSItemFilter defaultFilter) { // } @Override public VFSContainer getDelegate() { if(super.getDelegate() == null) { try { ICourse course = CourseFactory.loadCourse(res.getResourceableId()); VFSContainer courseFolder = course.getCourseFolderContainer(); setDelegate(courseFolder); if(parentContainer != null) { super.setParentContainer(parentContainer); parentContainer = null; } } catch (Exception e) { log.error("Error loading course: " + res, e); } } return super.getDelegate(); } @Override public VFSItemFilter getDefaultItemFilter() { return null; } @Override public void setParentContainer(VFSContainer parentContainer) { if(super.getDelegate() == null) { this.parentContainer = parentContainer; } else { super.setParentContainer(parentContainer); } } }
apache-2.0
pon-prisma/PrismaDemo
DAL/src/main/java/it/prisma/dal/dao/paas/services/caaas/EjbcaCostDAO.java
609
package it.prisma.dal.dao.paas.services.caaas; import it.prisma.dal.dao.QueryDSLGenericDAO; import it.prisma.dal.entities.paas.services.caaas.EjbcaCost; import it.prisma.dal.entities.paas.services.caaas.QEjbcaCost; import javax.ejb.Local; import javax.ejb.Stateless; import com.mysema.query.jpa.impl.JPAQuery; @Local(EjbcaCostDAO.class) //@TransactionAttribute(TransactionAttributeType.REQUIRED) @Stateless public class EjbcaCostDAO extends QueryDSLGenericDAO<EjbcaCost, Long> { private QEjbcaCost qEjbcaCost; public EjbcaCostDAO() { super(EjbcaCost.class); qEjbcaCost = QEjbcaCost.ejbcaCost; } }
apache-2.0
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/highlighter/MdColorSettingsPage.java
17992
// Copyright (c) 2015-2020 Vladimir Schneider <vladimir.schneider@gmail.com> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.highlighter; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.ColorDescriptor; import com.intellij.openapi.options.colors.ColorSettingsPage; import com.intellij.openapi.util.io.FileUtil; import com.vladsch.md.nav.MdBundle; import com.vladsch.md.nav.highlighter.api.MdColorSettingsExtension; import com.vladsch.md.nav.settings.MdApplicationSettings; import com.vladsch.md.nav.settings.MdRenderingProfile; import icons.MdIcons; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.Icon; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.List; import java.util.Map; public class MdColorSettingsPage implements ColorSettingsPage { private final static Logger LOG = Logger.getInstance(MdColorSettingsPage.class.getName()); protected static final ColorDescriptor[] EMPTY_COLOR_DESCRIPTOR_ARRAY = new ColorDescriptor[] { }; @NonNls public static final String SAMPLE_MARKDOWN_DOCUMENT_PATH = "/com/vladsch/md/nav/samples/sample-document.md"; protected static final List<AttributesDescriptor> attributeDescriptors = new LinkedList<>(); private static final AttributesDescriptor[] EMPTY_DESCRIPTORS = new AttributesDescriptor[0]; private void addTextAttributesKey(String name, TextAttributesKey attributesKey) { attributeDescriptors.add(new AttributesDescriptor(name, attributesKey)); } public MdColorSettingsPage() { MdHighlighterColors highlighterColors = MdHighlighterColors.getInstance(); addTextAttributesKey(MdBundle.message("colors.abbreviation"), highlighterColors.ABBREVIATION_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.abbreviation-short"), highlighterColors.ABBREVIATION_SHORT_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.abbreviation-expanded"), highlighterColors.ABBREVIATION_EXPANDED_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.abbreviated-text"), highlighterColors.ABBREVIATED_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.auto-link"), highlighterColors.AUTO_LINK_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.anchor"), highlighterColors.ANCHOR_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.anchor-id"), highlighterColors.ANCHOR_ID_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.emoji-marker"), highlighterColors.EMOJI_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.emoji-id"), highlighterColors.EMOJI_ID_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.block-quote"), highlighterColors.BLOCK_QUOTE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.bold"), highlighterColors.BOLD_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.bold-marker"), highlighterColors.BOLD_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.underline"), highlighterColors.UNDERLINE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.underline-marker"), highlighterColors.UNDERLINE_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.superscript"), highlighterColors.SUPERSCRIPT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.superscript-marker"), highlighterColors.SUPERSCRIPT_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.subscript"), highlighterColors.SUBSCRIPT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.subscript-marker"), highlighterColors.SUBSCRIPT_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.bullet-list"), highlighterColors.BULLET_LIST_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.block-comment"), highlighterColors.BLOCK_COMMENT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.comment"), highlighterColors.COMMENT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.code"), highlighterColors.CODE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.code-marker"), highlighterColors.CODE_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.definition-marker"), highlighterColors.DEFINITION_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.definition-term"), highlighterColors.DEFINITION_TERM_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.link-ref"), highlighterColors.LINK_REF_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.atx-header"), highlighterColors.ATX_HEADER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.setext-header"), highlighterColors.SETEXT_HEADER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.header-text"), highlighterColors.HEADER_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.atx-header-marker"), highlighterColors.HEADER_ATX_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.setext-header-marker"), highlighterColors.HEADER_SETEXT_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.hrule"), highlighterColors.HRULE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.html-block"), highlighterColors.HTML_BLOCK_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.image"), highlighterColors.IMAGE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.inline-html"), highlighterColors.INLINE_HTML_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.html-entity"), highlighterColors.HTML_ENTITY_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.italic"), highlighterColors.ITALIC_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.italic-marker"), highlighterColors.ITALIC_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.jekyll-front-matter-block"), highlighterColors.JEKYLL_FRONT_MATTER_BLOCK_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.jekyll-front-matter-marker"), highlighterColors.JEKYLL_FRONT_MATTER_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.jekyll-tag-marker"), highlighterColors.JEKYLL_TAG_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.jekyll-tag-name"), highlighterColors.JEKYLL_TAG_NAME_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.jekyll-tag-parameters"), highlighterColors.JEKYLL_TAG_PARAMETERS_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.mail-link"), highlighterColors.MAIL_LINK_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.ordered-list"), highlighterColors.ORDERED_LIST_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.quote"), highlighterColors.QUOTE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.quoted-text"), highlighterColors.QUOTED_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.smarts"), highlighterColors.SMARTS_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.special-text"), highlighterColors.SPECIAL_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.special-text-marker"), highlighterColors.SPECIAL_TEXT_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.line-break-spaces"), highlighterColors.LINE_BREAK_SPACES_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.strikethrough"), highlighterColors.STRIKETHROUGH_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.strikethrough-marker"), highlighterColors.STRIKETHROUGH_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table"), highlighterColors.TABLE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-separator"), highlighterColors.TABLE_SEPARATOR_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-caption"), highlighterColors.TABLE_CAPTION_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-caption-marker"), highlighterColors.TABLE_CAPTION_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-cell-reven-ceven"), highlighterColors.TABLE_CELL_REVEN_CEVEN_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-cell-reven-codd"), highlighterColors.TABLE_CELL_REVEN_CODD_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-cell-rodd-ceven"), highlighterColors.TABLE_CELL_RODD_CEVEN_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-cell-rodd-codd"), highlighterColors.TABLE_CELL_RODD_CODD_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-row-even"), highlighterColors.TABLE_ROW_EVEN_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-row-odd"), highlighterColors.TABLE_ROW_ODD_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-header-cell-reven-ceven"), highlighterColors.TABLE_HDR_CELL_REVEN_CEVEN_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-header-cell-reven-codd"), highlighterColors.TABLE_HDR_CELL_REVEN_CODD_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-header-cell-rodd-ceven"), highlighterColors.TABLE_HDR_CELL_RODD_CEVEN_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-header-cell-rodd-codd"), highlighterColors.TABLE_HDR_CELL_RODD_CODD_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-header-row-even"), highlighterColors.TABLE_HDR_ROW_EVEN_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-header-row-odd"), highlighterColors.TABLE_HDR_ROW_ODD_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-column-even"), highlighterColors.TABLE_SEP_COLUMN_EVEN_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.table-column-odd"), highlighterColors.TABLE_SEP_COLUMN_ODD_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.task-item-marker-done"), highlighterColors.TASK_DONE_ITEM_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.task-item-done-text"), highlighterColors.TASK_DONE_ITEM_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.task-item-marker"), highlighterColors.TASK_ITEM_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.text"), highlighterColors.TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.wiki-link-marker"), highlighterColors.WIKI_LINK_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.wiki-link-separator"), highlighterColors.WIKI_LINK_SEPARATOR_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.wiki-link-ref"), highlighterColors.WIKI_LINK_REF_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.wiki-link-ref-anchor"), highlighterColors.WIKI_LINK_REF_ANCHOR_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.wiki-link-ref-anchor-marker"), highlighterColors.WIKI_LINK_REF_ANCHOR_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.wiki-link-text"), highlighterColors.WIKI_LINK_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-image"), highlighterColors.REFERENCE_IMAGE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-link"), highlighterColors.REFERENCE_LINK_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference"), highlighterColors.REFERENCE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.verbatim"), highlighterColors.VERBATIM_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-image-reference"), highlighterColors.REFERENCE_IMAGE_REFERENCE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-image-text"), highlighterColors.REFERENCE_IMAGE_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.explicit-link"), highlighterColors.EXPLICIT_LINK_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-link-reference"), highlighterColors.REFERENCE_LINK_REFERENCE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-link-text"), highlighterColors.REFERENCE_LINK_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-address"), highlighterColors.REFERENCE_LINK_REF_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-title"), highlighterColors.REFERENCE_TITLE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-text"), highlighterColors.REFERENCE_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-anchor"), highlighterColors.REFERENCE_ANCHOR_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.reference-anchor-marker"), highlighterColors.REFERENCE_ANCHOR_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.verbatim-marker"), highlighterColors.VERBATIM_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.verbatim-content"), highlighterColors.VERBATIM_CONTENT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.verbatim-lang"), highlighterColors.VERBATIM_LANG_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.link-ref-text"), highlighterColors.LINK_REF_TEXT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.link-ref-title"), highlighterColors.LINK_REF_TITLE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.link-ref-anchor"), highlighterColors.LINK_REF_ANCHOR_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.link-ref-anchor-marker"), highlighterColors.LINK_REF_ANCHOR_MARKER_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.image-link-ref"), highlighterColors.IMAGE_LINK_REF_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.image-url-content"), highlighterColors.IMAGE_URL_CONTENT_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.image-link-ref-title"), highlighterColors.IMAGE_LINK_REF_TITLE_ATTR_KEY); addTextAttributesKey(MdBundle.message("colors.image-alt-text"), highlighterColors.IMAGE_ALT_TEXT_ATTR_KEY); for (MdColorSettingsExtension extension : MdColorSettingsExtension.EXTENSIONS.getValue()) { extension.addTextAttributes(this::addTextAttributesKey); } if (MdApplicationSettings.getInstance().getDebugSettings().getDebugCombinationColors()) { // add the combination colors for (TextAttributesKey key : MdSyntaxHighlighter.getMergedKeys()) { addTextAttributesKey(key.getExternalName(), key); } } } @Nullable public Map<String, TextAttributesKey> getAdditionalHighlightingTagToDescriptorMap() { return null; } /** * Get the set of {@link AttributesDescriptor} defining the configurable options in the dialog. * * @return {@link #attributeDescriptors} as an array. */ @NotNull public AttributesDescriptor[] getAttributeDescriptors() { return attributeDescriptors.toArray(EMPTY_DESCRIPTORS); } /** * Get the list of descriptors specifying the {@link com.intellij.openapi.editor.colors.ColorKey} instances for which colors are specified in the settings page. * * @return {@link #EMPTY_COLOR_DESCRIPTOR_ARRAY} */ @NotNull public ColorDescriptor[] getColorDescriptors() { return EMPTY_COLOR_DESCRIPTOR_ARRAY; } /** * Returns the text shown in the preview pane. If some elements need to be highlighted in the preview text which are not highlighted by the syntax highlighter, they need to be surrounded by XML-like tags, for example: <code>&lt;class&gt;MyClass&lt;/class&gt;</code>. The mapping between the names of the tags and the text attribute keys used for highlighting is defined by the {@link #getAdditionalHighlightingTagToDescriptorMap()} method. * * @return the text to show in the preview pane. */ @NonNls @NotNull public String getDemoText() { for (MdColorSettingsExtension extension : MdColorSettingsExtension.EXTENSIONS.getValue()) { String demoText = extension.getDemoText(); if (demoText != null) return demoText; } return loadSampleMarkdownDocument(SAMPLE_MARKDOWN_DOCUMENT_PATH); } /** * Get the title of the page, shown as text in the dialog tab. * * @return the name as defined by {@link MdBundle} */ @NotNull public String getDisplayName() { return MdBundle.message("multimarkdown.filetype.name"); } /** * Get the syntax highlighter which is used to highlight the text shown in the preview pane of the page. * * @return an instance of {@link MdSyntaxHighlighter} */ @NotNull public SyntaxHighlighter getHighlighter() { return new MdSyntaxHighlighter(MdRenderingProfile.getFOR_SAMPLE_DOC(), true, false); } /** * Get the icon for the page, shown in the dialog tab. * * @return {@link MdIcons.Document#FILE} */ @Nullable public Icon getIcon() { return MdIcons.getDocumentIcon(); } /** * Load the sample text to be displayed in the preview pane. */ private static String loadSampleMarkdownDocument(String path) { try { return FileUtil.loadTextAndClose(new InputStreamReader(MdColorSettingsPage.class.getResourceAsStream(path))); } catch (Exception e) { LOG.error("Failed loading sample Markdown document", e); } return MdBundle.message("colors.sample-loading-error"); } }
apache-2.0
sgaw/OpenYOLO-Android
demoproviders/trapdoor/java/org/openyolo/demoprovider/trapdoor/CredentialQueryReceiver.java
3020
/* * Copyright 2016 The OpenYOLO Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package org.openyolo.demoprovider.trapdoor; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.util.Log; import com.google.bbq.QueryResponseSender; import com.google.bbq.proto.BroadcastQuery; import java.util.Set; import okio.ByteString; import org.openyolo.api.AuthenticationDomain; import org.openyolo.api.AuthenticationMethods; import org.openyolo.api.RetrieveRequest; import org.openyolo.api.internal.IntentUtil; import org.openyolo.proto.CredentialRetrieveResponse; import org.openyolo.spi.BaseCredentialQueryReceiver; /** * Handles OpenYOLO credential retrieve broadcasts. As trapdoor does not store any credentials, * we respond to all requests with an intent as long as the * {@link org.openyolo.api.AuthenticationMethods#ID_AND_PASSWORD id and password} authentication * method is supported. */ public class CredentialQueryReceiver extends BaseCredentialQueryReceiver { private static final String LOG_TAG = "CredentialQueryReceiver"; /** * Creates the query receiver. */ public CredentialQueryReceiver() { super(LOG_TAG); } @Override protected void processCredentialRequest( @NonNull Context context, @NonNull BroadcastQuery query, @NonNull RetrieveRequest request, @NonNull Set<AuthenticationDomain> requestorDomains) { Log.i(LOG_TAG, "Processing retrieve query from claimed caller: " + query.requestingApp); final Context applicationContext = context.getApplicationContext(); final QueryResponseSender responseSender = new QueryResponseSender(applicationContext); // Ensure the caller supports the Id and Password authentication method if (!request.getAuthenticationMethods().contains(AuthenticationMethods.ID_AND_PASSWORD)) { responseSender.sendResponse(query, null /* response */); return; } Intent retrieveIntent = RetrieveActivity.createIntent(applicationContext); CredentialRetrieveResponse response = new CredentialRetrieveResponse.Builder() .retrieveIntent(ByteString.of(IntentUtil.toBytes(retrieveIntent))) .build(); Log.i(LOG_TAG, "Accepting credential request for claimed caller: " + query.requestingApp); responseSender.sendResponse(query, response.encode()); } }
apache-2.0
jason-rhodes/bridgepoint
src/org.xtuml.bp.xtext.masl.parent/org.xtuml.bp.xtext.masl/emf-gen/org/xtuml/bp/xtext/masl/masl/behavior/StatementList.java
1332
/** * generated by Xtext 2.9.2 */ package org.xtuml.bp.xtext.masl.masl.behavior; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Statement List</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link org.xtuml.bp.xtext.masl.masl.behavior.StatementList#getStatements <em>Statements</em>}</li> * </ul> * * @see org.xtuml.bp.xtext.masl.masl.behavior.BehaviorPackage#getStatementList() * @model * @generated */ public interface StatementList extends EObject { /** * Returns the value of the '<em><b>Statements</b></em>' containment reference list. * The list contents are of type {@link org.xtuml.bp.xtext.masl.masl.behavior.AbstractStatement}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Statements</em>' containment reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Statements</em>' containment reference list. * @see org.xtuml.bp.xtext.masl.masl.behavior.BehaviorPackage#getStatementList_Statements() * @model containment="true" * @generated */ EList<AbstractStatement> getStatements(); } // StatementList
apache-2.0
CognizantQAHub/Cognizant-Intelligent-Test-Scripter
Engine/src/main/java/com/cognizant/cognizantits/engine/reporting/sync/BasicHttpClient.java
13674
/* * Copyright 2014 - 2019 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.cognizantits.engine.reporting.sync; import com.cognizant.cognizantits.engine.support.DLogger; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URL; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPatch; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.protocol.HttpContext; import org.json.simple.JSONObject; public class BasicHttpClient extends AbstractHttpClient { private static final Logger LOG = Logger.getLogger(BasicHttpClient.class.getName()); public final URL url; private CloseableHttpClient client; private HttpContext context; /** * false - if the server has untrusted SSL (accept all cert) true - for * default system keystore */ private boolean trusted = false; private UsernamePasswordCredentials creds; private HttpHost proxy; public BasicHttpClient(URL url, String userName, String password) { this(url, userName, password, null); } public BasicHttpClient(URL url, String userName, String password, Map<String, String> config) { this.url = url; try { client = trusted ? getSystemClient() : getCustomClient(); creds = new UsernamePasswordCredentials(userName, password); context = createContext(url.toURI(), creds); if (config != null && Boolean.valueOf(config.get("useProxy"))) { this.proxy = new HttpHost(config.get("proxyHost"), Integer.valueOf(config.get("proxyPort"))); } } catch (Exception ex) { LOG.log(Level.SEVERE, "Error creating HttpClient!", ex); } } /** * basic auth implementation * * @param req * @throws AuthenticationException */ public void auth(HttpRequest req) throws AuthenticationException { req.addHeader(new BasicScheme().authenticate(creds, req, context)); } /** * execute the given URI request * * @param req * @return * @throws Exception */ @Override public CloseableHttpResponse execute(HttpUriRequest req) throws Exception { DLogger.Log(req.toString()); Optional.ofNullable(proxy).ifPresent((p) -> ((HttpRequestBase) req).setConfig(RequestConfig.custom().setProxy(p).build())); return client.execute(req, context); } // <editor-fold defaultstate="collapsed" desc="PUT implementation"> /** * Http Post request for given data as JSON string * * @param targetUrl * @param data * @return * @throws Exception */ public JSONObject put(URL targetUrl, String data) throws Exception { HttpPut httpput = new HttpPut(targetUrl.toURI()); setPutEntity(data, httpput); auth(httpput); setHeader(httpput); return parseResponse(doPut(httpput)); } public JSONObject put(URL targetUrl, String data, String accessKey, String value) throws Exception { HttpPut httpput = new HttpPut(targetUrl.toURI()); setPutEntity(data, httpput); auth(httpput); setHeader(httpput); addHeader(httpput, accessKey, value); return parseResponse(doPut(httpput)); } private void addHeader(HttpPut httpput, String accessKey, String value) { httpput.addHeader(accessKey, value); } /** * custom header for respective client * * @param httpput */ public void setHeader(HttpPut httpput) { httpput.addHeader("Accept", "application/json"); } public void addHeader(HttpGet httpGet, String Key, String Value) { httpGet.addHeader(Key, Value); } public void setPutEntity(String xmlstr, HttpPut httpput) throws UnsupportedEncodingException { StringEntity input = new StringEntity(xmlstr); if (xmlstr != null && !xmlstr.isEmpty()) { input.setContentType("application/json"); } httpput.setEntity(input); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="POST implementation"> /** * Http Post request for given data as JSON string * * @param targetUrl * @param payload * @return * @throws Exception */ public JSONObject post(URL targetUrl, String payload) throws Exception { HttpPost httppost = new HttpPost(targetUrl.toURI()); setPostEntity(payload, httppost); return parseResponse(doPost(httppost)); } /** * Http Post request for given data as JSON string * * @param targetUrl * @param payload * @return * @throws Exception */ public JSONObject post(URL targetUrl, File toUplod, String key, String value) throws Exception { HttpPost httppost = new HttpPost(targetUrl.toURI()); setPostEntityJ(toUplod, httppost); return parseResponse(doPost(httppost, key, value)); } /** * Http Post request for uploading files * * @param targetUrl * @param toUplod * @return * @throws Exception */ public JSONObject post(URL targetUrl, File toUplod) throws Exception { HttpPost httppost = new HttpPost(targetUrl.toURI()); setPostEntity(toUplod, httppost); return parseResponse(doPost(httppost)); } public JSONObject put(URL targetUrl, File toUplod) throws Exception { HttpPut httpput = new HttpPut(targetUrl.toURI()); setPutEntity(toUplod, httpput); return parseResponse(doPut(httpput)); } public JSONObject post(URL targetUrl, List<NameValuePair> parameters) throws Exception { HttpPost httppost = new HttpPost(targetUrl.toURI()); setPostEntity(parameters, httppost); return parseResponse(doPost(httppost)); } /** * Http Post request for uploading files * * @param targetUrl * @param data * @param toUplod * @return * @throws Exception */ public JSONObject post(URL targetUrl, String data, File toUplod) throws Exception { HttpPost httppost = new HttpPost(targetUrl.toURI()); setPostEntity(data, toUplod, httppost); return parseResponse(doPost(httppost)); } /** * custom header for respective client * * @param httppost */ public void setHeader(HttpPost httppost) { httppost.addHeader("Accept", "application/json"); } @Override public HttpResponse doPost(HttpPost httpPost) throws Exception { auth(httpPost); setHeader(httpPost); return super.doPost(httpPost); } public HttpResponse doPost(HttpPost httpPost, String key, String value) throws Exception { auth(httpPost); setHeader(httpPost); addHeader(httpPost, key, value); return super.doPost(httpPost); } private void addHeader(HttpPost httpPost, String key, String value) { httpPost.addHeader(key, value); } public void setPostEntity(File toUplod, HttpPost httppost) { final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", toUplod, ContentType.APPLICATION_OCTET_STREAM, toUplod.getName()); httppost.setEntity(builder.build()); } public void setPutEntity(File toUplod, HttpPut httpput) { final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", toUplod, ContentType.APPLICATION_OCTET_STREAM, toUplod.getName()); httpput.setEntity(builder.build()); } public void setPostEntityJ(File toUplod, HttpPost httppost) { MultipartEntity entity = new MultipartEntity(); entity.addPart("attachment", new FileBody(toUplod)); httppost.setEntity(entity); } public void setPostEntity(String data, File file, HttpPost httppost) { final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, file.getName()); builder.addTextBody("body", data, ContentType.APPLICATION_XML); httppost.setEntity(builder.build()); } public void setPostEntity(String jsonStr, HttpPost httppost) throws UnsupportedEncodingException { StringEntity input = new StringEntity(jsonStr); input.setContentType("application/json"); httppost.addHeader("accept", "application/json"); httppost.setEntity(input); } public void setPostEntity(List<NameValuePair> params, HttpPost httppost) { try { final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params); httppost.setEntity(entity); } catch (UnsupportedEncodingException ex) { Logger.getLogger(BasicHttpClient.class.getName()).log(Level.SEVERE, null, ex); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="PATCH implementation"> public JSONObject patch(URL targetUrl, String payload) throws Exception { HttpPatch httppatch = new HttpPatch(targetUrl.toURI()); auth(httppatch); setHeader(httppatch); setPatchEntity(payload, httppatch); return parseResponse(doPatch(httppatch)); } /** * custom header for respective client * * @param httppatch */ public void setHeader(HttpPatch httppatch) { httppatch.addHeader("Accept", "application/json"); } public void setPatchEntity(String jsonStr, HttpPatch httppatch) throws UnsupportedEncodingException { StringEntity input = new StringEntity(jsonStr); input.setContentType("application/json"); httppatch.setEntity(input); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="GET implementation"> /** * Http Get request for given url * * @param targetUrl * @return * @throws Exception */ public JSONObject Get(URL targetUrl) throws Exception { return Get(targetUrl.toURI()); } public JSONObject Get(URL targetUrl, String key, String val) throws Exception { URIBuilder builder = new URIBuilder(targetUrl.toString()); builder.setParameter(key, val); return Get(builder.build()); } public JSONObject Get(URL targetUrl, String key, String val, String empty) throws Exception { URIBuilder builder = new URIBuilder(targetUrl.toString()); builder.setParameter(key, val); return Get(builder.build(), key, val); } public JSONObject Get(URL targetUrl, boolean isJwtToken, String key, String val ) throws Exception { URIBuilder builder = new URIBuilder(targetUrl.toString()); return Get(builder.build(), key, val); } /** * Http Get request for given params as JSON string * * @param targetUrl * @param jsonStr * @return * @throws Exception */ public JSONObject Get(URL targetUrl, String jsonStr) throws Exception { URIBuilder builder = new URIBuilder(targetUrl.toString()); setParams(builder, jsonStr); return Get(setParams(builder, jsonStr).build()); } /** * custom header for respective client * * @param httpGet */ public void setHeader(HttpGet httpGet) { httpGet.addHeader("Accept", "application/json"); } private JSONObject Get(URI uri) throws Exception { HttpGet httpGet = new HttpGet(uri); auth(httpGet); setHeader(httpGet); return parseResponse(doGet(httpGet)); } private JSONObject Get(URI uri, String Key, String Value) throws Exception { HttpGet httpGet = new HttpGet(uri); auth(httpGet); setHeader(httpGet); addHeader(httpGet, Key, Value); return parseResponse(doGet(httpGet)); } // </editor-fold> }
apache-2.0
iAmGhost/brut.apktool
apktool-lib/src/main/java/brut/androlib/res/data/value/ResIntValue.java
1373
/** * Copyright 2011 Ryszard Wiśniewski <brut.alll@gmail.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 brut.androlib.res.data.value; import android.util.TypedValue; import brut.androlib.AndrolibException; /** * @author Ryszard Wiśniewski <brut.alll@gmail.com> */ public class ResIntValue extends ResScalarValue { protected final int mValue; private int type; public ResIntValue(int value, String rawValue, int type) { this(value, rawValue, "integer"); this.type = type; } public ResIntValue(int value, String rawValue, String type) { super(type, rawValue); this.mValue = value; } public int getValue() { return mValue; } protected String encodeAsResXml() throws AndrolibException { return TypedValue.coerceToString(type, mValue); } }
apache-2.0
Banno/sbt-plantuml-plugin
src/main/java/net/sourceforge/plantuml/graphic/GraphicStrings.java
6172
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2017, Arnaud Roques * * Project Info: http://plantuml.com * * This file is part of PlantUML. * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.graphic; import java.awt.Font; import java.awt.geom.Dimension2D; import java.awt.image.BufferedImage; import java.util.List; import net.sourceforge.plantuml.Dimension2DDouble; import net.sourceforge.plantuml.SpriteContainerEmpty; import net.sourceforge.plantuml.cucadiagram.Display; import net.sourceforge.plantuml.svek.IEntityImage; import net.sourceforge.plantuml.svek.ShapeType; import net.sourceforge.plantuml.ugraphic.ColorMapper; import net.sourceforge.plantuml.ugraphic.ColorMapperIdentity; import net.sourceforge.plantuml.ugraphic.UAntiAliasing; import net.sourceforge.plantuml.ugraphic.UChangeColor; import net.sourceforge.plantuml.ugraphic.UFont; import net.sourceforge.plantuml.ugraphic.UGraphic; import net.sourceforge.plantuml.ugraphic.UImage; import net.sourceforge.plantuml.ugraphic.UTranslate; public class GraphicStrings extends AbstractTextBlock implements IEntityImage { private final HtmlColor background; private final UFont font; private final HtmlColor green; private final HtmlColor hyperlinkColor = HtmlColorUtils.BLUE; private final boolean useUnderlineForHyperlink = true; private final List<String> strings; private final BufferedImage image; private final GraphicPosition position; private final UAntiAliasing antiAliasing; private final ColorMapper colorMapper = new ColorMapperIdentity(); public static GraphicStrings createDefault(List<String> strings, boolean useRed) { if (useRed) { return new GraphicStrings(strings, new UFont("SansSerif", Font.BOLD, 14), HtmlColorUtils.BLACK, HtmlColorUtils.RED_LIGHT, UAntiAliasing.ANTI_ALIASING_ON); } return new GraphicStrings(strings, new UFont("SansSerif", Font.BOLD, 14), HtmlColorSet.getInstance() .getColorIfValid("#33FF02"), HtmlColorUtils.BLACK, UAntiAliasing.ANTI_ALIASING_ON); } public GraphicStrings(List<String> strings, UFont font, HtmlColor green, HtmlColor background, UAntiAliasing antiAliasing) { this(strings, font, green, background, antiAliasing, null, null); } public GraphicStrings(List<String> strings, UFont font, HtmlColor green, HtmlColor background, UAntiAliasing antiAliasing, BufferedImage image, GraphicPosition position) { this.strings = strings; this.font = font; this.green = green; this.background = background; this.image = image; this.position = position; this.antiAliasing = antiAliasing; } private double minWidth; public void setMinWidth(double minWidth) { this.minWidth = minWidth; } private int maxLine = 0; private TextBlock getTextBlock() { TextBlock result = null; if (maxLine == 0) { result = Display.create(strings).create( new FontConfiguration(font, green, hyperlinkColor, useUnderlineForHyperlink), HorizontalAlignment.LEFT, new SpriteContainerEmpty()); } else { for (int i = 0; i < strings.size(); i += maxLine) { final int n = Math.min(i + maxLine, strings.size()); final TextBlock textBlock1 = Display.create(strings.subList(i, n)).create( new FontConfiguration(font, green, hyperlinkColor, useUnderlineForHyperlink), HorizontalAlignment.LEFT, new SpriteContainerEmpty()); if (result == null) { result = textBlock1; } else { result = TextBlockUtils.withMargin(result, 0, 10, 0, 0); result = TextBlockUtils.mergeLR(result, textBlock1, VerticalAlignment.TOP); } } } result = DateEventUtils.addEvent(result, green); return result; } public void drawU(UGraphic ug) { final Dimension2D size = calculateDimension(ug.getStringBounder()); getTextBlock().drawU(ug.apply(new UChangeColor(green))); if (image != null) { if (position == GraphicPosition.BOTTOM) { ug.apply(new UTranslate((size.getWidth() - image.getWidth()) / 2, size.getHeight() - image.getHeight())) .draw(new UImage(image)); } else if (position == GraphicPosition.BACKGROUND_CORNER_BOTTOM_RIGHT) { ug.apply(new UTranslate(size.getWidth() - image.getWidth(), size.getHeight() - image.getHeight())) .draw(new UImage(image)); } else if (position == GraphicPosition.BACKGROUND_CORNER_TOP_RIGHT) { ug.apply(new UTranslate(size.getWidth() - image.getWidth() - 1, 1)).draw(new UImage(image)); } } } public Dimension2D calculateDimension(StringBounder stringBounder) { Dimension2D dim = getTextBlock().calculateDimension(stringBounder); if (dim.getWidth() < minWidth) { dim = new Dimension2DDouble(minWidth, dim.getHeight()); } if (image != null) { if (position == GraphicPosition.BOTTOM) { dim = new Dimension2DDouble(dim.getWidth(), dim.getHeight() + image.getHeight()); } else if (position == GraphicPosition.BACKGROUND_CORNER_BOTTOM_RIGHT) { dim = new Dimension2DDouble(dim.getWidth() + image.getWidth(), dim.getHeight()); } else if (position == GraphicPosition.BACKGROUND_CORNER_TOP_RIGHT) { dim = new Dimension2DDouble(dim.getWidth() + image.getWidth(), dim.getHeight()); } } return dim; } public ShapeType getShapeType() { return ShapeType.RECTANGLE; } public HtmlColor getBackcolor() { return background; } public int getShield() { return 0; } public boolean isHidden() { return false; } public final void setMaxLine(int maxLine) { this.maxLine = maxLine; } }
apache-2.0
CenPC434/java-tools
en16931-edifact-to-xml/src/main/java/com/altova/text/edi/EDIFixedSettings.java
596
//////////////////////////////////////////////////////////////////////// // // EDIFixedSettings.java // // This file was generated by MapForce 2017sp2. // // YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE // OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION. // // Refer to the MapForce Documentation for further details. // http://www.altova.com/mapforce // //////////////////////////////////////////////////////////////////////// package com.altova.text.edi; public class EDIFixedSettings extends EDISettings { public EDIFixedSettings() { super.mEDIStandard = EDIStandard.EDIFixed; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/SimpleEmail.java
9473
/* * 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.pinpoint.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Specifies the contents of an email message, composed of a subject, a text part, and an HTML part. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-2016-12-01/SimpleEmail" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class SimpleEmail implements Serializable, Cloneable, StructuredPojo { /** * <p> * The body of the email message, in HTML format. We recommend using HTML format for email clients that render HTML * content. You can include links, formatted text, and more in an HTML message. * </p> */ private SimpleEmailPart htmlPart; /** * <p> * The subject line, or title, of the email. * </p> */ private SimpleEmailPart subject; /** * <p> * The body of the email message, in plain text format. We recommend using plain text format for email clients that * don't render HTML content and clients that are connected to high-latency networks, such as mobile devices. * </p> */ private SimpleEmailPart textPart; /** * <p> * The body of the email message, in HTML format. We recommend using HTML format for email clients that render HTML * content. You can include links, formatted text, and more in an HTML message. * </p> * * @param htmlPart * The body of the email message, in HTML format. We recommend using HTML format for email clients that * render HTML content. You can include links, formatted text, and more in an HTML message. */ public void setHtmlPart(SimpleEmailPart htmlPart) { this.htmlPart = htmlPart; } /** * <p> * The body of the email message, in HTML format. We recommend using HTML format for email clients that render HTML * content. You can include links, formatted text, and more in an HTML message. * </p> * * @return The body of the email message, in HTML format. We recommend using HTML format for email clients that * render HTML content. You can include links, formatted text, and more in an HTML message. */ public SimpleEmailPart getHtmlPart() { return this.htmlPart; } /** * <p> * The body of the email message, in HTML format. We recommend using HTML format for email clients that render HTML * content. You can include links, formatted text, and more in an HTML message. * </p> * * @param htmlPart * The body of the email message, in HTML format. We recommend using HTML format for email clients that * render HTML content. You can include links, formatted text, and more in an HTML message. * @return Returns a reference to this object so that method calls can be chained together. */ public SimpleEmail withHtmlPart(SimpleEmailPart htmlPart) { setHtmlPart(htmlPart); return this; } /** * <p> * The subject line, or title, of the email. * </p> * * @param subject * The subject line, or title, of the email. */ public void setSubject(SimpleEmailPart subject) { this.subject = subject; } /** * <p> * The subject line, or title, of the email. * </p> * * @return The subject line, or title, of the email. */ public SimpleEmailPart getSubject() { return this.subject; } /** * <p> * The subject line, or title, of the email. * </p> * * @param subject * The subject line, or title, of the email. * @return Returns a reference to this object so that method calls can be chained together. */ public SimpleEmail withSubject(SimpleEmailPart subject) { setSubject(subject); return this; } /** * <p> * The body of the email message, in plain text format. We recommend using plain text format for email clients that * don't render HTML content and clients that are connected to high-latency networks, such as mobile devices. * </p> * * @param textPart * The body of the email message, in plain text format. We recommend using plain text format for email * clients that don't render HTML content and clients that are connected to high-latency networks, such as * mobile devices. */ public void setTextPart(SimpleEmailPart textPart) { this.textPart = textPart; } /** * <p> * The body of the email message, in plain text format. We recommend using plain text format for email clients that * don't render HTML content and clients that are connected to high-latency networks, such as mobile devices. * </p> * * @return The body of the email message, in plain text format. We recommend using plain text format for email * clients that don't render HTML content and clients that are connected to high-latency networks, such as * mobile devices. */ public SimpleEmailPart getTextPart() { return this.textPart; } /** * <p> * The body of the email message, in plain text format. We recommend using plain text format for email clients that * don't render HTML content and clients that are connected to high-latency networks, such as mobile devices. * </p> * * @param textPart * The body of the email message, in plain text format. We recommend using plain text format for email * clients that don't render HTML content and clients that are connected to high-latency networks, such as * mobile devices. * @return Returns a reference to this object so that method calls can be chained together. */ public SimpleEmail withTextPart(SimpleEmailPart textPart) { setTextPart(textPart); 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 (getHtmlPart() != null) sb.append("HtmlPart: ").append(getHtmlPart()).append(","); if (getSubject() != null) sb.append("Subject: ").append(getSubject()).append(","); if (getTextPart() != null) sb.append("TextPart: ").append(getTextPart()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof SimpleEmail == false) return false; SimpleEmail other = (SimpleEmail) obj; if (other.getHtmlPart() == null ^ this.getHtmlPart() == null) return false; if (other.getHtmlPart() != null && other.getHtmlPart().equals(this.getHtmlPart()) == false) return false; if (other.getSubject() == null ^ this.getSubject() == null) return false; if (other.getSubject() != null && other.getSubject().equals(this.getSubject()) == false) return false; if (other.getTextPart() == null ^ this.getTextPart() == null) return false; if (other.getTextPart() != null && other.getTextPart().equals(this.getTextPart()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getHtmlPart() == null) ? 0 : getHtmlPart().hashCode()); hashCode = prime * hashCode + ((getSubject() == null) ? 0 : getSubject().hashCode()); hashCode = prime * hashCode + ((getTextPart() == null) ? 0 : getTextPart().hashCode()); return hashCode; } @Override public SimpleEmail clone() { try { return (SimpleEmail) 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.pinpoint.model.transform.SimpleEmailMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
mbizhani/Demeter
service/src/main/java/org/devocative/demeter/service/DTaskScheduleJob.java
1823
package org.devocative.demeter.service; import org.devocative.demeter.entity.DTaskSchedule; import org.devocative.demeter.iservice.IDemeterCoreService; import org.devocative.demeter.iservice.ISecurityService; import org.devocative.demeter.iservice.persistor.IPersistorService; import org.devocative.demeter.iservice.task.ITaskService; import org.devocative.demeter.vo.UserVO; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DTaskScheduleJob implements Job { private static Logger logger = LoggerFactory.getLogger(DTaskScheduleJob.class); @Override public void execute(JobExecutionContext context) throws JobExecutionException { String scheduleId = context.getJobDetail().getKey().getName(); logger.info("DTaskScheduleJob: scheduleId={}", scheduleId); IDemeterCoreService demeterCoreService = (IDemeterCoreService) context.getMergedJobDataMap().get(IDemeterCoreService.JOB_KEY); IPersistorService persistorService = (IPersistorService) demeterCoreService.getBean("dmtPersistorService"); ITaskService taskService = demeterCoreService.getBean(ITaskService.class); ISecurityService securityService = demeterCoreService.getBean(ISecurityService.class); UserVO currentUser = securityService.getCurrentUser(); if (currentUser == null) { securityService.authenticate(securityService.getSystemUser()); } try { DTaskSchedule schedule = persistorService.get(DTaskSchedule.class, new Long(scheduleId)); if (schedule.getEnabled()) { taskService.start(schedule.getTask().getId(), null, schedule.getRefId(), null); } } catch (Exception e) { logger.error("DemeterSimpleTaskJob: schedule=" + scheduleId, e); } finally { persistorService.endSession(); } } }
apache-2.0
orientechnologies/orientdb
lucene/src/test/java/com/orientechnologies/lucene/test/LuceneContextTest.java
2554
/* * * * Copyright 2010-2016 OrientDB LTD (http://orientdb.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.orientechnologies.lucene.test; import com.orientechnologies.orient.core.command.script.OCommandScript; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.sql.OCommandSQL; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import java.io.InputStream; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** Created by enricorisa on 08/10/14. */ public class LuceneContextTest extends BaseLuceneTest { @Before public void init() { InputStream stream = ClassLoader.getSystemResourceAsStream("testLuceneIndex.sql"); db.command(new OCommandScript("sql", getScriptFromStream(stream))).execute(); db.command(new OCommandSQL("create index Song.title on Song (title) FULLTEXT ENGINE LUCENE")) .execute(); db.command(new OCommandSQL("create index Song.author on Song (author) FULLTEXT ENGINE LUCENE")) .execute(); } @Test public void testContext() { List<ODocument> docs = db.query( new OSQLSynchQuery<ODocument>( "select *,$score from Song where [title] LUCENE \"(title:man)\"")); Assert.assertEquals(docs.size(), 14); Float latestScore = 100f; for (ODocument doc : docs) { Float score = doc.field("$score"); Assert.assertNotNull(score); Assert.assertTrue(score <= latestScore); latestScore = score; } docs = db.query( new OSQLSynchQuery<ODocument>( "select *,$totalHits,$Song_title_totalHits from Song where [title] LUCENE \"(title:man)\" limit 1")); Assert.assertEquals(docs.size(), 1); ODocument doc = docs.iterator().next(); Assert.assertEquals(new Long(14), doc.<Long>field("$totalHits")); Assert.assertEquals(new Long(14), doc.<Long>field("$Song_title_totalHits")); } }
apache-2.0
chuanzhangjiang/ZLib
zlib/src/test/java/me/zjc/zlib/common/utils/ArgumentCheckerTest.java
1135
package me.zjc.zlib.common.utils; import static org.junit.Assert.*; import org.junit.Test; import me.zjc.zlib.common.utils.ArgumentChecker; /** * Created by ChuanZhangjiang on 2016/8/5. * 参数校验工具类单元测试 */ public class ArgumentCheckerTest { @Test public void testCheckNotNullNoMsg() throws Exception { try { ArgumentChecker.checkNotNull(null); fail(); } catch (Exception e) { assertTrue(e.getClass() == NullPointerException.class); } try { ArgumentChecker.checkNotNull(new Object()); }catch (Exception e) { fail(); } } @Test public void testCheckNotNullHasMsg() throws Exception { String msg = "msg"; try { ArgumentChecker.checkNotNull(null, msg); } catch (Exception e) { assertTrue(e.getClass() == NullPointerException.class); assertEquals(e.getMessage(), msg); } try { ArgumentChecker.checkNotNull(new Object(), msg); } catch (Exception e) { fail(); } } }
apache-2.0
roguexz/gae-java-template
src/main/java/rogue/app/framework/view/beans/Site.java
1037
/* * Copyright 2013, Rogue.IO * * 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 rogue.app.framework.view.beans; import javax.enterprise.context.ApplicationScoped; import javax.inject.Named; /** * A simple bean that provides access to the site details. */ @Named @ApplicationScoped public class Site { /** * Get the template for the site. * * @return the template for the site. */ public String getPageTemplate() { return "/WEB-INF/templates/site-template.xhtml"; } }
apache-2.0
ufo5260987423/pillForZhihu
webApp/src/main/java/com/pillForZhihu/webApp/tools/StringProcessor.java
305
package com.pillForZhihu.webApp.tools; /** * Created by ufo on 6/16/15. */ public class StringProcessor { public static String lowerFirstChar(String target) { return target.replaceFirst( target.substring(0, 1), target.substring(0, 1).toLowerCase()); } }
apache-2.0
nickman/heliosutils
src/main/java/com/heliosapm/utils/events/SlidingConsecutiveEventTrigger.java
4297
/** Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.heliosapm.utils.events; import java.util.EnumMap; import org.json.JSONArray; import org.json.JSONObject; import com.heliosapm.utils.enums.BitMasked; import com.heliosapm.utils.enums.Rollup; /** * <p>Title: SlidingConsecutiveEventTrigger</p> * <p>Description: Consecutive event trigger that does not wind down and alarms until the consecutive streak ends</p> * <p>Company: Helios Development Group LLC</p> * @author Whitehead (nwhitehead AT heliosdev DOT org) * <p><code>com.heliosapm.utils.events.SlidingConsecutiveEventTrigger</code></p> * @param <E> The event type */ public class SlidingConsecutiveEventTrigger<E extends Enum<E> & BitMasked> extends AbstractConsecutiveEventTrigger<E> { /** * Creates a new SlidingConsecutiveEventTrigger * @param eventType The event type class * @param thresholds A map of the triggering consecutive thresholds for each triggering event type * @param acceptedEvents The events accepted by this trigger. If length is zero, will assume all event types */ public SlidingConsecutiveEventTrigger(final Class<E> eventType, final EnumMap<E, Integer> thresholds, final E... acceptedEvents) { super(eventType, thresholds, acceptedEvents); } /** * Creates a new SlidingConsecutiveEventTrigger from the passed JSON definition * @param jsonDef The json trigger definition * @return the SlidingConsecutiveEventTrigger */ @SuppressWarnings("unchecked") public static <E extends Enum<E> & BitMasked> SlidingConsecutiveEventTrigger<E> fromJSON(final JSONObject jsonDef) { if(jsonDef==null) throw new IllegalArgumentException("The passed JSON was null"); final Class<E> eventType; final EnumMap<E, Integer> thresholds; final E[] acceptedEvents; final String eventTypeName = jsonDef.optString("eventType"); if(eventTypeName==null) throw new IllegalArgumentException("The passed JSON did not contain an eventType"); final JSONObject thresholdJsonMap = jsonDef.optJSONObject("thresholds"); if(thresholdJsonMap==null) throw new IllegalArgumentException("The passed JSON did not contain a thresholds map"); JSONArray acceptedEventArr = jsonDef.optJSONArray("acceptedEvents"); if(acceptedEventArr==null) acceptedEventArr = new JSONArray(); try { eventType = (Class<E>) Class.forName(eventTypeName, true, Thread.currentThread().getContextClassLoader()); thresholds = new EnumMap<E, Integer>(eventType); for(Object key: thresholdJsonMap.keySet()) { final String sKey = key.toString(); final E event = Enum.valueOf(eventType, sKey.trim().toUpperCase()); final int t = thresholdJsonMap.getInt(sKey); thresholds.put(event, t); } final int ecnt = acceptedEventArr.length(); if(ecnt==0) { acceptedEvents = eventType.getEnumConstants(); } else { acceptedEvents = BitMasked.StaticOps.makeArr(eventType, ecnt); for(int i = 0; i < ecnt; i++) { acceptedEvents[i] = Enum.valueOf(eventType, acceptedEventArr.getString(i).trim().toUpperCase()); } } return new SlidingConsecutiveEventTrigger<E>(eventType, thresholds, acceptedEvents); } catch (Exception ex) { throw new RuntimeException("Failed to build SlidingConsecutiveEventTrigger from JSON", ex); } } /** * {@inheritDoc} * @see com.heliosapm.utils.events.Trigger#windDown(java.lang.Enum) */ @Override public void windDown(final E event) { final boolean lockedByMe = lock.isLockedByMe(); try { if(!lockedByMe) lock.xlock(); counters.get(event)[0]--; } finally { if(!lockedByMe) lock.xunlock(); } } }
apache-2.0
lhfei/hbase-in-action
client-api/src/main/java/cn/lhfei/hbase/ch07/mapreduce/ParseJson.java
8197
package cn.lhfei.hbase.ch07.mapreduce; // cc ParseJson MapReduce job that parses the raw data into separate columns. import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.Mutation; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapreduce.IdentityTableReducer; import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil; import org.apache.hadoop.hbase.mapreduce.TableMapper; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.util.GenericOptionsParser; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import java.io.IOException; /** * @version 0.1 * * @author Hefei Li * * @since Jun 13, 2016 */ public class ParseJson { private static final Log LOG = LogFactory.getLog(ParseJson.class); public static final String NAME = "ParseJson"; public enum Counters { ROWS, COLS, ERROR, VALID } /** * Implements the <code>Mapper</code> that reads the data and extracts the * required information. */ // vv ParseJson static class ParseMapper extends TableMapper<ImmutableBytesWritable, Mutation> { private JSONParser parser = new JSONParser(); private byte[] columnFamily = null; @Override protected void setup(Context context) throws IOException, InterruptedException { columnFamily = Bytes.toBytes( context.getConfiguration().get("conf.columnfamily")); } // ^^ ParseJson /** * Maps the input. * * @param row The row key. * @param columns The columns of the row. * @param context The task context. * @throws java.io.IOException When mapping the input fails. */ // vv ParseJson @Override public void map(ImmutableBytesWritable row, Result columns, Context context) throws IOException { context.getCounter(Counters.ROWS).increment(1); String value = null; try { Put put = new Put(row.get()); for (Cell cell : columns.listCells()) { context.getCounter(Counters.COLS).increment(1); value = Bytes.toStringBinary(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()); JSONObject json = (JSONObject) parser.parse(value); for (Object key : json.keySet()) { Object val = json.get(key); put.addColumn(columnFamily, Bytes.toBytes(key.toString()), // co ParseJson-1-Put Store the top-level JSON keys as columns, with their value set as the column value. Bytes.toBytes(val.toString())); } } context.write(row, put); context.getCounter(Counters.VALID).increment(1); } catch (Exception e) { e.printStackTrace(); System.err.println("Error: " + e.getMessage() + ", Row: " + Bytes.toStringBinary(row.get()) + ", JSON: " + value); context.getCounter(Counters.ERROR).increment(1); } } // ^^ ParseJson /* { "updated": "Mon, 14 Sep 2009 17:09:02 +0000", "links": [{ "href": "http://www.webdesigndev.com/", "type": "text/html", "rel": "alternate" }], "title": "Web Design Tutorials | Creating a Website | Learn Adobe Flash, Photoshop and Dreamweaver", "author": "outernationalist", "comments": "http://delicious.com/url/e104984ea5f37cf8ae70451a619c9ac0", "guidislink": false, "title_detail": { "base": "http://feeds.delicious.com/v2/rss/recent?min=1&count=100", "type": "text/plain", "language": null, "value": "Web Design Tutorials | Creating a Website | Learn Adobe Flash, Photoshop and Dreamweaver" }, "link": "http://www.webdesigndev.com/", "source": {}, "wfw_commentrss": "http://feeds.delicious.com/v2/rss/url/ e104984ea5f37cf8ae70451a619c9ac0", "id": "http://delicious.com/url/ e104984ea5f37cf8ae70451a619c9ac0#outernationalist" } */ // vv ParseJson } // ^^ ParseJson /** * Parse the command line parameters. * * @param args The parameters to parse. * @return The parsed command line. * @throws org.apache.commons.cli.ParseException When the parsing of the parameters fails. */ private static CommandLine parseArgs(String[] args) throws ParseException { Options options = new Options(); Option o = new Option("i", "input", true, "table to read from (must exist)"); o.setArgName("input-table-name"); o.setRequired(true); options.addOption(o); o = new Option("o", "output", true, "table to write to (must exist)"); o.setArgName("output-table-name"); o.setRequired(true); options.addOption(o); o = new Option("c", "column", true, "column to read data from (must exist)"); o.setArgName("family:qualifier"); options.addOption(o); options.addOption("d", "debug", false, "switch on DEBUG log level"); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (Exception e) { System.err.println("ERROR: " + e.getMessage() + "\n"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(NAME + " ", options, true); System.exit(-1); } if (cmd.hasOption("d")) { Logger log = Logger.getLogger("mapreduce"); log.setLevel(Level.DEBUG); System.out.println("DEBUG ON"); } return cmd; } /** * Main entry point. * * @param args The command line parameters. * @throws Exception When running the job fails. */ // vv ParseJson public static void main(String[] args) throws Exception { /*...*/ // ^^ ParseJson Configuration conf = HBaseConfiguration.create(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); CommandLine cmd = parseArgs(otherArgs); // check debug flag and other options if (cmd.hasOption("d")) conf.set("conf.debug", "true"); // get details String input = cmd.getOptionValue("i"); String output = cmd.getOptionValue("o"); String column = cmd.getOptionValue("c"); // vv ParseJson Scan scan = new Scan(); if (column != null) { byte[][] colkey = KeyValue.parseColumn(Bytes.toBytes(column)); if (colkey.length > 1) { scan.addColumn(colkey[0], colkey[1]); conf.set("conf.columnfamily", Bytes.toStringBinary(colkey[0])); // co ParseJson-2-Conf Store the column family in the configuration for later use in the mapper. conf.set("conf.columnqualifier", Bytes.toStringBinary(colkey[1])); } else { scan.addFamily(colkey[0]); conf.set("conf.columnfamily", Bytes.toStringBinary(colkey[0])); } } Job job = Job.getInstance(conf, "Parse data in " + input + ", write to " + output); job.setJarByClass(ParseJson.class); TableMapReduceUtil.initTableMapperJob(input, scan, ParseMapper.class, // co ParseJson-3-SetMap Setup map phase details using the utility method. ImmutableBytesWritable.class, Put.class, job); TableMapReduceUtil.initTableReducerJob(output, // co ParseJson-4-SetReduce Configure an identity reducer to store the parsed data. IdentityTableReducer.class, job); System.exit(job.waitForCompletion(true) ? 0 : 1); } // ^^ ParseJson }
apache-2.0
VuCant/CQurity
app/src/com/azhuoinfo/cqurity/view/listview/OnLoadMoreListener.java
127
package com.azhuoinfo.cqurity.view.listview; public interface OnLoadMoreListener { boolean hasMore(); void onLoadMore(); }
apache-2.0
mattxia/unique-web
src/main/java/org/unique/common/tools/JSONUtil.java
1920
package org.unique.common.tools; import java.util.HashMap; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSON; /** * json util * @author:rex * @date:2014年8月22日 * @version:1.0 */ @SuppressWarnings("unchecked") public class JSONUtil { public static <T> String toJSON(T t) { if (null != t) { return JSON.toJSONString(t); } return null; } /** * map转json * * @author:rex * @param map * @return */ public static <K, V> String map2Json(Map<K, V> map) { if (!CollectionUtil.isEmpty(map)) { return JSON.toJSONString(map); } return null; } /** * list转json * * @author:rex * @param list * @return */ public static <T> String list2JSON(List<T> list) { if (!CollectionUtil.isEmpty(list)) { return JSON.toJSONString(list); } return null; } /** * JSON转map * * @param <K> * @author:rex * @param json * @return */ public static <K, V> Map<K, V> json2Map(final String json) { if (StringUtils.isNotBlank(json)) { return JSON.parseObject(json, HashMap.class); } return null; } /** * JSON转list * * @author:rex * @param json * @return */ public static <T> List<T> json2List(final String json) { if (StringUtils.isNotBlank(json)) { return JSON.parseObject(json, List.class); } return null; } /** * json转对象 * * @param json * @param clazz * @return */ public static <T> T json2Object(final String json, Class<T> clazz) { if (StringUtils.isNotBlank(json) && null != clazz) { return JSON.parseObject(json, clazz); } return null; } }
apache-2.0
gfis/jextra
src/main/java/org/teherba/jextra/gener/Grammar.java
8498
/* LR(1) Grammar of a language and corresponding parser table @(#) $Id$ 2022-02-10: LF only 2017-05-28: javadoc 1.8 2016-05-29: Java generics 2007-05-08: relaunch with prototype states 2005-02-10, Georg Fischer: copied from Symbol.java */ /* * Copyright 2006 Georg Fischer <dr dot georg dot fischer at gmail dot 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 org.teherba.jextra.gener; import org.teherba.jextra.Parm; import org.teherba.jextra.gener.Item; import org.teherba.jextra.gener.Production; import org.teherba.jextra.gener.Rule; import org.teherba.jextra.scan.Scanner; import org.teherba.jextra.scan.Symbol; import org.teherba.jextra.scan.SymbolList; import java.util.ArrayList; import java.util.Iterator; import java.util.TreeMap; /** LR(1) Grammar of a language and corresponding parser table, consisting of * <ul> * <li>a set of <em>Rule</em>s consisting of sets of <em>Production</em>s</li> * <li>an <em>axiom</em> - the rule with this <em>Symbol</em> * on the left side is the top-most rule of the grammar</li> * <li>a set of <em>State</em>s of the LR(1) <em>Parser</em></li> * <li>a set of <em>Item</em>s which represents the parser Table * generated from this <em>Grammar</em></li> * </ul> * @author Dr. Georg Fischer */ public class Grammar { public final static String CVSID = "@(#) $Id$"; /** a special nonterminal symbol which is the starting point of the grammar */ public Symbol axiom; /** Map a left side to the corresponding rule (set of productions) */ private TreeMap<Symbol, Rule> ruleMap; /** underlying scanner with symbol table */ private Scanner scanner; /** the top-most production for a fictious hyper-axiom */ private Production prod1; /** the symbol list */ private SymbolList symbolList; /** No-args Constructor - creates a new grammar */ public Grammar() { this(new Scanner()); } // Constructor() /** Constructor - creates a new grammar with an associated scanner * @param scan the Scanner to be used */ public Grammar(Scanner scan) { scanner = scan; symbolList = scanner.getSymbolList(); // symbolList.put(Production.EOP); axiom = symbolList.put("axiom"); ruleMap = new TreeMap<Symbol, Rule>(); } // Constructor(Scanner) /** Get the axiom (root symbol) of the grammar * @return symbol for the axiom of the grammar */ public Symbol getAxiom() { return axiom; } // getAxiom /** Set the axiom (root symbol) of the grammar * @param nonterminal symbol for the axiom */ public void setAxiom(Symbol nonterminal) { axiom = nonterminal; } // setAxiom /** Get the scanner associated with the grammar * @return scanner associated with the grammar */ public Scanner getScanner() { return scanner; } // getScanner /** Get the symbol list of this grammar object * @return symbol list */ public SymbolList getSymbolList() { return symbolList; } // getSymbolList /** Check whether the grammar has a rule for a nonterminal * @param leftSide symbol to be checked * @return whether the symbol is a terminal */ public boolean isTerminal(Symbol leftSide) { return ruleMap.get(leftSide) != null; } // isTerminal /** Get the set of productions for a nonterminal * @param leftSide symbol on the left side of the rule * @return rule, or null if there is none */ public Rule getRule(Symbol leftSide) { return ruleMap.get(leftSide); } // getRule /** Insert or replaces a rule in the set of rules; * there is no check whether the rule was already stored * @param rule rule to be inserted or replaced */ public void insert(Rule rule) { ruleMap.put(rule.getLeftSide(), rule); System.out.println("irule: " + rule.getLeftSide().getEntity() + ", size=" + rule.size()); } // insert /** Remove all productions for a nonterminal, and thereby * transform it into a terminal * @param leftSide symbol on the left side * @return whether the rule was previously stored in the grammar * (that is whether the left side was a nonterminal) */ /* public boolean removeRule(Symbol leftSide) { boolean found = false; Rule rule = ruleMap.get(leftSide); if (rule != null) { found = true; ruleMap.remove(leftSide); } return found; } // removeRule */ /** Add a production to the grammar; * check whether the production was already stored, and ignore * the call in that case * @param prod production to be added * @return number of productions previously stored in the grammar */ public int insert(Production prod) { int found = 0; Symbol leftSide = prod.getLeftSide(); Rule rule = getRule(leftSide); if (rule == null) { rule = new Rule(leftSide); // was terminal } else { // some rule for this left side was previously stored - expand it rule.insert(prod); } // expand ruleMap.put(leftSide, rule); leftSide.setRule(rule); return rule.insert(prod); } // insert(prod) /** Remove a production from the grammar; * check whether the production was already stored, and print * a message if that was not the case * @param prod production to be removed * @return number of productions previously stored in the grammar */ public int delete(Production prod) { int found = 0; Rule rule = getRule(prod.getLeftSide()); if (rule == null) { Parm.alert(201); // system error: no rule with left side of production } else { found = rule.delete(prod); } return found; } // delete(prod) /** Return a human readable representation of this grammar * @return lines with all rules, prefixed by dots */ public String legible() { String result = "["; Iterator<Symbol> siter = symbolList.iterator(); int index = 0; while (siter.hasNext()) { Symbol leftSide = siter.next(); Rule rule = leftSide.getRule(); if (rule != null) { // nonterminal if (index > 0) { result += Parm.newline() + "."; } result += rule.legible(); index ++; } // nonterminal } // while hasNext return result + Parm.newline() + "]"; } // legible /** Return an XML description of this grammar * @return list of XML elements representing the symbol list * and the rules with productions and members. */ public String toString() { String result = Parm.getIndent() + "<grammar axiom=\"" + axiom.getEntity() + "\">" + Parm.getNewline(); Parm.incrIndent(); result += symbolList.toString() + Parm.getNewline(); result += Parm.getIndent() + "<rules>" + Parm.getNewline(); Parm.incrIndent(); try { Iterator<Symbol> siter = ruleMap.keySet().iterator(); while (siter.hasNext()) { Symbol leftSide = siter.next(); result += ruleMap.get(leftSide).toString() + Parm.getNewline(); } // while index } catch (Exception exc) { System.err.println(exc.getMessage()); exc.printStackTrace(); } // try - catch Parm.decrIndent(); result += Parm.getIndent() + "</rules>" + Parm.getNewline(); Parm.decrIndent(); result += Parm.getIndent() + "</grammar>"; return result; } // toString /** Test Frame * @param args commandline arguments */ public static void main (String args[]) { } // main } // Grammar
apache-2.0
JosefHruska/FloatingActionButton
library/src/main/java/com/github/clans/fab/Label.java
11914
package com.github.clans.fab; import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Outline; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.RectF; import android.graphics.Xfermode; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.graphics.drawable.RippleDrawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.StateListDrawable; import android.graphics.drawable.shapes.RoundRectShape; import android.os.Build; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.ViewOutlineProvider; import android.view.animation.Animation; import android.widget.TextView; public class Label extends TextView { private static final Xfermode PORTER_DUFF_CLEAR = new PorterDuffXfermode(PorterDuff.Mode.CLEAR); private int mShadowRadius; private int mShadowXOffset; private int mShadowYOffset; private int mShadowColor; private Drawable mBackgroundDrawable; private boolean mShowShadow = true; private int mRawWidth; private int mRawHeight; private int mColorNormal; private int mColorPressed; private int mColorRipple; private int mCornerRadius; private FloatingActionButton mFab; private Animation mShowAnimation; private Animation mHideAnimation; private boolean mUsingStyle; GestureDetector mGestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { onActionDown(); if (mFab != null) { mFab.onActionDown(); } return super.onDown(e); } @Override public boolean onSingleTapUp(MotionEvent e) { onActionUp(); if (mFab != null) { mFab.onActionUp(); } return super.onSingleTapUp(e); } }); private boolean mHandleVisibilityChanges = true; public Label(Context context) { super(context); } public Label(Context context, AttributeSet attrs) { super(context, attrs); } public Label(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(calculateMeasuredWidth(), calculateMeasuredHeight()); } private int calculateMeasuredWidth() { if (mRawWidth == 0) { mRawWidth = getMeasuredWidth(); } return getMeasuredWidth() + calculateShadowWidth(); } private int calculateMeasuredHeight() { if (mRawHeight == 0) { mRawHeight = getMeasuredHeight(); } return getMeasuredHeight() + calculateShadowHeight(); } protected int calculateShadowWidth() { return mShowShadow ? (mShadowRadius + Math.abs(mShadowXOffset)) : 0; } protected int calculateShadowHeight() { return mShowShadow ? (mShadowRadius + Math.abs(mShadowYOffset)) : 0; } void updateBackground() { LayerDrawable layerDrawable; if (mShowShadow) { layerDrawable = new LayerDrawable(new Drawable[]{ new Shadow(), createFillDrawable() }); int leftInset = mShadowRadius + Math.abs(mShadowXOffset); int topInset = mShadowRadius + Math.abs(mShadowYOffset); int rightInset = (mShadowRadius + Math.abs(mShadowXOffset)); int bottomInset = (mShadowRadius + Math.abs(mShadowYOffset)); layerDrawable.setLayerInset( 1, leftInset, topInset, rightInset, bottomInset ); } else { layerDrawable = new LayerDrawable(new Drawable[]{ createFillDrawable() }); } setBackgroundCompat(layerDrawable); } public void removeLabelBackground() { setBackgroundCompat(new ColorDrawable(Color.argb(0, 0, 0, 0))); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private Drawable createFillDrawable() { StateListDrawable drawable = new StateListDrawable(); drawable.addState(new int[]{android.R.attr.state_pressed}, createRectDrawable(mColorPressed)); drawable.addState(new int[]{}, createRectDrawable(mColorNormal)); if (Util.hasLollipop()) { RippleDrawable ripple = new RippleDrawable(new ColorStateList(new int[][]{{}}, new int[]{mColorRipple}), drawable, null); setOutlineProvider(new ViewOutlineProvider() { @Override public void getOutline(View view, Outline outline) { outline.setOval(0, 0, view.getWidth(), view.getHeight()); } }); setClipToOutline(true); mBackgroundDrawable = ripple; return ripple; } mBackgroundDrawable = drawable; return drawable; } private Drawable createRectDrawable(int color) { RoundRectShape shape = new RoundRectShape( new float[]{ mCornerRadius, mCornerRadius, mCornerRadius, mCornerRadius, mCornerRadius, mCornerRadius, mCornerRadius, mCornerRadius }, null, null); ShapeDrawable shapeDrawable = new ShapeDrawable(shape); shapeDrawable.getPaint().setColor(color); return shapeDrawable; } private void setShadow(FloatingActionButton fab) { mShadowColor = fab.getShadowColor(); mShadowRadius = fab.getShadowRadius(); mShadowXOffset = fab.getShadowXOffset(); mShadowYOffset = fab.getShadowYOffset(); mShowShadow = fab.hasShadow(); } @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void setBackgroundCompat(Drawable drawable) { if (Util.hasJellyBean()) { setBackground(drawable); } else { setBackgroundDrawable(drawable); } } private void playShowAnimation() { if (mShowAnimation != null) { mHideAnimation.cancel(); startAnimation(mShowAnimation); } } private void playHideAnimation() { if (mHideAnimation != null) { mShowAnimation.cancel(); startAnimation(mHideAnimation); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) void onActionDown() { if (mUsingStyle) { mBackgroundDrawable = getBackground(); } if (mBackgroundDrawable instanceof StateListDrawable) { StateListDrawable drawable = (StateListDrawable) mBackgroundDrawable; drawable.setState(new int[]{android.R.attr.state_pressed}); } else if (Util.hasLollipop() && mBackgroundDrawable instanceof RippleDrawable) { RippleDrawable ripple = (RippleDrawable) mBackgroundDrawable; ripple.setState(new int[]{android.R.attr.state_enabled, android.R.attr.state_pressed}); ripple.setHotspot(getMeasuredWidth() / 2, getMeasuredHeight() / 2); ripple.setVisible(true, true); } // setPressed(true); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) void onActionUp() { if (mUsingStyle) { mBackgroundDrawable = getBackground(); } if (mBackgroundDrawable instanceof StateListDrawable) { StateListDrawable drawable = (StateListDrawable) mBackgroundDrawable; drawable.setState(new int[]{}); } else if (Util.hasLollipop() && mBackgroundDrawable instanceof RippleDrawable) { RippleDrawable ripple = (RippleDrawable) mBackgroundDrawable; ripple.setState(new int[]{}); ripple.setHotspot(getMeasuredWidth() / 2, getMeasuredHeight() / 2); ripple.setVisible(true, true); } // setPressed(false); } void setFab(FloatingActionButton fab) { mFab = fab; setShadow(fab); } void setShowShadow(boolean show) { mShowShadow = show; } void setCornerRadius(int cornerRadius) { mCornerRadius = cornerRadius; } void setColors(int colorNormal, int colorPressed, int colorRipple) { mColorNormal = colorNormal; mColorPressed = colorPressed; mColorRipple = colorRipple; } void show(boolean animate) { if (animate) { playShowAnimation(); } setVisibility(VISIBLE); } void hide(boolean animate) { if (animate) { playHideAnimation(); } setVisibility(INVISIBLE); } void setShowAnimation(Animation showAnimation) { mShowAnimation = showAnimation; } void setHideAnimation(Animation hideAnimation) { mHideAnimation = hideAnimation; } void setUsingStyle(boolean usingStyle) { mUsingStyle = usingStyle; } boolean isHandleVisibilityChanges() { return mHandleVisibilityChanges; } void setHandleVisibilityChanges(boolean handle) { mHandleVisibilityChanges = handle; } @Override public boolean onTouchEvent(MotionEvent event) { if (mFab == null || mFab.getOnClickListener() == null || !mFab.isEnabled()) { return super.onTouchEvent(event); } int action = event.getAction(); switch (action) { case MotionEvent.ACTION_UP: onActionUp(); mFab.onActionUp(); break; case MotionEvent.ACTION_CANCEL: onActionUp(); mFab.onActionUp(); break; } mGestureDetector.onTouchEvent(event); return super.onTouchEvent(event); } private class Shadow extends Drawable { private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private Paint mErase = new Paint(Paint.ANTI_ALIAS_FLAG); private Shadow() { this.init(); } private void init() { setLayerType(LAYER_TYPE_SOFTWARE, null); mPaint.setStyle(Paint.Style.FILL); mPaint.setColor(mColorNormal); mErase.setXfermode(PORTER_DUFF_CLEAR); if (!isInEditMode()) { mPaint.setShadowLayer(mShadowRadius, mShadowXOffset, mShadowYOffset, mShadowColor); } } @Override public void draw(Canvas canvas) { RectF shadowRect = new RectF( mShadowRadius + Math.abs(mShadowXOffset), mShadowRadius + Math.abs(mShadowYOffset), mRawWidth, mRawHeight ); canvas.drawRoundRect(shadowRect, mCornerRadius, mCornerRadius, mPaint); canvas.drawRoundRect(shadowRect, mCornerRadius, mCornerRadius, mErase); } @Override public void setAlpha(int alpha) { } @Override public void setColorFilter(ColorFilter cf) { } @Override public int getOpacity() { return 0; } } }
apache-2.0
hhu94/Synapse-Repository-Services
integration-test/src/test/java/org/sagebionetworks/IT510SynapseJavaClientSearchTest.java
3801
package org.sagebionetworks; import static org.junit.Assert.assertTrue; import java.io.UnsupportedEncodingException; import java.util.LinkedList; import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Test; import org.sagebionetworks.client.SynapseAdminClient; import org.sagebionetworks.client.SynapseAdminClientImpl; import org.sagebionetworks.client.SynapseClient; import org.sagebionetworks.client.SynapseClientImpl; import org.sagebionetworks.client.exceptions.SynapseException; import org.sagebionetworks.repo.model.Project; import org.sagebionetworks.repo.model.search.SearchResults; import org.sagebionetworks.repo.model.search.query.KeyValue; import org.sagebionetworks.repo.model.search.query.SearchQuery; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; /** * Run this integration test as a sanity check to ensure our Synapse Java Client * is working * * @author deflaux */ public class IT510SynapseJavaClientSearchTest { private static SynapseAdminClient adminSynapse; private static SynapseClient synapse; private static Long userToDelete; private static final long MAX_WAIT_TIME_MS = 10*60*1000; // ten min /** * All objects are added to this project. */ private static Project project; @BeforeClass public static void beforeClass() throws Exception { StackConfiguration config = new StackConfiguration(); // Only run this test if search is enabled. Assume.assumeTrue(config.getSearchEnabled()); // Create a user adminSynapse = new SynapseAdminClientImpl(); SynapseClientHelper.setEndpoints(adminSynapse); adminSynapse.setUsername(StackConfiguration.getMigrationAdminUsername()); adminSynapse.setApiKey(StackConfiguration.getMigrationAdminAPIKey()); adminSynapse.clearAllLocks(); synapse = new SynapseClientImpl(); userToDelete = SynapseClientHelper.createUser(adminSynapse, synapse); // Setup a project for this test. project = new Project(); project.setDescription("This is a base project to hold entites for test: "+IT510SynapseJavaClientSearchTest.class.getName()); project = synapse.createEntity(project); } @AfterClass public static void afterClass() throws Exception { StackConfiguration config = new StackConfiguration(); // There's nothing to do if search is disabled if (!config.getSearchEnabled()) { return; } if (synapse != null && project != null) { synapse.deleteAndPurgeEntity(project); } adminSynapse.deleteUser(userToDelete); } @Test public void testSearch() throws Exception{ // wait for the project to appear in the search waitForId(project.getId()); } /** * Helper to wait for a single entity ID to be published to a search index. * @param id * @throws UnsupportedEncodingException * @throws SynapseException * @throws JSONObjectAdapterException * @throws InterruptedException */ private static void waitForId(String id) throws UnsupportedEncodingException, SynapseException, JSONObjectAdapterException, InterruptedException{ SearchQuery searchQuery = new SearchQuery(); searchQuery.setBooleanQuery(new LinkedList<KeyValue>()); KeyValue kv = new KeyValue(); kv.setKey("id"); kv.setValue(id); searchQuery.getBooleanQuery().add(kv); long start = System.currentTimeMillis(); while(true){ SearchResults results = synapse.search(searchQuery); if (results.getFound() == 1) { System.out.println("Found entity " + id + " in search index"); return; } System.out.println("Waiting for entity to be published to the search index, id: "+id+"..."); Thread.sleep(2000); long elapse = System.currentTimeMillis()-start; assertTrue("Timed out waiting for entity to be published to the search index, id: "+id,elapse < MAX_WAIT_TIME_MS); } } }
apache-2.0
yecjl/AndroidStudyDemo
Day11/01_fragment/src/main/java/com/study/fragment/MainActivity.java
2717
package com.study.fragment; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends AppCompatActivity { @Bind(R.id.btn_sound) Button btnSound; @Bind(R.id.btn_storage) Button btnStorage; @Bind(R.id.btn_show) Button btnShow; @Bind(R.id.fl_content) FrameLayout flContent; @Bind(R.id.et_name) EditText etName; private FragmentManager fm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); fm = getFragmentManager(); btnSound.performClick(); } @OnClick({R.id.btn_sound, R.id.btn_storage, R.id.btn_show}) public void onClick(View view) { String tag = null; switch (view.getId()) { case R.id.btn_sound: tag = "soundFragment"; SoundFragment soundFragment = null; if (fm.findFragmentByTag(tag) == null) { soundFragment = new SoundFragment(); } else { soundFragment = (SoundFragment) fm.findFragmentByTag(tag); } inflater(soundFragment, tag); break; case R.id.btn_storage: tag = "storageFragment"; StorageFragment storageFragment = null; if (fm.findFragmentByTag(tag) == null) { storageFragment = new StorageFragment(); } else { storageFragment = (StorageFragment) fm.findFragmentByTag(tag); } inflater(storageFragment, tag); break; case R.id.btn_show: tag = "showFragment"; ShowFragment showFragment = null; if (fm.findFragmentByTag(tag) == null) { showFragment = new ShowFragment(); } else { showFragment = (ShowFragment) fm.findFragmentByTag(tag); } inflater(showFragment, tag); break; } } private void inflater(Fragment fragment, String tag) { FragmentTransaction transaction = fm.beginTransaction(); transaction.replace(R.id.fl_content, fragment, tag); transaction.commit(); } }
apache-2.0
mrz-alagheband/skeleton-boot-app
src/main/java/com/infotech/app/model/TransactionalEntity.java
5759
package com.infotech.app.model; import java.io.Serializable; import java.util.UUID; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Version; import javax.validation.constraints.NotNull; import com.infotech.app.util.RequestContext; import org.joda.time.DateTime; /** * The parent class for all transactional persistent entities. * * @author MohammadReza Alagheband */ @MappedSuperclass public class TransactionalEntity implements Serializable { /** * The default serial version UID. */ private static final long serialVersionUID = 1L; /** * The primary key identifier. */ @Id @GeneratedValue private Long id; /** * A secondary unique identifier which may be used as a reference to this entity by external systems. */ @NotNull private String referenceId = UUID.randomUUID().toString(); /** * The entity instance version used for optimistic locking. */ @Version private Integer version; /** * A reference to the entity or process which created this entity instance. */ @NotNull private String createdBy; /** * The timestamp when this entity instance was created. */ @NotNull private DateTime createdAt; /** * A reference to the entity or process which most recently updated this entity instance. */ private String updatedBy; /** * The timestamp when this entity instance was most recently updated. */ private DateTime updatedAt; public Long getId() { return id; } public void setId(final Long id) { this.id = id; } public String getReferenceId() { return referenceId; } public void setReferenceId(final String referenceId) { this.referenceId = referenceId; } public Integer getVersion() { return version; } public void setVersion(final Integer version) { this.version = version; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(final String createdBy) { this.createdBy = createdBy; } public DateTime getCreatedAt() { return createdAt; } public void setCreatedAt(final DateTime createdAt) { this.createdAt = createdAt; } public String getUpdatedBy() { return updatedBy; } public void setUpdatedBy(final String updatedBy) { this.updatedBy = updatedBy; } public DateTime getUpdatedAt() { return updatedAt; } public void setUpdatedAt(final DateTime updatedAt) { this.updatedAt = updatedAt; } /** * A listener method which is invoked on instances of TransactionalEntity (or their subclasses) prior to initial * persistence. Sets the <code>created</code> audit values for the entity. Attempts to obtain this thread's instance * of a username from the RequestContext. If none exists, throws an IllegalArgumentException. The username is used * to set the <code>createdBy</code> value. The <code>createdAt</code> value is set to the current timestamp. */ @PrePersist public void beforePersist() { final String username = RequestContext.getUsername(); if (username == null) { throw new IllegalArgumentException("Cannot persist a TransactionalEntity without a username " + "in the RequestContext for this thread."); } setCreatedBy(username); setCreatedAt(new DateTime()); } /** * A listener method which is invoked on instances of TransactionalEntity (or their subclasses) prior to being * updated. Sets the <code>updated</code> audit values for the entity. Attempts to obtain this thread's instance of * username from the RequestContext. If none exists, throws an IllegalArgumentException. The username is used to set * the <code>updatedBy</code> value. The <code>updatedAt</code> value is set to the current timestamp. */ @PreUpdate public void beforeUpdate() { final String username = RequestContext.getUsername(); if (username == null) { throw new IllegalArgumentException("Cannot update a TransactionalEntity without a username " + "in the RequestContext for this thread."); } setUpdatedBy(username); setUpdatedAt(new DateTime()); } /** * Determines the equality of two TransactionalEntity objects. If the supplied object is null, returns false. If * both objects are of the same class, and their <code>id</code> values are populated and equal, return * <code>true</code>. Otherwise, return <code>false</code>. * * @param that An Object * @return A boolean * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(final Object that) { if (that == null) { return false; } if (this.getClass().equals(that.getClass())) { final TransactionalEntity thatEntity = (TransactionalEntity) that; if (this.getId() == null || thatEntity.getId() == null) { return false; } if (this.getId().equals(thatEntity.getId())) { return true; } } return false; } /** * Returns the hash value of this object. * * @return An int * @see java.lang.Object#hashCode() */ public int hashCode() { if (getId() == null) { return -1; } return getId().hashCode(); } }
apache-2.0
wenzhucjy/tomcat_source
tomcat-8.0.9-sourcecode/modules/tomcat-lite/java/org/apache/tomcat/lite/io/FileConnectorJavaIo.java
1170
/* */ package org.apache.tomcat.lite.io; import java.io.File; import java.io.IOException; /** * Catalina uses JNDI to abstract filesystem - this is both heavy and * a bit complex. * * This is also a bit complex - but hopefully we can implement it as * non-blocking and without much copy. * */ public class FileConnectorJavaIo extends FileConnector { File base; public FileConnectorJavaIo(File file) { this.base = file; } @Override public boolean isDirectory(String path) { File file = new File(base, path); return file.isDirectory(); } @Override public boolean isFile(String path) { File file = new File(base, path); return file.exists() && !file.isDirectory(); } @Override public void acceptor(ConnectedCallback sc, CharSequence port, Object extra) throws IOException { // TODO: unix domain socket impl. // Maybe: detect new files in the filesystem ? } @Override public void connect(String host, int port, ConnectedCallback sc) throws IOException { } }
apache-2.0
ehcache/sizeof
src/main/java/org/ehcache/sizeof/FlyWeightType.java
8389
/** * Copyright Terracotta, 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 org.ehcache.sizeof; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.net.Proxy; import java.nio.charset.CodingErrorAction; import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import javax.xml.datatype.DatatypeConstants; import javax.xml.namespace.QName; /** * Enum with all the flyweight types that we check for sizeOf measurements * * @author Alex Snaps */ @SuppressWarnings("BoxingBoxedValue") // Don't be smart IDE, these _ARE_ required, we want access to the instances in the cache. enum FlyweightType { /** * java.lang.Enum */ ENUM(Enum.class) { @Override boolean isShared(final Object obj) { return true; } }, /** * java.lang.Class */ CLASS(Class.class) { @Override boolean isShared(final Object obj) { return true; } }, // XXX There is no nullipotent way of determining the interned status of a string // There are numerous String constants within the JDK (see list at http://docs.oracle.com/javase/7/docs/api/constant-values.html), // but enumerating all of them would lead to lots of == tests. //STRING(String.class) { // @Override // boolean isShared(final Object obj) { return obj == ((String)obj).intern(); } //}, /** * java.lang.Boolean */ BOOLEAN(Boolean.class) { @Override boolean isShared(final Object obj) { return obj == Boolean.TRUE || obj == Boolean.FALSE; } }, /** * java.lang.Integer */ INTEGER(Integer.class) { @Override boolean isShared(final Object obj) { int value = (Integer)obj; return value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE && obj == Integer.valueOf(value); } }, /** * java.lang.Short */ SHORT(Short.class) { @Override boolean isShared(final Object obj) { short value = (Short)obj; return value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE && obj == Short.valueOf(value); } }, /** * java.lang.Byte */ BYTE(Byte.class) { @Override boolean isShared(final Object obj) { return obj == Byte.valueOf((Byte)obj); } }, /** * java.lang.Long */ LONG(Long.class) { @Override boolean isShared(final Object obj) { long value = (Long)obj; return value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE && obj == Long.valueOf(value); } }, /** * java.math.BigInteger */ BIGINTEGER(BigInteger.class) { @Override boolean isShared(final Object obj) { return obj == BigInteger.ZERO || obj == BigInteger.ONE || obj == BigInteger.TEN; } }, /** * java.math.BigDecimal */ BIGDECIMAL(BigDecimal.class) { @Override boolean isShared(final Object obj) { return obj == BigDecimal.ZERO || obj == BigDecimal.ONE || obj == BigDecimal.TEN; } }, /** * java.math.MathContext */ MATHCONTEXT(MathContext.class) { @Override boolean isShared(final Object obj) { return obj == MathContext.UNLIMITED || obj == MathContext.DECIMAL32 || obj == MathContext.DECIMAL64 || obj == MathContext.DECIMAL128; } }, /** * java.lang.Character */ CHARACTER(Character.class) { @Override boolean isShared(final Object obj) { return (Character)obj <= Byte.MAX_VALUE && obj == Character.valueOf((Character)obj); } }, /** * java.lang.Locale */ LOCALE(Locale.class) { @Override boolean isShared(final Object obj) { return obj instanceof Locale && GLOBAL_LOCALES.contains(obj); } }, /** * java.util.Logger */ LOGGER(Logger.class) { @Override @SuppressWarnings("deprecation") boolean isShared(final Object obj) { return obj == Logger.global; } }, /** * java.net.Proxy */ PROXY(Proxy.class) { @Override boolean isShared(final Object obj) { return obj == Proxy.NO_PROXY; } }, /** * java.nio.charset.CodingErrorAction */ CODINGERRORACTION(CodingErrorAction.class) { @Override boolean isShared(final Object obj) { return true; } }, /** * javax.xml.datatype.DatatypeConstants.Field */ DATATYPECONSTANTS_FIELD(DatatypeConstants.Field.class) { @Override boolean isShared(final Object obj) { return true; } }, /** * javax.xml.namespace.QName */ QNAME(QName.class) { @Override boolean isShared(final Object obj) { return obj == DatatypeConstants.DATETIME || obj == DatatypeConstants.TIME || obj == DatatypeConstants.DATE || obj == DatatypeConstants.GYEARMONTH || obj == DatatypeConstants.GMONTHDAY || obj == DatatypeConstants.GYEAR || obj == DatatypeConstants.GMONTH || obj == DatatypeConstants.GDAY || obj == DatatypeConstants.DURATION || obj == DatatypeConstants.DURATION_DAYTIME || obj == DatatypeConstants.DURATION_YEARMONTH; } }, /** * misc comparisons that can not rely on the object's class. */ MISC(Void.class) { @Override boolean isShared(final Object obj) { boolean emptyCollection = obj == Collections.EMPTY_SET || obj == Collections.EMPTY_LIST || obj == Collections.EMPTY_MAP; boolean systemStream = obj == System.in || obj == System.out || obj == System.err; return emptyCollection || systemStream || obj == String.CASE_INSENSITIVE_ORDER; } }; private static final Map<Class<?>, FlyweightType> TYPE_MAPPINGS = new HashMap<>(); static { for (FlyweightType type : FlyweightType.values()) { TYPE_MAPPINGS.put(type.clazz, type); } } private static final Set<Locale> GLOBAL_LOCALES; static { Map<Locale, Void> locales = new IdentityHashMap<>(); for (Field f : Locale.class.getFields()) { int modifiers = f.getModifiers(); if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Locale.class.equals(f.getType())) { try { locales.put((Locale)f.get(null), null); } catch (IllegalArgumentException | IllegalAccessException e) { // } } } GLOBAL_LOCALES = locales.keySet(); } private final Class<?> clazz; FlyweightType(final Class<?> clazz) { this.clazz = clazz; } /** * Whether this is a shared object * * @param obj the object to check for * @return true, if shared */ abstract boolean isShared(Object obj); /** * Will return the Flyweight enum instance for the flyweight Class, or null if type isn't flyweight * * @param aClazz the class we need the FlyweightType instance for * @return the FlyweightType, or null */ static FlyweightType getFlyweightType(final Class<?> aClazz) { if (aClazz.isEnum() || (aClazz.getSuperclass() != null && aClazz.getSuperclass().isEnum())) { return ENUM; } else { FlyweightType flyweightType = TYPE_MAPPINGS.get(aClazz); return flyweightType != null ? flyweightType : MISC; } } }
apache-2.0
kingargyle/turmeric-bot
components/camel-quartz/src/main/java/org/apache/camel/routepolicy/quartz/ScheduledJob.java
2378
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.routepolicy.quartz; import java.io.Serializable; import org.apache.camel.Route; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.SchedulerContext; import org.quartz.SchedulerException; public class ScheduledJob implements Job, Serializable, ScheduledRoutePolicyConstants { private static final long serialVersionUID = 26L; private Route storedRoute; /* (non-Javadoc) * @see org.quartz.Job#execute(org.quartz.JobExecutionContext) */ public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { SchedulerContext schedulerContext; try { schedulerContext = jobExecutionContext.getScheduler().getContext(); } catch (SchedulerException e) { throw new JobExecutionException("Failed to obtain scheduler context for job " + jobExecutionContext.getJobDetail().getName()); } Action storedAction = (Action) schedulerContext.get(SCHEDULED_ACTION); storedRoute = (Route) schedulerContext.get(SCHEDULED_ROUTE); ScheduledRoutePolicy policy = (ScheduledRoutePolicy) storedRoute.getRouteContext().getRoutePolicy(); try { policy.onJobExecute(storedAction, storedRoute); } catch (Exception e) { throw new JobExecutionException("Failed to execute Scheduled Job for route " + storedRoute.getId() + " with trigger name: " + jobExecutionContext.getTrigger().getFullName()); } } }
apache-2.0
leadware/jpersistence-tools
jpersistence-tools-core/src/test/java/net/leadware/persistence/tools/test/dao/SXGroupDAO.java
1244
/** * 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 net.leadware.persistence.tools.test.dao; import net.leadware.persistence.tools.core.dao.JPAGenericDAO; import net.leadware.persistence.tools.test.dao.entities.sx.SXGroup; /** * Interface de la DAO de gestion des Groupes * @author Jean-Jacques ETUNÈ NGI */ public interface SXGroupDAO extends JPAGenericDAO<SXGroup> { /** * Nom du service DAO */ public static final String SERVICE_NAME = "GroupDAO"; }
apache-2.0
jmacglashan/burlap
src/main/java/burlap/shell/visual/VisualExplorer.java
16650
package burlap.shell.visual; import burlap.mdp.core.action.Action; import burlap.mdp.core.oo.OODomain; import burlap.mdp.core.oo.propositional.GroundedProp; import burlap.mdp.core.oo.propositional.PropositionalFunction; import burlap.mdp.core.oo.state.OOState; import burlap.mdp.core.state.State; import burlap.mdp.singleagent.SADomain; import burlap.mdp.core.action.ActionType; import burlap.mdp.singleagent.environment.Environment; import burlap.mdp.singleagent.environment.EnvironmentOutcome; import burlap.mdp.singleagent.environment.SimulatedEnvironment; import burlap.mdp.singleagent.environment.extensions.StateSettableEnvironment; import burlap.visualizer.Visualizer; import burlap.shell.BurlapShell; import burlap.shell.EnvironmentShell; import burlap.shell.ShellObserver; import burlap.shell.command.ShellCommand; import burlap.shell.command.env.ObservationCommand; import joptsimple.OptionParser; import joptsimple.OptionSet; import javax.swing.*; import javax.swing.text.DefaultCaret; import java.awt.*; import java.awt.event.*; import java.io.PrintStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; /** * This class allows you act as the agent by choosing actions in an {@link burlap.mdp.singleagent.environment.Environment}. * States are * conveyed to the user through a 2D visualization and the user specifies actions * by either pressing keys that are mapped to actions or by typing the actions into the action command field. * Action parameters in the action field are specified by space delineated input. For instance: "stack block0 block1" will cause * the stack action to called with action parameters block0 and block1. The ` key * causes the environment to reset. * <p> * Additionally, the VisualExplorer also creates an associated instance of an {@link burlap.shell.EnvironmentShell} * that you can access using the "Show Shell" button. You can use the shell to modify the state (assuming the input * {@link burlap.mdp.singleagent.environment.Environment} implements {@link StateSettableEnvironment}, * record trajectories that you make in the environment, and any number of other tasks. The shell's "programs," specified with * {@link burlap.shell.command.ShellCommand} instances, may also be expanded so that you can create your own runtime tools. * See the {@link burlap.shell.BurlapShell} and {@link burlap.shell.EnvironmentShell} Java doc for more information on how * to use them. If you need access to the shell instance, you can get it with the {@link #getShell()} method. You can * also set shell commands to be executed when a key is pressed in the visualization. Set them with the * {@link #addKeyShellCommand(String, String)} method. * <p> * A special shell command, "livePoll" is automatically added to the shell, that allows the user to set the visualizer * to auto poll the environment at a fixed interval for the state and display it. This is useful when the environment * can evolve independent of agent action or explicit shell commands. See it's help in the shell (-h option) for more * information on it. * @author James MacGlashan * */ public class VisualExplorer extends JFrame implements ShellObserver{ private static final long serialVersionUID = 1L; protected Environment env; protected SADomain domain; protected Map <String, Action> keyActionMap; protected Map <String, String> keyShellMap = new HashMap<String, String>(); protected Visualizer painter; protected TextArea propViewer; protected TextField actionField; protected JButton actionButton; protected int cWidth; protected int cHeight; protected JFrame consoleFrame; protected JTextArea stateConsole; protected Timer livePollingTimer; protected int pollInterval; protected EnvironmentShell shell; protected TextAreaStreams tstreams; /** * Initializes with a domain and initial state, automatically creating a {@link burlap.mdp.singleagent.environment.SimulatedEnvironment} * as the environment with which to interact. The created {@link burlap.mdp.singleagent.environment.SimulatedEnvironment} will * have a {@link burlap.mdp.singleagent.common.NullRewardFunction} and {@link burlap.mdp.auxiliary.common.NullTermination} functions set. * @param domain the domain to explore * @param painter the 2D state visualizer * @param baseState the initial state from which to explore */ public VisualExplorer(SADomain domain, Visualizer painter, State baseState){ Environment env = new SimulatedEnvironment(domain, baseState); this.init(domain, env, painter, 800, 800); } /** * Initializes with a visualization canvas size set to 800x800. * @param domain the domain to explore * @param env the {@link burlap.mdp.singleagent.environment.Environment} with which to interact. * @param painter the 2D state visualizer */ public VisualExplorer(SADomain domain, Environment env, Visualizer painter){ this.init(domain, env, painter, 800, 800); } /** * Initializes. * @param domain the domain to explore * @param env the {@link burlap.mdp.singleagent.environment.Environment} with which to interact. * @param painter the 2D state visualizer * @param w the width of the visualizer canvas * @param h the height of the visualizer canvas */ public VisualExplorer(SADomain domain, Environment env, Visualizer painter, int w, int h){ this.init(domain, env, painter, w, h); } protected void init(SADomain domain, Environment env, Visualizer painter, int w, int h){ this.domain = domain; this.env = env; this.painter = painter; this.keyActionMap = new HashMap <String, Action>(); this.keyShellMap.put("`", "reset"); this.cWidth = w; this.cHeight = h; this.propViewer = new TextArea(); this.propViewer.setEditable(false); } /** * Returns the {@link burlap.visualizer.Visualizer} used by this explorer. * @return the {@link burlap.visualizer.Visualizer} used by this explorer. */ public Visualizer getVisualizer(){ return this.painter; } /** * Returns the {@link burlap.shell.EnvironmentShell} instance associated with this object. * @return the {@link burlap.shell.EnvironmentShell} instance associated with this object. */ public EnvironmentShell getShell() { return shell; } /** * Specifies which action to execute for a given key press * @param key the key that is pressed by the user * @param action the {@link Action} to take when the key is pressed */ public void addKeyAction(String key, Action action){ keyActionMap.put(key, action); } /** * Adds a key action mapping. * @param key the key that is pressed by the user * @param actionTypeName the name of the {@link ActionType} * @param paramStringRep the string representation of the action parameters */ public void addKeyAction(String key, String actionTypeName, String paramStringRep){ keyActionMap.put(key, this.domain.getAction(actionTypeName).associatedAction(paramStringRep)); } /** * Cause a shell command to be executed when key is pressed with the visualizer highlighted. * @param key the key to activate the shell command. * @param shellCommand the shell command to execute. */ public void addKeyShellCommand(String key, String shellCommand){ this.keyShellMap.put(key, shellCommand); } /** * Starts a thread that polls this explorer's {@link burlap.mdp.singleagent.environment.Environment} every * msPollDelay milliseconds for its current state and updates the visualizer to that state. * Polling can be stopped with the {@link #stopLivePolling()}. If live polling is already running, * this method call will only change the poll rate. * @param msPollDelay the number of milliseconds between environment polls and state updates. */ public void startLiveStatePolling(final int msPollDelay){ this.pollInterval = msPollDelay; if (this.livePollingTimer != null) { if (!this.livePollingTimer.isRunning()) { this.livePollingTimer.start(); } return; } ActionListener animate = new ActionListener() { public void actionPerformed(ActionEvent ae) { State s = env.currentObservation(); if(s != null) { updateState(s); } } }; Timer timer = new Timer(pollInterval, animate); timer.start(); } /** * Stops this class from live polling this explorer's {@link burlap.mdp.singleagent.environment.Environment}. */ public void stopLivePolling() { if (this.livePollingTimer.isRunning()) { this.livePollingTimer.stop(); } } @Override public void observeCommand(BurlapShell shell, ShellCommandEvent event) { if(event.returnCode == 1){ this.updateState(this.env.currentObservation()); } if(event.command instanceof ObservationCommand){ this.updateState(this.env.currentObservation()); } } /** * Initializes the visual explorer GUI and presents it to the user. */ public void initGUI(){ painter.setPreferredSize(new Dimension(cWidth, cHeight)); propViewer.setPreferredSize(new Dimension(cWidth, 100)); Container bottomContainer = new Container(); bottomContainer.setLayout(new BorderLayout()); bottomContainer.add(propViewer, BorderLayout.NORTH); getContentPane().add(bottomContainer, BorderLayout.SOUTH); getContentPane().add(painter, BorderLayout.CENTER); addKeyListener(new KeyListener(){ public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { handleKeyPressed(e); } }); //also add key listener to the painter in case the focus is changed painter.addKeyListener(new KeyListener(){ public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { handleKeyPressed(e); } }); propViewer.addKeyListener(new KeyListener(){ public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { handleKeyPressed(e); } }); painter.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { painter.requestFocus(); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }); actionField = new TextField(20); bottomContainer.add(actionField, BorderLayout.CENTER); actionButton = new JButton("Execute"); actionButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { handleExecute(); } }); bottomContainer.add(actionButton, BorderLayout.EAST); painter.updateState(this.env.currentObservation()); this.updatePropTextArea(this.env.currentObservation()); JButton showConsoleButton = new JButton("Show Shell"); showConsoleButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { VisualExplorer.this.consoleFrame.setVisible(true); } }); bottomContainer.add(showConsoleButton, BorderLayout.SOUTH); this.consoleFrame = new JFrame(); this.consoleFrame.setPreferredSize(new Dimension(600, 500)); this.stateConsole = new JTextArea(40, 40); this.stateConsole.setLineWrap(true); DefaultCaret caret = (DefaultCaret)this.stateConsole.getCaret(); caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); this.stateConsole.setEditable(false); this.stateConsole.setMargin(new Insets(10, 5, 10, 5)); JScrollPane shellScroll = new JScrollPane(this.stateConsole, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); this.consoleFrame.getContentPane().add(shellScroll, BorderLayout.CENTER); this.tstreams = new TextAreaStreams(this.stateConsole); this.shell = new EnvironmentShell(domain, env, tstreams.getTin(), new PrintStream(tstreams.getTout())); this.shell.addObservers(this); this.shell.setVisualizer(this.painter); this.shell.addCommand(new LivePollCommand()); this.shell.start(); final JTextField consoleCommand = new JTextField(40); consoleCommand.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String command = ((JTextField)e.getSource()).getText(); consoleCommand.setText(""); tstreams.receiveInput(command + "\n"); } }); this.consoleFrame.getContentPane().add(consoleCommand, BorderLayout.SOUTH); this.stateConsole.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { consoleCommand.requestFocus(); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }); pack(); setVisible(true); this.consoleFrame.pack(); this.consoleFrame.setVisible(false); } /** * Updates the currently visualized state to the input state. * @param s the state to visualize. */ synchronized public void updateState(State s){ this.painter.updateState(s); this.updatePropTextArea(s); } /** * Handles action execute button. */ protected void handleExecute(){ String actionCommand = this.actionField.getText(); if(actionCommand.length() == 0){ return ; } this.shell.executeCommand("ex " + actionCommand); } /** * Handles key presses * @param e the key event */ protected void handleKeyPressed(KeyEvent e){ String key = String.valueOf(e.getKeyChar()); //otherwise this could be an action, see if there is an action mapping Action mappedAction = keyActionMap.get(key); if(mappedAction != null){ this.executeAction(mappedAction); } else{ String shellCommand = this.keyShellMap.get(key); if(shellCommand != null && this.shell != null){ this.shell.executeCommand(shellCommand); } } } /** * Executes the provided {@link Action} in the explorer's environment and records * the result if episodes are being recorded. * @param ga the {@link Action} to execute. */ protected void executeAction(Action ga){ EnvironmentOutcome eo = env.executeAction(ga); this.updateState(eo.op); } /** * Updates the propositional function evaluation text display for the given state. * @param s the input state on which propositional functions are to be evaluated. */ protected void updatePropTextArea(State s){ if(!(domain instanceof OODomain) || !(s instanceof OOState)){ return ; } StringBuilder buf = new StringBuilder(); List <PropositionalFunction> props = ((OODomain)domain).propFunctions(); for(PropositionalFunction pf : props){ List<GroundedProp> gps = pf.allGroundings((OOState)s); for(GroundedProp gp : gps){ if(gp.isTrue((OOState)s)){ buf.append(gp.toString()).append("\n"); } } } propViewer.setText(buf.toString()); } /** * Shell command that allow live polling of the {@link VisualExplorer} to be polled. */ public class LivePollCommand implements ShellCommand{ protected OptionParser parser = new OptionParser("t:fch*"); @Override public String commandName() { return "livePoll"; } @Override public int call(BurlapShell shell, String argString, Scanner is, PrintStream os) { Environment env = ((EnvironmentShell)shell).getEnv(); OptionSet oset = this.parser.parse(argString.split(" ")); if(oset.has("h")){ os.println("[-t interval] [-f] [-c]\n\n" + "Used to set the associated visual explorer to poll the environment for the current state and update the display on a fixed interval.\n" + "-t interval: turns on live polling and causes the environment to be polled every interval milliseconds.\n" + "-f: turns off live polling.\n" + "-c: returns the status of live polling (enabled/disabled and rate"); } if(oset.has("t")){ String val = (String)oset.valueOf("t"); int interval = Integer.valueOf(val); startLiveStatePolling(interval); } else if(oset.has("f")){ stopLivePolling(); } if(oset.has("c")){ if(livePollingTimer != null && livePollingTimer.isRunning()){ os.println("Live polling is enabled and polls every " + pollInterval + " milliseconds."); } else{ os.println("Live polling is disabled."); } } return 0; } } }
apache-2.0
agwlvssainokuni/springapp2
galleryapp/gallery-web/src/main/java/cherry/gallery/web/applied/ex60/AppliedEx60ServiceImpl.java
6053
/* * Copyright 2015,2016 agwlvssainokuni * * 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 cherry.gallery.web.applied.ex60; import static cherry.gallery.common.CodeValue.SORT_BY.SORT_BY_00; import static cherry.gallery.common.CodeValue.SORT_BY.SORT_BY_01; import static cherry.gallery.common.CodeValue.SORT_BY.SORT_BY_02; import static cherry.gallery.common.CodeValue.SORT_BY.SORT_BY_03; import static cherry.gallery.common.CodeValue.SORT_BY.SORT_BY_04; import static cherry.gallery.common.CodeValue.SORT_BY.SORT_BY_05; import static cherry.gallery.common.CodeValue.SORT_BY.SORT_BY_06; import static cherry.gallery.common.CodeValue.SORT_BY.SORT_BY_07; import static java.util.Arrays.asList; import java.time.LocalDateTime; import java.util.List; import java.util.function.Function; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cherry.elemental.paginate.PagedList; import cherry.fundamental.bizcal.BizDateTime; import cherry.fundamental.download.TableDownloadOperation; import cherry.fundamental.querydsl.QuerydslSupport; import cherry.fundamental.spring.webmvc.SortOrder; import cherry.fundamental.spring.webmvc.SortParam; import cherry.gallery.common.CodeValue.SORT_BY; import cherry.gallery.db.gen.query.BExTbl1; import cherry.gallery.db.gen.query.QExTbl1; import com.querydsl.core.types.OrderSpecifier; import com.querydsl.core.types.dsl.ComparableExpressionBase; import com.querydsl.sql.SQLQuery; @Service public class AppliedEx60ServiceImpl implements AppliedEx60Service { @Autowired private QuerydslSupport querydslSupport; @Autowired private TableDownloadOperation tableDownloadOperation; @Autowired private BizDateTime bizDateTime; private final QExTbl1 et1 = new QExTbl1("et1"); private final String filename = "ex60_{0}.xlsx"; private final List<String> header = asList("ID", "文字列【10】", "文字列【100】", "整数【64bit】", "小数【1桁】", "小数【3桁】", "日付", "時刻", "日時"); @Transactional @Override public PagedList<BExTbl1> search(AppliedEx60Form form) { return querydslSupport.search(commonClause(form), orderByClause(form), form.getPno(), form.getPsz(), et1); } @Transactional @Override public void downloadXlsx(AppliedEx60Form form, HttpServletResponse response) { LocalDateTime now = bizDateTime.now(); tableDownloadOperation.downloadXlsx(response, filename, now, header, commonClause(form), orderByClause(form), et1.id, et1.text10, et1.text100, et1.int64, et1.decimal1, et1.decimal3, et1.dt, et1.tm, et1.dtm); } private Function<SQLQuery<?>, SQLQuery<?>> commonClause(final AppliedEx60Form form) { return (SQLQuery<?> query) -> { query.from(et1); if (StringUtils.isNotEmpty(form.getText10())) { query.where(et1.text10.startsWith(form.getText10())); } if (form.getInt64From() != null) { query.where(et1.int64.goe(form.getInt64From())); } if (form.getInt64To() != null) { query.where(et1.int64.loe(form.getInt64To())); } if (form.getDecimal1From() != null) { query.where(et1.decimal1.goe(form.getDecimal1From())); } if (form.getDecimal1To() != null) { query.where(et1.decimal1.loe(form.getDecimal1To())); } if (form.getDecimal3From() != null) { query.where(et1.decimal3.goe(form.getDecimal3From())); } if (form.getDecimal3To() != null) { query.where(et1.decimal3.loe(form.getDecimal3To())); } if (form.getDtFrom() != null) { query.where(et1.dt.goe(form.getDtFrom())); } if (form.getDtTo() != null) { query.where(et1.dt.loe(form.getDtTo())); } if (form.getTmFrom() != null) { query.where(et1.tm.goe(form.getTmFrom())); } if (form.getTmTo() != null) { query.where(et1.tm.loe(form.getTmTo())); } if (form.getDtmFromD() != null && form.getDtmFromT() != null) { query.where(et1.dtm.goe(form.getDtmFromD().atTime(form.getDtmFromT()))); } if (form.getDtmToD() != null && form.getDtmToT() != null) { query.where(et1.dtm.loe(form.getDtmToD().atTime(form.getDtmToT()))); } return query; }; } private Function<SQLQuery<?>, SQLQuery<?>> orderByClause(final AppliedEx60Form form) { return (SQLQuery<?> query) -> { query.orderBy(createOrderSpec(form.getSort1())); query.orderBy(createOrderSpec(form.getSort2())); return query; }; } private OrderSpecifier<?> createOrderSpec(SortParam sort) { SORT_BY sortBy = SORT_BY.resolve(sort.getBy()); ComparableExpressionBase<?> sortKey; if (sortBy == SORT_BY_00) { sortKey = et1.id; } else if (sortBy == SORT_BY_01) { sortKey = et1.text10; } else if (sortBy == SORT_BY_02) { sortKey = et1.int64; } else if (sortBy == SORT_BY_03) { sortKey = et1.decimal1; } else if (sortBy == SORT_BY_04) { sortKey = et1.decimal3; } else if (sortBy == SORT_BY_05) { sortKey = et1.dt; } else if (sortBy == SORT_BY_06) { sortKey = et1.tm; } else if (sortBy == SORT_BY_07) { sortKey = et1.dtm; } else { sortKey = et1.id; } if (sort.getOrder() == SortOrder.ASC) { return sortKey.asc(); } else if (sort.getOrder() == SortOrder.DESC) { return sortKey.desc(); } else { return sortKey.asc(); } } }
apache-2.0
cn-cerc/summer-mis
src/main/java/cn/cerc/ui/core/HtmlContent.java
100
package cn.cerc.ui.core; public interface HtmlContent { public void output(HtmlWriter html); }
apache-2.0
NJUJYB/disYarn
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/TestLocalFileSystemPermission.java
8481
/** * 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.fs; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.permission.*; import org.apache.hadoop.test.GenericTestUtils; import org.apache.hadoop.util.StringUtils; import org.apache.log4j.Level; import org.apache.hadoop.util.Shell; import java.io.*; import java.util.*; import junit.framework.*; /** * This class tests the local file system via the FileSystem abstraction. */ public class TestLocalFileSystemPermission extends TestCase { static final String TEST_PATH_PREFIX = GenericTestUtils.getTempPath( TestLocalFileSystemPermission.class.getSimpleName()); static { GenericTestUtils.setLogLevel(FileSystem.LOG, Level.DEBUG); } private Path writeFile(FileSystem fs, String name) throws IOException { Path f = new Path(TEST_PATH_PREFIX + name); FSDataOutputStream stm = fs.create(f); stm.writeBytes("42\n"); stm.close(); return f; } private Path writeFile(FileSystem fs, String name, FsPermission perm) throws IOException { Path f = new Path(TEST_PATH_PREFIX + name); FSDataOutputStream stm = fs.create(f, perm, true, 2048, (short)1, 32 * 1024 * 1024, null); stm.writeBytes("42\n"); stm.close(); return f; } private void cleanup(FileSystem fs, Path name) throws IOException { assertTrue(fs.exists(name)); fs.delete(name, true); assertTrue(!fs.exists(name)); } public void testLocalFSDirsetPermission() throws IOException { if (Path.WINDOWS) { System.out.println("Cannot run test for Windows"); return; } Configuration conf = new Configuration(); conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "044"); LocalFileSystem localfs = FileSystem.getLocal(conf); Path dir = new Path(TEST_PATH_PREFIX + "dir"); localfs.mkdirs(dir); try { FsPermission initialPermission = getPermission(localfs, dir); assertEquals( FsPermission.getDirDefault().applyUMask(FsPermission.getUMask(conf)), initialPermission); } catch(Exception e) { System.out.println(StringUtils.stringifyException(e)); System.out.println("Cannot run test"); return; } FsPermission perm = new FsPermission((short)0755); Path dir1 = new Path(TEST_PATH_PREFIX + "dir1"); localfs.mkdirs(dir1, perm); try { FsPermission initialPermission = getPermission(localfs, dir1); assertEquals(perm.applyUMask(FsPermission.getUMask(conf)), initialPermission); } catch(Exception e) { System.out.println(StringUtils.stringifyException(e)); System.out.println("Cannot run test"); return; } Path dir2 = new Path(TEST_PATH_PREFIX + "dir2"); localfs.mkdirs(dir2); try { FsPermission initialPermission = getPermission(localfs, dir2); Path copyPath = new Path(TEST_PATH_PREFIX + "dir_copy"); localfs.rename(dir2, copyPath); FsPermission copyPermission = getPermission(localfs, copyPath); assertEquals(copyPermission, initialPermission); dir2 = copyPath; } catch (Exception e) { System.out.println(StringUtils.stringifyException(e)); System.out.println("Cannot run test"); return; } finally { cleanup(localfs, dir); cleanup(localfs, dir1); if (localfs.exists(dir2)) { localfs.delete(dir2, true); } } } /** Test LocalFileSystem.setPermission */ public void testLocalFSsetPermission() throws IOException { if (Path.WINDOWS) { System.out.println("Cannot run test for Windows"); return; } Configuration conf = new Configuration(); conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "044"); LocalFileSystem localfs = FileSystem.getLocal(conf); String filename = "foo"; Path f = writeFile(localfs, filename); try { FsPermission initialPermission = getPermission(localfs, f); assertEquals( FsPermission.getFileDefault().applyUMask(FsPermission.getUMask(conf)), initialPermission); } catch(Exception e) { System.out.println(StringUtils.stringifyException(e)); System.out.println("Cannot run test"); return; } String filename1 = "foo1"; FsPermission perm = new FsPermission((short)0755); Path f1 = writeFile(localfs, filename1, perm); try { FsPermission initialPermission = getPermission(localfs, f1); assertEquals( perm.applyUMask(FsPermission.getUMask(conf)), initialPermission); } catch(Exception e) { System.out.println(StringUtils.stringifyException(e)); System.out.println("Cannot run test"); return; } String filename2 = "foo2"; Path f2 = writeFile(localfs, filename2); try { FsPermission initialPermission = getPermission(localfs, f2); Path copyPath = new Path(TEST_PATH_PREFIX + "/foo_copy"); localfs.rename(f2, copyPath); FsPermission copyPermission = getPermission(localfs, copyPath); assertEquals(copyPermission, initialPermission); f2 = copyPath; } catch (Exception e) { System.out.println(StringUtils.stringifyException(e)); System.out.println("Cannot run test"); return; } try { // create files and manipulate them. FsPermission all = new FsPermission((short)0777); FsPermission none = new FsPermission((short)0); localfs.setPermission(f, none); assertEquals(none, getPermission(localfs, f)); localfs.setPermission(f, all); assertEquals(all, getPermission(localfs, f)); } finally { cleanup(localfs, f); cleanup(localfs, f1); if (localfs.exists(f2)) { localfs.delete(f2, true); } } } FsPermission getPermission(LocalFileSystem fs, Path p) throws IOException { return fs.getFileStatus(p).getPermission(); } /** Test LocalFileSystem.setOwner */ public void testLocalFSsetOwner() throws IOException { if (Path.WINDOWS) { System.out.println("Cannot run test for Windows"); return; } Configuration conf = new Configuration(); conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "044"); LocalFileSystem localfs = FileSystem.getLocal(conf); String filename = "bar"; Path f = writeFile(localfs, filename); List<String> groups = null; try { groups = getGroups(); System.out.println(filename + ": " + getPermission(localfs, f)); } catch(IOException e) { System.out.println(StringUtils.stringifyException(e)); System.out.println("Cannot run test"); return; } if (groups == null || groups.size() < 1) { System.out.println("Cannot run test: need at least one group. groups=" + groups); return; } // create files and manipulate them. try { String g0 = groups.get(0); localfs.setOwner(f, null, g0); assertEquals(g0, getGroup(localfs, f)); if (groups.size() > 1) { String g1 = groups.get(1); localfs.setOwner(f, null, g1); assertEquals(g1, getGroup(localfs, f)); } else { System.out.println("Not testing changing the group since user " + "belongs to only one group."); } } finally {cleanup(localfs, f);} } static List<String> getGroups() throws IOException { List<String> a = new ArrayList<String>(); String s = Shell.execCommand(Shell.getGroupsCommand()); for(StringTokenizer t = new StringTokenizer(s); t.hasMoreTokens(); ) { a.add(t.nextToken()); } return a; } String getGroup(LocalFileSystem fs, Path p) throws IOException { return fs.getFileStatus(p).getGroup(); } }
apache-2.0
netboynb/coco
coco-common/src/main/java/com/ms/coco/exception/RpcNettyConnectLessException.java
599
package com.ms.coco.exception; /** * * TODO: DOCUMENT ME! * * @author netboy */ public class RpcNettyConnectLessException extends RpcFrameworkException { private static final long serialVersionUID = 1L; public RpcNettyConnectLessException() { super(RpcErrorMsgConstant.SERVICE_CONNECT_LOST); } public RpcNettyConnectLessException(String msg) { super(RpcErrorMsgConstant.SERVICE_CONNECT_LOST, msg); } public RpcNettyConnectLessException(String message, Throwable cause) { super(message, RpcErrorMsgConstant.SERVICE_CONNECT_LOST, cause); } }
apache-2.0
jstrachan/kubernetes-client
kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/ServiceAccountOperationsImpl.java
1429
/** * Copyright (C) 2015 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.kubernetes.client.dsl.internal; import io.fabric8.kubernetes.api.model.DoneableServiceAccount; import io.fabric8.kubernetes.api.model.ServiceAccount; import io.fabric8.kubernetes.api.model.ServiceAccountList; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.dsl.ClientResource; public class ServiceAccountOperationsImpl extends HasMetadataOperation<KubernetesClient, ServiceAccount, ServiceAccountList, DoneableServiceAccount, ClientResource<ServiceAccount, DoneableServiceAccount>> { public ServiceAccountOperationsImpl(KubernetesClient client) { super(client,"serviceaccounts", null, null); } public ServiceAccountOperationsImpl(KubernetesClient client, String namespace, String name) { super(client,"serviceaccounts", namespace, name); } }
apache-2.0
arongeorgel/lightab
app/src/main/java/ro/arongeorgel/lighttab/LightNavigationActivity.java
9462
/** * * Copyright [2013] [Aron Georgel - aron.georgel@gmail.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 ro.arongeorgel.lighttab; import android.app.Activity; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TabHost; import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Stack; /** * @author Georgel Aron <a * href="mailto:aron.georgel@gmail.com">aron.georgel@gmail.com</a> * <p/> * Created by Aron Georgel on 18/12/2013 * Updated by Aron Georgel on 11/29/2014. * <p/> * <p> * Activity container for tabbed navigation which holds the logic of * navigation and stack of fragments from each tab. * </p> */ @SuppressWarnings("UnusedDeclaration") public class LightNavigationActivity extends Activity { /** * Container for a tabbed window view */ private TabHost mTabHost; /** * Navigation stacks for each tab gets created */ private HashMap<String, Stack<LightFragment>> mStacks; /** * Holds the name of current tab */ private String mCurrentTab; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_tab_navigation_activity); mStacks = new HashMap<String, Stack<LightFragment>>(); mTabHost = (TabHost) findViewById(android.R.id.tabhost); mTabHost.setup(); int apiLevel = android.os.Build.VERSION.SDK_INT; if (apiLevel >= 15) { mTabHost.getTabWidget().setDividerDrawable(R.drawable.tab_unselected); } } /** * Add a new tab in container * * @param tabName will be displayed on tab * @param fragmentClass fragment inside tab * @param drawableId resource id for add an icon for tab */ private synchronized void addTab(String tabName, LightFragment fragmentClass, int drawableId) { mStacks.put(tabName, new Stack<LightFragment>()); TabHost.TabSpec spec = mTabHost.newTabSpec(tabName); View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, mTabHost.getTabWidget(), false); TextView title = (TextView) tabIndicator.findViewById(R.id.title); ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon); title.setText(tabName); icon.setImageResource(drawableId); spec.setContent(new TabHost.TabContentFactory() { public View createTabContent(String tag) { return findViewById(R.id.realtabcontent); } }); spec.setIndicator(tabIndicator); mTabHost.addTab(spec); } /** * Switch tab programmatically, from inside any of the fragment. * * @param tabNumber the number of the tab */ public final void setCurrentTab(int tabNumber) { mTabHost.setCurrentTab(tabNumber); } /** * Add fragment to a tab.<br /> * <br /> * <p/> * <p> * Push a new fragment in same tab:<br /> * Example: <br /> * <code> * getNavigator().pushFragment("ONE", new FragmentOneTabOneTwo(), true, true); * </code> * </p> * * @param tagId Tab identifier fragment * @param fragment Fragment to show, in tab identified by tag * @param shouldAnimate should animate transaction false when we switch tabs, or * adding first fragment to a tab true when when we are pushing * more fragment into navigation stack * @param shouldAdd Should add to fragment navigation stack (mStacks.get(tag)). * false when we are switching tabs (except for the first time) * true in all other cases. */ public synchronized final void pushFragment(String tagId, LightFragment fragment, boolean shouldAnimate, boolean shouldAdd, Bundle extras) { if (shouldAdd) mStacks.get(tagId).push(fragment); FragmentManager manager = getFragmentManager(); FragmentTransaction ft = manager.beginTransaction(); if (shouldAnimate) ft.setCustomAnimations(LightAnimation.Animation.LEFT_IN.getAnimation(), LightAnimation.getComplementaryAnimation(LightAnimation.Animation.LEFT_IN)); ft.replace(R.id.realtabcontent, fragment); ft.commit(); } /** * Remove a fragment from a tab */ public synchronized final void popFragment() { LightFragment fragment = mStacks.get(mCurrentTab).elementAt(mStacks.get(mCurrentTab).size() - 2); mStacks.get(mCurrentTab).pop(); FragmentManager manager = getFragmentManager(); FragmentTransaction ft = manager.beginTransaction(); ft.setCustomAnimations(R.animator.slide_right_in, R.animator.slide_right_out); ft.replace(R.id.realtabcontent, fragment); ft.commit(); } /** * toggle tabs visibility (VISIBLE or GONE) */ public void toggleNavBarVisibility() { mTabHost.setVisibility(mTabHost.getVisibility() == View.GONE ? View.VISIBLE : View.GONE); } /** * @return true if tabs are visible, false otherwise */ public boolean isNavBarVisible() { return mTabHost.getVisibility() != View.GONE; } @Override public void onBackPressed() { if (mStacks.get(mCurrentTab).size() == 1) { finish(); return; } popFragment(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (mStacks.get(mCurrentTab).size() == 0) { return; } mStacks.get(mCurrentTab).lastElement().onActivityResult(requestCode, resultCode, data); } /** * @author Georgel Aron */ private static class FragmentHolder { private String mKey; private LightFragment mValue; public FragmentHolder(String key, LightFragment value) { mKey = key; mValue = value; } /** * @return tab key */ public String getKey() { return mKey; } /** * @return first fragment from a tab */ public LightFragment getValue() { return mValue; } } /** * @author Georgel Aron */ public static class NavigationBuilder { private LightNavigationActivity mTabNavigation; private List<FragmentHolder> mFragmentHolderList; /** * Constructor using a context for this builder * * @throws LightException */ public NavigationBuilder(Activity activity) throws LightException { if (activity instanceof LightNavigationActivity) { mFragmentHolderList = new ArrayList<FragmentHolder>(); mTabNavigation = (LightNavigationActivity) activity; } else { throw new LightException("Fragment activity must be '" + this.getClass().getName() + "' type."); } } /** * Add a new tab in container * * @param tabName will be displayed on tab * @param fragmentClass fragment inside tab * @param drawableId resource id for add an icon for tab */ public NavigationBuilder addTab(String tabName, LightFragment fragmentClass, int drawableId) { mFragmentHolderList.add(new FragmentHolder(tabName, fragmentClass)); mTabNavigation.addTab(tabName, fragmentClass, drawableId); return this; } public void build() { Collections.reverse(mFragmentHolderList); for (int i = 0; i < mFragmentHolderList.size(); i++) { mTabNavigation.pushFragment(mFragmentHolderList.get(i).getKey(), mFragmentHolderList.get(i).getValue(), false, true, null); if (i == mFragmentHolderList.size() - 1) { mTabNavigation.mCurrentTab = mFragmentHolderList.get(i).getKey(); } } mTabNavigation.mTabHost.setOnTabChangedListener(mTabChangeListener); mFragmentHolderList = null; } private TabHost.OnTabChangeListener mTabChangeListener = new TabHost.OnTabChangeListener() { @Override public void onTabChanged(String tabId) { mTabNavigation.mCurrentTab = tabId; mTabNavigation.pushFragment(tabId, mTabNavigation.mStacks.get(tabId).lastElement(), false, false, null); } }; } }
apache-2.0
esileme/phonemanage
PhoneManager/app/src/androidTest/java/com/android/yl/phonemanager/ApplicationTest.java
1069
package com.android.yl.phonemanager; import android.content.Context; import android.test.AndroidTestCase; import com.android.yl.phonemanager.db.dao.BlackNumberDao; import com.android.yl.phonemanager.db.dao.BlackNumberOpenHelper; import java.util.Random; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends AndroidTestCase { public Context mContext; @Override protected void setUp() throws Exception { this.mContext = getContext(); super.setUp(); } public void testCreateDb() { BlackNumberOpenHelper helper = new BlackNumberOpenHelper(getContext()); helper.getWritableDatabase(); } public void testAdd() { BlackNumberDao dao = new BlackNumberDao(mContext); Random random = new Random(); for (int i = 0; i < 200; i++) { Long number = 13300000000l + i; dao.add(number + "", String.valueOf(random.nextInt(3) + 1)); } } }
apache-2.0
EBIvariation/variation-commons
variation-commons-core/src/main/java/uk/ac/ebi/eva/commons/core/models/AbstractVariant.java
10299
/* * Copyright 2017 EMBL - European Bioinformatics Institute * * 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 uk.ac.ebi.eva.commons.core.models; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; /** * Basic abstract implementation of AbstractVariant model with all the common elements for the current models. */ public abstract class AbstractVariant implements IVariant { public static final int SV_THRESHOLD = 50; protected static final String VARIANT_START_COORDINATE_CANNOT_BE_NEGATIVE = "Variant start coordinate cannot be negative"; protected static final String VARIANT_END_COORDINATE_CANNOT_BE_NEGATIVE = "Variant end coordinate cannot be negative"; protected static final String END_POSITION_MUST_BE_EQUAL_OR_GREATER_THAN_THE_START_POSITION = "End position must be equal or greater than the start position"; /** * Chromosome where the genomic variation occurred. */ private final String chromosome; /** * Position where the genomic variation starts. * <ul> * <li>SNVs have the same start and end position</li> * <li>Insertions start in the position after the last unmodified nucleotide: if the first * nucleotide is inserted between positions 6 and 7, the start is position 7</li> * <li>Deletions start in the first previously present position: if the first * deleted nucleotide is in position 6, the start is position 6</li> * </ul> */ private long start; /** * Position where the genomic variation ends. * <ul> * <li>SNVs have the same start and end positions</li> * <li>Insertions end in the last inserted position: if 4 nucleotides are inserted between positions 5 and 6, * the end is position 9</li> * <li>Deletions ends in the last previously present position: if the last * deleted nucleotide is in position 9, the end is position 9</li> * </ul> */ private long end; /** * Reference allele. * * Should be normalized, i.e. no common bases should be present in both reference and alternate. * Also, empty alleles are allowed. */ private String reference; /** * Alternate allele. * * Should be normalized, i.e. no common bases should be present in both reference and alternate. * Also, empty alleles are allowed. */ private String alternate; /** * Among all the identifiers used for this genomic variation, the one that is considered the most relevant. */ private String mainId; /** * Set of identifiers used for this genomic variation. */ private final Set<String> ids; /** * Set of identifiers used for this genomic variation, according to dbsnp. * @deprecated this field is temporary for the dbsnp import, use getIds or getMainId instead */ @Deprecated private final Set<String> dbsnpIds; /** * Unique identifier following the HGVS nomenclature. */ private final Map<String, Set<String>> hgvs; protected AbstractVariant() { this.chromosome = null; this.start = -1; this.end = -1; this.reference = null; this.alternate = null; this.mainId = null; this.ids = new HashSet<>(); this.dbsnpIds = new HashSet<>(); this.hgvs = new HashMap<>(); } public AbstractVariant(String chromosome, long start, long end, String reference, String alternate) { this(chromosome, start, end, reference, alternate, null); } public AbstractVariant(String chromosome, long start, long end, String reference, String alternate, String mainId) { if (chromosome == null || chromosome.trim().equals("")) { throw new IllegalArgumentException("Chromosome name cannot be empty"); } this.chromosome = chromosome; this.setCoordinates(start, end); this.setReference(reference); this.setAlternate(alternate); this.mainId = mainId; this.ids = new HashSet<>(); this.dbsnpIds = new HashSet<>(); this.hgvs = new HashMap<>(); if (getType() == VariantType.SNV) { // Generate HGVS code only for SNVs Set<String> hgvsCodes = new HashSet<>(); hgvsCodes.add(chromosome + ":g." + start + reference + ">" + alternate); this.hgvs.put("genomic", hgvsCodes); } } public int getLength() { return Math.max(this.reference.length(), this.alternate.length()); } public VariantType getType() { if (this.alternate.equals(".")) { return VariantType.NO_ALTERNATE; } else if (this.reference.startsWith("<") && this.reference.endsWith(">") || this.alternate.startsWith("<") && this.alternate.endsWith(">")) { return VariantType.SEQUENCE_ALTERATION; } else if (!reference.equals(".") && reference.length() == alternate.length()) { if (getLength() > 1) { return VariantType.MNV; } else { return VariantType.SNV; } } else if (getLength() <= SV_THRESHOLD) { if (reference.isEmpty()) { return VariantType.INS; } else if (alternate.isEmpty()) { return VariantType.DEL; } else { /* * 2 possibilities for being an INDEL: * - The REF allele is . but the ALT is not * - The REF field length is different than the ALT field length and there are no context bases ("no * context bases" can be detected by checking if one of the alleles is empty) */ return VariantType.INDEL; } } else { return VariantType.SV; } } public String getChromosome() { return chromosome; } public long getStart() { return start; } public long getEnd() { return end; } public String getReference() { return reference; } public String getAlternate() { return alternate; } public String getMainId() { return mainId; } private void setReference(String reference) { this.reference = (reference != null) ? reference : ""; } private void setAlternate(String alternate) { this.alternate = (alternate != null) ? alternate : ""; } private void setCoordinates(long start, long end) { if (start < 0) { throw new IllegalArgumentException(VARIANT_START_COORDINATE_CANNOT_BE_NEGATIVE); } if (end < 0) { throw new IllegalArgumentException(VARIANT_END_COORDINATE_CANNOT_BE_NEGATIVE); } if (end < start) { throw new IllegalArgumentException(END_POSITION_MUST_BE_EQUAL_OR_GREATER_THAN_THE_START_POSITION); } this.start = start; this.end = end; } public void setMainId(String mainId) { this.mainId = mainId; } public void addId(String id) { this.ids.add(id); } public void setIds(Set<String> ids) { this.ids.clear(); this.ids.addAll(ids); } public Set<String> getIds() { return Collections.unmodifiableSet(ids); } public void addDbsnpId(String id) { this.dbsnpIds.add(id); } public void setDbsnpIds(Set<String> ids) { this.dbsnpIds.clear(); this.dbsnpIds.addAll(ids); } public Set<String> getDbsnpIds() { return Collections.unmodifiableSet(dbsnpIds); } public boolean addHgvs(String type, String value) { Set<String> listByType = hgvs.get(type); if (listByType == null) { listByType = new HashSet<>(); } return listByType.add(value); } public Map<String, Set<String>> getHgvs() { return Collections.unmodifiableMap(hgvs); } public void renormalize(long newStart, long newEnd, String newReference, String newAlternate) { this.setCoordinates(newStart, newEnd); this.setReference(newReference); this.setAlternate(newAlternate); } @Override public String toString() { return "AbstractVariant{" + "chromosome='" + chromosome + '\'' + ", position=" + start + "-" + end + ", reference='" + reference + '\'' + ", alternate='" + alternate + '\'' + ", ids='" + ids + '\'' + '}'; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final AbstractVariant other = (AbstractVariant) obj; if (!Objects.equals(this.chromosome, other.chromosome)) { return false; } if (this.start != other.start) { return false; } if (this.end != other.end) { return false; } if (!Objects.equals(this.reference, other.reference)) { return false; } if (!Objects.equals(this.alternate, other.alternate)) { return false; } return true; } @Override public int hashCode() { int hash = 5; hash = 37 * hash + Objects.hashCode(this.chromosome); hash = 37 * hash + (int) (start ^ (start >>> 32)); hash = 37 * hash + (int) (end ^ (end >>> 32)); hash = 37 * hash + Objects.hashCode(this.reference); hash = 37 * hash + Objects.hashCode(this.alternate); return hash; } }
apache-2.0
zuesgooogle/HappyCard
card-server/src/main/java/com/s4game/server/bus/bag/export/response/IBagDecrMallCheckResponse.java
494
package com.s4game.server.bus.bag.export.response; import java.util.Map; import com.s4game.server.gamerule.money.MoneyType; /** * * @Author zeusgooogle@gmail.com * @sine 2015年8月11日 下午3:08:57 * */ public interface IBagDecrMallCheckResponse { public Map<String, Integer> getDecrMallGoodsMap(); public Map<String, Integer> getMallBuyGoodsMap(); public Map<MoneyType, Integer> getMallDecrMoney(); public Integer getError(); public boolean isSuccess(); }
apache-2.0
tsoy-petr/chapter_002
_7_1/src/main/java/ru/bildovich/start/IdExeption.java
205
package ru.bildovich.start; /** * Created by mac on 26.03.17. * Class */ public class IdExeption extends NumberFormatException { public IdExeption(String message) { super(message); } }
apache-2.0
livingvirus/jphp
jphp-swing-ext/src/org/develnext/jphp/swing/loader/support/BaseTag.java
1305
package org.develnext.jphp.swing.loader.support; import org.develnext.jphp.swing.loader.UIReader; import org.w3c.dom.Node; import java.awt.*; abstract public class BaseTag<T extends Component> { abstract public T create(ElementItem element, UIReader uiReader); public void read(ElementItem element, T component, Node node, UIReader uiReader) { } public void afterRead(ElementItem element, T component, Node node, UIReader uiReader) { } public void onReadAttribute(ElementItem element, String property, Value value, T component, UIReader uiReader) { } public void addChildren(T component, Component child) { if (component instanceof Container) ((Container) component).add(child); } public void addUnknown(T component, Node node, UIReader uiReader) { } public boolean isAllowsChildren() { return true; } public boolean isNeedRegister() { return true; } public Component getContentPane(T component) { return component; } public Component applyProperty(String property, T component) { return component; } protected static boolean isCDataContent(Node node) { return node.getFirstChild() != null && node.getFirstChild().getNodeType() == Node.CDATA_SECTION_NODE; } }
apache-2.0
apache/hadoop-mapreduce
src/contrib/sqoop/src/java/org/apache/hadoop/sqoop/util/DirectImportUtils.java
3357
/** * 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.sqoop.util; import java.io.IOException; import java.io.File; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.sqoop.ImportOptions; import org.apache.hadoop.sqoop.io.SplittingOutputStream; import org.apache.hadoop.sqoop.io.SplittableBufferedWriter; import org.apache.hadoop.util.Shell; /** * Utility methods that are common to various the direct import managers. */ public final class DirectImportUtils { public static final Log LOG = LogFactory.getLog( DirectImportUtils.class.getName()); private DirectImportUtils() { } /** * Executes chmod on the specified file, passing in the mode string 'modstr' * which may be e.g. "a+x" or "0600", etc. * @throws IOException if chmod failed. */ public static void setFilePermissions(File file, String modstr) throws IOException { // Set this file to be 0600. Java doesn't have a built-in mechanism for this // so we need to go out to the shell to execute chmod. try { Shell.execCommand("chmod", modstr, file.toString()); } catch (IOException ioe) { // Shell.execCommand will throw IOException on exit code != 0. LOG.error("Could not chmod " + modstr + " " + file.toString()); throw new IOException("Could not ensure password file security.", ioe); } } /** * Open a file in HDFS for write to hold the data associated with a table. * Creates any necessary directories, and returns the OutputStream to write * to. The caller is responsible for calling the close() method on the * returned stream. */ public static SplittableBufferedWriter createHdfsSink(Configuration conf, ImportOptions options, String tableName) throws IOException { FileSystem fs = FileSystem.get(conf); String warehouseDir = options.getWarehouseDir(); Path destDir = null; if (null != warehouseDir) { destDir = new Path(new Path(warehouseDir), tableName); } else { destDir = new Path(tableName); } LOG.debug("Writing to filesystem: " + conf.get("fs.default.name")); LOG.debug("Creating destination directory " + destDir); fs.mkdirs(destDir); // This Writer will be closed by the caller. return new SplittableBufferedWriter( new SplittingOutputStream(conf, destDir, "data-", options.getDirectSplitSize(), options.shouldUseCompression())); } }
apache-2.0
gavin2lee/incubator
mnis/core/src/main/java/com/lachesis/mnis/core/inspection/entity/InspectionOrder.java
5959
package com.lachesis.mnis.core.inspection.entity; import java.util.Date; public class InspectionOrder { private String inspecOrderId; //预约检查流水号 private String orderId; //医嘱ID private String inHospNo; private String patientId; private String deptNo; private String patientName; private String sex; private String bedNo; private String diseaseinfo; //病史 private String itemNote; //检查部位 private boolean isCritical; //是否危重 private boolean isEmc; //是否急诊 private Date inspectionOrderDate; //预约开始时间 private String doctorId; //开嘱医生 private String orderDate; //医嘱开立时间 private String orderType; //医嘱类型 private String inspec_code; //检查项目代码 private String inspec_name; //检查项目名称 private float qty; //数量 private String freq; //频次 private String unit; //单位 private String unitPrice; //单价 private float cose; //金额 private String operatorId; //操作人 private String execDeptNo; //执行科室 private String operateDate; //执行时间 private String dcId; //作废人 private boolean isExec; //是否已执行 private String execManId; //执行人 private String execDate; //执行时间 private boolean isCheck; //是否已确定 private String checkManId; //确定人 private String checkDate; //确定时间 private Date endDate; //预约结束时间 private String state; //状态 public String getInspecOrderId() { return inspecOrderId; } public void setInspecOrderId(String inspecOrderId) { this.inspecOrderId = inspecOrderId; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public String getInHospNo() { return inHospNo; } public void setInHospNo(String inHospNo) { this.inHospNo = inHospNo; } public String getPatientId() { return patientId; } public void setPatientId(String patientId) { this.patientId = patientId; } public String getDeptNo() { return deptNo; } public void setDeptNo(String deptNo) { this.deptNo = deptNo; } public String getPatientName() { return patientName; } public void setPatientName(String patientName) { this.patientName = patientName; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getBedNo() { return bedNo; } public void setBedNo(String bedNo) { this.bedNo = bedNo; } public String getDiseaseinfo() { return diseaseinfo; } public void setDiseaseinfo(String diseaseinfo) { this.diseaseinfo = diseaseinfo; } public String getItemNote() { return itemNote; } public void setItemNote(String itemNote) { this.itemNote = itemNote; } public boolean isCritical() { return isCritical; } public void setCritical(boolean isCritical) { this.isCritical = isCritical; } public boolean isEmc() { return isEmc; } public void setEmc(boolean isEmc) { this.isEmc = isEmc; } public Date getInspectionOrderDate() { return inspectionOrderDate; } public void setInspectionOrderDate(Date inspectionOrderDate) { this.inspectionOrderDate = inspectionOrderDate; } public String getDoctorId() { return doctorId; } public void setDoctorId(String doctorId) { this.doctorId = doctorId; } public String getOrderDate() { return orderDate; } public void setOrderDate(String orderDate) { this.orderDate = orderDate; } public String getOrderType() { return orderType; } public void setOrderType(String orderType) { this.orderType = orderType; } public String getInspec_code() { return inspec_code; } public void setInspec_code(String inspec_code) { this.inspec_code = inspec_code; } public String getInspec_name() { return inspec_name; } public void setInspec_name(String inspec_name) { this.inspec_name = inspec_name; } public float getQty() { return qty; } public void setQty(float qty) { this.qty = qty; } public String getFreq() { return freq; } public void setFreq(String freq) { this.freq = freq; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public String getUnitPrice() { return unitPrice; } public void setUnitPrice(String unitPrice) { this.unitPrice = unitPrice; } public float getCose() { return cose; } public void setCose(float cose) { this.cose = cose; } public String getOperatorId() { return operatorId; } public void setOperatorId(String operatorId) { this.operatorId = operatorId; } public String getExecDeptNo() { return execDeptNo; } public void setExecDeptNo(String execDeptNo) { this.execDeptNo = execDeptNo; } public String getOperateDate() { return operateDate; } public void setOperateDate(String operateDate) { this.operateDate = operateDate; } public String getDcId() { return dcId; } public void setDcId(String dcId) { this.dcId = dcId; } public boolean isExec() { return isExec; } public void setExec(boolean isExec) { this.isExec = isExec; } public String getExecManId() { return execManId; } public void setExecManId(String execManId) { this.execManId = execManId; } public String getExecDate() { return execDate; } public void setExecDate(String execDate) { this.execDate = execDate; } public boolean isCheck() { return isCheck; } public void setCheck(boolean isCheck) { this.isCheck = isCheck; } public String getCheckManId() { return checkManId; } public void setCheckManId(String checkManId) { this.checkManId = checkManId; } public String getCheckDate() { return checkDate; } public void setCheckDate(String checkDate) { this.checkDate = checkDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
apache-2.0
quarkusio/quarkus
independent-projects/bootstrap/app-model/src/main/java/io/quarkus/paths/ArchivePathTree.java
9084
package io.quarkus.paths; import io.quarkus.fs.util.ZipUtils; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Objects; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Consumer; import java.util.function.Function; import java.util.jar.Manifest; public class ArchivePathTree extends PathTreeWithManifest implements PathTree { private final Path archive; private final PathFilter pathFilter; public ArchivePathTree(Path archive) { this(archive, null); } ArchivePathTree(Path archive, PathFilter pathFilter) { this(archive, pathFilter, true); } ArchivePathTree(Path archive, PathFilter pathFilter, boolean manifestEnabled) { super(manifestEnabled); this.archive = archive; this.pathFilter = pathFilter; } @Override public Collection<Path> getRoots() { return Collections.singletonList(archive); } @Override public void walk(PathVisitor visitor) { try (FileSystem fs = openFs()) { final Path dir = fs.getPath("/"); PathTreeVisit.walk(archive, dir, pathFilter, getMultiReleaseMapping(), visitor); } catch (IOException e) { throw new UncheckedIOException("Failed to read " + archive, e); } } private void ensureResourcePath(String path) { DirectoryPathTree.ensureResourcePath(archive.getFileSystem(), path); } @Override protected <T> T apply(String relativePath, Function<PathVisit, T> func, boolean manifestEnabled) { ensureResourcePath(relativePath); if (!PathFilter.isVisible(pathFilter, relativePath)) { return func.apply(null); } if (manifestEnabled) { relativePath = toMultiReleaseRelativePath(relativePath); } try (FileSystem fs = openFs()) { for (Path root : fs.getRootDirectories()) { final Path path = root.resolve(relativePath); if (!Files.exists(path)) { continue; } return PathTreeVisit.process(archive, root, path, pathFilter, func); } } catch (IOException e) { throw new UncheckedIOException("Failed to read " + archive, e); } return func.apply(null); } @Override public void accept(String relativePath, Consumer<PathVisit> consumer) { ensureResourcePath(relativePath); if (!PathFilter.isVisible(pathFilter, relativePath)) { consumer.accept(null); return; } if (manifestEnabled) { relativePath = toMultiReleaseRelativePath(relativePath); } try (FileSystem fs = openFs()) { for (Path root : fs.getRootDirectories()) { final Path path = root.resolve(relativePath); if (!Files.exists(path)) { continue; } PathTreeVisit.consume(archive, root, path, pathFilter, consumer); return; } } catch (IOException e) { throw new UncheckedIOException("Failed to read " + archive, e); } consumer.accept(null); } @Override public boolean contains(String relativePath) { ensureResourcePath(relativePath); if (!PathFilter.isVisible(pathFilter, relativePath)) { return false; } if (manifestEnabled) { relativePath = toMultiReleaseRelativePath(relativePath); } try (FileSystem fs = openFs()) { for (Path root : fs.getRootDirectories()) { final Path path = root.resolve(relativePath); if (Files.exists(path)) { return true; } } } catch (IOException e) { throw new UncheckedIOException("Failed to read " + archive, e); } return false; } private FileSystem openFs() throws IOException { return ZipUtils.newFileSystem(archive); } @Override public OpenPathTree open() { try { return new OpenArchivePathTree(openFs()); } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public int hashCode() { return Objects.hash(archive, pathFilter, manifestEnabled); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ArchivePathTree other = (ArchivePathTree) obj; return Objects.equals(archive, other.archive) && Objects.equals(pathFilter, other.pathFilter) && manifestEnabled == other.manifestEnabled; } private class OpenArchivePathTree extends DirectoryPathTree { private final FileSystem fs; private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private OpenArchivePathTree(FileSystem fs) { super(fs.getPath("/"), pathFilter, ArchivePathTree.this); this.fs = fs; } @Override protected void initManifest(Manifest m) { super.initManifest(m); ArchivePathTree.this.manifestReadLock().lock(); try { if (!ArchivePathTree.this.manifestInitialized) { ArchivePathTree.this.manifestReadLock().unlock(); ArchivePathTree.this.manifestWriteLock().lock(); ArchivePathTree.this.initManifest(m); ArchivePathTree.this.manifestReadLock().lock(); ArchivePathTree.this.manifestWriteLock().unlock(); } } finally { ArchivePathTree.this.manifestReadLock().unlock(); } } @Override protected void initMultiReleaseMapping(Map<String, String> mrMapping) { super.initMultiReleaseMapping(mrMapping); if (ArchivePathTree.this.multiReleaseMapping == null) { ArchivePathTree.this.initMultiReleaseMapping(mrMapping); } } @Override public boolean isOpen() { return fs.isOpen(); } @Override protected <T> T apply(String relativePath, Function<PathVisit, T> func, boolean manifestEnabled) { lock.readLock().lock(); try { ensureOpen(); return super.apply(relativePath, func, manifestEnabled); } finally { lock.readLock().unlock(); } } @Override public void accept(String relativePath, Consumer<PathVisit> consumer) { lock.readLock().lock(); try { ensureOpen(); super.accept(relativePath, consumer); } finally { lock.readLock().unlock(); } } @Override public void walk(PathVisitor visitor) { lock.readLock().lock(); try { ensureOpen(); super.walk(visitor); } finally { lock.readLock().unlock(); } } @Override public boolean contains(String relativePath) { lock.readLock().lock(); try { ensureOpen(); return super.contains(relativePath); } finally { lock.readLock().unlock(); } } @Override public Path getPath(String relativePath) { lock.readLock().lock(); try { ensureOpen(); return super.getPath(relativePath); } finally { lock.readLock().unlock(); } } private void ensureOpen() { if (isOpen()) { return; } throw new RuntimeException("Failed to access " + ArchivePathTree.this.getRoots() + " because the FileSystem has been closed"); } @Override public void close() throws IOException { Throwable t = null; lock.writeLock().lock(); try { super.close(); } catch (Throwable e) { t = e; throw e; } finally { try { fs.close(); } catch (IOException e) { if (t != null) { e.addSuppressed(t); } throw e; } lock.writeLock().unlock(); } } @Override public PathTree getOriginalTree() { return ArchivePathTree.this; } } }
apache-2.0
firebase/firebase-admin-java
src/main/java/com/google/firebase/internal/package-info.java
651
/* * Copyright 2017 Google 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. */ /** * @hide */ package com.google.firebase.internal;
apache-2.0
xiaokuangkuang/kuangjingxiangmu
flink-yarn/src/main/java/org/apache/flink/yarn/AbstractYarnClusterDescriptor.java
64367
/* * 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.flink.yarn; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.client.deployment.ClusterDeploymentException; import org.apache.flink.client.deployment.ClusterDescriptor; import org.apache.flink.client.deployment.ClusterRetrieveException; import org.apache.flink.client.deployment.ClusterSpecification; import org.apache.flink.client.program.ClusterClient; import org.apache.flink.configuration.ConfigConstants; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.CoreOptions; import org.apache.flink.configuration.HighAvailabilityOptions; import org.apache.flink.configuration.IllegalConfigurationException; import org.apache.flink.configuration.JobManagerOptions; import org.apache.flink.configuration.ResourceManagerOptions; import org.apache.flink.configuration.RestOptions; import org.apache.flink.configuration.SecurityOptions; import org.apache.flink.configuration.TaskManagerOptions; import org.apache.flink.runtime.akka.AkkaUtils; import org.apache.flink.runtime.clusterframework.BootstrapTools; import org.apache.flink.runtime.clusterframework.ContaineredTaskManagerParameters; import org.apache.flink.runtime.entrypoint.ClusterEntrypoint; import org.apache.flink.runtime.jobgraph.JobGraph; import org.apache.flink.runtime.jobmanager.HighAvailabilityMode; import org.apache.flink.runtime.taskexecutor.TaskManagerServices; import org.apache.flink.util.FlinkException; import org.apache.flink.util.Preconditions; import org.apache.flink.util.ShutdownHookUtil; import org.apache.flink.yarn.configuration.YarnConfigOptions; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsAction; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.ApplicationConstants; import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationResponse; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.LocalResource; import org.apache.hadoop.yarn.api.records.NodeReport; import org.apache.hadoop.yarn.api.records.NodeState; import org.apache.hadoop.yarn.api.records.QueueInfo; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.api.records.YarnClusterMetrics; import org.apache.hadoop.yarn.client.api.YarnClient; import org.apache.hadoop.yarn.client.api.YarnClientApplication; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.util.Records; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import static org.apache.flink.configuration.ConfigConstants.ENV_FLINK_LIB_DIR; import static org.apache.flink.yarn.cli.FlinkYarnSessionCli.CONFIG_FILE_LOG4J_NAME; import static org.apache.flink.yarn.cli.FlinkYarnSessionCli.CONFIG_FILE_LOGBACK_NAME; import static org.apache.flink.yarn.cli.FlinkYarnSessionCli.getDynamicProperties; /** * The descriptor with deployment information for spawning or resuming a {@link YarnClusterClient}. */ public abstract class AbstractYarnClusterDescriptor implements ClusterDescriptor<ApplicationId> { private static final Logger LOG = LoggerFactory.getLogger(AbstractYarnClusterDescriptor.class); private final YarnConfiguration yarnConfiguration; private final YarnClient yarnClient; /** True if the descriptor must not shut down the YarnClient. */ private final boolean sharedYarnClient; private String yarnQueue; private String configurationDirectory; private Path flinkJarPath; private String dynamicPropertiesEncoded; /** Lazily initialized list of files to ship. */ protected List<File> shipFiles = new LinkedList<>(); private final Configuration flinkConfiguration; private boolean detached; private String customName; private String zookeeperNamespace; private String nodeLabel; /** Optional Jar file to include in the system class loader of all application nodes * (for per-job submission). */ private final Set<File> userJarFiles = new HashSet<>(); private YarnConfigOptions.UserJarInclusion userJarInclusion; public AbstractYarnClusterDescriptor( Configuration flinkConfiguration, YarnConfiguration yarnConfiguration, String configurationDirectory, YarnClient yarnClient, boolean sharedYarnClient) { this.yarnConfiguration = Preconditions.checkNotNull(yarnConfiguration); // for unit tests only if (System.getenv("IN_TESTS") != null) { try { yarnConfiguration.addResource(new File(System.getenv("YARN_CONF_DIR"), "yarn-site.xml").toURI().toURL()); } catch (Throwable t) { throw new RuntimeException("Error", t); } } this.yarnClient = Preconditions.checkNotNull(yarnClient); this.sharedYarnClient = sharedYarnClient; this.flinkConfiguration = Preconditions.checkNotNull(flinkConfiguration); userJarInclusion = getUserJarInclusionMode(flinkConfiguration); this.configurationDirectory = Preconditions.checkNotNull(configurationDirectory); } public YarnClient getYarnClient() { return yarnClient; } /** * The class to start the application master with. This class runs the main * method in case of session cluster. */ protected abstract String getYarnSessionClusterEntrypoint(); /** * The class to start the application master with. This class runs the main * method in case of the job cluster. */ protected abstract String getYarnJobClusterEntrypoint(); public Configuration getFlinkConfiguration() { return flinkConfiguration; } public void setQueue(String queue) { this.yarnQueue = queue; } public void setLocalJarPath(Path localJarPath) { if (!localJarPath.toString().endsWith("jar")) { throw new IllegalArgumentException("The passed jar path ('" + localJarPath + "') does not end with the 'jar' extension"); } this.flinkJarPath = localJarPath; } /** * Adds the given files to the list of files to ship. * * <p>Note that any file matching "<tt>flink-dist*.jar</tt>" will be excluded from the upload by * {@link #uploadAndRegisterFiles(Collection, FileSystem, Path, ApplicationId, List, Map, StringBuilder)} * since we upload the Flink uber jar ourselves and do not need to deploy it multiple times. * * @param shipFiles files to ship */ public void addShipFiles(List<File> shipFiles) { this.shipFiles.addAll(shipFiles); } public void setDynamicPropertiesEncoded(String dynamicPropertiesEncoded) { this.dynamicPropertiesEncoded = dynamicPropertiesEncoded; } /** * Returns true if the descriptor has the job jars to include in the classpath. */ public boolean hasUserJarFiles(List<URL> requiredJarFiles) { if (userJarInclusion == YarnConfigOptions.UserJarInclusion.DISABLED) { return false; } if (userJarFiles.size() != requiredJarFiles.size()) { return false; } try { for (URL jarFile : requiredJarFiles) { if (!userJarFiles.contains(new File(jarFile.toURI()))) { return false; } } } catch (URISyntaxException e) { return false; } return true; } /** * Sets the user jar which is included in the system classloader of all nodes. */ public void setProvidedUserJarFiles(List<URL> userJarFiles) { for (URL jarFile : userJarFiles) { try { this.userJarFiles.add(new File(jarFile.toURI())); } catch (URISyntaxException e) { throw new IllegalArgumentException("Couldn't add local user jar: " + jarFile + " Currently only file:/// URLs are supported."); } } } public String getDynamicPropertiesEncoded() { return this.dynamicPropertiesEncoded; } private void isReadyForDeployment(ClusterSpecification clusterSpecification) throws YarnDeploymentException { if (clusterSpecification.getNumberTaskManagers() <= 0) { throw new YarnDeploymentException("Taskmanager count must be positive"); } if (this.flinkJarPath == null) { throw new YarnDeploymentException("The Flink jar path is null"); } if (this.configurationDirectory == null) { throw new YarnDeploymentException("Configuration directory not set"); } if (this.flinkConfiguration == null) { throw new YarnDeploymentException("Flink configuration object has not been set"); } // Check if we don't exceed YARN's maximum virtual cores. // Fetch numYarnMaxVcores from all the RUNNING nodes via yarnClient final int numYarnMaxVcores; try { numYarnMaxVcores = yarnClient.getNodeReports(NodeState.RUNNING) .stream() .mapToInt(report -> report.getCapability().getVirtualCores()) .max() .orElse(0); } catch (Exception e) { throw new YarnDeploymentException("Couldn't get cluster description, please check on the YarnConfiguration", e); } int configuredVcores = flinkConfiguration.getInteger(YarnConfigOptions.VCORES, clusterSpecification.getSlotsPerTaskManager()); // don't configure more than the maximum configured number of vcores if (configuredVcores > numYarnMaxVcores) { throw new IllegalConfigurationException( String.format("The number of requested virtual cores per node %d" + " exceeds the maximum number of virtual cores %d available in the Yarn Cluster." + " Please note that the number of virtual cores is set to the number of task slots by default" + " unless configured in the Flink config with '%s.'", configuredVcores, numYarnMaxVcores, YarnConfigOptions.VCORES.key())); } // check if required Hadoop environment variables are set. If not, warn user if (System.getenv("HADOOP_CONF_DIR") == null && System.getenv("YARN_CONF_DIR") == null) { LOG.warn("Neither the HADOOP_CONF_DIR nor the YARN_CONF_DIR environment variable is set. " + "The Flink YARN Client needs one of these to be set to properly load the Hadoop " + "configuration for accessing YARN."); } } private static boolean allocateResource(int[] nodeManagers, int toAllocate) { for (int i = 0; i < nodeManagers.length; i++) { if (nodeManagers[i] >= toAllocate) { nodeManagers[i] -= toAllocate; return true; } } return false; } /** * @deprecated The cluster descriptor should not know about this option. */ @Deprecated public void setDetachedMode(boolean detachedMode) { this.detached = detachedMode; } /** * @deprecated The cluster descriptor should not know about this option. */ @Deprecated public boolean isDetachedMode() { return detached; } public String getZookeeperNamespace() { return zookeeperNamespace; } public void setZookeeperNamespace(String zookeeperNamespace) { this.zookeeperNamespace = zookeeperNamespace; } public String getNodeLabel() { return nodeLabel; } public void setNodeLabel(String nodeLabel) { this.nodeLabel = nodeLabel; } // ------------------------------------------------------------- // Lifecycle management // ------------------------------------------------------------- @Override public void close() { if (!sharedYarnClient) { yarnClient.stop(); } } // ------------------------------------------------------------- // ClusterClient overrides // ------------------------------------------------------------- @Override public ClusterClient<ApplicationId> retrieve(ApplicationId applicationId) throws ClusterRetrieveException { try { // check if required Hadoop environment variables are set. If not, warn user if (System.getenv("HADOOP_CONF_DIR") == null && System.getenv("YARN_CONF_DIR") == null) { LOG.warn("Neither the HADOOP_CONF_DIR nor the YARN_CONF_DIR environment variable is set." + "The Flink YARN Client needs one of these to be set to properly load the Hadoop " + "configuration for accessing YARN."); } final ApplicationReport appReport = yarnClient.getApplicationReport(applicationId); if (appReport.getFinalApplicationStatus() != FinalApplicationStatus.UNDEFINED) { // Flink cluster is not running anymore LOG.error("The application {} doesn't run anymore. It has previously completed with final status: {}", applicationId, appReport.getFinalApplicationStatus()); throw new RuntimeException("The Yarn application " + applicationId + " doesn't run anymore."); } final String host = appReport.getHost(); final int rpcPort = appReport.getRpcPort(); LOG.info("Found application JobManager host name '{}' and port '{}' from supplied application id '{}'", host, rpcPort, applicationId); flinkConfiguration.setString(JobManagerOptions.ADDRESS, host); flinkConfiguration.setInteger(JobManagerOptions.PORT, rpcPort); flinkConfiguration.setString(RestOptions.ADDRESS, host); flinkConfiguration.setInteger(RestOptions.PORT, rpcPort); return createYarnClusterClient( this, -1, // we don't know the number of task managers of a started Flink cluster -1, // we don't know how many slots each task manager has for a started Flink cluster appReport, flinkConfiguration, false); } catch (Exception e) { throw new ClusterRetrieveException("Couldn't retrieve Yarn cluster", e); } } @Override public ClusterClient<ApplicationId> deploySessionCluster(ClusterSpecification clusterSpecification) throws ClusterDeploymentException { try { return deployInternal( clusterSpecification, "Flink session cluster", getYarnSessionClusterEntrypoint(), null, false); } catch (Exception e) { throw new ClusterDeploymentException("Couldn't deploy Yarn session cluster", e); } } @Override public void killCluster(ApplicationId applicationId) throws FlinkException { try { yarnClient.killApplication(applicationId); Utils.deleteApplicationFiles(Collections.singletonMap( YarnConfigKeys.FLINK_YARN_FILES, getYarnFilesDir(applicationId).toUri().toString())); } catch (YarnException | IOException e) { throw new FlinkException("Could not kill the Yarn Flink cluster with id " + applicationId + '.', e); } } /** * Method to validate cluster specification before deploy it, it will throw * an {@link FlinkException} if the {@link ClusterSpecification} is invalid. * * @param clusterSpecification cluster specification to check against the configuration of the * AbstractYarnClusterDescriptor * @throws FlinkException if the cluster cannot be started with the provided {@link ClusterSpecification} */ private void validateClusterSpecification(ClusterSpecification clusterSpecification) throws FlinkException { try { final long taskManagerMemorySize = clusterSpecification.getTaskManagerMemoryMB(); // We do the validation by calling the calculation methods here // Internally these methods will check whether the cluster can be started with the provided // ClusterSpecification and the configured memory requirements final long cutoff = ContaineredTaskManagerParameters.calculateCutoffMB(flinkConfiguration, taskManagerMemorySize); TaskManagerServices.calculateHeapSizeMB(taskManagerMemorySize - cutoff, flinkConfiguration); } catch (IllegalArgumentException iae) { throw new FlinkException("Cannot fulfill the minimum memory requirements with the provided " + "cluster specification. Please increase the memory of the cluster.", iae); } } /** * This method will block until the ApplicationMaster/JobManager have been deployed on YARN. * * @param clusterSpecification Initial cluster specification for the Flink cluster to be deployed * @param applicationName name of the Yarn application to start * @param yarnClusterEntrypoint Class name of the Yarn cluster entry point. * @param jobGraph A job graph which is deployed with the Flink cluster, {@code null} if none * @param detached True if the cluster should be started in detached mode */ protected ClusterClient<ApplicationId> deployInternal( ClusterSpecification clusterSpecification, String applicationName, String yarnClusterEntrypoint, @Nullable JobGraph jobGraph, boolean detached) throws Exception { // ------------------ Check if configuration is valid -------------------- validateClusterSpecification(clusterSpecification); if (UserGroupInformation.isSecurityEnabled()) { // note: UGI::hasKerberosCredentials inaccurately reports false // for logins based on a keytab (fixed in Hadoop 2.6.1, see HADOOP-10786), // so we check only in ticket cache scenario. boolean useTicketCache = flinkConfiguration.getBoolean(SecurityOptions.KERBEROS_LOGIN_USETICKETCACHE); UserGroupInformation loginUser = UserGroupInformation.getCurrentUser(); if (loginUser.getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.KERBEROS && useTicketCache && !loginUser.hasKerberosCredentials()) { LOG.error("Hadoop security with Kerberos is enabled but the login user does not have Kerberos credentials"); throw new RuntimeException("Hadoop security with Kerberos is enabled but the login user " + "does not have Kerberos credentials"); } } isReadyForDeployment(clusterSpecification); // ------------------ Check if the specified queue exists -------------------- checkYarnQueues(yarnClient); // ------------------ Add dynamic properties to local flinkConfiguraton ------ Map<String, String> dynProperties = getDynamicProperties(dynamicPropertiesEncoded); for (Map.Entry<String, String> dynProperty : dynProperties.entrySet()) { flinkConfiguration.setString(dynProperty.getKey(), dynProperty.getValue()); } // ------------------ Check if the YARN ClusterClient has the requested resources -------------- // Create application via yarnClient final YarnClientApplication yarnApplication = yarnClient.createApplication(); final GetNewApplicationResponse appResponse = yarnApplication.getNewApplicationResponse(); Resource maxRes = appResponse.getMaximumResourceCapability(); final ClusterResourceDescription freeClusterMem; try { freeClusterMem = getCurrentFreeClusterResources(yarnClient); } catch (YarnException | IOException e) { failSessionDuringDeployment(yarnClient, yarnApplication); throw new YarnDeploymentException("Could not retrieve information about free cluster resources.", e); } final int yarnMinAllocationMB = yarnConfiguration.getInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 0); final ClusterSpecification validClusterSpecification; try { validClusterSpecification = validateClusterResources( clusterSpecification, yarnMinAllocationMB, maxRes, freeClusterMem); } catch (YarnDeploymentException yde) { failSessionDuringDeployment(yarnClient, yarnApplication); throw yde; } LOG.info("Cluster specification: {}", validClusterSpecification); final ClusterEntrypoint.ExecutionMode executionMode = detached ? ClusterEntrypoint.ExecutionMode.DETACHED : ClusterEntrypoint.ExecutionMode.NORMAL; flinkConfiguration.setString(ClusterEntrypoint.EXECUTION_MODE, executionMode.toString()); ApplicationReport report = startAppMaster( flinkConfiguration, applicationName, yarnClusterEntrypoint, jobGraph, yarnClient, yarnApplication, validClusterSpecification); String host = report.getHost(); int port = report.getRpcPort(); // Correctly initialize the Flink config flinkConfiguration.setString(JobManagerOptions.ADDRESS, host); flinkConfiguration.setInteger(JobManagerOptions.PORT, port); flinkConfiguration.setString(RestOptions.ADDRESS, host); flinkConfiguration.setInteger(RestOptions.PORT, port); // the Flink cluster is deployed in YARN. Represent cluster return createYarnClusterClient( this, validClusterSpecification.getNumberTaskManagers(), validClusterSpecification.getSlotsPerTaskManager(), report, flinkConfiguration, true); } protected ClusterSpecification validateClusterResources( ClusterSpecification clusterSpecification, int yarnMinAllocationMB, Resource maximumResourceCapability, ClusterResourceDescription freeClusterResources) throws YarnDeploymentException { int taskManagerCount = clusterSpecification.getNumberTaskManagers(); int jobManagerMemoryMb = clusterSpecification.getMasterMemoryMB(); int taskManagerMemoryMb = clusterSpecification.getTaskManagerMemoryMB(); if (jobManagerMemoryMb < yarnMinAllocationMB || taskManagerMemoryMb < yarnMinAllocationMB) { LOG.warn("The JobManager or TaskManager memory is below the smallest possible YARN Container size. " + "The value of 'yarn.scheduler.minimum-allocation-mb' is '" + yarnMinAllocationMB + "'. Please increase the memory size." + "YARN will allocate the smaller containers but the scheduler will account for the minimum-allocation-mb, maybe not all instances " + "you requested will start."); } // set the memory to minAllocationMB to do the next checks correctly if (jobManagerMemoryMb < yarnMinAllocationMB) { jobManagerMemoryMb = yarnMinAllocationMB; } if (taskManagerMemoryMb < yarnMinAllocationMB) { taskManagerMemoryMb = yarnMinAllocationMB; } final String note = "Please check the 'yarn.scheduler.maximum-allocation-mb' and the 'yarn.nodemanager.resource.memory-mb' configuration values\n"; if (jobManagerMemoryMb > maximumResourceCapability.getMemory()) { throw new YarnDeploymentException("The cluster does not have the requested resources for the JobManager available!\n" + "Maximum Memory: " + maximumResourceCapability.getMemory() + "MB Requested: " + jobManagerMemoryMb + "MB. " + note); } if (taskManagerMemoryMb > maximumResourceCapability.getMemory()) { throw new YarnDeploymentException("The cluster does not have the requested resources for the TaskManagers available!\n" + "Maximum Memory: " + maximumResourceCapability.getMemory() + " Requested: " + taskManagerMemoryMb + "MB. " + note); } final String noteRsc = "\nThe Flink YARN client will try to allocate the YARN session, but maybe not all TaskManagers are " + "connecting from the beginning because the resources are currently not available in the cluster. " + "The allocation might take more time than usual because the Flink YARN client needs to wait until " + "the resources become available."; int totalMemoryRequired = jobManagerMemoryMb + taskManagerMemoryMb * taskManagerCount; if (freeClusterResources.totalFreeMemory < totalMemoryRequired) { LOG.warn("This YARN session requires " + totalMemoryRequired + "MB of memory in the cluster. " + "There are currently only " + freeClusterResources.totalFreeMemory + "MB available." + noteRsc); } if (taskManagerMemoryMb > freeClusterResources.containerLimit) { LOG.warn("The requested amount of memory for the TaskManagers (" + taskManagerMemoryMb + "MB) is more than " + "the largest possible YARN container: " + freeClusterResources.containerLimit + noteRsc); } if (jobManagerMemoryMb > freeClusterResources.containerLimit) { LOG.warn("The requested amount of memory for the JobManager (" + jobManagerMemoryMb + "MB) is more than " + "the largest possible YARN container: " + freeClusterResources.containerLimit + noteRsc); } // ----------------- check if the requested containers fit into the cluster. int[] nmFree = Arrays.copyOf(freeClusterResources.nodeManagersFree, freeClusterResources.nodeManagersFree.length); // first, allocate the jobManager somewhere. if (!allocateResource(nmFree, jobManagerMemoryMb)) { LOG.warn("Unable to find a NodeManager that can fit the JobManager/Application master. " + "The JobManager requires " + jobManagerMemoryMb + "MB. NodeManagers available: " + Arrays.toString(freeClusterResources.nodeManagersFree) + noteRsc); } // allocate TaskManagers for (int i = 0; i < taskManagerCount; i++) { if (!allocateResource(nmFree, taskManagerMemoryMb)) { LOG.warn("There is not enough memory available in the YARN cluster. " + "The TaskManager(s) require " + taskManagerMemoryMb + "MB each. " + "NodeManagers available: " + Arrays.toString(freeClusterResources.nodeManagersFree) + "\n" + "After allocating the JobManager (" + jobManagerMemoryMb + "MB) and (" + i + "/" + taskManagerCount + ") TaskManagers, " + "the following NodeManagers are available: " + Arrays.toString(nmFree) + noteRsc); } } return new ClusterSpecification.ClusterSpecificationBuilder() .setMasterMemoryMB(jobManagerMemoryMb) .setTaskManagerMemoryMB(taskManagerMemoryMb) .setNumberTaskManagers(clusterSpecification.getNumberTaskManagers()) .setSlotsPerTaskManager(clusterSpecification.getSlotsPerTaskManager()) .createClusterSpecification(); } private void checkYarnQueues(YarnClient yarnClient) { try { List<QueueInfo> queues = yarnClient.getAllQueues(); if (queues.size() > 0 && this.yarnQueue != null) { // check only if there are queues configured in yarn and for this session. boolean queueFound = false; for (QueueInfo queue : queues) { if (queue.getQueueName().equals(this.yarnQueue)) { queueFound = true; break; } } if (!queueFound) { String queueNames = ""; for (QueueInfo queue : queues) { queueNames += queue.getQueueName() + ", "; } LOG.warn("The specified queue '" + this.yarnQueue + "' does not exist. " + "Available queues: " + queueNames); } } else { LOG.debug("The YARN cluster does not have any queues configured"); } } catch (Throwable e) { LOG.warn("Error while getting queue information from YARN: " + e.getMessage()); if (LOG.isDebugEnabled()) { LOG.debug("Error details", e); } } } public ApplicationReport startAppMaster( Configuration configuration, String applicationName, String yarnClusterEntrypoint, JobGraph jobGraph, YarnClient yarnClient, YarnClientApplication yarnApplication, ClusterSpecification clusterSpecification) throws Exception { // ------------------ Initialize the file systems ------------------------- try { org.apache.flink.core.fs.FileSystem.initialize(configuration); } catch (IOException e) { throw new IOException("Error while setting the default " + "filesystem scheme from configuration.", e); } // initialize file system // Copy the application master jar to the filesystem // Create a local resource to point to the destination jar path final FileSystem fs = FileSystem.get(yarnConfiguration); final Path homeDir = fs.getHomeDirectory(); // hard coded check for the GoogleHDFS client because its not overriding the getScheme() method. if (!fs.getClass().getSimpleName().equals("GoogleHadoopFileSystem") && fs.getScheme().startsWith("file")) { LOG.warn("The file system scheme is '" + fs.getScheme() + "'. This indicates that the " + "specified Hadoop configuration path is wrong and the system is using the default Hadoop configuration values." + "The Flink YARN client needs to store its files in a distributed file system"); } ApplicationSubmissionContext appContext = yarnApplication.getApplicationSubmissionContext(); Set<File> systemShipFiles = new HashSet<>(shipFiles.size()); for (File file : shipFiles) { systemShipFiles.add(file.getAbsoluteFile()); } //check if there is a logback or log4j file File logbackFile = new File(configurationDirectory + File.separator + CONFIG_FILE_LOGBACK_NAME); final boolean hasLogback = logbackFile.exists(); if (hasLogback) { systemShipFiles.add(logbackFile); } File log4jFile = new File(configurationDirectory + File.separator + CONFIG_FILE_LOG4J_NAME); final boolean hasLog4j = log4jFile.exists(); if (hasLog4j) { systemShipFiles.add(log4jFile); if (hasLogback) { // this means there is already a logback configuration file --> fail LOG.warn("The configuration directory ('" + configurationDirectory + "') contains both LOG4J and " + "Logback configuration files. Please delete or rename one of them."); } } addLibFolderToShipFiles(systemShipFiles); // Set-up ApplicationSubmissionContext for the application final ApplicationId appId = appContext.getApplicationId(); // ------------------ Add Zookeeper namespace to local flinkConfiguraton ------ String zkNamespace = getZookeeperNamespace(); // no user specified cli argument for namespace? if (zkNamespace == null || zkNamespace.isEmpty()) { // namespace defined in config? else use applicationId as default. zkNamespace = configuration.getString(HighAvailabilityOptions.HA_CLUSTER_ID, String.valueOf(appId)); setZookeeperNamespace(zkNamespace); } configuration.setString(HighAvailabilityOptions.HA_CLUSTER_ID, zkNamespace); if (HighAvailabilityMode.isHighAvailabilityModeActivated(configuration)) { // activate re-execution of failed applications appContext.setMaxAppAttempts( configuration.getInteger( YarnConfigOptions.APPLICATION_ATTEMPTS.key(), YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS)); activateHighAvailabilitySupport(appContext); } else { // set number of application retries to 1 in the default case appContext.setMaxAppAttempts( configuration.getInteger( YarnConfigOptions.APPLICATION_ATTEMPTS.key(), 1)); } if (jobGraph != null) { // add the user code jars from the provided JobGraph for (org.apache.flink.core.fs.Path path : jobGraph.getUserJars()) { userJarFiles.add(new File(path.toUri())); } } // local resource map for Yarn final Map<String, LocalResource> localResources = new HashMap<>(2 + systemShipFiles.size() + userJarFiles.size()); // list of remote paths (after upload) final List<Path> paths = new ArrayList<>(2 + systemShipFiles.size() + userJarFiles.size()); // ship list that enables reuse of resources for task manager containers StringBuilder envShipFileList = new StringBuilder(); // upload and register ship files List<String> systemClassPaths = uploadAndRegisterFiles( systemShipFiles, fs, homeDir, appId, paths, localResources, envShipFileList); List<String> userClassPaths; if (userJarInclusion != YarnConfigOptions.UserJarInclusion.DISABLED) { userClassPaths = uploadAndRegisterFiles( userJarFiles, fs, homeDir, appId, paths, localResources, envShipFileList); } else { userClassPaths = Collections.emptyList(); } if (userJarInclusion == YarnConfigOptions.UserJarInclusion.ORDER) { systemClassPaths.addAll(userClassPaths); } // normalize classpath by sorting Collections.sort(systemClassPaths); Collections.sort(userClassPaths); // classpath assembler StringBuilder classPathBuilder = new StringBuilder(); if (userJarInclusion == YarnConfigOptions.UserJarInclusion.FIRST) { for (String userClassPath : userClassPaths) { classPathBuilder.append(userClassPath).append(File.pathSeparator); } } for (String classPath : systemClassPaths) { classPathBuilder.append(classPath).append(File.pathSeparator); } if (userJarInclusion == YarnConfigOptions.UserJarInclusion.LAST) { for (String userClassPath : userClassPaths) { classPathBuilder.append(userClassPath).append(File.pathSeparator); } } // Setup jar for ApplicationMaster Path remotePathJar = setupSingleLocalResource( "flink.jar", fs, appId, flinkJarPath, localResources, homeDir, ""); // set the right configuration values for the TaskManager configuration.setInteger( TaskManagerOptions.NUM_TASK_SLOTS, clusterSpecification.getSlotsPerTaskManager()); configuration.setString( TaskManagerOptions.TASK_MANAGER_HEAP_MEMORY, clusterSpecification.getTaskManagerMemoryMB() + "m"); // Upload the flink configuration // write out configuration file File tmpConfigurationFile = File.createTempFile(appId + "-flink-conf.yaml", null); tmpConfigurationFile.deleteOnExit(); BootstrapTools.writeConfiguration(configuration, tmpConfigurationFile); Path remotePathConf = setupSingleLocalResource( "flink-conf.yaml", fs, appId, new Path(tmpConfigurationFile.getAbsolutePath()), localResources, homeDir, ""); paths.add(remotePathJar); classPathBuilder.append("flink.jar").append(File.pathSeparator); paths.add(remotePathConf); classPathBuilder.append("flink-conf.yaml").append(File.pathSeparator); // write job graph to tmp file and add it to local resource // TODO: server use user main method to generate job graph if (jobGraph != null) { try { File fp = File.createTempFile(appId.toString(), null); fp.deleteOnExit(); try (FileOutputStream output = new FileOutputStream(fp); ObjectOutputStream obOutput = new ObjectOutputStream(output);){ obOutput.writeObject(jobGraph); } Path pathFromYarnURL = setupSingleLocalResource( "job.graph", fs, appId, new Path(fp.toURI()), localResources, homeDir, ""); paths.add(pathFromYarnURL); classPathBuilder.append("job.graph").append(File.pathSeparator); } catch (Exception e) { LOG.warn("Add job graph to local resource fail"); throw e; } } final Path yarnFilesDir = getYarnFilesDir(appId); FsPermission permission = new FsPermission(FsAction.ALL, FsAction.NONE, FsAction.NONE); fs.setPermission(yarnFilesDir, permission); // set permission for path. //To support Yarn Secure Integration Test Scenario //In Integration test setup, the Yarn containers created by YarnMiniCluster does not have the Yarn site XML //and KRB5 configuration files. We are adding these files as container local resources for the container //applications (JM/TMs) to have proper secure cluster setup Path remoteKrb5Path = null; Path remoteYarnSiteXmlPath = null; boolean hasKrb5 = false; if (System.getenv("IN_TESTS") != null) { String krb5Config = System.getProperty("java.security.krb5.conf"); if (krb5Config != null && krb5Config.length() != 0) { File krb5 = new File(krb5Config); LOG.info("Adding KRB5 configuration {} to the AM container local resource bucket", krb5.getAbsolutePath()); Path krb5ConfPath = new Path(krb5.getAbsolutePath()); remoteKrb5Path = setupSingleLocalResource( Utils.KRB5_FILE_NAME, fs, appId, krb5ConfPath, localResources, homeDir, ""); File f = new File(System.getenv("YARN_CONF_DIR"), Utils.YARN_SITE_FILE_NAME); LOG.info("Adding Yarn configuration {} to the AM container local resource bucket", f.getAbsolutePath()); Path yarnSitePath = new Path(f.getAbsolutePath()); remoteYarnSiteXmlPath = setupSingleLocalResource( Utils.YARN_SITE_FILE_NAME, fs, appId, yarnSitePath, localResources, homeDir, ""); hasKrb5 = true; } } // setup security tokens Path remotePathKeytab = null; String keytab = configuration.getString(SecurityOptions.KERBEROS_LOGIN_KEYTAB); if (keytab != null) { LOG.info("Adding keytab {} to the AM container local resource bucket", keytab); remotePathKeytab = setupSingleLocalResource( Utils.KEYTAB_FILE_NAME, fs, appId, new Path(keytab), localResources, homeDir, ""); } final ContainerLaunchContext amContainer = setupApplicationMasterContainer( yarnClusterEntrypoint, hasLogback, hasLog4j, hasKrb5, clusterSpecification.getMasterMemoryMB()); if (UserGroupInformation.isSecurityEnabled()) { // set HDFS delegation tokens when security is enabled LOG.info("Adding delegation token to the AM container.."); Utils.setTokensFor(amContainer, paths, yarnConfiguration); } amContainer.setLocalResources(localResources); fs.close(); // Setup CLASSPATH and environment variables for ApplicationMaster final Map<String, String> appMasterEnv = new HashMap<>(); // set user specified app master environment variables appMasterEnv.putAll(Utils.getEnvironmentVariables(ResourceManagerOptions.CONTAINERIZED_MASTER_ENV_PREFIX, configuration)); // set Flink app class path appMasterEnv.put(YarnConfigKeys.ENV_FLINK_CLASSPATH, classPathBuilder.toString()); // set Flink on YARN internal configuration values appMasterEnv.put(YarnConfigKeys.ENV_TM_COUNT, String.valueOf(clusterSpecification.getNumberTaskManagers())); appMasterEnv.put(YarnConfigKeys.ENV_TM_MEMORY, String.valueOf(clusterSpecification.getTaskManagerMemoryMB())); appMasterEnv.put(YarnConfigKeys.FLINK_JAR_PATH, remotePathJar.toString()); appMasterEnv.put(YarnConfigKeys.ENV_APP_ID, appId.toString()); appMasterEnv.put(YarnConfigKeys.ENV_CLIENT_HOME_DIR, homeDir.toString()); appMasterEnv.put(YarnConfigKeys.ENV_CLIENT_SHIP_FILES, envShipFileList.toString()); appMasterEnv.put(YarnConfigKeys.ENV_SLOTS, String.valueOf(clusterSpecification.getSlotsPerTaskManager())); appMasterEnv.put(YarnConfigKeys.ENV_DETACHED, String.valueOf(detached)); appMasterEnv.put(YarnConfigKeys.ENV_ZOOKEEPER_NAMESPACE, getZookeeperNamespace()); appMasterEnv.put(YarnConfigKeys.FLINK_YARN_FILES, yarnFilesDir.toUri().toString()); // https://github.com/apache/hadoop/blob/trunk/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/YarnApplicationSecurity.md#identity-on-an-insecure-cluster-hadoop_user_name appMasterEnv.put(YarnConfigKeys.ENV_HADOOP_USER_NAME, UserGroupInformation.getCurrentUser().getUserName()); if (remotePathKeytab != null) { appMasterEnv.put(YarnConfigKeys.KEYTAB_PATH, remotePathKeytab.toString()); String principal = configuration.getString(SecurityOptions.KERBEROS_LOGIN_PRINCIPAL); appMasterEnv.put(YarnConfigKeys.KEYTAB_PRINCIPAL, principal); } //To support Yarn Secure Integration Test Scenario if (remoteYarnSiteXmlPath != null && remoteKrb5Path != null) { appMasterEnv.put(YarnConfigKeys.ENV_YARN_SITE_XML_PATH, remoteYarnSiteXmlPath.toString()); appMasterEnv.put(YarnConfigKeys.ENV_KRB5_PATH, remoteKrb5Path.toString()); } if (dynamicPropertiesEncoded != null) { appMasterEnv.put(YarnConfigKeys.ENV_DYNAMIC_PROPERTIES, dynamicPropertiesEncoded); } // set classpath from YARN configuration Utils.setupYarnClassPath(yarnConfiguration, appMasterEnv); amContainer.setEnvironment(appMasterEnv); // Set up resource type requirements for ApplicationMaster Resource capability = Records.newRecord(Resource.class); capability.setMemory(clusterSpecification.getMasterMemoryMB()); capability.setVirtualCores(1); final String customApplicationName = customName != null ? customName : applicationName; appContext.setApplicationName(customApplicationName); appContext.setApplicationType("Apache Flink"); appContext.setAMContainerSpec(amContainer); appContext.setResource(capability); if (yarnQueue != null) { appContext.setQueue(yarnQueue); } setApplicationNodeLabel(appContext); setApplicationTags(appContext); // add a hook to clean up in case deployment fails Thread deploymentFailureHook = new DeploymentFailureHook(yarnClient, yarnApplication, yarnFilesDir); Runtime.getRuntime().addShutdownHook(deploymentFailureHook); LOG.info("Submitting application master " + appId); yarnClient.submitApplication(appContext); LOG.info("Waiting for the cluster to be allocated"); final long startTime = System.currentTimeMillis(); ApplicationReport report; YarnApplicationState lastAppState = YarnApplicationState.NEW; loop: while (true) { try { report = yarnClient.getApplicationReport(appId); } catch (IOException e) { throw new YarnDeploymentException("Failed to deploy the cluster.", e); } YarnApplicationState appState = report.getYarnApplicationState(); LOG.debug("Application State: {}", appState); switch(appState) { case FAILED: case FINISHED: case KILLED: throw new YarnDeploymentException("The YARN application unexpectedly switched to state " + appState + " during deployment. \n" + "Diagnostics from YARN: " + report.getDiagnostics() + "\n" + "If log aggregation is enabled on your cluster, use this command to further investigate the issue:\n" + "yarn logs -applicationId " + appId); //break .. case RUNNING: LOG.info("YARN application has been deployed successfully."); break loop; default: if (appState != lastAppState) { LOG.info("Deploying cluster, current state " + appState); } if (System.currentTimeMillis() - startTime > 60000) { LOG.info("Deployment took more than 60 seconds. Please check if the requested resources are available in the YARN cluster"); } } lastAppState = appState; Thread.sleep(250); } // print the application id for user to cancel themselves. if (isDetachedMode()) { LOG.info("The Flink YARN client has been started in detached mode. In order to stop " + "Flink on YARN, use the following command or a YARN web interface to stop " + "it:\nyarn application -kill " + appId + "\nPlease also note that the " + "temporary files of the YARN session in the home directory will not be removed."); } // since deployment was successful, remove the hook ShutdownHookUtil.removeShutdownHook(deploymentFailureHook, getClass().getSimpleName(), LOG); return report; } /** * Returns the Path where the YARN application files should be uploaded to. * * @param appId YARN application id */ private Path getYarnFilesDir(final ApplicationId appId) throws IOException { final FileSystem fileSystem = FileSystem.get(yarnConfiguration); final Path homeDir = fileSystem.getHomeDirectory(); return new Path(homeDir, ".flink/" + appId + '/'); } /** * Uploads and registers a single resource and adds it to <tt>localResources</tt>. * * @param key * the key to add the resource under * @param fs * the remote file system to upload to * @param appId * application ID * @param localSrcPath * local path to the file * @param localResources * map of resources * * @return the remote path to the uploaded resource */ private static Path setupSingleLocalResource( String key, FileSystem fs, ApplicationId appId, Path localSrcPath, Map<String, LocalResource> localResources, Path targetHomeDir, String relativeTargetPath) throws IOException, URISyntaxException { Tuple2<Path, LocalResource> resource = Utils.setupLocalResource( fs, appId.toString(), localSrcPath, targetHomeDir, relativeTargetPath); localResources.put(key, resource.f1); return resource.f0; } /** * Recursively uploads (and registers) any (user and system) files in <tt>shipFiles</tt> except * for files matching "<tt>flink-dist*.jar</tt>" which should be uploaded separately. * * @param shipFiles * files to upload * @param fs * file system to upload to * @param targetHomeDir * remote home directory to upload to * @param appId * application ID * @param remotePaths * paths of the remote resources (uploaded resources will be added) * @param localResources * map of resources (uploaded resources will be added) * @param envShipFileList * list of shipped files in a format understood by {@link Utils#createTaskExecutorContext} * * @return list of class paths with the the proper resource keys from the registration */ static List<String> uploadAndRegisterFiles( Collection<File> shipFiles, FileSystem fs, Path targetHomeDir, ApplicationId appId, List<Path> remotePaths, Map<String, LocalResource> localResources, StringBuilder envShipFileList) throws IOException, URISyntaxException { final List<String> classPaths = new ArrayList<>(2 + shipFiles.size()); for (File shipFile : shipFiles) { if (shipFile.isDirectory()) { // add directories to the classpath java.nio.file.Path shipPath = shipFile.toPath(); final java.nio.file.Path parentPath = shipPath.getParent(); Files.walkFileTree(shipPath, new SimpleFileVisitor<java.nio.file.Path>() { @Override public FileVisitResult visitFile(java.nio.file.Path file, BasicFileAttributes attrs) throws IOException { String fileName = file.getFileName().toString(); if (!(fileName.startsWith("flink-dist") && fileName.endsWith("jar"))) { java.nio.file.Path relativePath = parentPath.relativize(file); String key = relativePath.toString(); try { Path remotePath = setupSingleLocalResource( key, fs, appId, new Path(file.toUri()), localResources, targetHomeDir, relativePath.getParent().toString()); remotePaths.add(remotePath); envShipFileList.append(key).append("=") .append(remotePath).append(","); // add files to the classpath classPaths.add(key); } catch (URISyntaxException e) { throw new IOException(e); } } return FileVisitResult.CONTINUE; } }); } else { if (!(shipFile.getName().startsWith("flink-dist") && shipFile.getName().endsWith("jar"))) { Path shipLocalPath = new Path(shipFile.toURI()); String key = shipFile.getName(); Path remotePath = setupSingleLocalResource( key, fs, appId, shipLocalPath, localResources, targetHomeDir, ""); remotePaths.add(remotePath); envShipFileList.append(key).append("=").append(remotePath).append(","); // add files to the classpath classPaths.add(key); } } } return classPaths; } /** * Kills YARN application and stops YARN client. * * <p>Use this method to kill the App before it has been properly deployed */ private void failSessionDuringDeployment(YarnClient yarnClient, YarnClientApplication yarnApplication) { LOG.info("Killing YARN application"); try { yarnClient.killApplication(yarnApplication.getNewApplicationResponse().getApplicationId()); } catch (Exception e) { // we only log a debug message here because the "killApplication" call is a best-effort // call (we don't know if the application has been deployed when the error occured). LOG.debug("Error while killing YARN application", e); } yarnClient.stop(); } private static class ClusterResourceDescription { public final int totalFreeMemory; public final int containerLimit; public final int[] nodeManagersFree; public ClusterResourceDescription(int totalFreeMemory, int containerLimit, int[] nodeManagersFree) { this.totalFreeMemory = totalFreeMemory; this.containerLimit = containerLimit; this.nodeManagersFree = nodeManagersFree; } } private ClusterResourceDescription getCurrentFreeClusterResources(YarnClient yarnClient) throws YarnException, IOException { List<NodeReport> nodes = yarnClient.getNodeReports(NodeState.RUNNING); int totalFreeMemory = 0; int containerLimit = 0; int[] nodeManagersFree = new int[nodes.size()]; for (int i = 0; i < nodes.size(); i++) { NodeReport rep = nodes.get(i); int free = rep.getCapability().getMemory() - (rep.getUsed() != null ? rep.getUsed().getMemory() : 0); nodeManagersFree[i] = free; totalFreeMemory += free; if (free > containerLimit) { containerLimit = free; } } return new ClusterResourceDescription(totalFreeMemory, containerLimit, nodeManagersFree); } @Override public String getClusterDescription() { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); YarnClusterMetrics metrics = yarnClient.getYarnClusterMetrics(); ps.append("NodeManagers in the ClusterClient " + metrics.getNumNodeManagers()); List<NodeReport> nodes = yarnClient.getNodeReports(NodeState.RUNNING); final String format = "|%-16s |%-16s %n"; ps.printf("|Property |Value %n"); ps.println("+---------------------------------------+"); int totalMemory = 0; int totalCores = 0; for (NodeReport rep : nodes) { final Resource res = rep.getCapability(); totalMemory += res.getMemory(); totalCores += res.getVirtualCores(); ps.format(format, "NodeID", rep.getNodeId()); ps.format(format, "Memory", res.getMemory() + " MB"); ps.format(format, "vCores", res.getVirtualCores()); ps.format(format, "HealthReport", rep.getHealthReport()); ps.format(format, "Containers", rep.getNumContainers()); ps.println("+---------------------------------------+"); } ps.println("Summary: totalMemory " + totalMemory + " totalCores " + totalCores); List<QueueInfo> qInfo = yarnClient.getAllQueues(); for (QueueInfo q : qInfo) { ps.println("Queue: " + q.getQueueName() + ", Current Capacity: " + q.getCurrentCapacity() + " Max Capacity: " + q.getMaximumCapacity() + " Applications: " + q.getApplications().size()); } return baos.toString(); } catch (Exception e) { throw new RuntimeException("Couldn't get cluster description", e); } } public void setName(String name) { if (name == null) { throw new IllegalArgumentException("The passed name is null"); } customName = name; } private void activateHighAvailabilitySupport(ApplicationSubmissionContext appContext) throws InvocationTargetException, IllegalAccessException { ApplicationSubmissionContextReflector reflector = ApplicationSubmissionContextReflector.getInstance(); reflector.setKeepContainersAcrossApplicationAttempts(appContext, true); reflector.setAttemptFailuresValidityInterval(appContext, AkkaUtils.getTimeout(flinkConfiguration).toMillis()); } private void setApplicationTags(final ApplicationSubmissionContext appContext) throws InvocationTargetException, IllegalAccessException { final ApplicationSubmissionContextReflector reflector = ApplicationSubmissionContextReflector.getInstance(); final String tagsString = flinkConfiguration.getString(YarnConfigOptions.APPLICATION_TAGS); final Set<String> applicationTags = new HashSet<>(); // Trim whitespace and cull empty tags for (final String tag : tagsString.split(",")) { final String trimmedTag = tag.trim(); if (!trimmedTag.isEmpty()) { applicationTags.add(trimmedTag); } } reflector.setApplicationTags(appContext, applicationTags); } private void setApplicationNodeLabel(final ApplicationSubmissionContext appContext) throws InvocationTargetException, IllegalAccessException { if (nodeLabel != null) { final ApplicationSubmissionContextReflector reflector = ApplicationSubmissionContextReflector.getInstance(); reflector.setApplicationNodeLabel(appContext, nodeLabel); } } /** * Singleton object which uses reflection to determine whether the {@link ApplicationSubmissionContext} * supports various methods which, depending on the Hadoop version, may or may not be supported. * * <p>If an unsupported method is invoked, nothing happens. * * <p>Currently three methods are proxied: * - setApplicationTags (>= 2.4.0) * - setAttemptFailuresValidityInterval (>= 2.6.0) * - setKeepContainersAcrossApplicationAttempts (>= 2.4.0) * - setNodeLabelExpression (>= 2.6.0) */ private static class ApplicationSubmissionContextReflector { private static final Logger LOG = LoggerFactory.getLogger(ApplicationSubmissionContextReflector.class); private static final ApplicationSubmissionContextReflector instance = new ApplicationSubmissionContextReflector(ApplicationSubmissionContext.class); public static ApplicationSubmissionContextReflector getInstance() { return instance; } private static final String APPLICATION_TAGS_METHOD_NAME = "setApplicationTags"; private static final String ATTEMPT_FAILURES_METHOD_NAME = "setAttemptFailuresValidityInterval"; private static final String KEEP_CONTAINERS_METHOD_NAME = "setKeepContainersAcrossApplicationAttempts"; private static final String NODE_LABEL_EXPRESSION_NAME = "setNodeLabelExpression"; private final Method applicationTagsMethod; private final Method attemptFailuresValidityIntervalMethod; private final Method keepContainersMethod; @Nullable private final Method nodeLabelExpressionMethod; private ApplicationSubmissionContextReflector(Class<ApplicationSubmissionContext> clazz) { Method applicationTagsMethod; Method attemptFailuresValidityIntervalMethod; Method keepContainersMethod; Method nodeLabelExpressionMethod; try { // this method is only supported by Hadoop 2.4.0 onwards applicationTagsMethod = clazz.getMethod(APPLICATION_TAGS_METHOD_NAME, Set.class); LOG.debug("{} supports method {}.", clazz.getCanonicalName(), APPLICATION_TAGS_METHOD_NAME); } catch (NoSuchMethodException e) { LOG.debug("{} does not support method {}.", clazz.getCanonicalName(), APPLICATION_TAGS_METHOD_NAME); // assign null because the Hadoop version apparently does not support this call. applicationTagsMethod = null; } this.applicationTagsMethod = applicationTagsMethod; try { // this method is only supported by Hadoop 2.6.0 onwards attemptFailuresValidityIntervalMethod = clazz.getMethod(ATTEMPT_FAILURES_METHOD_NAME, long.class); LOG.debug("{} supports method {}.", clazz.getCanonicalName(), ATTEMPT_FAILURES_METHOD_NAME); } catch (NoSuchMethodException e) { LOG.debug("{} does not support method {}.", clazz.getCanonicalName(), ATTEMPT_FAILURES_METHOD_NAME); // assign null because the Hadoop version apparently does not support this call. attemptFailuresValidityIntervalMethod = null; } this.attemptFailuresValidityIntervalMethod = attemptFailuresValidityIntervalMethod; try { // this method is only supported by Hadoop 2.4.0 onwards keepContainersMethod = clazz.getMethod(KEEP_CONTAINERS_METHOD_NAME, boolean.class); LOG.debug("{} supports method {}.", clazz.getCanonicalName(), KEEP_CONTAINERS_METHOD_NAME); } catch (NoSuchMethodException e) { LOG.debug("{} does not support method {}.", clazz.getCanonicalName(), KEEP_CONTAINERS_METHOD_NAME); // assign null because the Hadoop version apparently does not support this call. keepContainersMethod = null; } this.keepContainersMethod = keepContainersMethod; try { nodeLabelExpressionMethod = clazz.getMethod(NODE_LABEL_EXPRESSION_NAME, String.class); LOG.debug("{} supports method {}.", clazz.getCanonicalName(), NODE_LABEL_EXPRESSION_NAME); } catch (NoSuchMethodException e) { LOG.debug("{} does not support method {}.", clazz.getCanonicalName(), NODE_LABEL_EXPRESSION_NAME); nodeLabelExpressionMethod = null; } this.nodeLabelExpressionMethod = nodeLabelExpressionMethod; } public void setApplicationTags( ApplicationSubmissionContext appContext, Set<String> applicationTags) throws InvocationTargetException, IllegalAccessException { if (applicationTagsMethod != null) { LOG.debug("Calling method {} of {}.", applicationTagsMethod.getName(), appContext.getClass().getCanonicalName()); applicationTagsMethod.invoke(appContext, applicationTags); } else { LOG.debug("{} does not support method {}. Doing nothing.", appContext.getClass().getCanonicalName(), APPLICATION_TAGS_METHOD_NAME); } } public void setApplicationNodeLabel( ApplicationSubmissionContext appContext, String nodeLabel) throws InvocationTargetException, IllegalAccessException { if (nodeLabelExpressionMethod != null) { LOG.debug("Calling method {} of {}.", nodeLabelExpressionMethod.getName(), appContext.getClass().getCanonicalName()); nodeLabelExpressionMethod.invoke(appContext, nodeLabel); } else { LOG.debug("{} does not support method {}. Doing nothing.", appContext.getClass().getCanonicalName(), NODE_LABEL_EXPRESSION_NAME); } } public void setAttemptFailuresValidityInterval( ApplicationSubmissionContext appContext, long validityInterval) throws InvocationTargetException, IllegalAccessException { if (attemptFailuresValidityIntervalMethod != null) { LOG.debug("Calling method {} of {}.", attemptFailuresValidityIntervalMethod.getName(), appContext.getClass().getCanonicalName()); attemptFailuresValidityIntervalMethod.invoke(appContext, validityInterval); } else { LOG.debug("{} does not support method {}. Doing nothing.", appContext.getClass().getCanonicalName(), ATTEMPT_FAILURES_METHOD_NAME); } } public void setKeepContainersAcrossApplicationAttempts( ApplicationSubmissionContext appContext, boolean keepContainers) throws InvocationTargetException, IllegalAccessException { if (keepContainersMethod != null) { LOG.debug("Calling method {} of {}.", keepContainersMethod.getName(), appContext.getClass().getCanonicalName()); keepContainersMethod.invoke(appContext, keepContainers); } else { LOG.debug("{} does not support method {}. Doing nothing.", appContext.getClass().getCanonicalName(), KEEP_CONTAINERS_METHOD_NAME); } } } private static class YarnDeploymentException extends RuntimeException { private static final long serialVersionUID = -812040641215388943L; public YarnDeploymentException(String message) { super(message); } public YarnDeploymentException(String message, Throwable cause) { super(message, cause); } } private class DeploymentFailureHook extends Thread { private final YarnClient yarnClient; private final YarnClientApplication yarnApplication; private final Path yarnFilesDir; DeploymentFailureHook(YarnClient yarnClient, YarnClientApplication yarnApplication, Path yarnFilesDir) { this.yarnClient = Preconditions.checkNotNull(yarnClient); this.yarnApplication = Preconditions.checkNotNull(yarnApplication); this.yarnFilesDir = Preconditions.checkNotNull(yarnFilesDir); } @Override public void run() { LOG.info("Cancelling deployment from Deployment Failure Hook"); failSessionDuringDeployment(yarnClient, yarnApplication); LOG.info("Deleting files in {}.", yarnFilesDir); try { FileSystem fs = FileSystem.get(yarnConfiguration); if (!fs.delete(yarnFilesDir, true)) { throw new IOException("Deleting files in " + yarnFilesDir + " was unsuccessful"); } fs.close(); } catch (IOException e) { LOG.error("Failed to delete Flink Jar and configuration files in HDFS", e); } } } protected void addLibFolderToShipFiles(Collection<File> effectiveShipFiles) { // Add lib folder to the ship files if the environment variable is set. // This is for convenience when running from the command-line. // (for other files users explicitly set the ship files) String libDir = System.getenv().get(ENV_FLINK_LIB_DIR); if (libDir != null) { File libDirFile = new File(libDir); if (libDirFile.isDirectory()) { effectiveShipFiles.add(libDirFile); } else { throw new YarnDeploymentException("The environment variable '" + ENV_FLINK_LIB_DIR + "' is set to '" + libDir + "' but the directory doesn't exist."); } } else if (this.shipFiles.isEmpty()) { LOG.warn("Environment variable '{}' not set and ship files have not been provided manually. " + "Not shipping any library files.", ENV_FLINK_LIB_DIR); } } protected ContainerLaunchContext setupApplicationMasterContainer( String yarnClusterEntrypoint, boolean hasLogback, boolean hasLog4j, boolean hasKrb5, int jobManagerMemoryMb) { // ------------------ Prepare Application Master Container ------------------------------ // respect custom JVM options in the YAML file String javaOpts = flinkConfiguration.getString(CoreOptions.FLINK_JVM_OPTIONS); if (flinkConfiguration.getString(CoreOptions.FLINK_JM_JVM_OPTIONS).length() > 0) { javaOpts += " " + flinkConfiguration.getString(CoreOptions.FLINK_JM_JVM_OPTIONS); } //applicable only for YarnMiniCluster secure test run //krb5.conf file will be available as local resource in JM/TM container if (hasKrb5) { javaOpts += " -Djava.security.krb5.conf=krb5.conf"; } // Set up the container launch context for the application master ContainerLaunchContext amContainer = Records.newRecord(ContainerLaunchContext.class); final Map<String, String> startCommandValues = new HashMap<>(); startCommandValues.put("java", "$JAVA_HOME/bin/java"); startCommandValues.put("jvmmem", "-Xmx" + Utils.calculateHeapSize(jobManagerMemoryMb, flinkConfiguration) + "m"); startCommandValues.put("jvmopts", javaOpts); String logging = ""; if (hasLogback || hasLog4j) { logging = "-Dlog.file=\"" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/jobmanager.log\""; if (hasLogback) { logging += " -Dlogback.configurationFile=file:" + CONFIG_FILE_LOGBACK_NAME; } if (hasLog4j) { logging += " -Dlog4j.configuration=file:" + CONFIG_FILE_LOG4J_NAME; } } startCommandValues.put("logging", logging); startCommandValues.put("class", yarnClusterEntrypoint); startCommandValues.put("redirects", "1> " + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/jobmanager.out " + "2> " + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/jobmanager.err"); startCommandValues.put("args", ""); final String commandTemplate = flinkConfiguration .getString(ConfigConstants.YARN_CONTAINER_START_COMMAND_TEMPLATE, ConfigConstants.DEFAULT_YARN_CONTAINER_START_COMMAND_TEMPLATE); final String amCommand = BootstrapTools.getStartCommand(commandTemplate, startCommandValues); amContainer.setCommands(Collections.singletonList(amCommand)); LOG.debug("Application Master start command: " + amCommand); return amContainer; } private static YarnConfigOptions.UserJarInclusion getUserJarInclusionMode(org.apache.flink.configuration.Configuration config) { String configuredUserJarInclusion = config.getString(YarnConfigOptions.CLASSPATH_INCLUDE_USER_JAR); try { return YarnConfigOptions.UserJarInclusion.valueOf(configuredUserJarInclusion.toUpperCase()); } catch (IllegalArgumentException e) { LOG.warn("Configuration parameter {} was configured with an invalid value {}. Falling back to default ({}).", YarnConfigOptions.CLASSPATH_INCLUDE_USER_JAR.key(), configuredUserJarInclusion, YarnConfigOptions.CLASSPATH_INCLUDE_USER_JAR.defaultValue()); return YarnConfigOptions.UserJarInclusion.valueOf(YarnConfigOptions.CLASSPATH_INCLUDE_USER_JAR.defaultValue()); } } /** * Creates a YarnClusterClient; may be overriden in tests. */ protected abstract ClusterClient<ApplicationId> createYarnClusterClient( AbstractYarnClusterDescriptor descriptor, int numberTaskManagers, int slotsPerTaskManager, ApplicationReport report, org.apache.flink.configuration.Configuration flinkConfiguration, boolean perJobCluster) throws Exception; }
apache-2.0
rmap-project/rmap
webapp/src/main/java/info/rmapproject/webapp/controllers/SearchController.java
5204
/******************************************************************************* * Copyright 2018 Johns Hopkins University * * 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. * * This software was produced as part of the RMap Project (http://rmap-project.info), * The RMap Project was funded by the Alfred P. Sloan Foundation and is a * collaboration between Data Conservancy, Portico, and IEEE. *******************************************************************************/ package info.rmapproject.webapp.controllers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.solr.core.query.result.FacetAndHighlightPage; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import info.rmapproject.core.model.request.DateRange; import info.rmapproject.core.model.request.RMapSearchParams; import info.rmapproject.core.model.request.RMapSearchParamsFactory; import info.rmapproject.core.model.request.RMapStatusFilter; import info.rmapproject.indexing.solr.model.DiscoSolrDocument; import info.rmapproject.webapp.service.DataDisplayService; import info.rmapproject.webapp.service.SearchService; /** * Handles display of the search page. * * @author khanson */ @Controller @SessionAttributes({"user","account"}) public class SearchController { /** The log. */ private static final Logger LOG = LoggerFactory.getLogger(SearchController.class); private SearchService searchService; private DataDisplayService dataDisplayService; private RMapSearchParamsFactory paramsFactory; @Autowired public SearchController(SearchService searchService, DataDisplayService dataDisplayService, RMapSearchParamsFactory paramsFactory) { this.searchService = searchService; this.dataDisplayService = dataDisplayService; this.paramsFactory = paramsFactory; } /** * Retrieves and displays search results from indexer * * @param search * @param model * @param page * @param status * @param agent * @param agentDisplay * @param dateFrom * @param dateTo * @return * @throws Exception */ @RequestMapping(value="/searchresults", method = RequestMethod.GET) public String searchResults(@RequestParam(value="search", required=false) String search, Model model, @RequestParam(value="page", required=false) Integer page, @RequestParam(value="status", required=false) String status, @RequestParam(value="agent", required=false) String agent, @RequestParam(value="agentDisplay", required=false) String agentDisplay, @RequestParam(value="dateFrom", required=false) String dateFrom, @RequestParam(value="dateTo", required=false) String dateTo) throws Exception { if (page==null) { page=0; } if (search==null) { search=""; } Integer INCREMENT = 20; Pageable pageable = PageRequest.of(page, INCREMENT); search = search.trim(); search = search.replace("\"", ""); //remove quotes search = search.replaceAll("( )+", " "); //remove extra spaces RMapSearchParams params = paramsFactory.newInstance(); params.setSystemAgents(agent); RMapStatusFilter statusFilter = RMapStatusFilter.getStatusFromTerm(status); statusFilter = (statusFilter==null) ? RMapStatusFilter.ALL : statusFilter; params.setStatusCode(statusFilter); params.setDateRange(new DateRange(dateFrom,dateTo)); FacetAndHighlightPage<DiscoSolrDocument> indexerResults = searchService.searchDiSCOs(search, params, pageable); boolean hasExactMatch = dataDisplayService.isResourceInRMap(search, params); model.addAttribute("search", search); model.addAttribute("numRecords",indexerResults.getTotalElements()); model.addAttribute("matches",indexerResults.getHighlighted()); model.addAttribute("statusFacets",indexerResults.getFacetResultPage("disco_status").getContent()); model.addAttribute("agentFacets",indexerResults.getPivot("agent_uri,agent_name")); model.addAttribute("pageable", pageable); model.addAttribute("agent", agent); model.addAttribute("agentDisplay", agentDisplay); model.addAttribute("dateFrom", dateFrom); model.addAttribute("dateTo", dateTo); model.addAttribute("status", status); model.addAttribute("hasExactMatch", hasExactMatch); return "searchresults"; } }
apache-2.0
WANdisco/gerrit
java/com/google/gerrit/lucene/GerritIndexWriterConfig.java
4525
// 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.gerrit.lucene; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MINUTES; import com.google.common.collect.ImmutableMap; import com.google.common.flogger.FluentLogger; import com.google.gerrit.server.config.ConfigUtil; import org.apache.lucene.analysis.CharArraySet; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.index.ConcurrentMergeScheduler; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.util.InfoStream; import org.eclipse.jgit.lib.Config; /** Combination of Lucene {@link IndexWriterConfig} with additional Gerrit-specific options. */ class GerritIndexWriterConfig { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); public static final InfoStream VERBOSE = new VerboseOutput(); private static final ImmutableMap<String, String> CUSTOM_CHAR_MAPPING = ImmutableMap.of("_", " ", ".", " "); private final IndexWriterConfig luceneConfig; private long commitWithinMs; private final CustomMappingAnalyzer analyzer; /** * Note that GerritIndexWriterConfig takes both a cfg object and a name. * Name is the name of the subsection, i.e changes_open / change_closed */ GerritIndexWriterConfig(Config cfg, String name) { analyzer = new CustomMappingAnalyzer( new StandardAnalyzer(CharArraySet.EMPTY_SET), CUSTOM_CHAR_MAPPING); luceneConfig = new IndexWriterConfig(analyzer) .setOpenMode(OpenMode.CREATE_OR_APPEND) .setCommitOnClose(true); int maxMergeCount = cfg.getInt("index", name, "maxMergeCount", -1); int maxThreadCount = cfg.getInt("index", name, "maxThreadCount", -1); boolean enableAutoIOThrottle = cfg.getBoolean("index", name, "enableAutoIOThrottle", true); if (maxMergeCount != -1 || maxThreadCount != -1 || !enableAutoIOThrottle) { ConcurrentMergeScheduler mergeScheduler = new ConcurrentMergeScheduler(); if (maxMergeCount != -1 || maxThreadCount != -1) { mergeScheduler.setMaxMergesAndThreads(maxMergeCount, maxThreadCount); } if (!enableAutoIOThrottle) { mergeScheduler.disableAutoIOThrottle(); } luceneConfig.setMergeScheduler(mergeScheduler); } double m = 1 << 20; luceneConfig.setRAMBufferSizeMB( cfg.getLong( "index", name, "ramBufferSize", (long) (IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB * m)) / m); luceneConfig.setMaxBufferedDocs( cfg.getInt("index", name, "maxBufferedDocs", IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS)); try { commitWithinMs = ConfigUtil.getTimeUnit( cfg, "index", name, "commitWithin", MILLISECONDS.convert(5, MINUTES), MILLISECONDS); } catch (IllegalArgumentException e) { commitWithinMs = cfg.getLong("index", name, "commitWithin", 0); } //Checking that it has been set correctly and if so turn the verbose logging on //for Lucene. if (cfg.getBoolean("index", name, "verboseLogging", false)) { // turn on verbose logging for lucene luceneConfig.setInfoStream(VERBOSE); // Show the current configuration. logger.atInfo().log("Current lucene configuration: {}", luceneConfig.toString()); } } private static class VerboseOutput extends InfoStream { VerboseOutput() { } public void message(String component, String message) { logger.atInfo().log(message); } public boolean isEnabled(String component) { return true; } public void close() {} } CustomMappingAnalyzer getAnalyzer() { return analyzer; } IndexWriterConfig getLuceneConfig() { return luceneConfig; } long getCommitWithinMs() { return commitWithinMs; } }
apache-2.0
SeaCloudsEU/paas-unified-library
adapter-REST/src/main/java/eu/cloud4soa/adapter/rest/AdapterClient.java
1251
/* * Copyright 2013 Cloud4SOA, www.cloud4soa.eu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.cloud4soa.adapter.rest; import java.io.IOException; import eu.cloud4soa.adapter.rest.auth.Credentials; import eu.cloud4soa.adapter.rest.exception.AdapterClientException; import eu.cloud4soa.adapter.rest.request.Request; import java.net.UnknownHostException; /** * * @author Denis Neuling (dn@cloudcontrol.de) * */ public interface AdapterClient { /** * @param t the typed request * @return response the response to expect * @throws IOException */ public <T> T send(Request<T> t, Credentials credentials) throws AdapterClientException,UnknownHostException; public String getAdapterRootPath(); }
apache-2.0
2419043433/LanTool
src/com/orange/net/asio/AsynChannelImpl.java
1883
package com.orange.net.asio; import java.io.IOException; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.concurrent.TimeUnit; import com.orange.net.asio.interfaces.IAsyncChannel; public class AsynChannelImpl implements IAsyncChannel { private AsynchronousSocketChannel mChannel; public AsynChannelImpl() { try { mChannel = AsynchronousSocketChannel.open(); } catch (IOException e) { e.printStackTrace(); } } public AsynChannelImpl(AsynchronousSocketChannel channel) { mChannel = channel; } @Override public <A> void connect(SocketAddress remote, A attachment, CompletionHandler<Void, ? super A> handler) { mChannel.connect(remote, attachment, handler); } @Override public <A> void read(ByteBuffer dst, long timeout, TimeUnit unit, A attachment, CompletionHandler<Integer, ? super A> handler) { mChannel.read(dst, timeout, unit, attachment, handler); } @Override public <A> void write(ByteBuffer src, long timeout, TimeUnit unit, A attachment, CompletionHandler<Integer, ? super A> handler) { mChannel.write(src, timeout, unit, attachment, handler); } @Override public SocketAddress getLocalAddress() { try { return mChannel.getLocalAddress(); } catch (IOException e) { e.printStackTrace(); return null; } } @Override public SocketAddress getRemoteAddress() { try { return mChannel.getRemoteAddress(); } catch (IOException e) { e.printStackTrace(); return null; } } }
apache-2.0
lievendoclo/Valkyrie-RCP
valkyrie-rcp-core/src/main/java/org/valkyriercp/widget/AbstractFocussableWidgetForm.java
3878
/** * Copyright (C) 2015 Valkyrie RCP * * 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.valkyriercp.widget; import org.valkyriercp.component.Focussable; import org.valkyriercp.util.ValkyrieRepository; import javax.swing.*; import java.awt.*; /** * Form implementation for the Focussable interface. * * @author Jan Hoskens * */ public abstract class AbstractFocussableWidgetForm extends AbstractWidgetForm implements Focussable//, SecurityControllable { public static final String UNSAVEDCHANGES_WARNING_ID = "unsavedchanges.warning"; public static final String UNSAVEDCHANGES_HASERRORS_WARNING_ID = "unsavedchanges.haserrors.warning"; private JComponent focusControl; private final Runnable focusRequestRunnable = new Runnable() { public void run() { if (focusControl != null) focusControl.requestFocusInWindow(); } }; protected AbstractFocussableWidgetForm() { } protected AbstractFocussableWidgetForm(String id) { super(id); } /** * Override to do nothing. Superclass registers a default command, but we are using a different system to * define default commands. */ @Override protected void handleEnabledChange(boolean enabled) { } /** * Registers the component that receives the focus when the form receives focus. * * @see #grabFocus */ public void setFocusControl(JComponent field) { this.focusControl = field; } public void grabFocus() { if (this.focusControl != null) EventQueue.invokeLater(focusRequestRunnable); } public boolean canClose() { boolean userBreak = false; int answer = JOptionPane.NO_OPTION; // by default no save is required. // unless of course there are unsaved changes and we can commit (isAuthorized) if (this.getFormModel().isEnabled() && this.getFormModel().isDirty() && this.getCommitCommand().isAuthorized()) { // then we ask the user to save the mess first: yes/no/cancel answer = ValkyrieRepository.getInstance().getApplicationConfig().dialogFactory().showWarningDialog(this.getControl(), UNSAVEDCHANGES_WARNING_ID, JOptionPane.YES_NO_CANCEL_OPTION); switch (answer) { case JOptionPane.CANCEL_OPTION : // backup the selection change so table and detail keep in sync // gives problems (asks unsavedchanges twice) userBreak = true; break; case JOptionPane.YES_OPTION : if (this.getFormModel().getHasErrors() == true) { ValkyrieRepository.getInstance().getApplicationConfig().dialogFactory().showWarningDialog(this.getControl(), UNSAVEDCHANGES_HASERRORS_WARNING_ID); userBreak = true; break; } this.getCommitCommand().execute(); break; case JOptionPane.NO_OPTION : { this.revert(); // revert so no strange things happen (hopefully) break; } } } return !userBreak; } }
apache-2.0
datumbox/datumbox-framework
datumbox-framework-core/src/test/java/com/datumbox/framework/core/statistics/survival/nonparametrics/independentsamples/PetoPetoWilcoxonTest.java
2020
/** * Copyright (C) 2013-2020 Vasilis Vryniotis <bbriniotis@datumbox.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.datumbox.framework.core.statistics.survival.nonparametrics.independentsamples; import com.datumbox.framework.common.dataobjects.FlatDataCollection; import com.datumbox.framework.common.dataobjects.TransposeDataCollection; import com.datumbox.framework.tests.abstracts.AbstractTest; import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.assertEquals; /** * Test cases for PetoPetoWilcoxon. * * @author Vasilis Vryniotis <bbriniotis@datumbox.com> */ public class PetoPetoWilcoxonTest extends AbstractTest { /** * Test of test method, of class PetoPetoWilcoxon. */ @Test public void testTest() { logger.info("test"); //Example from Dimaki's Survival Non-parametrics notes. It should reject the null hypothesis and return true. TransposeDataCollection transposeDataCollection = new TransposeDataCollection(); transposeDataCollection.put(0, new FlatDataCollection(Arrays.asList(new Object[]{23,"16+","18+","20+","24+"}))); transposeDataCollection.put(1, new FlatDataCollection(Arrays.asList(new Object[]{15,18,19,19,20.0}))); boolean is_twoTailed = true; double aLevel = 0.05; boolean expResult = true; boolean result = PetoPetoWilcoxon.test(transposeDataCollection, is_twoTailed, aLevel); assertEquals(expResult, result); } }
apache-2.0
youtongluan/sumk
src/main/java/org/yx/db/conn/SqlSessionHook.java
1751
/** * Copyright (C) 2016 - 2030 youtongluan. * * 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.yx.db.conn; import java.util.Objects; import java.util.function.Consumer; import org.yx.db.enums.TxHook; class SqlSessionHook { private final TxHook type; private final Consumer<HookContext> action; public SqlSessionHook(TxHook type, Consumer<HookContext> action) { this.type = Objects.requireNonNull(type); this.action = Objects.requireNonNull(action); } public TxHook getType() { return type; } public Consumer<HookContext> getAction() { return action; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((action == null) ? 0 : action.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SqlSessionHook other = (SqlSessionHook) obj; if (action == null) { if (other.action != null) return false; } else if (!action.equals(other.action)) return false; if (type != other.type) return false; return true; } }
apache-2.0
leepc12/BigDataScript
src/org/bds/run/BdsThreads.java
2366
package org.bds.run; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.bds.data.Data; import org.bds.task.Task; /** * All BdsThreads are tracked here * * @author pcingola */ public class BdsThreads { private static BdsThreads bdsThreads = new BdsThreads(); Map<Long, BdsThread> bdsThreadByThreadId = new HashMap<Long, BdsThread>(); Set<BdsThread> bdsThreadDone = new HashSet<BdsThread>(); /** * Get canonical path to file using thread's 'current dir' to de-reference * relative paths * * Warning: When un-serializing a task form a checkpoint, threads are not * initialized, thus they are null */ public static Data data(String url) { BdsThread bdsThread = BdsThreads.getInstance().get(); if (bdsThread == null) return Data.factory(url); return bdsThread.data(url); } /** * Get singleton */ public static BdsThreads getInstance() { return bdsThreads; } /** * Reset singleton */ public static void reset() { bdsThreads = new BdsThreads(); } /** * Add a bdsThread */ public synchronized void add(BdsThread bdsThread) { long id = Thread.currentThread().getId(); bdsThreadByThreadId.put(id, bdsThread); } /** * Get bdsThread */ public synchronized BdsThread get() { long id = Thread.currentThread().getId(); return bdsThreadByThreadId.get(id); } /** * Remove a bdsThread */ public synchronized void remove() { long id = Thread.currentThread().getId(); BdsThread bdsThread = get(); if (bdsThreadByThreadId.get(id) == bdsThread) { bdsThreadByThreadId.remove(id); bdsThreadDone.add(bdsThread); } else throw new RuntimeException("Cannot remove thread '" + bdsThread.getBdsThreadId() + "'"); } public static Task getTaskNoSync(String taskId) { for (BdsThread bdsThread : bdsThreads.bdsThreadByThreadId.values() ) { Task task = bdsThread.getTaskNoSync(taskId); if (task != null) return task; } for (BdsThread bdsThread : bdsThreads.bdsThreadDone) { Task task = bdsThread.getTaskNoSync(taskId); if (task != null) return task; } return null; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (Long thid : bdsThreadByThreadId.keySet()) sb.append(thid + "\t" + bdsThreadByThreadId.get(thid).getBdsThreadId() + "\n"); return sb.toString(); } }
apache-2.0
vimaier/conqat
org.conqat.engine.core/external/commons-src/org/conqat/lib/commons/assessment/external/PrefixSuffixFileResolver.java
3916
/*-------------------------------------------------------------------------+ | | | Copyright 2005-2011 the ConQAT Project | | | | Licensed under the Apache License, Version 2.0 (the "License"); | | you may not use this file except in compliance with the License. | | You may obtain a copy of the License at | | | | http://www.apache.org/licenses/LICENSE-2.0 | | | | Unless required by applicable law or agreed to in writing, software | | distributed under the License is distributed on an "AS IS" BASIS, | | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | | See the License for the specific language governing permissions and | | limitations under the License. | +-------------------------------------------------------------------------*/ package org.conqat.lib.commons.assessment.external; /** * A file resolver that works by adding prefixes and suffixes to the base name. * Optionally, it can also map paths into a parallel directory tree. This tree * is determined by an "anchor directory" (such as "src") that is searched in * the path to find the point of the parallel tree, and the replacement * directory (e.g. "ratings") where the parallel tree resides. See the test-case * for examples. * * Note that the fully qualified name of this class is used in the rating * comments of many code files. Thus, rename or move this class only if it can * not be avoided. * * @author $Author: kinnen $ * @version $Rev: 41751 $ * @ConQAT.Rating GREEN Hash: DE1CBE957CDD47F3119835302DD25E24 */ public class PrefixSuffixFileResolver implements IFilePathResolver { /** The prefix. */ private String filenamePrefix; /** The suffix. */ private String filenameSuffix; /** The name of the "anchor" directory. */ private String anchorDirectoryName; /** * The name of the directory replacing {@link #anchorDirectoryName} in the * parallel tree. */ private String replacementDirectoryName; /** * {@inheritDoc}. * * @param args * the arguments taken are (in order) the prefix, the suffix, the * anchor directory and the replacement directory. It is ok to * provide only one or two parameters (prefix or prefix and * suffix). */ @Override public void init(String... args) throws ExternalRatingTableException { if (args.length == 0 || args.length == 3 || args.length > 4) { throw new ExternalRatingTableException( "Expecting 1, 2, or 4 arguments!"); } filenamePrefix = pickArg(args, 0, ""); filenameSuffix = pickArg(args, 1, ""); anchorDirectoryName = pickArg(args, 2, null); replacementDirectoryName = pickArg(args, 3, null); } /** Returns the i-th argument if it exists (otherwise the provided default). */ private String pickArg(String[] args, int i, String defaultValue) { if (i >= args.length) { return defaultValue; } return args[i]; } /** {@inheritDoc} */ @Override public String getRelativeFilePath(String path) { String[] parts = path.split("/"); String result = filenamePrefix + parts[parts.length - 1] + filenameSuffix; if (anchorDirectoryName == null) { return result; } String dotsPart = ""; for (int i = parts.length - 2; i >= 0; --i) { dotsPart += "../"; if (parts[i].equalsIgnoreCase(anchorDirectoryName)) { return dotsPart + replacementDirectoryName + "/" + result; } result = parts[i] + "/" + result; } // No anchor found return null; } }
apache-2.0
Intera/urlaubsverwaltung
src/test/java/org/synyx/urlaubsverwaltung/restapi/workday/WorkDayControllerTest.java
6899
package org.synyx.urlaubsverwaltung.restapi.workday; import org.joda.time.DateMidnight; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.synyx.urlaubsverwaltung.core.period.DayLength; import org.synyx.urlaubsverwaltung.core.person.Person; import org.synyx.urlaubsverwaltung.core.person.PersonService; import org.synyx.urlaubsverwaltung.core.workingtime.WorkDaysService; import org.synyx.urlaubsverwaltung.restapi.ApiExceptionHandlerControllerAdvice; import org.synyx.urlaubsverwaltung.test.TestDataCreator; import java.math.BigDecimal; import java.util.Optional; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup; import static org.synyx.urlaubsverwaltung.core.period.DayLength.FULL; /** * @author Aljona Murygina - murygina@synyx.de */ @RunWith(MockitoJUnitRunner.class) public class WorkDayControllerTest { private WorkDayController sut; @Mock private PersonService personServiceMock; @Mock private WorkDaysService workDaysServiceMock; @Before public void setUp() { sut = new WorkDayController(personServiceMock, workDaysServiceMock); } @Test public void ensureReturnsWorkDays() throws Exception { Person person = TestDataCreator.createPerson(); when(personServiceMock.getPersonByID(anyInt())).thenReturn(Optional.of(person)); when(workDaysServiceMock.getWorkDays(any(DayLength.class), any(DateMidnight.class), any(DateMidnight.class), any(Person.class))) .thenReturn(BigDecimal.ONE); perform(get("/api/workdays") .param("from", "2016-01-04") .param("to", "2016-01-04") .param("length", "FULL") .param("person", "23")) .andExpect(status().isOk()) .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.response").exists()) .andExpect(jsonPath("$.response.workDays").exists()) .andExpect(jsonPath("$.response.workDays", is("1"))); verify(personServiceMock).getPersonByID(23); verify(workDaysServiceMock).getWorkDays(FULL, new DateMidnight(2016, 1, 4), new DateMidnight(2016, 1, 4), person); } @Test public void ensureBadRequestForMissingFromParameter() throws Exception { perform(get("/api/workdays") .param("to", "2016-01-06") .param("length", "FULL") .param("person", "23")) .andExpect(status().isBadRequest()); } @Test public void ensureBadRequestForInvalidFromParameter() throws Exception { perform(get("/api/workdays") .param("from", "foo") .param("to", "2016-01-06") .param("length", "FULL") .param("person", "23")) .andExpect(status().isBadRequest()); } @Test public void ensureBadRequestForMissingToParameter() throws Exception { perform(get("/api/workdays") .param("from", "2016-01-01") .param("length", "FULL") .param("person", "23")) .andExpect(status().isBadRequest()); } @Test public void ensureBadRequestForInvalidToParameter() throws Exception { perform(get("/api/workdays") .param("from", "2016-01-01") .param("to", "foo") .param("length", "FULL") .param("person", "23")) .andExpect(status().isBadRequest()); } @Test public void ensureBadRequestForMissingPersonParameter() throws Exception { perform(get("/api/workdays") .param("from", "2016-01-01") .param("to", "2016-01-06") .param("length", "FULL")) .andExpect(status().isBadRequest()); } @Test public void ensureBadRequestForInvalidPersonParameter() throws Exception { perform(get("/api/workdays") .param("from", "2016-01-01") .param("to", "2016-01-06") .param("length", "FULL") .param("person", "foo")) .andExpect(status().isBadRequest()); } @Test public void ensureBadRequestIfThereIsNoPersonForGivenID() throws Exception { when(personServiceMock.getPersonByID(anyInt())).thenReturn(Optional.empty()); perform(get("/api/workdays") .param("from", "2016-01-01") .param("to", "2016-01-06") .param("length", "FULL") .param("person", "23")) .andExpect(status().isBadRequest()); verify(personServiceMock).getPersonByID(23); } @Test public void ensureBadRequestForMissingLengthParameter() throws Exception { perform(get("/api/workdays") .param("from", "2016-01-01") .param("to", "2016-01-06") .param("person", "23")) .andExpect(status().isBadRequest()); } @Test public void ensureBadRequestForInvalidLengthParameter() throws Exception { Person person = TestDataCreator.createPerson("muster"); when(personServiceMock.getPersonByID(anyInt())).thenReturn(Optional.of(person)); perform(get("/api/workdays") .param("from", "2016-01-01") .param("to", "2016-01-06") .param("length", "FOO") .param("person", "23")) .andExpect(status().isBadRequest()); } @Test public void ensureBadRequestForInvalidPeriod() throws Exception { perform(get("/api/workdays") .param("from", "2016-01-01") .param("to", "2015-01-06") .param("length", "FULL") .param("person", "23")) .andExpect(status().isBadRequest()); } private ResultActions perform(MockHttpServletRequestBuilder builder) throws Exception { return standaloneSetup(sut).setControllerAdvice(new ApiExceptionHandlerControllerAdvice()).build().perform(builder); } }
apache-2.0
googleads/googleads-java-lib
modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201809/cm/ReportDefinitionError.java
5556
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. /** * ReportDefinitionError.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.adwords.axis.v201809.cm; /** * Encapsulates the errors that can be thrown during {@link ReportDefinition} * mutate operation. */ public class ReportDefinitionError extends com.google.api.ads.adwords.axis.v201809.cm.ApiError implements java.io.Serializable { private com.google.api.ads.adwords.axis.v201809.cm.ReportDefinitionErrorReason reason; public ReportDefinitionError() { } public ReportDefinitionError( java.lang.String fieldPath, com.google.api.ads.adwords.axis.v201809.cm.FieldPathElement[] fieldPathElements, java.lang.String trigger, java.lang.String errorString, java.lang.String apiErrorType, com.google.api.ads.adwords.axis.v201809.cm.ReportDefinitionErrorReason reason) { super( fieldPath, fieldPathElements, trigger, errorString, apiErrorType); this.reason = reason; } @Override public String toString() { return com.google.common.base.MoreObjects.toStringHelper(this.getClass()) .omitNullValues() .add("apiErrorType", getApiErrorType()) .add("errorString", getErrorString()) .add("fieldPath", getFieldPath()) .add("fieldPathElements", getFieldPathElements()) .add("reason", getReason()) .add("trigger", getTrigger()) .toString(); } /** * Gets the reason value for this ReportDefinitionError. * * @return reason */ public com.google.api.ads.adwords.axis.v201809.cm.ReportDefinitionErrorReason getReason() { return reason; } /** * Sets the reason value for this ReportDefinitionError. * * @param reason */ public void setReason(com.google.api.ads.adwords.axis.v201809.cm.ReportDefinitionErrorReason reason) { this.reason = reason; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof ReportDefinitionError)) return false; ReportDefinitionError other = (ReportDefinitionError) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.reason==null && other.getReason()==null) || (this.reason!=null && this.reason.equals(other.getReason()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); if (getReason() != null) { _hashCode += getReason().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(ReportDefinitionError.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "ReportDefinitionError")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("reason"); elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "reason")); elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201809", "ReportDefinitionError.Reason")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
apache-2.0
mifos/1.5.x
application/src/test/java/org/mifos/reports/business/BranchReportParameterFormTest.java
3078
/* * Copyright (c) 2005-2010 Grameen Foundation USA * 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. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.reports.business; import static org.easymock.classextension.EasyMock.replay; import static org.easymock.classextension.EasyMock.verify; import static org.mifos.reports.ui.SelectionItem.SELECT_BRANCH_OFFICE_SELECTION_ITEM; import org.mifos.framework.exceptions.ApplicationException; import org.mifos.framework.exceptions.SystemException; import org.mifos.reports.util.helpers.ReportValidationConstants; public class BranchReportParameterFormTest extends AbstractReportParametersTest { public BranchReportParameterFormTest() throws SystemException, ApplicationException { super(); } private static final String VALID_BRANCH_REPORT_DATE = "21/01/2007"; private static final String INVALID_BRANCH_REPORT_DATE = "01/21/2007"; public void testValidatorReturnsErrorIfBranchIdIsSelect() throws Exception { reportParams = new BranchReportParameterForm(String.valueOf(SELECT_BRANCH_OFFICE_SELECTION_ITEM.getId()), VALID_BRANCH_REPORT_DATE); errorsMock.rejectValue(ReportValidationConstants.BRANCH_ID_PARAM, ReportValidationConstants.BRANCH_ID_INVALID_MSG); replay(errorsMock); reportParams.validate(errorsMock); verify(errorsMock); } public void testValidatorReturnsErrorIfReportDateIsEmpty() throws Exception { reportParams = new BranchReportParameterForm(VALID_ID, ""); errorsMock .rejectValue(ReportValidationConstants.RUN_DATE_PARAM, ReportValidationConstants.RUN_DATE_INVALID_MSG); replay(errorsMock); reportParams.validate(errorsMock); verify(errorsMock); } public void testReportDateFormatIsInvalid() throws Exception { reportParams = new BranchReportParameterForm(VALID_ID, INVALID_BRANCH_REPORT_DATE); errorsMock .rejectValue(ReportValidationConstants.RUN_DATE_PARAM, ReportValidationConstants.RUN_DATE_INVALID_MSG); replay(errorsMock); reportParams.validate(errorsMock); verify(errorsMock); } public void testReportDateFormatIsValid() throws Exception { reportParams = new BranchReportParameterForm(VALID_ID, VALID_BRANCH_REPORT_DATE); replay(errorsMock); reportParams.validate(errorsMock); verify(errorsMock); } }
apache-2.0
sernaleon/charlie
Others/ClienteRobot/src/asl/clienterobot/DatagramCommands.java
384
package asl.clienterobot; public class DatagramCommands { public static final byte ON = 1; public static final byte OFF = 0; public static final byte NOPARAM = 0; public static final byte STOP = 0; public static final byte MOVE_FORWARD = 1; public static final byte MOVE_BACKWARD = 2; public static final byte BEEP = 3; public static final byte LED = 4; }
apache-2.0
mavas/lifelogger
src/org/olimar/klog/PhotoHandler.java
1542
package org.olimar.klog; import java.io.File; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.Date; import android.content.ContentValues; import android.content.Context; import android.hardware.Camera; import android.hardware.Camera.PictureCallback; import android.database.sqlite.SQLiteDatabase; import android.os.Environment; import android.util.Log; import android.widget.Toast; /** Takes care of storing picture data after picture taken. * * Handles data either via directory files or SQLite database. * * @author David Kilgore */ public class PhotoHandler implements PictureCallback { private final Context context; private final static String TAG = "KLOG"; public PhotoHandler(Context context) { this.context = context; } @Override public void onPictureTaken(byte[] data, Camera camera) { Log.d(TAG, "Starting to insert photo."); sqliteHandle(data, camera); } private void sqliteHandle(byte[] data, Camera camera) { SQLiteDatabase db = (new SQLiteHelper(this.context)).getWritableDatabase(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss"); String date = dateFormat.format(new Date()); ContentValues values = new ContentValues(); values.put(SQLiteHelper.COLUMN_PHOTO, data); values.put(SQLiteHelper.COLUMN_WHEN, date); long insertID = db.insert(SQLiteHelper.TABLE_PHOTOS, null, values); Log.d(TAG, "Done inserting photo."); } }
apache-2.0
BeeShield/AndroidPicker
library/src/main/java/uk/co/senab/photoview/IPhotoView.java
12568
/******************************************************************************* * 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 uk.co.senab.photoview; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.view.GestureDetector; import android.view.View; import android.widget.ImageView; public interface IPhotoView { float DEFAULT_MAX_SCALE = 3.0f; float DEFAULT_MID_SCALE = 1.75f; float DEFAULT_MIN_SCALE = 1.0f; int DEFAULT_ZOOM_DURATION = 200; /** * Returns true if the PhotoView is set to allow zooming of Photos. * * @return true if the PhotoView allows zooming. */ boolean canZoom(); /** * Gets the Display Rectangle of the currently displayed Drawable. The Rectangle is relative to * this View and includes all scaling and translations. * * @return - RectF of Displayed Drawable */ RectF getDisplayRect(); /** * Sets the Display Matrix of the currently displayed Drawable. The Rectangle is considered * relative to this View and includes all scaling and translations. * * @param finalMatrix target matrix to set PhotoView to * @return - true if rectangle was applied successfully */ boolean setDisplayMatrix(Matrix finalMatrix); /** * Gets the Display Matrix of the currently displayed Drawable. The Rectangle is considered * relative to this View and includes all scaling and translations. * * @return copy of current Display Matrix */ Matrix getDisplayMatrix(); /** * Copies the Display Matrix of the currently displayed Drawable. The Rectangle is considered * relative to this View and includes all scaling and translations. * * @param matrix target matrix to copy to */ void getDisplayMatrix(Matrix matrix); /** * Use {@link #getMinimumScale()} instead, this will be removed in future release * * @return The current minimum scale level. What this value represents depends on the current * {@link ImageView.ScaleType}. */ @Deprecated float getMinScale(); /** * @return The current minimum scale level. What this value represents depends on the current * {@link ImageView.ScaleType}. */ float getMinimumScale(); /** * Use {@link #getMediumScale()} instead, this will be removed in future release * * @return The current middle scale level. What this value represents depends on the current * {@link ImageView.ScaleType}. */ @Deprecated float getMidScale(); /** * @return The current medium scale level. What this value represents depends on the current * {@link ImageView.ScaleType}. */ float getMediumScale(); /** * Use {@link #getMaximumScale()} instead, this will be removed in future release * * @return The current maximum scale level. What this value represents depends on the current * {@link ImageView.ScaleType}. */ @Deprecated float getMaxScale(); /** * @return The current maximum scale level. What this value represents depends on the current * {@link ImageView.ScaleType}. */ float getMaximumScale(); /** * Returns the current scale value * * @return float - current scale value */ float getScale(); /** * Return the current scale type in use by the ImageView. * * @return current ImageView.ScaleType */ ImageView.ScaleType getScaleType(); /** * Whether to allow the ImageView's parent to intercept the touch event when the photo is scroll * to it's horizontal edge. * * @param allow whether to allow intercepting by parent element or not */ void setAllowParentInterceptOnEdge(boolean allow); /** * Use {@link #setMinimumScale(float minimumScale)} instead, this will be removed in future * release * <p>&nbsp;</p> * Sets the minimum scale level. What this value represents depends on the current {@link * ImageView.ScaleType}. * * @param minScale minimum allowed scale */ @Deprecated void setMinScale(float minScale); /** * Sets the minimum scale level. What this value represents depends on the current {@link * ImageView.ScaleType}. * * @param minimumScale minimum allowed scale */ void setMinimumScale(float minimumScale); /** * Use {@link #setMediumScale(float mediumScale)} instead, this will be removed in future * release * <p>&nbsp;</p> * Sets the middle scale level. What this value represents depends on the current {@link * ImageView.ScaleType}. * * @param midScale medium scale preset */ @Deprecated void setMidScale(float midScale); /** * Sets the medium scale level. What this value represents depends on the current {@link ImageView.ScaleType}. * * @param mediumScale medium scale preset */ void setMediumScale(float mediumScale); /** * Use {@link #setMaximumScale(float maximumScale)} instead, this will be removed in future * release * <p>&nbsp;</p> * Sets the maximum scale level. What this value represents depends on the current {@link * ImageView.ScaleType}. * * @param maxScale maximum allowed scale preset */ @Deprecated void setMaxScale(float maxScale); /** * Sets the maximum scale level. What this value represents depends on the current {@link * ImageView.ScaleType}. * * @param maximumScale maximum allowed scale preset */ void setMaximumScale(float maximumScale); /** * Allows to set all three scale levels at once, so you don't run into problem with setting * medium/minimum scale before the maximum one * * @param minimumScale minimum allowed scale * @param mediumScale medium allowed scale * @param maximumScale maximum allowed scale preset */ void setScaleLevels(float minimumScale, float mediumScale, float maximumScale); /** * Register a callback to be invoked when the Photo displayed by this view is long-pressed. * * @param listener - Listener to be registered. */ void setOnLongClickListener(View.OnLongClickListener listener); /** * Register a callback to be invoked when the Matrix has changed for this View. An example would * be the user panning or scaling the Photo. * * @param listener - Listener to be registered. */ void setOnMatrixChangeListener(PhotoViewAttacher.OnMatrixChangedListener listener); /** * Register a callback to be invoked when the Photo displayed by this View is tapped with a * single tap. * * @param listener - Listener to be registered. */ void setOnPhotoTapListener(PhotoViewAttacher.OnPhotoTapListener listener); /** * PhotoViewAttacher.OnPhotoTapListener reference should be stored in a variable instead, this * will be removed in future release. * <p>&nbsp;</p> * Returns a listener to be invoked when the Photo displayed by this View is tapped with a * single tap. * * @return PhotoViewAttacher.OnPhotoTapListener currently set, may be null */ @Deprecated PhotoViewAttacher.OnPhotoTapListener getOnPhotoTapListener(); /** * Register a callback to be invoked when the View is tapped with a single tap. * * @param listener - Listener to be registered. */ void setOnViewTapListener(PhotoViewAttacher.OnViewTapListener listener); /** * Enables rotation via PhotoView internal functions. * * @param rotationDegree - Degree to rotate PhotoView to, should be in range 0 to 360 */ void setRotationTo(float rotationDegree); /** * Enables rotation via PhotoView internal functions. * * @param rotationDegree - Degree to rotate PhotoView by, should be in range 0 to 360 */ void setRotationBy(float rotationDegree); /** * PhotoViewAttacher.OnViewTapListener reference should be stored in a variable instead, this * will be removed in future release. * <p>&nbsp;</p> * Returns a callback listener to be invoked when the View is tapped with a single tap. * * @return PhotoViewAttacher.OnViewTapListener currently set, may be null */ @Deprecated PhotoViewAttacher.OnViewTapListener getOnViewTapListener(); /** * Changes the current scale to the specified value. * * @param scale - Value to scale to */ void setScale(float scale); /** * Changes the current scale to the specified value. * * @param scale - Value to scale to * @param animate - Whether to animate the scale */ void setScale(float scale, boolean animate); /** * Changes the current scale to the specified value, around the given focal point. * * @param scale - Value to scale to * @param focalX - X Focus Point * @param focalY - Y Focus Point * @param animate - Whether to animate the scale */ void setScale(float scale, float focalX, float focalY, boolean animate); /** * Controls how the image should be resized or moved to match the size of the ImageView. Any * scaling or panning will happen within the confines of this {@link * ImageView.ScaleType}. * * @param scaleType - The desired scaling mode. */ void setScaleType(ImageView.ScaleType scaleType); /** * Allows you to enable/disable the zoom functionality on the ImageView. When disable the * ImageView reverts to using the FIT_CENTER matrix. * * @param zoomable - Whether the zoom functionality is enabled. */ void setZoomable(boolean zoomable); /** * Enables rotation via PhotoView internal functions. Name is chosen so it won't collide with * View.setRotation(float) in API since 11 * * @param rotationDegree - Degree to rotate PhotoView to, should be in range 0 to 360 * @deprecated use {@link #setRotationTo(float)} */ void setPhotoViewRotation(float rotationDegree); /** * Extracts currently visible area to Bitmap object, if there is no image loaded yet or the * ImageView is already destroyed, returns {@code null} * * @return currently visible area as bitmap or null */ Bitmap getVisibleRectangleBitmap(); /** * Allows to change zoom transition speed, default value is 200 (PhotoViewAttacher.DEFAULT_ZOOM_DURATION). * Will default to 200 if provided negative value * * @param milliseconds duration of zoom interpolation */ void setZoomTransitionDuration(int milliseconds); /** * Will return instance of IPhotoView (eg. PhotoViewAttacher), can be used to provide better * integration * * @return IPhotoView implementation instance if available, null if not */ IPhotoView getIPhotoViewImplementation(); /** * Sets custom double tap listener, to intercept default given functions. To reset behavior to * default, you can just pass in "null" or public field of PhotoViewAttacher.defaultOnDoubleTapListener * * @param newOnDoubleTapListener custom OnDoubleTapListener to be set on ImageView */ void setOnDoubleTapListener(GestureDetector.OnDoubleTapListener newOnDoubleTapListener); /** * Will report back about scale changes * * @param onScaleChangeListener OnScaleChangeListener instance */ void setOnScaleChangeListener(PhotoViewAttacher.OnScaleChangeListener onScaleChangeListener); /** * Will report back about fling(single touch) * * @param onSingleFlingListener OnSingleFlingListener instance */ void setOnSingleFlingListener(PhotoViewAttacher.OnSingleFlingListener onSingleFlingListener); }
apache-2.0
griffon/griffon-pivot-plugin
src/main/griffon/pivot/support/adapters/TextAreaContentAdapter.java
2690
/* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package griffon.pivot.support.adapters; import groovy.lang.Closure; /** * @author Andres Almiray */ public class TextAreaContentAdapter implements GriffonPivotAdapter, org.apache.pivot.wtk.TextAreaContentListener { private Closure textChanged; private Closure paragraphInserted; private Closure paragraphsRemoved; public Closure getTextChanged() { return this.textChanged; } public Closure getParagraphInserted() { return this.paragraphInserted; } public Closure getParagraphsRemoved() { return this.paragraphsRemoved; } public void setTextChanged(Closure textChanged) { this.textChanged = textChanged; if (this.textChanged != null) { this.textChanged.setDelegate(this); this.textChanged.setResolveStrategy(Closure.DELEGATE_FIRST); } } public void setParagraphInserted(Closure paragraphInserted) { this.paragraphInserted = paragraphInserted; if (this.paragraphInserted != null) { this.paragraphInserted.setDelegate(this); this.paragraphInserted.setResolveStrategy(Closure.DELEGATE_FIRST); } } public void setParagraphsRemoved(Closure paragraphsRemoved) { this.paragraphsRemoved = paragraphsRemoved; if (this.paragraphsRemoved != null) { this.paragraphsRemoved.setDelegate(this); this.paragraphsRemoved.setResolveStrategy(Closure.DELEGATE_FIRST); } } public void textChanged(org.apache.pivot.wtk.TextArea arg0) { if (textChanged != null) { textChanged.call(arg0); } } public void paragraphInserted(org.apache.pivot.wtk.TextArea arg0, int arg1) { if (paragraphInserted != null) { paragraphInserted.call(arg0, arg1); } } public void paragraphsRemoved(org.apache.pivot.wtk.TextArea arg0, int arg1, org.apache.pivot.collections.Sequence arg2) { if (paragraphsRemoved != null) { paragraphsRemoved.call(arg0, arg1, arg2); } } }
apache-2.0
bcopy/opc-ua-stack
stack-core/src/main/java/com/digitalpetri/opcua/stack/core/types/structured/ReadProcessedDetails.java
3567
package com.digitalpetri.opcua.stack.core.types.structured; import com.digitalpetri.opcua.stack.core.Identifiers; import com.digitalpetri.opcua.stack.core.serialization.DelegateRegistry; import com.digitalpetri.opcua.stack.core.serialization.UaDecoder; import com.digitalpetri.opcua.stack.core.serialization.UaEncoder; import com.digitalpetri.opcua.stack.core.types.builtin.DateTime; import com.digitalpetri.opcua.stack.core.types.builtin.NodeId; public class ReadProcessedDetails extends HistoryReadDetails { public static final NodeId TypeId = Identifiers.ReadProcessedDetails; public static final NodeId BinaryEncodingId = Identifiers.ReadProcessedDetails_Encoding_DefaultBinary; public static final NodeId XmlEncodingId = Identifiers.ReadProcessedDetails_Encoding_DefaultXml; protected final DateTime _startTime; protected final DateTime _endTime; protected final Double _processingInterval; protected final NodeId[] _aggregateType; protected final AggregateConfiguration _aggregateConfiguration; public ReadProcessedDetails(DateTime _startTime, DateTime _endTime, Double _processingInterval, NodeId[] _aggregateType, AggregateConfiguration _aggregateConfiguration) { super(); this._startTime = _startTime; this._endTime = _endTime; this._processingInterval = _processingInterval; this._aggregateType = _aggregateType; this._aggregateConfiguration = _aggregateConfiguration; } public DateTime getStartTime() { return _startTime; } public DateTime getEndTime() { return _endTime; } public Double getProcessingInterval() { return _processingInterval; } public NodeId[] getAggregateType() { return _aggregateType; } public AggregateConfiguration getAggregateConfiguration() { return _aggregateConfiguration; } @Override public NodeId getTypeId() { return TypeId; } @Override public NodeId getBinaryEncodingId() { return BinaryEncodingId; } @Override public NodeId getXmlEncodingId() { return XmlEncodingId; } public static void encode(ReadProcessedDetails readProcessedDetails, UaEncoder encoder) { encoder.encodeDateTime("StartTime", readProcessedDetails._startTime); encoder.encodeDateTime("EndTime", readProcessedDetails._endTime); encoder.encodeDouble("ProcessingInterval", readProcessedDetails._processingInterval); encoder.encodeArray("AggregateType", readProcessedDetails._aggregateType, encoder::encodeNodeId); encoder.encodeSerializable("AggregateConfiguration", readProcessedDetails._aggregateConfiguration); } public static ReadProcessedDetails decode(UaDecoder decoder) { DateTime _startTime = decoder.decodeDateTime("StartTime"); DateTime _endTime = decoder.decodeDateTime("EndTime"); Double _processingInterval = decoder.decodeDouble("ProcessingInterval"); NodeId[] _aggregateType = decoder.decodeArray("AggregateType", decoder::decodeNodeId, NodeId.class); AggregateConfiguration _aggregateConfiguration = decoder.decodeSerializable("AggregateConfiguration", AggregateConfiguration.class); return new ReadProcessedDetails(_startTime, _endTime, _processingInterval, _aggregateType, _aggregateConfiguration); } static { DelegateRegistry.registerEncoder(ReadProcessedDetails::encode, ReadProcessedDetails.class, BinaryEncodingId, XmlEncodingId); DelegateRegistry.registerDecoder(ReadProcessedDetails::decode, ReadProcessedDetails.class, BinaryEncodingId, XmlEncodingId); } }
apache-2.0
ceylon/ceylon
compiler-java/langtools/src/share/classes/org/eclipse/ceylon/langtools/source/tree/AnnotationTree.java
1714
/* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.eclipse.ceylon.langtools.source.tree; import java.util.List; /** * A tree node for an annotation. * * For example: * <pre> * {@code @}<em>annotationType</em> * {@code @}<em>annotationType</em> ( <em>arguments</em> ) * </pre> * * @jls section 9.7 * * @author Peter von der Ah&eacute; * @author Jonathan Gibbons * @since 1.6 */ public interface AnnotationTree extends ExpressionTree { Tree getAnnotationType(); List<? extends ExpressionTree> getArguments(); }
apache-2.0
aws/aws-sdk-java-v2
core/sdk-core/src/main/java/software/amazon/awssdk/core/client/config/SdkClientOptionValidation.java
2849
/* * Copyright 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 software.amazon.awssdk.core.client.config; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.Validate; /** * A set of static methods used to validate that a {@link SdkClientConfiguration} contains all of * the values required for the SDK to function. */ @SdkProtectedApi public class SdkClientOptionValidation { protected SdkClientOptionValidation() { } public static void validateAsyncClientOptions(SdkClientConfiguration c) { require("asyncConfiguration.advancedOption[FUTURE_COMPLETION_EXECUTOR]", c.option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR)); require("asyncHttpClient", c.option(SdkClientOption.ASYNC_HTTP_CLIENT)); validateClientOptions(c); } public static void validateSyncClientOptions(SdkClientConfiguration c) { require("syncHttpClient", c.option(SdkClientOption.SYNC_HTTP_CLIENT)); validateClientOptions(c); } private static void validateClientOptions(SdkClientConfiguration c) { require("endpoint", c.option(SdkClientOption.ENDPOINT)); require("overrideConfiguration.additionalHttpHeaders", c.option(SdkClientOption.ADDITIONAL_HTTP_HEADERS)); require("overrideConfiguration.executionInterceptors", c.option(SdkClientOption.EXECUTION_INTERCEPTORS)); require("overrideConfiguration.retryPolicy", c.option(SdkClientOption.RETRY_POLICY)); require("overrideConfiguration.advancedOption[SIGNER]", c.option(SdkAdvancedClientOption.SIGNER)); require("overrideConfiguration.advancedOption[USER_AGENT_PREFIX]", c.option(SdkAdvancedClientOption.USER_AGENT_PREFIX)); require("overrideConfiguration.advancedOption[USER_AGENT_SUFFIX]", c.option(SdkAdvancedClientOption.USER_AGENT_SUFFIX)); require("overrideConfiguration.advancedOption[CRC32_FROM_COMPRESSED_DATA_ENABLED]", c.option(SdkClientOption.CRC32_FROM_COMPRESSED_DATA_ENABLED)); } /** * Validate that the customer set the provided field. */ protected static <U> U require(String field, U required) { return Validate.notNull(required, "The '%s' must be configured in the client builder.", field); } }
apache-2.0