repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
SES-fortiss/SmartGridCoSimulation
core/cim15/src/CIM15/IEC61970/Informative/InfAssets/Cabinet.java
641
/** */ package CIM15.IEC61970.Informative.InfAssets; import CIM15.IEC61968.Assets.AssetContainer; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Cabinet</b></em>'. * <!-- end-user-doc --> * * * @generated */ public class Cabinet extends AssetContainer { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Cabinet() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return InfAssetsPackage.eINSTANCE.getCabinet(); } } // Cabinet
apache-2.0
manzoli2122/Sae
Sae/src/sae/core/control/ManageAdministradorControl.java
4009
package sae.core.control; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.faces.application.FacesMessage; import javax.inject.Named; import br.ufes.inf.nemo.util.ejb3.application.CrudException; import br.ufes.inf.nemo.util.ejb3.application.CrudService; import br.ufes.inf.nemo.util.ejb3.application.filters.LikeFilter; import br.ufes.inf.nemo.util.ejb3.controller.CrudController; import sae.core.application.ManageAdministradorService; import sae.core.domain.Administrador; /** * Controller class responsible for mediating the communication between user interface and application service for the * use case "Manage Administrador". * * This use case is a CRUD and, thus, the controller also uses the mini CRUD framework for EJB3. * * @author Bruno Manzoli (manzoli2122@gmail.com) */ @Named @SessionScoped public class ManageAdministradorControl extends CrudController<Administrador>{ /** Serialization id. */ private static final long serialVersionUID = 1L; /** The logger. */ private static final Logger logger = Logger.getLogger(ManageAdministradorControl.class.getCanonicalName()); /** The "Manage Administrador" service. */ @EJB private ManageAdministradorService manageAdministradorService; /** CONSTRUTOR DA CLASSE */ public ManageAdministradorControl(){ viewPath = "/core/manageAdministrador/"; bundleName = "msgs"; } /** @see br.ufes.inf.nemo.util.ejb3.controller.CrudController#getCrudService() */ @Override protected CrudService<Administrador> getCrudService() { manageAdministradorService.authorize(); return manageAdministradorService; } /** @see br.ufes.inf.nemo.util.ejb3.controller.CrudController#createNewEntity() */ @Override protected Administrador createNewEntity() { logger.log(Level.FINER, "INITIALIZING AN EMPTY ADMINISTRADOR ......"); Administrador newEntity = new Administrador(); return newEntity; } /** @see br.ufes.inf.nemo.util.ejb3.controller.CrudController#initFilters() */ @Override protected void initFilters() { logger.log(Level.FINER, "INITIALIZING FILTER TYPES ......"); addFilter(new LikeFilter("manageAdministrador.filter.byName", "nome", getI18nMessage(bundleName, "manageAdministrador.text.filter.byName"))); } /** * Saves (create or update) the entity based on the data sent from the form. * Send email in the case create * * @return The view path of the listing if no problems occurred. Otherwise, return error page. */ @Override public String save() { try { logger.log(Level.INFO, "Saving entity..."); // Prepare the entity for saving. prepEntity(); // Checks if we want to create or update the entity. Validates the operation first and stops in case of errors. try { // if create send email cadastro if (selectedEntity.getId() == null) { getCrudService().validateCreate(selectedEntity); getCrudService().create(selectedEntity); manageAdministradorService.sendEmailCadastro(selectedEntity); return list(); } else { getCrudService().validateUpdate(selectedEntity); getCrudService().update(selectedEntity); return list(); } } catch (CrudException crudException) { logger.log(Level.INFO, "CRUD EXCEPCIOMN"); throw new Exception(); } } catch (Exception e) { logger.log(Level.INFO, "EXCEPCION"); selectedEntity.setId(null); addGlobalI18nMessage(getBundleName(), FacesMessage.SEVERITY_ERROR, getBundlePrefix() + ".error.save" , summarizeSelectedEntity() ); return null; } } /** @see br.ufes.inf.nemo.util.ejb3.controller.CrudController#delete() */ @Override public String delete() { try{ return super.delete(); } catch(Exception e){ addGlobalI18nMessage(getBundleName(), FacesMessage.SEVERITY_ERROR, getBundlePrefix() + ".error.delete", summarizeSelectedEntity()); cancelDeletion(); return null; } } }
apache-2.0
Ntipa/ntipa-mashup
src/main/java/com/ipublic/mashup/web/filter/CachingHttpHeadersFilter.java
1512
package com.ipublic.mashup.web.filter; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.concurrent.TimeUnit; /** * This filter is used in production, to put HTTP cache headers with a long (1 month) expiration time. * </p> */ public class CachingHttpHeadersFilter implements Filter { // Cache period is 1 month (in ms) private final static long CACHE_PERIOD = TimeUnit.DAYS.toMillis(31L); // We consider the last modified date is the start up time of the server private final static long LAST_MODIFIED = System.currentTimeMillis(); @Override public void init(FilterConfig filterConfig) throws ServletException { // Nothing to initialize } @Override public void destroy() { // Nothing to destroy } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setHeader("Cache-Control", "max-age=2678400000, public"); httpResponse.setHeader("Pragma", "cache"); // Setting Expires header, for proxy caching httpResponse.setDateHeader("Expires", CACHE_PERIOD + System.currentTimeMillis()); // Setting the Last-Modified header, for browser caching httpResponse.setDateHeader("Last-Modified", LAST_MODIFIED); chain.doFilter(request, response); } }
apache-2.0
s-case/RESTreviews
src/main/java/eu/fp7/scase/reviews/purchase/GetpurchaseHandler.java
4845
/* * ARISTOSTLE UNIVERSITY OF THESSALONIKI * Copyright (C) 2015 * Aristotle University of Thessaloniki * Department of Electrical & Computer Engineering * Division of Electronics & Computer Engineering * Intelligent Systems & Software Engineering Lab * * Project : reviews * WorkFile : * Compiler : * File Description : * Document Description: * Related Documents : * Note : * Programmer : RESTful MDE Engine created by Christoforos Zolotas * Contact : christopherzolotas@issel.ee.auth.gr */ package eu.fp7.scase.reviews.purchase; import javax.ws.rs.core.UriInfo; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import com.sun.jersey.core.util.Base64; import eu.fp7.scase.reviews.account.JavaaccountModel; import eu.fp7.scase.reviews.utilities.HypermediaLink; import eu.fp7.scase.reviews.utilities.HibernateController; /* This class processes GET requests for purchase resources and creates the hypermedia to be returned to the client*/ public class GetpurchaseHandler{ private HibernateController oHibernateController; private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request private JavapurchaseModel oJavapurchaseModel; private String authHeader; private JavaaccountModel oAuthenticationAccount; public GetpurchaseHandler(String authHeader, int purchaseId, UriInfo oApplicationUri){ oJavapurchaseModel = new JavapurchaseModel(); oJavapurchaseModel.setpurchaseId(purchaseId); this.oHibernateController = HibernateController.getHibernateControllerHandle(); this.oApplicationUri = oApplicationUri; this.authHeader = authHeader; this.oAuthenticationAccount = new JavaaccountModel(); } public JavapurchaseModel getJavapurchaseModel(){ //check if there is a non null authentication header if(authHeader == null){ throw new WebApplicationException(Response.Status.FORBIDDEN); } else{ //decode the auth header decodeAuthorizationHeader(); //authenticate the user against the database oAuthenticationAccount = oHibernateController.authenticateUser(oAuthenticationAccount); //check if the authentication failed if(oAuthenticationAccount == null){ throw new WebApplicationException(Response.Status.UNAUTHORIZED); } } return createHypermedia(oHibernateController.getpurchase(oJavapurchaseModel)); } /* This function performs the decoding of the authentication header */ public void decodeAuthorizationHeader() { //check if this request has basic authentication if( !authHeader.contains("Basic ")) { throw new WebApplicationException(Response.Status.BAD_REQUEST); } authHeader = authHeader.substring("Basic ".length()); String[] decodedHeader; decodedHeader = Base64.base64Decode(authHeader).split(":"); if( decodedHeader == null) { throw new WebApplicationException(Response.Status.BAD_REQUEST); } oAuthenticationAccount.setusername(decodedHeader[0]); oAuthenticationAccount.setpassword(decodedHeader[1]); } /* This function produces hypermedia links to be sent to the client so as it will be able to forward the application state in a valid way.*/ public JavapurchaseModel createHypermedia(JavapurchaseModel oJavapurchaseModel){ /* Create hypermedia links towards this specific purchase resource. These can be GET, PUT and/or delete depending on what was specified in the service CIM.*/ oJavapurchaseModel.getlinklist().add(new HypermediaLink(String.format("%s%s", oApplicationUri.getBaseUri(), oApplicationUri.getPath()), "Get the purchase", "GET", "Sibling")); oJavapurchaseModel.getlinklist().add(new HypermediaLink(String.format("%s%s", oApplicationUri.getBaseUri(), oApplicationUri.getPath()), "Delete the purchase", "DELETE", "Sibling")); /* Finally, truncate the current URI so as to point to the resource manager of which this resource is related. Then create the hypermedia links towards the parent resources.*/ int iLastSlashIndex = String.format("%s%s", oApplicationUri.getBaseUri(), oApplicationUri.getPath()).lastIndexOf("/"); oJavapurchaseModel.getlinklist().add(new HypermediaLink(String.format("%s%s", oApplicationUri.getBaseUri(), oApplicationUri.getPath()).substring(0, iLastSlashIndex), "Create a new purchase", "POST", "Parent")); oJavapurchaseModel.getlinklist().add(new HypermediaLink(String.format("%s%s", oApplicationUri.getBaseUri(), oApplicationUri.getPath()).substring(0, iLastSlashIndex), "Get all purchases of this account", "GET", "Parent")); return oJavapurchaseModel; } }
apache-2.0
steschw/bpmn-simulator
bpmn/src/main/java/com/googlecode/bpmn_simulator/bpmn/model/core/common/events/CancelEventDefinition.java
1018
/* * 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.googlecode.bpmn_simulator.bpmn.model.core.common.events; public class CancelEventDefinition extends AbstractEventDefinition { public CancelEventDefinition(final String id) { super(id); } }
apache-2.0
spincast/spincast-framework
spincast-plugins/spincast-plugins-http-client-parent/spincast-plugins-http-client-with-websocket/src/main/java/org/spincast/plugins/httpclient/websocket/utils/SpincastHttpClientWithWebsocketUtils.java
278
package org.spincast.plugins.httpclient.websocket.utils; import org.spincast.plugins.httpclient.utils.SpincastHttpClientUtils; import org.xnio.Xnio; public interface SpincastHttpClientWithWebsocketUtils extends SpincastHttpClientUtils { public Xnio getXnioInstance(); }
apache-2.0
o3project/openflowj-otn
src/main/java/org/projectfloodlight/openflow/protocol/ver14/OFPortDescStatsRequestVer14.java
11306
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University // Copyright (c) 2011, 2012 Open Networking Foundation // Copyright (c) 2012, 2013 Big Switch Networks, Inc. // This library was generated by the LoxiGen Compiler. // See the file LICENSE.txt which should have been included in the source distribution // Automatically generated by LOXI from template of_class.java // Do not modify package org.projectfloodlight.openflow.protocol.ver14; import org.projectfloodlight.openflow.protocol.*; import org.projectfloodlight.openflow.protocol.action.*; import org.projectfloodlight.openflow.protocol.actionid.*; import org.projectfloodlight.openflow.protocol.bsntlv.*; import org.projectfloodlight.openflow.protocol.errormsg.*; import org.projectfloodlight.openflow.protocol.meterband.*; import org.projectfloodlight.openflow.protocol.instruction.*; import org.projectfloodlight.openflow.protocol.instructionid.*; import org.projectfloodlight.openflow.protocol.match.*; import org.projectfloodlight.openflow.protocol.oxm.*; import org.projectfloodlight.openflow.protocol.queueprop.*; import org.projectfloodlight.openflow.types.*; import org.projectfloodlight.openflow.util.*; import org.projectfloodlight.openflow.exceptions.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import com.google.common.collect.ImmutableSet; import org.jboss.netty.buffer.ChannelBuffer; import com.google.common.hash.PrimitiveSink; import com.google.common.hash.Funnel; class OFPortDescStatsRequestVer14 implements OFPortDescStatsRequest { private static final Logger logger = LoggerFactory.getLogger(OFPortDescStatsRequestVer14.class); // version: 1.4 final static byte WIRE_VERSION = 5; final static int LENGTH = 16; private final static long DEFAULT_XID = 0x0L; private final static Set<OFStatsRequestFlags> DEFAULT_FLAGS = ImmutableSet.<OFStatsRequestFlags>of(); // OF message fields private final long xid; private final Set<OFStatsRequestFlags> flags; // // Immutable default instance final static OFPortDescStatsRequestVer14 DEFAULT = new OFPortDescStatsRequestVer14( DEFAULT_XID, DEFAULT_FLAGS ); // package private constructor - used by readers, builders, and factory OFPortDescStatsRequestVer14(long xid, Set<OFStatsRequestFlags> flags) { if(flags == null) { throw new NullPointerException("OFPortDescStatsRequestVer14: property flags cannot be null"); } this.xid = xid; this.flags = flags; } // Accessors for OF message fields @Override public OFVersion getVersion() { return OFVersion.OF_14; } @Override public OFType getType() { return OFType.STATS_REQUEST; } @Override public long getXid() { return xid; } @Override public OFStatsType getStatsType() { return OFStatsType.PORT_DESC; } @Override public Set<OFStatsRequestFlags> getFlags() { return flags; } public OFPortDescStatsRequest.Builder createBuilder() { return new BuilderWithParent(this); } static class BuilderWithParent implements OFPortDescStatsRequest.Builder { final OFPortDescStatsRequestVer14 parentMessage; // OF message fields private boolean xidSet; private long xid; private boolean flagsSet; private Set<OFStatsRequestFlags> flags; BuilderWithParent(OFPortDescStatsRequestVer14 parentMessage) { this.parentMessage = parentMessage; } @Override public OFVersion getVersion() { return OFVersion.OF_14; } @Override public OFType getType() { return OFType.STATS_REQUEST; } @Override public long getXid() { return xid; } @Override public OFPortDescStatsRequest.Builder setXid(long xid) { this.xid = xid; this.xidSet = true; return this; } @Override public OFStatsType getStatsType() { return OFStatsType.PORT_DESC; } @Override public Set<OFStatsRequestFlags> getFlags() { return flags; } @Override public OFPortDescStatsRequest.Builder setFlags(Set<OFStatsRequestFlags> flags) { this.flags = flags; this.flagsSet = true; return this; } @Override public OFPortDescStatsRequest build() { long xid = this.xidSet ? this.xid : parentMessage.xid; Set<OFStatsRequestFlags> flags = this.flagsSet ? this.flags : parentMessage.flags; if(flags == null) throw new NullPointerException("Property flags must not be null"); // return new OFPortDescStatsRequestVer14( xid, flags ); } } static class Builder implements OFPortDescStatsRequest.Builder { // OF message fields private boolean xidSet; private long xid; private boolean flagsSet; private Set<OFStatsRequestFlags> flags; @Override public OFVersion getVersion() { return OFVersion.OF_14; } @Override public OFType getType() { return OFType.STATS_REQUEST; } @Override public long getXid() { return xid; } @Override public OFPortDescStatsRequest.Builder setXid(long xid) { this.xid = xid; this.xidSet = true; return this; } @Override public OFStatsType getStatsType() { return OFStatsType.PORT_DESC; } @Override public Set<OFStatsRequestFlags> getFlags() { return flags; } @Override public OFPortDescStatsRequest.Builder setFlags(Set<OFStatsRequestFlags> flags) { this.flags = flags; this.flagsSet = true; return this; } // @Override public OFPortDescStatsRequest build() { long xid = this.xidSet ? this.xid : DEFAULT_XID; Set<OFStatsRequestFlags> flags = this.flagsSet ? this.flags : DEFAULT_FLAGS; if(flags == null) throw new NullPointerException("Property flags must not be null"); return new OFPortDescStatsRequestVer14( xid, flags ); } } final static Reader READER = new Reader(); static class Reader implements OFMessageReader<OFPortDescStatsRequest> { @Override public OFPortDescStatsRequest readFrom(ChannelBuffer bb) throws OFParseError { int start = bb.readerIndex(); // fixed value property version == 5 byte version = bb.readByte(); if(version != (byte) 0x5) throw new OFParseError("Wrong version: Expected=OFVersion.OF_14(5), got="+version); // fixed value property type == 18 byte type = bb.readByte(); if(type != (byte) 0x12) throw new OFParseError("Wrong type: Expected=OFType.STATS_REQUEST(18), got="+type); int length = U16.f(bb.readShort()); if(length != 16) throw new OFParseError("Wrong length: Expected=16(16), got="+length); if(bb.readableBytes() + (bb.readerIndex() - start) < length) { // Buffer does not have all data yet bb.readerIndex(start); return null; } if(logger.isTraceEnabled()) logger.trace("readFrom - length={}", length); long xid = U32.f(bb.readInt()); // fixed value property statsType == 13 short statsType = bb.readShort(); if(statsType != (short) 0xd) throw new OFParseError("Wrong statsType: Expected=OFStatsType.PORT_DESC(13), got="+statsType); Set<OFStatsRequestFlags> flags = OFStatsRequestFlagsSerializerVer14.readFrom(bb); // pad: 4 bytes bb.skipBytes(4); OFPortDescStatsRequestVer14 portDescStatsRequestVer14 = new OFPortDescStatsRequestVer14( xid, flags ); if(logger.isTraceEnabled()) logger.trace("readFrom - read={}", portDescStatsRequestVer14); return portDescStatsRequestVer14; } } public void putTo(PrimitiveSink sink) { FUNNEL.funnel(this, sink); } final static OFPortDescStatsRequestVer14Funnel FUNNEL = new OFPortDescStatsRequestVer14Funnel(); static class OFPortDescStatsRequestVer14Funnel implements Funnel<OFPortDescStatsRequestVer14> { private static final long serialVersionUID = 1L; @Override public void funnel(OFPortDescStatsRequestVer14 message, PrimitiveSink sink) { // fixed value property version = 5 sink.putByte((byte) 0x5); // fixed value property type = 18 sink.putByte((byte) 0x12); // fixed value property length = 16 sink.putShort((short) 0x10); sink.putLong(message.xid); // fixed value property statsType = 13 sink.putShort((short) 0xd); OFStatsRequestFlagsSerializerVer14.putTo(message.flags, sink); // skip pad (4 bytes) } } public void writeTo(ChannelBuffer bb) { WRITER.write(bb, this); } final static Writer WRITER = new Writer(); static class Writer implements OFMessageWriter<OFPortDescStatsRequestVer14> { @Override public void write(ChannelBuffer bb, OFPortDescStatsRequestVer14 message) { // fixed value property version = 5 bb.writeByte((byte) 0x5); // fixed value property type = 18 bb.writeByte((byte) 0x12); // fixed value property length = 16 bb.writeShort((short) 0x10); bb.writeInt(U32.t(message.xid)); // fixed value property statsType = 13 bb.writeShort((short) 0xd); OFStatsRequestFlagsSerializerVer14.writeTo(bb, message.flags); // pad: 4 bytes bb.writeZero(4); } } @Override public String toString() { StringBuilder b = new StringBuilder("OFPortDescStatsRequestVer14("); b.append("xid=").append(xid); b.append(", "); b.append("flags=").append(flags); b.append(")"); return b.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; OFPortDescStatsRequestVer14 other = (OFPortDescStatsRequestVer14) obj; if( xid != other.xid) return false; if (flags == null) { if (other.flags != null) return false; } else if (!flags.equals(other.flags)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * (int) (xid ^ (xid >>> 32)); result = prime * result + ((flags == null) ? 0 : flags.hashCode()); return result; } }
apache-2.0
vishnus1224/RxJavaTeamworkClient
TeamworkApiDemo/app/src/test/java/com/vishnus1224/teamworkapidemo/datastore/ProjectCloudDataStoreTest.java
2157
package com.vishnus1224.teamworkapidemo.datastore; import com.vishnus1224.rxjavateamworkclient.client.ProjectApiClient; import com.vishnus1224.rxjavateamworkclient.model.ProjectResponse; import com.vishnus1224.rxjavateamworkclient.model.ProjectResponseWrapper; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.net.UnknownHostException; import java.util.List; import rx.Observable; import rx.observers.TestSubscriber; import static org.junit.Assert.*; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Created by vishnu on 07/09/16. */ public class ProjectCloudDataStoreTest { @Mock private ProjectApiClient projectApiClient; private ProjectCloudDataStore projectCloudDataStore; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); projectCloudDataStore = new ProjectCloudDataStore(projectApiClient); } @Test public void testGetAllItems() throws Exception { when(projectApiClient.getAllProjects()).thenReturn(Observable.<ProjectResponseWrapper>empty()); Observable<List<ProjectResponse>> observable = projectCloudDataStore.getAllItems(); TestSubscriber testSubscriber = new TestSubscriber(); observable.subscribe(testSubscriber); testSubscriber.assertCompleted(); testSubscriber.assertNoErrors(); testSubscriber.assertTerminalEvent(); verify(projectApiClient).getAllProjects(); } @Test public void testGetAllItemsThrowsUnknownHostException() throws Exception{ when(projectApiClient.getAllProjects()).thenReturn(Observable.<ProjectResponseWrapper>error(new UnknownHostException())); Observable<List<ProjectResponse>> observable = projectCloudDataStore.getAllItems(); TestSubscriber testSubscriber = new TestSubscriber(); observable.subscribe(testSubscriber); testSubscriber.assertError(UnknownHostException.class); testSubscriber.assertTerminalEvent(); verify(projectApiClient).getAllProjects(); } }
apache-2.0
AsierFox/diverjoy-android
app/src/androidTest/java/com/devdream/diverjoy/ExampleInstrumentedTest.java
772
package com.devdream.diverjoy; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.devdream.diverjoy", appContext.getPackageName()); } }
apache-2.0
dokeeffe/auxremote
app/src/main/java/com/bobs/serialcommands/Guide.java
1895
package com.bobs.serialcommands; import com.bobs.mount.Axis; import com.bobs.mount.Mount; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Experimental!! * <p> * Guide pulse commands do not seem to work on my mount. Leaving this here for reference only. * Reverse engineered from INDI celestron driver. */ public class Guide extends MountCommand { private static final Logger LOGGER = LoggerFactory.getLogger(Guide.class); public static final byte MESSAGE_LENGTH = 0x03; public static final byte RESPONSE_LENGTH = 0x01; private final Axis axis; private final int rate; private final int durationCsec; /** * Constructor for a guide pulse command. * rate should be a signed 8-bit integer in the range (-100,100) that represents * the pulse velocity in % of sidereal. "duration_csec" is an unsigned 8-bit integer * (0,255) with the pulse duration in centiseconds (i.e. 1/100 s = 10ms). * The max pulse duration is 2550 ms. * * @param mount * @param rate is a * @param axis the Axis ALT or AZ */ public Guide(Mount mount, int rate, Axis axis, int durationCsec) { super(mount); this.rate = rate; this.axis = axis; this.durationCsec = durationCsec; } @Override public byte[] getCommand() { byte result[] = new byte[8]; result[0] = MC_HC_AUX_COMMAND_PREFIX; result[1] = MESSAGE_LENGTH; if (Axis.ALT == axis) { result[2] = ALT_BOARD; } else { result[2] = AZM_BOARD; } result[3] = MC_PULSE_GUIDE; result[4] = (byte) rate; result[5] = (byte) durationCsec; result[6] = 0x00; result[7] = RESPONSE_LENGTH; return result; } @Override public void handleMessage(byte[] message) { //nothing to do here. } }
apache-2.0
trialmanager/voxce
src/com/Voxce/DAO/FinancialDiscDAO.java
2561
package com.Voxce.DAO; import java.sql.Date; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import org.apache.commons.fileupload.FileItem; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.HibernateTemplate; import com.Voxce.model.FinancialDisc; public class FinancialDiscDAO { private HibernateTemplate hibernateTemplate; List<?> data; public void setSessionFactory(SessionFactory sessionFactory) { this.hibernateTemplate = new HibernateTemplate(sessionFactory); } public int UploadFinancialDisc(FileItem item,FinancialDisc financialdisc,int idnum){ if(item != null){ financialdisc.setData(item.get()); financialdisc.setFilename(item.getName()); financialdisc.setType(item.getContentType()); } if(idnum == 0){ Calendar cal = Calendar.getInstance(); Date oneDate =new java.sql.Date(cal.getTime().getTime() ); financialdisc.setDate_created(oneDate); financialdisc.setDate_modified(oneDate); try{ data=hibernateTemplate.find("FROM FinancialDisc WHERE site_id='"+financialdisc.getSite_id()+"' AND study_id='"+financialdisc.getStudy_id()+"' AND user_id='"+financialdisc.getUser_id()+"' AND signed_dt='"+financialdisc.getSigned_dt()+"' AND received_dt='"+financialdisc.getReceived_dt()+"' AND type_id='"+financialdisc.getReceived_dt()+"'"); }catch(Exception e) { e.printStackTrace(); } if(data.size()!= 0) { System.out.println("Record Found"); return 0; } // Code Does not Exists // else if(data.size()== 0) { hibernateTemplate.saveOrUpdate(financialdisc); return 1; } return 0; } else{ Calendar cal = Calendar.getInstance(); Date oneDate =new java.sql.Date(cal.getTime().getTime() ); financialdisc.setDate_modified(oneDate); try{ hibernateTemplate.saveOrUpdate(financialdisc); return 1; }catch(Exception e) { e.printStackTrace(); return 0; } } } @SuppressWarnings("unchecked") public FinancialDisc find(int id) { try{ data= (List<FinancialDisc>) hibernateTemplate.find("FROM FinancialDisc WHERE financial_disc_id='"+id+"'"); return (FinancialDisc) data.get(0); }catch(Exception e) { return null; } } @SuppressWarnings("unchecked") public List<FinancialDisc> listfinancialdisc(int studyid) { List<FinancialDisc> list=(List<FinancialDisc>) hibernateTemplate.find("FROM FinancialDisc WHERE study_id='"+studyid+"'"); if(list==null) return new ArrayList<FinancialDisc>(); return list; } }
apache-2.0
luoxn28/fight-job
fight-job-admin/src/main/java/com/fight/job/admin/controller/JobApiController.java
1330
package com.fight.job.admin.controller; import com.fight.job.admin.service.JobApiService; import com.fight.job.core.biz.model.RegisterParam; import com.fight.job.core.biz.model.ReturnT; import com.fight.job.core.biz.model.TriggerCallbackParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; /** * JobApiController. */ @Controller @RequestMapping("/jobapi") public class JobApiController { @Autowired private JobApiService jobApiService; @RequestMapping(value = "/register", method = RequestMethod.POST, consumes = "application/json") @ResponseBody public ReturnT<String> register(@RequestBody RegisterParam registryParam) { return jobApiService.register(registryParam); } @RequestMapping(value = "/callback", method = RequestMethod.POST, consumes = "application/json") @ResponseBody public ReturnT<String> callback(@RequestBody List<TriggerCallbackParam> registryParamList) { return jobApiService.callback(registryParamList); } }
apache-2.0
ddwreczycki/Welhome
src/main/java/com/welhome/domain/property/enums/BuildingType.java
950
package com.welhome.domain.property.enums; public enum BuildingType { BLOCK, TOWN_HOUSE, SINGLE_HOUSE, TERRACE_HOUSE, INFILL, APARTMENT, LOFT, ALL; private String name; private BuildingType() { name = toName(); } public String getName() { return name; } private String toName() { String enumName = super.toString(); String readableName = ""; switch(enumName) { case "BLOCK" : { readableName += "Blok"; }break; case "TOWN_HOUSE" : { readableName += "Kamienica"; }break; case "SINGLE_HOUSE" : { readableName += "Dom wolnostojący"; }break; case "TERRACE_HOUSE" : { readableName += "Szeregowiec"; }break; case "INFILL" : { readableName += "Plomba"; }break; case "APARTMENT" : { readableName += "Apartament"; }break; case "LOFT" : { readableName += "Loft"; }break; case "ALL" : { readableName += "Wszystkie"; }break; } //end of switch return readableName; } }
apache-2.0
RackerWilliams/xercesj
src/org/apache/xerces/impl/xs/XSModelImpl.java
33648
/* * 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.xerces.impl.xs; import java.lang.reflect.Array; import java.util.AbstractList; import java.util.Iterator; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.Vector; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.xs.util.StringListImpl; import org.apache.xerces.impl.xs.util.XSNamedMap4Types; import org.apache.xerces.impl.xs.util.XSNamedMapImpl; import org.apache.xerces.impl.xs.util.XSObjectListImpl; import org.apache.xerces.util.SymbolHash; import org.apache.xerces.util.XMLSymbols; import org.apache.xerces.xs.StringList; import org.apache.xerces.xs.XSAttributeDeclaration; import org.apache.xerces.xs.XSAttributeGroupDefinition; import org.apache.xerces.xs.XSConstants; import org.apache.xerces.xs.XSElementDeclaration; import org.apache.xerces.xs.XSIDCDefinition; import org.apache.xerces.xs.XSModel; import org.apache.xerces.xs.XSModelGroupDefinition; import org.apache.xerces.xs.XSNamedMap; import org.apache.xerces.xs.XSNamespaceItem; import org.apache.xerces.xs.XSNamespaceItemList; import org.apache.xerces.xs.XSNotationDeclaration; import org.apache.xerces.xs.XSObject; import org.apache.xerces.xs.XSObjectList; import org.apache.xerces.xs.XSTypeDefinition; /** * Implements XSModel: a read-only interface that represents an XML Schema, * which could be components from different namespaces. * * @xerces.internal * * @author Sandy Gao, IBM * * @version $Id$ */ public final class XSModelImpl extends AbstractList implements XSModel, XSNamespaceItemList { // the max index / the max value of XSObject type private static final short MAX_COMP_IDX = XSTypeDefinition.SIMPLE_TYPE; private static final boolean[] GLOBAL_COMP = {false, // null true, // attribute true, // element true, // type false, // attribute use true, // attribute group true, // group false, // model group false, // particle false, // wildcard true, // idc true, // notation false, // annotation false, // facet false, // multi value facet true, // complex type true // simple type }; // number of grammars/namespaces stored here private final int fGrammarCount; // all target namespaces private final String[] fNamespaces; // all schema grammar objects (for each namespace) private final SchemaGrammar[] fGrammarList; // a map from namespace to schema grammar private final SymbolHash fGrammarMap; // a map from element declaration to its substitution group private final SymbolHash fSubGroupMap; // store a certain kind of components from all namespaces private final XSNamedMap[] fGlobalComponents; // store a certain kind of components from one namespace private final XSNamedMap[][] fNSComponents; // a string list of all the target namespaces. private final StringList fNamespacesList; // store all annotations private XSObjectList fAnnotations = null; // whether there is any IDC in this XSModel private final boolean fHasIDC; /** * Construct an XSModelImpl, by storing some grammars and grammars imported * by them to this object. * * @param grammars the array of schema grammars */ public XSModelImpl(SchemaGrammar[] grammars) { this(grammars, Constants.SCHEMA_VERSION_1_0); } public XSModelImpl(SchemaGrammar[] grammars, short s4sVersion) { // copy namespaces/grammars from the array to our arrays int len = grammars.length; final int initialSize = Math.max(len+1, 5); String[] namespaces = new String[initialSize]; SchemaGrammar[] grammarList = new SchemaGrammar[initialSize]; boolean hasS4S = false; for (int i = 0; i < len; i++) { final SchemaGrammar sg = grammars[i]; final String tns = sg.getTargetNamespace(); namespaces[i] = tns; grammarList[i] = sg; if (tns == SchemaSymbols.URI_SCHEMAFORSCHEMA) { hasS4S = true; } } // If a schema for the schema namespace isn't included, include it here. if (!hasS4S) { namespaces[len] = SchemaSymbols.URI_SCHEMAFORSCHEMA; grammarList[len++] = SchemaGrammar.getS4SGrammar(s4sVersion); } SchemaGrammar sg1, sg2; Vector gs; int i, j, k; // and recursively get all imported grammars, add them to our arrays for (i = 0; i < len; i++) { // get the grammar sg1 = grammarList[i]; gs = sg1.getImportedGrammars(); // for each imported grammar for (j = gs == null ? -1 : gs.size() - 1; j >= 0; j--) { sg2 = (SchemaGrammar)gs.elementAt(j); // check whether this grammar is already in the list for (k = 0; k < len; k++) { if (sg2 == grammarList[k]) { break; } } // if it's not, add it to the list if (k == len) { // ensure the capacity of the arrays if (len == grammarList.length) { String[] newSA = new String[len*2]; System.arraycopy(namespaces, 0, newSA, 0, len); namespaces = newSA; SchemaGrammar[] newGA = new SchemaGrammar[len*2]; System.arraycopy(grammarList, 0, newGA, 0, len); grammarList = newGA; } namespaces[len] = sg2.getTargetNamespace(); grammarList[len] = sg2; len++; } } } fNamespaces = namespaces; fGrammarList = grammarList; boolean hasIDC = false; // establish the mapping from namespace to grammars fGrammarMap = new SymbolHash(len*2); for (i = 0; i < len; i++) { fGrammarMap.put(null2EmptyString(fNamespaces[i]), fGrammarList[i]); // update the idc field if (fGrammarList[i].hasIDConstraints()) { hasIDC = true; } } fHasIDC = hasIDC; fGrammarCount = len; fGlobalComponents = new XSNamedMap[MAX_COMP_IDX+1]; fNSComponents = new XSNamedMap[len][MAX_COMP_IDX+1]; fNamespacesList = new StringListImpl(fNamespaces, fGrammarCount); // build substitution groups fSubGroupMap = buildSubGroups(s4sVersion); } private SymbolHash buildSubGroups_Org(short s4sVersion) { SubstitutionGroupHandler sgHandler = new SubstitutionGroupHandler(null); for (int i = 0 ; i < fGrammarCount; i++) { sgHandler.addSubstitutionGroup(fGrammarList[i].getSubstitutionGroups()); } final XSNamedMap elements = getComponents(XSConstants.ELEMENT_DECLARATION); final int len = elements.getLength(); final SymbolHash subGroupMap = new SymbolHash(len*2); XSElementDecl head; XSElementDeclaration[] subGroup; for (int i = 0; i < len; i++) { head = (XSElementDecl)elements.item(i); subGroup = sgHandler.getSubstitutionGroup(head, s4sVersion); subGroupMap.put(head, subGroup.length > 0 ? new XSObjectListImpl(subGroup, subGroup.length) : XSObjectListImpl.EMPTY_LIST); } return subGroupMap; } private SymbolHash buildSubGroups(short s4sVersion) { SubstitutionGroupHandler sgHandler = new SubstitutionGroupHandler(null); for (int i = 0 ; i < fGrammarCount; i++) { sgHandler.addSubstitutionGroup(fGrammarList[i].getSubstitutionGroups()); } final XSObjectListImpl elements = getGlobalElements(); final int len = elements.getLength(); final SymbolHash subGroupMap = new SymbolHash(len*2); XSElementDecl head; XSElementDeclaration[] subGroup; for (int i = 0; i < len; i++) { head = (XSElementDecl)elements.item(i); subGroup = sgHandler.getSubstitutionGroup(head, s4sVersion); subGroupMap.put(head, subGroup.length > 0 ? new XSObjectListImpl(subGroup, subGroup.length) : XSObjectListImpl.EMPTY_LIST); } return subGroupMap; } private XSObjectListImpl getGlobalElements() { final SymbolHash[] tables = new SymbolHash[fGrammarCount]; int length = 0; for (int i = 0; i < fGrammarCount; i++) { tables[i] = fGrammarList[i].fAllGlobalElemDecls; length += tables[i].getLength(); } if (length == 0) { return XSObjectListImpl.EMPTY_LIST; } final XSObject[] components = new XSObject[length]; int start = 0; for (int i = 0; i < fGrammarCount; i++) { tables[i].getValues(components, start); start += tables[i].getLength(); } return new XSObjectListImpl(components, length); } /** * Convenience method. Returns a list of all namespaces that belong to * this schema. * @return A list of all namespaces that belong to this schema or * <code>null</code> if all components don't have a targetNamespace. */ public StringList getNamespaces() { return fNamespacesList; } /** * A set of namespace schema information information items (of type * <code>XSNamespaceItem</code>), one for each namespace name which * appears as the target namespace of any schema component in the schema * used for that assessment, and one for absent if any schema component * in the schema had no target namespace. For more information see * schema information. */ public XSNamespaceItemList getNamespaceItems() { return this; } /** * Returns a list of top-level components, i.e. element declarations, * attribute declarations, etc. * @param objectType The type of the declaration, i.e. * <code>ELEMENT_DECLARATION</code>. Note that * <code>XSTypeDefinition.SIMPLE_TYPE</code> and * <code>XSTypeDefinition.COMPLEX_TYPE</code> can also be used as the * <code>objectType</code> to retrieve only complex types or simple * types, instead of all types. * @return A list of top-level definitions of the specified type in * <code>objectType</code> or an empty <code>XSNamedMap</code> if no * such definitions exist. */ public synchronized XSNamedMap getComponents(short objectType) { if (objectType <= 0 || objectType > MAX_COMP_IDX || !GLOBAL_COMP[objectType]) { return XSNamedMapImpl.EMPTY_MAP; } SymbolHash[] tables = new SymbolHash[fGrammarCount]; // get all hashtables from all namespaces for this type of components if (fGlobalComponents[objectType] == null) { for (int i = 0; i < fGrammarCount; i++) { switch (objectType) { case XSConstants.TYPE_DEFINITION: case XSTypeDefinition.COMPLEX_TYPE: case XSTypeDefinition.SIMPLE_TYPE: tables[i] = fGrammarList[i].fGlobalTypeDecls; break; case XSConstants.ATTRIBUTE_DECLARATION: tables[i] = fGrammarList[i].fGlobalAttrDecls; break; case XSConstants.ELEMENT_DECLARATION: tables[i] = fGrammarList[i].fGlobalElemDecls; break; case XSConstants.ATTRIBUTE_GROUP: tables[i] = fGrammarList[i].fGlobalAttrGrpDecls; break; case XSConstants.MODEL_GROUP_DEFINITION: tables[i] = fGrammarList[i].fGlobalGroupDecls; break; case XSConstants.NOTATION_DECLARATION: tables[i] = fGrammarList[i].fGlobalNotationDecls; break; case XSConstants.IDENTITY_CONSTRAINT: tables[i] = fGrammarList[i].fGlobalIDConstraintDecls; break; } } // for complex/simple types, create a special implementation, // which take specific types out of the hash table if (objectType == XSTypeDefinition.COMPLEX_TYPE || objectType == XSTypeDefinition.SIMPLE_TYPE) { fGlobalComponents[objectType] = new XSNamedMap4Types(fNamespaces, tables, fGrammarCount, objectType); } else { fGlobalComponents[objectType] = new XSNamedMapImpl(fNamespaces, tables, fGrammarCount); } } return fGlobalComponents[objectType]; } /** * Convenience method. Returns a list of top-level component declarations * that are defined within the specified namespace, i.e. element * declarations, attribute declarations, etc. * @param objectType The type of the declaration, i.e. * <code>ELEMENT_DECLARATION</code>. * @param namespace The namespace to which the declaration belongs or * <code>null</code> (for components with no target namespace). * @return A list of top-level definitions of the specified type in * <code>objectType</code> and defined in the specified * <code>namespace</code> or an empty <code>XSNamedMap</code>. */ public synchronized XSNamedMap getComponentsByNamespace(short objectType, String namespace) { if (objectType <= 0 || objectType > MAX_COMP_IDX || !GLOBAL_COMP[objectType]) { return XSNamedMapImpl.EMPTY_MAP; } // try to find the grammar int i = 0; if (namespace != null) { for (; i < fGrammarCount; ++i) { if (namespace.equals(fNamespaces[i])) { break; } } } else { for (; i < fGrammarCount; ++i) { if (fNamespaces[i] == null) { break; } } } if (i == fGrammarCount) { return XSNamedMapImpl.EMPTY_MAP; } // get the hashtable for this type of components if (fNSComponents[i][objectType] == null) { SymbolHash table = null; switch (objectType) { case XSConstants.TYPE_DEFINITION: case XSTypeDefinition.COMPLEX_TYPE: case XSTypeDefinition.SIMPLE_TYPE: table = fGrammarList[i].fGlobalTypeDecls; break; case XSConstants.ATTRIBUTE_DECLARATION: table = fGrammarList[i].fGlobalAttrDecls; break; case XSConstants.ELEMENT_DECLARATION: table = fGrammarList[i].fGlobalElemDecls; break; case XSConstants.ATTRIBUTE_GROUP: table = fGrammarList[i].fGlobalAttrGrpDecls; break; case XSConstants.MODEL_GROUP_DEFINITION: table = fGrammarList[i].fGlobalGroupDecls; break; case XSConstants.NOTATION_DECLARATION: table = fGrammarList[i].fGlobalNotationDecls; break; case XSConstants.IDENTITY_CONSTRAINT: table = fGrammarList[i].fGlobalIDConstraintDecls; break; } // for complex/simple types, create a special implementation, // which take specific types out of the hash table if (objectType == XSTypeDefinition.COMPLEX_TYPE || objectType == XSTypeDefinition.SIMPLE_TYPE) { fNSComponents[i][objectType] = new XSNamedMap4Types(namespace, table, objectType); } else { fNSComponents[i][objectType] = new XSNamedMapImpl(namespace, table); } } return fNSComponents[i][objectType]; } /** * Convenience method. Returns a top-level simple or complex type * definition. * @param name The name of the definition. * @param namespace The namespace of the definition, otherwise null. * @return An <code>XSTypeDefinition</code> or null if such definition * does not exist. */ public XSTypeDefinition getTypeDefinition(String name, String namespace) { SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace)); if (sg == null) { return null; } return (XSTypeDefinition)sg.fGlobalTypeDecls.get(name); } /** * Convenience method. Returns a top-level simple or complex type * definition. * @param name The name of the definition. * @param namespace The namespace of the definition, otherwise null. * @param loc The schema location where the component was defined * @return An <code>XSTypeDefinition</code> or null if such definition * does not exist. */ public XSTypeDefinition getTypeDefinition(String name, String namespace, String loc) { SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace)); if (sg == null) { return null; } return sg.getGlobalTypeDecl(name, loc); } /** * Convenience method. Returns a top-level attribute declaration. * @param name The name of the declaration. * @param namespace The namespace of the definition, otherwise null. * @return A top-level attribute declaration or null if such declaration * does not exist. */ public XSAttributeDeclaration getAttributeDeclaration(String name, String namespace) { SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace)); if (sg == null) { return null; } return (XSAttributeDeclaration)sg.fGlobalAttrDecls.get(name); } /** * Convenience method. Returns a top-level attribute declaration. * @param name The name of the declaration. * @param namespace The namespace of the definition, otherwise null. * @param loc The schema location where the component was defined * @return A top-level attribute declaration or null if such declaration * does not exist. */ public XSAttributeDeclaration getAttributeDeclaration(String name, String namespace, String loc) { SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace)); if (sg == null) { return null; } return sg.getGlobalAttributeDecl(name, loc); } /** * Convenience method. Returns a top-level element declaration. * @param name The name of the declaration. * @param namespace The namespace of the definition, otherwise null. * @return A top-level element declaration or null if such declaration * does not exist. */ public XSElementDeclaration getElementDeclaration(String name, String namespace) { SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace)); if (sg == null) { return null; } return (XSElementDeclaration)sg.fGlobalElemDecls.get(name); } /** * Convenience method. Returns a top-level element declaration. * @param name The name of the declaration. * @param namespace The namespace of the definition, otherwise null. * @param loc The schema location where the component was defined * @return A top-level element declaration or null if such declaration * does not exist. */ public XSElementDeclaration getElementDeclaration(String name, String namespace, String loc) { SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace)); if (sg == null) { return null; } return sg.getGlobalElementDecl(name, loc); } /** * Convenience method. Returns a top-level attribute group definition. * @param name The name of the definition. * @param namespace The namespace of the definition, otherwise null. * @return A top-level attribute group definition or null if such * definition does not exist. */ public XSAttributeGroupDefinition getAttributeGroup(String name, String namespace) { SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace)); if (sg == null) { return null; } return (XSAttributeGroupDefinition)sg.fGlobalAttrGrpDecls.get(name); } /** * Convenience method. Returns a top-level attribute group definition. * @param name The name of the definition. * @param namespace The namespace of the definition, otherwise null. * @param loc The schema location where the component was defined * @return A top-level attribute group definition or null if such * definition does not exist. */ public XSAttributeGroupDefinition getAttributeGroup(String name, String namespace, String loc) { SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace)); if (sg == null) { return null; } return sg.getGlobalAttributeGroupDecl(name, loc); } /** * Convenience method. Returns a top-level model group definition. * * @param name The name of the definition. * @param namespace The namespace of the definition, otherwise null. * @return A top-level model group definition definition or null if such * definition does not exist. */ public XSModelGroupDefinition getModelGroupDefinition(String name, String namespace) { SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace)); if (sg == null) { return null; } return (XSModelGroupDefinition)sg.fGlobalGroupDecls.get(name); } /** * Convenience method. Returns a top-level model group definition. * * @param name The name of the definition. * @param namespace The namespace of the definition, otherwise null. * @param loc The schema location where the component was defined * @return A top-level model group definition definition or null if such * definition does not exist. */ public XSModelGroupDefinition getModelGroupDefinition(String name, String namespace, String loc) { SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace)); if (sg == null) { return null; } return sg.getGlobalGroupDecl(name, loc); } /** * Convenience method. Returns a top-level model group definition. * * @param name The name of the definition. * @param namespace The namespace of the definition, otherwise null. * @return A top-level model group definition definition or null if such * definition does not exist. */ public XSIDCDefinition getIDCDefinition(String name, String namespace) { SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace)); if (sg == null) { return null; } return (XSIDCDefinition)sg.fGlobalIDConstraintDecls.get(name); } /** * Convenience method. Returns a top-level model group definition. * * @param name The name of the definition. * @param namespace The namespace of the definition, otherwise null. * @param loc The schema location where the component was defined * @return A top-level model group definition definition or null if such * definition does not exist. */ public XSIDCDefinition getIDCDefinition(String name, String namespace, String loc) { SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace)); if (sg == null) { return null; } return sg.getIDConstraintDecl(name, loc); } /** * @see org.apache.xerces.xs.XSModel#getNotationDeclaration(String, String) */ public XSNotationDeclaration getNotationDeclaration(String name, String namespace) { SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace)); if (sg == null) { return null; } return (XSNotationDeclaration)sg.fGlobalNotationDecls.get(name); } public XSNotationDeclaration getNotationDeclaration(String name, String namespace, String loc) { SchemaGrammar sg = (SchemaGrammar)fGrammarMap.get(null2EmptyString(namespace)); if (sg == null) { return null; } return sg.getGlobalNotationDecl(name, loc); } /** * [annotations]: a set of annotations if it exists, otherwise an empty * <code>XSObjectList</code>. */ public synchronized XSObjectList getAnnotations() { if (fAnnotations != null) { return fAnnotations; } // do this in two passes to avoid inaccurate array size int totalAnnotations = 0; for (int i = 0; i < fGrammarCount; i++) { totalAnnotations += fGrammarList[i].fNumAnnotations; } if (totalAnnotations == 0) { fAnnotations = XSObjectListImpl.EMPTY_LIST; return fAnnotations; } XSAnnotationImpl [] annotations = new XSAnnotationImpl [totalAnnotations]; int currPos = 0; for (int i = 0; i < fGrammarCount; i++) { SchemaGrammar currGrammar = fGrammarList[i]; if (currGrammar.fNumAnnotations > 0) { System.arraycopy(currGrammar.fAnnotations, 0, annotations, currPos, currGrammar.fNumAnnotations); currPos += currGrammar.fNumAnnotations; } } fAnnotations = new XSObjectListImpl(annotations, annotations.length); return fAnnotations; } private static final String null2EmptyString(String str) { return str == null ? XMLSymbols.EMPTY_STRING : str; } /** * REVISIT: to expose identity constraints from XSModel. * For now, we only expose whether there are any IDCs. * We also need to add these methods to the public * XSModel interface. */ public boolean hasIDConstraints() { return fHasIDC; } /** * Convenience method. Returns a list containing the members of the * substitution group for the given <code>XSElementDeclaration</code> * or an empty <code>XSObjectList</code> if the substitution group * contains no members. * @param head The substitution group head. * @return A list containing the members of the substitution group * for the given <code>XSElementDeclaration</code> or an empty * <code>XSObjectList</code> if the substitution group contains * no members. */ public XSObjectList getSubstitutionGroup(XSElementDeclaration head) { return (XSObjectList)fSubGroupMap.get(head); } // // XSNamespaceItemList methods // /** * The number of <code>XSNamespaceItem</code>s in the list. The range of * valid child object indices is 0 to <code>length-1</code> inclusive. */ public int getLength() { return fGrammarCount; } /** * Returns the <code>index</code>th item in the collection or * <code>null</code> if <code>index</code> is greater than or equal to * the number of objects in the list. The index starts at 0. * @param index index into the collection. * @return The <code>XSNamespaceItem</code> at the <code>index</code>th * position in the <code>XSNamespaceItemList</code>, or * <code>null</code> if the index specified is not valid. */ public XSNamespaceItem item(int index) { if (index < 0 || index >= fGrammarCount) { return null; } return fGrammarList[index]; } // // java.util.List methods // public Object get(int index) { if (index >= 0 && index < fGrammarCount) { return fGrammarList[index]; } throw new IndexOutOfBoundsException("Index: " + index); } public int size() { return getLength(); } public Iterator iterator() { return listIterator0(0); } public ListIterator listIterator() { return listIterator0(0); } public ListIterator listIterator(int index) { if (index >= 0 && index < fGrammarCount) { return listIterator0(index); } throw new IndexOutOfBoundsException("Index: " + index); } private ListIterator listIterator0(int index) { return new XSNamespaceItemListIterator(index); } public Object[] toArray() { Object[] a = new Object[fGrammarCount]; toArray0(a); return a; } public Object[] toArray(Object[] a) { if (a.length < fGrammarCount) { Class arrayClass = a.getClass(); Class componentType = arrayClass.getComponentType(); a = (Object[]) Array.newInstance(componentType, fGrammarCount); } toArray0(a); if (a.length > fGrammarCount) { a[fGrammarCount] = null; } return a; } private void toArray0(Object[] a) { if (fGrammarCount > 0) { System.arraycopy(fGrammarList, 0, a, 0, fGrammarCount); } } private final class XSNamespaceItemListIterator implements ListIterator { private int index; public XSNamespaceItemListIterator(int index) { this.index = index; } public boolean hasNext() { return (index < fGrammarCount); } public Object next() { if (index < fGrammarCount) { return fGrammarList[index++]; } throw new NoSuchElementException(); } public boolean hasPrevious() { return (index > 0); } public Object previous() { if (index > 0) { return fGrammarList[--index]; } throw new NoSuchElementException(); } public int nextIndex() { return index; } public int previousIndex() { return index - 1; } public void remove() { throw new UnsupportedOperationException(); } public void set(Object o) { throw new UnsupportedOperationException(); } public void add(Object o) { throw new UnsupportedOperationException(); } } } // class XSModelImpl
apache-2.0
SSEHUB/EASyProducer
Plugins/VarModel/Model/src/net/ssehub/easy/varModel/model/filter/ReferenceValuesFinder.java
3108
/* * Copyright 2009-2013 University of Hildesheim, Software Systems Engineering * * 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.ssehub.easy.varModel.model.filter; import java.util.List; import net.ssehub.easy.varModel.model.AbstractVariable; import net.ssehub.easy.varModel.model.Project; import net.ssehub.easy.varModel.model.datatypes.IDatatype; import net.ssehub.easy.varModel.model.datatypes.Reference; import net.ssehub.easy.varModel.model.filter.DeclarationFinder.VisibilityType; /** * Class for finding relevant {@link AbstractVariable}s matching to the data type of a given {@link Reference}. * @author El-Sharkawy * */ public class ReferenceValuesFinder { /** * Searches inside the whole {@link Project} for {@link AbstractVariable}s, which can be referenced by * {@link net.ssehub.easy.varModel.confModel.IDecisionVariable}s of the given {@link Reference} type. * @param project The project which should contain all relevant possible variable, which can be used * to configure the given {@link Reference} variable. * @param refType A given {@link Reference}, for which relevant/possible {@link AbstractVariable}s should be * found. * @return A list of all relevant {@link AbstractVariable} found in the given project with the correct data type. * This list is maybe empty, but not <tt>null</tt>. */ public static List<AbstractVariable> findPossibleValues(Project project, Reference refType) { return findPossibleValues(project, refType.getType()); } /** * Searches inside the whole {@link Project} for {@link AbstractVariable}s, which are of the specified * <code>type</code>. * @param project The project which should contain all relevant possible variable, which can be used * to configure the given {@link Reference} variable. * @param type A given type for which relevant/possible {@link AbstractVariable}s should be found. * @return A list of all relevant {@link AbstractVariable} found in the given project with the correct data type. * This list is maybe empty, but not <tt>null</tt>. */ public static List<AbstractVariable> findPossibleValues(Project project, IDatatype type) { DeclarationFinder finder = new DeclarationFinder(project, FilterType.ALL, type); /* * Slots of a compound are currently not supported by * IVML, thus, the user should not be able to configure this. */ return finder.getVariableDeclarations(VisibilityType.ONLY_EXPORTED); } }
apache-2.0
trustathsh/ifmapj
src/main/java/de/hshannover/f4/trust/ifmapj/messages/NewSessionResult.java
1644
/* * #%L * ===================================================== * _____ _ ____ _ _ _ _ * |_ _|_ __ _ _ ___| |_ / __ \| | | | ___ | | | | * | | | '__| | | / __| __|/ / _` | |_| |/ __|| |_| | * | | | | | |_| \__ \ |_| | (_| | _ |\__ \| _ | * |_| |_| \__,_|___/\__|\ \__,_|_| |_||___/|_| |_| * \____/ * * ===================================================== * * Hochschule Hannover * (University of Applied Sciences and Arts, Hannover) * Faculty IV, Dept. of Computer Science * Ricklinger Stadtweg 118, 30459 Hannover, Germany * * Email: trust@f4-i.fh-hannover.de * Website: http://trust.f4.hs-hannover.de/ * * This file is part of ifmapj, version 2.3.2, implemented by the Trust@HsH * research group at the Hochschule Hannover. * %% * Copyright (C) 2010 - 2016 Trust@HsH * %% * 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. * #L% */ package de.hshannover.f4.trust.ifmapj.messages; public interface NewSessionResult extends Result { String getSessionId(); String getPublisherId(); Integer getMaxPollResultSize(); }
apache-2.0
gijsleussink/ceylon
langtools-classfile/src/com/redhat/ceylon/langtools/classfile/AnnotationDefault_attribute.java
2481
/* * Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.redhat.ceylon.langtools.classfile; import java.io.IOException; /** * See JVMS, section 4.8.15. * * <p><b>This is NOT part of any supported API. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice.</b> */ public class AnnotationDefault_attribute extends Attribute { AnnotationDefault_attribute(ClassReader cr, int name_index, int length) throws IOException, Annotation.InvalidAnnotation { super(name_index, length); default_value = Annotation.element_value.read(cr); } public AnnotationDefault_attribute(ConstantPool constant_pool, Annotation.element_value default_value) throws ConstantPoolException { this(constant_pool.getUTF8Index(Attribute.AnnotationDefault), default_value); } public AnnotationDefault_attribute(int name_index, Annotation.element_value default_value) { super(name_index, default_value.length()); this.default_value = default_value; } public <R, D> R accept(Visitor<R, D> visitor, D data) { return visitor.visitAnnotationDefault(this, data); } public final Annotation.element_value default_value; }
apache-2.0
benvanwerkhoven/Xenon
src/main/java/nl/esciencecenter/xenon/engine/jobs/JobsEngine.java
6753
/* * Copyright 2013 Netherlands eScience Center * * 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 nl.esciencecenter.xenon.engine.jobs; import java.util.HashSet; import java.util.Map; import nl.esciencecenter.xenon.XenonException; import nl.esciencecenter.xenon.credentials.Credential; import nl.esciencecenter.xenon.engine.Adaptor; import nl.esciencecenter.xenon.engine.XenonEngine; import nl.esciencecenter.xenon.jobs.Job; import nl.esciencecenter.xenon.jobs.JobDescription; import nl.esciencecenter.xenon.jobs.JobStatus; import nl.esciencecenter.xenon.jobs.Jobs; import nl.esciencecenter.xenon.jobs.QueueStatus; import nl.esciencecenter.xenon.jobs.Scheduler; import nl.esciencecenter.xenon.jobs.Streams; public class JobsEngine implements Jobs { private final XenonEngine xenonEngine; public JobsEngine(XenonEngine xenonEngine) { this.xenonEngine = xenonEngine; } private Adaptor getAdaptor(Scheduler scheduler) throws XenonException { return xenonEngine.getAdaptor(scheduler.getAdaptorName()); } public Scheduler newScheduler(String scheme, String location, Credential credential, Map<String, String> properties) throws XenonException { Adaptor adaptor = xenonEngine.getAdaptorFor(scheme); return adaptor.jobsAdaptor().newScheduler(scheme, location, credential, properties); } @Override public void close(Scheduler scheduler) throws XenonException { getAdaptor(scheduler).jobsAdaptor().close(scheduler); } @Override public boolean isOpen(Scheduler scheduler) throws XenonException { return getAdaptor(scheduler).jobsAdaptor().isOpen(scheduler); } @Override public String getDefaultQueueName(Scheduler scheduler) throws XenonException { return getAdaptor(scheduler).jobsAdaptor().getDefaultQueueName(scheduler); } @Override public JobStatus getJobStatus(Job job) throws XenonException { return getAdaptor(job.getScheduler()).jobsAdaptor().getJobStatus(job); } private String[] getAdaptors(Job[] in) { HashSet<String> result = new HashSet<String>(); for (int i = 0; i < in.length; i++) { if (in[i] != null) { result.add(in[i].getScheduler().getAdaptorName()); } } return result.toArray(new String[result.size()]); } private void selectJobs(String adaptorName, Job[] in, Job[] out) { for (int i = 0; i < in.length; i++) { if (in[i] != null && adaptorName.equals(in[i].getScheduler().getAdaptorName())) { out[i] = in[i]; } else { out[i] = null; } } } private void getJobStatus(String adaptor, Job[] in, JobStatus[] out) { JobStatus[] result = null; XenonException exception = null; try { result = xenonEngine.getAdaptor(adaptor).jobsAdaptor().getJobStatuses(in); } catch (XenonException e) { exception = e; } for (int i = 0; i < in.length; i++) { if (in[i] != null) { if (result != null) { out[i] = result[i]; } else { out[i] = new JobStatusImplementation(in[i], null, null, exception, false, false, null); } } } } @Override public JobStatus[] getJobStatuses(Job... jobs) { // First check for the three simple cases; null, no jobs or 1 job. if (jobs == null || jobs.length == 0) { return new JobStatus[0]; } if (jobs.length == 1) { if (jobs[0] == null) { return new JobStatus[1]; } try { return new JobStatus[] { getJobStatus(jobs[0]) }; } catch (Exception e) { return new JobStatus[] { new JobStatusImplementation(jobs[0], null, null, e, false, false, null) }; } } // If we have more than one job, we first collect all adaptor names. String[] adaptors = getAdaptors(jobs); // Next we traverse over the names, and get the JobStatus for each adaptor individually, merging the result into the // overall result on the fly. JobStatus[] result = new JobStatus[jobs.length]; Job[] tmp = new Job[jobs.length]; for (int i = 0; i < adaptors.length; i++) { selectJobs(adaptors[i], jobs, tmp); getJobStatus(adaptors[i], tmp, result); } return result; } @Override public JobStatus waitUntilDone(Job job, long timeout) throws XenonException { return getAdaptor(job.getScheduler()).jobsAdaptor().waitUntilDone(job, timeout); } @Override public JobStatus waitUntilRunning(Job job, long timeout) throws XenonException { return getAdaptor(job.getScheduler()).jobsAdaptor().waitUntilRunning(job, timeout); } @Override public JobStatus cancelJob(Job job) throws XenonException { return getAdaptor(job.getScheduler()).jobsAdaptor().cancelJob(job); } @Override public Job[] getJobs(Scheduler scheduler, String... queueNames) throws XenonException { return getAdaptor(scheduler).jobsAdaptor().getJobs(scheduler, queueNames); } @Override public Job submitJob(Scheduler scheduler, JobDescription description) throws XenonException { return getAdaptor(scheduler).jobsAdaptor().submitJob(scheduler, description); } @Override public QueueStatus getQueueStatus(Scheduler scheduler, String queueName) throws XenonException { return getAdaptor(scheduler).jobsAdaptor().getQueueStatus(scheduler, queueName); } @Override public QueueStatus[] getQueueStatuses(Scheduler scheduler, String... queueNames) throws XenonException { return getAdaptor(scheduler).jobsAdaptor().getQueueStatuses(scheduler, queueNames); } @Override public Streams getStreams(Job job) throws XenonException { return getAdaptor(job.getScheduler()).jobsAdaptor().getStreams(job); } @Override public String toString() { return "JobsEngine [xenonEngine=" + xenonEngine + "]"; } }
apache-2.0
spring-projects/spring-framework
spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/reactive/PayloadMethodArgumentResolver.java
11961
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.messaging.handler.annotation.reactive; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Consumer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.core.Conventions; import org.springframework.core.MethodParameter; import org.springframework.core.ReactiveAdapter; import org.springframework.core.ReactiveAdapterRegistry; import org.springframework.core.ResolvableType; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.core.codec.Decoder; import org.springframework.core.codec.DecodingException; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.lang.Nullable; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.handler.annotation.Payload; import org.springframework.messaging.handler.annotation.support.MethodArgumentNotValidException; import org.springframework.messaging.handler.invocation.MethodArgumentResolutionException; import org.springframework.messaging.handler.invocation.reactive.HandlerMethodArgumentResolver; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.MimeType; import org.springframework.util.MimeTypeUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.SmartValidator; import org.springframework.validation.Validator; import org.springframework.validation.annotation.Validated; /** * A resolver to extract and decode the payload of a message using a * {@link Decoder}, where the payload is expected to be a {@link Publisher} of * {@link DataBuffer DataBuffer}. * * <p>Validation is applied if the method argument is annotated with * {@code @jakarta.validation.Valid} or * {@link org.springframework.validation.annotation.Validated}. Validation * failure results in an {@link MethodArgumentNotValidException}. * * <p>This resolver should be ordered last if {@link #useDefaultResolution} is * set to {@code true} since in that case it supports all types and does not * require the presence of {@link Payload}. * * @author Rossen Stoyanchev * @since 5.2 */ public class PayloadMethodArgumentResolver implements HandlerMethodArgumentResolver { protected final Log logger = LogFactory.getLog(getClass()); private final List<Decoder<?>> decoders; @Nullable private final Validator validator; private final ReactiveAdapterRegistry adapterRegistry; private final boolean useDefaultResolution; public PayloadMethodArgumentResolver(List<? extends Decoder<?>> decoders, @Nullable Validator validator, @Nullable ReactiveAdapterRegistry registry, boolean useDefaultResolution) { Assert.isTrue(!CollectionUtils.isEmpty(decoders), "At least one Decoder is required"); this.decoders = Collections.unmodifiableList(new ArrayList<>(decoders)); this.validator = validator; this.adapterRegistry = registry != null ? registry : ReactiveAdapterRegistry.getSharedInstance(); this.useDefaultResolution = useDefaultResolution; } /** * Return a read-only list of the configured decoders. */ public List<Decoder<?>> getDecoders() { return this.decoders; } /** * Return the configured validator, if any. */ @Nullable public Validator getValidator() { return this.validator; } /** * Return the configured {@link ReactiveAdapterRegistry}. */ public ReactiveAdapterRegistry getAdapterRegistry() { return this.adapterRegistry; } /** * Whether this resolver is configured to use default resolution, i.e. * works for any argument type regardless of whether {@code @Payload} is * present or not. */ public boolean isUseDefaultResolution() { return this.useDefaultResolution; } @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.hasParameterAnnotation(Payload.class) || this.useDefaultResolution; } /** * Decode the content of the given message payload through a compatible * {@link Decoder}. * * <p>Validation is applied if the method argument is annotated with * {@code @jakarta.validation.Valid} or * {@link org.springframework.validation.annotation.Validated}. Validation * failure results in an {@link MethodArgumentNotValidException}. * @param parameter the target method argument that we are decoding to * @param message the message from which the content was extracted * @return a Mono with the result of argument resolution * @see #extractContent(MethodParameter, Message) * @see #getMimeType(Message) */ @Override public final Mono<Object> resolveArgument(MethodParameter parameter, Message<?> message) { Payload ann = parameter.getParameterAnnotation(Payload.class); if (ann != null && StringUtils.hasText(ann.expression())) { throw new IllegalStateException("@Payload SpEL expressions not supported by this resolver"); } MimeType mimeType = getMimeType(message); mimeType = mimeType != null ? mimeType : MimeTypeUtils.APPLICATION_OCTET_STREAM; Flux<DataBuffer> content = extractContent(parameter, message); return decodeContent(parameter, message, ann == null || ann.required(), content, mimeType); } @SuppressWarnings("unchecked") private Flux<DataBuffer> extractContent(MethodParameter parameter, Message<?> message) { Object payload = message.getPayload(); if (payload instanceof DataBuffer) { return Flux.just((DataBuffer) payload); } if (payload instanceof Publisher) { return Flux.from((Publisher<?>) payload).map(value -> { if (value instanceof DataBuffer) { return (DataBuffer) value; } String className = value.getClass().getName(); throw getUnexpectedPayloadError(message, parameter, "Publisher<" + className + ">"); }); } return Flux.error(getUnexpectedPayloadError(message, parameter, payload.getClass().getName())); } private MethodArgumentResolutionException getUnexpectedPayloadError( Message<?> message, MethodParameter parameter, String actualType) { return new MethodArgumentResolutionException(message, parameter, "Expected DataBuffer or Publisher<DataBuffer> for the Message payload, actual: " + actualType); } /** * Return the mime type for the content. By default this method checks the * {@link MessageHeaders#CONTENT_TYPE} header expecting to find a * {@link MimeType} value or a String to parse to a {@link MimeType}. * @param message the input message */ @Nullable protected MimeType getMimeType(Message<?> message) { Object headerValue = message.getHeaders().get(MessageHeaders.CONTENT_TYPE); if (headerValue == null) { return null; } else if (headerValue instanceof String) { return MimeTypeUtils.parseMimeType((String) headerValue); } else if (headerValue instanceof MimeType) { return (MimeType) headerValue; } else { throw new IllegalArgumentException("Unexpected MimeType value: " + headerValue); } } private Mono<Object> decodeContent(MethodParameter parameter, Message<?> message, boolean isContentRequired, Flux<DataBuffer> content, MimeType mimeType) { ResolvableType targetType = ResolvableType.forMethodParameter(parameter); Class<?> resolvedType = targetType.resolve(); ReactiveAdapter adapter = (resolvedType != null ? getAdapterRegistry().getAdapter(resolvedType) : null); ResolvableType elementType = (adapter != null ? targetType.getGeneric() : targetType); isContentRequired = isContentRequired || (adapter != null && !adapter.supportsEmpty()); Consumer<Object> validator = getValidator(message, parameter); Map<String, Object> hints = Collections.emptyMap(); for (Decoder<?> decoder : this.decoders) { if (decoder.canDecode(elementType, mimeType)) { if (adapter != null && adapter.isMultiValue()) { Flux<?> flux = content .filter(this::nonEmptyDataBuffer) .map(buffer -> decoder.decode(buffer, elementType, mimeType, hints)) .onErrorResume(ex -> Flux.error(handleReadError(parameter, message, ex))); if (isContentRequired) { flux = flux.switchIfEmpty(Flux.error(() -> handleMissingBody(parameter, message))); } if (validator != null) { flux = flux.doOnNext(validator); } return Mono.just(adapter.fromPublisher(flux)); } else { // Single-value (with or without reactive type wrapper) Mono<?> mono = content.next() .filter(this::nonEmptyDataBuffer) .map(buffer -> decoder.decode(buffer, elementType, mimeType, hints)) .onErrorResume(ex -> Mono.error(handleReadError(parameter, message, ex))); if (isContentRequired) { mono = mono.switchIfEmpty(Mono.error(() -> handleMissingBody(parameter, message))); } if (validator != null) { mono = mono.doOnNext(validator); } return (adapter != null ? Mono.just(adapter.fromPublisher(mono)) : Mono.from(mono)); } } } return Mono.error(new MethodArgumentResolutionException( message, parameter, "Cannot decode to [" + targetType + "]" + message)); } private boolean nonEmptyDataBuffer(DataBuffer buffer) { if (buffer.readableByteCount() > 0) { return true; } DataBufferUtils.release(buffer); return false; } private Throwable handleReadError(MethodParameter parameter, Message<?> message, Throwable ex) { return ex instanceof DecodingException ? new MethodArgumentResolutionException(message, parameter, "Failed to read HTTP message", ex) : ex; } private MethodArgumentResolutionException handleMissingBody(MethodParameter param, Message<?> message) { return new MethodArgumentResolutionException(message, param, "Payload content is missing: " + param.getExecutable().toGenericString()); } @Nullable private Consumer<Object> getValidator(Message<?> message, MethodParameter parameter) { if (this.validator == null) { return null; } for (Annotation ann : parameter.getParameterAnnotations()) { Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class); if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) { Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann)); Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints}); String name = Conventions.getVariableNameForParameter(parameter); return target -> { BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(target, name); if (!ObjectUtils.isEmpty(validationHints) && this.validator instanceof SmartValidator) { ((SmartValidator) this.validator).validate(target, bindingResult, validationHints); } else { this.validator.validate(target, bindingResult); } if (bindingResult.hasErrors()) { throw new MethodArgumentNotValidException(message, parameter, bindingResult); } }; } } return null; } }
apache-2.0
coding0011/elasticsearch
x-pack/plugin/transform/src/main/java/org/elasticsearch/xpack/transform/action/compat/TransportPreviewTransformActionDeprecated.java
1632
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ package org.elasticsearch.xpack.transform.action.compat; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.license.XPackLicenseState; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import org.elasticsearch.xpack.core.transform.action.compat.PreviewTransformActionDeprecated; import org.elasticsearch.xpack.transform.action.TransportPreviewTransformAction; public class TransportPreviewTransformActionDeprecated extends TransportPreviewTransformAction { @Inject public TransportPreviewTransformActionDeprecated(TransportService transportService, ActionFilters actionFilters, Client client, ThreadPool threadPool, XPackLicenseState licenseState, IndexNameExpressionResolver indexNameExpressionResolver, ClusterService clusterService) { super(PreviewTransformActionDeprecated.NAME, transportService, actionFilters, client, threadPool, licenseState, indexNameExpressionResolver, clusterService); } }
apache-2.0
Novartis/YADA
yada-api/src/main/java/com/novartis/opensource/yada/io/FileHelper.java
7030
/** * Copyright 2016 Novartis Institutes for BioMedical Research 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.novartis.opensource.yada.io; import java.io.Reader; import java.util.Map; import org.apache.log4j.Logger; /** * The abstract root of the {@code yada.io} package. It contains constants and method stubs and implementations * to facilitate parsing of files, primarily by plugins. * @author David Varon * */ public abstract class FileHelper { /** * Local logger handle */ private static Logger l = Logger.getLogger(FileHelper.class); /** * Constant equal to: {@value} */ public final static String TAB = "\t"; /** * Constant equal to: {@value} */ public final static String COMMA = ","; /** * Constant equal to: {@value} */ public final static String PIPE = "|"; /** * Constant equal to: {@value} */ public final static String NEWLINE = "\n"; /** * Constant equal to: {@value} */ public final static int DEFAULT_HEADER_LINE_NUMBER = 0; /** * Constant equal to: {@value} */ public final static int DEFAULT_BYTE_OFFSET = 0; /** * Constant equal to: {@value} */ public final static String DEFAULT_DELIMITER = TAB; /** * Constant equal to: {@code System.getProperty("line.separotor")} usually a newline. */ public final static String DEFAULT_LINE_SEPARATOR = System.getProperty("line.separator"); /** * Instance variable for {@code java.io} utilization */ protected Reader reader; /** * Instance variable for storing file header */ private String fileHeader = null; /** * Instance variable for storing column header */ private String columnHeader = null; /** * Instance variable for storing line in file occupied by column header row. Defaults to {@link #DEFAULT_HEADER_LINE_NUMBER} */ protected int headerLineNumber = DEFAULT_HEADER_LINE_NUMBER; /** * Instance variable for storing byte offset in file where header row begins. Defaults to {@link #DEFAULT_BYTE_OFFSET} */ protected int headerByteOffset = DEFAULT_BYTE_OFFSET; /** * Instance variable for storage of name/value pairs found in file header */ protected Map<String,String> fileHeaderMap = null; /** * Indexed instance variable for storage of column header values and positions */ protected String[] colHeaderArray = null; /** * Method stub for mutator. Requires subclass implementation. */ protected void setHeaderLineNumber() { l.debug("Nothing to do."); } /** * Standard accessor for variable * @return {@code int} value of {@link #headerLineNumber} */ public int getHeaderLineNumber() { return this.headerLineNumber; } /** * Method stub for mutator. Requires subclass implementation. */ protected void setHeaderByteOffset() { l.debug("Nothing to do."); } /** * Standard accessor for variable * @return the {@code int} value of the offset, set to {@link #DEFAULT_BYTE_OFFSET} by default */ public int getHeaderByteOffset() { return DEFAULT_BYTE_OFFSET; } /** * Standard accessor for variable * @return the {@code java.lang.String} value the delimiter, set to {@link #DEFAULT_DELIMITER} by default */ public String getDelimiter() { return DEFAULT_DELIMITER; } /** * Standard accessor for variable * @return the {@code java.lang.String} value the separator, set to {@link #DEFAULT_LINE_SEPARATOR} by default */ public String getLineSeparator() { return DEFAULT_LINE_SEPARATOR; } /** * Standard mutator for variable * @param fileHeader string containing file header data */ protected void setFileHeader(String fileHeader) { this.fileHeader = fileHeader; } /** * Standard accessor for variable * @return the {@code java.lang.String} value the file header */ public String getFileHeader() { return this.fileHeader; } /** * Method stub for mutator. Requires subclass implementation. */ protected void setFileHeaderMap() { l.debug("Nothing to do."); } /** * Standard mutator for variable * @param fileHeaderMap map containing file header key/value pairs */ protected void setFileHeaderMap(Map<String,String> fileHeaderMap) { this.fileHeaderMap = fileHeaderMap; } /** * Returns the map of name/value pairs from the file header * @return the map of name/value pairs from the file header */ public Map<String,String> getFileHeaderMap() { return this.fileHeaderMap; } /** * Standard mutator for variable * @param columnHeader string containing column header line */ protected void setColumnHeader(String columnHeader) { this.columnHeader = columnHeader; } /** * Returns the column header row as a {@link String} * @return the column header row as a {@link String} */ public String getColumnHeader() { return this.columnHeader; } /** * Method stub for mutator. Requires subclass implementation. * @throws YADAIOException when the column header can't be parsed into an array */ protected void setColHeaderArray() throws YADAIOException { l.debug("Nothing to do."); } /** * Standard mutator for variable * @param colHeaderArray the array of values constituting column headers */ protected void setColHeaderArray(String[] colHeaderArray) { this.colHeaderArray = colHeaderArray; } /** * Returns the column header row as an array of {@link String} values. * @return the column header row as an array of {@link String} values */ public String[] getColHeaderArray() { return this.colHeaderArray; } /** * Standard mutator for variable * @param reader the java.io component for processing the file */ protected void setReader(Reader reader) { this.reader = reader; } /** * Returns the {@code java.io} object for processing the file. * @return the {@code java.io} object for processing the file */ public Reader getReader() { return this.reader; } /** * @throws YADAIOException when the file headers can't be read successfully */ protected void setHeaders() throws YADAIOException { l.debug("Nothing to do."); } }
apache-2.0
tticoin/JointER
src/jp/tti_coin/main/java/data/nlp/joint/Pair.java
4424
package data.nlp.joint; import java.util.Collection; import java.util.Set; import java.util.TreeSet; import config.Parameters; import data.Label; import data.LabelUnit; import data.SequenceUnit; public class Pair extends SequenceUnit { Parameters params; Word w1, w2; public Pair(Parameters params, Word w1, Word w2){ this.params = params; this.w1 = w1; this.w2 = w2; assert this.w1.getWord().getOffset().compareTo(this.w2.getWord().getOffset()) <= 0; } @Override public String getType() { //TODO: check pair assert false; return null; } @Override public LabelUnit getNegativeClassLabel() { return PairLabelUnit.getNegativeClassLabelUnit(); } public Word getW1() { return w1; } public Word getW2() { return w2; } public Collection<LabelUnit> getPossibleLabels() { assert false; return null; } public Collection<LabelUnit> getPossibleLabels(Label label, JointInstance instance) { int w1Idx = instance.getWord(w1.getId()); String w1Type = ""; int w2Idx = instance.getWord(w2.getId()); String w2Type = ""; if(params.getUseGoldEntitySpan()){ String goldW1Position = ((WordLabelUnit)instance.getGoldLabel().getLabel(w1Idx)).getPosition(); String goldW2Position = ((WordLabelUnit)instance.getGoldLabel().getLabel(w2Idx)).getPosition(); if(!(goldW1Position.equals("U") || goldW1Position.equals("L")) || !(goldW2Position.equals("U") || goldW2Position.equals("L"))){ Set<LabelUnit> labels = new TreeSet<LabelUnit>(); labels.add(getNegativeClassLabel()); return labels; } w1Type = instance.getGoldType(label, w1.getId()); w2Type = instance.getGoldType(label, w2.getId()); } if(w1Idx < label.size()){ assert label.getLabel(w1Idx) instanceof WordLabelUnit; String position = ((WordLabelUnit)label.getLabel(w1Idx)).getPosition(); if(position.equals(WordLabelUnit.B) || position.equals(WordLabelUnit.I) || position.equals(WordLabelUnit.O)){ Set<LabelUnit> labels = new TreeSet<LabelUnit>(); labels.add(getNegativeClassLabel()); return labels; } w1Type = ((WordLabelUnit)label.getLabel(w1Idx)).getType(); } if(w1.getId() < instance.getNumWords() - 1){ int nw1Idx = instance.getWord(w1.getId() + 1); if(nw1Idx < label.size()){ String nextPosition = ((WordLabelUnit)label.getLabel(nw1Idx)).getPosition(); if(nextPosition.equals(WordLabelUnit.I) || nextPosition.equals(WordLabelUnit.L)){ Set<LabelUnit> labels = new TreeSet<LabelUnit>(); labels.add(getNegativeClassLabel()); return labels; } } } if(w1Type.equals("") && w1.getId() > 0){ int pw1Idx = instance.getWord(w1.getId() - 1); if(pw1Idx < label.size()){ WordLabelUnit unit = (WordLabelUnit)label.getLabel(pw1Idx); if(unit.getPosition().equals(WordLabelUnit.B)||unit.getPosition().equals(WordLabelUnit.I)){ w1Type = unit.getType(); } } } if(w2Idx < label.size()){ assert label.getLabel(w2Idx) instanceof WordLabelUnit; String position = ((WordLabelUnit)label.getLabel(w2Idx)).getPosition(); if(position.equals(WordLabelUnit.B) || position.equals(WordLabelUnit.I) || position.equals(WordLabelUnit.O)){ Set<LabelUnit> labels = new TreeSet<LabelUnit>(); labels.add(getNegativeClassLabel()); return labels; } w2Type = ((WordLabelUnit)label.getLabel(w2Idx)).getType(); } if(w2.getId() < instance.getNumWords() - 1){ int nw2Idx = instance.getWord(w2.getId() + 1); if(nw2Idx < label.size()){ String nextPosition = ((WordLabelUnit)label.getLabel(nw2Idx)).getPosition(); if(nextPosition.equals(WordLabelUnit.I) || nextPosition.equals(WordLabelUnit.L)){ Set<LabelUnit> labels = new TreeSet<LabelUnit>(); labels.add(getNegativeClassLabel()); return labels; } } } if(w2Type.equals("") && w2.getId() > 0){ int pw2Idx = instance.getWord(w2.getId() - 1); if(pw2Idx < label.size()){ WordLabelUnit unit = (WordLabelUnit)label.getLabel(pw2Idx); if(unit.getPosition().equals(WordLabelUnit.B)||unit.getPosition().equals(WordLabelUnit.I)){ w2Type = unit.getType(); } } } String type = ":"; if(params.getUseRelationTypeFilter()){ type = w1Type+":"+w2Type; } if(!params.getPossibleLabels().containsKey(type)){ Set<LabelUnit> labels = new TreeSet<LabelUnit>(); labels.add(getNegativeClassLabel()); return labels; } return params.getPossibleLabels(type); } }
apache-2.0
tallycheck/data-support
test-material-for-jpa/src/main/java/com/taoswork/tallycheck/testmaterial/jpa/domain/common/Address.java
1146
package com.taoswork.tallycheck.testmaterial.jpa.domain.common; import com.taoswork.tallycheck.datadomain.base.presentation.PresentationField; import com.taoswork.tallycheck.datadomain.base.presentation.Visibility; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Column; import javax.persistence.Embeddable; @Embeddable @Access(AccessType.FIELD) public class Address { @PresentationField(visibility = Visibility.GRID_HIDE) private String street; private String city; private String state; @Column(name = "ZIP_CODE") private String zip; public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } }
apache-2.0
inbloom/secure-data-service
POC/ingestion-tests/edfi-0100/src/main/java/org/ed_fi/_0100/Payroll.java
4625
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.01.22 at 01:42:02 PM EST // package org.ed_fi._0100; import java.math.BigDecimal; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * This financial entity represents the sum of the financial transactions to date for employee compensation. An "employee" who performs services under the direction of the employing institution or agency, is compensated for such services by the employer, and is eligible for employee benefits and wage or salary tax withholdings. * * <p>Java class for Payroll complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="Payroll"> * &lt;complexContent> * &lt;extension base="{http://ed-fi.org/0100}ComplexObjectType"> * &lt;sequence> * &lt;element name="AmountToDate" type="{http://ed-fi.org/0100}Currency"/> * &lt;element name="AsOfDate" type="{http://www.w3.org/2001/XMLSchema}date"/> * &lt;element name="AccountReference" type="{http://ed-fi.org/0100}AccountReferenceType"/> * &lt;element name="StaffReference" type="{http://ed-fi.org/0100}StaffReferenceType"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Payroll", propOrder = { "amountToDate", "asOfDate", "accountReference", "staffReference" }) public class Payroll extends ComplexObjectType { @XmlElement(name = "AmountToDate", required = true) protected BigDecimal amountToDate; @XmlElement(name = "AsOfDate", required = true) @XmlSchemaType(name = "date") protected XMLGregorianCalendar asOfDate; @XmlElement(name = "AccountReference", required = true) protected AccountReferenceType accountReference; @XmlElement(name = "StaffReference", required = true) protected StaffReferenceType staffReference; /** * Gets the value of the amountToDate property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getAmountToDate() { return amountToDate; } /** * Sets the value of the amountToDate property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setAmountToDate(BigDecimal value) { this.amountToDate = value; } /** * Gets the value of the asOfDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getAsOfDate() { return asOfDate; } /** * Sets the value of the asOfDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setAsOfDate(XMLGregorianCalendar value) { this.asOfDate = value; } /** * Gets the value of the accountReference property. * * @return * possible object is * {@link AccountReferenceType } * */ public AccountReferenceType getAccountReference() { return accountReference; } /** * Sets the value of the accountReference property. * * @param value * allowed object is * {@link AccountReferenceType } * */ public void setAccountReference(AccountReferenceType value) { this.accountReference = value; } /** * Gets the value of the staffReference property. * * @return * possible object is * {@link StaffReferenceType } * */ public StaffReferenceType getStaffReference() { return staffReference; } /** * Sets the value of the staffReference property. * * @param value * allowed object is * {@link StaffReferenceType } * */ public void setStaffReference(StaffReferenceType value) { this.staffReference = value; } }
apache-2.0
pipipark/Commons
src/main/java/com/pipipark/commons/date/excep/DateMonthException.java
788
package com.pipipark.commons.date.excep; import com.pipipark.commons.PPPark; import com.pipipark.commons.date.PPPDateMonth; import com.pipipark.commons.throwable.ExceptionMessage; import com.pipipark.commons.throwable.PPPRuntimeException; /** * 月配置异常. * @version 1.0 * @author <a style="font-weight:bolder;" href="http://tech.pipipark.com">陈文杰</a><p><a style="text-decoration:underline;" href="mailto:tech@pipipark.com">联系邮箱</a></p> * @since 2016年12月1日 */ @SuppressWarnings("serial") public class DateMonthException extends PPPRuntimeException { public DateMonthException(Integer month, Class<PPPDateMonth> cause) { super(new ExceptionMessage("Month number {0} no found in {1}", month, PPPark.String.aliasName(cause))); } }
apache-2.0
mifos/1.4.x
application/src/main/java/org/mifos/framework/struts/tags/HeaderTag.java
2658
/* * Copyright (c) 2005-2009 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.framework.struts.tags; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; import org.mifos.framework.business.BusinessObject; import org.mifos.framework.components.taggenerator.TagGenerator; import org.mifos.framework.exceptions.PageExpiredException; import org.mifos.framework.util.helpers.Constants; import org.mifos.framework.util.helpers.SessionUtils; /** * This tag class is used to display header links on the top of the jsp page. */ public class HeaderTag extends TagSupport { private String selfLink; public HeaderTag() { super(); } public String getSelfLink() { return selfLink; } public void setSelfLink(String selfLink) { this.selfLink = selfLink; } @Override public int doStartTag() throws JspException { BusinessObject obj = null; Object randomNum = pageContext.getSession().getAttribute(Constants.RANDOMNUM); try { obj = (BusinessObject) SessionUtils.getAttribute(Constants.BUSINESS_KEY, (HttpServletRequest) pageContext .getRequest()); } catch (PageExpiredException pex) { obj = (BusinessObject) pageContext.getSession().getAttribute(Constants.BUSINESS_KEY); } try { String linkStr; if (selfLink != null && selfLink != "") linkStr = TagGenerator.createHeaderLinks(obj, Boolean.getBoolean(selfLink), randomNum); else linkStr = TagGenerator.createHeaderLinks(obj, true, randomNum); pageContext.getOut().write(linkStr); } catch (PageExpiredException e) { new JspException(e); } catch (IOException e) { new JspException(e); } return SKIP_BODY; } }
apache-2.0
misberner/automatalib
util/src/main/java/net/automatalib/util/automata/builders/DFABuilderImpl.java
1534
/* Copyright (C) 2013-2020 TU Dortmund * This file is part of AutomataLib, http://www.automatalib.net/. * * 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.automatalib.util.automata.builders; import com.github.misberner.duzzt.annotations.DSLAction; import com.github.misberner.duzzt.annotations.GenerateEmbeddedDSL; import com.github.misberner.duzzt.annotations.SubExpr; import net.automatalib.automata.fsa.MutableDFA; @GenerateEmbeddedDSL(name = "DFABuilder", enableAllMethods = false, syntax = "<transOrAcc>* withInitial <transOrAcc>* create", where = {@SubExpr(name = "transOrAcc", definedAs = "(from (on (loop|to))+)+|withAccepting")}) class DFABuilderImpl<S, I, A extends MutableDFA<S, ? super I>> extends FSABuilderImpl<S, I, A> { DFABuilderImpl(A automaton) { super(automaton); } @Override @DSLAction(autoVarArgs = false) public void withInitial(Object stateId) { super.withInitial(stateId); } }
apache-2.0
lutzfischer/XiSearch
src/main/java/rappsilber/ms/statistics/generator/WaterGain.java
4205
/* * Copyright 2016 Lutz Fischer <l.fischer@ed.ac.uk>. * * 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 rappsilber.ms.statistics.generator; import rappsilber.ms.sequence.AminoAcid; import rappsilber.ms.sequence.Peptide; import rappsilber.ms.sequence.ions.BIon; import rappsilber.ms.sequence.ions.loss.BIonWaterGain; import rappsilber.ms.sequence.ions.loss.Loss; import rappsilber.ms.spectra.SpectraPeak; import rappsilber.ms.spectra.annotation.SpectraPeakAnnotation; import rappsilber.ms.spectra.annotation.SpectraPeakMatchedFragment; import rappsilber.ms.spectra.match.MatchedBaseFragment; import rappsilber.ms.spectra.match.MatchedFragmentCollection; import rappsilber.ms.spectra.match.MatchedXlinkedPeptide; import rappsilber.utils.CountOccurence; /** * looks for BIons that have a gain of water - suppostly that can happen at the B(n-1) ion * @author Lutz Fischer <l.fischer@ed.ac.uk> */ public class WaterGain extends AbstractStatistic{ //StatisticsFragementationSiteSingle CountOccurence<Integer> BIonOccurence = new CountOccurence<Integer>(); CountOccurence<Integer> BIonOccurenceReverse = new CountOccurence<Integer>(); CountOccurence<Integer> BIonOccurenceOnly = new CountOccurence<Integer>(); CountOccurence<Integer> BIonOccurenceReverseOnly = new CountOccurence<Integer>(); int count = 0; public WaterGain() { } public void countSpectraMatch(MatchedXlinkedPeptide match) { MatchedFragmentCollection MatchedFragments = new MatchedFragmentCollection(match.getSpectrum().getPrecurserCharge()); for (SpectraPeak sp : match.getSpectrum().getPeaks()) { for (SpectraPeakMatchedFragment mf : sp.getMatchedAnnotation()) { MatchedFragments.add(mf.getFragment(), mf.getCharge(), sp); if (mf.getFragment().isClass(BIonWaterGain.class)) { count++; } } } for (MatchedBaseFragment mbf : MatchedFragments) { for (Loss l : mbf.getLosses().keySet()) { SpectraPeak sp = mbf.getLosses().get(l); // check only, if it is the only "loss" at the BIon if (l instanceof BIonWaterGain && l.getParentFragment() instanceof BIon //&& mbf.isBaseFragmentFound() // and a B-Ion without loss was found && sp.hasAnnotation(SpectraPeakAnnotation.monoisotop)) { // and is the monoisotopic peak of a cluster BIonOccurence.add((int)l.length()); BIonOccurenceReverse.add(l.getPeptide().length() - l.length()); if (sp.getMatchedFragments().size() == 1) { BIonOccurenceOnly.add((int)l.length()); BIonOccurenceReverseOnly.add(l.getPeptide().length() - l.length()); } } } } } public String getTable() { StringBuffer sb = new StringBuffer(); for (Integer i : BIonOccurence.getCountedObjects()) { sb.append("B" + i + "\t" + BIonOccurence.count(i) + "\n"); } for (Integer i : BIonOccurenceReverse.getCountedObjects()) { sb.append("B(n - " + i + ")\t" + BIonOccurenceReverse.count(i) + "\n"); } for (Integer i : BIonOccurenceOnly.getCountedObjects()) { sb.append("Only B" + i + "\t" + BIonOccurenceOnly.count(i) + "\n"); } for (Integer i : BIonOccurenceReverseOnly.getCountedObjects()) { sb.append("Only B(n - " + i + ")\t" + BIonOccurenceReverseOnly.count(i) + "\n"); } return sb.toString(); } }
apache-2.0
omanand/spring-app-event-demo
src/main/java/com/wordpress/omanandj/event/AppEventListener.java
687
package com.wordpress.omanandj.event; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.impl.Log4jLoggerFactory; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; /** * Created with IntelliJ IDEA. * User: ojha * Date: 09/08/13 * Time: 10:48 PM */ @Component public class AppEventListener implements ApplicationListener<NewAppEvent> { private static final Logger LOG = LoggerFactory.getLogger(AppEventListener.class); @Override public void onApplicationEvent(NewAppEvent event) { LOG.info("Event Occured {} " , event); } }
apache-2.0
dsaetgareev/junior
chapter_002/tracker/src/main/java/ru/job4j/start/RussLanguage.java
8109
package ru.job4j.start; /** * class RussLanguage implements Language - has questions in Russian. * @author Dinis Saetgareev (dinis0086@mail.ru) * @since 24.03.2017 * @version 1.0 */ public class RussLanguage implements Language { /** * array questions languageTracker. */ private String[] languageTracker = new String[5]; /** * array questions languageAdd. */ private String[] languageAdd = new String[5]; /** * array questions languageShow. */ private String[] languageShow = new String[1]; /** * array questions languageUpdate. */ private String[] languageUpdate = new String[6]; /** * array questions languageDelete. */ private String[] languageDelete = new String[2]; /** * array questions languageShowDelete. */ private String[] languageShowDelete = new String[1]; /** * array questions languageFindById. */ private String[] languageFindById = new String[2]; /** * array questions languageFindByKey. */ private String[] languageFindByKey = new String[2]; /** * array questions languageRestore. */ private String[] languageRestore = new String[2]; /** * array questions languageAddComment. */ private String[] languageAddComment = new String[3]; /** * fillAll - fill all methods. */ @Override public void fillAll() { this.fillLanguageTracker(); this.fillLanguageAdd(); this.fillLanguageShow(); this.fillLanguageUpdate(); this.fillLanguageDelete(); this.fillLanguageShowDelete(); this.fillLanguageFindById(); this.fillLanguageFindByKey(); this.fillLanguageRestore(); this.fillLanguageAddComment(); } /** * method fill a tracker questions. */ @Override public void fillLanguageTracker() { this.languageTracker[0] = "Выбор:_"; this.languageTracker[1] = "Продолжить? любой символ. Exit? '"; this.languageTracker[2] = "':__ "; this.languageTracker[3] = "выход"; this.languageTracker[4] = "Здравствуйте!\n Данная программа учета заявок.\n " + "Выберите пункт меню, чтобы добавить новый элемент - 0,\n" + "показать элементы - 1, заменить элемент - 2, удалить элемент - 3,\n" + "найти по id - 4, найти по ключу - 5, показать удаленные элементы - 6,\n" + "восстановить удаленный элемент - 7, добавить новый комментарий элементу - 8.\n" + "----------------------------------------------------------------------------"; } /** * String[] getLanguageTracker(). * @return LanguageTracker */ @Override public String[] getLanguageTracker() { return this.languageTracker; } /** * fill questions for AddAction. */ @Override public void fillLanguageAdd() { this.languageAdd[0] = "Добавить новую задачу."; this.languageAdd[1] = "Пожалуйста, введите имя задачи: "; this.languageAdd[2] = "Пожалуйста, введите описание задачи: "; this.languageAdd[3] = "Пожалуйста, введите дату создания задачи: "; this.languageAdd[4] = "Пожалуйса, введите комментарий к задаче: "; } /** * getLanguageAdd(). * @return LanguageAdd */ @Override public String[] getLanguageAdd() { return this.languageAdd; } /** * method fill questions for ShowAction. */ @Override public void fillLanguageShow() { this.languageShow[0] = "Показать элементы."; } /** * getLanguageShow(). * @return LanguageShow */ @Override public String[] getLanguageShow() { return this.languageShow; } /** * method fill questions for UpdateAction. */ @Override public void fillLanguageUpdate() { this.languageUpdate[0] = "Изменить элемент."; this.languageUpdate[1] = "Пожалуйста, введите id заменяемого элемента: "; this.languageUpdate[2] = "Пожалуйста, введите новое имя: "; this.languageUpdate[3] = "Пожалуйста, введите новое описание задачи: "; this.languageUpdate[4] = "Пожалуйста, введите дату изменения задачи: "; this.languageUpdate[5] = "Пожалуйста, введите новый комментарий к задаче: "; } /** * getLanguageUpdate(). * @return LanguageUpdate */ @Override public String[] getLanguageUpdate() { return this.languageUpdate; } /** * fill questions for DeleteAction. */ @Override public void fillLanguageDelete() { this.languageDelete[0] = "Удалить элемент."; this.languageDelete[1] = "Пожалуйста, введите id удаляемого элемента: "; } /** * getLanguageDelete(). * @return LanguageDelete */ @Override public String[] getLanguageDelete() { return this.languageDelete; } /** * fill questions for ShowDeleteAction. */ @Override public void fillLanguageShowDelete() { this.languageShowDelete[0] = "Показать удаленные элементы."; } /** * getLanguageShowDelete(). * @return LanguageShowDelete */ @Override public String[] getLanguageShowDelete() { return this.languageShowDelete; } /** * fill questions for FindByIdAction. */ @Override public void fillLanguageFindById() { this.languageFindById[0] = "Найти элемент по id."; this.languageFindById[1] = "Пожалуйста, введите id элемента: "; } /** * getLanguageFindById(). * @return LanguageFindById */ @Override public String[] getLanguageFindById() { return this.languageFindById; } /** * fill questions for FindByKeyAction. */ @Override public void fillLanguageFindByKey() { this.languageFindByKey[0] = "Найти элемент по ключу."; this.languageFindByKey[1] = "Пожалуйста, введите ключ: "; } /** * getLanguageFindByKey(). * @return LanguageFindByKey */ @Override public String[] getLanguageFindByKey() { return this.languageFindByKey; } /** * fill questions RestoreAction. */ @Override public void fillLanguageRestore() { this.languageRestore[0] = "Восстановить удаленный элемент."; this.languageRestore[1] = "Пожалуйста, введите id востанавливаемого элемента: "; } /** * getLanguageRestore(). * @return LanguageRestore */ @Override public String[] getLanguageRestore() { return this.languageRestore; } /** * fill questions AddCommentAction. */ @Override public void fillLanguageAddComment() { this.languageAddComment[0] = "Добавить новый коментарий элементу по id."; this.languageAddComment[1] = "Пожалуйста, введите id элемента: "; this.languageAddComment[2] = "Пожалуйста, введите новый комментарий: "; } /** * getLanguageAddComment(). * @return LanguageAddComment */ @Override public String[] getLanguageAddComment() { return this.languageAddComment; } }
apache-2.0
freeVM/freeVM
enhanced/buildtest/tests/vts/vm/src/test/vm/jni/reflection/FromReflectedMethodTest/FromReflectedMethodTest.java
2464
/* Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable 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. */ /** * @author Petr Ivanov * @version $Revision: 1.5 $ */ /* * Created on 03.25.2005 */ package org.apache.harmony.vts.test.vm.jni.reflection; import org.apache.harmony.vts.test.vm.jni.share.JNITest; import java.lang.reflect.*; /** * Test creates the reflections of String method and constructor and * provides them to native; in native, methodIDs are derived and * it is checked that they are the same as those derived * by the ordinary JNI means. */ public class FromReflectedMethodTest extends JNITest{ private native boolean nativeExecute(java.lang.reflect.Method mReflection); private native boolean nativeExecute1(java.lang.reflect.Constructor cReflection); /** * Test logics function * @see org.apache.harmony.vts.test.vm.jni.share.JNITest#execute() * @return test result true for passed, false for failed. */ public boolean execute() throws Exception{ java.lang.reflect.Method methodR1, methodR2; java.lang.reflect.Constructor constructorR1, constructorR2; String str = new String("Test"); methodR1 = (str.getClass()).getMethod("length",(Class[])null); methodR2 = (str.getClass()).getMethod("hashCode",(Class[])null); Class[] list = new Class[1]; list[0] = str.getClass(); constructorR1 = (str.getClass()).getConstructor(list); constructorR2 = (str.getClass()).getConstructor((Class[])null); if(nativeExecute(methodR1) == false) return false; if(nativeExecute(methodR2) == true) return false; if(nativeExecute1(constructorR1) == false) return false; if(nativeExecute1(constructorR2) == true) return false; return true; } public static void main(String[] args){ System.exit(new FromReflectedMethodTest().test()); } }
apache-2.0
MHarris021/games-common
src/test/java/com/darcstarsolutions/games/common/beans/rules/SetPlayerScoreRuleTest.java
3203
package com.darcstarsolutions.games.common.beans.rules; import com.darcstarsolutions.games.common.beans.Player; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.math.BigInteger; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.*; public class SetPlayerScoreRuleTest { private Player player; private SetPlayerScoreRule defaultSetPlayerScoreRule; private SetPlayerScoreRule setPlayerScoreRule; @Before public void setUp() throws Exception { player = new Player(); player.setScore(10); defaultSetPlayerScoreRule = new SetPlayerScoreRule(); } @After public void tearDown() throws Exception { player = null; defaultSetPlayerScoreRule = null; setPlayerScoreRule = null; } @Test public void testApplyRule() { assertNotNull(defaultSetPlayerScoreRule); assertNotNull(player); assertThat(player.getScore(), is(equalTo(BigInteger.valueOf(10)))); assertThat(defaultSetPlayerScoreRule.getScore(), is(equalTo(BigInteger.ZERO))); defaultSetPlayerScoreRule.apply(player); assertThat(player.getScore(), is(equalTo(BigInteger.ZERO))); } @Test public void testSetPlayerScoreRule() { assertNotNull(defaultSetPlayerScoreRule); assertThat(defaultSetPlayerScoreRule.getName(), is(equalTo(""))); assertThat(defaultSetPlayerScoreRule.getDescription(), is(equalTo(""))); assertThat(defaultSetPlayerScoreRule.getScore(), is(equalTo(BigInteger.ZERO))); } @Test public void testSetPlayerScoreRuleBigInteger() { setPlayerScoreRule = new SetPlayerScoreRule(BigInteger.ONE); assertNotNull(setPlayerScoreRule); assertThat(setPlayerScoreRule.getScore(), is(equalTo(BigInteger.ONE))); assertThat(player.getScore(), is(equalTo(BigInteger.valueOf(10)))); setPlayerScoreRule.apply(player); assertThat(player.getScore(), is(equalTo(BigInteger.ONE))); } @Test public void testSetPlayerScoreRuleStringStringBigInteger() { setPlayerScoreRule = new SetPlayerScoreRule("test", "test description", BigInteger.ONE); assertNotNull(setPlayerScoreRule); assertNotSame(defaultSetPlayerScoreRule, setPlayerScoreRule); assertThat(setPlayerScoreRule.getName(), is(equalTo("test"))); assertThat(setPlayerScoreRule.getDescription(), is(equalTo("test description"))); assertThat(setPlayerScoreRule.getScore(), is(equalTo(BigInteger.ONE))); } @Test public void testSetPlayerScoreRuleStringString() { setPlayerScoreRule = new SetPlayerScoreRule("test", "test description"); assertNotNull(setPlayerScoreRule); assertNotSame(defaultSetPlayerScoreRule, setPlayerScoreRule); assertThat(setPlayerScoreRule.getName(), is(equalTo("test"))); assertThat(setPlayerScoreRule.getDescription(), is(equalTo("test description"))); assertThat(setPlayerScoreRule.getScore(), is(equalTo(BigInteger.ZERO))); } }
apache-2.0
nince-wyj/jahhan
cache/cache-redis-sentinel/src/main/java/net/jahhan/jedis/JedisFactory.java
3575
package net.jahhan.jedis; import java.net.URI; import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.PooledObjectFactory; import org.apache.commons.pool2.impl.DefaultPooledObject; import redis.clients.jedis.BinaryJedis; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.exceptions.InvalidURIException; import redis.clients.util.JedisURIHelper; /** * PoolableObjectFactory custom impl. */ public class JedisFactory implements PooledObjectFactory<Jedis> { private final AtomicReference<HostAndPort> hostAndPort = new AtomicReference<HostAndPort>(); private final int connectionTimeout; private final String password; private final int database; private final String clientName; public JedisFactory(final String host, final int port, final int connectionTimeout, final String password, final int database, final String clientName) { this.hostAndPort.set(new HostAndPort(host, port)); this.connectionTimeout = connectionTimeout; this.password = password; this.database = database; this.clientName = clientName; } public JedisFactory(final URI uri, final int connectionTimeout, final String clientName) { if (!JedisURIHelper.isValid(uri)) { throw new InvalidURIException( String.format("Cannot open Redis connection due invalid URI. %s", uri.toString())); } this.hostAndPort.set(new HostAndPort(uri.getHost(), uri.getPort())); this.connectionTimeout = connectionTimeout; this.password = JedisURIHelper.getPassword(uri); this.database = JedisURIHelper.getDBIndex(uri); this.clientName = clientName; } public void setHostAndPort(final HostAndPort hostAndPort) { this.hostAndPort.set(hostAndPort); } @Override public void activateObject(PooledObject<Jedis> pooledJedis) throws Exception { final BinaryJedis jedis = pooledJedis.getObject(); if (jedis.getDB() != database) { jedis.select(database); } } @Override public void destroyObject(PooledObject<Jedis> pooledJedis) throws Exception { final BinaryJedis jedis = pooledJedis.getObject(); if (jedis.isConnected()) { try { try { jedis.quit(); } catch (Exception e) { } jedis.disconnect(); } catch (Exception e) { } } } @Override public PooledObject<Jedis> makeObject() throws Exception { final HostAndPort hostAndPort = this.hostAndPort.get(); final Jedis jedis = new Jedis(hostAndPort.getHost(), hostAndPort.getPort(), connectionTimeout); jedis.connect(); if (null != this.password) { jedis.auth(this.password); } if (database != 0) { jedis.select(database); } if (clientName != null) { jedis.clientSetname(clientName); } return new DefaultPooledObject<Jedis>(jedis); } @Override public void passivateObject(PooledObject<Jedis> pooledJedis) throws Exception { // TODO maybe should select db 0? Not sure right now. } @Override public boolean validateObject(PooledObject<Jedis> pooledJedis) { final BinaryJedis jedis = pooledJedis.getObject(); try { HostAndPort hostAndPort = this.hostAndPort.get(); String connectionHost = jedis.getClient().getHost(); int connectionPort = jedis.getClient().getPort(); return hostAndPort.getHost().equals(connectionHost) && hostAndPort.getPort() == connectionPort && jedis.isConnected() && jedis.ping().equals("PONG"); } catch (final Exception e) { return false; } } }
apache-2.0
dturk3/pingnetics
src/com/monitor/model/Bytes.java
576
package com.monitor.model; public class Bytes { private final long mBytes; public Bytes(long bytes) { mBytes = bytes; } public static Bytes fromLong(long bytes) { return new Bytes(bytes); } public float toMegabytes() { return new Float(mBytes).floatValue() / new Float(1048576).floatValue(); } public float toGigabytes() { return new Float(mBytes).floatValue() / new Float(1073741824).floatValue(); } public long getBytes() { return mBytes; } @Override public String toString() { return String.format("%.0f", toMegabytes()) + " MB"; } }
apache-2.0
andytaylor/activemq-artemis
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/bridge/BridgeRoutingTest.java
6761
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.tests.integration.bridge; import java.util.Arrays; import java.util.Collection; import org.apache.activemq.artemis.api.core.QueueConfiguration; import org.apache.activemq.artemis.api.core.RoutingType; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; import org.apache.activemq.artemis.api.core.client.ClientProducer; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.config.BridgeConfiguration; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.ComponentConfigurationRoutingType; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.tests.util.Wait; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(value = Parameterized.class) public class BridgeRoutingTest extends ActiveMQTestBase { private ActiveMQServer server0; private ActiveMQServer server1; private final boolean netty; @Parameterized.Parameters(name = "isNetty={0}") public static Collection getParameters() { return Arrays.asList(new Object[][]{{true}, {false}}); } public BridgeRoutingTest(boolean isNetty) { this.netty = isNetty; } protected boolean isNetty() { return netty; } private String getServer0URL() { return isNetty() ? "tcp://localhost:61616" : "vm://0"; } private String getServer1URL() { return isNetty() ? "tcp://localhost:61617" : "vm://1"; } @Override @Before public void setUp() throws Exception { super.setUp(); server0 = createServer(false, createBasicConfig()); server1 = createServer(false, createBasicConfig()); server0.getConfiguration().addAcceptorConfiguration("acceptor", getServer0URL()); server0.getConfiguration().addConnectorConfiguration("connector", getServer1URL()); server1.getConfiguration().addAcceptorConfiguration("acceptor", getServer1URL()); server0.start(); server1.start(); } @Test public void testAnycastBridge() throws Exception { testBridgeInternal(RoutingType.MULTICAST, RoutingType.ANYCAST, ComponentConfigurationRoutingType.ANYCAST, 0, 1); } @Test public void testAnycastBridgeNegative() throws Exception { testBridgeInternal(RoutingType.MULTICAST, RoutingType.ANYCAST, ComponentConfigurationRoutingType.PASS, 500, 0); } @Test public void testMulticastBridge() throws Exception { testBridgeInternal(RoutingType.ANYCAST, RoutingType.MULTICAST, ComponentConfigurationRoutingType.MULTICAST, 0, 1); } @Test public void testMulticastBridgeNegative() throws Exception { testBridgeInternal(RoutingType.ANYCAST, RoutingType.MULTICAST, ComponentConfigurationRoutingType.PASS, 500, 0); } @Test public void testPassBridge() throws Exception { testBridgeInternal(RoutingType.MULTICAST, RoutingType.MULTICAST, ComponentConfigurationRoutingType.PASS, 0, 1); } @Test public void testPassBridge2() throws Exception { testBridgeInternal(RoutingType.ANYCAST, RoutingType.ANYCAST, ComponentConfigurationRoutingType.PASS, 0, 1); } @Test public void testPassBridgeNegative() throws Exception { testBridgeInternal(RoutingType.ANYCAST, RoutingType.MULTICAST, ComponentConfigurationRoutingType.PASS, 500, 0); } @Test public void testStripBridge() throws Exception { testBridgeInternal(RoutingType.MULTICAST, RoutingType.ANYCAST, ComponentConfigurationRoutingType.STRIP, 0, 1); } @Test public void testStripBridge2() throws Exception { testBridgeInternal(RoutingType.ANYCAST, RoutingType.MULTICAST, ComponentConfigurationRoutingType.STRIP, 0, 1); } private void testBridgeInternal(RoutingType sourceRoutingType, RoutingType destinationRoutingType, ComponentConfigurationRoutingType bridgeRoutingType, long sleepTime, int destinationMessageCount) throws Exception { SimpleString source = SimpleString.toSimpleString("source"); SimpleString destination = SimpleString.toSimpleString("destination"); server0.createQueue(new QueueConfiguration(source).setRoutingType(sourceRoutingType)); server1.createQueue(new QueueConfiguration(destination).setRoutingType(destinationRoutingType)); server0.deployBridge(new BridgeConfiguration() .setRoutingType(bridgeRoutingType) .setName("bridge") .setForwardingAddress(destination.toString()) .setQueueName(source.toString()) .setConfirmationWindowSize(10) .setStaticConnectors(Arrays.asList("connector"))); try (ServerLocator locator = ActiveMQClient.createServerLocator(getServer0URL()); ClientSessionFactory sessionFactory = locator.createSessionFactory(); ClientSession session = sessionFactory.createSession(); ClientProducer producer = session.createProducer(source)) { producer.send(session.createMessage(true).setRoutingType(sourceRoutingType)); } Wait.waitFor(() -> server0.locateQueue(source).getMessageCount() == 0, 2000, 100); Wait.waitFor(() -> server0.getClusterManager().getBridges().get("bridge").getMetrics().getMessagesAcknowledged() == 1, 2000, 100); Thread.sleep(sleepTime); assertTrue(Wait.waitFor(() -> server1.locateQueue(destination).getMessageCount() == destinationMessageCount, 2000, 100)); } }
apache-2.0
Ravmouse/vvasilyev
chapter_004/src/test/java/ru/job4j/h2stream/t4transform/TransformTest.java
1593
package ru.job4j.h2stream.t4transform; import org.junit.Before; import org.junit.Test; import ru.job4j.h2stream.t1filterstudent.Student; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /** * @author Vitaly Vasilyev, date: 21.09.2019, e-mail: rav.energ@rambler.ru * @version 1.0 */ public class TransformTest { /** * Список студентов. */ private final List<CollegeStudent> students = new ArrayList<>(); /** * Карта. */ private final Map<String, Student> expected = new HashMap<>(); /** * Создание студентов и заполнение списка и карты. */ @Before public void init() { final CollegeStudent one = new CollegeStudent(50, "Mike"); final CollegeStudent two = new CollegeStudent(60, "Pete"); final CollegeStudent three = new CollegeStudent(90, "John"); final CollegeStudent four = new CollegeStudent(30, "Carl"); students.addAll(Arrays.asList(one, two, three, four)); expected.put(one.getSurname(), one); expected.put(two.getSurname(), two); expected.put(three.getSurname(), three); expected.put(four.getSurname(), four); } /** * Проверка. */ @Test public void collectToMapTest() { final Map<String, Student> result = Transform.collectToMap(students); assertThat(result, is(expected)); } }
apache-2.0
ozkangokturk/moviefan
src/main/java/com/ozkangokturk/moviefan/web/filter/gzip/GZipServletFilter.java
4356
package com.ozkangokturk.moviefan.web.filter.gzip; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.GZIPOutputStream; public class GZipServletFilter implements Filter { private Logger log = LoggerFactory.getLogger(GZipServletFilter.class); @Override public void init(FilterConfig filterConfig) throws ServletException { // Nothing to initialize } @Override public void destroy() { // Nothing to destroy } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if (!isIncluded(httpRequest) && acceptsGZipEncoding(httpRequest) && !response.isCommitted()) { // Client accepts zipped content if (log.isTraceEnabled()) { log.trace("{} Written with gzip compression", httpRequest.getRequestURL()); } // Create a gzip stream final ByteArrayOutputStream compressed = new ByteArrayOutputStream(); final GZIPOutputStream gzout = new GZIPOutputStream(compressed); // Handle the request final GZipServletResponseWrapper wrapper = new GZipServletResponseWrapper(httpResponse, gzout); wrapper.setDisableFlushBuffer(true); chain.doFilter(request, wrapper); wrapper.flush(); gzout.close(); // double check one more time before writing out // repsonse might have been committed due to error if (response.isCommitted()) { return; } // return on these special cases when content is empty or unchanged switch (wrapper.getStatus()) { case HttpServletResponse.SC_NO_CONTENT: case HttpServletResponse.SC_RESET_CONTENT: case HttpServletResponse.SC_NOT_MODIFIED: return; default: } // Saneness checks byte[] compressedBytes = compressed.toByteArray(); boolean shouldGzippedBodyBeZero = GZipResponseUtil.shouldGzippedBodyBeZero(compressedBytes, httpRequest); boolean shouldBodyBeZero = GZipResponseUtil.shouldBodyBeZero(httpRequest, wrapper.getStatus()); if (shouldGzippedBodyBeZero || shouldBodyBeZero) { // No reason to add GZIP headers or write body if no content was written or status code specifies no // content response.setContentLength(0); return; } // Write the zipped body GZipResponseUtil.addGzipHeader(httpResponse); response.setContentLength(compressedBytes.length); response.getOutputStream().write(compressedBytes); } else { // Client does not accept zipped content - don't bother zipping if (log.isTraceEnabled()) { log.trace("{} Written without gzip compression because the request does not accept gzip", httpRequest.getRequestURL()); } chain.doFilter(request, response); } } /** * Checks if the request uri is an include. These cannot be gzipped. */ private boolean isIncluded(final HttpServletRequest request) { String uri = (String) request.getAttribute("javax.servlet.include.request_uri"); boolean includeRequest = !(uri == null); if (includeRequest && log.isDebugEnabled()) { log.debug("{} resulted in an include request. This is unusable, because" + "the response will be assembled into the overrall response. Not gzipping.", request.getRequestURL()); } return includeRequest; } private boolean acceptsGZipEncoding(HttpServletRequest httpRequest) { String acceptEncoding = httpRequest.getHeader("Accept-Encoding"); return acceptEncoding != null && acceptEncoding.contains("gzip"); } }
apache-2.0
chRyNaN/Android-Guitar-Tuner
app/src/main/java/com/chrynan/android_guitar_tuner/ui/view/TunerView.java
327
package com.chrynan.android_guitar_tuner.ui.view; /** * A View interface for a view implementation that reacts to the result of a tuner. */ public interface TunerView { void onShowNote(String noteName, double frequency, float percentOffset); void onPlayNote(String noteName, double frequency, float x, float y); }
apache-2.0
chmyga/component-runtime
sample-parent/documentation-sample/datastorevalidation-component/src/main/java/org/talend/sdk/component/documentation/sample/datastorevalidation/components/source/DataStoreValidationInputSource.java
1988
/** * Copyright (C) 2006-2020 Talend Inc. - www.talend.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.talend.sdk.component.documentation.sample.datastorevalidation.components.source; import java.io.Serializable; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.talend.sdk.component.api.configuration.Option; import org.talend.sdk.component.api.input.Producer; import org.talend.sdk.component.api.meta.Documentation; import org.talend.sdk.component.api.record.Record; import org.talend.sdk.component.api.service.record.RecordBuilderFactory; import org.talend.sdk.component.documentation.sample.datastorevalidation.components.service.DatastorevalidationComponentService; @Documentation("TODO fill the documentation for this source") public class DataStoreValidationInputSource implements Serializable { private final DataStoreValidationInputMapperConfiguration configuration; public DataStoreValidationInputSource( @Option("configuration") final DataStoreValidationInputMapperConfiguration configuration) { this.configuration = configuration; } @Producer public Record next() { // this is the method allowing you to go through the dataset associated // to the component configuration // // return null means the dataset has no more data to go through // you can use the builderFactory to create a new Record. return null; } }
apache-2.0
crate/crate
server/src/main/java/io/crate/expression/tablefunctions/PgGetKeywordsFunction.java
3788
/* * Licensed to Crate.io GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.expression.tablefunctions; import io.crate.data.Input; import io.crate.data.Row; import io.crate.data.RowN; import io.crate.metadata.FunctionName; import io.crate.metadata.NodeContext; import io.crate.metadata.TransactionContext; import io.crate.metadata.functions.Signature; import io.crate.metadata.pgcatalog.PgCatalogSchemaInfo; import io.crate.metadata.tablefunctions.TableFunctionImplementation; import io.crate.sql.Identifiers; import io.crate.types.RowType; import java.util.List; import java.util.Locale; import java.util.function.Function; import static io.crate.types.DataTypes.STRING; public final class PgGetKeywordsFunction extends TableFunctionImplementation<List<Object>> { private static final String NAME = "pg_get_keywords"; private static final FunctionName FUNCTION_NAME = new FunctionName(PgCatalogSchemaInfo.NAME, NAME); private static final RowType RETURN_TYPE = new RowType( List.of(STRING, STRING, STRING), List.of("word", "catcode", "catdesc") ); public static void register(TableFunctionModule module) { module.register( Signature.table( FUNCTION_NAME, RETURN_TYPE.getTypeSignature() ), PgGetKeywordsFunction::new ); } private final Signature signature; private final Signature boundSignature; public PgGetKeywordsFunction(Signature signature, Signature boundSignature) { this.signature = signature; this.boundSignature = boundSignature; } @Override public Iterable<Row> evaluate(TransactionContext txnCtx, NodeContext nodeCtx, Input<List<Object>>[] args) { return () -> Identifiers.KEYWORDS.stream() .map(new Function<Identifiers.Keyword, Row>() { final Object[] columns = new Object[3]; final RowN row = new RowN(columns); @Override public Row apply(Identifiers.Keyword keyword) { columns[0] = keyword.getWord().toLowerCase(Locale.ENGLISH); if (keyword.isReserved()) { columns[1] = "R"; columns[2] = "reserved"; } else { columns[1] = "U"; columns[2] = "unreserved"; } return row; } }).iterator(); } @Override public Signature signature() { return signature; } @Override public Signature boundSignature() { return boundSignature; } @Override public RowType returnType() { return RETURN_TYPE; } @Override public boolean hasLazyResultSet() { return false; } }
apache-2.0
jefperito/nfe
src/main/java/com/fincatto/documentofiscal/nfe310/classes/nota/NFNotaInfoItemProdutoDeclaracaoImportacaoAdicao.java
2544
package com.fincatto.documentofiscal.nfe310.classes.nota; import java.math.BigDecimal; import java.math.BigInteger; import org.simpleframework.xml.Element; import com.fincatto.documentofiscal.DFBase; import com.fincatto.documentofiscal.validadores.BigDecimalParser; import com.fincatto.documentofiscal.validadores.BigIntegerValidador; import com.fincatto.documentofiscal.validadores.IntegerValidador; import com.fincatto.documentofiscal.validadores.StringValidador; public class NFNotaInfoItemProdutoDeclaracaoImportacaoAdicao extends DFBase { private static final long serialVersionUID = -7286071184901675008L; @Element(name = "nAdicao", required = true) private Integer numero; @Element(name = "nSeqAdic", required = true) private Integer sequencial; @Element(name = "cFabricante", required = true) private String codigoFabricante; @Element(name = "vDescDI", required = false) private String desconto; @Element(name = "nDraw", required = false) private BigInteger numeroAtoConcessorioDrawback; public void setNumero(final Integer numero) { IntegerValidador.tamanho3(numero, "Numero Declaracao Importacao Adicao"); this.numero = numero; } public void setSequencial(final Integer sequencial) { IntegerValidador.tamanho3(sequencial, "Sequencial Declaracao Importacao Adicao"); this.sequencial = sequencial; } public void setCodigoFabricante(final String codigoFabricante) { StringValidador.tamanho60(codigoFabricante, "Codigo Fabricante Declaracao Importacao Adicao"); this.codigoFabricante = codigoFabricante; } public void setDesconto(final BigDecimal desconto) { this.desconto = BigDecimalParser.tamanho15Com2CasasDecimais(desconto, "Desconto Declaracao Importacao Adicao"); } public void setNumeroAtoConcessorioDrawback(final BigInteger numeroAtoConcessorioDrawback) { BigIntegerValidador.tamanho11(numeroAtoConcessorioDrawback, "Numero Ato Concessorio Declaracao Importacao Adicao"); this.numeroAtoConcessorioDrawback = numeroAtoConcessorioDrawback; } public Integer getNumero() { return this.numero; } public Integer getSequencial() { return this.sequencial; } public String getCodigoFabricante() { return this.codigoFabricante; } public String getDesconto() { return this.desconto; } public BigInteger getNumeroAtoConcessorioDrawback() { return this.numeroAtoConcessorioDrawback; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-codecommit/src/main/java/com/amazonaws/services/codecommit/model/ApprovalRuleEventMetadata.java
7510
/* * 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.codecommit.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Returns information about an event for an approval rule. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/ApprovalRuleEventMetadata" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ApprovalRuleEventMetadata implements Serializable, Cloneable, StructuredPojo { /** * <p> * The name of the approval rule. * </p> */ private String approvalRuleName; /** * <p> * The system-generated ID of the approval rule. * </p> */ private String approvalRuleId; /** * <p> * The content of the approval rule. * </p> */ private String approvalRuleContent; /** * <p> * The name of the approval rule. * </p> * * @param approvalRuleName * The name of the approval rule. */ public void setApprovalRuleName(String approvalRuleName) { this.approvalRuleName = approvalRuleName; } /** * <p> * The name of the approval rule. * </p> * * @return The name of the approval rule. */ public String getApprovalRuleName() { return this.approvalRuleName; } /** * <p> * The name of the approval rule. * </p> * * @param approvalRuleName * The name of the approval rule. * @return Returns a reference to this object so that method calls can be chained together. */ public ApprovalRuleEventMetadata withApprovalRuleName(String approvalRuleName) { setApprovalRuleName(approvalRuleName); return this; } /** * <p> * The system-generated ID of the approval rule. * </p> * * @param approvalRuleId * The system-generated ID of the approval rule. */ public void setApprovalRuleId(String approvalRuleId) { this.approvalRuleId = approvalRuleId; } /** * <p> * The system-generated ID of the approval rule. * </p> * * @return The system-generated ID of the approval rule. */ public String getApprovalRuleId() { return this.approvalRuleId; } /** * <p> * The system-generated ID of the approval rule. * </p> * * @param approvalRuleId * The system-generated ID of the approval rule. * @return Returns a reference to this object so that method calls can be chained together. */ public ApprovalRuleEventMetadata withApprovalRuleId(String approvalRuleId) { setApprovalRuleId(approvalRuleId); return this; } /** * <p> * The content of the approval rule. * </p> * * @param approvalRuleContent * The content of the approval rule. */ public void setApprovalRuleContent(String approvalRuleContent) { this.approvalRuleContent = approvalRuleContent; } /** * <p> * The content of the approval rule. * </p> * * @return The content of the approval rule. */ public String getApprovalRuleContent() { return this.approvalRuleContent; } /** * <p> * The content of the approval rule. * </p> * * @param approvalRuleContent * The content of the approval rule. * @return Returns a reference to this object so that method calls can be chained together. */ public ApprovalRuleEventMetadata withApprovalRuleContent(String approvalRuleContent) { setApprovalRuleContent(approvalRuleContent); 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 (getApprovalRuleName() != null) sb.append("ApprovalRuleName: ").append(getApprovalRuleName()).append(","); if (getApprovalRuleId() != null) sb.append("ApprovalRuleId: ").append(getApprovalRuleId()).append(","); if (getApprovalRuleContent() != null) sb.append("ApprovalRuleContent: ").append(getApprovalRuleContent()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ApprovalRuleEventMetadata == false) return false; ApprovalRuleEventMetadata other = (ApprovalRuleEventMetadata) obj; if (other.getApprovalRuleName() == null ^ this.getApprovalRuleName() == null) return false; if (other.getApprovalRuleName() != null && other.getApprovalRuleName().equals(this.getApprovalRuleName()) == false) return false; if (other.getApprovalRuleId() == null ^ this.getApprovalRuleId() == null) return false; if (other.getApprovalRuleId() != null && other.getApprovalRuleId().equals(this.getApprovalRuleId()) == false) return false; if (other.getApprovalRuleContent() == null ^ this.getApprovalRuleContent() == null) return false; if (other.getApprovalRuleContent() != null && other.getApprovalRuleContent().equals(this.getApprovalRuleContent()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getApprovalRuleName() == null) ? 0 : getApprovalRuleName().hashCode()); hashCode = prime * hashCode + ((getApprovalRuleId() == null) ? 0 : getApprovalRuleId().hashCode()); hashCode = prime * hashCode + ((getApprovalRuleContent() == null) ? 0 : getApprovalRuleContent().hashCode()); return hashCode; } @Override public ApprovalRuleEventMetadata clone() { try { return (ApprovalRuleEventMetadata) 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.codecommit.model.transform.ApprovalRuleEventMetadataMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
codehaus/xbean
xbean-reflect/src/main/java/org/apache/xbean/propertyeditor/MapEditor.java
1170
/** * * Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable. * * 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.apache.xbean.propertyeditor; import java.util.LinkedHashMap; import java.util.Map; /** * A property editor for indirect property bundles. This editor * transforms the text value of the propery into a Property resource bundle. * * @version $Rev: 6680 $ */ public class MapEditor extends AbstractMapConverter { public MapEditor() { super(Map.class); } protected Map createMap(Map map) { Map finalMap = new LinkedHashMap(map); return finalMap; } }
apache-2.0
pascalrobert/aribaweb
src/metaui/src/main/java/ariba/ui/meta/core/ParserTokenManager.java
43074
/* ParserTokenManager.java */ /* Generated By:JavaCC: Do not edit this line. ParserTokenManager.java */ package ariba.ui.meta.core; import ariba.util.core.Fmt; import ariba.util.core.ListUtil; import java.math.BigDecimal; import java.math.BigInteger; import java.io.BufferedReader; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** Token Manager. */ @SuppressWarnings("unused")public class ParserTokenManager implements ParserConstants { /** Holds the last value computed by a constant token. */ Object literalValue; /** Holds the last character escaped or in a character literal. */ private char charValue; /** Holds char literal start token. */ private char charLiteralStartQuote; /** Holds the last string literal parsed. */ private StringBuffer stringBuffer; /** Indicates whether last EXPR_LITERAL is of the "$${" variety **/ boolean isStaticDynamicExpr; int braceNestingDepth; /** Converts an escape sequence into a character value. */ private char escapeChar() { int ofs = image.length() - 1; switch ( image.charAt(ofs) ) { case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case 'b': return '\b'; case 'f': return '\f'; case '\\': return '\\'; case '\'': return '\''; case '\"': return '\"'; } // Otherwise, it's an octal number. Find the backslash and convert. while ( image.charAt(--ofs) != '\\' ) {} int value = 0; while ( ++ofs < image.length() ) value = (value << 3) | (image.charAt(ofs) - '0'); return (char) value; } private Object makeInt() { Object result; String s = image.toString(); int base = 10; if ( s.charAt(0) == '0' ) base = (s.length() > 1 && (s.charAt(1) == 'x' || s.charAt(1) == 'X'))? 16 : 8; if ( base == 16 ) s = s.substring(2); // Trim the 0x off the front switch ( s.charAt(s.length()-1) ) { case 'l': case 'L': result = Long.valueOf( s.substring(0,s.length()-1), base ); break; case 'h': case 'H': result = new BigInteger( s.substring(0,s.length()-1), base ); break; default: result = Integer.valueOf( s, base ); break; } return result; } private Object makeFloat() { String s = image.toString(); switch ( s.charAt(s.length()-1) ) { case 'f': case 'F': return Float.valueOf( s ); case 'b': case 'B': return new BigDecimal( s.substring(0,s.length()-1) ); case 'd': case 'D': default: return Double.valueOf( s ); } } /** Debug output. */ public java.io.PrintStream debugStream = System.out; /** Set debug output. */ public void setDebugStream(java.io.PrintStream ds) { debugStream = ds; } private final int jjStopStringLiteralDfa_0(int pos, long active0){ switch (pos) { case 0: if ((active0 & 0xe0000L) != 0L) { jjmatchedKind = 28; return 31; } if ((active0 & 0xc00000000000L) != 0L) return 26; return -1; case 1: if ((active0 & 0xe0000L) != 0L) { jjmatchedKind = 28; jjmatchedPos = 1; return 31; } return -1; case 2: if ((active0 & 0xe0000L) != 0L) { jjmatchedKind = 28; jjmatchedPos = 2; return 31; } return -1; case 3: if ((active0 & 0x40000L) != 0L) { jjmatchedKind = 28; jjmatchedPos = 3; return 31; } if ((active0 & 0xa0000L) != 0L) return 31; return -1; default : return -1; } } private final int jjStartNfa_0(int pos, long active0){ return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0), pos + 1); } private int jjStopAtPos(int pos, int kind) { jjmatchedKind = kind; jjmatchedPos = pos; return pos + 1; } private int jjMoveStringLiteralDfa0_0(){ switch(curChar) { case 33: return jjStopAtPos(0, 6); case 34: return jjStopAtPos(0, 32); case 35: return jjStopAtPos(0, 1); case 36: return jjMoveStringLiteralDfa1_0(0xc00000000000L); case 39: return jjStopAtPos(0, 33); case 40: return jjStopAtPos(0, 11); case 41: return jjStopAtPos(0, 12); case 42: return jjStopAtPos(0, 7); case 44: return jjStopAtPos(0, 14); case 47: return jjMoveStringLiteralDfa1_0(0x2000000L); case 58: return jjStopAtPos(0, 5); case 59: return jjStopAtPos(0, 4); case 61: jjmatchedKind = 10; return jjMoveStringLiteralDfa1_0(0x100L); case 64: return jjStopAtPos(0, 9); case 91: return jjStopAtPos(0, 15); case 93: return jjStopAtPos(0, 16); case 102: return jjMoveStringLiteralDfa1_0(0x40000L); case 110: return jjMoveStringLiteralDfa1_0(0x80000L); case 116: return jjMoveStringLiteralDfa1_0(0x20000L); case 123: return jjStopAtPos(0, 2); case 125: return jjStopAtPos(0, 3); case 126: return jjStopAtPos(0, 13); default : return jjMoveNfa_0(0, 0); } } private int jjMoveStringLiteralDfa1_0(long active0){ try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(0, active0); return 1; } switch(curChar) { case 36: return jjMoveStringLiteralDfa2_0(active0, 0x800000000000L); case 42: if ((active0 & 0x2000000L) != 0L) return jjStopAtPos(1, 25); break; case 62: if ((active0 & 0x100L) != 0L) return jjStopAtPos(1, 8); break; case 97: return jjMoveStringLiteralDfa2_0(active0, 0x40000L); case 114: return jjMoveStringLiteralDfa2_0(active0, 0x20000L); case 117: return jjMoveStringLiteralDfa2_0(active0, 0x80000L); case 123: if ((active0 & 0x400000000000L) != 0L) return jjStopAtPos(1, 46); break; default : break; } return jjStartNfa_0(0, active0); } private int jjMoveStringLiteralDfa2_0(long old0, long active0){ if (((active0 &= old0)) == 0L) return jjStartNfa_0(0, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(1, active0); return 2; } switch(curChar) { case 108: return jjMoveStringLiteralDfa3_0(active0, 0xc0000L); case 117: return jjMoveStringLiteralDfa3_0(active0, 0x20000L); case 123: if ((active0 & 0x800000000000L) != 0L) return jjStopAtPos(2, 47); break; default : break; } return jjStartNfa_0(1, active0); } private int jjMoveStringLiteralDfa3_0(long old0, long active0){ if (((active0 &= old0)) == 0L) return jjStartNfa_0(1, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(2, active0); return 3; } switch(curChar) { case 101: if ((active0 & 0x20000L) != 0L) return jjStartNfaWithStates_0(3, 17, 31); break; case 108: if ((active0 & 0x80000L) != 0L) return jjStartNfaWithStates_0(3, 19, 31); break; case 115: return jjMoveStringLiteralDfa4_0(active0, 0x40000L); default : break; } return jjStartNfa_0(2, active0); } private int jjMoveStringLiteralDfa4_0(long old0, long active0){ if (((active0 &= old0)) == 0L) return jjStartNfa_0(2, old0); try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { jjStopStringLiteralDfa_0(3, active0); return 4; } switch(curChar) { case 101: if ((active0 & 0x40000L) != 0L) return jjStartNfaWithStates_0(4, 18, 31); break; default : break; } return jjStartNfa_0(3, active0); } private int jjStartNfaWithStates_0(int pos, int kind, int state) { jjmatchedKind = kind; jjmatchedPos = pos; try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return pos + 1; } return jjMoveNfa_0(state, pos + 1); } private int jjMoveNfa_0(int startState, int curPos) { int startsAt = 0; jjnewStateCnt = 31; int i = 1; jjstateSet[0] = startState; int kind = 0x7fffffff; for (;;) { if (++jjround == 0x7fffffff) ReInitRounds(); if (curChar < 64) { long l = 1L << curChar; do { switch(jjstateSet[--i]) { case 0: if ((0x3ff000000000000L & l) != 0L) { jjCheckNAddStates(0, 5); } else if (curChar == 36) { jjAddStates(6, 7); } else if (curChar == 46) { jjCheckNAdd(4); } if ((0x3fe000000000000L & l) != 0L) { if (kind > 40) kind = 40; { jjCheckNAddTwoStates(1, 2); } } else if (curChar == 48) { if (kind > 40) kind = 40; { jjCheckNAddStates(8, 10); } } break; case 31: if ((0x3ff401000000000L & l) != 0L) { if (kind > 29) kind = 29; { jjCheckNAdd(24); } } if ((0x3ff000000000000L & l) != 0L) { if (kind > 28) kind = 28; { jjCheckNAdd(23); } } break; case 1: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 40) kind = 40; { jjCheckNAddTwoStates(1, 2); } break; case 3: if (curChar == 46) { jjCheckNAdd(4); } break; case 4: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 41) kind = 41; { jjCheckNAddStates(11, 13); } break; case 6: if ((0x280000000000L & l) != 0L) { jjCheckNAdd(7); } break; case 7: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 41) kind = 41; { jjCheckNAddTwoStates(7, 8); } break; case 9: if ((0x3ff000000000000L & l) != 0L) { jjCheckNAddStates(0, 5); } break; case 10: if ((0x3ff000000000000L & l) != 0L) { jjCheckNAddTwoStates(10, 11); } break; case 11: if (curChar != 46) break; if (kind > 41) kind = 41; { jjCheckNAddStates(14, 16); } break; case 12: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 41) kind = 41; { jjCheckNAddStates(14, 16); } break; case 13: if ((0x3ff000000000000L & l) != 0L) { jjCheckNAddTwoStates(13, 14); } break; case 15: if ((0x280000000000L & l) != 0L) { jjCheckNAdd(16); } break; case 16: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 41) kind = 41; { jjCheckNAddTwoStates(16, 8); } break; case 17: if ((0x3ff000000000000L & l) != 0L) { jjCheckNAddTwoStates(17, 8); } break; case 18: if (curChar != 48) break; if (kind > 40) kind = 40; { jjCheckNAddStates(8, 10); } break; case 19: if ((0xff000000000000L & l) == 0L) break; if (kind > 40) kind = 40; { jjCheckNAddTwoStates(19, 2); } break; case 21: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 40) kind = 40; { jjCheckNAddTwoStates(21, 2); } break; case 23: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 28) kind = 28; { jjCheckNAdd(23); } break; case 24: if ((0x3ff401000000000L & l) == 0L) break; if (kind > 29) kind = 29; { jjCheckNAdd(24); } break; case 25: if (curChar == 36) { jjAddStates(6, 7); } break; case 27: if ((0x3ff400000000000L & l) == 0L) break; if (kind > 30) kind = 30; jjstateSet[jjnewStateCnt++] = 27; break; case 29: if ((0x3ff000000000000L & l) != 0L) { jjAddStates(17, 18); } break; default : break; } } while(i != startsAt); } else if (curChar < 128) { long l = 1L << (curChar & 077); do { switch(jjstateSet[--i]) { case 0: if ((0x7fffffe87fffffeL & l) == 0L) break; if (kind > 28) kind = 28; { jjCheckNAddTwoStates(23, 24); } break; case 31: if ((0x7fffffe87fffffeL & l) != 0L) { if (kind > 29) kind = 29; { jjCheckNAdd(24); } } if ((0x7fffffe87fffffeL & l) != 0L) { if (kind > 28) kind = 28; { jjCheckNAdd(23); } } break; case 26: if ((0x7fffffe87fffffeL & l) != 0L) { if (kind > 30) kind = 30; { jjCheckNAdd(27); } } else if (curChar == 91) { jjCheckNAddTwoStates(29, 30); } break; case 2: if ((0x110000001100L & l) != 0L && kind > 40) kind = 40; break; case 5: if ((0x2000000020L & l) != 0L) { jjAddStates(19, 20); } break; case 8: if ((0x5400000054L & l) != 0L && kind > 41) kind = 41; break; case 14: if ((0x2000000020L & l) != 0L) { jjAddStates(21, 22); } break; case 20: if ((0x100000001000000L & l) != 0L) { jjCheckNAdd(21); } break; case 21: if ((0x7e0000007eL & l) == 0L) break; if (kind > 40) kind = 40; { jjCheckNAddTwoStates(21, 2); } break; case 23: if ((0x7fffffe87fffffeL & l) == 0L) break; if (kind > 28) kind = 28; { jjCheckNAdd(23); } break; case 24: if ((0x7fffffe87fffffeL & l) == 0L) break; if (kind > 29) kind = 29; { jjCheckNAdd(24); } break; case 27: if ((0x7fffffe87fffffeL & l) == 0L) break; if (kind > 30) kind = 30; { jjCheckNAdd(27); } break; case 28: if (curChar == 91) { jjCheckNAddTwoStates(29, 30); } break; case 29: if ((0x7fffffe87fffffeL & l) != 0L) { jjCheckNAddTwoStates(29, 30); } break; case 30: if (curChar == 93) kind = 31; break; default : break; } } while(i != startsAt); } else { int hiByte = (curChar >> 8); int i1 = hiByte >> 6; long l1 = 1L << (hiByte & 077); int i2 = (curChar & 0xff) >> 6; long l2 = 1L << (curChar & 077); do { switch(jjstateSet[--i]) { default : if (i1 == 0 || l1 == 0 || i2 == 0 || l2 == 0) break; else break; } } while(i != startsAt); } if (kind != 0x7fffffff) { jjmatchedKind = kind; jjmatchedPos = curPos; kind = 0x7fffffff; } ++curPos; if ((i = jjnewStateCnt) == (startsAt = 31 - (jjnewStateCnt = startsAt))) return curPos; try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return curPos; } } } private final int jjStopStringLiteralDfa_5(int pos, long active0){ switch (pos) { default : return -1; } } private final int jjStartNfa_5(int pos, long active0){ return jjMoveNfa_5(jjStopStringLiteralDfa_5(pos, active0), pos + 1); } private int jjMoveStringLiteralDfa0_5(){ switch(curChar) { case 123: return jjStopAtPos(0, 50); case 125: return jjStopAtPos(0, 52); default : return jjMoveNfa_5(0, 0); } } static final long[] jjbitVec0 = { 0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL }; static final long[] jjbitVec2 = { 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL }; private int jjMoveNfa_5(int startState, int curPos) { int startsAt = 0; jjnewStateCnt = 1; int i = 1; jjstateSet[0] = startState; int kind = 0x7fffffff; for (;;) { if (++jjround == 0x7fffffff) ReInitRounds(); if (curChar < 64) { long l = 1L << curChar; do { switch(jjstateSet[--i]) { case 0: kind = 51; break; default : break; } } while(i != startsAt); } else if (curChar < 128) { long l = 1L << (curChar & 077); do { switch(jjstateSet[--i]) { case 0: if ((0xd7ffffffffffffffL & l) != 0L) kind = 51; break; default : break; } } while(i != startsAt); } else { int hiByte = (curChar >> 8); int i1 = hiByte >> 6; long l1 = 1L << (hiByte & 077); int i2 = (curChar & 0xff) >> 6; long l2 = 1L << (curChar & 077); do { switch(jjstateSet[--i]) { case 0: if (jjCanMove_0(hiByte, i1, i2, l1, l2) && kind > 51) kind = 51; break; default : if (i1 == 0 || l1 == 0 || i2 == 0 || l2 == 0) break; else break; } } while(i != startsAt); } if (kind != 0x7fffffff) { jjmatchedKind = kind; jjmatchedPos = curPos; kind = 0x7fffffff; } ++curPos; if ((i = jjnewStateCnt) == (startsAt = 1 - (jjnewStateCnt = startsAt))) return curPos; try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return curPos; } } } private final int jjStopStringLiteralDfa_4(int pos, long active0){ switch (pos) { default : return -1; } } private final int jjStartNfa_4(int pos, long active0){ return jjMoveNfa_4(jjStopStringLiteralDfa_4(pos, active0), pos + 1); } private int jjMoveStringLiteralDfa0_4(){ switch(curChar) { case 123: return jjStopAtPos(0, 48); case 125: return jjStopAtPos(0, 53); default : return jjMoveNfa_4(0, 0); } } private int jjMoveNfa_4(int startState, int curPos) { int startsAt = 0; jjnewStateCnt = 1; int i = 1; jjstateSet[0] = startState; int kind = 0x7fffffff; for (;;) { if (++jjround == 0x7fffffff) ReInitRounds(); if (curChar < 64) { long l = 1L << curChar; do { switch(jjstateSet[--i]) { case 0: kind = 49; break; default : break; } } while(i != startsAt); } else if (curChar < 128) { long l = 1L << (curChar & 077); do { switch(jjstateSet[--i]) { case 0: if ((0xd7ffffffffffffffL & l) != 0L) kind = 49; break; default : break; } } while(i != startsAt); } else { int hiByte = (curChar >> 8); int i1 = hiByte >> 6; long l1 = 1L << (hiByte & 077); int i2 = (curChar & 0xff) >> 6; long l2 = 1L << (curChar & 077); do { switch(jjstateSet[--i]) { case 0: if (jjCanMove_0(hiByte, i1, i2, l1, l2) && kind > 49) kind = 49; break; default : if (i1 == 0 || l1 == 0 || i2 == 0 || l2 == 0) break; else break; } } while(i != startsAt); } if (kind != 0x7fffffff) { jjmatchedKind = kind; jjmatchedPos = curPos; kind = 0x7fffffff; } ++curPos; if ((i = jjnewStateCnt) == (startsAt = 1 - (jjnewStateCnt = startsAt))) return curPos; try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return curPos; } } } private final int jjStopStringLiteralDfa_3(int pos, long active0){ switch (pos) { default : return -1; } } private final int jjStartNfa_3(int pos, long active0){ return jjMoveNfa_3(jjStopStringLiteralDfa_3(pos, active0), pos + 1); } private int jjMoveStringLiteralDfa0_3(){ switch(curChar) { case 39: return jjStopAtPos(0, 39); default : return jjMoveNfa_3(0, 0); } } private int jjMoveNfa_3(int startState, int curPos) { int startsAt = 0; jjnewStateCnt = 1; int i = 1; jjstateSet[0] = startState; int kind = 0x7fffffff; for (;;) { if (++jjround == 0x7fffffff) ReInitRounds(); if (curChar < 64) { long l = 1L << curChar; do { switch(jjstateSet[--i]) { case 0: if ((0xffffff7fffffffffL & l) != 0L) kind = 38; break; default : break; } } while(i != startsAt); } else if (curChar < 128) { long l = 1L << (curChar & 077); do { switch(jjstateSet[--i]) { case 0: if ((0xffffffffefffffffL & l) != 0L) kind = 38; break; default : break; } } while(i != startsAt); } else { int hiByte = (curChar >> 8); int i1 = hiByte >> 6; long l1 = 1L << (hiByte & 077); int i2 = (curChar & 0xff) >> 6; long l2 = 1L << (curChar & 077); do { switch(jjstateSet[--i]) { case 0: if (jjCanMove_0(hiByte, i1, i2, l1, l2) && kind > 38) kind = 38; break; default : if (i1 == 0 || l1 == 0 || i2 == 0 || l2 == 0) break; else break; } } while(i != startsAt); } if (kind != 0x7fffffff) { jjmatchedKind = kind; jjmatchedPos = curPos; kind = 0x7fffffff; } ++curPos; if ((i = jjnewStateCnt) == (startsAt = 1 - (jjnewStateCnt = startsAt))) return curPos; try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return curPos; } } } private final int jjStopStringLiteralDfa_2(int pos, long active0){ switch (pos) { default : return -1; } } private final int jjStartNfa_2(int pos, long active0){ return jjMoveNfa_2(jjStopStringLiteralDfa_2(pos, active0), pos + 1); } private int jjMoveStringLiteralDfa0_2(){ switch(curChar) { case 34: return jjStopAtPos(0, 37); default : return jjMoveNfa_2(0, 0); } } private int jjMoveNfa_2(int startState, int curPos) { int startsAt = 0; jjnewStateCnt = 10; int i = 1; jjstateSet[0] = startState; int kind = 0x7fffffff; for (;;) { if (++jjround == 0x7fffffff) ReInitRounds(); if (curChar < 64) { long l = 1L << curChar; do { switch(jjstateSet[--i]) { case 0: if ((0xfffffffbffffffffL & l) != 0L && kind > 36) kind = 36; break; case 2: if ((0x8400000000L & l) != 0L && kind > 34) kind = 34; break; case 3: if ((0xf000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 4; break; case 4: if ((0xff000000000000L & l) == 0L) break; if (kind > 34) kind = 34; jjstateSet[jjnewStateCnt++] = 5; break; case 5: if ((0xff000000000000L & l) != 0L && kind > 34) kind = 34; break; case 6: if ((0x8400000000L & l) != 0L && kind > 35) kind = 35; break; case 7: if ((0xf000000000000L & l) != 0L) jjstateSet[jjnewStateCnt++] = 8; break; case 8: if ((0xff000000000000L & l) == 0L) break; if (kind > 35) kind = 35; jjstateSet[jjnewStateCnt++] = 9; break; case 9: if ((0xff000000000000L & l) != 0L && kind > 35) kind = 35; break; default : break; } } while(i != startsAt); } else if (curChar < 128) { long l = 1L << (curChar & 077); do { switch(jjstateSet[--i]) { case 0: if ((0xffffffffefffffffL & l) != 0L) { if (kind > 36) kind = 36; } else if (curChar == 92) { jjAddStates(23, 28); } break; case 1: if (curChar == 92) { jjAddStates(23, 28); } break; case 2: if ((0x14404510000000L & l) != 0L && kind > 34) kind = 34; break; case 6: if ((0x14404510000000L & l) != 0L && kind > 35) kind = 35; break; default : break; } } while(i != startsAt); } else { int hiByte = (curChar >> 8); int i1 = hiByte >> 6; long l1 = 1L << (hiByte & 077); int i2 = (curChar & 0xff) >> 6; long l2 = 1L << (curChar & 077); do { switch(jjstateSet[--i]) { case 0: if (jjCanMove_0(hiByte, i1, i2, l1, l2) && kind > 36) kind = 36; break; default : if (i1 == 0 || l1 == 0 || i2 == 0 || l2 == 0) break; else break; } } while(i != startsAt); } if (kind != 0x7fffffff) { jjmatchedKind = kind; jjmatchedPos = curPos; kind = 0x7fffffff; } ++curPos; if ((i = jjnewStateCnt) == (startsAt = 10 - (jjnewStateCnt = startsAt))) return curPos; try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return curPos; } } } private int jjMoveStringLiteralDfa0_1(){ switch(curChar) { case 42: return jjMoveStringLiteralDfa1_1(0x4000000L); default : return 1; } } private int jjMoveStringLiteralDfa1_1(long active0){ try { curChar = input_stream.readChar(); } catch(java.io.IOException e) { return 1; } switch(curChar) { case 47: if ((active0 & 0x4000000L) != 0L) return jjStopAtPos(1, 26); break; default : return 2; } return 2; } static final int[] jjnextStates = { 10, 11, 13, 14, 17, 8, 26, 28, 19, 20, 2, 4, 5, 8, 12, 5, 8, 29, 30, 6, 7, 15, 16, 2, 3, 4, 6, 7, 8, }; private static final boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2) { switch(hiByte) { case 0: return ((jjbitVec2[i2] & l2) != 0L); default : if ((jjbitVec0[i1] & l1) != 0L) return true; return false; } } /** Token literal values. */ public static final String[] jjstrLiteralImages = { "", "\43", "\173", "\175", "\73", "\72", "\41", "\52", "\75\76", "\100", "\75", "\50", "\51", "\176", "\54", "\133", "\135", "\164\162\165\145", "\146\141\154\163\145", "\156\165\154\154", null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, }; protected Token jjFillToken() { final Token t; final String curTokenImage; final int beginLine; final int endLine; final int beginColumn; final int endColumn; String im = jjstrLiteralImages[jjmatchedKind]; curTokenImage = (im == null) ? input_stream.GetImage() : im; beginLine = input_stream.getBeginLine(); beginColumn = input_stream.getBeginColumn(); endLine = input_stream.getEndLine(); endColumn = input_stream.getEndColumn(); t = Token.newToken(jjmatchedKind, curTokenImage); t.beginLine = beginLine; t.endLine = endLine; t.beginColumn = beginColumn; t.endColumn = endColumn; return t; } int curLexState = 0; int defaultLexState = 0; int jjnewStateCnt; int jjround; int jjmatchedPos; int jjmatchedKind; /** Get the next Token. */ public Token getNextToken() { Token matchedToken; int curPos = 0; EOFLoop : for (;;) { try { curChar = input_stream.BeginToken(); } catch(Exception e) { jjmatchedKind = 0; jjmatchedPos = -1; matchedToken = jjFillToken(); return matchedToken; } image = jjimage; image.setLength(0); jjimageLen = 0; for (;;) { switch(curLexState) { case 0: try { input_stream.backup(0); while (curChar <= 32 && (0x100003600L & (1L << curChar)) != 0L) curChar = input_stream.BeginToken(); } catch (java.io.IOException e1) { continue EOFLoop; } jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_0(); if (jjmatchedPos == 0 && jjmatchedKind > 54) { jjmatchedKind = 54; } break; case 1: jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_1(); if (jjmatchedPos == 0 && jjmatchedKind > 27) { jjmatchedKind = 27; } break; case 2: jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_2(); if (jjmatchedPos == 0 && jjmatchedKind > 54) { jjmatchedKind = 54; } break; case 3: jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_3(); if (jjmatchedPos == 0 && jjmatchedKind > 54) { jjmatchedKind = 54; } break; case 4: jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_4(); if (jjmatchedPos == 0 && jjmatchedKind > 54) { jjmatchedKind = 54; } break; case 5: jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_5(); if (jjmatchedPos == 0 && jjmatchedKind > 54) { jjmatchedKind = 54; } break; } if (jjmatchedKind != 0x7fffffff) { if (jjmatchedPos + 1 < curPos) input_stream.backup(curPos - jjmatchedPos - 1); if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) { matchedToken = jjFillToken(); TokenLexicalActions(matchedToken); if (jjnewLexState[jjmatchedKind] != -1) curLexState = jjnewLexState[jjmatchedKind]; return matchedToken; } else if ((jjtoSkip[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) { if (jjnewLexState[jjmatchedKind] != -1) curLexState = jjnewLexState[jjmatchedKind]; continue EOFLoop; } MoreLexicalActions(); if (jjnewLexState[jjmatchedKind] != -1) curLexState = jjnewLexState[jjmatchedKind]; curPos = 0; jjmatchedKind = 0x7fffffff; try { curChar = input_stream.readChar(); continue; } catch (java.io.IOException e1) { } } int error_line = input_stream.getEndLine(); int error_column = input_stream.getEndColumn(); String error_after = null; boolean EOFSeen = false; try { input_stream.readChar(); input_stream.backup(1); } catch (java.io.IOException e1) { EOFSeen = true; error_after = curPos <= 1 ? "" : input_stream.GetImage(); if (curChar == '\n' || curChar == '\r') { error_line++; error_column = 0; } else error_column++; } if (!EOFSeen) { input_stream.backup(1); error_after = curPos <= 1 ? "" : input_stream.GetImage(); } throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); } } } void MoreLexicalActions() { jjimageLen += (lengthOfMatch = jjmatchedPos + 1); switch(jjmatchedKind) { case 32 : image.append(input_stream.GetSuffix(jjimageLen)); jjimageLen = 0; stringBuffer = new StringBuffer(); break; case 33 : image.append(input_stream.GetSuffix(jjimageLen)); jjimageLen = 0; stringBuffer = new StringBuffer(); break; case 34 : image.append(input_stream.GetSuffix(jjimageLen)); jjimageLen = 0; charValue = escapeChar(); stringBuffer.append(charValue); break; case 35 : image.append(input_stream.GetSuffix(jjimageLen)); jjimageLen = 0; stringBuffer.append( escapeChar() ); break; case 36 : image.append(input_stream.GetSuffix(jjimageLen)); jjimageLen = 0; stringBuffer.append( image.charAt(image.length()-1) ); break; case 38 : image.append(input_stream.GetSuffix(jjimageLen)); jjimageLen = 0; stringBuffer.append( image.charAt(image.length()-1) ); break; case 46 : image.append(input_stream.GetSuffix(jjimageLen)); jjimageLen = 0; isStaticDynamicExpr = false; stringBuffer = new StringBuffer(); break; case 47 : image.append(input_stream.GetSuffix(jjimageLen)); jjimageLen = 0; isStaticDynamicExpr = true; stringBuffer = new StringBuffer(); break; case 48 : image.append(input_stream.GetSuffix(jjimageLen)); jjimageLen = 0; braceNestingDepth++; stringBuffer.append("{"); break; case 49 : image.append(input_stream.GetSuffix(jjimageLen)); jjimageLen = 0; stringBuffer.append( image.charAt(image.length()-1) ); break; case 50 : image.append(input_stream.GetSuffix(jjimageLen)); jjimageLen = 0; braceNestingDepth++; stringBuffer.append("{"); break; case 51 : image.append(input_stream.GetSuffix(jjimageLen)); jjimageLen = 0; stringBuffer.append( image.charAt(image.length()-1) ); break; case 52 : image.append(input_stream.GetSuffix(jjimageLen)); jjimageLen = 0; stringBuffer.append("}"); braceNestingDepth--; SwitchTo( braceNestingDepth==0 ? WithinExprLiteral : WithinExprLiteralNested ); break; default : break; } } void TokenLexicalActions(Token matchedToken) { switch(jjmatchedKind) { case 37 : image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); literalValue = new String( stringBuffer ); break; case 39 : image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); literalValue = new String( stringBuffer ); break; case 40 : image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); literalValue = makeInt(); break; case 41 : image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); literalValue = makeFloat(); break; case 53 : image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); literalValue = new String( stringBuffer ); break; default : break; } } private void jjCheckNAdd(int state) { if (jjrounds[state] != jjround) { jjstateSet[jjnewStateCnt++] = state; jjrounds[state] = jjround; } } private void jjAddStates(int start, int end) { do { jjstateSet[jjnewStateCnt++] = jjnextStates[start]; } while (start++ != end); } private void jjCheckNAddTwoStates(int state1, int state2) { jjCheckNAdd(state1); jjCheckNAdd(state2); } private void jjCheckNAddStates(int start, int end) { do { jjCheckNAdd(jjnextStates[start]); } while (start++ != end); } /** Constructor. */ public ParserTokenManager(JavaCharStream stream){ if (JavaCharStream.staticFlag) throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer."); input_stream = stream; } /** Constructor. */ public ParserTokenManager (JavaCharStream stream, int lexState){ ReInit(stream); SwitchTo(lexState); } /** Reinitialise parser. */ public void ReInit(JavaCharStream stream) { jjmatchedPos = jjnewStateCnt = 0; curLexState = defaultLexState; input_stream = stream; ReInitRounds(); } private void ReInitRounds() { int i; jjround = 0x80000001; for (i = 31; i-- > 0;) jjrounds[i] = 0x80000000; } /** Reinitialise parser. */ public void ReInit( JavaCharStream stream, int lexState) { ReInit( stream); SwitchTo(lexState); } /** Switch to specified lex state. */ public void SwitchTo(int lexState) { if (lexState >= 6 || lexState < 0) throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); else curLexState = lexState; } /** Lexer state names. */ public static final String[] lexStateNames = { "DEFAULT", "IN_COMMENT", "WithinStringLiteral", "WithinSQStringLiteral", "WithinExprLiteral", "WithinExprLiteralNested", }; /** Lex State array. */ public static final int[] jjnewLexState = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, 2, 3, -1, -1, -1, 0, -1, 0, -1, -1, -1, -1, -1, -1, 4, 4, 5, -1, -1, -1, -1, 0, -1, }; static final long[] jjtoToken = { 0x6003a0f00fffffL, }; static final long[] jjtoSkip = { 0x5f00000L, }; static final long[] jjtoMore = { 0x1fc05f0a000000L, }; protected JavaCharStream input_stream; private final int[] jjrounds = new int[31]; private final int[] jjstateSet = new int[2 * 31]; private final StringBuilder jjimage = new StringBuilder(); private StringBuilder image = jjimage; private int jjimageLen; private int lengthOfMatch; protected int curChar; }
apache-2.0
abcrenjunlin/coolweather
src/com/coolweather/app/activity/WeatherActivity.java
5235
package com.coolweather.app.activity; import com.coolweather.app.R; import com.coolweather.app.service.AutoUpdateService; import com.coolweather.app.util.HttpCallbackListener; import com.coolweather.app.util.HttpUtil; import com.coolweather.app.util.Utility; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class WeatherActivity extends Activity implements OnClickListener{ private LinearLayout weatherInfoLayout; /** * ÓÃÓÚÏÔʾ³ÇÊÐÃû */ private TextView cityNameText; /** * ÓÃÓÚÏÔʾ·¢²¼Ê±¼ä */ private TextView publishText; /** * ÓÃÓÚÏÔʾÌìÆøÃèÊöÐÅÏ¢ */ private TextView weatherDespText; /** * ÓÃÓÚÏÔÊ¾ÆøÎÂ1 */ private TextView temp1Text; /** * ÓÃÓÚÏÔÊ¾ÆøÎÂ2 */ private TextView temp2Text; /** * ÓÃÓÚÏÔʾµ±Ç°ÈÕÆÚ */ private TextView currentDateText; /** * Çл»³ÇÊа´Å¥ */ private Button switchCity; /** * ¸üÐÂÌìÆø°´Å¥ */ private Button refreshWeather; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.weather_layout); //³õʼ»¯¸÷¿Ø¼þ weatherInfoLayout=(LinearLayout)findViewById(R.id.weather_info_layout); cityNameText=(TextView)findViewById(R.id.city_name); publishText=(TextView)findViewById(R.id.publish_text); weatherDespText=(TextView)findViewById(R.id.weather_desp); temp1Text=(TextView)findViewById(R.id.temp1); temp2Text=(TextView)findViewById(R.id.temp2); currentDateText=(TextView)findViewById(R.id.current_date); String countyCode=getIntent().getStringExtra("county_code"); if(!TextUtils.isEmpty(countyCode)){ //ÓÐÏØ¼¶´úºÅÊǾÍÈ¥²éѯÌìÆø publishText.setText("ͬ²½ÖС£¡£¡£"); weatherInfoLayout.setVisibility(View.INVISIBLE); cityNameText.setVisibility(View.INVISIBLE); queryWeatherCode(countyCode); }else{ //ûÓоÍÖ±½ÓÏÔʾ±¾µØÌìÆøÐÅÏ¢ showWeather(); } switchCity=(Button)findViewById(R.id.refresh_weather); refreshWeather=(Button)findViewById(R.id.refresh_weather); switchCity.setOnClickListener(this); refreshWeather.setOnClickListener(this); } @Override public void onClick(View v){ switch (v.getId()) { case R.id.switch_city: Intent intent =new Intent(this,ChooseAreaActivity.class); intent.putExtra("from_weather_activity", true); startActivity(intent); finish(); break; case R.id.refresh_weather: publishText.setText("ͬ²½ÖÐ..."); SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this); String weatherCode=prefs.getString("weather_code", ""); if(!TextUtils.isEmpty(weatherCode)){ queryWeatherInfo(weatherCode); } break; default: break; } } /** * ²éÑ¯ÏØ¼¶´úºÅËù¶ÔÓ¦µÄÌìÆø´úºÅ¡£ */ private void queryWeatherCode(String countyCode){ String address ="http://www.weather.com.cn/data/list3/city"+countyCode+".xml"; queryFromServer(address,"countyCode"); } /** * ²éѯÌìÆø´úºÅËù¶ÔÓ¦µÄÌìÆø¡£ */ private void queryWeatherInfo(String weatherCode){ String address="http://www.weather.com.cn/data/cityinfo/"+weatherCode+".html"; queryFromServer(address,"weatherCode"); } /** *¸ù¾Ý´«ÈëµÄµØÖ·ºÍÀàÐÍÈ¥Ïò·þÎñÆ÷²éѯÌìÆø´úºÅ»òÕßÌìÆøÐÅÏ¢ */ private void queryFromServer(final String address,final String type){ HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinish(final String response) { if("countyCode".equals(type)){ if(!TextUtils.isEmpty(response)){ //´Ó·þÎñÆ÷·µ»ØµÄÊý¾ÝÖнâÎö³öÌìÆø´úºÅ String[] array =response.split("\\|"); if(array!=null&&array.length==2){ String weatherCode=array[1]; queryWeatherInfo(weatherCode); } } }else if ("weatherCode".equals(type)){ //´¦Àí·þÎñÆ÷·µ»ØµÄÌìÆøÐÅÏ¢ Utility.handleWeatherResponse(WeatherActivity.this, response); runOnUiThread(new Runnable() { @Override public void run() { showWeather(); } }); } } @Override public void onError(Exception e) { runOnUiThread(new Runnable() { @Override public void run() { publishText.setText("ͬ²½Ê§°Ü"); } }); } }); } /** * ´ÓSharedPreferencesÎļþÖж¼È¥´æ´¢µÄÌìÆøÐÅÏ¢£¬²¢ÏÔʾµ½½çÃæÉÏ¡£ */ private void showWeather() { SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this); cityNameText.setText(prefs.getString("city_name", "")); temp1Text.setText(prefs.getString("temp1", "")); temp2Text.setText(prefs.getString("temp2", "")); weatherDespText.setText(prefs.getString("weather_desp", "")); publishText.setText("½ñÌì"+prefs.getString("publish_time", "")+"·¢²¼"); currentDateText.setText(prefs.getString("current_date", "")); weatherInfoLayout.setVisibility(View.VISIBLE); cityNameText.setVisibility(View.VISIBLE); Intent intent =new Intent(this,AutoUpdateService.class); startActivity(intent); } }
apache-2.0
Yorxxx/playednext
app/src/main/java/com/piticlistudio/playednext/di/component/AppComponent.java
1625
package com.piticlistudio.playednext.di.component; import android.content.Context; import com.piticlistudio.playednext.collection.CollectionModule; import com.piticlistudio.playednext.company.model.CompanyModule; import com.piticlistudio.playednext.di.module.AppModule; import com.piticlistudio.playednext.di.module.IGDBModule; import com.piticlistudio.playednext.game.GameComponent; import com.piticlistudio.playednext.game.GameModule; import com.piticlistudio.playednext.game.model.repository.IGameRepository; import com.piticlistudio.playednext.gamerelation.GameRelationModule; import com.piticlistudio.playednext.gamerelation.model.repository.IGameRelationRepository; import com.piticlistudio.playednext.genre.GenreModule; import com.piticlistudio.playednext.platform.PlatformModule; import com.piticlistudio.playednext.platform.ui.PlatformUIUtils; import com.piticlistudio.playednext.relationinterval.RelationIntervalModule; import com.piticlistudio.playednext.relationinterval.model.repository.RelationIntervalRepository; import com.squareup.picasso.Picasso; import javax.inject.Singleton; import dagger.Component; @Singleton @Component(modules = {AppModule.class, GameRelationModule.class, RelationIntervalModule.class, IGDBModule.class, GameModule.class, CollectionModule.class, CompanyModule.class, GenreModule.class, PlatformModule.class}) public interface AppComponent { Context context(); Picasso picasso(); PlatformUIUtils platformUtils(); IGameRelationRepository repository(); IGameRepository gameRepository(); RelationIntervalRepository intervalRepository(); }
apache-2.0
duck1123/java-xmltooling
src/main/java/org/opensaml/xml/schema/impl/XSStringUnmarshaller.java
2441
/* * Copyright [2006] [University Corporation for Advanced Internet Development, 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.opensaml.xml.schema.impl; import org.opensaml.xml.XMLObject; import org.opensaml.xml.io.AbstractXMLObjectUnmarshaller; import org.opensaml.xml.io.UnmarshallingException; import org.opensaml.xml.schema.XSString; import org.w3c.dom.Attr; /** * Thread-safe unmarshaller for {@link org.opensaml.xml.schema.XSString} objects. */ public class XSStringUnmarshaller extends AbstractXMLObjectUnmarshaller { /** Constructor. */ public XSStringUnmarshaller() { super(); } /** * This constructor supports checking an XMLObject to be marshalled, either element name or schema type, against a * given namespace/local name pair. * * @param targetNamespaceURI the namespace URI of either the schema type QName or element QName of the elements this * unmarshaller operates on * @param targetLocalName the local name of either the schema type QName or element QName of the elements this * unmarshaller operates on */ protected XSStringUnmarshaller(String targetNamespaceURI, String targetLocalName) { super(targetNamespaceURI, targetLocalName); } /** {@inheritDoc} */ protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject) throws UnmarshallingException { // no children } /** {@inheritDoc} */ protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException { //no attributes } /** {@inheritDoc} */ protected void processElementContent(XMLObject xmlObject, String elementContent) { XSString xsiString = (XSString) xmlObject; xsiString.setValue(elementContent); } }
apache-2.0
dvdkruk/protolipse
protolipse/src-gen/protolipse/protobuf/NumberLink.java
330
/** */ package protolipse.protobuf; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Number Link</b></em>'. * <!-- end-user-doc --> * * * @see protolipse.protobuf.ProtobufPackage#getNumberLink() * @model * @generated */ public interface NumberLink extends SimpleValueLink { } // NumberLink
apache-2.0
SmartDeveloperHub/sdh-curator-connector
src/test/java/org/smartdeveloperhub/curator/connector/io/EnrichmentResponseMessageParserTest.java
2826
/** * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * This file is part of the Smart Developer Hub Project: * http://www.smartdeveloperhub.org/ * * Center for Open Middleware * http://www.centeropenmiddleware.com/ * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * Copyright (C) 2015-2016 Center for Open Middleware. * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * 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. * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# * Artifact : org.smartdeveloperhub.curator:sdh-curator-connector:0.2.0 * Bundle : sdh-curator-connector-0.2.0.jar * #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# */ package org.smartdeveloperhub.curator.connector.io; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; import org.junit.Test; import org.smartdeveloperhub.curator.protocol.EnrichmentResponseMessage; import org.smartdeveloperhub.curator.protocol.vocabulary.STOA; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Resource; public class EnrichmentResponseMessageParserTest { @Test public void testFromModel$happyPath() { new ParserTester("messages/enrichment_response.ttl",STOA.ENRICHMENT_RESPONSE_TYPE) { @Override protected void exercise(final Model model, final Resource target) { final EnrichmentResponseMessage result=EnrichmentResponseMessageParser.fromModel(model, target); assertThat(result,notNullValue()); System.out.println(result); } }.verify(); } // @Test // public void testFromModel$fail$multiple() { // new ParserTester("data/agent/multiple.ttl",FOAF.AGENT_TYPE) { // @Override // protected void exercise(Model model, Resource target) { // try { // AgentParser.fromModel(model, target); // fail("Should not return an agent when multiple are available"); // } catch (Exception e) { // assertThat(e.getMessage(),equalTo("Too many Agent definitions for resource '"+target+"'")); // assertThat(e.getCause(),nullValue()); // } // } // }.verify(); // } }
apache-2.0
aperepel/netty
src/main/java/org/jboss/netty/channel/ChannelPipeline.java
20467
/* * Copyright 2009 Red Hat, Inc. * * Red Hat 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.jboss.netty.channel; import java.io.InputStream; import java.io.OutputStream; import java.util.Map; import java.util.NoSuchElementException; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.handler.execution.ExecutionHandler; import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; import org.jboss.netty.handler.ssl.SslHandler; /** * A list of {@link ChannelHandler}s which handles or intercepts * {@link ChannelEvent}s of a {@link Channel}. {@link ChannelPipeline} * implements an advanced form of the * <a href="http://java.sun.com/blueprints/corej2eepatterns/Patterns/InterceptingFilter.html">Intercepting * Filter</a> pattern to give a user full control over how an event is handled * and how the {@link ChannelHandler}s in the pipeline interact with each other. * * <h3>Creation of a pipeline</h3> * * For each new channel, a new pipeline must be created and attached to the * channel. Once attached, the coupling between the channel and the pipeline * is permanent; the channel cannot attach another pipeline to it nor detach * the current pipeline from it. * <p> * The recommended way to create a new pipeline is to use the helper methods in * {@link Channels} rather than calling an individual implementation's * constructor: * <pre> * import static org.jboss.netty.channel.{@link Channels}.*; * {@link ChannelPipeline} pipeline = pipeline(); // same with Channels.pipeline() * </pre> * * <h3>How an event flows in a pipeline</h3> * * The following diagram describes how {@link ChannelEvent}s are processed by * {@link ChannelHandler}s in a {@link ChannelPipeline} typically. * A {@link ChannelEvent} can be handled by either a {@link ChannelUpstreamHandler} * or a {@link ChannelDownstreamHandler} and be forwarded to the closest * handler by calling {@link ChannelHandlerContext#sendUpstream(ChannelEvent)} * or {@link ChannelHandlerContext#sendDownstream(ChannelEvent)}. The meaning * of the event is interpreted somewhat differently depending on whether it is * going upstream or going downstream. Please refer to {@link ChannelEvent} for * more information. * <pre> * I/O Request * via {@link Channel} or * {@link ChannelHandlerContext} * | * +----------------------------------------+---------------+ * | ChannelPipeline | | * | \|/ | * | +----------------------+ +-----------+------------+ | * | | Upstream Handler N | | Downstream Handler 1 | | * | +----------+-----------+ +-----------+------------+ | * | /|\ | | * | | \|/ | * | +----------+-----------+ +-----------+------------+ | * | | Upstream Handler N-1 | | Downstream Handler 2 | | * | +----------+-----------+ +-----------+------------+ | * | /|\ . | * | . . | * | [ sendUpstream() ] [ sendDownstream() ] | * | [ + INBOUND data ] [ + OUTBOUND data ] | * | . . | * | . \|/ | * | +----------+-----------+ +-----------+------------+ | * | | Upstream Handler 2 | | Downstream Handler M-1 | | * | +----------+-----------+ +-----------+------------+ | * | /|\ | | * | | \|/ | * | +----------+-----------+ +-----------+------------+ | * | | Upstream Handler 1 | | Downstream Handler M | | * | +----------+-----------+ +-----------+------------+ | * | /|\ | | * +-------------+--------------------------+---------------+ * | \|/ * +-------------+--------------------------+---------------+ * | | | | * | [ Socket.read() ] [ Socket.write() ] | * | | * | Netty Internal I/O Threads (Transport Implementation) | * +--------------------------------------------------------+ * </pre> * An upstream event is handled by the upstream handlers in the bottom-up * direction as shown on the left side of the diagram. An upstream handler * usually handles the inbound data generated by the I/O thread on the bottom * of the diagram. The inbound data is often read from a remote peer via the * actual input operation such as {@link InputStream#read(byte[])}. * If an upstream event goes beyond the top upstream handler, it is discarded * silently. * <p> * A downstream event is handled by the downstream handler in the top-down * direction as shown on the right side of the diagram. A downstream handler * usually generates or transforms the outbound traffic such as write requests. * If a downstream event goes beyond the bottom downstream handler, it is * handled by an I/O thread associated with the {@link Channel}. The I/O thread * often performs the actual output operation such as {@link OutputStream#write(byte[])}. * <p> * For example, let us assume that we created the following pipeline: * <pre> * {@link ChannelPipeline} p = {@link Channels}.pipeline(); * p.addLast("1", new UpstreamHandlerA()); * p.addLast("2", new UpstreamHandlerB()); * p.addLast("3", new DownstreamHandlerA()); * p.addLast("4", new DownstreamHandlerB()); * p.addLast("5", new UpstreamHandlerX()); * </pre> * In the example above, the class whose name starts with {@code Upstream} means * it is an upstream handler. The class whose name starts with * {@code Downstream} means it is a downstream handler. * <p> * In the given example configuration, the handler evaluation order is 1, 2, 3, * 4, 5 when an event goes upstream. When an event goes downstream, the order * is 5, 4, 3, 2, 1. On top of this principle, {@link ChannelPipeline} skips * the evaluation of certain handlers to shorten the stack depth: * <ul> * <li>3 and 4 don't implement {@link ChannelUpstreamHandler}, and therefore the * actual evaluation order of an upstream event will be: 1, 2, and 5.</li> * <li>1, 2, and 5 don't implement {@link ChannelDownstreamHandler}, and * therefore the actual evaluation order of a downstream event will be: * 4 and 3.</li> * <li>If 5 extended {@link SimpleChannelHandler} which implements both * {@link ChannelUpstreamHandler} and {@link ChannelDownstreamHandler}, the * evaluation order of an upstream and a downstream event could be 125 and * 543 respectively.</li> * </ul> * * <h3>Building a pipeline</h3> * <p> * A user is supposed to have one or more {@link ChannelHandler}s in a * pipeline to receive I/O events (e.g. read) and to request I/O operations * (e.g. write and close). For example, a typical server will have the following * handlers in each channel's pipeline, but your mileage may vary depending on * the complexity and characteristics of the protocol and business logic: * * <ol> * <li>Protocol Decoder - translates binary data (e.g. {@link ChannelBuffer}) * into a Java object.</li> * <li>Protocol Encoder - translates a Java object into binary data.</li> * <li>{@link ExecutionHandler} - applies a thread model.</li> * <li>Business Logic Handler - performs the actual business logic * (e.g. database access).</li> * </ol> * * and it could be represented as shown in the following example: * * <pre> * {@link ChannelPipeline} pipeline = {@link Channels#pipeline() Channels.pipeline()}; * pipeline.addLast("decoder", new MyProtocolDecoder()); * pipeline.addLast("encoder", new MyProtocolEncoder()); * pipeline.addLast("executor", new {@link ExecutionHandler}(new {@link OrderedMemoryAwareThreadPoolExecutor}(16, 1048576, 1048576))); * pipeline.addLast("handler", new MyBusinessLogicHandler()); * </pre> * * <h3>Thread safety</h3> * <p> * A {@link ChannelHandler} can be added or removed at any time because a * {@link ChannelPipeline} is thread safe. For example, you can insert a * {@link SslHandler} when sensitive information is about to be exchanged, * and remove it after the exchange. * * <h3>Pitfall</h3> * <p> * Due to the internal implementation detail of the current default * {@link ChannelPipeline}, the following code does not work as expected if * <tt>FirstHandler</tt> is the last handler in the pipeline: * <pre> * public class FirstHandler extends {@link SimpleChannelUpstreamHandler} { * * {@code @Override} * public void messageReceived({@link ChannelHandlerContext} ctx, {@link MessageEvent} e) { * // Remove this handler from the pipeline, * ctx.getPipeline().remove(this); * // And let SecondHandler handle the current event. * ctx.getPipeline().addLast("2nd", new SecondHandler()); * ctx.sendUpstream(e); * } * } * </pre> * To implement the expected behavior, you have to add <tt>SecondHandler</tt> * before the removal or make sure there is at least one more handler between * <tt>FirstHandler</tt> and <tt>SecondHandler</tt>. * * @author <a href="http://www.jboss.org/netty/">The Netty Project</a> * @author <a href="http://gleamynode.net/">Trustin Lee</a> * * @version $Rev$, $Date$ * * @apiviz.landmark * @apiviz.composedOf org.jboss.netty.channel.ChannelHandlerContext * @apiviz.owns org.jboss.netty.channel.ChannelHandler * @apiviz.uses org.jboss.netty.channel.ChannelSink - - sends events downstream */ public interface ChannelPipeline { /** * Inserts a {@link ChannelHandler} at the first position of this pipeline. * * @param name the name of the handler to insert first * @param handler the handler to insert first * * @throws IllegalArgumentException * if there's an entry with the same name already in the pipeline * @throws NullPointerException * if the specified name or handler is {@code null} */ void addFirst (String name, ChannelHandler handler); /** * Appends a {@link ChannelHandler} at the last position of this pipeline. * * @param name the name of the handler to append * @param handler the handler to append * * @throws IllegalArgumentException * if there's an entry with the same name already in the pipeline * @throws NullPointerException * if the specified name or handler is {@code null} */ void addLast (String name, ChannelHandler handler); /** * Inserts a {@link ChannelHandler} before an existing handler of this * pipeline. * * @param baseName the name of the existing handler * @param name the name of the handler to insert before * @param handler the handler to insert before * * @throws NoSuchElementException * if there's no such entry with the specified {@code baseName} * @throws IllegalArgumentException * if there's an entry with the same name already in the pipeline * @throws NullPointerException * if the specified baseName, name, or handler is {@code null} */ void addBefore(String baseName, String name, ChannelHandler handler); /** * Inserts a {@link ChannelHandler} after an existing handler of this * pipeline. * * @param baseName the name of the existing handler * @param name the name of the handler to insert after * @param handler the handler to insert after * * @throws NoSuchElementException * if there's no such entry with the specified {@code baseName} * @throws IllegalArgumentException * if there's an entry with the same name already in the pipeline * @throws NullPointerException * if the specified baseName, name, or handler is {@code null} */ void addAfter (String baseName, String name, ChannelHandler handler); /** * Removes the specified {@link ChannelHandler} from this pipeline. * * @throws NoSuchElementException * if there's no such handler in this pipeline * @throws NullPointerException * if the specified handler is {@code null} */ void remove(ChannelHandler handler); /** * Removes the {@link ChannelHandler} with the specified name from this * pipeline. * * @return the removed handler * * @throws NoSuchElementException * if there's no such handler with the specified name in this pipeline * @throws NullPointerException * if the specified name is {@code null} */ ChannelHandler remove(String name); /** * Removes the {@link ChannelHandler} of the specified type from this * pipeline * * @param <T> the type of the handler * @param handlerType the type of the handler * * @return the removed handler * * @throws NoSuchElementException * if there's no such handler of the specified type in this pipeline * @throws NullPointerException * if the specified handler type is {@code null} */ <T extends ChannelHandler> T remove(Class<T> handlerType); /** * Removes the first {@link ChannelHandler} in this pipeline. * * @return the removed handler * * @throws NoSuchElementException * if this pipeline is empty */ ChannelHandler removeFirst(); /** * Removes the last {@link ChannelHandler} in this pipeline. * * @return the removed handler * * @throws NoSuchElementException * if this pipeline is empty */ ChannelHandler removeLast(); /** * Replaces the specified {@link ChannelHandler} with a new handler in * this pipeline. * * @throws NoSuchElementException * if the specified old handler does not exist in this pipeline * @throws IllegalArgumentException * if a handler with the specified new name already exists in this * pipeline, except for the handler to be replaced * @throws NullPointerException * if the specified old handler, new name, or new handler is * {@code null} */ void replace(ChannelHandler oldHandler, String newName, ChannelHandler newHandler); /** * Replaces the {@link ChannelHandler} of the specified name with a new * handler in this pipeline. * * @return the removed handler * * @throws NoSuchElementException * if the handler with the specified old name does not exist in this pipeline * @throws IllegalArgumentException * if a handler with the specified new name already exists in this * pipeline, except for the handler to be replaced * @throws NullPointerException * if the specified old handler, new name, or new handler is * {@code null} */ ChannelHandler replace(String oldName, String newName, ChannelHandler newHandler); /** * Replaces the {@link ChannelHandler} of the specified type with a new * handler in this pipeline. * * @return the removed handler * * @throws NoSuchElementException * if the handler of the specified old handler type does not exist * in this pipeline * @throws IllegalArgumentException * if a handler with the specified new name already exists in this * pipeline, except for the handler to be replaced * @throws NullPointerException * if the specified old handler, new name, or new handler is * {@code null} */ <T extends ChannelHandler> T replace(Class<T> oldHandlerType, String newName, ChannelHandler newHandler); /** * Returns the first {@link ChannelHandler} in this pipeline. * * @return the first handler. {@code null} if this pipeline is empty. */ ChannelHandler getFirst(); /** * Returns the last {@link ChannelHandler} in this pipeline. * * @return the last handler. {@code null} if this pipeline is empty. */ ChannelHandler getLast(); /** * Returns the {@link ChannelHandler} with the specified name in this * pipeline. * * @return the handler with the specified name. * {@code null} if there's no such handler in this pipeline. */ ChannelHandler get(String name); /** * Returns the {@link ChannelHandler} of the specified type in this * pipeline. * * @return the handler of the specified handler type. * {@code null} if there's no such handler in this pipeline. */ <T extends ChannelHandler> T get(Class<T> handlerType); /** * Returns the context object of the specified {@link ChannelHandler} in * this pipeline. * * @return the context object of the specified handler. * {@code null} if there's no such handler in this pipeline. */ ChannelHandlerContext getContext(ChannelHandler handler); /** * Returns the context object of the {@link ChannelHandler} with the * specified name in this pipeline. * * @return the context object of the handler with the specified name. * {@code null} if there's no such handler in this pipeline. */ ChannelHandlerContext getContext(String name); /** * Returns the context object of the {@link ChannelHandler} of the * specified type in this pipeline. * * @return the context object of the handler of the specified type. * {@code null} if there's no such handler in this pipeline. */ ChannelHandlerContext getContext(Class<? extends ChannelHandler> handlerType); /** * Sends the specified {@link ChannelEvent} to the first * {@link ChannelUpstreamHandler} in this pipeline. * * @throws NullPointerException * if the specified event is {@code null} */ void sendUpstream(ChannelEvent e); /** * Sends the specified {@link ChannelEvent} to the last * {@link ChannelDownstreamHandler} in this pipeline. * * @throws NullPointerException * if the specified event is {@code null} */ void sendDownstream(ChannelEvent e); /** * Returns the {@link Channel} that this pipeline is attached to. * * @return the channel. {@code null} if this pipeline is not attached yet. */ Channel getChannel(); /** * Returns the {@link ChannelSink} that this pipeline is attached to. * * @return the sink. {@code null} if this pipeline is not attached yet. */ ChannelSink getSink(); /** * Attaches this pipeline to the specified {@link Channel} and * {@link ChannelSink}. Once a pipeline is attached, it can't be detached * nor attached again. * * @throws IllegalStateException if this pipeline is attached already */ void attach(Channel channel, ChannelSink sink); /** * Returns {@code true} if and only if this pipeline is attached to * a {@link Channel}. */ boolean isAttached(); /** * Converts this pipeline into an ordered {@link Map} whose keys are * handler names and whose values are handlers. */ Map<String, ChannelHandler> toMap(); }
apache-2.0
OpenHFT/Chronicle-Bytes
src/main/java/net/openhft/chronicle/bytes/internal/ByteStringReader.java
2146
/* * Copyright 2016-2020 chronicle.software * * https://chronicle.software * * 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.openhft.chronicle.bytes.internal; import net.openhft.chronicle.bytes.ByteStringParser; import java.io.IOException; import java.io.Reader; import java.nio.BufferUnderflowException; import static net.openhft.chronicle.bytes.internal.ReferenceCountedUtil.throwExceptionIfReleased; /** * A Reader wrapper for Bytes. This Reader moves the readPosition() of the underlying Bytes up to the readLimit() */ @SuppressWarnings("rawtypes") public class ByteStringReader extends Reader { private final ByteStringParser in; public ByteStringReader(ByteStringParser in) { throwExceptionIfReleased(in); this.in = in; } @Override public int read() { try { return in.readRemaining() > 0 ? in.readUnsignedByte() : -1; } catch (IllegalStateException e) { return -1; } } @Override public long skip(long n) throws IOException { long len = Math.min(in.readRemaining(), n); try { in.readSkip(len); } catch (BufferUnderflowException | IllegalStateException e) { throw new IOException(e); } return len; } @Override public int read(char[] cbuf, int off, int len) throws IOException { try { return in.read(cbuf, off, len); } catch (IllegalStateException e) { throw new IOException(e); } } @Override public void close() { // Do nothing } }
apache-2.0
FAU-Inf2/AuDoscore
tests/thread/junit/UnitTest.java
580
import static org.junit.Assert.assertEquals; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import tester.annotations.Ex; import tester.annotations.Exercises; import tester.annotations.Points; @Exercises({ @Ex(exID = "Threads", points = 2.0) }) public class UnitTest { @Rule public final PointsLogger pointsLogger = new PointsLogger(); @ClassRule public static final PointsSummary pointsSummary = new PointsSummary(); @Test(timeout=100) @Points(exID = "Threads", bonus = 0.00001) public void test() { assertEquals(42, ToTest.test()); } }
apache-2.0
Gugli/Openfire
src/plugins/gojara/src/java/org/jivesoftware/openfire/plugin/gojara/sessions/TransportSessionManager.java
8506
package org.jivesoftware.openfire.plugin.gojara.sessions; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.jivesoftware.openfire.plugin.gojara.database.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This is the central point for doing anything Gojara GatewaySession related. We keep track of Users connected to * Transports, stats about these and provide some methods for Presentation in JSP Pages. * * @author axel.frederik.brand */ public class TransportSessionManager { private static TransportSessionManager myself; private DatabaseManager db; private GojaraAdminManager adminManager; private Map<String, Map<String, Long>> transportSessions = new ConcurrentHashMap<String, Map<String, Long>>(16, 0.75f, 1); private static final Logger Log = LoggerFactory.getLogger(TransportSessionManager.class); private TransportSessionManager() { db = DatabaseManager.getInstance(); adminManager = GojaraAdminManager.getInstance(); Log.info(" Created TransportSessionManager"); } public static synchronized TransportSessionManager getInstance() { if (myself == null) { myself = new TransportSessionManager(); } return myself; } /** * adds a subdomain to watched transports * * @param subdomain */ public void addTransport(String subdomain) { transportSessions.put(subdomain, new ConcurrentHashMap<String, Long>(64, 0.75f, 1)); Log.debug("Added key to transportSessionMap: " + subdomain); } /** * removes subdomain from watched transports * * @param subdomain */ public void removeTransport(String subdomain) { transportSessions.remove(subdomain); Log.debug("Removed " + subdomain + "from TransportSessionMap "); } public boolean isTransportActive(String subdomain) { return transportSessions.containsKey(subdomain) ? true : false; } /** * register is seperate to connect because a user may register to transport but not connect to it, e.g. with wrong credentials. * we still want to keep track of those registrations so we know they happened and we can reset them * * @param transport * @param user */ public void registerUserTo(String transport, String user) { db.insertOrUpdateSession(transport, user, 0); } /** * Add the session of user that connected to gateway and update or create timestamp for session * * @param transport * @param user * @return */ public boolean connectUserTo(String transport, String user) { //dont update if user is already present, else lots of away to online changes might be spammed if (transportSessions.get(transport) != null && transportSessions.get(transport).get(user) == null) { long millis = System.currentTimeMillis(); transportSessions.get(transport).put(user, millis); db.insertOrUpdateSession(transport, user, millis); return true; } return false; } public boolean disconnectUserFrom(String transport, String user) { // Log.debug("Trying to remove User " + JID.nodeprep(user) + " from Session for Transport " + transport); if (isUserConnectedTo(transport, user)) { transportSessions.get(transport).remove(user); return true; } return false; } public boolean isUserConnectedTo(String transport, String user) { return transportSessions.get(transport).containsKey(user); } /** * Removes registration from our database. * * @param transport * @param user * @return String that describes what happened. */ public void removeRegistrationOfUserFromDB(String transport, String user) { db.removeSessionEntry(transport, user); } /** * Initializes Sessions through adminmanager, ofc needs to be called at a point where there are Transports registered in * transportSessions */ public void initializeSessions() { Log.info("Initializing Sessions."); for (String transport : transportSessions.keySet()) { adminManager.getOnlineUsersOf(transport); } } /** * @return Set of currently active Gateways */ public final Set<String>getActiveGateways() { return transportSessions.keySet(); } public final Map<String, Map<String, Long>> getSessions() { return transportSessions; } /** * Puts all Sessions into an ArrayList of GatewaySession Objects, and sorts it according to specified sorting * attributes. * * @param sortby * username, transport or LoginTime * @param sortorder * ASC or DESC * @return Sorted/Unsorted ArrayList of GatewaySession Objects */ public ArrayList<GatewaySession> getSessionsSorted(String sortby, String sortorder) { ArrayList<GatewaySession> result = new ArrayList<GatewaySession>(getNumberOfActiveSessions()); for (Map.Entry<String, Map<String,Long>> gateway : transportSessions.entrySet()) { for (Map.Entry<String, Long> entry : gateway.getValue().entrySet()) { Timestamp stamp = new Timestamp(entry.getValue()); Date date = new Date(stamp.getTime()); result.add(new GatewaySession(entry.getKey(), gateway.getKey(), date)); } } if (sortby.equals("username")) { Collections.sort(result, new SortUserName()); } else if (sortby.equals("transport")) { Collections.sort(result, new SortTransport()); } else if (sortby.equals("loginTime")) { Collections.sort(result, new SortLastActivity()); } if (sortorder.equals("DESC")) { Collections.reverse(result); } return result; } /** * @return count of recognized active Sessions */ public int getNumberOfActiveSessions() { int result = 0; for (Map.Entry<String, Map<String,Long>> gateway : transportSessions.entrySet()) { result += gateway.getValue().size(); } return result; } /** * Returns number of active Sessions for specified transport or 0 if not valid transport. * @param transport * @return */ public int getNumberOfActiveSessionsFor(String transport) { if (transportSessions.containsKey(transport)) return transportSessions.get(transport).size(); return 0; } /** * Searches for Sessions with given Username and returns them as ArrList * * @param username * @return */ public ArrayList<GatewaySession> getConnectionsFor(String username) { ArrayList<GatewaySession> userconnections = new ArrayList<GatewaySession>(); for (Map.Entry<String, Map<String, Long>> transport : transportSessions.entrySet()) { if (transport.getValue().containsKey(username)) { Timestamp stamp = new Timestamp(transport.getValue().get(username)); Date date = new Date(stamp.getTime()); userconnections.add(new GatewaySession(username, transport.getKey(), date)); } } return userconnections; } /** * Returns Registrations associated with Username * * @param username * @return ArrayList of SessionEntries */ public ArrayList<SessionEntry> getRegistrationsFor(String username) { return db.getSessionEntriesFor(username); } /** * Get all registrations sorted by attribute and order. Validation for correctness of attributes is done in DB * Manager, returns default sorting: username ASC when not valid */ public ArrayList<SessionEntry> getAllRegistrations(String orderAttr, String order) { return db.getAllSessionEntries(orderAttr, order); } public int getNumberOfRegistrations() { return db.getNumberOfRegistrations(); } public int getNumberOfRegistrationsForTransport(String transport) { if (transportSessions.containsKey(transport)) { return db.getNumberOfRegistrationsForTransport(transport); } return 0; } }
apache-2.0
taktik/Ektorp
org.ektorp/src/main/java/org/ektorp/impl/jackson/EktorpAnnotationIntrospector.java
2814
package org.ektorp.impl.jackson; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.ektorp.docref.DocumentReferences; import org.ektorp.impl.NameConventions; import org.ektorp.util.Predicate; import org.ektorp.util.ReflectionUtils; import com.fasterxml.jackson.databind.introspect.Annotated; import com.fasterxml.jackson.databind.introspect.AnnotatedClass; import com.fasterxml.jackson.databind.introspect.AnnotatedField; import com.fasterxml.jackson.databind.introspect.AnnotatedMember; import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; import com.fasterxml.jackson.databind.introspect.NopAnnotationIntrospector; public class EktorpAnnotationIntrospector extends NopAnnotationIntrospector { private final Map<Class<?>, Set<String>> ignorableMethods = new HashMap<Class<?>, Set<String>>(); private final Set<Class<?>> annotatedClasses = new HashSet<Class<?>>(); @Override public boolean isHandled(Annotation ann) { return DocumentReferences.class == ann.annotationType(); } @Override public boolean hasIgnoreMarker(AnnotatedMember member) { return super.hasIgnoreMarker(member); } public boolean isIgnorableField(AnnotatedField f) { return f.hasAnnotation(DocumentReferences.class); } public boolean isIgnorableMethod(AnnotatedMethod m) { Set<String> names = ignorableMethods.get(m.getDeclaringClass()); if (names == null) { initIgnorableMethods(m.getDeclaringClass()); names = ignorableMethods.get(m.getDeclaringClass()); } return names.contains(m.getName()); } @Override public String[] findPropertiesToIgnore(Annotated ac) { if(ac instanceof AnnotatedClass){ return findPropertiesToIgnore((AnnotatedClass) ac); } return super.findPropertiesToIgnore(ac); } public String[] findPropertiesToIgnore(AnnotatedClass ac) { List<String> ignoreFields = null; for (AnnotatedField f : ac.fields()) { if (isIgnorableField(f)) { if (ignoreFields == null) { ignoreFields = new ArrayList<String>(); } ignoreFields.add(f.getName()); } } return ignoreFields != null ? ignoreFields.toArray(new String[ignoreFields.size()]) : null; } private void initIgnorableMethods(final Class<?> clazz) { final Set<String> names = new HashSet<String>(); ReflectionUtils.eachField(clazz, new Predicate<Field>() { @Override public boolean apply(Field input) { if (ReflectionUtils.hasAnnotation(input, DocumentReferences.class)) { annotatedClasses.add(clazz); names.add(NameConventions.getterName(input.getName())); } return false; } }); ignorableMethods.put(clazz, names); } }
apache-2.0
milliondreams/moquette-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/events/InitEvent.java
116
package org.dna.mqtt.moquette.messaging.spi.impl.events; /** */ public class InitEvent extends MessagingEvent { }
apache-2.0
zhuangzhi/simple-actor
src/test/java/simpleactor/MyActor.java
498
package simpleactor; import simpleactor.common.actor.Actor; import simpleactor.common.util.ReceiveBuilder; public class MyActor extends Actor { public MyActor() { receive(ReceiveBuilder. match(String.class, s -> { System.out.println("Received String message: {}"+ s); }). matchAny(o -> System.out.println("received unknown message")).build() ); } }
apache-2.0
KimuraTakaumi/digdag
digdag-core/src/main/java/io/digdag/core/archive/ProjectArchive.java
2130
package io.digdag.core.archive; import java.io.IOException; import java.time.ZoneId; import java.nio.file.Path; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.immutables.value.Value; import io.digdag.client.config.Config; import io.digdag.core.repository.WorkflowDefinitionList; import static java.util.Locale.ENGLISH; public class ProjectArchive { public static final String WORKFLOW_FILE_SUFFIX = ".dig"; public interface PathConsumer { public void accept(String resourceName, Path path) throws IOException; } private final Path projectPath; private final ArchiveMetadata metadata; ProjectArchive(Path projectPath, ArchiveMetadata metadata) { this.projectPath = projectPath; this.metadata = metadata; } public Path getProjectPath() { return projectPath; } public ArchiveMetadata getArchiveMetadata() { return metadata; } public void listFiles(PathConsumer consumer) throws IOException { ProjectArchiveLoader.listFiles(projectPath, consumer); } public String pathToResourceName(Path path) { return realPathToResourceName(projectPath, path.normalize().toAbsolutePath()); } static String realPathToResourceName(Path projectPath, Path realPath) { if (!realPath.startsWith(projectPath)) { throw new IllegalArgumentException(String.format(ENGLISH, "Given path '%s' is outside of project directory '%s'", realPath, projectPath)); } Path relative = projectPath.relativize(realPath); return relative.toString(); // TODO make sure path names are separated by '/' } public static String resourceNameToWorkflowName(String resourceName) { if (resourceName.endsWith(WORKFLOW_FILE_SUFFIX)) { return resourceName.substring(0, resourceName.length() - WORKFLOW_FILE_SUFFIX.length()); } else { return resourceName; } } }
apache-2.0
huijimuhe/common-layout-android
CommonLayout/app/src/main/java/com/huijimuhe/commonlayout/adapter/xcCommentAdapter.java
1422
package com.huijimuhe.commonlayout.adapter; import android.annotation.TargetApi; import android.view.ViewGroup; import com.huijimuhe.commonlayout.adapter.base.AbstractRender; import com.huijimuhe.commonlayout.adapter.base.AbstractRenderAdapter; import com.huijimuhe.commonlayout.adapter.base.AbstractViewHolder; import com.huijimuhe.commonlayout.adapter.render.xcCommentRender; import com.huijimuhe.commonlayout.data.xc.xcComment; import java.util.List; public class xcCommentAdapter extends AbstractRenderAdapter<xcComment> { public xcCommentAdapter(List<xcComment> data) { this.mDataset=data; } @TargetApi(4) public AbstractViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { //header view 的判断 AbstractViewHolder holder = super.onCreateViewHolder(viewGroup, viewType); if (holder != null) { return holder; } xcCommentRender render = new xcCommentRender(viewGroup, this); AbstractViewHolder renderHolder = render.getReusableComponent(); renderHolder.itemView.setTag(android.support.design.R.id.list_item, render); return renderHolder; } @TargetApi(4) public void onBindViewHolder(AbstractViewHolder holder, int position) { AbstractRender render = (AbstractRender) holder.itemView.getTag(android.support.design.R.id.list_item); render.bindData(position); } }
apache-2.0
darlyhellen/oto
shtr/src/main/java/cn/com/service/imp/SerServiceImp.java
1212
/**下午4:13:59 * @author zhangyh2 * SerServiceImp.java * TODO */ package cn.com.service.imp; import java.util.List; import javax.annotation.Resource; import javax.transaction.Transactional; import org.springframework.stereotype.Service; import cn.com.bean.Admin_User; import cn.com.dao.Admin_UserMapper; import cn.com.service.SerService; /** * @author zhangyh2 SerServiceImp 下午4:13:59 TODO */ @Service @Transactional public class SerServiceImp implements SerService { @Resource private Admin_UserMapper map; /* * (non-Javadoc) * * @see cn.com.service.SerService#selectAllUser() */ @Override public List<Admin_User> selectAllUser() { // TODO Auto-generated method stub return map.selectAll(); } /* * (non-Javadoc) * * @see cn.com.service.SerService#registUser(cn.com.bean.Admin_User) */ @Override public int registUser(Admin_User user) { // TODO Auto-generated method stub return map.insert(user); } /* * (non-Javadoc) * * @see cn.com.service.SerService#login(java.lang.String, java.lang.String) */ @Override public Admin_User login(String name, String pass) { // TODO Auto-generated method stub return map.selectByLogin(name, pass); } }
apache-2.0
martenscs/optaplanner-osgi
org.optaplanner.examples.curriculumcourse/src/org/optaplanner/examples/curriculumcourse/persistence/CurriculumCourseDao.java
1035
/* * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.optaplanner.examples.curriculumcourse.persistence; import org.optaplanner.examples.curriculumcourse.Activator; import org.optaplanner.examples.curriculumcourse.domain.CourseSchedule; import org.optaplanner.osgi.common.persistence.XStreamSolutionDao; public class CurriculumCourseDao extends XStreamSolutionDao { public CurriculumCourseDao() { super(Activator.getContext(), "curriculumcourse", CourseSchedule.class); } }
apache-2.0
vichid/Ship-Android-Fast
domain/src/main/java/com/example/domain/executor/PostExecutionThread.java
407
package com.example.domain.executor; import rx.Scheduler; /** * Thread abstraction created to change the execution context from any thread to any other thread. * Useful to encapsulate a UI Thread for example, since some job will be done in background, an * implementation of this interface will change context and update the UI. */ public interface PostExecutionThread { Scheduler getScheduler(); }
apache-2.0
JFL110/app-base-prender
src/main/java/org/jfl110/prender/api/resources/URLResourceSource.java
529
package org.jfl110.prender.api.resources; import java.net.MalformedURLException; import java.net.URL; /** * A ResourceSource that can be resolved from a URL * * @author JFL110 */ public class URLResourceSource implements ResourceSource { private final URL url; URLResourceSource(String path) throws MalformedURLException{ this.url = new URL(path); } URLResourceSource(URL url){ this.url = url; } @Override public String getPath() { return url.getPath(); } public URL getUrl() { return url; } }
apache-2.0
UPB-FILS/MD
2014/Android/MarinIuliana1231E_FirstLabHw/src/com/example/lab3/MainActivity.java
3336
package com.example.lab3; import android.app.Activity; import android.content.Context; import java.io.BufferedReader; //import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; //import android.text.Editable; import android.view.View; //import android.R; import android.os.Bundle; import android.view.Menu; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { EditText tf1, tf2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Button Save=(Button) findViewById(R.id.button1); Button button1 = (Button) findViewById(R.id.button1); Button button2= (Button) findViewById(R.id.button2); tf1 = (EditText) findViewById(R.id.editText1); tf2 = (EditText) findViewById(R.id.editText2); // File f=new File(tf1.getText(),"str"); /*private void writeToFile(String str){ try{ OutputStreamWriter osw = new OutputStreamWriter(openFileOutput("file.txt", Context.MODE_PRIVATE)); } }*/ button1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { writeToFile(tf1.getText().toString()); //tf2.setText("yay"); } private void writeToFile(String str) { // TODO Auto-generated method stub try{ OutputStreamWriter osw = new OutputStreamWriter(openFileOutput("file.txt", Context.MODE_PRIVATE)); osw.write(str); osw.close(); } catch(IOException e){ System.out.println("Failed while writing to file"); e.printStackTrace(); } } }); button2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { tf2.setText(""+readFromFile()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("aah!"); } } private String readFromFile() throws IOException { // TODO Auto-generated method stub String res = ""; try{ InputStream is = openFileInput("file.txt"); if(is != null){ InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String recstr=""; StringBuilder sb = new StringBuilder(); while((recstr = br.readLine()) != null){ sb.append(recstr); } is.close(); res = sb.toString(); } } catch(FileNotFoundException e){ System.out.println("The file has not been found!"); } return res; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
apache-2.0
businesscode/BCD-UI
Server/src/main/java/de/businesscode/bcdui/subjectsettings/SubjectPreferencesRealm.java
6452
/* Copyright 2010-2022 BusinessCode GmbH, Germany Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package de.businesscode.bcdui.subjectsettings; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.session.Session; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.SimplePrincipalCollection; import org.apache.shiro.subject.Subject; import org.apache.shiro.subject.support.DefaultSubjectContext; import de.businesscode.bcdui.subjectsettings.config.SubjectSettingsConfig.UserSettingsDefaults; import de.businesscode.bcdui.subjectsettings.config.SubjectSettingsConfig.UserSettingsDefaults.Default; import de.businesscode.bcdui.web.servlets.SubjectPreferences; /* * This AuthorizingRealm is the counter part to the SubjectPreferences servlet. * It allows * a) setting of subjectSettings UserSettingsDefault values * b) setting of subjectPreferences * * For subjectPreferences, default values for static rights are filled on the * first getPermissionMap call. */ public class SubjectPreferencesRealm extends org.apache.shiro.realm.AuthorizingRealm { public static final String PERMISSION_MAP_TOKEN = "bcdPermissionMapToken"; public static final String PERMISSION_MAP_SESSION_ATTRIBUTE = "bcdPermMap"; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) { SubjectSettings subjectSettings = SubjectSettings.getInstance(); Set<String> permissions = new HashSet<>(); // add all subjectSettings UserSettingsDefaults permissions UserSettingsDefaults userDefaults = subjectSettings.getUserSettingsDefaults(); if (userDefaults != null) { List<Default> defaults = userDefaults.getDefault(); if (defaults != null) { for (Default def : defaults) { String type = def.getType(); String value = def.getValue(); if (type != null && ! type.isBlank()) { permissions.add(type + ":" + value); } } } } // SubjectPreferences permission HashMap<String, ArrayList<String>> permissionMap = new HashMap<>(getPermissionMap()); // add all permissions from map permissionMap.forEach((key, values) -> { for (String value : values) permissions.add(key + ":" + value); }); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); authorizationInfo.setStringPermissions(permissions); return authorizationInfo; } // returns the permission map in any case // if it's not yet created, it is created and the permissions are refreshed as // an initial default-injecting process public Map<String, ArrayList<String>> getPermissionMap() { Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(false); if (session == null) session = subject.getSession(); HashMap<String, ArrayList<String>> permissionMap = null; boolean doRefresh = false; /// map does not exist yet, add an empty one permissionMap = (session.getAttribute(PERMISSION_MAP_SESSION_ATTRIBUTE) == null) ? new HashMap<>() : new HashMap<>((HashMap<String, ArrayList<String>>)session.getAttribute(PERMISSION_MAP_SESSION_ATTRIBUTE)); // check all allowed attributes which are not yet taken over into the perm map // avoid re-entry by using the PERMISSION_MAP_TOKEN since getDefaultValue might trigger doGetAuthorizationInfo via // testValue -> subject.isPermitted if (session.getAttribute(PERMISSION_MAP_TOKEN) == null) { session.setAttribute(PERMISSION_MAP_TOKEN, "true"); for (String rightType : SubjectPreferences.allowedRightTypes) { if (! permissionMap.containsKey(rightType)) { ArrayList<String> defaultRightValues = new ArrayList<>(SubjectPreferences.getDefaultValues(rightType, false)); if (! defaultRightValues.isEmpty()) { permissionMap.put(rightType, defaultRightValues); doRefresh = true; } } } session.removeAttribute(PERMISSION_MAP_TOKEN); } if (doRefresh) { // finally attach new map to session session.setAttribute(PERMISSION_MAP_SESSION_ATTRIBUTE, permissionMap); // and activate it refreshPermissions(session); } return permissionMap; } // sets the provided map as new permission map and refreshes permissions public void setPermissionMap(Map<String, ArrayList<String>> permissionMap) { Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(false); if (session == null) session = subject.getSession(); session.setAttribute(PERMISSION_MAP_SESSION_ATTRIBUTE, permissionMap); refreshPermissions(session); } public void refreshPermissions(Session session) { // in case we're not yet logged in, use a guest principal, otherwise // doGetAuthorizationInfo won't get triggered at all if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) == null) session.setAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY, new SimplePrincipalCollection("bcd-guest", "bcd-guest")); // clear cache and send dummy isPermitted so that doGetAuthorizationInfo is actually called this.clearCache(SecurityUtils.getSubject().getPrincipals()); SecurityUtils.getSubject().isPermitted(PERMISSION_MAP_TOKEN); } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException { // TODO Auto-generated method stub return null; } }
apache-2.0
open-adk/OpenADK-java
adk-library/src/main/java/openadk/library/Provisioner.java
8689
// // Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // package openadk.library; /** * Provisioner is a common interface implemented by the Agent, Zone, and Topic * classes. It provides common APIs for setting Subscribers, Publisher, and QueryResults * handlers * @author Andrew * */ public interface Provisioner { /** * Register a Publisher message handler to process SIF_Request * messages for all object types.<p> * * @param publisher An object that implements the <code>Publisher</code> * interface to respond to SIF_Request queries received by the agent. * This object will be called whenever a SIF_Request is received and * no other object in the message dispatching chain has * processed the message. */ public void setPublisher( Publisher publisher ) throws ADKException; /** * Register a Publisher message handler with this zone to process SIF_Requests * for the specified object type. This method may be called repeatedly for * each SIF Data Object type the agent will publish on this zone.<p> * * @param publisher An object that implements the <code>Publisher</code> * interface to respond to SIF_Request queries received by the agent, * where the SIF object type referenced by the request matches the * specified objectType. This Publisher will be called whenever a * SIF_Request is received on this zone and no other object in the * message dispatching chain has processed the message. * * @param objectType An ElementDef constant from the SIFDTD class that * identifies a SIF Data Object type. E.g. SIFDTD.STUDENTPERSONAL * */ public void setPublisher( Publisher publisher, ElementDef objectType ) throws ADKException; /** * Register a Publisher message handler with this zone to process SIF_Requests * for the specified object type. This method may be called repeatedly for * each SIF Data Object type the agent will publish on this zone.<p> * * @param publisher An object that implements the <code>Publisher</code> * interface to respond to SIF_Request queries received by the agent, * where the SIF object type referenced by the request matches the * specified objectType. This Publisher will be called whenever a * SIF_Request is received on this zone and no other object in the * message dispatching chain has processed the message. * * @param objectType An ElementDef constant from the SIFDTD class that * identifies a SIF Data Object type. E.g. SIFDTD.STUDENTPERSONAL * * @param options Specify options about which SIF Contexts to join and whether * SIF_Provide messagees will be sent when the agent is running in SIF 1.5r1 or lower */ public void setPublisher( Publisher publisher, ElementDef objectType, PublishingOptions options ) throws ADKException; /** * Register a ReportPublisher message handler to respond to * SIF_Requests for SIF_ReportObject objects. ReportPublisher is implemented * by Vertical Reporting applications that publish report data via the * SIF_ReportObject object introduced in SIF 1.5.<p> * * @param publisher An object that implements the <code>Publisher</code> * interface to respond to SIF_Request queries received by the agent. * This object will be called whenever a SIF_Request is received and * no other object in the message dispatching chain has * processed the message. * */ public void setReportPublisher( ReportPublisher publisher ) throws ADKException; /** * Register a ReportPublisher message handler to respond to * SIF_Requests for SIF_ReportObject objects. ReportPublisher is implemented * by Vertical Reporting applications that publish report data via the * SIF_ReportObject object introduced in SIF 1.5.<p> * * @param publisher An object that implements the <code>Publisher</code> * interface to respond to SIF_Request queries received by the agent. * This object will be called whenever a SIF_Request is received and * no other object in the message dispatching chain has * processed the message. * * @param options Specify which contexts to join as a provider and whether * to send a SIF_Provide message when the agent is running in SIF 1.5r1 or lower */ public void setReportPublisher( ReportPublisher publisher, ReportPublishingOptions options ) throws ADKException; /** * Register a Subscriber message handler with this zone to process SIF_Event * messages for the specified object type. This method may be called * repeatedly for each SIF Data Object type the agent subscribes to on * this zone.<p> * * @param subscriber An object that implements the <code>Subscriber</code> * interface to respond to SIF_Event notifications received by the agent, * where the SIF object type referenced by the request matches the * specified objectType. This Subscriber will be called whenever a * SIF_Event is received on this zone and no other object in the * message dispatching chain has processed the message. * * @param objectType A constant from the SIFDTD class that identifies a * SIF Data Object type. * */ public void setSubscriber( Subscriber subscriber, ElementDef objectType ) throws ADKException; /** * Register a Subscriber message handler with this zone to process SIF_Event * messages for the specified object type. This method may be called * repeatedly for each SIF Data Object type the agent subscribes to on * this zone.<p> * * @param subscriber An object that implements the <code>Subscriber</code> * interface to respond to SIF_Event notifications received by the agent, * where the SIF object type referenced by the request matches the * specified objectType. This Subscriber will be called whenever a * SIF_Event is received on this zone and no other object in the * message dispatching chain has processed the message. * * @param objectType A constant from the SIFDTD class that identifies a * SIF Data Object type. * * @param options Specify which contexts to join and whether SIF_Subscribe * messages will be sent when the agent is running in SIF 1.5r1 or lower */ public void setSubscriber( Subscriber subscriber, ElementDef objectType, SubscriptionOptions options ) throws ADKException; /** * Register a QueryResults message handler with this zone to process * SIF_Response messages for all object types.<p> * * @param queryResults An object that implements the <code>QueryResults</code> * interface to respond to SIF_Response query results received by the * agent. This object will be called whenever a SIF_Response is received * and no other object in the message dispatching chain has processed the message. */ public void setQueryResults( QueryResults queryResults ) throws ADKException; /** * Register a QueryResults object with this zone for the specified SIF object type.<p> * * @param queryResults An object that implements the <code>QueryResults</code> * interface to respond to SIF_Response query results received by the agent, * where the SIF object type referenced by the request matches the * specified objectType. This QueryResults object will be called whenever * a SIF_Response is received on this zone and no other object in the * message dispatching chain has processed the message. * * @param objectType A constant from the SIFDTD class that identifies a * SIF Data Object type. * */ public void setQueryResults( QueryResults queryResults, ElementDef objectType ) throws ADKException; /** * Register a QueryResults object with this zone for the specified SIF object type.<p> * * @param queryResults An object that implements the <code>QueryResults</code> * interface to respond to SIF_Response query results received by the agent, * where the SIF object type referenced by the request matches the * specified objectType. This QueryResults object will be called whenever * a SIF_Response is received on this zone and no other object in the * message dispatching chain has processed the message. * * @param objectType A constant from the SIFDTD class that identifies a * SIF Data Object type. * * @param options Specify which contexts to join */ public void setQueryResults( QueryResults queryResults, ElementDef objectType, QueryResultsOptions options ) throws ADKException; }
apache-2.0
datathings/greycat
plugins/websocket/src/test/java/greycat/websocket/withWorkers/KillTasksTest.java
7776
package greycat.websocket.withWorkers; import greycat.*; import greycat.websocket.WSClientForWorkers; import greycat.websocket.WSServerWithWorkers; import greycat.workers.*; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.util.Collection; import java.util.concurrent.CountDownLatch; import static greycat.Tasks.newTask; public class KillTasksTest { private static WSServerWithWorkers wsServer; @BeforeClass public static void setUp() { CountDownLatch latch = new CountDownLatch(1); //Log.LOG_LEVEL = Log.TRACE; GraphWorkerPool.NUMBER_OF_TASK_WORKER = 3; GraphWorkerPool.MAXIMUM_TASK_QUEUE_SIZE = 100; GraphBuilder graphBuilder = GraphBuilder.newBuilder().withPlugin(new PluginForWorkersTest()); WorkerBuilderFactory defaultRootFactory = () -> DefaultRootWorkerBuilder.newBuilder().withGraphBuilder(graphBuilder); WorkerBuilderFactory defaultFactory = () -> DefaultWorkerBuilder.newBuilder().withGraphBuilder(graphBuilder); GraphWorkerPool workersPool = GraphWorkerPool.getInstance() .withRootWorkerBuilderFactory(defaultRootFactory) .withDefaultWorkerBuilderFactory(defaultFactory); workersPool.setOnPoolReady((worker, allSet) -> { allSet.run(); latch.countDown(); }); workersPool.initialize(); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } GraphWorkerPool.getInstance().createWorker(WorkerAffinity.GENERAL_PURPOSE_WORKER, "GP1", null); wsServer = new WSServerWithWorkers(3003); wsServer.start(); } @Test public void subTasksTest() { CountDownLatch latch = new CountDownLatch(1); Graph clientGraph = GraphBuilder.newBuilder().withStorage(new WSClientForWorkers("ws://localhost:3003/ws")).build(); clientGraph.connect(connected -> { System.out.println("Client Graph connected:" + connected); Task task = newTask().action(PluginForWorkersTest.PARENT_TASK_LAUNCHER); TaskContext taskContext = task.prepare(clientGraph, null, result -> { System.out.println("rootTask finished"); if (result.exception() != null && !(result.exception() instanceof InterruptedException)) { result.exception().printStackTrace(); } clientGraph.disconnect(disconnected -> { System.out.println("Client Graph disconnected: " + disconnected); latch.countDown(); }); }); taskContext.setTaskScopeName("RootWorkerForTestName"); taskContext.setWorkerAffinity(WorkerAffinity.TASK_WORKER); System.out.println("Task submitted"); task.executeRemotelyUsing(taskContext); }); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } @Test public void subTaskKillTest() { CountDownLatch latch = new CountDownLatch(1); WSClientForWorkers wsClient = new WSClientForWorkers("ws://localhost:3003/ws"); Graph clientGraph = GraphBuilder.newBuilder().withStorage(wsClient).build(); clientGraph.connect(connected -> { System.out.println("Client Graph connected:" + connected); Task task = newTask().action(PluginForWorkersTest.PARENT_TASK_LAUNCHER); TaskContext taskContext = task.prepare(clientGraph, null, result -> { System.out.println("rootTask finished"); if (result.exception() != null && !(result.exception() instanceof InterruptedException)) { result.exception().printStackTrace(); } clientGraph.disconnect(disconnected -> { System.out.println("Client Graph disconnected: " + disconnected); latch.countDown(); }); }); taskContext.setWorkerAffinity(WorkerAffinity.TASK_WORKER); System.out.println("Root task submitted"); task.executeRemotelyUsing(taskContext); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //String stats = GraphWorkerPool.getInstance().tasksStats(); Collection<String> workersRefs = GraphWorkerPool.getInstance().getRegisteredWorkers(); workersRefs.forEach(ref -> { if(ref.contains("subTask3")) { wsClient.workerTaskStop(ref, 0, registered -> { System.out.println("subTask3 kill registered"); }); } }); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } workersRefs.forEach(ref -> { if(ref.contains("subTask2")) { wsClient.workerTaskStop(ref, 0, registered -> { System.out.println("subTask3 kill registered"); }); } }); }); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } @Test public void rootTaskKillTest() { CountDownLatch latch = new CountDownLatch(1); WSClientForWorkers wsClient = new WSClientForWorkers("ws://localhost:3003/ws"); Graph clientGraph = GraphBuilder.newBuilder().withStorage(wsClient).build(); clientGraph.connect(connected -> { System.out.println("Client Graph connected:" + connected); Task task = newTask().action(PluginForWorkersTest.PARENT_TASK_LAUNCHER); TaskContext taskContext = task.prepare(clientGraph, null, result -> { System.out.println("rootTask finished"); if (result.exception() != null && !(result.exception() instanceof InterruptedException)) { result.exception().printStackTrace(); } clientGraph.disconnect(disconnected -> { System.out.println("Client Graph disconnected: " + disconnected); latch.countDown(); }); });taskContext.setProgressHook(report->{ System.out.println(report); }); taskContext.setWorkerAffinity(WorkerAffinity.TASK_WORKER); taskContext.setTaskScopeName("RootTaskWorker"); System.out.println("Root task submitted"); task.executeRemotelyUsing(taskContext); try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } //String stats = GraphWorkerPool.getInstance().tasksStats(); Collection<String> workersRefs = GraphWorkerPool.getInstance().getRegisteredWorkers(); workersRefs.forEach(ref -> { if(ref.contains("RootTaskWorker")) { wsClient.workerTaskStop(ref, 0, registered -> { System.out.println("RootTaskWorker kill registered"); }); } }); }); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } @AfterClass public static void tearDown() { if (wsServer != null) { wsServer.stop(); } GraphWorkerPool.getInstance().halt(); } }
apache-2.0
neckhyg/reigister
src/main/java/simplemail/MailAuthenticator.java
970
package simplemail; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class MailAuthenticator extends Authenticator{ /** * 用户名(登录邮箱) */ private String username; /** * 密码 */ private String password; /** * 初始化邮箱和密码 * * @param username 邮箱 * @param password 密码 */ public MailAuthenticator(String username, String password) { this.username = username; this.password = password; } String getPassword() { return password; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public void setUsername(String username) { this.username = username; } }
apache-2.0
ederign/kie-wb-common
kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-api/kie-wb-common-stunner-client-api/src/main/java/org/kie/workbench/common/stunner/core/client/canvas/controls/drag/LocationControl.java
1644
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.stunner.core.client.canvas.controls.drag; import org.kie.workbench.common.stunner.core.client.canvas.CanvasHandler; import org.kie.workbench.common.stunner.core.client.canvas.controls.CanvasControl; import org.kie.workbench.common.stunner.core.client.command.CanvasViolation; import org.kie.workbench.common.stunner.core.client.command.RequiresCommandManager; import org.kie.workbench.common.stunner.core.client.session.ClientFullSession; import org.kie.workbench.common.stunner.core.command.CommandResult; import org.kie.workbench.common.stunner.core.graph.Element; import org.kie.workbench.common.stunner.core.graph.content.view.Point2D; public interface LocationControl<C extends CanvasHandler, E extends Element> extends CanvasControl<C>, RequiresCommandManager<C>, CanvasControl.SessionAware<ClientFullSession> { CommandResult<CanvasViolation> move(final E[] element, final Point2D[] location); }
apache-2.0
brunocvcunha/taskerbox
core/src/main/java/org/brunocvcunha/taskerbox/impl/soap/SOAPChannel.java
3020
/** * Copyright (C) 2015 Bruno Candido Volpato da Cunha (brunocvcunha@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 org.brunocvcunha.taskerbox.impl.soap; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.xml.ws.Endpoint; import org.brunocvcunha.taskerbox.core.ITaskerboxAction; import org.brunocvcunha.taskerbox.core.TaskerboxChannel; import org.brunocvcunha.taskerbox.core.ws.MessageWebService; import org.brunocvcunha.taskerbox.core.ws.TaskerboxWebService; import org.hibernate.validator.constraints.NotEmpty; import org.hibernate.validator.constraints.URL; import lombok.extern.log4j.Log4j; @WebService(name = "SOAP", serviceName = "SOAPService", portName = "SOAPPort") @SOAPBinding(style = SOAPBinding.Style.RPC) @Log4j public class SOAPChannel<T> extends TaskerboxChannel<T> { @NotEmpty @URL private String wsAddress; private Class<? extends TaskerboxWebService> wsClass = MessageWebService.class; public SOAPChannel() { this.singleItemAction = false; } @WebMethod(operationName = "sendMessage") public String sendMessage(@WebParam(name = "msg") T msg) { log.debug("Performing actions to message"); for (ITaskerboxAction<T> action : this.getActions()) { action.action(msg); } return msg.hashCode() + " received."; } @Override @WebMethod(exclude = true) protected void execute() throws Exception { TaskerboxWebService<T> wsImpl = this.wsClass.newInstance(); wsImpl.setChannel(this); Endpoint.publish(this.wsAddress, wsImpl); logInfo(log, "Web service '" + this.wsClass.getName() + "' was published successfully.\n" + "WSDL URL: " + this.wsAddress + "?WSDL"); // Keep the local web server running until the process is killed while (Thread.currentThread().isAlive()) { try { Thread.sleep(10000); } catch (InterruptedException ex) { } } } @Override @WebMethod(exclude = true) public String getItemFingerprint(T entry) { return entry.toString(); } @WebMethod(exclude = true) public String getWsAddress() { return this.wsAddress; } @WebMethod(exclude = true) public void setWsAddress(String wsAddress) { this.wsAddress = wsAddress; } public Class<? extends TaskerboxWebService> getWsClass() { return this.wsClass; } public void setWsClass(Class<? extends TaskerboxWebService> wsClass) { this.wsClass = wsClass; } }
apache-2.0
hanks-zyh/AndroidDesignPattern
app/src/main/java/com/hanks/androiddesignpattern/chapter11/teterimachine/RightCommand.java
365
package com.hanks.androiddesignpattern.chapter11.teterimachine; /** * Created by hanks on 15-12-18. */ public class RightCommand implements Command { TetriMachine tetriMachine; public RightCommand(TetriMachine tetriMachine) { this.tetriMachine = tetriMachine; } @Override public void executed() { tetriMachine.toRight(); } }
apache-2.0
eqot/xray
sample/src/main/java/com/eqot/xray/SampleException.java
316
package com.eqot.xray; @SuppressWarnings("ALL") public class SampleException { private void throwException() throws Exception { throw new Exception(); } private int throwIllegalArgumentException() throws IllegalArgumentException { throw new IllegalArgumentException("message"); } }
apache-2.0
magnetsystems/message-server
server/plugins/mmxmgmt/src/main/java/com/magnet/mmx/server/plugin/mmxmgmt/util/MMXConfigKeys.java
7489
/* Copyright (c) 2015-2016 Magnet Systems, 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.magnet.mmx.server.plugin.mmxmgmt.util; import com.magnet.mmx.protocol.PushMessage; /** * Keys for the configuration values. */ public interface MMXConfigKeys { public static final String WAKEUP_INITIAL_WAIT_KEY = "mmx.wakeup.initialwait"; public static final String WAKEUP_FREQUENCY_KEY = "mmx.wakeup.frequency"; public static final String WAKEUP_MUTE_PERIOD_MINUTES = "mmx.wakeup.mute.minutes"; public static final String SMTP_HOSTNAME_KEY = "mmx.smtp.hostname"; public static final String SMTP_PORT_KEY = "mmx.smtp.port"; public static final String SMTP_ENABLE_TLS_KEY = "mmx.smtp.tls.enable"; public static final String SMTP_LINGERDELAY_SECS_KEY = "mmx.smtp.lingerdelay.secs"; public static final String SMTP_USER_DISPLAY_NAME_KEY = "mmx.system.user.display.name"; public static final String SMTP_USER_EMAIL_ADDRESS_KEY = "mmx.system.user.email.address"; public static final String SMTP_REPLY_EMAIL_ADDRESS_KEY = "mmx.system.user.reply.email.address"; public static final String SMTP_USER_EMAIL_PASSWORD_KEY = "mmx.system.user.email.password"; public static final String EXT_SERVICE_EVENT_GEO = "mmx.ext.service.event.geo"; public static final String EXT_SERVICE_EVENT_GEO_SECRET = "mmx.ext.service.event.geo.secret"; public static final String EXT_SERVICE_PORT = "mmx.ext.service.port"; public static final String EXT_SERVICE_ENABLED = "mmx.ext.service.enabled"; public static final String EXT_SERVICE_EVENT_MESSAGE = "mmx.ext.service.event.message"; /** * Number of minutes after which we should retry sending a wakeup message */ public static final String RETRY_INTERVAL_MINUTES = "mmx.retry.interval.minutes"; /** * Number of wakeup message retries. Minimum value is 1. */ public static final String RETRY_COUNT = "mmx.retry.count"; /** * Mechanism that should be used when doing retry. Possible value are * Standard -- use the basic wakeup mechanism (GCM/APNS) * Enhanced -- use something like SMS ? for retry */ public static final String RETRY_MECHANISM = "mmx.retry.mechanism"; /** * Key to get the number of minutes after which a message is marked as timed out. */ public static final String MESSAGE_TIMEOUT_MINUTES = "mmx.timeout.period.minutes"; @Deprecated public static final String PUSH_CALLBACK_URL = "mmx.push.callbackurl"; /** * Duration in seconds for which push callback url token is valid. */ public static final String PUSH_CALLBACK_TOKEN_TTL = "push.token.ttl"; /** * User name that should be used for sending message from the console. */ public static final String CONSOLE_MESSAGE_SEND_USER = "mmx.console.messagesender"; /** * Server domain name that should be used for construction the TO and From * addresses when delivering messages triggered from the console. */ public static final String SERVER_DOMAIN_NAME = "mmx.domain.name"; public static final String MAX_DEVICES_PER_APP = "mmx.cluster.max.devices.per.app"; public static final String MAX_DEVICES_PER_USER = "mmx.cluster.max.devices.per.user"; public static final String MAX_APP_PER_OWNER = "mmx.cluster.max.apps"; public static final String MAX_XMPP_RATE = "mmx.instance.max.xmpp.rate.per.sec"; public static final String MAX_HTTP_RATE = "mmx.instance.max.http.rate.per.sec"; public static final String ALERT_EMAIL_SUBJECT = "mmx.alert.email.subject"; public static final String ALERT_EMAIL_HOST="mmx.alert.email.host"; public static final String ALERT_EMAIL_PORT="mmx.alert.email.port"; public static final String ALERT_EMAIL_USER="mmx.alert.email.user"; public static final String ALERT_EMAIL_PASSWORD="mmx.alert.email.password"; public static final String ALERT_EMAIL_BCC_LIST = "mmx.alert.email.bcc.list"; public static final String ALERT_EMAIL_ENABLED = "mmx.alert.email.enabled"; public static final String ALERT_INTER_EMAIL_TIME_MINUTES = "mmx.alert.inter.email.time.minutes"; /** * Keys related to APNS Connection pool. */ public static final String APNS_POOL_MAX_TOTAL_CONNECTIONS = "mmx.apns.pool.max.connections"; public static final String APNS_POOL_MAX_CONNECTIONS_PER_APP = "mmx.apns.pool.max.app.connections"; public static final String APNS_POOL_MAX_IDLE_CONNECTIONS_PER_APP = "mmx.apns.pool.max.idle.count"; public static final String APNS_POOL_WAIT_SECONDS = "mmx.apns.pool.wait.sec"; public static final String APNS_POOL_IDLE_TTL_MINUTES = "mmx.apns.pool.idle.ttl.min"; /** * Keys related to https for the rest API */ public static final String REST_ENABLE_HTTPS = "mmx.rest.enable.https"; public static final String REST_HTTP_PORT = "mmx.rest.http.port"; public static final String REST_HTTPS_PORT = "mmx.rest.https.port"; /** * Keys related to admin api server */ public static final String ADMIN_API_PORT = "mmx.admin.api.port"; public static final String ADMIN_API_ENABLE_HTTPS = "mmx.admin.api.enable.https"; public static final String ADMIN_API_HTTPS_PORT = "mmx.admin.api.https.port"; /** * Key related to admin security mode */ public static final String ADMIN_REST_API_ACCESS_CONTROL_MODE = "mmx.admin.api.access.control.mode"; public static final String ADMIN_API_HTTPS_CERT_FILE = "mmx.admin.api.https.certfile"; public static final String ADMIN_API_HTTPS_CERT_PASSWORD = "mmx.admin.api.https.certpwd"; /** * XMPP keys to expose via config servlet */ public static final String XMPP_CLIENT_TLS_POLICY = "xmpp.client.tls.policy"; public static final String DATABASE_URL = "mmx.db.url"; public static final String DATABASE_USER = "mmx.db.user"; /** * Host name to be used for call back URL construction */ public static final String PUSH_CALLBACK_HOST = "mmx.push.callback.host"; /** * Protocol to be used for call back URL construction. Choices are http or https */ public static final String PUSH_CALLBACK_PROTOCOL = "mmx.push.callback.protocol"; /** * Port to be used for call back URL construction. If not specified this will default to REST_HTTP_PORT */ public static final String PUSH_CALLBACK_PORT = "mmx.push.callback.port"; public static final String MMX_VERSION = "mmx.version"; /* * APNS Feedback */ public static final String APNS_FEEDBACK_PROCESS_INITIAL_DELAY_MINUTES = "mmx.apns.feedback.initialwait.min"; public static final String APNS_FEEDBACK_PROCESS_FREQUENCY_MINUTES = "mmx.apns.feedback.frequency.min"; /* * Pubsub Notification. The types are defined in PushMessage.Action (case * insensitive.) An empty string will disable the pubsub notification. */ public static final String PUBSUB_NOTIFICATION_TYPE = "mmx.pubsub.notification.type"; public static final String PUBSUB_NOTIFICATION_TITLE = "mmx.pubsub.notification.title"; public static final String PUBSUB_NOTIFICATION_BODY = "mmx.pubsub.notification.body"; }
apache-2.0
10045125/VandaIMLibForHub
AndroidBucket-master/src/com/wangjie/androidbucket/adapter/typeadapter/expand/ExpandGroupAdapterTypeRender.java
701
package com.wangjie.androidbucket.adapter.typeadapter.expand; import android.view.View; /** * 用于对不同类型item的group数据到UI的渲染 * Author: wangjie * Email: tiantian.china.2@gmail.com * Date: 9/14/14. */ public interface ExpandGroupAdapterTypeRender { /** * 返回一个item的convertView,也就是BaseAdapter中getView方法中返回的convertView * * @return */ View getConvertView(); /** * 填充item中各个控件的事件,比如按钮点击事件等 */ void fitEvents(); /** * 对指定position的item进行数据的适配 * * @param groupPosition */ void fitDatas(int groupPosition); }
apache-2.0
divyabellur/starbright
src/main/java/com/startup/sportwise/service/package-info.java
80
/** * */ /** * @author dmurthy * */ package com.startup.sportwise.service;
apache-2.0
amoudi87/asterixdb
asterix-runtime/src/main/java/org/apache/asterix/runtime/evaluators/common/SimilarityJaccardSortedCheckEvaluator.java
1977
/* * 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.asterix.runtime.evaluators.common; import org.apache.asterix.fuzzyjoin.similarity.SimilarityMetricJaccard; import org.apache.asterix.om.types.ATypeTag; import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException; import org.apache.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory; import org.apache.hyracks.api.exceptions.HyracksDataException; import org.apache.hyracks.data.std.api.IDataOutputProvider; public class SimilarityJaccardSortedCheckEvaluator extends SimilarityJaccardCheckEvaluator { protected final SimilarityMetricJaccard jaccard = new SimilarityMetricJaccard(); public SimilarityJaccardSortedCheckEvaluator(ICopyEvaluatorFactory[] args, IDataOutputProvider output) throws AlgebricksException { super(args, output); } @Override protected float computeResult(byte[] bytes, int firstStart, int secondStart, ATypeTag argType) throws AlgebricksException { try { return jaccard.getSimilarity(firstListIter, secondListIter, jaccThresh); } catch (HyracksDataException e) { throw new AlgebricksException(e); } } }
apache-2.0
asakusafw/asakusafw-compiler
vanilla/runtime/core/src/test/java/com/asakusafw/vanilla/core/mirror/GraphMirrorTest.java
6607
/** * Copyright 2011-2021 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.vanilla.core.mirror; import static com.asakusafw.vanilla.core.testing.ModelMirrors.*; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import org.junit.Test; import com.asakusafw.dag.api.model.GraphInfo; import com.asakusafw.dag.api.model.PortInfo; import com.asakusafw.dag.api.model.VertexInfo; import com.asakusafw.dag.api.model.basic.BasicEdgeDescriptor.Movement; import com.asakusafw.dag.runtime.skeleton.VoidVertexProcessor; import com.asakusafw.dag.runtime.testing.IntSerDe; import com.asakusafw.dag.runtime.testing.MockDataModelUtil; /** * Test for {@link GraphMirror}. */ public class GraphMirrorTest { /** * simple case. */ @Test public void simple() { GraphInfo graph = new GraphInfo(); VertexInfo v0 = graph.addVertex("v0", vertex(VoidVertexProcessor.class)); GraphMirror mirror = GraphMirror.of(graph); assertThat(mirror.getVertices(), hasSize(1)); VertexMirror v0m = mirror.getVertex(v0.getId()); assertThat(v0m.getInputs(), hasSize(0)); assertThat(v0m.getOutputs(), hasSize(0)); assertThat(v0m.newProcessor(getClass().getClassLoader()), instanceOf(VoidVertexProcessor.class)); } /** * with edge. */ @Test public void edge() { GraphInfo graph = new GraphInfo(); VertexInfo v0 = graph.addVertex("v0", vertex(VoidVertexProcessor.class)); VertexInfo v1 = graph.addVertex("v1", vertex(VoidVertexProcessor.class)); PortInfo v0o0 = v0.addOutputPort("o0"); PortInfo v1i0 = v1.addInputPort("i0"); graph.addEdge(v0o0.getId(), v1i0.getId(), oneToOne(IntSerDe.class)); GraphMirror mirror = GraphMirror.of(graph); VertexMirror v0m = mirror.getVertex(v0.getId()); VertexMirror v1m = mirror.getVertex(v1.getId()); OutputPortMirror v0o0m = mirror.getOutput(v0o0.getId()); InputPortMirror v1i0m = mirror.getInput(v1i0.getId()); assertThat(v0o0m.getOwner(), is(v0m)); assertThat(v0o0m.getMovement(), is(Movement.ONE_TO_ONE)); assertThat(v0o0m.newValueSerDe(getClass().getClassLoader()), instanceOf(IntSerDe.class)); assertThat(v0o0m.getOpposites(), contains(v1i0m)); assertThat(v1i0m.getOwner(), is(v1m)); assertThat(v1i0m.getMovement(), is(Movement.ONE_TO_ONE)); assertThat(v1i0m.newValueSerDe(getClass().getClassLoader()), instanceOf(IntSerDe.class)); assertThat(v1i0m.getOpposites(), contains(v0o0m)); } /** * w/ scatter-gather. */ @Test public void scatter_gather() { GraphInfo graph = new GraphInfo(); VertexInfo v0 = graph.addVertex("v0", vertex(VoidVertexProcessor.class)); VertexInfo v1 = graph.addVertex("v1", vertex(VoidVertexProcessor.class)); PortInfo v0o0 = v0.addOutputPort("o0"); PortInfo v1i0 = v1.addInputPort("i0"); graph.addEdge(v0o0.getId(), v1i0.getId(), scatterGather(MockDataModelUtil.KvSerDe1.class, MockDataModelUtil.KvSerDe1.class)); GraphMirror mirror = GraphMirror.of(graph); VertexMirror v0m = mirror.getVertex(v0.getId()); VertexMirror v1m = mirror.getVertex(v1.getId()); OutputPortMirror v0o0m = mirror.getOutput(v0o0.getId()); InputPortMirror v1i0m = mirror.getInput(v1i0.getId()); assertThat(v0o0m.getOwner(), is(v0m)); assertThat(v0o0m.getMovement(), is(Movement.SCATTER_GATHER)); assertThat(v0o0m.newKeyValueSerDe(getClass().getClassLoader()), instanceOf(MockDataModelUtil.KvSerDe1.class)); assertThat(v0o0m.newComparator(getClass().getClassLoader()), instanceOf(MockDataModelUtil.KvSerDe1.class)); assertThat(v0o0m.getOpposites(), contains(v1i0m)); assertThat(v1i0m.getOwner(), is(v1m)); assertThat(v1i0m.getMovement(), is(Movement.SCATTER_GATHER)); assertThat(v1i0m.newKeyValueSerDe(getClass().getClassLoader()), instanceOf(MockDataModelUtil.KvSerDe1.class)); assertThat(v1i0m.newComparator(getClass().getClassLoader()), instanceOf(MockDataModelUtil.KvSerDe1.class)); assertThat(v1i0m.getOpposites(), contains(v0o0m)); } /** * multiple vertices. */ @Test public void multiple() { GraphInfo graph = new GraphInfo(); VertexInfo v0 = graph.addVertex("v0", vertex(VoidVertexProcessor.class)); VertexInfo v1 = graph.addVertex("v1", vertex(VoidVertexProcessor.class)); VertexInfo v2 = graph.addVertex("v2", vertex(VoidVertexProcessor.class)); PortInfo v0o0 = v0.addOutputPort("o0"); PortInfo v1i0 = v1.addInputPort("i0"); PortInfo v1o0 = v1.addOutputPort("o0"); PortInfo v2i0 = v2.addInputPort("i0"); graph.addEdge(v0o0.getId(), v1i0.getId(), oneToOne(IntSerDe.class)); graph.addEdge(v1o0.getId(), v2i0.getId(), oneToOne(IntSerDe.class)); GraphMirror mirror = GraphMirror.of(graph); assertThat(mirror.getVertices(), hasSize(3)); VertexMirror v0m = mirror.getVertex(v0.getId()); assertThat(v0m.getInputs(), hasSize(0)); assertThat(v0m.getOutputs(), hasSize(1)); VertexMirror v1m = mirror.getVertex(v1.getId()); assertThat(v1m.getInputs(), hasSize(1)); assertThat(v1m.getOutputs(), hasSize(1)); VertexMirror v2m = mirror.getVertex(v2.getId()); assertThat(v2m.getInputs(), hasSize(1)); assertThat(v2m.getOutputs(), hasSize(0)); OutputPortMirror v0o0m = mirror.getOutput(v0o0.getId()); InputPortMirror v1i0m = mirror.getInput(v1i0.getId()); assertThat(v0o0m.getOpposites(), contains(v1i0m)); assertThat(v1i0m.getOpposites(), contains(v0o0m)); OutputPortMirror v1o0m = mirror.getOutput(v1o0.getId()); InputPortMirror v2i0m = mirror.getInput(v2i0.getId()); assertThat(v1o0m.getOpposites(), contains(v2i0m)); assertThat(v2i0m.getOpposites(), contains(v1o0m)); } }
apache-2.0
joshelser/cereal
core/src/main/java/cereal/impl/StoreImpl.java
5379
/* * Copyright 2015 Josh Elser * * 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 cereal.impl; import static com.google.common.base.Preconditions.checkNotNull; import java.lang.reflect.Method; import java.util.Collection; import org.apache.accumulo.core.client.BatchWriter; import org.apache.accumulo.core.client.BatchWriterConfig; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.MutationsRejectedException; import org.apache.accumulo.core.client.Scanner; import org.apache.accumulo.core.client.TableNotFoundException; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.security.Authorizations; import org.apache.hadoop.io.Text; import cereal.Field; import cereal.InstanceOrBuilder; import cereal.Mapping; import cereal.Registry; import cereal.Store; import com.google.protobuf.GeneratedMessage; import com.google.protobuf.Message; /** * {@link Store} implementation that uses Accumulo. */ public class StoreImpl implements Store { Registry reg; Connector conn; String table; BatchWriter bw; public StoreImpl(Registry reg, Connector conn, String table) { checkNotNull(reg, "Registry was null"); checkNotNull(conn, "Connector was null"); checkNotNull(table, "Accumulo table was null"); this.reg = reg; this.conn = conn; this.table = table; } BatchWriter getOrCreateBatchWriter() throws TableNotFoundException { if (null == bw) { bw = conn.createBatchWriter(table, new BatchWriterConfig()); } return bw; } /** * @return Get the internal {@link BatchWriter}, or null if it's not initialized. */ BatchWriter getBatchWriter() { return bw; } @Override public <T> void write(Collection<T> msgs) throws Exception { checkNotNull(msgs, "Message to write were null"); BatchWriter bw = getOrCreateBatchWriter(); Mapping<T> mapping = null; for (T m : msgs) { if (null == mapping) { InstanceOrBuilder<T> instOrBuilder = toInstanceOrBuilder(m); mapping = reg.get(instOrBuilder); if (null == mapping) { throw new IllegalStateException("Registry doesn't contain Mapping for " + instOrBuilder); } } Mutation mut = new Mutation(mapping.getRowId(m)); for (Field f : mapping.getFields(m)) { mut.put(f.grouping(), f.name(), f.visibility(), f.value()); } bw.addMutation(mut); } } @Override public void flush() throws Exception { if (bw != null) { bw.flush(); } } @Override public <T> T read(Text id, Class<T> clz) throws Exception { checkNotNull(id, "ID was null"); checkNotNull(clz, "Target class was null"); Scanner s = conn.createScanner(table, Authorizations.EMPTY); s.setRange(Range.exact(id)); InstanceOrBuilder<T> instOrBuilder = toInstanceOrBuilder(clz); Mapping<T> mapping = reg.get(instOrBuilder); mapping.update(s, instOrBuilder); switch (instOrBuilder.getType()) { case INSTANCE: @SuppressWarnings("unchecked") T obj = (T) instOrBuilder.get(); return obj; case BUILDER: GeneratedMessage.Builder<?> builder = (GeneratedMessage.Builder<?>) instOrBuilder.get(); @SuppressWarnings("unchecked") T pb = (T) builder.build(); return pb; default: throw new IllegalArgumentException("Cannot handle unknown InstanceOrBuilder.Type"); } } protected <T> InstanceOrBuilder<T> toInstanceOrBuilder(T instance) { if (instance instanceof GeneratedMessage) { try { Message.Builder builder = ((GeneratedMessage) instance).newBuilderForType(); @SuppressWarnings("unchecked") Class<T> typedClz = (Class<T>) instance.getClass(); return new InstanceOrBuilderImpl<T>(builder, typedClz); } catch (Exception e) { throw new RuntimeException(e); } } else { // POJO or Thrift return new InstanceOrBuilderImpl<T>(instance); } } protected <T> InstanceOrBuilder<T> toInstanceOrBuilder(Class<T> clz) { try { if (GeneratedMessage.class.isAssignableFrom(clz)) { // Protobuf Message @SuppressWarnings("unchecked") Class<? extends GeneratedMessage> msgClz = (Class<GeneratedMessage>) clz; Method newBuilderMethod = msgClz.getMethod("newBuilder"); Message.Builder builder = (Message.Builder) newBuilderMethod.invoke(null); return new InstanceOrBuilderImpl<T>(builder, clz); } else { // A POJO or Thrift return new InstanceOrBuilderImpl<T>(clz.newInstance()); } } catch (Exception e) { throw new RuntimeException(e); } } @Override public void close() throws MutationsRejectedException { if (null != bw) { bw.close(); bw = null; } } }
apache-2.0
agapsys/simple-http-client
src/main/java/com/agapsys/http/utils/Pair.java
1935
/* * Copyright 2015 Agapsys Tecnologia Ltda-ME. * * 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.agapsys.http.utils; import java.util.Objects; /** Represents a pair of objects. */ public class Pair<T1, T2> { private final T1 first; private final T2 second; /** Constructor. */ public Pair(T1 first, T2 second) { this.first = first; this.second = second; } /** @return the first object. */ protected T1 getFirst() { return first; } /** @return the second object. */ protected T2 getSecond() { return second; } @Override public String toString() { return String.format("[%s, %s]", first.toString(), second.toString()); } @Override public int hashCode() { int hash = 7; hash = 53 * hash + Objects.hashCode(this.first); hash = 53 * hash + Objects.hashCode(this.second); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Pair<?, ?> other = (Pair<?, ?>) obj; if (!Objects.equals(this.first, other.first)) { return false; } if (!Objects.equals(this.second, other.second)) { return false; } return true; } }
apache-2.0
XihuLai/GS
src/com/dyz/myBatis/services/NoticeTableService.java
1748
package com.dyz.myBatis.services; import java.sql.SQLException; import org.apache.ibatis.session.SqlSessionFactory; import com.dyz.myBatis.dao.NoticeTableMapper; import com.dyz.myBatis.daoImp.NoitceTableDaoImp; import com.dyz.myBatis.model.NoticeTable; /** * Created by kevin on 2016/6/21. */ public class NoticeTableService { private NoticeTableMapper noticeTableMapper; private static NoticeTableService noticeTableService = new NoticeTableService(); public static NoticeTableService getInstance(){ return noticeTableService; } public void initSetSession(SqlSessionFactory sqlSessionFactory){ noticeTableMapper = new NoitceTableDaoImp(sqlSessionFactory); } /** * * @param account * @throws SQLException */ public void updateAccount(NoticeTable noticeTable) { try { int index = noticeTableMapper.updateByPrimaryKey(noticeTable); System.out.println("===index====> "+index); }catch (Exception e){ System.out.println(e.getMessage()); } } /** * * @param account * @throws SQLException */ public void updateByPrimaryKeySelective(NoticeTable noticeTable){ try{ int index = noticeTableMapper.updateByPrimaryKeySelective(noticeTable); }catch (Exception e){ System.out.println(e.getMessage()); } } /** * 获取最近一次公告 */ public NoticeTable selectRecentlyObject(){ NoticeTable noticeTable = null; try{ noticeTable = noticeTableMapper.selectRecentlyObject(); }catch (Exception e){ System.out.println(e.getMessage()); } return noticeTable; } }
apache-2.0
devemux86/graphhopper
reader-gtfs/src/main/java/com/graphhopper/reader/gtfs/Transfers.java
6641
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH 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.graphhopper.reader.gtfs; import com.conveyal.gtfs.GTFSFeed; import com.conveyal.gtfs.model.Transfer; import java.util.*; import java.util.stream.Collectors; public class Transfers { private final Map<String, List<Transfer>> transfersFromStop; private final Map<String, List<Transfer>> transfersToStop; private final Map<String, Set<String>> routesByStop; public Transfers(GTFSFeed feed) { this.transfersToStop = feed.transfers.values().stream().collect(Collectors.groupingBy(t -> t.to_stop_id)); this.transfersFromStop = feed.transfers.values().stream().collect(Collectors.groupingBy(t -> t.from_stop_id)); this.routesByStop = feed.stop_times.values().stream() .collect(Collectors.groupingBy(stopTime -> stopTime.stop_id, Collectors.mapping(stopTime -> feed.trips.get(stopTime.trip_id).route_id, Collectors.toSet()))); } // Starts implementing the proposed GTFS extension for route and trip specific transfer rules. // So far, only the route is supported. List<Transfer> getTransfersToStop(String toStopId, String toRouteId) { final List<Transfer> allInboundTransfers = transfersToStop.getOrDefault(toStopId, Collections.emptyList()); final Map<String, List<Transfer>> byFromStop = allInboundTransfers.stream() .filter(t -> t.transfer_type == 0 || t.transfer_type == 2) .filter(t -> t.to_route_id == null || toRouteId.equals(t.to_route_id)) .collect(Collectors.groupingBy(t -> t.from_stop_id)); final List<Transfer> result = new ArrayList<>(); byFromStop.forEach((fromStop, transfers) -> { if (hasNoRouteSpecificArrivalTransferRules(fromStop)) { Transfer myRule = new Transfer(); myRule.from_stop_id = fromStop; myRule.to_stop_id = toStopId; result.add(myRule); } else { routesByStop.getOrDefault(fromStop, Collections.emptySet()).forEach(fromRoute -> { final Transfer mostSpecificRule = findMostSpecificRule(transfers, fromRoute, toRouteId); final Transfer myRule = new Transfer(); myRule.to_route_id = toRouteId; myRule.from_route_id = fromRoute; myRule.to_stop_id = mostSpecificRule.to_stop_id; myRule.from_stop_id = mostSpecificRule.from_stop_id; myRule.transfer_type = mostSpecificRule.transfer_type; myRule.min_transfer_time = mostSpecificRule.min_transfer_time; myRule.from_trip_id = mostSpecificRule.from_trip_id; myRule.to_trip_id = mostSpecificRule.to_trip_id; result.add(myRule); }); } }); if (result.stream().noneMatch(t -> t.from_stop_id.equals(toStopId))) { final Transfer withinStationTransfer = new Transfer(); withinStationTransfer.from_stop_id = toStopId; withinStationTransfer.to_stop_id = toStopId; result.add(withinStationTransfer); } return result; } List<Transfer> getTransfersFromStop(String fromStopId, String fromRouteId) { final List<Transfer> allOutboundTransfers = transfersFromStop.getOrDefault(fromStopId, Collections.emptyList()); final Map<String, List<Transfer>> byToStop = allOutboundTransfers.stream() .filter(t -> t.transfer_type == 0 || t.transfer_type == 2) .filter(t -> t.from_route_id == null || fromRouteId.equals(t.from_route_id)) .collect(Collectors.groupingBy(t -> t.to_stop_id)); final List<Transfer> result = new ArrayList<>(); byToStop.forEach((toStop, transfers) -> { routesByStop.getOrDefault(toStop, Collections.emptySet()).forEach(toRouteId -> { final Transfer mostSpecificRule = findMostSpecificRule(transfers, fromRouteId, toRouteId); final Transfer myRule = new Transfer(); myRule.to_route_id = toRouteId; myRule.from_route_id = fromRouteId; myRule.to_stop_id = mostSpecificRule.to_stop_id; myRule.from_stop_id = mostSpecificRule.from_stop_id; myRule.transfer_type = mostSpecificRule.transfer_type; myRule.min_transfer_time = mostSpecificRule.min_transfer_time; myRule.from_trip_id = mostSpecificRule.from_trip_id; myRule.to_trip_id = mostSpecificRule.to_trip_id; result.add(myRule); }); }); return result; } private Transfer findMostSpecificRule(List<Transfer> transfers, String fromRouteId, String toRouteId) { final ArrayList<Transfer> transfersBySpecificity = new ArrayList<>(transfers); transfersBySpecificity.sort(Comparator.comparingInt(t -> { int score = 0; if (Objects.equals(fromRouteId, t.from_route_id)) { score++; } if (Objects.equals(toRouteId, t.to_route_id)) { score++; } return -score; })); if (transfersBySpecificity.isEmpty()) { throw new RuntimeException(); } return transfersBySpecificity.get(0); } public boolean hasNoRouteSpecificDepartureTransferRules(String stop_id) { return transfersToStop.getOrDefault(stop_id, Collections.emptyList()).stream().allMatch(transfer -> transfer.to_route_id == null); } public boolean hasNoRouteSpecificArrivalTransferRules(String stop_id) { return transfersFromStop.getOrDefault(stop_id, Collections.emptyList()).stream().allMatch(transfer -> transfer.from_route_id == null); } }
apache-2.0
bluemind-net/bm-agent
bm-agent/net.bluemind.bm-agent.common/src/net/bluemind/agent/server/ServerConnection.java
1120
/* BEGIN LICENSE * Copyright © Blue Mind SAS, 2012-2016 * * This file is part of Blue Mind. Blue Mind is a messaging and collaborative * solution. * * This program is free software; you can redistribute it and/or modify * it under the terms of either the GNU Affero General Public License as * published by the Free Software Foundation (version 3 of the License) * or the CeCILL as published by CeCILL.info (version 2 of the License). * * There are special exceptions to the terms and conditions of the * licenses as they are applied to this program. See LICENSE.txt in * the directory of this program distribution. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See LICENSE.txt * END LICENSE */ package net.bluemind.agent.server; import net.bluemind.agent.DoneHandler; public interface ServerConnection { void send(String agentId, String command, byte[] data, DoneHandler doneHandler); void send(String agentId, String command, byte[] bytes); }
apache-2.0
macrozheng/mall
mall-portal/src/main/java/com/macro/mall/portal/config/GlobalCorsConfig.java
1121
package com.macro.mall.portal.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; /** * 全局跨域相关配置 * Created by macro on 2019/7/27. */ @Configuration public class GlobalCorsConfig { /** * 允许跨域调用的过滤器 */ @Bean public CorsFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); //允许所有域名进行跨域调用 config.addAllowedOrigin("*"); //允许跨越发送cookie config.setAllowCredentials(true); //放行全部原始头信息 config.addAllowedHeader("*"); //允许所有请求方法跨域调用 config.addAllowedMethod("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } }
apache-2.0
peng571/library-core
tool-datalist/src/main/java/org/pengyr/tool/datalist/RefreshModelProvider.java
7037
package org.pengyr.tool.datalist; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import org.pengyr.tool.core.data.DataModel; import org.pengyr.tool.core.data.DataModelProvider; import org.pengyr.tool.core.log.Logger; import org.pengyr.tool.datalist.parser.ObjectParser; import java.io.IOException; import java.util.List; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * to get refresh data from server and parse into @link AdapterDataProvider * <p> * only refresh data when option is on main ui thread * <p> * Created by Peng on 2017/6/13. */ public class RefreshModelProvider<M extends DataModel<P>, P> extends DataModelProvider<M, P> { private final String TAG = RefreshModelProvider.class.getSimpleName(); protected boolean fetching = false; protected boolean noMore = false; protected boolean refresh = false; @Nullable protected PagingOption pageOption; @Nullable protected OnRefreshListener<P> refreshOption; @Nullable protected RefreshCellHolder<M, P> refreshCellHolder; public RefreshModelProvider() { super(); fetching = false; noMore = false; refresh = false; } @Override public void unbind() { super.unbind(); this.refreshOption = null; this.pageOption = null; this.refreshCellHolder = null; } public void bind(RecyclerView.Adapter adapter, RefreshCellHolder remotCell) { bind(adapter, null, null, remotCell); } public void bind(RecyclerView.Adapter adapter, @Nullable OnRefreshListener refresh, RefreshCellHolder remotCell) { bind(adapter, null, refresh, remotCell); } public void bind(RecyclerView.Adapter adapter, @Nullable OnNotifyListener<P> notifyListener, @Nullable OnRefreshListener refresh, RefreshCellHolder remotCell) { bind(adapter, notifyListener, refresh, null, remotCell); } public void bind(RecyclerView.Adapter adapter, @Nullable OnNotifyListener<P> notifyListener, @Nullable OnRefreshListener refresh, @Nullable PagingOption page, RefreshCellHolder remotCell) { super.bind(adapter, notifyListener); this.refreshOption = refresh; this.pageOption = page; this.refreshCellHolder = remotCell; // call on refresh done again when bind again this.refreshOption.onRefreshDone(false); } @Nullable @Override public P get(int position) { // ask load more, on item get askLoadMore(position); return super.get(position); } private boolean isPagable() { return pageOption != null; } private boolean isRefreshable() { return refreshOption != null; } public boolean isFetching() { return fetching; } // Not recommended for use public void setFetching(boolean b) { fetching = b; } /** * Refresh Method */ public void reload() { if (!isRefreshable()) { Logger.WS(TAG, "provider is not refreshable"); return; } refresh = true; noMore = false; load(); } public int getLoadOffset() { if (refresh) return 0; return count(); } /** * Paging Method */ protected void askLoadMore(int position) { if (!isPagable()) return; if (isFetching()) return; if (noMore) return; if (count() - position < pageOption.getPageItemCount()) { // load more load(); } } public synchronized void load() { if (!refresh && fetching) { return; } if (refreshCellHolder == null) return; fetching = true; refreshCellHolder.getRefreshApiCell().enqueue(new Callback<List<M>>() { @Override public void onResponse(Call<List<M>> call, Response<List<M>> response) { if (response == null) { Logger.ES(TAG, "get null response"); onLoadFinish(null); return; } // check if response has error body try { ResponseBody errorBody = response.errorBody(); if (errorBody != null) { String errormessage = errorBody.string(); Logger.ES(TAG, "refresh failed: %s", errormessage); onLoadFinish(null); return; } } catch (IOException e) { e.printStackTrace(); } // parse response to items if (refreshCellHolder != null) { List<P> list = refreshCellHolder.getRefreshParser().parseResponse(response); onLoadFinish(list); } else { onLoadFinish(null); } } @Override public void onFailure(Call call, Throwable t) { Logger.ES(TAG, "call api onFailure"); onLoadFinish(null); } }); } protected synchronized void onLoadFinish(@Nullable List<P> newItems) { fetching = false; boolean loadSuccess; if (newItems == null) { Logger.ES(TAG, "get null data"); loadSuccess = false; } else { loadSuccess = true; if (refresh) { // On refresh, clean old data clear(); } int newItemCount = newItems.size(); Logger.I(TAG, "update item %d", newItemCount); for (P p : newItems) { add(p); } if (isPagable()) { if (newItemCount < pageOption.getPageItemCount()) { noMore = true; } else { noMore = false; } } } refresh = false; if (refreshOption == null) return; refreshOption.onRefreshDone(loadSuccess); } /** * @Param <L> item in list * <p> * Created by Peng on 2017/6/14. */ public interface OnRefreshListener<L> { void onRefreshDone(boolean success); } /** * Paging option * <p> * Created by Peng on 2017/6/14. */ public interface PagingOption { int getPageItemCount(); } /** * Use for refreshable and pageable list activity * * @param <S> item in Server * @param <L> item in Shown List */ public interface RefreshCellHolder<S extends DataModel<L>, L> { /** * parse item to what list want, return null to ignore this item from list */ @NonNull ObjectParser<L, S> getRefreshParser(); @NonNull Call<List<S>> getRefreshApiCell(); } }
apache-2.0
whuwxl/bazel
src/main/java/com/google/devtools/build/lib/packages/AspectDefinition.java
16115
// Copyright 2014 The Bazel 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 com.google.devtools.build.lib.packages; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; import com.google.devtools.build.lib.cmdline.Label; import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable; import com.google.devtools.build.lib.packages.ConfigurationFragmentPolicy.MissingFragmentPolicy; import com.google.devtools.build.lib.packages.NativeAspectClass.NativeAspectFactory; import com.google.devtools.build.lib.util.Preconditions; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * The definition of an aspect (see {@link Aspect} for moreinformation.) * * <p>Contains enough information to build up the configured target graph except for the actual way * to build the Skyframe node (that is the territory of * {@link com.google.devtools.build.lib.view AspectFactory}). In particular: * <ul> * <li>The condition that must be fulfilled for an aspect to be able to operate on a configured * target * <li>The (implicit or late-bound) attributes of the aspect that denote dependencies the aspect * itself needs (e.g. runtime libraries for a new language for protocol buffers) * <li>The aspects this aspect requires from its direct dependencies * </ul> * * <p>The way to build the Skyframe node is not here because this data needs to be accessible from * the {@code .packages} package and that one requires references to the {@code .view} package. */ @Immutable public final class AspectDefinition { private final String name; private final ImmutableSet<Class<?>> requiredProviders; private final ImmutableSet<String> requiredProviderNames; private final ImmutableMap<String, Attribute> attributes; private final ImmutableMultimap<String, AspectClass> attributeAspects; @Nullable private final ConfigurationFragmentPolicy configurationFragmentPolicy; private AspectDefinition( String name, ImmutableSet<Class<?>> requiredProviders, ImmutableMap<String, Attribute> attributes, ImmutableMultimap<String, AspectClass> attributeAspects, @Nullable ConfigurationFragmentPolicy configurationFragmentPolicy) { this.name = name; this.requiredProviders = requiredProviders; this.requiredProviderNames = toStringSet(requiredProviders); this.attributes = attributes; this.attributeAspects = attributeAspects; this.configurationFragmentPolicy = configurationFragmentPolicy; } public String getName() { return name; } /** * Returns the attributes of the aspect in the form of a String -&gt; {@link Attribute} map. * * <p>All attributes are either implicit or late-bound. */ public ImmutableMap<String, Attribute> getAttributes() { return attributes; } /** * Returns the set of {@link com.google.devtools.build.lib.analysis.TransitiveInfoProvider} * instances that must be present on a configured target so that this aspect can be applied to it. * * <p>We cannot refer to that class here due to our dependency structure, so this returns a set * of unconstrained class objects. * * <p>If a configured target does not have a required provider, the aspect is silently not created * for it. */ public ImmutableSet<Class<?>> getRequiredProviders() { return requiredProviders; } /** * Returns the set of class names of * {@link com.google.devtools.build.lib.analysis.TransitiveInfoProvider} instances that must be * present on a configured target so that this aspect can be applied to it. * * <p>This set is a mirror of the set returned by {@link #getRequiredProviders}, but contains the * names of the classes rather than the class objects themselves. * * <p>If a configured target does not have a required provider, the aspect is silently not created * for it. */ public ImmutableSet<String> getRequiredProviderNames() { return requiredProviderNames; } /** * Returns the attribute -&gt; set of required aspects map. */ public ImmutableMultimap<String, AspectClass> getAttributeAspects() { return attributeAspects; } /** * Returns the set of configuration fragments required by this Aspect, or {@code null} if it has * not set a configuration fragment policy, meaning it should inherit from the attached rule. */ @Nullable public ConfigurationFragmentPolicy getConfigurationFragmentPolicy() { // TODO(mstaib): When all existing aspects properly set their configuration fragment policy, // this method and the associated member should no longer be nullable. // "inherit from the attached rule" should go away. return configurationFragmentPolicy; } /** * Returns the attribute -&gt; set of labels that are provided by aspects of attribute. */ public static ImmutableMultimap<Attribute, Label> visitAspectsIfRequired( Target from, Attribute attribute, Target to, DependencyFilter dependencyFilter) { // Aspect can be declared only for Rules. if (!(from instanceof Rule) || !(to instanceof Rule)) { return ImmutableMultimap.of(); } RuleClass ruleClass = ((Rule) to).getRuleClassObject(); ImmutableSet<Class<?>> providers = ruleClass.getAdvertisedProviders(); return visitAspectsIfRequired((Rule) from, attribute, toStringSet(providers), dependencyFilter); } /** * Returns the attribute -&gt; set of labels that are provided by aspects of attribute. */ public static ImmutableMultimap<Attribute, Label> visitAspectsIfRequired( Rule from, Attribute attribute, Set<String> advertisedProviders, DependencyFilter dependencyFilter) { if (advertisedProviders.isEmpty()) { return ImmutableMultimap.of(); } LinkedHashMultimap<Attribute, Label> result = LinkedHashMultimap.create(); for (Aspect candidateClass : attribute.getAspects(from)) { // Check if target satisfies condition for this aspect (has to provide all required // TransitiveInfoProviders) if (!advertisedProviders.containsAll( candidateClass.getDefinition().getRequiredProviderNames())) { continue; } addAllAttributesOfAspect(from, result, candidateClass, dependencyFilter); } return ImmutableMultimap.copyOf(result); } private static ImmutableSet<String> toStringSet(ImmutableSet<Class<?>> classes) { ImmutableSet.Builder<String> classStrings = new ImmutableSet.Builder<>(); for (Class<?> clazz : classes) { classStrings.add(clazz.getName()); } return classStrings.build(); } /** * Collects all attribute labels from the specified aspectDefinition. */ public static void addAllAttributesOfAspect( Rule from, Multimap<Attribute, Label> labelBuilder, Aspect aspect, DependencyFilter dependencyFilter) { ImmutableMap<String, Attribute> attributes = aspect.getDefinition().getAttributes(); for (Attribute aspectAttribute : attributes.values()) { if (!dependencyFilter.apply(aspect, aspectAttribute)) { continue; } if (aspectAttribute.getType() == BuildType.LABEL) { Label label = from.getLabel().resolveRepositoryRelative( BuildType.LABEL.cast(aspectAttribute.getDefaultValue(from))); if (label != null) { labelBuilder.put(aspectAttribute, label); } } else if (aspectAttribute.getType() == BuildType.LABEL_LIST) { for (Label label : BuildType.LABEL_LIST.cast(aspectAttribute.getDefaultValue(from))) { labelBuilder.put(aspectAttribute, from.getLabel().resolveRepositoryRelative(label)); } } } } /** * Builder class for {@link AspectDefinition}. */ public static final class Builder { private final String name; private final Map<String, Attribute> attributes = new LinkedHashMap<>(); private final Set<Class<?>> requiredProviders = new LinkedHashSet<>(); private final Multimap<String, AspectClass> attributeAspects = LinkedHashMultimap.create(); private final ConfigurationFragmentPolicy.Builder configurationFragmentPolicy = new ConfigurationFragmentPolicy.Builder(); // TODO(mstaib): When all existing aspects properly set their configuration fragment policy, // remove this flag and the code that interacts with it. /** * True if the aspect definition has intentionally specified a configuration fragment policy by * calling any of the methods which set up the policy, and thus needs the built AspectDefinition * to retain the policy. */ private boolean hasConfigurationFragmentPolicy = false; public Builder(String name) { this.name = name; } /** * Asserts that this aspect can only be evaluated for rules that supply the specified provider. */ public Builder requireProvider(Class<?> requiredProvider) { this.requiredProviders.add(requiredProvider); return this; } /** * Declares that this aspect depends on the given aspects in {@code aspectFactories} provided * by direct dependencies through attribute {@code attribute} on the target associated with this * aspect. * * <p>Note that {@code ConfiguredAspectFactory} instances are expected in the second argument, * but we cannot reference that interface here. */ @SafeVarargs public final Builder attributeAspect( String attribute, Class<? extends NativeAspectFactory>... aspectFactories) { Preconditions.checkNotNull(attribute); for (Class<? extends NativeAspectFactory> aspectFactory : aspectFactories) { this .attributeAspect( attribute, new NativeAspectClass<>(Preconditions.checkNotNull(aspectFactory))); } return this; } /** * Declares that this aspect depends on the given {@link AspectClass} provided * by direct dependencies through attribute {@code attribute} on the target associated with this * aspect. */ public final Builder attributeAspect(String attribute, AspectClass aspectClass) { Preconditions.checkNotNull(attribute); this.attributeAspects.put(attribute, Preconditions.checkNotNull(aspectClass)); return this; } /** * Adds an attribute to the aspect. * * <p>Since aspects do not appear in BUILD files, the attribute must be either implicit * (not available in the BUILD file, starting with '$') or late-bound (determined after the * configuration is available, starting with ':') */ public <TYPE> Builder add(Attribute.Builder<TYPE> attr) { Attribute attribute = attr.build(); return add(attribute); } /** * Adds an attribute to the aspect. * * <p>Since aspects do not appear in BUILD files, the attribute must be either implicit * (not available in the BUILD file, starting with '$') or late-bound (determined after the * configuration is available, starting with ':') */ public Builder add(Attribute attribute) { Preconditions.checkArgument(attribute.isImplicit() || attribute.isLateBound()); Preconditions.checkArgument(!attributes.containsKey(attribute.getName()), "An attribute with the name '%s' already exists.", attribute.getName()); attributes.put(attribute.getName(), attribute); return this; } /** * Declares that the implementation of the associated aspect definition requires the given * fragments to be present in this rule's host and target configurations. * * <p>The value is inherited by subclasses. */ public Builder requiresConfigurationFragments(Class<?>... configurationFragments) { hasConfigurationFragmentPolicy = true; configurationFragmentPolicy .requiresConfigurationFragments(ImmutableSet.copyOf(configurationFragments)); return this; } /** * Declares that the implementation of the associated aspect definition requires the given * fragments to be present in the host configuration. * * <p>The value is inherited by subclasses. */ public Builder requiresHostConfigurationFragments(Class<?>... configurationFragments) { hasConfigurationFragmentPolicy = true; configurationFragmentPolicy .requiresHostConfigurationFragments(ImmutableSet.copyOf(configurationFragments)); return this; } /** * Declares the configuration fragments that are required by this rule for the target * configuration. * * <p>In contrast to {@link #requiresConfigurationFragments(Class...)}, this method takes the * Skylark module names of fragments instead of their classes. */ public Builder requiresConfigurationFragmentsBySkylarkModuleName( Collection<String> configurationFragmentNames) { // This method is unconditionally called from Skylark code, so only consider the user to have // specified a configuration policy if the collection actually has anything in it. // TODO(mstaib): Stop caring about this as soon as all aspects have configuration policies. hasConfigurationFragmentPolicy = hasConfigurationFragmentPolicy || !configurationFragmentNames.isEmpty(); configurationFragmentPolicy .requiresConfigurationFragmentsBySkylarkModuleName(configurationFragmentNames); return this; } /** * Declares the configuration fragments that are required by this rule for the host * configuration. * * <p>In contrast to {@link #requiresHostConfigurationFragments(Class...)}, this method takes * the Skylark module names of fragments instead of their classes. */ public Builder requiresHostConfigurationFragmentsBySkylarkModuleName( Collection<String> configurationFragmentNames) { // This method is unconditionally called from Skylark code, so only consider the user to have // specified a configuration policy if the collection actually has anything in it. // TODO(mstaib): Stop caring about this as soon as all aspects have configuration policies. hasConfigurationFragmentPolicy = hasConfigurationFragmentPolicy || !configurationFragmentNames.isEmpty(); configurationFragmentPolicy .requiresHostConfigurationFragmentsBySkylarkModuleName(configurationFragmentNames); return this; } /** * Sets the policy for the case where the configuration is missing required fragments (see * {@link #requiresConfigurationFragments}). */ public Builder setMissingFragmentPolicy(MissingFragmentPolicy missingFragmentPolicy) { hasConfigurationFragmentPolicy = true; configurationFragmentPolicy.setMissingFragmentPolicy(missingFragmentPolicy); return this; } /** * Builds the aspect definition. * * <p>The builder object is reusable afterwards. */ public AspectDefinition build() { return new AspectDefinition(name, ImmutableSet.copyOf(requiredProviders), ImmutableMap.copyOf(attributes), ImmutableSetMultimap.copyOf(attributeAspects), hasConfigurationFragmentPolicy ? configurationFragmentPolicy.build() : null); } } }
apache-2.0
gutsy/sling
tooling/ide/eclipse-ui/src/org/apache/sling/ide/eclipse/ui/nav/model/GenericJcrRootFile.java
7147
/* * 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.sling.ide.eclipse.ui.nav.model; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.io.IOUtils; import org.apache.sling.ide.eclipse.core.internal.Activator; import org.apache.sling.ide.serialization.SerializationManager; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.xml.sax.SAXException; import de.pdark.decentxml.Document; import de.pdark.decentxml.Element; import de.pdark.decentxml.XMLTokenizer.Type; /** WIP: model object for a [.content.xml] shown in the content package view in project explorer **/ public class GenericJcrRootFile extends JcrNode { final IFile file; private final Document document; public GenericJcrRootFile(JcrNode parent, final IFile file) throws ParserConfigurationException, SAXException, IOException, CoreException { if (file==null) { throw new IllegalArgumentException("file must not be null"); } this.file = file; setResource(file); if (parent==null) { throw new IllegalArgumentException("parent must not be null"); } this.parent = parent; this.domElement = null; InputStream in = file.getContents(); try { this.document = TolerantXMLParser.parse(in, file.getFullPath().toOSString()); handleJcrRoot(this.document.getRootElement()); } finally { IOUtils.closeQuietly(in); } } @Override public int hashCode() { return file.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof GenericJcrRootFile) { GenericJcrRootFile other = (GenericJcrRootFile) obj; return file.equals(other.file); } return false; } private void handleJcrRoot(Element element) { List<Element> children = element.getChildren(); final JcrNode effectiveParent; if (isRootContentXml()) { if (parent instanceof DirNode) { DirNode dirNodeParent = (DirNode)parent; JcrNode effectiveSibling = dirNodeParent.getEffectiveSibling(); if (effectiveSibling!=null) { effectiveSibling.dirSibling = dirNodeParent; handleProperties(element, effectiveSibling.properties); } else { handleProperties(element, parent.properties); } effectiveParent = parent; } else { handleProperties(element, parent.properties); effectiveParent = parent; } } else { handleProperties(element, properties); effectiveParent = this; parent.addChild(this); } for (Iterator<Element> it = children.iterator(); it.hasNext();) { Element aChild = it.next(); handleChild(effectiveParent, aChild); } } private boolean isRootContentXml() { return file.getName().equals(".content.xml"); } private void handleProperties(Element domNode, ModifiableProperties properties) { properties.setNode(this, domNode); // NamedNodeMap attributes = domNode.getAttributes(); // for(int i=0; i<attributes.getLength(); i++) { // Node attr = attributes.item(i); // properties.add(attr.getNodeName(), attr.getNodeValue()); // } } @Override public String getLabel() { if (isRootContentXml()) { return "SHOULD NOT OCCUR"; } else { // de-escape the file name String label = file.getName(); // 1. remove the trailing .xml if (label.endsWith(".xml")) { label = label.substring(0, label.length()-4); } // 2. de-escape stuff like '_cq_' to 'cq:' if (label.startsWith("_")) { label = label.substring(1); int first = label.indexOf("_"); if (first!=-1) { label = label.substring(0, first) + ":" + label.substring(first+1); } } return label; } } private void handleChild(JcrNode parent, Element domNode) { if (domNode.getType() == Type.TEXT) { // ignore return; } JcrNode childJcrNode = new JcrNode(parent, domNode, this, null); handleProperties(domNode, childJcrNode.properties); List<Element> children = domNode.getChildren(); for (Iterator<Element> it = children.iterator(); it.hasNext();) { Element element = it.next(); handleChild(childJcrNode, element); } } public void pickResources(List<IResource> membersList) { final SerializationManager serializationManager = Activator.getDefault().getSerializationManager(); for (Iterator<IResource> it = membersList.iterator(); it.hasNext();) { final IResource resource = it.next(); final String resName = resource.getName(); Iterator<JcrNode> it2; if (isRootContentXml()) { it2 = parent.children.iterator(); } else { it2 = children.iterator(); } while(it2.hasNext()) { JcrNode aChild = it2.next(); if (resName.equals(serializationManager.getOsPath(aChild.getName()))) { // then pick this one it.remove(); aChild.setResource(resource); break; } } } } @Override public IFile getFileForEditor() { return file; } @Override void createDomChild(String childNodeName, String childNodeType) { createChild(childNodeName, childNodeType, document.getRootElement(), underlying); } public void save() { try { String xml = document.toXML(); file.setContents(new ByteArrayInputStream(xml.getBytes()), true, true, new NullProgressMonitor()); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } SyncDirManager.syncDirChanged(getSyncDir()); } @Override public boolean canBeRenamed() { return true; } @Override public boolean canBeDeleted() { return true; } @Override public void rename(String string) { try { file.move(file.getParent().getFullPath().append(string+".xml"), true, new NullProgressMonitor()); } catch (CoreException e) { Activator.getDefault().getPluginLogger().error("Error renaming resource ("+file+"): "+e, e); } } @Override public void delete() { try { file.delete(true, new NullProgressMonitor()); } catch (CoreException e) { Activator.getDefault().getPluginLogger().error("Error deleting resource ("+file+"): "+e, e); } } }
apache-2.0
cisasoft/docsearch
src/main/java/org/jab/docsearch/gui/NewIndexDialog.java
19211
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the * Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.jab.docsearch.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.border.TitledBorder; import org.jab.docsearch.DocSearch; import org.jab.docsearch.FileEnvironment; import org.jab.docsearch.utils.FileUtils; import org.jab.docsearch.utils.I18n; import org.jab.docsearch.utils.Messages; import org.jab.docsearch.utils.Utils; /** * Class NewIndexDialog * * @version $Id: NewIndexDialog.java 171 2012-09-07 20:08:01Z henschel $ */ public final class NewIndexDialog extends JDialog implements ActionListener { /** * FileEnvironment */ private final static FileEnvironment fEnv = FileEnvironment.getInstance(); private final static String IS_CD_IDX = Messages.getString("DocSearch.isCdIdx"); private final static String TYPE_OF_IDX = Messages.getString("DocSearch.typeOfNewIdx"); private final static String IS_WEB_IDX = Messages.getString("DocSearch.lblWSIdxg"); private final static String IS_LOCAL = Messages.getString("DocSearch.localIdx"); private final static String BROWSEFLDRS = Messages.getString("DocSearch.btnBrowseFolders"); private final static String SELECT = Messages.getString("DocSearch.btnSelect"); private final static String SELFOLD = Messages.getString("DocSearch.btnSelFold"); private final static String SELFLDREP = Messages.getString("DocSearch.btnSelLocalFold"); private final static String MAD = Messages.getString("DocSearch.errIdxMsgDesc"); private final static String MII = Messages.getString("DocSearch.msgMI"); private final static String MISL = Messages.getString("DocSearch.errMissStLoc"); private final static String MISWR = Messages.getString("DocSearch.errwsUrlRep"); private final static String MISRQ = Messages.getString("DocSearch.errRepPtrnWb"); private final static String MISRPMF = Messages.getString("DocSearch.errMsgPmF"); private final static String MISSEP = Messages.getString("DocSearch.errMsgSep"); private final static String[] updateChoices = { Messages.getString("DocSearch.optWhenISaySo"), Messages.getString("DocSearch.optDuringStartup"), Messages.getString("DocSearch.optIdxGtOne"), Messages.getString("DocSearch.optIdxGtFive"), Messages.getString("DocSearch.optIdxGtThiry"), Messages.getString("DocSearch.optIdxGtSixty"), Messages.getString("DocSearch.optIdxGtNintey"), Messages.getString("DocSearch.optIdxGtOneEighty"), Messages.getString("DocSearch.optIdxGtYr") }; private final static String pathSep = FileUtils.PATH_SEPARATOR; private final JPanel[] panels; private final JButton okButton; private final JButton cancelButton; private boolean returnBool = false; // start in private final JLabel startLabel = new JLabel(Messages.getString("DocSearch.lblStrtInFldr")); private final JLabel nameLabel = new JLabel(I18n.getString("index_name") + ":"); private final JLabel typeOfIdxLbl = new JLabel(TYPE_OF_IDX); private final JTextField nameField = new JTextField(25); private final JTextField startField = new JTextField(25); private final JButton startInButton = new JButton(SELFOLD); // search depth private final JLabel searchDepthLabel = new JLabel(Messages.getString("DocSearch.lblNumSbFldrs")); private final RadioListener rl = new RadioListener(); private final JComboBox sdChoice = new JComboBox(); private final int numPanels = 6; private final JCheckBox searchByDefault = new JCheckBox(Messages.getString("DocSearch.lblSrchdByDflt")); // RADIO BUTTONS FOR TYPE OF INDEX private final ButtonGroup idxTypeGroup = new ButtonGroup(); private final JRadioButton isWeb = new JRadioButton(IS_WEB_IDX); private final JRadioButton isCd = new JRadioButton(IS_CD_IDX); private final JRadioButton isLocal = new JRadioButton(IS_LOCAL); private final JPanel typeOfIdx = new JPanel(); private final JTextField replaceField = new JTextField(25); private final JButton selectFold = new JButton(SELFLDREP); private final JLabel replaceLabel = new JLabel(Messages.getString("DocSearch.lblMtchPtrnFld")); private final JLabel matchLabel = new JLabel(Messages.getString("DocSearch.lblReplPtrnFld")); private final JTextField matchField = new JTextField(45); private final DocSearch monitor; private final Font f = new Font("Times", Font.BOLD, 16); private final JLabel dirLabel = new JLabel(Messages.getString("DocSearch.lblSrchDpth")); private final JPanel webPanel = new JPanel(); private final JPanel indexFreqPanel = new JPanel(); private final JComboBox indexFreq = new JComboBox(updateChoices); private final JLabel freqLabel = new JLabel(Messages.getString("DocSearch.lblWhenUpdate")); private final JTabbedPane tabbedPane; private final JPanel archivePanel; private final JPanel archiveContentsPanel; private final JLabel archiveTitle = new JLabel(Messages.getString("DocSearch.lblArchTitle")); private final JLabel archiveTitle2 = new JLabel(Messages.getString("DocSearch.lblZipArchUse")); private final JLabel archiveLabel = new JLabel(Messages.getString("DocSearch.lblArchTo")); private final JTextField archiveField = new JTextField(33); private final JButton archiveBrowseButton = new JButton(BROWSEFLDRS); public NewIndexDialog(DocSearch monitor, String title, boolean modal) { super(monitor, title, modal); // super(parent, "Generate Meta Tag Table", true); this.monitor = monitor; tabbedPane = new JTabbedPane(); // archiveField.setText(fEnv.getArchiveDirectory()); // accessibility info searchByDefault.setSelected(true); sdChoice.setToolTipText(Messages.getString("DocSearch.tipDepth")); startField.setToolTipText(Messages.getString("DocSearch.tdFlFld")); searchByDefault.setToolTipText(Messages.getString("DocSearch.tipCBD")); // okButton = new JButton(I18n.getString("button.create_new")); okButton.setActionCommand("ac_create"); okButton.setMnemonic(I18n.getMnemonic("button.create_new.mnemonic")); // cancelButton = new JButton(I18n.getString("button.cancel")); cancelButton.setActionCommand("ac_cancel"); cancelButton.setMnemonic(I18n.getMnemonic("button.cancel.mnemonic")); // selectFold.setMnemonic(KeyEvent.VK_S); selectFold.setToolTipText(SELFLDREP); selectFold.addActionListener(this); selectFold.setEnabled(false); // dirLabel.setFont(f); // typeOfIdx.add(typeOfIdxLbl); typeOfIdx.add(isLocal); typeOfIdx.add(isWeb); typeOfIdx.add(isCd); // isLocal.setActionCommand(IS_LOCAL); isWeb.setActionCommand(IS_WEB_IDX); isCd.setActionCommand(IS_CD_IDX); isLocal.addActionListener(rl); isWeb.addActionListener(rl); isCd.addActionListener(rl); idxTypeGroup.add(isLocal); idxTypeGroup.add(isWeb); idxTypeGroup.add(isCd); // for (int i = 0; i <= 20; i++) sdChoice.addItem(i + ""); okButton.addActionListener(this); cancelButton.addActionListener(this); startInButton.addActionListener(this); archiveBrowseButton.addActionListener(this); panels = new JPanel[numPanels]; for (int i = 0; i < numPanels; i++) panels[i] = new JPanel(); // JPanel nWebPanel = new JPanel(); JPanel cWebPanel = new JPanel(); JPanel sWebPanel = new JPanel(); // archivePanel = new JPanel(); archiveContentsPanel = new JPanel(); archiveContentsPanel.add(archiveLabel); archiveContentsPanel.add(archiveField); archiveContentsPanel.add(archiveBrowseButton); archivePanel.setLayout(new BorderLayout()); archivePanel.setBorder(new TitledBorder(Messages.getString("DocSearch.optsFrArch"))); archivePanel.add(archiveTitle, BorderLayout.NORTH); archivePanel.add(archiveTitle2, BorderLayout.CENTER); archivePanel.add(archiveContentsPanel, BorderLayout.SOUTH); // nWebPanel.add(typeOfIdx); cWebPanel.add(matchLabel); cWebPanel.add(matchField); sWebPanel.add(replaceLabel); sWebPanel.add(replaceField); sWebPanel.add(selectFold); // // panels[1].add(startLabel); panels[1].add(startField); panels[1].add(startInButton); panels[2].add(searchDepthLabel); panels[2].add(sdChoice); panels[3].add(searchByDefault); // JPanel optsPane = new JPanel(); optsPane.setLayout(new BorderLayout()); optsPane.setBorder(new TitledBorder(Messages.getString("DocSearch.optsFrLclArch"))); optsPane.add(panels[1], BorderLayout.NORTH); optsPane.add(panels[2], BorderLayout.CENTER); optsPane.add(panels[3], BorderLayout.SOUTH); webPanel.setLayout(new BorderLayout()); webPanel.add(nWebPanel, BorderLayout.NORTH); webPanel.add(cWebPanel, BorderLayout.CENTER); webPanel.add(sWebPanel, BorderLayout.SOUTH); // indexFreqPanel.setLayout(new BorderLayout()); indexFreqPanel.setBorder(new TitledBorder(Messages.getString("DocSearch.optsIdxUpdts"))); JPanel freqP = new JPanel(); JLabel notice = new JLabel(Messages.getString("DocSearch.lblUpdLtr")); JLabel noLabel = new JLabel(Messages.getString("DocSearch.lblUpdRsn")); freqP.add(freqLabel); freqP.add(indexFreq); indexFreqPanel.add(noLabel, BorderLayout.NORTH); indexFreqPanel.add(freqP, BorderLayout.CENTER); indexFreqPanel.add(notice, BorderLayout.SOUTH); // webPanel.setBorder(new TitledBorder(Messages.getString("DocSearch.lblwsip"))); tabbedPane.addTab(Messages.getString("DocSearch.lblgnrlopts"), null, optsPane, Messages.getString("DocSearch.tipgnrlopts")); tabbedPane.addTab(Messages.getString("DocSearch.lbladvopts"), null, webPanel, Messages.getString("DocSearch.lbladvrsn")); tabbedPane.addTab(Messages.getString("DocSearch.lbludt"), null, indexFreqPanel, Messages.getString("DocSearch.lbludtrsn")); // archivePanel tabbedPane.addTab(Messages.getString("DocSearch.lblarctb"), null, archivePanel, Messages.getString("DocSearch.lblarchtrsn")); panels[0].add(nameLabel); panels[0].add(nameField); panels[4].add(tabbedPane); panels[5].add(okButton); panels[5].add(cancelButton); panels[2].setBackground(Color.orange); panels[1].setBackground(Color.orange); panels[3].setBackground(Color.orange); searchByDefault.setBackground(Color.orange); // now for the gridbag getContentPane().setLayout(new GridLayout(1, numPanels)); GridBagLayout gridbaglayout = new GridBagLayout(); GridBagConstraints gridbagconstraints = new GridBagConstraints(); getContentPane().setLayout(gridbaglayout); int curP = 0; for (int i = 0; i < numPanels; i++) { // if ((i == 0) || (i >= 4)) { gridbagconstraints.fill = 1; gridbagconstraints.insets = new Insets(1, 1, 1, 1); gridbagconstraints.gridx = 0; gridbagconstraints.gridy = curP; gridbagconstraints.gridwidth = 1; gridbagconstraints.gridheight = 1; gridbagconstraints.weightx = 0.0D; gridbagconstraints.weighty = 0.0D; gridbaglayout.setConstraints(panels[i], gridbagconstraints); getContentPane().add(panels[i]); curP++; } } } public void init() { pack(); // center this dialog Rectangle frameSize = getBounds(); Dimension screenD = Toolkit.getDefaultToolkit().getScreenSize(); int screenWidth = screenD.width; int screenHeight = screenD.height; int newX = 0; int newY = 0; if (screenWidth > frameSize.width) { newX = (screenWidth - frameSize.width) / 2; } if (screenHeight > frameSize.height) { newY = (screenHeight - frameSize.height) / 2; } if ((newX != 0) || (newY != 0)) { setLocation(newX, newY); } isLocal.setSelected(true); // end of centering the dialog } @Override public void actionPerformed(ActionEvent actionevent) { String s = actionevent.getActionCommand(); if (s.equals("ac_create")) { StringBuffer errBuf = new StringBuffer(); boolean hasErr = false; if (nameField.getText().trim().equals("")) { hasErr = true; errBuf.append(MAD); errBuf.append("\n\n"); } if (startField.getText().trim().equals("")) { hasErr = true; errBuf.append(MISL); errBuf.append("\n\n"); } if (isWeb.isSelected()) { if ((matchField.getText().equals("")) || (matchField.getText().equals("http://"))) { hasErr = true; errBuf.append(MISWR); errBuf.append("\n\n"); } else if (!matchField.getText().endsWith("/")) { hasErr = true; errBuf.append(MISRQ); errBuf.append("\n\n"); } if (replaceField.getText().equals("")) { hasErr = true; errBuf.append(MISRPMF); errBuf.append("\n\n"); } else if (!replaceField.getText().endsWith(pathSep)) { hasErr = true; errBuf.append(MISSEP + pathSep + ")\n\n"); } } // end for isWeb if (hasErr) { monitor.showMessage(MII, errBuf.toString()); } else { returnBool = true; this.setVisible(false); } } else if (s.equals(SELFLDREP)) { JFileChooser fdo = new JFileChooser(); fdo.setCurrentDirectory(new File(fEnv.getUserHome())); fdo.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int fileGotten = fdo.showDialog(this, SELECT); if (fileGotten == JFileChooser.APPROVE_OPTION) { File file = fdo.getCurrentDirectory(); replaceField.setText(file.toString()); } } else if (s.equals("ac_cancel")) { returnBool = false; this.setVisible(false); } else if (s.equals(SELFOLD)) { JFileChooser fdo = new JFileChooser(); fdo.setCurrentDirectory(new File(fEnv.getUserHome())); fdo.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int fileGotten = fdo.showDialog(this, SELECT); if (fileGotten == JFileChooser.APPROVE_OPTION) { File file = fdo.getSelectedFile(); startField.setText(file.toString()); } } else if (s.equals(BROWSEFLDRS)) { JFileChooser fdo = new JFileChooser(); fdo.setCurrentDirectory(new File(fEnv.getUserHome())); fdo.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int fileGotten = fdo.showDialog(this, SELECT); if (fileGotten == JFileChooser.APPROVE_OPTION) { File file = fdo.getSelectedFile(); archiveField.setText(file.toString()); } } } class RadioListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String CMD = e.getActionCommand(); if (CMD.equals(IS_WEB_IDX)) { replaceField.setEnabled(true); matchField.setEnabled(true); replaceField.setText(startField.getText()); matchField.setText("http://"); selectFold.setEnabled(true); } else if (CMD.equals(IS_CD_IDX)) { replaceField.setEnabled(true); matchField.setEnabled(true); replaceField.setText(Utils.getFolderOnly(startField.getText())); matchField.setText("[cdrom]"); selectFold.setEnabled(true); } else if (CMD.equals(IS_LOCAL)) { replaceField.setEnabled(false); matchField.setEnabled(false); replaceField.setText("na"); matchField.setText("na"); selectFold.setEnabled(false); } } // end of action } // end for radio listener public boolean getConfirmed() { return returnBool; } public String getNameFieldText() { return nameField.getText(); } public String replaceFieldText() { return replaceField.getText(); } public String matchFieldText() { return matchField.getText(); } public String startFieldText() { return startField.getText(); } public String archiveFieldText() { return archiveField.getText(); } public boolean isWebSelected() { return isWeb.isSelected(); } public boolean isCDSelected() { return isCd.isSelected(); } public boolean sbdSelected() { return searchByDefault.isSelected(); } public int getPolicy() { return indexFreq.getSelectedIndex(); } public int getSDChoice() { return sdChoice.getSelectedIndex(); } }
apache-2.0
wseemann/ServeStream
app/src/main/java/net/sourceforge/servestream/media/MetadataRetrieverTask.java
6068
/* * ServeStream: A HTTP stream browser/player for Android * Copyright 2013 William Seemann * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sourceforge.servestream.media; import java.util.HashMap; import net.sourceforge.servestream.provider.Media; import net.sourceforge.servestream.preference.PreferenceConstants; import wseemann.media.FFmpegMediaMetadataRetriever; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.util.Log; import android.util.SparseArray; import wseemann.media.FFmpegMediaMetadataRetriever; public class MetadataRetrieverTask implements Runnable { private static final String TAG = MetadataRetrieverTask.class.getName(); private boolean mIsCancelled; private AsyncTask.Status mStatus; private Context mContext = null; private long [] mList; private MetadataRetrieverListener mListener; public MetadataRetrieverTask(Context context, long [] list) { mIsCancelled = false; mStatus = AsyncTask.Status.PENDING; mContext = context; mList = list; // Verify that the host activity implements the callback interface try { // Instantiate the MetadataRetrieverListener so we can send events to the host mListener = (MetadataRetrieverListener) context; } catch (ClassCastException e) { // The activity doesn't implement the interface, throw exception throw new ClassCastException(context.toString() + " must implement MetadataRetrieverListener"); } } @Override public void run() { mStatus = AsyncTask.Status.RUNNING; try { Thread.sleep(3000); } catch (InterruptedException e) { } FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever(); SparseArray<String> uris = getUris(mContext, mList); for (int i = 0; i < mList.length; i++) { if (isCancelled()) { break; } String uri = uris.get((int) mList[i]); if (uri != null) { try { mmr.setDataSource(uri.toString()); Metadata metadata; if ((metadata = getMetadata(mContext, mList[i], mmr)) != null) { if (mListener != null) { mListener.onMetadataParsed(mList[i], metadata); } } try { Thread.sleep(1000); } catch (InterruptedException e) { } } catch(IllegalArgumentException ex) { Log.e(TAG, "Metadata for track could not be retrieved"); } } } mmr.release(); mStatus = AsyncTask.Status.FINISHED; } private SparseArray<String> getUris(Context context, long [] list) { SparseArray<String> uris = new SparseArray<String>(); StringBuffer selection = new StringBuffer(Media.MediaColumns._ID + " IN ("); int id = -1; String uri = null; for (int i = 0; i < list.length; i++) { if (i == 0) { selection.append(list[i]); } else { selection.append("," + list[i]); } } selection.append(")"); // Form an array specifying which columns to return. String [] projection = new String [] { Media.MediaColumns._ID, Media.MediaColumns.URI }; // Get the base URI for the Media Files table in the Media content provider. Uri mediaFile = Media.MediaColumns.CONTENT_URI; // Make the query. Cursor cursor = context.getContentResolver().query(mediaFile, projection, selection.toString(), null, null); while (cursor.moveToNext()) { id = cursor.getInt(cursor.getColumnIndex(Media.MediaColumns._ID)); uri = cursor.getString(cursor.getColumnIndex(Media.MediaColumns.URI)); uris.put(id, uri); } cursor.close(); return uris; } private Metadata getMetadata(Context context, long id, FFmpegMediaMetadataRetriever mmr) { byte [] artwork = null; String title = mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_TITLE); String album = mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ALBUM); String artist = mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ARTIST); String duration = mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_DURATION); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); // only attempt to retrieve album art if the user has enabled that option if (preferences.getBoolean(PreferenceConstants.RETRIEVE_ALBUM_ART, false)) { artwork = mmr.getEmbeddedPicture(); } // if we didn't obtain at least the title, album or artist then don't store // the metadata since it's pretty useless if (title == null && album == null && artist == null) { return null; } HashMap<String, Object> meta = new HashMap<String, Object>(); meta.put(Metadata.METADATA_KEY_TITLE, title); meta.put(Metadata.METADATA_KEY_ALBUM, album); meta.put(Metadata.METADATA_KEY_ARTIST, artist); meta.put(Metadata.METADATA_KEY_DURATION, duration); meta.put(Metadata.METADATA_KEY_ARTWORK, artwork); // Form an array specifying which columns to return. Metadata metadata = new Metadata(); metadata.parse(meta); return metadata; } private synchronized boolean isCancelled() { return mIsCancelled; } public synchronized boolean cancel() { if (mStatus != AsyncTask.Status.FINISHED) { mIsCancelled = true; return true; } return false; } public synchronized AsyncTask.Status getStatus() { return mStatus; } public void execute() { new Thread(this, "").start(); } }
apache-2.0
mariusj/org.openntf.domino
domino/core/src/main/java/org/openntf/domino/design/FileResourceHidden.java
753
/* * Copyright 2013 * * 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.openntf.domino.design; /** * @author Roland Praml * */ public interface FileResourceHidden extends AnyFileResource { }
apache-2.0
MartinLoeper/KAMP-DSL
edu.kit.ipd.sdq.kamp.ruledsl.ui/src/edu/kit/ipd/sdq/kamp/ruledsl/ui/DslJavaSourceBuilder.java
3754
package edu.kit.ipd.sdq.kamp.ruledsl.ui; import java.util.Map; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; import org.osgi.framework.BundleException; import org.osgi.framework.FrameworkUtil; import edu.kit.ipd.sdq.kamp.ruledsl.generator.KampRuleLanguageGenerator; import edu.kit.ipd.sdq.kamp.ruledsl.generator.KarlJobBase; import edu.kit.ipd.sdq.kamp.ruledsl.support.KampRuleLanguageFacade; import edu.kit.ipd.sdq.kamp.ruledsl.support.KampRuleLanguageUtil; import edu.kit.ipd.sdq.kamp.ruledsl.util.ErrorHandlingUtil; public class DslJavaSourceBuilder extends IncrementalProjectBuilder { public static final String BUILDER_ID = "edu.kit.ipd.sdq.kamp.ruledsl.ui.sourceBuilder"; @Override protected IProject[] build(final int kind, final Map<String, String> args, final IProgressMonitor monitor) throws CoreException { if(KarlJobBase.isKarlJobRunning()) { return new IProject[] { getProject() }; } SubMonitor subMonitor = SubMonitor.convert(monitor, "Build and register project", 10); System.out.println("A file was saved. Trigger the custom builder."); if (kind == IncrementalProjectBuilder.AUTO_BUILD || kind == IncrementalProjectBuilder.INCREMENTAL_BUILD) { IResourceDelta delta = getDelta(getProject()); if(delta != null) { IResourceDelta[] projDeltas = delta.getAffectedChildren( IResourceDelta.CHANGED| IResourceDelta.ADDED| IResourceDelta.REMOVED ); for (int i = 0; i < projDeltas.length; ++i) { IResource resource = projDeltas[i].getResource(); if(resource.getName().equals("src")) { String projectName = getProject().getName(); try { KampRuleLanguageFacade.buildProjectAndReInstall(projectName.substring(0, projectName.length() - 6), subMonitor.split(10)); } catch (OperationCanceledException | BundleException e) { PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { @Override public void run() { Shell shell = PlatformUI.getWorkbench().getDisplay().getActiveShell(); ErrorDialog.openError(shell, "Error", "The bundle could not be successfully created and injected.", ErrorHandlingUtil.createMultiStatus(FrameworkUtil.getBundle(KampRuleLanguageUtil.class).getSymbolicName(), e.getLocalizedMessage(), e)); Throwable t = ((BundleException) e).getNestedException(); if(t != null) { t.printStackTrace(); } } }); } } else if(resource.getName().equals("gen")) { // we have to check if the build was triggered by a user change... how to do that? // PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { // // @Override // public void run() { // MessageBox dialog = new MessageBox(PlatformUI.getWorkbench().getDisplay().getActiveShell(), SWT.ICON_WARNING | SWT.OK); // dialog.setText("Warning"); // dialog.setMessage("Making changes to the gen package is strongly discouraged."); // // dialog.open(); // } // }); } } } } return new IProject[] { getProject() }; } }
apache-2.0
adaptris/interlok
interlok-core/src/test/java/com/adaptris/core/transform/schema/ViolationHandlerTest.java
3792
package com.adaptris.core.transform.schema; import static com.adaptris.core.transform.schema.CollectingErrorHandlerTest.createException; import static com.adaptris.core.transform.schema.ViolationHandlerImpl.DEFAULT_KEY; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.xml.sax.SAXParseException; import com.adaptris.core.AdaptrisMessage; import com.adaptris.core.AdaptrisMessageFactory; import com.adaptris.core.ServiceException; import com.adaptris.core.XStreamMarshaller; public class ViolationHandlerTest { @Test public void testAsMetadata() throws Exception { ViolationsAsMetadata handler = new ViolationsAsMetadata().withMetadataKey(DEFAULT_KEY); List<SAXParseException> exceptions = Arrays.asList(createException("first"), createException("second")); AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage(); handler.handle(exceptions, msg); assertTrue(msg.headersContainsKey(DEFAULT_KEY)); SchemaViolations v = (SchemaViolations) new XStreamMarshaller().unmarshal(msg.getMetadataValue(DEFAULT_KEY)); assertEquals(2, v.getViolations().size()); } @Test(expected=ServiceException.class) public void testAsMetadata_WithException() throws Exception { ViolationsAsMetadata handler = new ViolationsAsMetadata().withMetadataKey(DEFAULT_KEY); List<SAXParseException> exceptions = Arrays.asList(createException("first"), createException("second")); AdaptrisMessage msg = mock(AdaptrisMessage.class); doThrow(new RuntimeException()).when(msg).addMessageHeader(anyString(), anyString()); doThrow(new RuntimeException()).when(msg).addMetadata(anyString(), anyString()); doThrow(new RuntimeException()).when(msg).addMetadata(any()); handler.handle(exceptions, msg); } @Test public void testAsObjectMetadata() throws Exception { ViolationsAsObjectMetadata handler = new ViolationsAsObjectMetadata().withObjectMetadataKey(DEFAULT_KEY); List<SAXParseException> exceptions = Arrays.asList(createException("first"), createException("second")); AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage(); handler.handle(exceptions, msg); assertTrue(msg.getObjectHeaders().containsKey(DEFAULT_KEY)); SchemaViolations v = (SchemaViolations) msg.getObjectHeaders().get(DEFAULT_KEY); assertEquals(2, v.getViolations().size()); } @Test public void testAsPayload() throws Exception { OverwritePayload handler = new OverwritePayload(); List<SAXParseException> exceptions = Arrays.asList(createException("first"), createException("second")); AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage(); handler.handle(exceptions, msg); assertFalse(msg.headersContainsKey(DEFAULT_KEY)); SchemaViolations v = (SchemaViolations) new XStreamMarshaller().unmarshal(msg.getContent()); assertEquals(2, v.getViolations().size()); } @Test(expected=ServiceException.class) public void testAsPayload_WithException() throws Exception { OverwritePayload handler = new OverwritePayload(); List<SAXParseException> exceptions = Arrays.asList(createException("first"), createException("second")); AdaptrisMessage msg = mock(AdaptrisMessage.class); doThrow(new RuntimeException()).when(msg).setContent(anyString(), anyString()); handler.handle(exceptions, msg); } }
apache-2.0
nes1983/tree-regex
src/ch/unibe/scg/regex/InputRange.java
3571
package ch.unibe.scg.regex; /** * {@link InputRange} represent a range of {@link Character} which can be used in * {@link TransitionTable} of TDFA. * * @author Fabien Dubosson */ abstract class InputRange implements Comparable<InputRange> { private static class Any extends RealInputRange { Any() { // Everything. super(Character.MIN_VALUE, Character.MAX_VALUE); } @Override public String toString() { return "ANY"; } } private static class Eos extends RealInputRange { Eos() { // Nothing. super((char) (Character.MIN_VALUE + 1), Character.MIN_VALUE); } @Override public String toString() { return "$"; } } static class SpecialInputRange extends RealInputRange { private SpecialInputRange(char from, char to) { super(from, to); } } public static final InputRange ANY = new Any(); public static final InputRange EOS = new Eos(); public static InputRange make(final char character) { return make(character, character); } public static InputRange make(final char from, final char to) { return new RealInputRange(from, to); } static class RealInputRange extends InputRange { /** * First {@link Character} of the range */ private final char from; /** * Last {@link Character} or the range */ private final char to; /** * Constructor which take the first and last character as parameter * * @param from The first {@link Character} of the range * @param to The last {@link Character} of the range */ RealInputRange(final char from, final char to) { this.from = from; this.to = to; } @Override public boolean contains(final char character) { return (from <= character && character <= to); } @Override public String toString() { String printedFrom = Character.toString(from); if (!Character.isLetterOrDigit(from)) { printedFrom = String.format("0x%x", (int) from); } String printedTo = Character.toString(to); if (!Character.isLetterOrDigit(to)) { printedTo = String.format("0x%x", (int) to); } return String.format("%s-%s", printedFrom, printedTo); } @Override public char getFrom() { return from; } @Override public char getTo() { return to; } } @Override public int compareTo(InputRange o) { int cmp = Character.compare(getFrom(), o.getFrom()); if (cmp != 0) { return cmp; } return Character.compare(getTo(), o.getTo()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof InputRange)) { return false; } InputRange that = (InputRange) o; return this.getFrom() == that.getFrom() && this.getTo() == that.getTo(); } /** * Tell if the {@link InputRange} contains a {@link Character} within its range * * @param character A specific {@link Character}. * @return if the {@link Character} is contained within the {@link InputRange}. */ public abstract boolean contains(final char character); /** * Return the first {@link Character} of the range * * @return the first {@link Character} of the range */ public abstract char getFrom(); /** * Return the last {@link Character} of the range * * @return the last {@link Character} of the range */ public abstract char getTo(); @Override public int hashCode() { return (getFrom() * 31) ^ getTo(); } }
apache-2.0
grails/gorm-hibernate5
grails-datastore-gorm-hibernate5/src/main/groovy/org/grails/orm/hibernate/HibernateSession.java
10004
/* Copyright (C) 2011 SpringSource * * 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.grails.orm.hibernate; import java.io.Serializable; import java.sql.SQLException; import java.util.Collections; import java.util.List; import java.util.Map; import javax.persistence.FlushModeType; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.grails.datastore.gorm.timestamp.DefaultTimestampProvider; import org.grails.datastore.mapping.model.PersistentProperty; import org.grails.datastore.mapping.model.config.GormProperties; import org.grails.datastore.mapping.proxy.ProxyHandler; import org.grails.datastore.mapping.query.event.PostQueryEvent; import org.grails.datastore.mapping.query.event.PreQueryEvent; import org.grails.orm.hibernate.proxy.HibernateProxyHandler; import org.grails.orm.hibernate.query.HibernateHqlQuery; import org.grails.orm.hibernate.query.HibernateQuery; import org.grails.datastore.mapping.model.PersistentEntity; import org.grails.datastore.mapping.query.Query; import org.grails.datastore.mapping.query.api.QueryableCriteria; import org.grails.datastore.mapping.query.jpa.JpaQueryBuilder; import org.grails.datastore.mapping.query.jpa.JpaQueryInfo; import org.grails.datastore.mapping.reflect.ClassPropertyFetcher; import org.hibernate.*; import org.hibernate.criterion.Restrictions; import org.hibernate.proxy.HibernateProxy; import org.springframework.context.ApplicationEventPublisher; /** * Session implementation that wraps a Hibernate {@link org.hibernate.Session}. * * @author Graeme Rocher * @since 1.0 */ @SuppressWarnings("rawtypes") public class HibernateSession extends AbstractHibernateSession { ProxyHandler proxyHandler = new HibernateProxyHandler(); DefaultTimestampProvider timestampProvider; public HibernateSession(HibernateDatastore hibernateDatastore, SessionFactory sessionFactory, int defaultFlushMode) { super(hibernateDatastore, sessionFactory); hibernateTemplate = new GrailsHibernateTemplate(sessionFactory, (HibernateDatastore) getDatastore()); } public HibernateSession(HibernateDatastore hibernateDatastore, SessionFactory sessionFactory) { this(hibernateDatastore, sessionFactory, hibernateDatastore.getDefaultFlushMode()); } @Override public Serializable getObjectIdentifier(Object instance) { if(instance == null) return null; if(proxyHandler.isProxy(instance)) { return ((HibernateProxy)instance).getHibernateLazyInitializer().getIdentifier(); } Class<?> type = instance.getClass(); ClassPropertyFetcher cpf = ClassPropertyFetcher.forClass(type); final PersistentEntity persistentEntity = getMappingContext().getPersistentEntity(type.getName()); if(persistentEntity != null) { return (Serializable) cpf.getPropertyValue(instance, persistentEntity.getIdentity().getName()); } return null; } /** * Deletes all objects matching the given criteria. * * @param criteria The criteria * @return The total number of records deleted */ public long deleteAll(final QueryableCriteria criteria) { return getHibernateTemplate().execute((GrailsHibernateTemplate.HibernateCallback<Integer>) session -> { JpaQueryBuilder builder = new JpaQueryBuilder(criteria); builder.setConversionService(getMappingContext().getConversionService()); builder.setHibernateCompatible(true); JpaQueryInfo jpaQueryInfo = builder.buildDelete(); org.hibernate.query.Query query = session.createQuery(jpaQueryInfo.getQuery()); getHibernateTemplate().applySettings(query); List parameters = jpaQueryInfo.getParameters(); if (parameters != null) { for (int i = 0, count = parameters.size(); i < count; i++) { query.setParameter(JpaQueryBuilder.PARAMETER_NAME_PREFIX + (i+1), parameters.get(i)); } } HibernateHqlQuery hqlQuery = new HibernateHqlQuery(HibernateSession.this, criteria.getPersistentEntity(), query); ApplicationEventPublisher applicationEventPublisher = datastore.getApplicationEventPublisher(); applicationEventPublisher.publishEvent(new PreQueryEvent(datastore, hqlQuery)); int result = query.executeUpdate(); applicationEventPublisher.publishEvent(new PostQueryEvent(datastore, hqlQuery, Collections.singletonList(result))); return result; }); } /** * Updates all objects matching the given criteria and property values. * * @param criteria The criteria * @param properties The properties * @return The total number of records updated */ public long updateAll(final QueryableCriteria criteria, final Map<String, Object> properties) { return getHibernateTemplate().execute((GrailsHibernateTemplate.HibernateCallback<Integer>) session -> { JpaQueryBuilder builder = new JpaQueryBuilder(criteria); builder.setConversionService(getMappingContext().getConversionService()); builder.setHibernateCompatible(true); PersistentEntity targetEntity = criteria.getPersistentEntity(); PersistentProperty lastUpdated = targetEntity.getPropertyByName(GormProperties.LAST_UPDATED); if(lastUpdated != null && targetEntity.getMapping().getMappedForm().isAutoTimestamp()) { if (timestampProvider == null) { timestampProvider = new DefaultTimestampProvider(); } properties.put(GormProperties.LAST_UPDATED, timestampProvider.createTimestamp(lastUpdated.getType())); } JpaQueryInfo jpaQueryInfo = builder.buildUpdate(properties); org.hibernate.query.Query query = session.createQuery(jpaQueryInfo.getQuery()); getHibernateTemplate().applySettings(query); List parameters = jpaQueryInfo.getParameters(); if (parameters != null) { for (int i = 0, count = parameters.size(); i < count; i++) { query.setParameter(JpaQueryBuilder.PARAMETER_NAME_PREFIX + (i+1), parameters.get(i)); } } HibernateHqlQuery hqlQuery = new HibernateHqlQuery(HibernateSession.this, targetEntity, query); ApplicationEventPublisher applicationEventPublisher = datastore.getApplicationEventPublisher(); applicationEventPublisher.publishEvent(new PreQueryEvent(datastore, hqlQuery)); int result = query.executeUpdate(); applicationEventPublisher.publishEvent(new PostQueryEvent(datastore, hqlQuery, Collections.singletonList(result))); return result; }); } public List retrieveAll(final Class type, final Iterable keys) { final PersistentEntity persistentEntity = getMappingContext().getPersistentEntity(type.getName()); return getHibernateTemplate().execute(session -> { final CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(type); final Root root = criteriaQuery.from(type); final String id = persistentEntity.getIdentity().getName(); criteriaQuery = criteriaQuery.where( criteriaBuilder.in( root.get(id).in(getIterableAsCollection(keys)) ) ); final org.hibernate.query.Query jpaQuery = session.createQuery(criteriaQuery); getHibernateTemplate().applySettings(jpaQuery); return new HibernateHqlQuery(this, persistentEntity, jpaQuery).list(); }); } public Query createQuery(Class type) { return createQuery(type, null); } @Override public Query createQuery(Class type, String alias) { final PersistentEntity persistentEntity = getMappingContext().getPersistentEntity(type.getName()); GrailsHibernateTemplate hibernateTemplate = getHibernateTemplate(); Session currentSession = hibernateTemplate.getSessionFactory().getCurrentSession(); final Criteria criteria = alias != null ? currentSession.createCriteria(type, alias) : currentSession.createCriteria(type); hibernateTemplate.applySettings(criteria); return new HibernateQuery(criteria, this, persistentEntity); } protected GrailsHibernateTemplate getHibernateTemplate() { return (GrailsHibernateTemplate)getNativeInterface(); } public void setFlushMode(FlushModeType flushMode) { if (flushMode == FlushModeType.AUTO) { hibernateTemplate.setFlushMode(GrailsHibernateTemplate.FLUSH_AUTO); } else if (flushMode == FlushModeType.COMMIT) { hibernateTemplate.setFlushMode(GrailsHibernateTemplate.FLUSH_COMMIT); } } public FlushModeType getFlushMode() { switch (hibernateTemplate.getFlushMode()) { case GrailsHibernateTemplate.FLUSH_AUTO: return FlushModeType.AUTO; case GrailsHibernateTemplate.FLUSH_COMMIT: return FlushModeType.COMMIT; case GrailsHibernateTemplate.FLUSH_ALWAYS: return FlushModeType.AUTO; default: return FlushModeType.AUTO; } } }
apache-2.0
kantega/Flyt-cms
modules/core/src/main/java/no/kantega/publishing/admin/content/action/NavigateController.java
5448
/* * Copyright 2009 Kantega AS * * 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 no.kantega.publishing.admin.content.action; import no.kantega.commons.client.util.RequestParameters; import no.kantega.commons.exception.ConfigurationException; import no.kantega.publishing.admin.AdminRequestParameters; import no.kantega.publishing.admin.AdminSessionAttributes; import no.kantega.publishing.admin.administration.action.CreateRootAction; import no.kantega.publishing.api.cache.SiteCache; import no.kantega.publishing.api.content.ContentIdHelper; import no.kantega.publishing.api.content.ContentIdentifier; import no.kantega.publishing.api.model.Site; import no.kantega.publishing.common.data.Content; import no.kantega.publishing.common.exception.ContentNotFoundException; import no.kantega.publishing.common.service.ContentManagementService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.List; import java.util.Map; public class NavigateController extends AbstractContentAction { private static final Logger log = LoggerFactory.getLogger(NavigateController.class); private String view; private SiteCache siteCache; private CreateRootAction createRootAction; @Autowired private ContentIdHelper contentIdHelper; @Override public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(true); ContentManagementService aksessService = new ContentManagementService(request); RequestParameters param = new RequestParameters(request); String url = param.getString(AdminRequestParameters.URL); Content current = (Content)session.getAttribute(AdminSessionAttributes.CURRENT_NAVIGATE_CONTENT); if (url != null || request.getParameter(AdminRequestParameters.THIS_ID) != null || request.getParameter(AdminRequestParameters.CONTENT_ID) != null) { ContentIdentifier cid = null; if (url != null) { cid = contentIdHelper.fromRequestAndUrl(request, url); } else { cid = contentIdHelper.fromRequest(request); } current = aksessService.getContent(cid); } if (current == null ) { ContentIdentifier cid = null; try { // No current object, go to start page cid = contentIdHelper.fromRequestAndUrl(request, "/"); } catch (ContentNotFoundException cnfe) { // Start page has not been created Site site = siteCache.getSiteByHostname(request.getServerName()); if (site == null) { List<Site> sites = siteCache.getSites(); if (sites.size() == 0) { throw new ConfigurationException("No sites defined in template configuration (aksess-templateconfig.xml)"); } site = sites.get(0); } createRootAction.createRootPage(site.getId(), request); cid = contentIdHelper.fromRequestAndUrl(request, "/"); } current = aksessService.getContent(cid); } session.setAttribute(AdminSessionAttributes.CURRENT_NAVIGATE_CONTENT, current); Content editedContent = (Content)session.getAttribute(AdminSessionAttributes.CURRENT_EDIT_CONTENT); String currentUrl = current.getUrl(); Map<String, Object> model = new HashMap<>(); if (editedContent != null && editedContent.isModified()) { // User is editing a page and has modified it, show preview currentUrl = request.getContextPath() + "/admin/publish/ViewContentPreviewFrame.action?thisId="; if (editedContent.isNew()) { // New page currentUrl += editedContent.getAssociation().getParentAssociationId(); } else { currentUrl += editedContent.getAssociation().getId(); } setRequestVariables(request, editedContent, aksessService, model); log.debug( "User is editing page:" + editedContent.getTitle()); } model.put("sites", siteCache.getSites()); model.put("currentUrl", currentUrl); return new ModelAndView(view, model); } public void setView(String view) { this.view = view; } public void setCreateRootAction(CreateRootAction createRootAction) { this.createRootAction = createRootAction; } public void setSiteCache(SiteCache siteCache) { this.siteCache = siteCache; } }
apache-2.0
reactor/reactor-netty
reactor-netty-http/src/test/java/reactor/netty/http/client/UriEndpointFactoryTest.java
14876
/* * Copyright (c) 2017-2021 VMware, 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. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package reactor.netty.http.client; import java.net.InetSocketAddress; import java.net.URI; import java.util.Arrays; import java.util.List; import java.util.function.BiFunction; import java.util.regex.Matcher; import org.junit.jupiter.api.Test; import reactor.netty.transport.AddressUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class UriEndpointFactoryTest { private final UriEndpointFactoryBuilder builder = new UriEndpointFactoryBuilder(); @Test void shouldParseUrls_1() { List<String[]> inputs = Arrays.asList( new String[]{"http://localhost:80/path", "http", "localhost", "80", "/path"}, new String[]{"http://localhost:80/path?key=val", "http", "localhost", "80", "/path?key=val"}, new String[]{"http://localhost/path", "http", "localhost", null, "/path"}, new String[]{"http://localhost/path?key=val", "http", "localhost", null, "/path?key=val"}, new String[]{"http://localhost/", "http", "localhost", null, "/"}, new String[]{"http://localhost/?key=val", "http", "localhost", null, "/?key=val"}, new String[]{"http://localhost", "http", "localhost", null, null}, new String[]{"http://localhost?key=val", "http", "localhost", null, "?key=val"}, new String[]{"http://localhost:80", "http", "localhost", "80", null}, new String[]{"http://localhost:80?key=val", "http", "localhost", "80", "?key=val"}, new String[]{"http://localhost/:1234", "http", "localhost", null, "/:1234"}, new String[]{"http://[::1]:80/path", "http", "[::1]", "80", "/path"}, new String[]{"http://[::1]:80/path?key=val", "http", "[::1]", "80", "/path?key=val"}, new String[]{"http://[::1]/path", "http", "[::1]", null, "/path"}, new String[]{"http://[::1]/path?key=val", "http", "[::1]", null, "/path?key=val"}, new String[]{"http://[::1]/", "http", "[::1]", null, "/"}, new String[]{"http://[::1]/?key=val", "http", "[::1]", null, "/?key=val"}, new String[]{"http://[::1]", "http", "[::1]", null, null}, new String[]{"http://[::1]?key=val", "http", "[::1]", null, "?key=val"}, new String[]{"http://[::1]:80", "http", "[::1]", "80", null}, new String[]{"http://[::1]:80?key=val", "http", "[::1]", "80", "?key=val"}, new String[]{"localhost:80/path", null, "localhost", "80", "/path"}, new String[]{"localhost:80/path?key=val", null, "localhost", "80", "/path?key=val"}, new String[]{"localhost/path", null, "localhost", null, "/path"}, new String[]{"localhost/path?key=val", null, "localhost", null, "/path?key=val"}, new String[]{"localhost/", null, "localhost", null, "/"}, new String[]{"localhost/?key=val", null, "localhost", null, "/?key=val"}, new String[]{"localhost", null, "localhost", null, null}, new String[]{"localhost?key=val", null, "localhost", null, "?key=val"}, new String[]{"localhost:80", null, "localhost", "80", null}, new String[]{"localhost:80?key=val", null, "localhost", "80", "?key=val"}, new String[]{"localhost/:1234", null, "localhost", null, "/:1234"} ); for (String[] input : inputs) { Matcher matcher = UriEndpointFactory.URL_PATTERN .matcher(input[0]); assertThat(matcher.matches()).isTrue(); assertThat(input[1]).isEqualTo(matcher.group(1)); assertThat(input[2]).isEqualTo(matcher.group(2)); assertThat(input[3]).isEqualTo(matcher.group(3)); assertThat(input[4]).isEqualTo(matcher.group(4)); } } @Test void shouldParseUrls_2() throws Exception { List<String[]> inputs = Arrays.asList( new String[]{"http://localhost:80/path", "http://localhost/path"}, new String[]{"http://localhost:80/path?key=val", "http://localhost/path?key=val"}, new String[]{"http://localhost/path", "http://localhost/path"}, new String[]{"http://localhost/path%20", "http://localhost/path%20"}, new String[]{"http://localhost/path?key=val", "http://localhost/path?key=val"}, new String[]{"http://localhost/", "http://localhost/"}, new String[]{"http://localhost/?key=val", "http://localhost/?key=val"}, new String[]{"http://localhost", "http://localhost/"}, new String[]{"http://localhost?key=val", "http://localhost/?key=val"}, new String[]{"http://localhost:80", "http://localhost/"}, new String[]{"http://localhost:80?key=val", "http://localhost/?key=val"}, new String[]{"http://localhost:80/?key=val#fragment", "http://localhost/?key=val"}, new String[]{"http://localhost:80/?key=%223", "http://localhost/?key=%223"}, new String[]{"http://localhost/:1234", "http://localhost/:1234"}, new String[]{"http://localhost:1234", "http://localhost:1234/"}, new String[]{"http://[::1]:80/path", "http://[::1]/path"}, new String[]{"http://[::1]:80/path?key=val", "http://[::1]/path?key=val"}, new String[]{"http://[::1]/path", "http://[::1]/path"}, new String[]{"http://[::1]/path%20", "http://[::1]/path%20"}, new String[]{"http://[::1]/path?key=val", "http://[::1]/path?key=val"}, new String[]{"http://[::1]/", "http://[::1]/"}, new String[]{"http://[::1]/?key=val", "http://[::1]/?key=val"}, new String[]{"http://[::1]", "http://[::1]/"}, new String[]{"http://[::1]?key=val", "http://[::1]/?key=val"}, new String[]{"http://[::1]:80", "http://[::1]/"}, new String[]{"http://[::1]:80?key=val", "http://[::1]/?key=val"}, new String[]{"http://[::1]:80/?key=val#fragment", "http://[::1]/?key=val"}, new String[]{"http://[::1]:80/?key=%223", "http://[::1]/?key=%223"}, new String[]{"http://[::1]:1234", "http://[::1]:1234/"} ); for (String[] input : inputs) { assertThat(externalForm(this.builder.build(), input[0], false, true)).isEqualTo(input[1]); } } @Test void createUriEndpointRelative() { String test1 = this.builder.build() .createUriEndpoint("/foo", false) .toExternalForm(); String test2 = this.builder.build() .createUriEndpoint("/foo", true) .toExternalForm(); assertThat(test1).isEqualTo("http://localhost/foo"); assertThat(test2).isEqualTo("ws://localhost/foo"); } @Test void createUriEndpointRelativeSslSupport() { String test1 = this.builder.sslSupport() .build() .createUriEndpoint("/foo", false) .toExternalForm(); String test2 = this.builder.sslSupport() .build() .createUriEndpoint("/foo", true) .toExternalForm(); assertThat(test1).isEqualTo("https://localhost/foo"); assertThat(test2).isEqualTo("wss://localhost/foo"); } @Test void createUriEndpointRelativeNoLeadingSlash() { String test1 = this.builder.sslSupport().build() .createUriEndpoint("example.com:8443/bar", false) .toExternalForm(); String test2 = this.builder.build() .createUriEndpoint("example.com:8443/bar", true) .toExternalForm(); assertThat(test1).isEqualTo("https://example.com:8443/bar"); assertThat(test2).isEqualTo("wss://example.com:8443/bar"); } @Test void createUriEndpointRelativeAddress() { String test1 = this.builder.host("127.0.0.1") .port(8080) .build() .createUriEndpoint("/foo", false) .toExternalForm(); String test2 = this.builder.host("127.0.0.1") .port(8080) .build() .createUriEndpoint("/foo", true) .toExternalForm(); assertThat(test1).isEqualTo("http://127.0.0.1:8080/foo"); assertThat(test2).isEqualTo("ws://127.0.0.1:8080/foo"); } @Test void createUriEndpointIPv6Address() { String test1 = this.builder.host("::1") .port(8080) .build() .createUriEndpoint("/foo", false) .toExternalForm(); String test2 = this.builder.host("::1") .port(8080) .build() .createUriEndpoint("/foo", true) .toExternalForm(); assertThat(test1).isEqualTo("http://[::1]:8080/foo"); assertThat(test2).isEqualTo("ws://[::1]:8080/foo"); } @Test void createUriEndpointRelativeAddressSsl() { String test1 = this.builder.host("example.com") .port(8080) .sslSupport() .build() .createUriEndpoint("/foo", false) .toExternalForm(); String test2 = this.builder.host("example.com") .port(8080) .sslSupport() .build() .createUriEndpoint("/foo", true) .toExternalForm(); assertThat(test1).isEqualTo("https://example.com:8080/foo"); assertThat(test2).isEqualTo("wss://example.com:8080/foo"); } @Test void createUriEndpointRelativeWithPort() { String test = this.builder .host("example.com") .port(443) .sslSupport() .build() .createUriEndpoint("/foo", false) .toExternalForm(); assertThat(test).isEqualTo("https://example.com/foo"); } @Test void createUriEndpointAbsoluteHttp() throws Exception { testCreateUriEndpointAbsoluteHttp(false); testCreateUriEndpointAbsoluteHttp(true); } private void testCreateUriEndpointAbsoluteHttp(boolean useUri) throws Exception { String test1 = externalForm(this.builder.build(), "https://localhost/foo", false, useUri); String test2 = externalForm(this.builder.build(), "http://localhost/foo", true, useUri); String test3 = externalForm(this.builder.sslSupport().build(), "http://localhost/foo", false, useUri); String test4 = externalForm(this.builder.sslSupport().build(), "https://localhost/foo", true, useUri); assertThat(test1).isEqualTo("https://localhost/foo"); assertThat(test2).isEqualTo("http://localhost/foo"); assertThat(test3).isEqualTo("http://localhost/foo"); assertThat(test4).isEqualTo("https://localhost/foo"); } @Test void createUriEndpointWithQuery() throws Exception { testCreateUriEndpointWithQuery(false); testCreateUriEndpointWithQuery(true); } private void testCreateUriEndpointWithQuery(boolean useUri) throws Exception { assertThat(externalForm(this.builder.build(), "http://localhost/foo?key=val", false, useUri)) .isEqualTo("http://localhost/foo?key=val"); assertThat(externalForm(this.builder.build(), "http://localhost/?key=val", false, useUri)) .isEqualTo("http://localhost/?key=val"); assertThat(externalForm(this.builder.build(), "http://localhost?key=val", false, useUri)) .isEqualTo("http://localhost/?key=val"); assertThat(externalForm(this.builder.build(), "http://localhost:80/foo?key=val", false, useUri)) .isEqualTo("http://localhost/foo?key=val"); assertThat(externalForm(this.builder.build(), "http://localhost:80/?key=val", false, useUri)) .isEqualTo("http://localhost/?key=val"); assertThat(externalForm(this.builder.build(), "http://localhost:80?key=val", false, useUri)) .isEqualTo("http://localhost/?key=val"); if (useUri) { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> externalForm(this.builder.build(), "localhost/foo?key=val", false, useUri)); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> externalForm(this.builder.build(), "localhost/?key=val", false, useUri)); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> externalForm(this.builder.build(), "localhost?key=val", false, useUri)); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> externalForm(this.builder.build(), "localhost:80/foo?key=val", false, useUri)); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> externalForm(this.builder.build(), "localhost:80/?key=val", false, useUri)); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> externalForm(this.builder.build(), "localhost:80?key=val", false, useUri)); } else { assertThat(externalForm(this.builder.build(), "localhost/foo?key=val", false, useUri)) .isEqualTo("http://localhost/foo?key=val"); assertThat(externalForm(this.builder.build(), "localhost/?key=val", false, useUri)) .isEqualTo("http://localhost/?key=val"); assertThat(externalForm(this.builder.build(), "localhost?key=val", false, useUri)) .isEqualTo("http://localhost/?key=val"); assertThat(externalForm(this.builder.build(), "localhost:80/foo?key=val", false, useUri)) .isEqualTo("http://localhost/foo?key=val"); assertThat(externalForm(this.builder.build(), "localhost:80/?key=val", false, useUri)) .isEqualTo("http://localhost/?key=val"); assertThat(externalForm(this.builder.build(), "localhost:80?key=val", false, useUri)) .isEqualTo("http://localhost/?key=val"); } } @Test void createUriEndpointAbsoluteWs() throws Exception { testCreateUriEndpointAbsoluteWs(false); testCreateUriEndpointAbsoluteWs(true); } private void testCreateUriEndpointAbsoluteWs(boolean useUri) throws Exception { String test1 = externalForm(this.builder.build(), "wss://localhost/foo", false, useUri); String test2 = externalForm(this.builder.build(), "ws://localhost/foo", true, useUri); String test3 = externalForm(this.builder.sslSupport().build(), "ws://localhost/foo", false, useUri); String test4 = externalForm(this.builder.sslSupport().build(), "wss://localhost/foo", true, useUri); assertThat(test1).isEqualTo("wss://localhost/foo"); assertThat(test2).isEqualTo("ws://localhost/foo"); assertThat(test3).isEqualTo("ws://localhost/foo"); assertThat(test4).isEqualTo("wss://localhost/foo"); } private static String externalForm(UriEndpointFactory factory, String url, boolean isWs, boolean useUri) throws Exception { if (useUri) { return factory.createUriEndpoint(new URI(url), isWs) .toExternalForm(); } else { return factory.createUriEndpoint(url, isWs) .toExternalForm(); } } private static final class UriEndpointFactoryBuilder { private boolean secure; private String host = "localhost"; private int port = -1; public UriEndpointFactory build() { return new UriEndpointFactory( () -> InetSocketAddress.createUnresolved(host, port != -1 ? port : (secure ? 443 : 80)), secure, URI_ADDRESS_MAPPER); } public UriEndpointFactoryBuilder sslSupport() { this.secure = true; return this; } public UriEndpointFactoryBuilder host(String host) { this.host = host; return this; } public UriEndpointFactoryBuilder port(int port) { this.port = port; return this; } static final BiFunction<String, Integer, InetSocketAddress> URI_ADDRESS_MAPPER = AddressUtils::createUnresolved; } }
apache-2.0
AntTaylor/SweetLife
app/src/main/java/com/myzl/sweetlife/fragment/RecipesDaquanFragment.java
732
package com.myzl.sweetlife.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.anttaylor.common.ui.fragment.BaseFragment; import com.myzl.sweetlife.R; /** * Created by Taylor on 2016/6/21 15:10. * Description: 菜谱大全页面 */ public class RecipesDaquanFragment extends BaseFragment{ @Override public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.page_recipes_daquan, null); return view; } @Override public void initData() { } @Override public void initListener() { } }
apache-2.0
McLeodMoores/starling
projects/financial/src/main/java/com/opengamma/financial/analytics/volatility/surface/RawEquityFutureOptionVolatilitySurfaceDataFunction.java
4414
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.volatility.surface; import java.util.Set; import com.google.common.collect.ImmutableSet; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.core.id.ExternalSchemes; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.target.ComputationTargetType; import com.opengamma.financial.analytics.model.InstrumentTypeProperties; import com.opengamma.financial.analytics.model.equity.EquitySecurityUtils; import com.opengamma.id.ExternalId; import com.opengamma.id.ExternalIdentifiable; import com.opengamma.id.ExternalScheme; import com.opengamma.id.VersionCorrection; /** * Constructs volatility surface data objects for equity options (single-name and index) if the target is a Bloomberg ticker or weak ticker. */ public class RawEquityFutureOptionVolatilitySurfaceDataFunction extends RawVolatilitySurfaceDataFunction { /** The supported schemes */ private static final Set<ExternalScheme> VALID_SCHEMES = ImmutableSet.of(ExternalSchemes.BLOOMBERG_TICKER, ExternalSchemes.BLOOMBERG_TICKER_WEAK, ExternalSchemes.ACTIVFEED_TICKER); /** * Default constructor. */ public RawEquityFutureOptionVolatilitySurfaceDataFunction() { super(InstrumentTypeProperties.EQUITY_FUTURE_OPTION); } @Override protected ComputationTargetType getTargetType() { return ComputationTargetType.PRIMITIVE; // Bloomberg ticker or weak ticker } @Override public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) { if (target.getValue() instanceof ExternalIdentifiable) { final ExternalId identifier = ((ExternalIdentifiable) target.getValue()).getExternalId(); return VALID_SCHEMES.contains(identifier.getScheme()); } return false; } /** * The postfix (e.g. Index, Equity) is removed from the Bloomberg ticker when constructing the surface name, so the full name of a surface with * <ul> * <li>definitionName = OPENGAMMA</li> * <li>target=BLOOMBERG_TICKER~DJX Index</li> * </ul> * is OPENGAMMA_DJX_EQUITY_FUTURE_OPTION {@inheritDoc} */ @Override protected VolatilitySurfaceDefinition<?, ?> getDefinition(final VolatilitySurfaceDefinitionSource definitionSource, final VersionCorrection versionCorrection, final ComputationTarget target, final String definitionName) { final String fullDefinitionName = definitionName + "_" + EquitySecurityUtils.getTrimmedTarget(((ExternalIdentifiable) target.getValue()).getExternalId()); final VolatilitySurfaceDefinition<?, ?> definition = definitionSource.getDefinition(fullDefinitionName, InstrumentTypeProperties.EQUITY_FUTURE_OPTION, versionCorrection); if (definition == null) { throw new OpenGammaRuntimeException( "Could not get volatility surface definition named " + fullDefinitionName + " for instrument type " + InstrumentTypeProperties.EQUITY_FUTURE_OPTION); } return definition; } /** * The postfix (e.g. Index, Equity) is removed from the Bloomberg ticker when constructing the surface name, so the full name of a surface with * <ul> * <li>specificationName = OPENGAMMA</li> * <li>target=BLOOMBERG_TICKER~DJX Index</li> * </ul> * is OPENGAMMA_DJX_EQUITY_FUTURE_OPTION {@inheritDoc} */ @Override protected VolatilitySurfaceSpecification getSpecification(final VolatilitySurfaceSpecificationSource specificationSource, final VersionCorrection versionCorrection, final ComputationTarget target, final String specificationName) { final String fullSpecificationName = specificationName + "_" + EquitySecurityUtils.getTrimmedTarget(((ExternalIdentifiable) target.getValue()).getExternalId()); final VolatilitySurfaceSpecification specification = specificationSource.getSpecification(fullSpecificationName, InstrumentTypeProperties.EQUITY_FUTURE_OPTION, versionCorrection); if (specification == null) { throw new OpenGammaRuntimeException("Could not get volatility surface specification named " + fullSpecificationName + " for instrument type " + InstrumentTypeProperties.EQUITY_FUTURE_OPTION); } return specification; } }
apache-2.0
triceo/zonkybot
robozonky-strategy-natural/src/test/java/com/github/robozonky/strategy/natural/PrimaryMarketplaceComparatorTest.java
4044
/* * Copyright 2020 The RoboZonky 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.github.robozonky.strategy.natural; import static org.assertj.core.api.SoftAssertions.assertSoftly; import java.time.Duration; import java.time.Instant; import java.time.OffsetDateTime; import java.util.Comparator; import org.junit.jupiter.api.Test; import com.github.robozonky.api.Money; import com.github.robozonky.api.remote.enums.Rating; import com.github.robozonky.api.strategies.LoanDescriptor; import com.github.robozonky.internal.Defaults; import com.github.robozonky.internal.remote.entities.LoanImpl; import com.github.robozonky.test.mock.MockLoanBuilder; class PrimaryMarketplaceComparatorTest { private final Comparator<LoanDescriptor> c = new PrimaryMarketplaceComparator(Rating::compareTo); private static LoanImpl mockLoan(final Rating rating, final int amount, final OffsetDateTime published) { return new MockLoanBuilder() .set(LoanImpl::setRating, rating) .set(LoanImpl::setDatePublished, published) .set(LoanImpl::setRemainingInvestment, Money.from(amount)) .set(LoanImpl::setReservedAmount, Money.from(0)) .build(); } @Test void sortByRating() { final OffsetDateTime first = OffsetDateTime.ofInstant(Instant.EPOCH, Defaults.ZONE_ID); final OffsetDateTime second = first.plus(Duration.ofMillis(1)); final LoanImpl l1 = mockLoan(Rating.D, 100000, first); final LoanImpl l2 = mockLoan(Rating.A, l1.getNonReservedRemainingInvestment() .getValue() .intValue(), second); final LoanDescriptor ld1 = new LoanDescriptor(l1), ld2 = new LoanDescriptor(l2); assertSoftly(softly -> { softly.assertThat(c.compare(ld1, ld2)) .isGreaterThan(0); softly.assertThat(c.compare(ld2, ld1)) .isLessThan(0); softly.assertThat(c.compare(ld1, ld1)) .isEqualTo(0); }); } @Test void sortByRecencyIfSameRating() { final OffsetDateTime first = OffsetDateTime.ofInstant(Instant.EPOCH, Defaults.ZONE_ID); final OffsetDateTime second = first.plus(Duration.ofMillis(1)); final LoanImpl l1 = mockLoan(Rating.A, 100000, first); final LoanImpl l2 = mockLoan(Rating.A, l1.getNonReservedRemainingInvestment() .getValue() .intValue(), second); final LoanDescriptor ld1 = new LoanDescriptor(l1), ld2 = new LoanDescriptor(l2); assertSoftly(softly -> { softly.assertThat(c.compare(ld1, ld2)) .isGreaterThan(0); softly.assertThat(c.compare(ld2, ld1)) .isLessThan(0); softly.assertThat(c.compare(ld1, ld1)) .isEqualTo(0); }); } @Test void sortByRemainingIfAsRecent() { final OffsetDateTime first = OffsetDateTime.ofInstant(Instant.EPOCH, Defaults.ZONE_ID); final LoanImpl l1 = mockLoan(Rating.A, 100000, first); final LoanImpl l2 = mockLoan(Rating.A, l1.getNonReservedRemainingInvestment() .getValue() .intValue() + 1, l1.getDatePublished()); final LoanDescriptor ld1 = new LoanDescriptor(l1), ld2 = new LoanDescriptor(l2); assertSoftly(softly -> { softly.assertThat(c.compare(ld1, ld2)) .isGreaterThan(0); softly.assertThat(c.compare(ld2, ld1)) .isLessThan(0); }); } }
apache-2.0
spring-cloud-incubator/spring-cloud-kubernetes
spring-cloud-kubernetes-integration-tests/discovery/tests/src/test/java/org/springframework/cloud/kubernetes/it/ServicesIT.java
2043
/* * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.kubernetes.it; import org.arquillian.cube.kubernetes.impl.requirement.RequiresKubernetes; import org.hamcrest.core.StringContains; import org.jboss.arquillian.junit.Arquillian; import org.junit.Test; import org.junit.runner.RunWith; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.hasSize; @RequiresKubernetes @RunWith(Arquillian.class) public class ServicesIT { private static final String HOST = System.getProperty("service.host"); private static final Integer PORT = Integer .valueOf(System.getProperty("service.port")); private static final String PROTOCOL = "true" .equalsIgnoreCase(System.getProperty("service.secure")) ? "https" : "http"; @Test public void testServicesEndpoint() { given().baseUri(String.format("%s://%s:%d", PROTOCOL, HOST, PORT)).get("services") .then().statusCode(200).body(new StringContains(false, "service-a") { @Override protected boolean evalSubstringOf(String s) { return s.contains("service-a") && s.contains("service-b"); } }); } @Test public void testInstancesEndpoint() { given().baseUri(String.format("%s://%s:%d", PROTOCOL, HOST, PORT)) .get("services/discovery-service-a/instances").then().statusCode(200) .body("instanceId", hasSize(1)) .body("serviceId", hasItems("discovery-service-a")); } }
apache-2.0
pdalbora/gosu-lang
gosu-xml/src/main/java/gw/internal/schema/gw/xsd/w3c/xmlschema/enums/BlockSet2.java
2181
package gw.internal.schema.gw.xsd.w3c.xmlschema.enums; /***************************************************************************/ /* THIS IS AUTOGENERATED CODE - DO NOT MODIFY OR YOUR CHANGES WILL BE LOST */ /* THIS CODE CAN BE REGENERATED USING 'xsd-codegen' */ /***************************************************************************/ public enum BlockSet2 implements gw.lang.reflect.gs.IGosuObject, gw.lang.reflect.IEnumValue, gw.xml.IXmlSchemaEnumValue, gw.internal.xml.IXmlGeneratedClass { Extension( "extension" ), Restriction( "restriction" ), Substitution( "substitution" ); public static final gw.util.concurrent.LockingLazyVar<gw.lang.reflect.IType> TYPE = new gw.util.concurrent.LockingLazyVar<gw.lang.reflect.IType>( gw.lang.reflect.TypeSystem.getGlobalLock() ) { @Override protected gw.lang.reflect.IType init() { return gw.lang.reflect.TypeSystem.getByFullName( "gw.xsd.w3c.xmlschema.enums.BlockSet2" ); } }; private final java.lang.String _serializedValue; private BlockSet2( java.lang.String serializedValue ) { _serializedValue = serializedValue; } @Override public gw.lang.reflect.IType getIntrinsicType() { return TYPE.get(); } @Override public java.lang.String toString() { return _serializedValue; } @Override public java.lang.Object getValue() { return this; } @Override public java.lang.String getCode() { return name(); } @Override public int getOrdinal() { return ordinal(); } @Override public java.lang.String getDisplayName() { return name(); } public gw.internal.schema.gw.xsd.w3c.xmlschema.enums.DerivationControl getGosuValue() { return (gw.internal.schema.gw.xsd.w3c.xmlschema.enums.DerivationControl) TYPE.get().getTypeInfo().getProperty( "GosuValue" ).getAccessor().getValue( this ); } public java.lang.String getSerializedValue() { return (java.lang.String) TYPE.get().getTypeInfo().getProperty( "SerializedValue" ).getAccessor().getValue( this ); } @SuppressWarnings( {"UnusedDeclaration"} ) private static final long FINGERPRINT = 2110283714877373226L; }
apache-2.0
arquillian/arquillian-container-weld
impl/src/main/java/org/jboss/arquillian/container/weld/embedded/mock/MockEjBServices.java
1880
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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.jboss.arquillian.container.weld.embedded.mock; import org.jboss.weld.ejb.api.SessionObjectReference; import org.jboss.weld.ejb.spi.EjbDescriptor; import org.jboss.weld.ejb.spi.EjbServices; import org.jboss.weld.ejb.spi.InterceptorBindings; public class MockEjBServices implements EjbServices { public SessionObjectReference resolveEjb(EjbDescriptor<?> ejbDescriptor) { return new SessionObjectReference() { private static final long serialVersionUID = 1L; public <S> S getBusinessObject(Class<S> businessInterfaceType) { // TODO Auto-generated method stub return null; } public void remove() { // TODO Auto-generated method stub } public boolean isRemoved() { // TODO Auto-generated method stub return false; } }; } public void registerInterceptors(EjbDescriptor<?> ejbDescriptor, InterceptorBindings interceptorBindings) { // do nothing } public void cleanup() { } }
apache-2.0