repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
bulain/netty-demo
src/test/java/com/bulain/netty/securitychat/SecureChatClientInitializer.java
1623
package com.bulain.netty.securitychat; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.Delimiters; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.handler.ssl.SslContext; /** * Creates a newly configured {@link ChannelPipeline} for a new channel. */ public class SecureChatClientInitializer extends ChannelInitializer<SocketChannel> { private final SslContext sslCtx; public SecureChatClientInitializer(SslContext sslCtx) { this.sslCtx = sslCtx; } @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // Add SSL handler first to encrypt and decrypt everything. // In this example, we use a bogus certificate in the server side // and accept any invalid certificates in the client side. // You will need something more complicated to identify both // and server in the real world. pipeline.addLast(sslCtx.newHandler(ch.alloc(), SecureChatClient.HOST, SecureChatClient.PORT)); // On top of the SSL handler, add the text line codec. pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); pipeline.addLast(new StringDecoder()); pipeline.addLast(new StringEncoder()); // and then business logic. pipeline.addLast(new SecureChatClientHandler()); } }
apache-2.0
iamtowne/yscardII
src/main/java/com/yscardII/framework/hibernate/dao/impl/UtocardDao.java
331
package com.yscardII.framework.hibernate.dao.impl; import org.springframework.stereotype.Repository; import com.yscardII.framework.common.dao.HibernateDao; import com.yscardII.framework.hibernate.bo.Utocard; @Repository(value = "utocardDaoHibernate4") public class UtocardDao extends HibernateDao<Utocard, Integer> { }
apache-2.0
yeastrc/proxl-web-app
proxl_web_app/src/main/java/org/yeastrc/xlink/www/dto/SrchRepPeptProtSeqIdPosLooplinkDTO.java
2255
package org.yeastrc.xlink.www.dto; /** * Looplink * * table srch_rep_pept__prot_seq_id_pos_looplink * */ public class SrchRepPeptProtSeqIdPosLooplinkDTO implements SrchRepPeptProtSeqIdPosCommonIF { private int id; private int searchId; private int reportedPeptideId; private int searchReportedPeptidepeptideId; private int proteinSequenceVersionId; private int proteinSequencePosition_1; private int proteinSequencePosition_2; @Override public String toString() { return "SrchRepPeptProtSeqIdPosDTO [id=" + id + ", searchId=" + searchId + ", reportedPeptideId=" + reportedPeptideId + ", searchReportedPeptidepeptideId=" + searchReportedPeptidepeptideId + ", proteinSequenceVersionId=" + proteinSequenceVersionId + ", proteinSequencePosition_1=" + proteinSequencePosition_1 + ", proteinSequencePosition_2=" + proteinSequencePosition_2 + "]"; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public int getSearchId() { return searchId; } public void setSearchId(int searchId) { this.searchId = searchId; } @Override public int getReportedPeptideId() { return reportedPeptideId; } public void setReportedPeptideId(int reportedPeptideId) { this.reportedPeptideId = reportedPeptideId; } @Override public int getSearchReportedPeptidepeptideId() { return searchReportedPeptidepeptideId; } public void setSearchReportedPeptidepeptideId(int searchReportedPeptidepeptideId) { this.searchReportedPeptidepeptideId = searchReportedPeptidepeptideId; } @Override public int getProteinSequenceVersionId() { return proteinSequenceVersionId; } public void setProteinSequenceVersionId(int proteinSequenceVersionId) { this.proteinSequenceVersionId = proteinSequenceVersionId; } public int getProteinSequencePosition_1() { return proteinSequencePosition_1; } public void setProteinSequencePosition_1(int proteinSequencePosition_1) { this.proteinSequencePosition_1 = proteinSequencePosition_1; } public int getProteinSequencePosition_2() { return proteinSequencePosition_2; } public void setProteinSequencePosition_2(int proteinSequencePosition_2) { this.proteinSequencePosition_2 = proteinSequencePosition_2; } }
apache-2.0
yueny/pra
scheduler/console-example/src/main/java/com/yueny/demo/dynamic/scheduler/util/DateTimeUtils.java
510
package com.yueny.demo.dynamic.scheduler.util; import java.text.SimpleDateFormat; import java.util.Date; @Deprecated public abstract class DateTimeUtils { /** * 根据规则格式化时间 * * @Title: fomat * @Description: TODO * @param date * @param pattern * @return * @return: String */ public static String fomat(final String date, final String pattern) { final SimpleDateFormat format = new SimpleDateFormat(pattern); return format.format(new Date(Long.valueOf(date))); } }
apache-2.0
javaslang/javaslang-circuitbreaker
resilience4j-spring/src/test/java/io/github/resilience4j/bulkhead/configure/BulkheadBuilderCustomizerTest.java
10954
package io.github.resilience4j.bulkhead.configure; import io.github.resilience4j.TestThreadLocalContextPropagator; import io.github.resilience4j.bulkhead.*; import io.github.resilience4j.bulkhead.configure.threadpool.ThreadPoolBulkheadConfiguration; import io.github.resilience4j.bulkhead.event.BulkheadEvent; import io.github.resilience4j.common.CompositeCustomizer; import io.github.resilience4j.common.bulkhead.configuration.BulkheadConfigCustomizer; import io.github.resilience4j.common.bulkhead.configuration.ThreadPoolBulkheadConfigCustomizer; import io.github.resilience4j.common.bulkhead.configuration.ThreadPoolBulkheadConfigurationProperties; import io.github.resilience4j.consumer.DefaultEventConsumerRegistry; import io.github.resilience4j.consumer.EventConsumerRegistry; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.time.Duration; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Supplier; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.util.ReflectionTestUtils.getField; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {BulkheadBuilderCustomizerTest.Config.class}) public class BulkheadBuilderCustomizerTest { @Autowired private ThreadPoolBulkheadRegistry threadPoolBulkheadRegistry; @Autowired private BulkheadRegistry bulkheadRegistry; @Autowired @Qualifier("compositeBulkheadCustomizer") private CompositeCustomizer<BulkheadConfigCustomizer> compositeBulkheadCustomizer; @Autowired @Qualifier("compositeThreadPoolBulkheadCustomizer") private CompositeCustomizer<ThreadPoolBulkheadConfigCustomizer> compositeThreadPoolBulkheadCustomizer; @Test public void testThreadPoolBulkheadCustomizer() { assertThat(threadPoolBulkheadRegistry).isNotNull(); assertThat(compositeThreadPoolBulkheadCustomizer).isNotNull(); //All Customizer bean should be added to CompositeBuilderCustomizer as its primary bean. Map<String, ThreadPoolBulkheadConfigCustomizer> map = (Map<String, ThreadPoolBulkheadConfigCustomizer>) getField( compositeThreadPoolBulkheadCustomizer, "customizerMap"); assertThat(map).isNotNull(); assertThat(map).hasSize(2).containsKeys("backendB", "backendD"); //This test context propagator set to config by properties. R4J will invoke default // constructor of ContextPropagator class using reflection. //downside is that no dependencies can be added to ContextPropagators class ThreadPoolBulkhead bulkheadA = threadPoolBulkheadRegistry.bulkhead("bulkheadA", "backendA"); assertThat(bulkheadA).isNotNull(); assertThat(bulkheadA.getBulkheadConfig().getCoreThreadPoolSize()).isEqualTo(2); assertThat(bulkheadA.getBulkheadConfig().getMaxThreadPoolSize()).isEqualTo(4); assertThat(bulkheadA.getBulkheadConfig().getContextPropagator()).hasSize(1); assertThat(bulkheadA.getBulkheadConfig().getContextPropagator().get(0)) .isInstanceOf(TestThreadLocalContextPropagator.class); //This test context propagator bean set to config using Customizer interface via SpringContext ThreadPoolBulkhead bulkheadB = threadPoolBulkheadRegistry.bulkhead("bulkheadB", "backendB"); assertThat(bulkheadB).isNotNull(); assertThat(bulkheadB.getBulkheadConfig().getCoreThreadPoolSize()).isEqualTo(2); assertThat(bulkheadB.getBulkheadConfig().getMaxThreadPoolSize()).isEqualTo(4); assertThat(bulkheadB.getBulkheadConfig().getContextPropagator()).hasSize(1); assertThat(bulkheadB.getBulkheadConfig().getContextPropagator().get(0)) .isInstanceOf(BeanContextPropagator.class); //This test has no context propagator ThreadPoolBulkhead bulkheadC = threadPoolBulkheadRegistry.bulkhead("bulkheadC", "backendC"); assertThat(bulkheadC).isNotNull(); assertThat(bulkheadC.getBulkheadConfig().getCoreThreadPoolSize()).isEqualTo(2); assertThat(bulkheadC.getBulkheadConfig().getMaxThreadPoolSize()).isEqualTo(4); assertThat(bulkheadC.getBulkheadConfig().getContextPropagator()).hasSize(0); //This test context propagator bean set to config using Customizer interface via SpringContext ThreadPoolBulkhead bulkheadD = threadPoolBulkheadRegistry.bulkhead("bulkheadD", "backendD"); assertThat(bulkheadD).isNotNull(); assertThat(bulkheadD.getBulkheadConfig().getCoreThreadPoolSize()).isEqualTo(2); assertThat(bulkheadD.getBulkheadConfig().getMaxThreadPoolSize()).isEqualTo(4); assertThat(bulkheadD.getBulkheadConfig().getContextPropagator()).hasSize(1); assertThat(bulkheadD.getBulkheadConfig().getContextPropagator().get(0)) .isInstanceOf(BeanContextPropagator.class); } @Test public void testBulkheadCustomizer() { assertThat(bulkheadRegistry).isNotNull(); assertThat(compositeBulkheadCustomizer).isNotNull(); //All Customizer bean should be added to CompositeBuilderCustomizer as its primary bean. Map<String, ThreadPoolBulkheadConfigCustomizer> map = (Map<String, ThreadPoolBulkheadConfigCustomizer>) getField( compositeBulkheadCustomizer, "customizerMap"); assertThat(map).isNotNull(); assertThat(map).hasSize(1).containsKeys("backendOne"); //This config is changed programmatically Bulkhead bulkheadOne = bulkheadRegistry.bulkhead("bulkheadOne", "backendOne"); assertThat(bulkheadOne).isNotNull(); assertThat(bulkheadOne.getBulkheadConfig().getMaxConcurrentCalls()).isEqualTo(20); assertThat(bulkheadOne.getBulkheadConfig().getMaxWaitDuration()) .isEqualTo(Duration.ofSeconds(1)); Bulkhead bulkheadTwo = bulkheadRegistry.bulkhead("bulkheadTwo", "backendTwo"); assertThat(bulkheadTwo).isNotNull(); assertThat(bulkheadTwo.getBulkheadConfig().getMaxConcurrentCalls()).isEqualTo(10); assertThat(bulkheadTwo.getBulkheadConfig().getMaxWaitDuration()) .isEqualTo(Duration.ofSeconds(1)); } @Configuration @Import({ThreadPoolBulkheadConfiguration.class, BulkheadConfiguration.class}) static class Config { @Bean public EventConsumerRegistry<BulkheadEvent> eventConsumerRegistry() { return new DefaultEventConsumerRegistry<>(); } @Bean public ThreadPoolBulkheadConfigCustomizer customizerB( List<? extends ContextPropagator> contextPropagators) { return ThreadPoolBulkheadConfigCustomizer.of("backendB", builder -> builder.contextPropagator( contextPropagators.toArray(new ContextPropagator[contextPropagators.size()]))); } @Bean public ThreadPoolBulkheadConfigCustomizer customizerD( List<? extends ContextPropagator> contextPropagators) { return ThreadPoolBulkheadConfigCustomizer.of("backendD", builder -> builder.contextPropagator( contextPropagators.toArray(new ContextPropagator[contextPropagators.size()]))); } @Bean public BulkheadConfigCustomizer customizerOne( List<? extends ContextPropagator> contextPropagators) { return BulkheadConfigCustomizer.of("backendOne", builder -> builder.maxConcurrentCalls(20)); } @Bean public BeanContextPropagator beanContextPropagator() { return new BeanContextPropagator(); } @Bean public ThreadPoolBulkheadConfigurationProperties threadPoolBulkheadConfigurationProperties() { return new ThreadPoolBulkheadConfigurationPropertiesTest(); } @Bean public BulkheadConfigurationProperties bulkheadConfigurationProperties() { return new BulkheadConfigurationPropertiesTest(); } private class ThreadPoolBulkheadConfigurationPropertiesTest extends ThreadPoolBulkheadConfigurationProperties { ThreadPoolBulkheadConfigurationPropertiesTest() { InstanceProperties properties1 = new InstanceProperties(); properties1.setCoreThreadPoolSize(2); properties1.setMaxThreadPoolSize(4); properties1.setContextPropagators(TestThreadLocalContextPropagator.class); getConfigs().put("backendA", properties1); InstanceProperties properties2 = new InstanceProperties(); properties2.setCoreThreadPoolSize(2); properties2.setMaxThreadPoolSize(4); getConfigs().put("backendB", properties2); InstanceProperties properties3 = new InstanceProperties(); properties3.setCoreThreadPoolSize(2); properties3.setMaxThreadPoolSize(4); getConfigs().put("backendC", properties3); InstanceProperties properties4 = new InstanceProperties(); properties4.setCoreThreadPoolSize(2); properties4.setMaxThreadPoolSize(4); getConfigs().put("backendD", properties3); } } private class BulkheadConfigurationPropertiesTest extends BulkheadConfigurationProperties { BulkheadConfigurationPropertiesTest() { InstanceProperties properties1 = new InstanceProperties(); properties1.setMaxConcurrentCalls(10); properties1.setMaxWaitDuration(Duration.ofSeconds(1)); getConfigs().put("backendOne", properties1); InstanceProperties properties2 = new InstanceProperties(); properties2.setMaxConcurrentCalls(10); properties2.setMaxWaitDuration(Duration.ofSeconds(1)); getConfigs().put("backendTwo", properties2); } } } public static class BeanContextPropagator implements ContextPropagator<String> { @Override public Supplier<Optional<String>> retrieve() { return () -> Optional.empty(); } @Override public Consumer<Optional<String>> copy() { return (t) -> { }; } @Override public Consumer<Optional<String>> clear() { return (t) -> { }; } } }
apache-2.0
f-evil/EVideoRecorder
app/src/main/java/com/fyj/videorecorder/VideoApp.java
989
package com.fyj.videorecorder; import android.app.Application; import android.content.Context; import com.fyj.erecord.VideoConfig; import java.lang.ref.SoftReference; /** * 当前作者: Fyj<br> * 时间: 2017/4/28<br> * 邮箱: f279259625@gmail.com<br> * 修改次数: <br> * 描述: */ public class VideoApp extends Application { private static SoftReference<Context> videoContext; @Override public void onCreate() { super.onCreate(); videoContext = new SoftReference<>(getApplicationContext()); VideoConfig.init(this, ""); } public static Context getApplication() { // if (videoContext == null) { // videoContext = new SoftReference<>(this); // return videoContext.get(); // } // if (videoContext.get() == null) { // videoContext = new SoftReference<>(getApplicationContext()); // return videoContext.get(); // } return videoContext.get(); } }
apache-2.0
IWSDevelopers/iws
iws-core/src/main/java/net/iaeste/iws/core/notifications/Notifications.java
2292
/* * Licensed to IAESTE A.s.b.l. (IAESTE) under one or more contributor * license agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. The Authors * (See the AUTHORS file distributed with this work) licenses this file to * You under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.iaeste.iws.core.notifications; import net.iaeste.iws.common.utils.Observable; import net.iaeste.iws.persistence.Authentication; import net.iaeste.iws.persistence.entities.UserEntity; import net.iaeste.iws.common.notification.Notifiable; import net.iaeste.iws.common.notification.NotificationType; /** * Classes to be observed, should extend the Notifiable interface. * * @author Kim Jensen / last $Author:$ * @version $Revision:$ / $Date:$ * @since IWS 1.0 */ public interface Notifications extends Observable { /** * For (almost) all notifications. this method should be invoked, since it * will ensure that the correct notification is persisted and send to the * notification queue. * * @param authentication Authentication information (user + group) * @param obj Instance to notify about changes for * @param type Type of Notification Message to send */ void notify(Authentication authentication, Notifiable obj, NotificationType type); /** * For the Forgot password functionality, we only have the {@code UserEntity} * Object at hand. * * @param user {@code UserEntity} Object */ void notify(UserEntity user); /** * Notify methods prepare jobs to be processed. The processing is invoked by this method * and creates tasks for consumers. It also trigger consumers */ void processJobs(); }
apache-2.0
KAMP-Research/KAMP4APS
edu.kit.ipd.sdq.kamp4aps.model.fieldofactivityannotations.tests/src/edu/kit/ipd/sdq/kamp4aps/model/fieldofactivityannotations/tests/ModuleDrawingTest.java
1667
/** */ package edu.kit.ipd.sdq.kamp4aps.model.fieldofactivityannotations.tests; import edu.kit.ipd.sdq.kamp4aps.model.fieldofactivityannotations.KAMP4aPSFieldofactivityannotationsFactory; import edu.kit.ipd.sdq.kamp4aps.model.fieldofactivityannotations.ModuleDrawing; import junit.textui.TestRunner; /** * <!-- begin-user-doc --> * A test case for the model object '<em><b>Module Drawing</b></em>'. * <!-- end-user-doc --> * @generated */ public class ModuleDrawingTest extends DrawingTest { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static void main(String[] args) { TestRunner.run(ModuleDrawingTest.class); } /** * Constructs a new Module Drawing test case with the given name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ModuleDrawingTest(String name) { super(name); } /** * Returns the fixture for this Module Drawing test case. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected ModuleDrawing getFixture() { return (ModuleDrawing)fixture; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see junit.framework.TestCase#setUp() * @generated */ @Override protected void setUp() throws Exception { setFixture(KAMP4aPSFieldofactivityannotationsFactory.eINSTANCE.createModuleDrawing()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see junit.framework.TestCase#tearDown() * @generated */ @Override protected void tearDown() throws Exception { setFixture(null); } } //ModuleDrawingTest
apache-2.0
xzcpp/coolweather
src/com/coolwealther/app/db/CoolWeatherOpenHelper.java
1293
package com.coolwealther.app.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class CoolWeatherOpenHelper extends SQLiteOpenHelper{ private static final String CREATE_PROVINCE = "create table Province (" + "id integer primary key autoincrement, " + "province_name text, " + "province_code text)"; private static final String CREATE_CITY = "create table City (" + "id integer primary key autoincrement, " + "city_name text, " + "city_code text)"; private static final String CREATE_COUNTY = "create table County (" + "id integer primary key autoincrement, " + "county_name text, " + "county_code text)"; @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL(CREATE_PROVINCE); db.execSQL(CREATE_CITY); db.execSQL(CREATE_COUNTY); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } public CoolWeatherOpenHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); // TODO Auto-generated constructor stub } }
apache-2.0
ngageoint/mrgeo
mrgeo-core/src/main/java/org/mrgeo/hdfs/vector/shp/esri/ShpFile.java
5189
/* * Copyright 2009-2017. DigitalGlobe, 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.mrgeo.hdfs.vector.shp.esri; import org.mrgeo.hdfs.vector.shp.SeekableDataInput; import org.mrgeo.hdfs.vector.shp.esri.geom.JShape; import org.mrgeo.hdfs.vector.shp.util.Convert; import java.io.IOException; import java.io.RandomAccessFile; /** * Internal class used by ESRILayer. If you're looking to read and write * shapefiles use ESRILayer instead. */ public class ShpFile { protected ShpData data; //protected String fileName = null; protected Header header; private SeekableDataInput in; private ShxFile index; private ESRILayer parent; /** * Creates new ShpFile */ protected ShpFile(ShxFile index, ESRILayer parent) { this.index = index; this.parent = parent; header = new Header(); } public void close() throws IOException { if (in != null) { in.close(); } } public void save(RandomAccessFile out) throws IOException { // write data if (index.offset.length > 0) { saveRows(out, index.getCachePos()); } // recalc header vars // calculate fileLength first (written in header) if (index.offset.length > 0) { int filePos = 0; if (index.cachepos == 0) { filePos = 100; } for (int j = 0; j < index.offset.length; j++) { // load geometry to get size JShape tempShape = data.getShape(j + index.cachepos); filePos += 8 + tempShape.getRecordLength(); } header.fileLength += filePos / 2; out.setLength(2 * header.fileLength); // write header out.seek(0); header.save(out); } } protected void load(SeekableDataInput sdi) throws IOException, FormatException { // save raf reference in = sdi; // read header in.seek(0); header.load(in); // initialize data interface switch (header.shapeType) { case JShape.POINT: data = new ShpPoint(index.recordCount); break; case JShape.POLYLINE: data = new ShpPolyLine(index.recordCount); break; case JShape.POLYGON: data = new ShpPolygon(index.recordCount); break; case JShape.POINTZ: data = new ShpPointZ(index.recordCount); break; case JShape.POLYLINEZ: data = new ShpPolyLineZ(index.recordCount); break; case JShape.POLYGONZ: data = new ShpPolygonZ(index.recordCount); break; default: throw new FormatException("Unhandled Shape Type: " + header.shapeType); } // set parent data.setParent(parent); // read data loadData(in, 0); } protected void loadData(int i) throws IOException, FormatException { if (header == null) { throw new IOException("Header never read. Cannot load!"); } loadData(in, i); } protected void loadRecord(SeekableDataInput is, int i) throws IOException, FormatException { // read record header byte[] recordHeader = new byte[8]; is.readFully(recordHeader, 0, 8); int recordNumber = Convert.getInteger(recordHeader, 0); if ((i + index.getCachePos() + 1) != recordNumber) { throw new FormatException("Unequal SHP Record Number Specification (" + recordNumber + ")"); } int contentLength = Convert.getInteger(recordHeader, 4); if (index.getContentLength(i + index.getCachePos()) != contentLength) { throw new FormatException("Unequal SHP/SHX Content Length Specification (" + contentLength + ")"); } byte[] record = new byte[contentLength * 2]; is.readFully(record, 0, contentLength * 2); // read geometry data.load(i, record); } private void loadData(SeekableDataInput is, int i) throws IOException, FormatException { //System.out.printf("cache size: %d", index.getCurrentCacheSize()); // resize data.resizeCache(index.getCurrentCacheSize()); int pos = index.getOffset(i); is.seek(pos * 2); // read data for (int j = 0; j < index.getCurrentCacheSize(); j++) { // initialize row data loadRecord(is, j); } } private void saveRows(RandomAccessFile os, int i) throws IOException { // write data int filePos = 100; int pos = index.getOffset(i); os.seek(pos * 2L); // loop for (int j = 0; j < index.getCurrentCacheSize(); j++) { // load geometry byte[] record = data.save(j); int contentLength = record.length / 2; // write record header byte[] recordHeader = new byte[8]; Convert.setInteger(recordHeader, 0, j + 1 + index.getCachePos()); // recordNumber Convert.setInteger(recordHeader, 4, contentLength); os.write(recordHeader, 0, recordHeader.length); index.offset[j] = filePos / 2; index.contentLength[j] = contentLength; filePos = filePos + 8; // write geometry os.write(record, 0, record.length); filePos = filePos + contentLength * 2; } } }
apache-2.0
nakamura5akihito/opensec-oval
src/main/java/io/opensec/oval/model/windows/GroupSidTest.java
3104
/** * Opensec OVAL - https://nakamura5akihito.github.io/ * Copyright (C) 2015 Akihito Nakamura * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.opensec.oval.model.windows; import io.opensec.oval.model.ComponentType; import io.opensec.oval.model.Family; import io.opensec.oval.model.common.CheckEnumeration; import io.opensec.oval.model.definitions.StateRefType; import io.opensec.oval.model.definitions.SystemObjectRefType; import io.opensec.oval.model.definitions.TestType; /** * The group_sid test allows the different users and subgroups, * that directly belong to specific groups (identified by SID), to be tested. * * @author Akihito Nakamura, AIST * @see <a href="http://oval.mitre.org/language/">OVAL Language</a> */ public class GroupSidTest extends TestType { /** * Constructor. */ public GroupSidTest() { this( null, 0 ); } public GroupSidTest( final String id, final int version ) { this( id, version, null, null ); } public GroupSidTest( final String id, final int version, final String comment, final CheckEnumeration check ) { this( id, version, comment, check, null, null ); } public GroupSidTest( final String id, final int version, final String comment, final CheckEnumeration check, final SystemObjectRefType object, final StateRefType[] stateList ) { super( id, version, comment, check, object, stateList ); // _oval_platform_type = OvalPlatformType.windows; // _oval_component_type = OvalComponentType.group_sid; _oval_family = Family.WINDOWS; _oval_component = ComponentType.GROUP_SID; } //************************************************************** // java.lang.Object //************************************************************** @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals( final Object obj ) { if (!(obj instanceof GroupSidTest)) { return false; } return super.equals( obj ); } @Override public String toString() { return "group_sid_test[" + super.toString() + "]"; } } //GroupSidTest
apache-2.0
dtag-dbu/task4java
com.task4java/src/com/task4java/http/client/RestClient.java
253
/* * Copyright (c) 2014 Andree Hagelstein, Maik Schulze, Deutsche Telekom AG. All Rights Reserved. * * Filename: RestClient.java */ package com.task4java.http.client; public class RestClient { public static IRestClient instance; }
apache-2.0
alt236/Bluetooth-LE-Library---Android
library/src/main/java/uk/co/alt236/bluetoothlelib/device/BluetoothLeDevice.java
13660
package uk.co.alt236.bluetoothlelib.device; import android.Manifest; import android.bluetooth.BluetoothDevice; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import androidx.annotation.Nullable; import androidx.annotation.RequiresPermission; import uk.co.alt236.bluetoothlelib.device.adrecord.AdRecordStore; import uk.co.alt236.bluetoothlelib.resolvers.BluetoothClassResolver; import uk.co.alt236.bluetoothlelib.util.AdRecordUtils; import uk.co.alt236.bluetoothlelib.util.ByteUtils; import uk.co.alt236.bluetoothlelib.util.LimitedLinkHashMap; // TODO: Auto-generated Javadoc /** * This is a wrapper around the default BluetoothDevice object * As BluetoothDevice is final it cannot be extended, so to get it you * need to call {@link #getDevice()} method. * * @author Alexandros Schillings */ public class BluetoothLeDevice implements Parcelable { /** * The Constant CREATOR. */ public static final Parcelable.Creator<BluetoothLeDevice> CREATOR = new Parcelable.Creator<BluetoothLeDevice>() { public BluetoothLeDevice createFromParcel(final Parcel in) { return new BluetoothLeDevice(in); } public BluetoothLeDevice[] newArray(final int size) { return new BluetoothLeDevice[size]; } }; protected static final int MAX_RSSI_LOG_SIZE = 10; private static final String PARCEL_EXTRA_BLUETOOTH_DEVICE = "bluetooth_device"; private static final String PARCEL_EXTRA_CURRENT_RSSI = "current_rssi"; private static final String PARCEL_EXTRA_CURRENT_TIMESTAMP = "current_timestamp"; private static final String PARCEL_EXTRA_DEVICE_RSSI_LOG = "device_rssi_log"; private static final String PARCEL_EXTRA_DEVICE_SCANRECORD = "device_scanrecord"; private static final String PARCEL_EXTRA_DEVICE_SCANRECORD_STORE = "device_scanrecord_store"; private static final String PARCEL_EXTRA_FIRST_RSSI = "device_first_rssi"; private static final String PARCEL_EXTRA_FIRST_TIMESTAMP = "first_timestamp"; private static final long LOG_INVALIDATION_THRESHOLD = 10 * 1000; private final AdRecordStore mRecordStore; private final BluetoothDevice mDevice; private final Map<Long, Integer> mRssiLog; private final byte[] mScanRecord; private final int mFirstRssi; private final long mFirstTimestamp; private int mCurrentRssi; private long mCurrentTimestamp; private transient Set<BluetoothService> mServiceSet; /** * Instantiates a new Bluetooth LE device. * * @param device a standard android Bluetooth device * @param rssi the RSSI value of the Bluetooth device * @param scanRecord the scan record of the device * @param timestamp the timestamp of the RSSI reading */ public BluetoothLeDevice(final BluetoothDevice device, final int rssi, final byte[] scanRecord, final long timestamp) { mDevice = device; mFirstRssi = rssi; mFirstTimestamp = timestamp; mRecordStore = new AdRecordStore(AdRecordUtils.parseScanRecordAsSparseArray(scanRecord)); mScanRecord = scanRecord; mRssiLog = new LimitedLinkHashMap<>(MAX_RSSI_LOG_SIZE); updateRssiReading(timestamp, rssi); } /** * Instantiates a new Bluetooth LE device. * * @param device the device */ public BluetoothLeDevice(final BluetoothLeDevice device) { mCurrentRssi = device.getRssi(); mCurrentTimestamp = device.getTimestamp(); mDevice = device.getDevice(); mFirstRssi = device.getFirstRssi(); mFirstTimestamp = device.getFirstTimestamp(); mRecordStore = new AdRecordStore( AdRecordUtils.parseScanRecordAsSparseArray(device.getScanRecord())); mRssiLog = device.getRssiLog(); mScanRecord = device.getScanRecord(); } /** * Instantiates a new bluetooth le device. * * @param in the in */ @SuppressWarnings("unchecked") protected BluetoothLeDevice(final Parcel in) { final Bundle b = in.readBundle(getClass().getClassLoader()); mCurrentRssi = b.getInt(PARCEL_EXTRA_CURRENT_RSSI, 0); mCurrentTimestamp = b.getLong(PARCEL_EXTRA_CURRENT_TIMESTAMP, 0); mDevice = b.getParcelable(PARCEL_EXTRA_BLUETOOTH_DEVICE); mFirstRssi = b.getInt(PARCEL_EXTRA_FIRST_RSSI, 0); mFirstTimestamp = b.getLong(PARCEL_EXTRA_FIRST_TIMESTAMP, 0); mRecordStore = b.getParcelable(PARCEL_EXTRA_DEVICE_SCANRECORD_STORE); mRssiLog = (Map<Long, Integer>) b.getSerializable(PARCEL_EXTRA_DEVICE_RSSI_LOG); mScanRecord = b.getByteArray(PARCEL_EXTRA_DEVICE_SCANRECORD); } /** * Adds the to rssi log. * * @param timestamp the timestamp * @param rssiReading the rssi reading */ private void addToRssiLog(final long timestamp, final int rssiReading) { synchronized (mRssiLog) { if (timestamp - mCurrentTimestamp > LOG_INVALIDATION_THRESHOLD) { mRssiLog.clear(); } mCurrentRssi = rssiReading; mCurrentTimestamp = timestamp; mRssiLog.put(timestamp, rssiReading); } } /* (non-Javadoc) * @see android.os.Parcelable#describeContents() */ @Override public int describeContents() { return 0; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final BluetoothLeDevice other = (BluetoothLeDevice) obj; if (mCurrentRssi != other.mCurrentRssi) return false; if (mCurrentTimestamp != other.mCurrentTimestamp) return false; if (mDevice == null) { if (other.mDevice != null) return false; } else if (!mDevice.equals(other.mDevice)) return false; if (mFirstRssi != other.mFirstRssi) return false; if (mFirstTimestamp != other.mFirstTimestamp) return false; if (mRecordStore == null) { if (other.mRecordStore != null) return false; } else if (!mRecordStore.equals(other.mRecordStore)) return false; if (mRssiLog == null) { if (other.mRssiLog != null) return false; } else if (!mRssiLog.equals(other.mRssiLog)) return false; if (!Arrays.equals(mScanRecord, other.mScanRecord)) return false; return true; } /** * Gets the ad record store. * * @return the ad record store */ public AdRecordStore getAdRecordStore() { return mRecordStore; } /** * Gets the address. * * @return the address */ public String getAddress() { return mDevice.getAddress(); } /** * Gets the bluetooth device bond state. * * @return the bluetooth device bond state */ @RequiresPermission(Manifest.permission.BLUETOOTH) public String getBluetoothDeviceBondState() { return resolveBondingState(mDevice.getBondState()); } /** * Gets the bluetooth device class name. * * @return the bluetooth device class name */ @RequiresPermission(Manifest.permission.BLUETOOTH) public String getBluetoothDeviceClassName() { return BluetoothClassResolver.resolveDeviceClass(mDevice.getBluetoothClass().getDeviceClass()); } @RequiresPermission(Manifest.permission.BLUETOOTH) public Set<BluetoothService> getBluetoothDeviceKnownSupportedServices() { if (mServiceSet == null) { synchronized (this) { if (mServiceSet == null) { final Set<BluetoothService> serviceSet = new HashSet<>(); for (final BluetoothService service : BluetoothService.values()) { if (mDevice.getBluetoothClass().hasService(service.getAndroidConstant())) { serviceSet.add(service); } } mServiceSet = Collections.unmodifiableSet(serviceSet); } } } return mServiceSet; } /** * Gets the bluetooth device major class name. * * @return the bluetooth device major class name */ @RequiresPermission(Manifest.permission.BLUETOOTH) public String getBluetoothDeviceMajorClassName() { return BluetoothClassResolver.resolveMajorDeviceClass(mDevice.getBluetoothClass().getMajorDeviceClass()); } /** * Gets the device. * * @return the device */ public BluetoothDevice getDevice() { return mDevice; } /** * Gets the first rssi. * * @return the first rssi */ public int getFirstRssi() { return mFirstRssi; } /** * Gets the first timestamp. * * @return the first timestamp */ public long getFirstTimestamp() { return mFirstTimestamp; } /** * Gets the name. * * @return the name */ @RequiresPermission(Manifest.permission.BLUETOOTH) @Nullable public String getName() { return mDevice.getName(); } /** * Gets the rssi. * * @return the rssi */ public int getRssi() { return mCurrentRssi; } /** * Gets the rssi log. * * @return the rssi log */ protected Map<Long, Integer> getRssiLog() { synchronized (mRssiLog) { return mRssiLog; } } /** * Gets the running average rssi. * * @return the running average rssi */ public double getRunningAverageRssi() { int sum = 0; int count = 0; synchronized (mRssiLog) { for (final Long aLong : mRssiLog.keySet()) { count++; sum += mRssiLog.get(aLong); } } if (count > 0) { return sum / count; } else { return 0; } } /** * Gets the scan record. * * @return the scan record */ public byte[] getScanRecord() { return mScanRecord; } /** * Gets the timestamp. * * @return the timestamp */ public long getTimestamp() { return mCurrentTimestamp; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + mCurrentRssi; result = prime * result + (int) (mCurrentTimestamp ^ (mCurrentTimestamp >>> 32)); result = prime * result + ((mDevice == null) ? 0 : mDevice.hashCode()); result = prime * result + mFirstRssi; result = prime * result + (int) (mFirstTimestamp ^ (mFirstTimestamp >>> 32)); result = prime * result + ((mRecordStore == null) ? 0 : mRecordStore.hashCode()); result = prime * result + ((mRssiLog == null) ? 0 : mRssiLog.hashCode()); result = prime * result + Arrays.hashCode(mScanRecord); return result; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override @RequiresPermission(Manifest.permission.BLUETOOTH) public String toString() { return "BluetoothLeDevice [mDevice=" + mDevice + ", mRssi=" + mFirstRssi + ", mScanRecord=" + ByteUtils.byteArrayToHexString(mScanRecord) + ", mRecordStore=" + mRecordStore + ", getBluetoothDeviceBondState()=" + getBluetoothDeviceBondState() + ", getBluetoothDeviceClassName()=" + getBluetoothDeviceClassName() + "]"; } /** * Update rssi reading. * * @param timestamp the timestamp * @param rssiReading the rssi reading */ public void updateRssiReading(final long timestamp, final int rssiReading) { addToRssiLog(timestamp, rssiReading); } /* (non-Javadoc) * @see android.os.Parcelable#writeToParcel(android.os.Parcel, int) */ @Override public void writeToParcel(final Parcel parcel, final int arg1) { final Bundle b = new Bundle(getClass().getClassLoader()); b.putByteArray(PARCEL_EXTRA_DEVICE_SCANRECORD, mScanRecord); b.putInt(PARCEL_EXTRA_FIRST_RSSI, mFirstRssi); b.putInt(PARCEL_EXTRA_CURRENT_RSSI, mCurrentRssi); b.putLong(PARCEL_EXTRA_FIRST_TIMESTAMP, mFirstTimestamp); b.putLong(PARCEL_EXTRA_CURRENT_TIMESTAMP, mCurrentTimestamp); b.putParcelable(PARCEL_EXTRA_BLUETOOTH_DEVICE, mDevice); b.putParcelable(PARCEL_EXTRA_DEVICE_SCANRECORD_STORE, mRecordStore); b.putSerializable(PARCEL_EXTRA_DEVICE_RSSI_LOG, (Serializable) mRssiLog); parcel.writeBundle(b); } /** * Resolve bonding state. * * @param bondState the bond state * @return the string */ private static String resolveBondingState(final int bondState) { switch (bondState) { case BluetoothDevice.BOND_BONDED: return "Paired"; case BluetoothDevice.BOND_BONDING: return "Pairing"; case BluetoothDevice.BOND_NONE: return "Unbonded"; default: return "Unknown"; } } }
apache-2.0
weifengbao/joyfulmongo
src/main/java/com/joyfulmongo/controller/JFSignupController.java
1416
/* * Copyright 2014 Weifeng Bao * * 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.joyfulmongo.controller; import com.joyfulmongo.db.JFMongoCmdResult; import com.joyfulmongo.db.JFMongoCmdSignup; import com.joyfulmongo.db.JFMongoUser; import org.json.JSONObject; public class JFSignupController extends JFController<JFSignupInput, JFSignupOutput> { @Override public JFSignupOutput process(JFSignupInput input) { JSONObject payload = input.getData(); String username = input.getUsername(); String password = input.getPassword(); JFMongoCmdSignup cmd = new JFMongoCmdSignup(payload, username, password); JFMongoCmdResult commandResult = cmd.invoke(); String sessionToken = JFMongoUser.generateSessionToken(); JFSignupOutput result = new JFSignupOutput(sessionToken, commandResult); return result; } }
apache-2.0
huangyugui/springboot-dubbo-test
application-test/src/main/java/com/huang/thread/atomic/StopThread.java
647
package com.huang.thread.atomic; import java.util.concurrent.TimeUnit; public class StopThread { /** * @param args */ private static boolean stopRequested; public static void main(String[] args) throws InterruptedException { Thread backgroundThread = new Thread(new Runnable() { public void run() { int i = 0; while (!stopRequested) { i++; } } }); backgroundThread.start(); TimeUnit.SECONDS.sleep(1); stopRequested = true; System.out.println("stopRequested = true"); } }
apache-2.0
JaySoyer/Advanced-Adapters
app/src/main/java/com/sawyer/advadapters/app/adapters/jsonadapter/JSONAdapterFragment.java
5204
/* * Copyright 2014 Jay Soyer * * 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.sawyer.advadapters.app.adapters.jsonadapter; import android.app.Activity; import android.app.ListFragment; import android.os.Bundle; import android.util.Log; import android.view.ActionMode; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.ListAdapter; import android.widget.ListView; import com.sawyer.advadapters.app.R; import com.sawyer.advadapters.app.ToastHelper; import org.json.JSONArray; import org.json.JSONException; public class JSONAdapterFragment extends ListFragment { private static final String STATE_CAB_CHECKED_COUNT = "State Cab Checked Count"; private static final String STATE_LIST = "State List"; private int mCheckedCount; private EventListener mEventListener; public static JSONAdapterFragment newInstance() { return new JSONAdapterFragment(); } @Override public MovieJSONAdapter getListAdapter() { return (MovieJSONAdapter) super.getListAdapter(); } @Override public void setListAdapter(ListAdapter adapter) { if (adapter instanceof MovieJSONAdapter) { super.setListAdapter(adapter); } else { throw new ClassCastException( "Adapter must be of type " + MovieJSONAdapter.class.getSimpleName()); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getListView().setAdapter(getListAdapter()); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (activity instanceof EventListener) { mEventListener = (EventListener) activity; } else { throw new ClassCastException( "Activity must implement " + EventListener.class.getSimpleName()); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { mCheckedCount = savedInstanceState.getInt(STATE_CAB_CHECKED_COUNT); try { JSONArray list = new JSONArray(savedInstanceState.getString(STATE_LIST)); setListAdapter(new MovieJSONAdapter(getActivity(), list)); } catch (JSONException e) { Log.e(JSONAdapterFragment.class.getSimpleName(), "OnRestore Error", e); mCheckedCount = 0; setListAdapter(new MovieJSONAdapter(getActivity())); } } else { setListAdapter(new MovieJSONAdapter(getActivity())); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ListView lv = (ListView) inflater.inflate(R.layout.listview, container, false); lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); lv.setMultiChoiceModeListener(new OnCabMultiChoiceModeListener()); return lv; } @Override public void onListItemClick(ListView l, View v, int position, long id) { ToastHelper.showItemUpdatesNotSupported(getActivity()); } private void onRemoveItemsClicked() { ToastHelper.showRemoveNotSupported(getActivity()); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(STATE_LIST, getListAdapter().getJSONArray().toString()); outState.putInt(STATE_CAB_CHECKED_COUNT, mCheckedCount); } public interface EventListener { public void onAdapterCountUpdated(); } private class OnCabMultiChoiceModeListener implements AbsListView.MultiChoiceModeListener { @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { boolean result; switch (item.getItemId()) { case R.id.menu_context_remove: onRemoveItemsClicked(); mode.finish(); result = true; break; default: result = false; break; } if (result && mEventListener != null) { mEventListener.onAdapterCountUpdated(); } return result; } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.cab_jsonarray, menu); mode.setTitle(mCheckedCount + getString(R.string.desc_selected)); return true; } @Override public void onDestroyActionMode(ActionMode mode) { mCheckedCount = 0; } @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { if (checked) { ++mCheckedCount; } else { --mCheckedCount; } mode.setTitle(mCheckedCount + getString(R.string.desc_selected)); } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } } }
apache-2.0
nopbyte/compose-idm
src/main/java/de/passau/uni/sec/compose/id/rest/controller/ServiceObjectCommandsController.java
6599
package de.passau.uni.sec.compose.id.rest.controller; import java.util.Collection; import java.util.LinkedList; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.util.UriComponentsBuilder; import de.passau.uni.sec.compose.id.common.exception.IdManagementException; import de.passau.uni.sec.compose.id.core.domain.IPrincipal; import de.passau.uni.sec.compose.id.core.event.CreateServiceObjectEvent; import de.passau.uni.sec.compose.id.core.event.DeleteServiceObjectEvent; import de.passau.uni.sec.compose.id.core.event.UpdateServiceObjectTokenEvent; import de.passau.uni.sec.compose.id.core.service.ServiceObjectService; import de.passau.uni.sec.compose.id.core.service.security.RestAuthentication; import de.passau.uni.sec.compose.id.rest.messages.AuthenticatedEmptyMessage; import de.passau.uni.sec.compose.id.rest.messages.EntityResponseMessage; import de.passau.uni.sec.compose.id.rest.messages.ServiceObjectCreateMessage; import de.passau.uni.sec.compose.id.rest.messages.ServiceObjectResponseMessage; import de.passau.uni.sec.compose.id.rest.messages.ServiceObjectTokenUpdateMessage; @Controller @RequestMapping("/idm/serviceobject") public class ServiceObjectCommandsController { private static Logger LOG = LoggerFactory.getLogger(ServiceObjectCommandsController.class); @Autowired private ServiceObjectService soService; @Autowired private RestAuthentication authenticator; /** * Create a new user * @param message containing the new user * @return userCreatedMessage with the appropiate data or an error otherwise */ @RequestMapping(value = "/", method = RequestMethod.POST, consumes = "application/json") @ResponseBody public ResponseEntity<Object> createUser( @Valid @RequestBody ServiceObjectCreateMessage message,UriComponentsBuilder builder,HttpServletRequest req) { HttpHeaders headers = new HttpHeaders(); Collection<String> cred = new LinkedList<String>(); cred.add(message.getAuthorization()); try{ //This method just authenticates... it doesn't do access control Collection<IPrincipal> principals = authenticator.authenticatePrincipals(LOG,cred); ServiceObjectResponseMessage res = (ServiceObjectResponseMessage) soService.createEntity(new CreateServiceObjectEvent(message,principals)); headers.setLocation( builder.path( req.getServletPath()+"/{id}") .buildAndExpand(res.getId()).toUri()); return new ResponseEntity<Object>(res, headers, HttpStatus.CREATED); } catch(IdManagementException idm){ //since the creation of the exception generated the log entries for the stacktrace, we don't do it again here return new ResponseEntity<Object>(idm.getErrorAsMap(), headers, HttpStatus.valueOf(idm.getHTTPErrorCode())); } catch(Exception e) { String s = IdManagementException.getStackTrace(e); LOG.error(s); return new ResponseEntity<Object>(null, headers, HttpStatus.INTERNAL_SERVER_ERROR); } } @RequestMapping(value="/{Id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) @ResponseBody public ResponseEntity<Object> DeteEntity( @Valid @RequestBody AuthenticatedEmptyMessage message, @RequestHeader("If-Unmodified-Since") long lastKnownUpdate, @PathVariable(value="Id") String uid) { HttpHeaders headers = new HttpHeaders(); Collection<String> cred = new LinkedList<String>(); cred.add(message.getAuthorization()); try{ Collection<IPrincipal> principals = authenticator.authenticatePrincipals(LOG,cred); soService.deleteEntity(new DeleteServiceObjectEvent(uid,principals,lastKnownUpdate)); return new ResponseEntity<Object>(null, headers, HttpStatus.OK); } catch(IdManagementException idm){ //since the creation of the exception generated the log entries for the stacktrace, we don't do it again here return new ResponseEntity<Object>(idm.getErrorAsMap(), headers, HttpStatus.valueOf(idm.getHTTPErrorCode())); }catch(Exception e) { String s = IdManagementException.getStackTrace(e); LOG.error(s); return new ResponseEntity<Object>(null, headers, HttpStatus.INTERNAL_SERVER_ERROR); } } @RequestMapping(value="/{Id}/api_token", method = RequestMethod.PUT) @ResponseBody public ResponseEntity<Object> UpdateTokenEntity( @Valid @RequestBody ServiceObjectTokenUpdateMessage message, @RequestHeader("If-Unmodified-Since") long lastKnownUpdate, @PathVariable(value="Id") String uid) { HttpHeaders headers = new HttpHeaders(); Collection<String> cred = new LinkedList<String>(); cred.add(message.getAuthorization()); try{ Collection<IPrincipal> principals = authenticator.authenticatePrincipals(LOG,cred); EntityResponseMessage res = soService.updateEntity(new UpdateServiceObjectTokenEvent(uid,message,principals,lastKnownUpdate)); return new ResponseEntity<Object>(res, headers, HttpStatus.OK); } catch(IdManagementException idm){ //since the creation of the exception generated the log entries for the stacktrace, we don't do it again here return new ResponseEntity<Object>(idm.getErrorAsMap(), headers, HttpStatus.valueOf(idm.getHTTPErrorCode())); }catch(Exception e) { String s = IdManagementException.getStackTrace(e); LOG.error(s); return new ResponseEntity<Object>(null, headers, HttpStatus.INTERNAL_SERVER_ERROR); } } }
apache-2.0
phax/ph-oton
ph-oton-security/src/test/java/com/helger/photon/security/object/accarea/AccountingAreaTest.java
4010
/* * Copyright (C) 2014-2022 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.photon.security.object.accarea; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import java.util.Locale; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import com.helger.masterdata.address.EPostalAddressType; import com.helger.masterdata.address.PostalAddress; import com.helger.masterdata.currency.ECurrency; import com.helger.photon.app.mock.PhotonAppWebTestRule; import com.helger.photon.security.object.tenant.Tenant; import com.helger.tenancy.tenant.ITenant; import com.helger.xml.mock.XMLTestHelper; /** * Test class for class {@link AccountingArea} * * @author Philip Helger */ public final class AccountingAreaTest { @Rule public final TestRule m_aRule = new PhotonAppWebTestRule (); @Test public void testBasic () { final ITenant aTenant = new Tenant ("anyid", "Mock tenant"); final PostalAddress aAddress = new PostalAddress (EPostalAddressType.PERSONAL, "AT", "Wien", "1234", "Vienna", "Test street", "123", "PO1", "co", Locale.GERMANY); final AccountingArea a = new AccountingArea (aTenant, "Accounting area 1", "GmbH", "ATU00000000", "company number", "debtor number", aAddress, "54321", "12345", "any@example.org", "http://www.helger.com", ECurrency.ISK, "Wien", "ABC", "Wien2", Locale.GERMANY); assertSame (aTenant, a.getTenant ()); assertEquals ("Accounting area 1", a.getDisplayName ()); assertEquals ("GmbH", a.getCompanyType ()); assertEquals ("ATU00000000", a.getCompanyVATIN ()); assertEquals ("company number", a.getCompanyNumber ()); assertEquals (aAddress, a.getAddress ()); assertEquals ("54321", a.getTelephone ()); assertEquals ("12345", a.getFax ()); assertEquals ("any@example.org", a.getEmailAddress ()); assertEquals ("http://www.helger.com", a.getWebSite ()); assertSame (ECurrency.ISK, a.getDefaultCurrency ()); assertEquals ("Wien", a.getOfficeLocation ()); assertEquals ("ABC", a.getCommercialRegistrationNumber ()); assertEquals ("Wien2", a.getCommercialCourt ()); XMLTestHelper.testMicroTypeConversion (a); } }
apache-2.0
snuk182/aceim
icq/src/main/java/aceim/protocol/snuk182/icq/inner/dataentity/ICBMMessage.java
1340
package aceim.protocol.snuk182.icq.inner.dataentity; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; public class ICBMMessage implements Serializable { /** * */ private static final long serialVersionUID = 7486438674845449876L; public String text; public String senderId; public String receiverId; public short channel = 0; public byte[] messageId = new byte[8]; public TLV[] tlvs; public String capability; public Date sendingTime; public Date receivingTime; public byte messageType; public byte[] pluginSpecificData; public String rvIp; public String internalIp; public String externalIp; public int externalPort; public String invitation; public short rvMessageType = 0; public final List<ICQFileInfo> files = new LinkedList<ICQFileInfo>(); public boolean connectFTProxy = false; public boolean connectFTPeer = false; public List<File> getFileList() { if (files.size() < 1) { return null; } List<File> ff = new ArrayList<File>(files.size()); for (ICQFileInfo file : files) { if (file.filename != null) { File f = new File(file.filename); if (f.exists()) { ff.add(f); } } } return ff; } }
apache-2.0
zhangzuoqiang/summer
src/main/java/cn/limw/summer/open/ApiMeta.java
1255
package cn.limw.summer.open; /** * @author li * @version 1 (2014年9月5日 下午5:46:25) * @since Java7 */ public class ApiMeta { private String appId; private String appKey; private String appSecret; private String redirectUri; private String token; private String url; public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getAppSecret() { return appSecret; } public void setAppSecret(String appSecret) { this.appSecret = appSecret; } public String getRedirectUri() { return redirectUri; } public void setRedirectUri(String redirectUri) { this.redirectUri = redirectUri; } public String getUrl() { return url; } public void setUrl(String openSite) { this.url = openSite; } public String getAppKey() { return appKey; } public void setAppKey(String appKey) { this.appKey = appKey; } }
apache-2.0
visallo/visallo
web/client-api/src/main/java/org/visallo/web/clientapi/model/ClientApiOntology.java
18179
package org.visallo.web.clientapi.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonSetter; import java.util.*; public class ClientApiOntology implements ClientApiObject { private List<Concept> concepts = new ArrayList<Concept>(); private List<Property> properties = new ArrayList<Property>(); private List<Relationship> relationships = new ArrayList<Relationship>(); public List<Concept> getConcepts() { return concepts; } public List<Property> getProperties() { return properties; } public List<Relationship> getRelationships() { return relationships; } public void addAllConcepts(Collection<Concept> concepts) { this.concepts.addAll(concepts); } public void addAllProperties(Collection<Property> properties) { this.properties.addAll(properties); } public void addAllRelationships(Collection<Relationship> relationships) { this.relationships.addAll(relationships); } public ClientApiOntology merge( Collection<Concept> mergeConcepts, Collection<Property> mergeProperties, Collection<Relationship> mergeRelationships) { ClientApiOntology copy = new ClientApiOntology(); mergeCollections(copy.getConcepts(), concepts, mergeConcepts); mergeCollections(copy.getProperties(), properties, mergeProperties); mergeCollections(copy.getRelationships(), relationships, mergeRelationships); return copy; } private <T extends OntologyId> void mergeCollections(Collection<T> newList, Collection<T> old, Collection<T> merge) { if (merge == null || merge.size() == 0) { newList.addAll(old); } else { List<T> unmerged = new ArrayList<T>(); unmerged.addAll(merge); for (T existing : old) { String existingIri = existing.getTitle(); T update = existing; for (T unmergedObject : unmerged) { if (unmergedObject.getTitle().equals(existingIri)) { update = unmergedObject; unmerged.remove(unmergedObject); break; } } newList.add(update); } newList.addAll(unmerged); } } interface OntologyId { String getTitle(); } public static class Concept implements ClientApiObject, OntologyId { private String id; private String title; private String displayName; private String displayType; private String titleFormula; private String subtitleFormula; private String timeFormula; private String parentConcept; private String pluralDisplayName; private Boolean userVisible; private Boolean searchable; private String glyphIconHref; private String glyphIconSelectedHref; private String color; private Boolean deleteable; private Boolean updateable; private List<String> intents = new ArrayList<String>(); private List<String> addRelatedConceptWhiteList = new ArrayList<String>(); private List<String> properties = new ArrayList<String>(); private Map<String, String> metadata = new HashMap<String, String>(); private SandboxStatus sandboxStatus; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getDisplayType() { return displayType; } public void setDisplayType(String displayType) { this.displayType = displayType; } public String getTitleFormula() { return titleFormula; } public void setTitleFormula(String titleFormula) { this.titleFormula = titleFormula; } public String getSubtitleFormula() { return subtitleFormula; } public void setSubtitleFormula(String subtitleFormula) { this.subtitleFormula = subtitleFormula; } public String getTimeFormula() { return timeFormula; } public void setTimeFormula(String timeFormula) { this.timeFormula = timeFormula; } public String getParentConcept() { return parentConcept; } public void setParentConcept(String parentConcept) { this.parentConcept = parentConcept; } public String getPluralDisplayName() { return pluralDisplayName; } public void setPluralDisplayName(String pluralDisplayName) { this.pluralDisplayName = pluralDisplayName; } public Boolean getUserVisible() { return userVisible; } public void setUserVisible(Boolean userVisible) { this.userVisible = userVisible; } public Boolean getSearchable() { return searchable; } public void setSearchable(Boolean searchable) { this.searchable = searchable; } public String getGlyphIconHref() { return glyphIconHref; } public void setGlyphIconHref(String glyphIconHref) { this.glyphIconHref = glyphIconHref; } public String getGlyphIconSelectedHref() { return glyphIconSelectedHref; } public void setGlyphIconSelectedHref(String glyphIconSelectedHref) { this.glyphIconSelectedHref = glyphIconSelectedHref; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public Boolean getUpdateable() { return updateable; } public void setUpdateable(Boolean updateable) { this.updateable = updateable; } public Boolean getDeleteable() { return deleteable; } public void setDeleteable(Boolean deleteable) { this.deleteable = deleteable; } @JsonInclude(JsonInclude.Include.NON_EMPTY) public Map<String, String> getMetadata() { return metadata; } @JsonInclude(JsonInclude.Include.NON_EMPTY) public List<String> getAddRelatedConceptWhiteList() { return addRelatedConceptWhiteList; } public List<String> getProperties() { return properties; } @JsonInclude(JsonInclude.Include.NON_EMPTY) public List<String> getIntents() { return intents; } public SandboxStatus getSandboxStatus() { return sandboxStatus; } public void setSandboxStatus(SandboxStatus sandboxStatus) { this.sandboxStatus = sandboxStatus; } } public static class Property implements ClientApiObject, OntologyId { private String title; private String displayName; private boolean userVisible; private boolean searchable; private boolean addable; private boolean sortable; private Integer sortPriority; private PropertyType dataType; private String displayType; private String propertyGroup; private Map<String, String> possibleValues = new HashMap<String, String>(); private String validationFormula; private String displayFormula; private String[] dependentPropertyIris; private boolean deleteable; private boolean updateable; private List<String> intents = new ArrayList<String>(); private List<String> textIndexHints = new ArrayList<String>(); private Map<String, String> metadata = new HashMap<String, String>(); private SandboxStatus sandboxStatus; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public boolean isUserVisible() { return userVisible; } public void setUserVisible(boolean userVisible) { this.userVisible = userVisible; } public boolean isSearchable() { return searchable; } public void setSearchable(boolean searchable) { this.searchable = searchable; } public boolean isAddable() { return addable; } public void setAddable(boolean addable) { this.addable = addable; } public boolean isSortable() { return sortable; } public void setSortable(boolean sortable) { this.sortable = sortable; } public Integer getSortPriority() { return sortPriority; } public void setSortPriority(Integer sortPriority) { this.sortPriority = sortPriority; } public boolean isUpdateable() { return updateable; } public void setUpdateable(boolean updateable) { this.updateable = updateable; } public boolean isDeleteable() { return deleteable; } public void setDeleteable(boolean deleteable) { this.deleteable = deleteable; } public PropertyType getDataType() { return dataType; } public void setDataType(PropertyType dataType) { this.dataType = dataType; } public String getDisplayType() { return displayType; } public void setDisplayType(String displayType) { this.displayType = displayType; } public String getPropertyGroup() { return propertyGroup; } public void setPropertyGroup(String propertyGroup) { this.propertyGroup = propertyGroup; } @JsonInclude(JsonInclude.Include.NON_EMPTY) public Map<String, String> getPossibleValues() { return possibleValues; } public void setValidationFormula(String validationFormula) { this.validationFormula = validationFormula; } public String getValidationFormula() { return validationFormula; } public void setDisplayFormula(String displayFormula) { this.displayFormula = displayFormula; } public String getDisplayFormula() { return displayFormula; } @JsonSetter public void setDependentPropertyIris(String[] dependentPropertyIris) { this.dependentPropertyIris = dependentPropertyIris; } public void setDependentPropertyIris(Collection<String> dependentPropertyIris) { if (dependentPropertyIris == null || dependentPropertyIris.size() == 0) { this.dependentPropertyIris = null; } else { this.dependentPropertyIris = dependentPropertyIris.toArray(new String[dependentPropertyIris.size()]); } } public String[] getDependentPropertyIris() { return dependentPropertyIris; } @JsonInclude(JsonInclude.Include.NON_EMPTY) public Map<String, String> getMetadata() { return metadata; } @JsonInclude(JsonInclude.Include.NON_EMPTY) public List<String> getIntents() { return intents; } @JsonInclude(JsonInclude.Include.NON_EMPTY) public List<String> getTextIndexHints() { return textIndexHints; } public SandboxStatus getSandboxStatus() { return sandboxStatus; } public void setSandboxStatus(SandboxStatus sandboxStatus) { this.sandboxStatus = sandboxStatus; } } public static class ExtendedDataTableProperty extends Property { private String titleFormula; private String subtitleFormula; private String timeFormula; private List<String> tablePropertyIris = new ArrayList<String>(); public String getTitleFormula() { return titleFormula; } public void setTitleFormula(String titleFormula) { this.titleFormula = titleFormula; } public String getSubtitleFormula() { return subtitleFormula; } public void setSubtitleFormula(String subtitleFormula) { this.subtitleFormula = subtitleFormula; } public String getTimeFormula() { return timeFormula; } public void setTimeFormula(String timeFormula) { this.timeFormula = timeFormula; } public void setTablePropertyIris(List<String> tablePropertyIris) { this.tablePropertyIris.clear(); this.tablePropertyIris.addAll(tablePropertyIris); } public List<String> getTablePropertyIris() { return tablePropertyIris; } } public static class Relationship implements ClientApiObject, OntologyId { private String parentIri; private String title; private String displayName; private Boolean userVisible; private Boolean updateable; private Boolean deleteable; private String titleFormula; private String subtitleFormula; private String timeFormula; private List<String> domainConceptIris = new ArrayList<String>(); private List<String> rangeConceptIris = new ArrayList<String>(); private List<InverseOf> inverseOfs = new ArrayList<InverseOf>(); private List<String> intents = new ArrayList<String>(); private List<String> properties = new ArrayList<String>(); private Map<String, String> metadata = new HashMap<String, String>(); private SandboxStatus sandboxStatus; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getParentIri() { return parentIri; } public void setParentIri(String parentIri) { this.parentIri = parentIri; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public List<String> getDomainConceptIris() { return domainConceptIris; } public void setDomainConceptIris(List<String> domainConceptIris) { this.domainConceptIris = domainConceptIris; } public List<String> getRangeConceptIris() { return rangeConceptIris; } public void setRangeConceptIris(List<String> rangeConceptIris) { this.rangeConceptIris = rangeConceptIris; } public Boolean getUserVisible() { return userVisible; } public void setUserVisible(Boolean userVisible) { this.userVisible = userVisible; } public Boolean getUpdateable() { return updateable; } public void setUpdateable(Boolean updateable) { this.updateable = updateable; } public Boolean getDeleteable() { return deleteable; } public void setDeleteable(Boolean deleteable) { this.deleteable = deleteable; } public List<String> getProperties() { return properties; } public void setProperties(List<String> properties) { this.properties = properties; } public String getTitleFormula() { return titleFormula; } public void setTitleFormula(String titleFormula) { this.titleFormula = titleFormula; } public String getSubtitleFormula() { return subtitleFormula; } public void setSubtitleFormula(String subtitleFormula) { this.subtitleFormula = subtitleFormula; } public String getTimeFormula() { return timeFormula; } public void setTimeFormula(String timeFormula) { this.timeFormula = timeFormula; } @JsonInclude(JsonInclude.Include.NON_EMPTY) public List<InverseOf> getInverseOfs() { return inverseOfs; } @JsonInclude(JsonInclude.Include.NON_EMPTY) public List<String> getIntents() { return intents; } @JsonInclude(JsonInclude.Include.NON_EMPTY) public Map<String, String> getMetadata() { return metadata; } public SandboxStatus getSandboxStatus() { return sandboxStatus; } public void setSandboxStatus(SandboxStatus sandboxStatus) { this.sandboxStatus = sandboxStatus; } public static class InverseOf { private String iri; private String primaryIri; public String getIri() { return iri; } public void setIri(String iri) { this.iri = iri; } public String getPrimaryIri() { return primaryIri; } public void setPrimaryIri(String primaryIri) { this.primaryIri = primaryIri; } } } }
apache-2.0
Taskana/taskana
lib/taskana-core/src/test/java/acceptance/config/TaskanaConfigAccTest.java
4468
package acceptance.config; import static org.assertj.core.api.Assertions.assertThat; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import pro.taskana.TaskanaEngineConfiguration; import pro.taskana.common.test.config.DataSourceGenerator; /** Test taskana configuration without roles. */ class TaskanaConfigAccTest { @TempDir Path tempDir; private TaskanaEngineConfiguration taskanaEngineConfiguration; @BeforeEach void setup() { taskanaEngineConfiguration = new TaskanaEngineConfiguration( DataSourceGenerator.getDataSource(), true, DataSourceGenerator.getSchemaName()); } @Test void should_ConfigureDomains_For_DefaultPropertiesFile() { assertThat(taskanaEngineConfiguration.getDomains()) .containsExactlyInAnyOrder("DOMAIN_A", "DOMAIN_B"); } @Test void should_ConfigureClassificationTypes_For_DefaultPropertiesFile() { assertThat(taskanaEngineConfiguration.getClassificationTypes()) .containsExactlyInAnyOrder("TASK", "DOCUMENT"); } @Test void should_ConfigureClassificationCategories_For_DefaultPropertiesFile() { assertThat(taskanaEngineConfiguration.getClassificationCategoriesByType("TASK")) .containsExactlyInAnyOrder("EXTERNAL", "MANUAL", "AUTOMATIC", "PROCESS"); } @Test void should_NotConfigureClassificationTypes_When_PropertiesAreNotDefined() throws Exception { String propertiesFileName = createNewConfigFile("dummyTestConfig1.properties", false, true); String delimiter = ";"; taskanaEngineConfiguration = new TaskanaEngineConfiguration( DataSourceGenerator.getDataSource(), true, true, propertiesFileName, delimiter, DataSourceGenerator.getSchemaName()); assertThat(taskanaEngineConfiguration.getClassificationTypes()).isEmpty(); } @Test void should_NotConfigureClassificationCategories_When_PropertiesAreNotDefined() throws Exception { String propertiesFileName = createNewConfigFile("dummyTestConfig2.properties", true, false); String delimiter = ";"; taskanaEngineConfiguration = new TaskanaEngineConfiguration( DataSourceGenerator.getDataSource(), true, true, propertiesFileName, delimiter, DataSourceGenerator.getSchemaName()); assertThat(taskanaEngineConfiguration.getClassificationCategoriesByTypeMap()) .containsExactly( Map.entry("TASK", Collections.emptyList()), Map.entry("DOCUMENT", Collections.emptyList())); } @Test void should_ApplyClassificationProperties_When_PropertiesAreDefined() throws Exception { String propertiesFileName = createNewConfigFile("dummyTestConfig3.properties", true, true); String delimiter = ";"; taskanaEngineConfiguration = new TaskanaEngineConfiguration( DataSourceGenerator.getDataSource(), true, true, propertiesFileName, delimiter, DataSourceGenerator.getSchemaName()); assertThat(taskanaEngineConfiguration.getClassificationCategoriesByTypeMap()) .containsExactly( Map.entry("TASK", List.of("EXTERNAL", "MANUAL", "AUTOMATIC", "PROCESS")), Map.entry("DOCUMENT", List.of("EXTERNAL"))); } private String createNewConfigFile( String filename, boolean addingTypes, boolean addingClassification) throws Exception { Path file = Files.createFile(tempDir.resolve(filename)); List<String> lines = Stream.of( "taskana.roles.admin =Holger|Stefan", "taskana.roles.businessadmin = ebe | konstantin ", "taskana.roles.user = nobody") .collect(Collectors.toList()); if (addingTypes) { lines.add("taskana.classification.types= TASK , document"); } if (addingClassification) { lines.add("taskana.classification.categories.task= EXTERNAL, manual, autoMAtic, Process"); lines.add("taskana.classification.categories.document= EXTERNAL"); } Files.write(file, lines, StandardCharsets.UTF_8); return file.toString(); } }
apache-2.0
yuzhongyousida/struts-2.3.1.2
src/plugins/javatemplates/src/main/java/org/apache/struts2/views/java/simple/SubmitHandler.java
4026
/* * $Id: SubmitHandler.java 1084872 2011-03-24 08:11:57Z mcucchiara $ * * 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.struts2.views.java.simple; import org.apache.struts2.views.java.TagGenerator; import org.apache.struts2.views.java.Attributes; import org.apache.commons.lang.StringUtils; import java.io.IOException; import java.util.Map; public class SubmitHandler extends AbstractTagHandler implements TagGenerator { public void generate() throws IOException { Map<String, Object> params = context.getParameters(); Attributes attrs = new Attributes(); String type = StringUtils.defaultString((String) params.get("type"), "input"); if ("button".equals(type)) { attrs.addIfExists("name", params.get("name")) .add("type", "submit") .addIfExists("value", params.get("nameValue")) .addIfTrue("disabled", params.get("disabled")) .addIfExists("tabindex", params.get("tabindex")) .addIfExists("id", params.get("id")) .addIfExists("class", params.get("cssClass")) .addIfExists("style", params.get("cssStyle")); start("button", attrs); } else if ("image".equals(type)) { attrs.addIfExists("src", params.get("src")) .add("type", "image") .addIfExists("alt", params.get("label")) .addIfExists("id", params.get("id")) .addIfExists("class", params.get("cssClass")) .addIfExists("style", params.get("cssStyle")); start("input", attrs); } else { attrs.addIfExists("name", params.get("name")) .add("type", "submit") .addIfExists("value", params.get("nameValue")) .addIfTrue("disabled", params.get("disabled")) .addIfExists("tabindex", params.get("tabindex")) .addIfExists("id", params.get("id")) .addIfExists("class", params.get("cssClass")) .addIfExists("style", params.get("cssStyle")); start("input", attrs); } } public static class CloseHandler extends AbstractTagHandler implements TagGenerator { public void generate() throws IOException { Map<String, Object> params = context.getParameters(); String body = (String) params.get("body"); String type = StringUtils.defaultString((String) params.get("type"), "input"); if ("button".equals(type)) { //button body if (StringUtils.isNotEmpty(body)) characters(body, false); else if (params.containsKey("label")) { String label = (String) params.get("label"); if (StringUtils.isNotEmpty(label)) characters(label, false); } end("button"); } else if ("image".equals(type)) { if (StringUtils.isNotEmpty(body)) characters(body, false); end("input"); } else end("input"); } } }
apache-2.0
twosigma/beaker-notebook
kernel/base/src/main/java/com/twosigma/beakerx/chart/serializer/HeatMapSerializer.java
2697
/* * Copyright 2014 TWO SIGMA OPEN SOURCE, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twosigma.beakerx.chart.serializer; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.twosigma.beakerx.chart.heatmap.HeatMap; import java.io.IOException; import static com.twosigma.beakerx.chart.heatmap.HeatMap.COLUMN_LIMIT; import static com.twosigma.beakerx.chart.heatmap.HeatMap.NUMBER_OF_NODES_LIMIT; import static com.twosigma.beakerx.chart.heatmap.HeatMap.ROWS_LIMIT; public class HeatMapSerializer extends AbstractChartSerializer<HeatMap> { public static final String GRAPHICS_LIST = "graphics_list"; public static final String COLOR = "color"; public static final String ITEMS = " items"; private HeatMapReducer heatMapReducer = new HeatMapReducer(COLUMN_LIMIT, ROWS_LIMIT); @Override public void serialize(HeatMap heatmap, JsonGenerator jgen, SerializerProvider sp) throws IOException { jgen.writeStartObject(); serialize(heatmap, jgen); if (heatmap.getData() == null) { jgen.writeObjectField(GRAPHICS_LIST, heatmap.getData()); jgen.writeObjectField(TOTAL_NUMBER_OF_POINTS, 0); jgen.writeBooleanField(TOO_MANY_ROWS, false); } else { serializeData(heatmap.getData(), jgen); } jgen.writeObjectField(COLOR, heatmap.getColor()); jgen.writeEndObject(); } private void serializeData(Number[][] data, JsonGenerator jgen) throws IOException { int totalPoints = HeatMapReducer.totalPoints(data); boolean tooManyPoints = totalPoints > NUMBER_OF_NODES_LIMIT; if (tooManyPoints) { Number[][] limitedHeatMapData = heatMapReducer.limitHeatmap(data); jgen.writeObjectField(GRAPHICS_LIST, limitedHeatMapData); jgen.writeObjectField(ROWS_LIMIT_ITEMS, NUMBER_OF_NODES_LIMIT); jgen.writeObjectField(NUMBER_OF_POINTS_TO_DISPLAY, HeatMapReducer.totalPoints(limitedHeatMapData) + ITEMS); } else { jgen.writeObjectField(GRAPHICS_LIST, data); } jgen.writeObjectField(TOTAL_NUMBER_OF_POINTS, totalPoints); jgen.writeBooleanField(TOO_MANY_ROWS, tooManyPoints); } }
apache-2.0
McLeodMoores/starling
projects/engine/src/main/java/com/opengamma/engine/cache/CachingFudgeMessageStore.java
3723
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.engine.cache; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.fudgemsg.FudgeMsg; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.opengamma.util.ehcache.EHCacheUtils; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; /** * Caches Fudge message objects on top of another Fudge message store. This is an in-memory cache. */ public class CachingFudgeMessageStore implements FudgeMessageStore { private static final Logger LOGGER = LoggerFactory.getLogger(CachingFudgeMessageStore.class); private final FudgeMessageStore _underlying; private final CacheManager _cacheManager; private final Cache _cache; public CachingFudgeMessageStore(final FudgeMessageStore underlying, final CacheManager cacheManager, final ViewComputationCacheKey cacheKey) { _underlying = underlying; _cacheManager = cacheManager; final String cacheName = cacheKey.toString(); EHCacheUtils.addCache(cacheManager, cacheKey.toString()); _cache = EHCacheUtils.getCacheFromManager(cacheManager, cacheName); } protected FudgeMessageStore getUnderlying() { return _underlying; } protected CacheManager getCacheManager() { return _cacheManager; } protected Cache getCache() { return _cache; } @Override public void delete() { LOGGER.info("Delete on {}", this); getCacheManager().removeCache(getCache().getName()); getUnderlying().delete(); } @Override public FudgeMsg get(final long identifier) { final Element cacheElement = getCache().get(identifier); if (cacheElement != null) { return (FudgeMsg) cacheElement.getObjectValue(); } final FudgeMsg data = getUnderlying().get(identifier); getCache().put(new Element(identifier, data)); return data; } @Override public void put(final long identifier, final FudgeMsg data) { getUnderlying().put(identifier, data); getCache().put(new Element(identifier, data)); } @Override public String toString() { return "CachingFudgeMessageStore[" + getCache().getName() + "]"; } @Override public Map<Long, FudgeMsg> get(final Collection<Long> identifiers) { final Map<Long, FudgeMsg> result = new HashMap<>(); final List<Long> missing = new ArrayList<>(identifiers.size()); for (final Long identifier : identifiers) { final Element cacheElement = getCache().get(identifier); if (cacheElement != null) { result.put(identifier, (FudgeMsg) cacheElement.getObjectValue()); } else { missing.add(identifier); } } if (missing.isEmpty()) { return result; } if (missing.size() == 1) { final Long missingIdentifier = missing.get(0); final FudgeMsg data = getUnderlying().get(missingIdentifier); result.put(missingIdentifier, data); getCache().put(new Element(missingIdentifier, data)); } else { final Map<Long, FudgeMsg> missingData = getUnderlying().get(missing); for (final Map.Entry<Long, FudgeMsg> data : missingData.entrySet()) { result.put(data.getKey(), data.getValue()); getCache().put(new Element(data.getKey(), data.getValue())); } } return result; } @Override public void put(final Map<Long, FudgeMsg> data) { getUnderlying().put(data); for (final Map.Entry<Long, FudgeMsg> element : data.entrySet()) { getCache().put(new Element(element.getKey(), element.getValue())); } } }
apache-2.0
orioncode/orionplatform
orion_math/orion_math_core/src/main/java/com/orionplatform/math/geometry/point/tasks/check/ArePointsCoplanarTask.java
1524
package com.orionplatform.math.geometry.point.tasks.check; import com.orionplatform.core.abstraction.Orion; import com.orionplatform.math.geometry.point.Point; import com.orionplatform.math.geometry.point.PointRules; import com.orionplatform.math.geometry.vector.Vector; import com.orionplatform.math.linearalgebra.matrix.Matrix; import com.orionplatform.math.number.ANumber; import com.orionplatform.math.number.precision.Precision; public class ArePointsCoplanarTask extends Orion { public static synchronized boolean run(int precision, Point... points) { if(points != null) { if(points.length < 4) { return true; } else { precision = Precision.getValidPrecision(precision); PointRules.doDimensionsMatch(points); int dimensions = points[0].getDimensions(); ANumber[][] elements = new ANumber[points.length - 1][dimensions]; for(int i = 0; i < points.length - 1; i++) { Vector vector = Vector.of(points[0], points[i + 1]); for(int j = 0; j < dimensions; j++) { elements[i][j] = vector.get(j); } } return Matrix.of(elements).getRank().isLessThanOrEqual(2); } } return false; } }
apache-2.0
AttwellBrian/RxJava
src/test/java/io/reactivex/internal/operators/observable/ObservableWindowWithObservableTest.java
18408
/** * Copyright (c) 2016-present, RxJava 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 io.reactivex.internal.operators.observable; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import io.reactivex.*; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.exceptions.*; import io.reactivex.functions.Function; import io.reactivex.internal.functions.Functions; import io.reactivex.observers.*; import io.reactivex.subjects.*; public class ObservableWindowWithObservableTest { @Test public void testWindowViaObservableNormal1() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> boundary = PublishSubject.create(); final Observer<Object> o = TestHelper.mockObserver(); final List<Observer<Object>> values = new ArrayList<Observer<Object>>(); Observer<Observable<Integer>> wo = new DefaultObserver<Observable<Integer>>() { @Override public void onNext(Observable<Integer> args) { final Observer<Object> mo = TestHelper.mockObserver(); values.add(mo); args.subscribe(mo); } @Override public void onError(Throwable e) { o.onError(e); } @Override public void onComplete() { o.onComplete(); } }; source.window(boundary).subscribe(wo); int n = 30; for (int i = 0; i < n; i++) { source.onNext(i); if (i % 3 == 2 && i < n - 1) { boundary.onNext(i / 3); } } source.onComplete(); verify(o, never()).onError(any(Throwable.class)); assertEquals(n / 3, values.size()); int j = 0; for (Observer<Object> mo : values) { verify(mo, never()).onError(any(Throwable.class)); for (int i = 0; i < 3; i++) { verify(mo).onNext(j + i); } verify(mo).onComplete(); j += 3; } verify(o).onComplete(); } @Test public void testWindowViaObservableBoundaryCompletes() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> boundary = PublishSubject.create(); final Observer<Object> o = TestHelper.mockObserver(); final List<Observer<Object>> values = new ArrayList<Observer<Object>>(); Observer<Observable<Integer>> wo = new DefaultObserver<Observable<Integer>>() { @Override public void onNext(Observable<Integer> args) { final Observer<Object> mo = TestHelper.mockObserver(); values.add(mo); args.subscribe(mo); } @Override public void onError(Throwable e) { o.onError(e); } @Override public void onComplete() { o.onComplete(); } }; source.window(boundary).subscribe(wo); int n = 30; for (int i = 0; i < n; i++) { source.onNext(i); if (i % 3 == 2 && i < n - 1) { boundary.onNext(i / 3); } } boundary.onComplete(); assertEquals(n / 3, values.size()); int j = 0; for (Observer<Object> mo : values) { for (int i = 0; i < 3; i++) { verify(mo).onNext(j + i); } verify(mo).onComplete(); verify(mo, never()).onError(any(Throwable.class)); j += 3; } verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } @Test public void testWindowViaObservableBoundaryThrows() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> boundary = PublishSubject.create(); final Observer<Object> o = TestHelper.mockObserver(); final List<Observer<Object>> values = new ArrayList<Observer<Object>>(); Observer<Observable<Integer>> wo = new DefaultObserver<Observable<Integer>>() { @Override public void onNext(Observable<Integer> args) { final Observer<Object> mo = TestHelper.mockObserver(); values.add(mo); args.subscribe(mo); } @Override public void onError(Throwable e) { o.onError(e); } @Override public void onComplete() { o.onComplete(); } }; source.window(boundary).subscribe(wo); source.onNext(0); source.onNext(1); source.onNext(2); boundary.onError(new TestException()); assertEquals(1, values.size()); Observer<Object> mo = values.get(0); verify(mo).onNext(0); verify(mo).onNext(1); verify(mo).onNext(2); verify(mo).onError(any(TestException.class)); verify(o, never()).onComplete(); verify(o).onError(any(TestException.class)); } @Test public void testWindowViaObservableSourceThrows() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> boundary = PublishSubject.create(); final Observer<Object> o = TestHelper.mockObserver(); final List<Observer<Object>> values = new ArrayList<Observer<Object>>(); Observer<Observable<Integer>> wo = new DefaultObserver<Observable<Integer>>() { @Override public void onNext(Observable<Integer> args) { final Observer<Object> mo = TestHelper.mockObserver(); values.add(mo); args.subscribe(mo); } @Override public void onError(Throwable e) { o.onError(e); } @Override public void onComplete() { o.onComplete(); } }; source.window(boundary).subscribe(wo); source.onNext(0); source.onNext(1); source.onNext(2); source.onError(new TestException()); assertEquals(1, values.size()); Observer<Object> mo = values.get(0); verify(mo).onNext(0); verify(mo).onNext(1); verify(mo).onNext(2); verify(mo).onError(any(TestException.class)); verify(o, never()).onComplete(); verify(o).onError(any(TestException.class)); } @Test public void testWindowNoDuplication() { final PublishSubject<Integer> source = PublishSubject.create(); final TestObserver<Integer> tsw = new TestObserver<Integer>() { boolean once; @Override public void onNext(Integer t) { if (!once) { once = true; source.onNext(2); } super.onNext(t); } }; TestObserver<Observable<Integer>> ts = new TestObserver<Observable<Integer>>() { @Override public void onNext(Observable<Integer> t) { t.subscribe(tsw); super.onNext(t); } }; source.window(new Callable<Observable<Object>>() { @Override public Observable<Object> call() { return Observable.never(); } }).subscribe(ts); source.onNext(1); source.onComplete(); ts.assertValueCount(1); tsw.assertValues(1, 2); } @Test public void testWindowViaObservableNoUnsubscribe() { Observable<Integer> source = Observable.range(1, 10); Callable<Observable<String>> boundary = new Callable<Observable<String>>() { @Override public Observable<String> call() { return Observable.empty(); } }; TestObserver<Observable<Integer>> ts = new TestObserver<Observable<Integer>>(); source.window(boundary).subscribe(ts); // 2.0.2 - not anymore // assertTrue("Not cancelled!", ts.isCancelled()); ts.assertComplete(); } @Test public void testBoundaryUnsubscribedOnMainCompletion() { PublishSubject<Integer> source = PublishSubject.create(); final PublishSubject<Integer> boundary = PublishSubject.create(); Callable<Observable<Integer>> boundaryFunc = new Callable<Observable<Integer>>() { @Override public Observable<Integer> call() { return boundary; } }; TestObserver<Observable<Integer>> ts = new TestObserver<Observable<Integer>>(); source.window(boundaryFunc).subscribe(ts); assertTrue(source.hasObservers()); assertTrue(boundary.hasObservers()); source.onComplete(); assertFalse(source.hasObservers()); assertFalse(boundary.hasObservers()); ts.assertComplete(); ts.assertNoErrors(); ts.assertValueCount(1); } @Test public void testMainUnsubscribedOnBoundaryCompletion() { PublishSubject<Integer> source = PublishSubject.create(); final PublishSubject<Integer> boundary = PublishSubject.create(); Callable<Observable<Integer>> boundaryFunc = new Callable<Observable<Integer>>() { @Override public Observable<Integer> call() { return boundary; } }; TestObserver<Observable<Integer>> ts = new TestObserver<Observable<Integer>>(); source.window(boundaryFunc).subscribe(ts); assertTrue(source.hasObservers()); assertTrue(boundary.hasObservers()); boundary.onComplete(); // FIXME source still active because the open window assertTrue(source.hasObservers()); assertFalse(boundary.hasObservers()); ts.assertComplete(); ts.assertNoErrors(); ts.assertValueCount(1); } @Test public void testChildUnsubscribed() { PublishSubject<Integer> source = PublishSubject.create(); final PublishSubject<Integer> boundary = PublishSubject.create(); Callable<Observable<Integer>> boundaryFunc = new Callable<Observable<Integer>>() { @Override public Observable<Integer> call() { return boundary; } }; TestObserver<Observable<Integer>> ts = new TestObserver<Observable<Integer>>(); source.window(boundaryFunc).subscribe(ts); assertTrue(source.hasObservers()); assertTrue(boundary.hasObservers()); ts.dispose(); // FIXME source has subscribers because the open window assertTrue(source.hasObservers()); // FIXME boundary has subscribers because the open window assertTrue(boundary.hasObservers()); ts.assertNotComplete(); ts.assertNoErrors(); ts.assertValueCount(1); } @Test public void newBoundaryCalledAfterWindowClosed() { final AtomicInteger calls = new AtomicInteger(); PublishSubject<Integer> source = PublishSubject.create(); final PublishSubject<Integer> boundary = PublishSubject.create(); Callable<Observable<Integer>> boundaryFunc = new Callable<Observable<Integer>>() { @Override public Observable<Integer> call() { calls.getAndIncrement(); return boundary; } }; TestObserver<Observable<Integer>> ts = new TestObserver<Observable<Integer>>(); source.window(boundaryFunc).subscribe(ts); source.onNext(1); boundary.onNext(1); assertTrue(boundary.hasObservers()); source.onNext(2); boundary.onNext(2); assertTrue(boundary.hasObservers()); source.onNext(3); boundary.onNext(3); assertTrue(boundary.hasObservers()); source.onNext(4); source.onComplete(); ts.assertNoErrors(); ts.assertValueCount(4); ts.assertComplete(); assertFalse(source.hasObservers()); assertFalse(boundary.hasObservers()); } @Test public void boundaryDispose() { TestHelper.checkDisposed(Observable.never().window(Observable.never())); } @Test public void boundaryDispose2() { TestHelper.checkDisposed(Observable.never().window(Functions.justCallable(Observable.never()))); } @Test public void boundaryOnError() { TestObserver<Object> to = Observable.error(new TestException()) .window(Observable.never()) .flatMap(Functions.<Observable<Object>>identity(), true) .test() .assertFailure(CompositeException.class); List<Throwable> errors = TestHelper.compositeList(to.errors().get(0)); TestHelper.assertError(errors, 0, TestException.class); } @Test public void mainError() { Observable.error(new TestException()) .window(Functions.justCallable(Observable.never())) .test() .assertError(TestException.class); } @Test public void innerBadSource() { TestHelper.checkBadSourceObservable(new Function<Observable<Integer>, Object>() { @Override public Object apply(Observable<Integer> o) throws Exception { return Observable.just(1).window(o).flatMap(new Function<Observable<Integer>, ObservableSource<Integer>>() { @Override public ObservableSource<Integer> apply(Observable<Integer> v) throws Exception { return v; } }); } }, false, 1, 1, (Object[])null); TestHelper.checkBadSourceObservable(new Function<Observable<Integer>, Object>() { @Override public Object apply(Observable<Integer> o) throws Exception { return Observable.just(1).window(Functions.justCallable(o)).flatMap(new Function<Observable<Integer>, ObservableSource<Integer>>() { @Override public ObservableSource<Integer> apply(Observable<Integer> v) throws Exception { return v; } }); } }, false, 1, 1, (Object[])null); } @Test public void reentrant() { final Subject<Integer> ps = PublishSubject.<Integer>create(); TestObserver<Integer> to = new TestObserver<Integer>() { @Override public void onNext(Integer t) { super.onNext(t); if (t == 1) { ps.onNext(2); ps.onComplete(); } } }; ps.window(BehaviorSubject.createDefault(1)) .flatMap(new Function<Observable<Integer>, ObservableSource<Integer>>() { @Override public ObservableSource<Integer> apply(Observable<Integer> v) throws Exception { return v; } }) .subscribe(to); ps.onNext(1); to .awaitDone(1, TimeUnit.SECONDS) .assertResult(1, 2); } @Test public void reentrantCallable() { final Subject<Integer> ps = PublishSubject.<Integer>create(); TestObserver<Integer> to = new TestObserver<Integer>() { @Override public void onNext(Integer t) { super.onNext(t); if (t == 1) { ps.onNext(2); ps.onComplete(); } } }; ps.window(new Callable<Observable<Integer>>() { boolean once; @Override public Observable<Integer> call() throws Exception { if (!once) { once = true; return BehaviorSubject.createDefault(1); } return Observable.never(); } }) .flatMap(new Function<Observable<Integer>, ObservableSource<Integer>>() { @Override public ObservableSource<Integer> apply(Observable<Integer> v) throws Exception { return v; } }) .subscribe(to); ps.onNext(1); to .awaitDone(1, TimeUnit.SECONDS) .assertResult(1, 2); } @Test public void badSource() { TestHelper.checkBadSourceObservable(new Function<Observable<Object>, Object>() { @Override public Object apply(Observable<Object> o) throws Exception { return o.window(Observable.never()).flatMap(new Function<Observable<Object>, ObservableSource<Object>>() { @Override public ObservableSource<Object> apply(Observable<Object> v) throws Exception { return v; } }); } }, false, 1, 1, 1); } @Test public void badSourceCallable() { TestHelper.checkBadSourceObservable(new Function<Observable<Object>, Object>() { @Override public Object apply(Observable<Object> o) throws Exception { return o.window(Functions.justCallable(Observable.never())).flatMap(new Function<Observable<Object>, ObservableSource<Object>>() { @Override public ObservableSource<Object> apply(Observable<Object> v) throws Exception { return v; } }); } }, false, 1, 1, 1); } }
apache-2.0
GIP-RECIA/esco-grouper-ui
ext/bundles/myfaces-api/src/main/java/javax/faces/component/UIComponentBase.java
40695
/** * Copyright (C) 2009 GIP RECIA http://www.recia.fr * @Author (C) 2009 GIP RECIA <contact@recia.fr> * @Contributor (C) 2009 SOPRA http://www.sopragroup.com/ * @Contributor (C) 2011 Pierre Legay <pierre.legay@recia.fr> * * 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. */ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package javax.faces.component; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.faces.FactoryFinder; import javax.faces.context.FacesContext; import javax.faces.el.ValueBinding; import javax.faces.event.AbortProcessingException; import javax.faces.event.FacesEvent; import javax.faces.event.FacesListener; import javax.faces.render.RenderKit; import javax.faces.render.RenderKitFactory; import javax.faces.render.Renderer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Standard implementation of the UIComponent base class; all standard JSF * components extend this class. * <p> * <i>Disclaimer</i>: The official definition for the behaviour of * this class is the JSF 1.1 specification but for legal reasons the * specification cannot be replicated here. Any javadoc here therefore * describes the current implementation rather than the spec, though * this class has been verified as correctly implementing the spec. * * see Javadoc of <a href="http://java.sun.com/j2ee/javaserverfaces/1.1_01/docs/api/index.html">JSF Specification</a> for more. * * @author Manfred Geiler (latest modification by $Author: grantsmith $) * @version $Revision: 472555 $ $Date: 2006-11-08 18:30:58 +0100 (Mi, 08 Nov 2006) $ */ public abstract class UIComponentBase extends UIComponent { private static Log log = LogFactory.getLog(UIComponentBase.class); private _ComponentAttributesMap _attributesMap = null; private Map _valueBindingMap = null; private List _childrenList = null; private Map _facetMap = null; private List _facesListeners = null; private String _clientId = null; private String _id = null; private UIComponent _parent = null; private boolean _transient = false; public UIComponentBase() { } /** * Get a map through which all the UIComponent's properties, value-bindings * and non-property attributes can be read and written. * <p> * When writing to the returned map: * <ul> * <li>If this component has an explicit property for the specified key * then the setter method is called. An IllegalArgumentException is * thrown if the property is read-only. If the property is readable * then the old value is returned, otherwise null is returned. * <li>Otherwise the key/value pair is stored in a map associated with * the component. * </ul> * Note that value-bindings are <i>not</i> written by put calls to this map. * Writing to the attributes map using a key for which a value-binding * exists will just store the value in the attributes map rather than * evaluating the binding, effectively "hiding" the value-binding from * later attributes.get calls. Setter methods on components commonly do * <i>not</i> evaluate a binding of the same name; they just store the * provided value directly on the component. * <p> * When reading from the returned map: * <ul> * <li>If this component has an explicit property for the specified key * then the getter method is called. If the property exists, but is * read-only (ie only a setter method is defined) then an * IllegalArgumentException is thrown. * <li>If the attribute map associated with the component has an entry * with the specified key, then that is returned. * <li>If this component has a value-binding for the specified key, then * the value-binding is evaluated to fetch the value. * <li>Otherwise, null is returned. * </ul> * Note that components commonly define getter methods such that they * evaluate a value-binding of the same name if there isn't yet a * local property. * <p> * Assigning values to the map which are not explicit properties on * the underlying component can be used to "tunnel" attributes from * the JSP tag (or view-specific equivalent) to the associated renderer * without modifying the component itself. * <p> * Any value-bindings and non-property attributes stored in this map * are automatically serialized along with the component when the view * is serialized. */ public Map getAttributes() { if (_attributesMap == null) { _attributesMap = new _ComponentAttributesMap(this); } return _attributesMap; } /** * Get the named value-binding associated with this component. * <p> * Value-bindings are stored in a map associated with the component, * though there is commonly a property (setter/getter methods) * of the same name defined on the component itself which * evaluates the value-binding when called. */ public ValueBinding getValueBinding(String name) { if (name == null) throw new NullPointerException("name"); if (_valueBindingMap == null) { return null; } else { return (ValueBinding)_valueBindingMap.get(name); } } /** * Put the provided value-binding into a map of value-bindings * associated with this component. */ public void setValueBinding(String name, ValueBinding binding) { if (name == null) throw new NullPointerException("name"); if (_valueBindingMap == null) { _valueBindingMap = new HashMap(); } _valueBindingMap.put(name, binding); } /** * Get a string which can be output to the response which uniquely * identifies this UIComponent within the current view. * <p> * The component should have an id attribute already assigned to it; * however if the id property is currently null then a unique id * is generated and set for this component. This only happens when * components are programmatically created without ids, as components * created by a ViewHandler should be assigned ids when they are created. * <p> * If this component is a descendant of a NamingContainer then the * client id is of form "{namingContainerId}:{componentId}". Note that * the naming container's id may itself be of compound form if it has * an ancestor naming container. Note also that this only applies to * naming containers; other UIComponent types in the component's * ancestry do not affect the clientId. * <p> * Finally the renderer associated with this component is asked to * convert the id into a suitable form. This allows escaping of any * characters in the clientId which are significant for the markup * language generated by that renderer. */ public String getClientId(FacesContext context) { if (context == null) throw new NullPointerException("context"); if (_clientId != null) return _clientId; boolean idWasNull = false; String id = getId(); if (id == null) { //Although this is an error prone side effect, we automatically create a new id //just to be compatible to the RI UIViewRoot viewRoot = context.getViewRoot(); if (viewRoot != null) { id = viewRoot.createUniqueId(); } else { context.getExternalContext().log("ERROR: Cannot automatically create an id for component of type " + getClass().getName() + " because there is no viewRoot in the current facesContext!"); id = "ERROR"; } setId(id); //We remember that the id was null and log a warning down below idWasNull = true; } UIComponent namingContainer = _ComponentUtils.findParentNamingContainer(this, false); if (namingContainer != null) { _clientId = namingContainer.getClientId(context) + NamingContainer.SEPARATOR_CHAR + id; } else { _clientId = id; } Renderer renderer = getRenderer(context); if (renderer != null) { _clientId = renderer.convertClientId(context, _clientId); } if (idWasNull) { context.getExternalContext().log("WARNING: Component " + _clientId + " just got an automatic id, because there was no id assigned yet. " + "If this component was created dynamically (i.e. not by a JSP tag) you should assign it an " + "explicit static id or assign it the id you get from the createUniqueId from the current UIViewRoot " + "component right after creation!"); } return _clientId; } /** * Get a string which uniquely identifies this UIComponent within the * scope of the nearest ancestor NamingContainer component. The id is * not necessarily unique across all components in the current view. */ public String getId() { return _id; } /** * Set an identifier for this component which is unique within the * scope of the nearest ancestor NamingContainer component. The id is * not necessarily unique across all components in the current view. * <p> * The id must start with an underscore if it is generated by the JSF * framework, and must <i>not</i> start with an underscore if it has * been specified by the user (eg in a JSP tag). * <p> * The first character of the id must be an underscore or letter. * Following characters may be letters, digits, underscores or dashes. * <p> * Null is allowed as a parameter, and will reset the id to null. * <p> * The clientId of this component is reset by this method; see * getClientId for more info. * * @throws IllegalArgumentException if the id is not valid. */ public void setId(String id) { isIdValid(id); _id = id; _clientId = null; } public UIComponent getParent() { return _parent; } public void setParent(UIComponent parent) { _parent = parent; } /** * Indicates whether this component or its renderer manages the * invocation of the rendering methods of its child components. * When this is true: * <ul> * <li>This component's encodeBegin method will only be called * after all the child components have been created and added * to this component. * <li>This component's encodeChildren method will be called * after its encodeBegin method. Components for which this * method returns false do not get this method invoked at all. * <li>No rendering methods will be called automatically on * child components; this component is required to invoke the * encodeBegin/encodeEnd/etc on them itself. * </ul> */ public boolean getRendersChildren() { Renderer renderer = getRenderer(getFacesContext()); if (renderer != null) { return renderer.getRendersChildren(); } else { return false; } } /** * Return a list of the UIComponent objects which are direct children * of this component. * <p> * The list object returned has some non-standard behaviour: * <ul> * <li>The list is type-checked; only UIComponent objects can be added. * <li>If a component is added to the list with an id which is the same * as some other component in the list then an exception is thrown. However * multiple components with a null id may be added. * <li>The component's parent property is set to this component. If the * component already had a parent, then the component is first removed * from its original parent's child list. * </ul> */ public List getChildren() { if (_childrenList == null) { _childrenList = new _ComponentChildrenList(this); } return _childrenList; } /** * Return the number of direct child components this component has. * <p> * Identical to getChildren().size() except that when this component * has no children this method will not force an empty list to be * created. */ public int getChildCount() { return _childrenList == null ? 0 : _childrenList.size(); } /** * Standard method for finding other components by id, inherited by * most UIComponent objects. * <p> * The lookup is performed in a manner similar to finding a file * in a filesystem; there is a "base" at which to start, and the * id can be for something in the "local directory", or can include * a relative path. Here, NamingContainer components fill the role * of directories, and ":" is the "path separator". Note, however, * that although components have a strict parent/child hierarchy, * component ids are only prefixed ("namespaced") with the id of * their parent when the parent is a NamingContainer. * <p> * The base node at which the search starts is determined as * follows: * <ul> * <li>When expr starts with ':', the search starts with the root * component of the tree that this component is in (ie the ancestor * whose parent is null). * <li>Otherwise, if this component is a NamingContainer then the search * starts with this component. * <li>Otherwise, the search starts from the nearest ancestor * NamingContainer (or the root component if there is no NamingContainer * ancestor). * </ul> * * @param expr is of form "id1:id2:id3". * @return UIComponent or null if no component with the specified id is * found. */ public UIComponent findComponent(String expr) { if (expr == null) throw new NullPointerException("expr"); if (expr.length() == 0) throw new IllegalArgumentException("empty expr"); //TODO: not specified! UIComponent findBase; if (expr.charAt(0) == NamingContainer.SEPARATOR_CHAR) { findBase = _ComponentUtils.getRootComponent(this); expr = expr.substring(1); } else { if (this instanceof NamingContainer) { findBase = this; } else { findBase = _ComponentUtils.findParentNamingContainer(this, true /* root if not found */); } } int separator = expr.indexOf(NamingContainer.SEPARATOR_CHAR); if (separator == -1) { return _ComponentUtils.findComponent(findBase, expr); } else { String id = expr.substring(0, separator); findBase = _ComponentUtils.findComponent(findBase, id); if (findBase == null) { return null; } else { if (!(findBase instanceof NamingContainer)) throw new IllegalArgumentException("Intermediate identifier " + id + " in search expression " + expr + " identifies a UIComponent that is not a NamingContainer"); return findBase.findComponent(expr.substring(separator + 1)); } } } public Map getFacets() { if (_facetMap == null) { _facetMap = new _ComponentFacetMap(this); } return _facetMap; } public UIComponent getFacet(String name) { return _facetMap == null ? null : (UIComponent)_facetMap.get(name); } public Iterator getFacetsAndChildren() { return new _FacetsAndChildrenIterator(_facetMap, _childrenList); } /** * Invoke any listeners attached to this object which are listening * for an event whose type matches the specified event's runtime * type. * <p> * This method does not propagate the event up to parent components, * ie listeners attached to parent components don't automatically * get called. * <p> * If any of the listeners throws AbortProcessingException then * that exception will prevent any further listener callbacks * from occurring, and the exception propagates out of this * method without alteration. * <p> * ActionEvent events are typically queued by the renderer associated * with this component in its decode method; ValueChangeEvent events by * the component's validate method. In either case the event's source * property references a component. At some later time the UIViewRoot * component iterates over its queued events and invokes the broadcast * method on each event's source object. * * @param event must not be null. */ public void broadcast(FacesEvent event) throws AbortProcessingException { if (event == null) throw new NullPointerException("event"); if (_facesListeners == null) return; for (Iterator it = _facesListeners.iterator(); it.hasNext(); ) { FacesListener facesListener = (FacesListener)it.next(); if (event.isAppropriateListener(facesListener)) { event.processListener(facesListener); } } } /** * Check the submitted form parameters for data associated with this * component. This default implementation delegates to this component's * renderer if there is one, and otherwise ignores the call. */ public void decode(FacesContext context) { if (context == null) throw new NullPointerException("context"); Renderer renderer = getRenderer(context); if (renderer != null) { renderer.decode(context, this); } } public void encodeBegin(FacesContext context) throws IOException { if (context == null) throw new NullPointerException("context"); if (!isRendered()) return; Renderer renderer = getRenderer(context); if (renderer != null) { renderer.encodeBegin(context, this); } } public void encodeChildren(FacesContext context) throws IOException { if (context == null) throw new NullPointerException("context"); if (!isRendered()) return; Renderer renderer = getRenderer(context); if (renderer != null) { renderer.encodeChildren(context, this); } } public void encodeEnd(FacesContext context) throws IOException { if (context == null) throw new NullPointerException("context"); if (!isRendered()) return; Renderer renderer = getRenderer(context); if (renderer != null) { renderer.encodeEnd(context, this); } } protected void addFacesListener(FacesListener listener) { if (listener == null) throw new NullPointerException("listener"); if (_facesListeners == null) { _facesListeners = new ArrayList(); } _facesListeners.add(listener); } protected FacesListener[] getFacesListeners(Class clazz) { if (_facesListeners == null) { return (FacesListener[])Array.newInstance(clazz, 0); } List lst = null; for (Iterator it = _facesListeners.iterator(); it.hasNext(); ) { FacesListener facesListener = (FacesListener)it.next(); if (clazz.isAssignableFrom(facesListener.getClass())) { if (lst == null) lst = new ArrayList(); lst.add(facesListener); } } if (lst == null) { return (FacesListener[])Array.newInstance(clazz, 0); } else { return (FacesListener[])lst.toArray((FacesListener[])Array.newInstance(clazz, lst.size())); } } protected void removeFacesListener(FacesListener listener) { if (_facesListeners != null) { _facesListeners.remove(listener); } } public void queueEvent(FacesEvent event) { if (event == null) throw new NullPointerException("event"); UIComponent parent = getParent(); if (parent == null) { throw new IllegalStateException("component is not a descendant of a UIViewRoot"); } parent.queueEvent(event); } public void processDecodes(FacesContext context) { if (context == null) throw new NullPointerException("context"); if (!isRendered()) return; for (Iterator it = getFacetsAndChildren(); it.hasNext(); ) { UIComponent childOrFacet = (UIComponent)it.next(); childOrFacet.processDecodes(context); } try { decode(context); } catch (RuntimeException e) { context.renderResponse(); throw e; } } public void processValidators(FacesContext context) { if (context == null) throw new NullPointerException("context"); if (!isRendered()) return; for (Iterator it = getFacetsAndChildren(); it.hasNext(); ) { UIComponent childOrFacet = (UIComponent)it.next(); childOrFacet.processValidators(context); } } /** * This isn't an input component, so just pass on the processUpdates * call to child components and facets that might be input components. * <p> * Components that were never rendered can't possibly be receiving * update data (no corresponding fields were ever put into the response) * so if this component is not rendered then this method does not * invoke processUpdates on its children. */ public void processUpdates(FacesContext context) { if (context == null) throw new NullPointerException("context"); if (!isRendered()) return; for (Iterator it = getFacetsAndChildren(); it.hasNext(); ) { UIComponent childOrFacet = (UIComponent)it.next(); childOrFacet.processUpdates(context); } } public Object processSaveState(FacesContext context) { if (context == null) throw new NullPointerException("context"); if (isTransient()) return null; Map facetMap = null; for (Iterator it = getFacets().entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next(); if (facetMap == null) facetMap = new HashMap(); UIComponent component = (UIComponent)entry.getValue(); if (!component.isTransient()) { facetMap.put(entry.getKey(), component.processSaveState(context)); } } List childrenList = null; if (getChildCount() > 0) { for (Iterator it = getChildren().iterator(); it.hasNext(); ) { UIComponent child = (UIComponent)it.next(); if (childrenList == null) { childrenList = new ArrayList(getChildCount()); } Object childState = child.processSaveState(context); if (childState != null) { childrenList.add(childState); } } } return new Object[] {saveState(context), facetMap, childrenList}; } public void processRestoreState(FacesContext context, Object state) { if (context == null) throw new NullPointerException("context"); Object myState = ((Object[])state)[0]; Map facetMap = (Map)((Object[])state)[1]; List childrenList = (List)((Object[])state)[2]; if(facetMap != null) { for (Iterator it = getFacets().entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next(); Object facetState = facetMap.get(entry.getKey()); if (facetState != null) { UIComponent component = (UIComponent)entry.getValue(); component.processRestoreState(context, facetState); } else { context.getExternalContext().log("No state found to restore facet " + entry.getKey()); } } } if (childrenList != null && getChildCount() > 0) { int idx = 0; for (Iterator it = getChildren().iterator(); it.hasNext(); ) { UIComponent child = (UIComponent)it.next(); if(!child.isTransient()) { Object childState = childrenList.get(idx++); if (childState != null) { child.processRestoreState(context, childState); } else { context.getExternalContext().log("No state found to restore child of component " + getId()); } } } } restoreState(context, myState); } protected FacesContext getFacesContext() { return FacesContext.getCurrentInstance(); } protected Renderer getRenderer(FacesContext context) { if (context == null) throw new NullPointerException("context"); String rendererType = getRendererType(); if (rendererType == null) return null; String renderKitId = context.getViewRoot().getRenderKitId(); RenderKitFactory rkf = (RenderKitFactory)FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); RenderKit renderKit = rkf.getRenderKit(context, renderKitId); Renderer renderer = renderKit.getRenderer(getFamily(), rendererType); if (renderer == null) { getFacesContext().getExternalContext().log("No Renderer found for component " + getPathToComponent(this) + " (component-family=" + getFamily() + ", renderer-type=" + rendererType + ")"); log.warn("No Renderer found for component " + getPathToComponent(this) + " (component-family=" + getFamily() + ", renderer-type=" + rendererType + ")"); } return renderer; } private String getPathToComponent(UIComponent component) { StringBuffer buf = new StringBuffer(); if(component == null) { buf.append("{Component-Path : "); buf.append("[null]}"); return buf.toString(); } getPathToComponent(component,buf); buf.insert(0,"{Component-Path : "); buf.append("}"); return buf.toString(); } private static void getPathToComponent(UIComponent component, StringBuffer buf) { if(component == null) return; StringBuffer intBuf = new StringBuffer(); intBuf.append("[Class: "); intBuf.append(component.getClass().getName()); if(component instanceof UIViewRoot) { intBuf.append(",ViewId: "); intBuf.append(((UIViewRoot) component).getViewId()); } else { intBuf.append(",Id: "); intBuf.append(component.getId()); } intBuf.append("]"); buf.insert(0,intBuf.toString()); getPathToComponent(component.getParent(), buf); } public boolean isTransient() { return _transient; } public void setTransient(boolean transientFlag) { _transient = transientFlag; } /** * Serializes objects which are "attached" to this component but which are * not UIComponent children of it. Examples are validator and listener * objects. To be precise, it returns an object which implements * java.io.Serializable, and which when serialized will persist the * state of the provided object. * <p> * If the attachedObject is a List then every object in the list is saved * via a call to this method, and the returned wrapper object contains * a List object. * <p> * If the object implements StateHolder then the object's saveState is * called immediately, and a wrapper is returned which contains both * this saved state and the original class name. However in the case * where the StateHolder.isTransient method returns true, null is * returned instead. * <p> * If the object implements java.io.Serializable then the object is simply * returned immediately; standard java serialization will later be used * to store this object. * <p> * In all other cases, a wrapper is returned which simply stores the type * of the provided object. When deserialized, a default instance of that * type will be recreated. */ public static Object saveAttachedState(FacesContext context, Object attachedObject) { if (attachedObject == null) return null; if (attachedObject instanceof List) { List lst = new ArrayList(((List)attachedObject).size()); for (Iterator it = ((List)attachedObject).iterator(); it.hasNext(); ) { lst.add(saveAttachedState(context, it.next())); } return new _AttachedListStateWrapper(lst); } else if (attachedObject instanceof StateHolder) { if (((StateHolder)attachedObject).isTransient()) { return null; } else { return new _AttachedStateWrapper(attachedObject.getClass(), ((StateHolder)attachedObject).saveState(context)); } } else if (attachedObject instanceof Serializable) { return attachedObject; } else { return new _AttachedStateWrapper(attachedObject.getClass(), null); } } public static Object restoreAttachedState(FacesContext context, Object stateObj) throws IllegalStateException { if (context == null) throw new NullPointerException("context"); if (stateObj == null) return null; if (stateObj instanceof _AttachedListStateWrapper) { List lst = ((_AttachedListStateWrapper)stateObj).getWrappedStateList(); List restoredList = new ArrayList(lst.size()); for (Iterator it = lst.iterator(); it.hasNext(); ) { restoredList.add(restoreAttachedState(context, it.next())); } return restoredList; } else if (stateObj instanceof _AttachedStateWrapper) { Class clazz = ((_AttachedStateWrapper)stateObj).getClazz(); Object restoredObject; try { restoredObject = clazz.newInstance(); } catch (InstantiationException e) { throw new RuntimeException("Could not restore StateHolder of type " + clazz.getName() + " (missing no-args constructor?)", e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } if (restoredObject instanceof StateHolder) { Object wrappedState = ((_AttachedStateWrapper)stateObj).getWrappedStateObject(); ((StateHolder)restoredObject).restoreState(context, wrappedState); } return restoredObject; } else { return stateObj; } } /** * Invoked after the render phase has completed, this method * returns an object which can be passed to the restoreState * of some other instance of UIComponentBase to reset that * object's state to the same values as this object currently * has. */ public Object saveState(FacesContext context) { Object values[] = new Object[7]; values[0] = _id; values[1] = _rendered; values[2] = _rendererType; values[3] = _clientId; values[4] = saveAttributesMap(); values[5] = saveAttachedState(context, _facesListeners); values[6] = saveValueBindingMap(context); return values; } /** * Invoked in the "restore view" phase, this initialises this * object's members from the values saved previously into the * provided state object. * <p> * @param state is an object previously returned by * the saveState method of this class. */ public void restoreState(FacesContext context, Object state) { Object values[] = (Object[])state; _id = (String)values[0]; _rendered = (Boolean)values[1]; _rendererType = (String)values[2]; _clientId = (String)values[3]; restoreAttributesMap(values[4]); _facesListeners = (List)restoreAttachedState(context, values[5]); restoreValueBindingMap(context, values[6]); } private Object saveAttributesMap() { if (_attributesMap != null) { return _attributesMap.getUnderlyingMap(); } else { return null; } } private void restoreAttributesMap(Object stateObj) { if (stateObj != null) { _attributesMap = new _ComponentAttributesMap(this, (Map)stateObj); } else { _attributesMap = null; } } private Object saveValueBindingMap(FacesContext context) { if (_valueBindingMap != null) { int initCapacity = (_valueBindingMap.size() * 4 + 3) / 3; HashMap stateMap = new HashMap(initCapacity); for (Iterator it = _valueBindingMap.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next(); stateMap.put(entry.getKey(), saveAttachedState(context, entry.getValue())); } return stateMap; } else { return null; } } private void restoreValueBindingMap(FacesContext context, Object stateObj) { if (stateObj != null) { Map stateMap = (Map)stateObj; int initCapacity = (stateMap.size() * 4 + 3) / 3; _valueBindingMap = new HashMap(initCapacity); for (Iterator it = stateMap.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next(); _valueBindingMap.put(entry.getKey(), restoreAttachedState(context, entry.getValue())); } } else { _valueBindingMap = null; } } /** * @param string the component id, that should be a vaild one. */ private void isIdValid(String string) { //is there any component identifier ? if(string == null) return; //Component identifiers must obey the following syntax restrictions: //1. Must not be a zero-length String. if(string.length()==0) { throw new IllegalArgumentException("component identifier must not be a zero-length String"); } //let's look at all chars inside of the ID if it is a valid ID! char[] chars = string.toCharArray(); //2. First character must be a letter or an underscore ('_'). if(!Character.isLetter(chars[0]) && chars[0] !='_') { throw new IllegalArgumentException("component identifier's first character must be a letter or an underscore ('_')! But it is \""+chars[0]+"\""); } for (int i = 1; i < chars.length; i++) { //3. Subsequent characters must be a letter, a digit, an underscore ('_'), or a dash ('-'). if(!Character.isDigit(chars[i]) && !Character.isLetter(chars[i]) && chars[i] !='-' && chars[i] !='_') { throw new IllegalArgumentException("Subsequent characters of component identifier must be a letter, a digit, an underscore ('_'), or a dash ('-')! But component identifier contains \""+chars[i]+"\""); } } } //------------------ GENERATED CODE BEGIN (do not modify!) -------------------- private static final boolean DEFAULT_RENDERED = true; private Boolean _rendered = null; private String _rendererType = null; public void setRendered(boolean rendered) { _rendered = Boolean.valueOf(rendered); } public boolean isRendered() { if (_rendered != null) return _rendered.booleanValue(); ValueBinding vb = getValueBinding("rendered"); Boolean v = vb != null ? (Boolean)vb.getValue(getFacesContext()) : null; return v != null ? v.booleanValue() : DEFAULT_RENDERED; } public void setRendererType(String rendererType) { _rendererType = rendererType; } public String getRendererType() { if (_rendererType != null) return _rendererType; ValueBinding vb = getValueBinding("rendererType"); return vb != null ? _ComponentUtils.getStringValue(getFacesContext(), vb) : null; } //------------------ GENERATED CODE END --------------------------------------- }
apache-2.0
krasserm/ipf
commons/ihe/xds/src/main/java/org/openehealth/ipf/commons/ihe/xds/core/ebxml/ebxml21/EbXMLProvideAndRegisterDocumentSetRequest21.java
4308
/* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openehealth.ipf.commons.ihe.xds.core.ebxml.ebxml21; import static org.apache.commons.lang3.Validate.notNull; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.activation.DataHandler; import org.openehealth.ipf.commons.ihe.xds.core.ebxml.EbXMLObjectLibrary; import org.openehealth.ipf.commons.ihe.xds.core.ebxml.EbXMLProvideAndRegisterDocumentSetRequest; import org.openehealth.ipf.commons.ihe.xds.core.ebxml.ebxml21.ProvideAndRegisterDocumentSetRequestType.Document; import org.openehealth.ipf.commons.ihe.xds.core.stub.ebrs21.rim.LeafRegistryObjectListType; import org.openehealth.ipf.commons.ihe.xds.core.stub.ebrs21.rs.SubmitObjectsRequest; /** * Encapsulation of {@link ProvideAndRegisterDocumentSetRequestType} * @author Jens Riemschneider */ public class EbXMLProvideAndRegisterDocumentSetRequest21 extends EbXMLObjectContainer21 implements EbXMLProvideAndRegisterDocumentSetRequest { private final ProvideAndRegisterDocumentSetRequestType request; /** * Constructs a request by wrapping the given ebXML 2.1 object. * @param request * the request to wrap. * @param objectLibrary * the object library to use. */ public EbXMLProvideAndRegisterDocumentSetRequest21(ProvideAndRegisterDocumentSetRequestType request, EbXMLObjectLibrary objectLibrary) { super(objectLibrary); notNull(request, "request cannot be null"); this.request = request; } /** * Constructs a request by wrapping the given ebXML 2.1 object and creating a new object library. * <p> * The object library is filled with the objects contained in the request. * @param request * the request to wrap. */ public EbXMLProvideAndRegisterDocumentSetRequest21(ProvideAndRegisterDocumentSetRequestType request) { this(request, new EbXMLObjectLibrary()); fillObjectLibrary(); } @Override public ProvideAndRegisterDocumentSetRequestType getInternal() { return request; } @Override public void addDocument(String id, DataHandler dataHandler) { if (dataHandler != null && id != null) { List<Document> documents = request.getDocument(); Document document = new Document(); document.setId(id); document.setValue(dataHandler); documents.add(document); } } @Override public void removeDocument(String id) { for (Document doc : request.getDocument()) { if (doc.getId().equals(id)) { request.getDocument().remove(doc); return; } } } @Override public Map<String, DataHandler> getDocuments() { Map<String, DataHandler> map = new HashMap<String, DataHandler>(); for (Document document : request.getDocument()) { map.put(document.getId(), document.getValue()); } return Collections.unmodifiableMap(map); } @Override protected List<Object> getContents() { SubmitObjectsRequest submitObjectsRequest = request.getSubmitObjectsRequest(); if (submitObjectsRequest == null) { return Collections.emptyList(); } LeafRegistryObjectListType list = submitObjectsRequest.getLeafRegistryObjectList(); if (list == null) { return Collections.emptyList(); } return list.getObjectRefOrAssociationOrAuditableEvent(); } }
apache-2.0
hortonworks/cloudbreak
common/src/main/java/com/sequenceiq/cloudbreak/ccm/cloudinit/DefaultCcmV2Parameters.java
2889
package com.sequenceiq.cloudbreak.ccm.cloudinit; import static com.sequenceiq.cloudbreak.ccm.cloudinit.CcmV2ParameterConstants.CCMV2_BACKEND_ID_FORMAT; import static org.apache.commons.lang3.StringUtils.EMPTY; import java.io.Serializable; import java.util.Map; import javax.annotation.Nonnull; import org.apache.commons.lang3.StringUtils; public class DefaultCcmV2Parameters implements CcmV2Parameters, Serializable { private static final long serialVersionUID = 1L; private final String invertingProxyHost; private final String invertingProxyCertificate; private final String agentCrn; private final String agentKeyId; private final String agentCertificate; private final String agentEncipheredPrivateKey; public DefaultCcmV2Parameters(@Nonnull String invertingProxyHost, @Nonnull String invertingProxyCertificate, @Nonnull String agentCrn, @Nonnull String agentKeyId, @Nonnull String agentEncipheredPrivateKey, @Nonnull String agentCertificate) { this.invertingProxyHost = invertingProxyHost; this.invertingProxyCertificate = invertingProxyCertificate; this.agentCrn = agentCrn; this.agentKeyId = agentKeyId; this.agentEncipheredPrivateKey = agentEncipheredPrivateKey; this.agentCertificate = agentCertificate; } @Override public String getInvertingProxyCertificate() { return invertingProxyCertificate; } @Override public String getInvertingProxyHost() { return invertingProxyHost; } @Override public String getAgentCertificate() { return agentCertificate; } @Override public String getAgentKeyId() { return agentKeyId; } @Override public String getAgentCrn() { return agentCrn; } @Override public String getAgentEncipheredPrivateKey() { return agentEncipheredPrivateKey; } @Override public String getAgentBackendIdPrefix() { return StringUtils.isNotBlank(getAgentCrn()) ? String.format(CCMV2_BACKEND_ID_FORMAT, getAgentCrn(), EMPTY) : EMPTY; } @Override public void addToTemplateModel(@Nonnull Map<String, Object> model) { model.put(CcmV2ParameterConstants.CCMV2_INVERTING_PROXY_HOST, getInvertingProxyHost()); model.put(CcmV2ParameterConstants.CCMV2_INVERTING_PROXY_CERTIFICATE, getInvertingProxyCertificate()); model.put(CcmV2ParameterConstants.CCMV2_AGENT_KEY_ID, getAgentKeyId()); model.put(CcmV2ParameterConstants.CCMV2_AGENT_CRN, getAgentCrn()); model.put(CcmV2ParameterConstants.CCMV2_AGENT_ENCIPHERED_KEY, getAgentEncipheredPrivateKey()); model.put(CcmV2ParameterConstants.CCMV2_AGENT_CERTIFICATE, getAgentCertificate()); model.put(CcmV2ParameterConstants.CCMV2_AGENT_BACKEND_ID_PREFIX, getAgentBackendIdPrefix()); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-pi/src/main/java/com/amazonaws/services/pi/AWSPI.java
10637
/* * 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.pi; import javax.annotation.Generated; import com.amazonaws.*; import com.amazonaws.regions.*; import com.amazonaws.services.pi.model.*; /** * Interface for accessing AWS PI. * <p> * <b>Note:</b> Do not directly implement this interface, new methods are added to it regularly. Extend from * {@link com.amazonaws.services.pi.AbstractAWSPI} instead. * </p> * <p> * <fullname>Amazon RDS Performance Insights</fullname> * <p> * Amazon RDS Performance Insights enables you to monitor and explore different dimensions of database load based on * data captured from a running DB instance. The guide provides detailed information about Performance Insights data * types, parameters and errors. * </p> * <p> * When Performance Insights is enabled, the Amazon RDS Performance Insights API provides visibility into the * performance of your DB instance. Amazon CloudWatch provides the authoritative source for Amazon Web Services * service-vended monitoring metrics. Performance Insights offers a domain-specific view of DB load. * </p> * <p> * DB load is measured as average active sessions. Performance Insights provides the data to API consumers as a * two-dimensional time-series dataset. The time dimension provides DB load data for each time point in the queried time * range. Each time point decomposes overall load in relation to the requested dimensions, measured at that time point. * Examples include SQL, Wait event, User, and Host. * </p> * <ul> * <li> * <p> * To learn more about Performance Insights and Amazon Aurora DB instances, go to the <a * href="https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights.html"> Amazon Aurora User * Guide</a>. * </p> * </li> * <li> * <p> * To learn more about Performance Insights and Amazon RDS DB instances, go to the <a * href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights.html"> Amazon RDS User Guide</a>. * </p> * </li> * </ul> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public interface AWSPI { /** * The region metadata service name for computing region endpoints. You can use this value to retrieve metadata * (such as supported regions) of the service. * * @see RegionUtils#getRegionsForService(String) */ String ENDPOINT_PREFIX = "pi"; /** * <p> * For a specific time period, retrieve the top <code>N</code> dimension keys for a metric. * </p> * <note> * <p> * Each response element returns a maximum of 500 bytes. For larger elements, such as SQL statements, only the first * 500 bytes are returned. * </p> * </note> * * @param describeDimensionKeysRequest * @return Result of the DescribeDimensionKeys operation returned by the service. * @throws InvalidArgumentException * One of the arguments provided is invalid for this request. * @throws InternalServiceErrorException * The request failed due to an unknown error. * @throws NotAuthorizedException * The user is not authorized to perform this request. * @sample AWSPI.DescribeDimensionKeys * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/pi-2018-02-27/DescribeDimensionKeys" target="_top">AWS API * Documentation</a> */ DescribeDimensionKeysResult describeDimensionKeys(DescribeDimensionKeysRequest describeDimensionKeysRequest); /** * <p> * Get the attributes of the specified dimension group for a DB instance or data source. For example, if you specify * a SQL ID, <code>GetDimensionKeyDetails</code> retrieves the full text of the dimension * <code>db.sql.statement</code>cassociated with this ID. This operation is useful because * <code>GetResourceMetrics</code> and <code>DescribeDimensionKeys</code> don't support retrieval of large SQL * statement text. * </p> * * @param getDimensionKeyDetailsRequest * @return Result of the GetDimensionKeyDetails operation returned by the service. * @throws InvalidArgumentException * One of the arguments provided is invalid for this request. * @throws InternalServiceErrorException * The request failed due to an unknown error. * @throws NotAuthorizedException * The user is not authorized to perform this request. * @sample AWSPI.GetDimensionKeyDetails * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/pi-2018-02-27/GetDimensionKeyDetails" target="_top">AWS API * Documentation</a> */ GetDimensionKeyDetailsResult getDimensionKeyDetails(GetDimensionKeyDetailsRequest getDimensionKeyDetailsRequest); /** * <p> * Retrieve the metadata for different features. For example, the metadata might indicate that a feature is turned * on or off on a specific DB instance. * </p> * * @param getResourceMetadataRequest * @return Result of the GetResourceMetadata operation returned by the service. * @throws InvalidArgumentException * One of the arguments provided is invalid for this request. * @throws InternalServiceErrorException * The request failed due to an unknown error. * @throws NotAuthorizedException * The user is not authorized to perform this request. * @sample AWSPI.GetResourceMetadata * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/pi-2018-02-27/GetResourceMetadata" target="_top">AWS API * Documentation</a> */ GetResourceMetadataResult getResourceMetadata(GetResourceMetadataRequest getResourceMetadataRequest); /** * <p> * Retrieve Performance Insights metrics for a set of data sources, over a time period. You can provide specific * dimension groups and dimensions, and provide aggregation and filtering criteria for each group. * </p> * <note> * <p> * Each response element returns a maximum of 500 bytes. For larger elements, such as SQL statements, only the first * 500 bytes are returned. * </p> * </note> * * @param getResourceMetricsRequest * @return Result of the GetResourceMetrics operation returned by the service. * @throws InvalidArgumentException * One of the arguments provided is invalid for this request. * @throws InternalServiceErrorException * The request failed due to an unknown error. * @throws NotAuthorizedException * The user is not authorized to perform this request. * @sample AWSPI.GetResourceMetrics * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/pi-2018-02-27/GetResourceMetrics" target="_top">AWS API * Documentation</a> */ GetResourceMetricsResult getResourceMetrics(GetResourceMetricsRequest getResourceMetricsRequest); /** * <p> * Retrieve the dimensions that can be queried for each specified metric type on a specified DB instance. * </p> * * @param listAvailableResourceDimensionsRequest * @return Result of the ListAvailableResourceDimensions operation returned by the service. * @throws InvalidArgumentException * One of the arguments provided is invalid for this request. * @throws InternalServiceErrorException * The request failed due to an unknown error. * @throws NotAuthorizedException * The user is not authorized to perform this request. * @sample AWSPI.ListAvailableResourceDimensions * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/pi-2018-02-27/ListAvailableResourceDimensions" * target="_top">AWS API Documentation</a> */ ListAvailableResourceDimensionsResult listAvailableResourceDimensions(ListAvailableResourceDimensionsRequest listAvailableResourceDimensionsRequest); /** * <p> * Retrieve metrics of the specified types that can be queried for a specified DB instance. * </p> * * @param listAvailableResourceMetricsRequest * @return Result of the ListAvailableResourceMetrics operation returned by the service. * @throws InvalidArgumentException * One of the arguments provided is invalid for this request. * @throws InternalServiceErrorException * The request failed due to an unknown error. * @throws NotAuthorizedException * The user is not authorized to perform this request. * @sample AWSPI.ListAvailableResourceMetrics * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/pi-2018-02-27/ListAvailableResourceMetrics" * target="_top">AWS API Documentation</a> */ ListAvailableResourceMetricsResult listAvailableResourceMetrics(ListAvailableResourceMetricsRequest listAvailableResourceMetricsRequest); /** * Shuts down this client object, releasing any resources that might be held open. This is an optional method, and * callers are not expected to call it, but can if they want to explicitly release any open resources. Once a client * has been shutdown, it should not be used to make any more requests. */ void shutdown(); /** * Returns additional metadata for a previously executed successful request, typically used for debugging issues * where a service isn't acting as expected. This data isn't considered part of the result data returned by an * operation, so it's available through this separate, diagnostic interface. * <p> * Response metadata is only cached for a limited period of time, so if you need to access this extra diagnostic * information for an executed request, you should use this method to retrieve it as soon as possible after * executing a request. * * @param request * The originally executed request. * * @return The response metadata for the specified request, or null if none is available. */ ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request); }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-importexport/src/main/java/com/amazonaws/services/importexport/model/UnableToCancelJobIdException.java
1222
/* * 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.importexport.model; import javax.annotation.Generated; /** * AWS Import/Export cannot cancel the job */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UnableToCancelJobIdException extends com.amazonaws.services.importexport.model.AmazonImportExportException { private static final long serialVersionUID = 1L; /** * Constructs a new UnableToCancelJobIdException with the specified error message. * * @param message * Describes the error encountered. */ public UnableToCancelJobIdException(String message) { super(message); } }
apache-2.0
andrenmaia/batfish
projects/batfish/src/batfish/grammar/juniper/SysStanza.java
116
package batfish.grammar.juniper; public abstract class SysStanza { public abstract SysStanzaType getSysType(); }
apache-2.0
jasonzhang2022/flexims
common/src/main/java/com/flexdms/flexims/file/FileSchemaLiteral.java
396
package com.flexdms.flexims.file; import javax.enterprise.util.AnnotationLiteral; public class FileSchemaLiteral extends AnnotationLiteral<FileSchema> implements FileSchema { /** * */ private static final long serialVersionUID = 1L; String value; public FileSchemaLiteral(String value) { super(); this.value = value; } @Override public String value() { return value; } }
apache-2.0
jporras66/8583core
8583core/src/main/java/com/indarsoft/iso8583core/coretypes/F063.java
1070
package com.indarsoft.iso8583core.coretypes; import com.indarsoft.iso8583core.types.Field; import com.indarsoft.iso8583core.types.TypeVar; import com.indarsoft.iso8583core.utl.Common; /** Application : ISO8583CORE - Class F063 - Reserved private. * */ public class F063 extends TypeVar { private F063 (byte[] bytearr , Field field) { super( bytearr, field ) ; if ( ! super.isValid() ){ return ; } } /** Static constructor . * * @param bytearr ( full array : coded length + coded data ). * @return {@link F063 } Reserved private */ protected static F063 get ( byte[] bytearr, Field field ){ return new F063 ( bytearr, field ) ; } /** Static constructor . * * @param bytearr * It calculates array length and adds to array data * @return {@link F063 } */ protected static F063 getIn ( byte[] bytearr, Field field ){ byte[] baro = Common.addLength( bytearr, field ) ; return new F063 ( baro, field ) ; } }
apache-2.0
vam-google/google-cloud-java
google-api-grpc/proto-google-cloud-dialogflow-v2beta1/src/main/java/com/google/cloud/dialogflow/v2beta1/ListIntentsRequest.java
36308
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dialogflow/v2beta1/intent.proto package com.google.cloud.dialogflow.v2beta1; /** * * * <pre> * The request message for * [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.ListIntentsRequest} */ public final class ListIntentsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2beta1.ListIntentsRequest) ListIntentsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListIntentsRequest.newBuilder() to construct. private ListIntentsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListIntentsRequest() { parent_ = ""; languageCode_ = ""; intentView_ = 0; pageSize_ = 0; pageToken_ = ""; } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ListIntentsRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); parent_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); languageCode_ = s; break; } case 24: { int rawValue = input.readEnum(); intentView_ = rawValue; break; } case 32: { pageSize_ = input.readInt32(); break; } case 42: { java.lang.String s = input.readStringRequireUtf8(); pageToken_ = s; break; } default: { if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.IntentProto .internal_static_google_cloud_dialogflow_v2beta1_ListIntentsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.IntentProto .internal_static_google_cloud_dialogflow_v2beta1_ListIntentsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.ListIntentsRequest.class, com.google.cloud.dialogflow.v2beta1.ListIntentsRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; private volatile java.lang.Object parent_; /** * * * <pre> * Required. The agent to list all intents from. * Format: `projects/&lt;Project ID&gt;/agent`. * </pre> * * <code>string parent = 1;</code> */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The agent to list all intents from. * Format: `projects/&lt;Project ID&gt;/agent`. * </pre> * * <code>string parent = 1;</code> */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int LANGUAGE_CODE_FIELD_NUMBER = 2; private volatile java.lang.Object languageCode_; /** * * * <pre> * Optional. The language to list training phrases, parameters and rich * messages for. If not specified, the agent's default language is used. * [More than a dozen * languages](https://dialogflow.com/docs/reference/language) are supported. * Note: languages must be enabled in the agent before they can be used. * </pre> * * <code>string language_code = 2;</code> */ public java.lang.String getLanguageCode() { java.lang.Object ref = languageCode_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); languageCode_ = s; return s; } } /** * * * <pre> * Optional. The language to list training phrases, parameters and rich * messages for. If not specified, the agent's default language is used. * [More than a dozen * languages](https://dialogflow.com/docs/reference/language) are supported. * Note: languages must be enabled in the agent before they can be used. * </pre> * * <code>string language_code = 2;</code> */ public com.google.protobuf.ByteString getLanguageCodeBytes() { java.lang.Object ref = languageCode_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); languageCode_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int INTENT_VIEW_FIELD_NUMBER = 3; private int intentView_; /** * * * <pre> * Optional. The resource view to apply to the returned intent. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.IntentView intent_view = 3;</code> */ public int getIntentViewValue() { return intentView_; } /** * * * <pre> * Optional. The resource view to apply to the returned intent. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.IntentView intent_view = 3;</code> */ public com.google.cloud.dialogflow.v2beta1.IntentView getIntentView() { @SuppressWarnings("deprecation") com.google.cloud.dialogflow.v2beta1.IntentView result = com.google.cloud.dialogflow.v2beta1.IntentView.valueOf(intentView_); return result == null ? com.google.cloud.dialogflow.v2beta1.IntentView.UNRECOGNIZED : result; } public static final int PAGE_SIZE_FIELD_NUMBER = 4; private int pageSize_; /** * * * <pre> * Optional. The maximum number of items to return in a single page. By * default 100 and at most 1000. * </pre> * * <code>int32 page_size = 4;</code> */ public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 5; private volatile java.lang.Object pageToken_; /** * * * <pre> * Optional. The next_page_token value returned from a previous list request. * </pre> * * <code>string page_token = 5;</code> */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * Optional. The next_page_token value returned from a previous list request. * </pre> * * <code>string page_token = 5;</code> */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getParentBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (!getLanguageCodeBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, languageCode_); } if (intentView_ != com.google.cloud.dialogflow.v2beta1.IntentView.INTENT_VIEW_UNSPECIFIED.getNumber()) { output.writeEnum(3, intentView_); } if (pageSize_ != 0) { output.writeInt32(4, pageSize_); } if (!getPageTokenBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 5, pageToken_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getParentBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (!getLanguageCodeBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, languageCode_); } if (intentView_ != com.google.cloud.dialogflow.v2beta1.IntentView.INTENT_VIEW_UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(3, intentView_); } if (pageSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(4, pageSize_); } if (!getPageTokenBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, pageToken_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.dialogflow.v2beta1.ListIntentsRequest)) { return super.equals(obj); } com.google.cloud.dialogflow.v2beta1.ListIntentsRequest other = (com.google.cloud.dialogflow.v2beta1.ListIntentsRequest) obj; boolean result = true; result = result && getParent().equals(other.getParent()); result = result && getLanguageCode().equals(other.getLanguageCode()); result = result && intentView_ == other.intentView_; result = result && (getPageSize() == other.getPageSize()); result = result && getPageToken().equals(other.getPageToken()); result = result && unknownFields.equals(other.unknownFields); return result; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + LANGUAGE_CODE_FIELD_NUMBER; hash = (53 * hash) + getLanguageCode().hashCode(); hash = (37 * hash) + INTENT_VIEW_FIELD_NUMBER; hash = (53 * hash) + intentView_; hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dialogflow.v2beta1.ListIntentsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.ListIntentsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ListIntentsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.ListIntentsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ListIntentsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.ListIntentsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ListIntentsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.ListIntentsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ListIntentsRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.ListIntentsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.dialogflow.v2beta1.ListIntentsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.ListIntentsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.dialogflow.v2beta1.ListIntentsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The request message for * [Intents.ListIntents][google.cloud.dialogflow.v2beta1.Intents.ListIntents]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.ListIntentsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2beta1.ListIntentsRequest) com.google.cloud.dialogflow.v2beta1.ListIntentsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.IntentProto .internal_static_google_cloud_dialogflow_v2beta1_ListIntentsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.IntentProto .internal_static_google_cloud_dialogflow_v2beta1_ListIntentsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.ListIntentsRequest.class, com.google.cloud.dialogflow.v2beta1.ListIntentsRequest.Builder.class); } // Construct using com.google.cloud.dialogflow.v2beta1.ListIntentsRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); parent_ = ""; languageCode_ = ""; intentView_ = 0; pageSize_ = 0; pageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.v2beta1.IntentProto .internal_static_google_cloud_dialogflow_v2beta1_ListIntentsRequest_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ListIntentsRequest getDefaultInstanceForType() { return com.google.cloud.dialogflow.v2beta1.ListIntentsRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ListIntentsRequest build() { com.google.cloud.dialogflow.v2beta1.ListIntentsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ListIntentsRequest buildPartial() { com.google.cloud.dialogflow.v2beta1.ListIntentsRequest result = new com.google.cloud.dialogflow.v2beta1.ListIntentsRequest(this); result.parent_ = parent_; result.languageCode_ = languageCode_; result.intentView_ = intentView_; result.pageSize_ = pageSize_; result.pageToken_ = pageToken_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return (Builder) super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return (Builder) super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return (Builder) super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return (Builder) super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return (Builder) super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.dialogflow.v2beta1.ListIntentsRequest) { return mergeFrom((com.google.cloud.dialogflow.v2beta1.ListIntentsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.v2beta1.ListIntentsRequest other) { if (other == com.google.cloud.dialogflow.v2beta1.ListIntentsRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; onChanged(); } if (!other.getLanguageCode().isEmpty()) { languageCode_ = other.languageCode_; onChanged(); } if (other.intentView_ != 0) { setIntentViewValue(other.getIntentViewValue()); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.dialogflow.v2beta1.ListIntentsRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.dialogflow.v2beta1.ListIntentsRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The agent to list all intents from. * Format: `projects/&lt;Project ID&gt;/agent`. * </pre> * * <code>string parent = 1;</code> */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The agent to list all intents from. * Format: `projects/&lt;Project ID&gt;/agent`. * </pre> * * <code>string parent = 1;</code> */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The agent to list all intents from. * Format: `projects/&lt;Project ID&gt;/agent`. * </pre> * * <code>string parent = 1;</code> */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; onChanged(); return this; } /** * * * <pre> * Required. The agent to list all intents from. * Format: `projects/&lt;Project ID&gt;/agent`. * </pre> * * <code>string parent = 1;</code> */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); onChanged(); return this; } /** * * * <pre> * Required. The agent to list all intents from. * Format: `projects/&lt;Project ID&gt;/agent`. * </pre> * * <code>string parent = 1;</code> */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; onChanged(); return this; } private java.lang.Object languageCode_ = ""; /** * * * <pre> * Optional. The language to list training phrases, parameters and rich * messages for. If not specified, the agent's default language is used. * [More than a dozen * languages](https://dialogflow.com/docs/reference/language) are supported. * Note: languages must be enabled in the agent before they can be used. * </pre> * * <code>string language_code = 2;</code> */ public java.lang.String getLanguageCode() { java.lang.Object ref = languageCode_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); languageCode_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. The language to list training phrases, parameters and rich * messages for. If not specified, the agent's default language is used. * [More than a dozen * languages](https://dialogflow.com/docs/reference/language) are supported. * Note: languages must be enabled in the agent before they can be used. * </pre> * * <code>string language_code = 2;</code> */ public com.google.protobuf.ByteString getLanguageCodeBytes() { java.lang.Object ref = languageCode_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); languageCode_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. The language to list training phrases, parameters and rich * messages for. If not specified, the agent's default language is used. * [More than a dozen * languages](https://dialogflow.com/docs/reference/language) are supported. * Note: languages must be enabled in the agent before they can be used. * </pre> * * <code>string language_code = 2;</code> */ public Builder setLanguageCode(java.lang.String value) { if (value == null) { throw new NullPointerException(); } languageCode_ = value; onChanged(); return this; } /** * * * <pre> * Optional. The language to list training phrases, parameters and rich * messages for. If not specified, the agent's default language is used. * [More than a dozen * languages](https://dialogflow.com/docs/reference/language) are supported. * Note: languages must be enabled in the agent before they can be used. * </pre> * * <code>string language_code = 2;</code> */ public Builder clearLanguageCode() { languageCode_ = getDefaultInstance().getLanguageCode(); onChanged(); return this; } /** * * * <pre> * Optional. The language to list training phrases, parameters and rich * messages for. If not specified, the agent's default language is used. * [More than a dozen * languages](https://dialogflow.com/docs/reference/language) are supported. * Note: languages must be enabled in the agent before they can be used. * </pre> * * <code>string language_code = 2;</code> */ public Builder setLanguageCodeBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); languageCode_ = value; onChanged(); return this; } private int intentView_ = 0; /** * * * <pre> * Optional. The resource view to apply to the returned intent. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.IntentView intent_view = 3;</code> */ public int getIntentViewValue() { return intentView_; } /** * * * <pre> * Optional. The resource view to apply to the returned intent. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.IntentView intent_view = 3;</code> */ public Builder setIntentViewValue(int value) { intentView_ = value; onChanged(); return this; } /** * * * <pre> * Optional. The resource view to apply to the returned intent. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.IntentView intent_view = 3;</code> */ public com.google.cloud.dialogflow.v2beta1.IntentView getIntentView() { @SuppressWarnings("deprecation") com.google.cloud.dialogflow.v2beta1.IntentView result = com.google.cloud.dialogflow.v2beta1.IntentView.valueOf(intentView_); return result == null ? com.google.cloud.dialogflow.v2beta1.IntentView.UNRECOGNIZED : result; } /** * * * <pre> * Optional. The resource view to apply to the returned intent. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.IntentView intent_view = 3;</code> */ public Builder setIntentView(com.google.cloud.dialogflow.v2beta1.IntentView value) { if (value == null) { throw new NullPointerException(); } intentView_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Optional. The resource view to apply to the returned intent. * </pre> * * <code>.google.cloud.dialogflow.v2beta1.IntentView intent_view = 3;</code> */ public Builder clearIntentView() { intentView_ = 0; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Optional. The maximum number of items to return in a single page. By * default 100 and at most 1000. * </pre> * * <code>int32 page_size = 4;</code> */ public int getPageSize() { return pageSize_; } /** * * * <pre> * Optional. The maximum number of items to return in a single page. By * default 100 and at most 1000. * </pre> * * <code>int32 page_size = 4;</code> */ public Builder setPageSize(int value) { pageSize_ = value; onChanged(); return this; } /** * * * <pre> * Optional. The maximum number of items to return in a single page. By * default 100 and at most 1000. * </pre> * * <code>int32 page_size = 4;</code> */ public Builder clearPageSize() { pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. The next_page_token value returned from a previous list request. * </pre> * * <code>string page_token = 5;</code> */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. The next_page_token value returned from a previous list request. * </pre> * * <code>string page_token = 5;</code> */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. The next_page_token value returned from a previous list request. * </pre> * * <code>string page_token = 5;</code> */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; onChanged(); return this; } /** * * * <pre> * Optional. The next_page_token value returned from a previous list request. * </pre> * * <code>string page_token = 5;</code> */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); onChanged(); return this; } /** * * * <pre> * Optional. The next_page_token value returned from a previous list request. * </pre> * * <code>string page_token = 5;</code> */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFieldsProto3(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.v2beta1.ListIntentsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2beta1.ListIntentsRequest) private static final com.google.cloud.dialogflow.v2beta1.ListIntentsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2beta1.ListIntentsRequest(); } public static com.google.cloud.dialogflow.v2beta1.ListIntentsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListIntentsRequest> PARSER = new com.google.protobuf.AbstractParser<ListIntentsRequest>() { @java.lang.Override public ListIntentsRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ListIntentsRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ListIntentsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListIntentsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ListIntentsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache-2.0
lcg0124/bootdo
bootdo/src/main/java/com/bootdo/common/utils/StringUtils.java
133
package com.bootdo.common.utils; /** * @author bootdo */ public class StringUtils extends org.apache.commons.lang3.StringUtils{ }
apache-2.0
Ariah-Group/Finance
af_webapp/src/main/java/org/kuali/kfs/module/purap/document/validation/impl/PurchaseOrderQuoteLanguageRule.java
4455
/* * Copyright 2007 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.kfs.module.purap.document.validation.impl; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.kuali.kfs.module.purap.PurapKeyConstants; import org.kuali.kfs.module.purap.businessobject.PurchaseOrderQuoteLanguage; import org.kuali.rice.kns.document.MaintenanceDocument; import org.kuali.rice.kns.maintenance.rules.MaintenanceDocumentRuleBase; import org.kuali.rice.krad.service.BusinessObjectService; /* * */ public class PurchaseOrderQuoteLanguageRule extends MaintenanceDocumentRuleBase { protected PurchaseOrderQuoteLanguage oldQuoteLanguage; protected PurchaseOrderQuoteLanguage newQuoteLanguage; protected BusinessObjectService boService; /** * @see org.kuali.rice.kns.maintenance.rules.MaintenanceDocumentRuleBase#setupConvenienceObjects() */ @Override public void setupConvenienceObjects() { oldQuoteLanguage = (PurchaseOrderQuoteLanguage) super.getOldBo(); // setup newDelegateChange convenience objects, make sure all possible sub-objects are populated newQuoteLanguage = (PurchaseOrderQuoteLanguage) super.getNewBo(); boService = (BusinessObjectService) super.getBoService(); super.setupConvenienceObjects(); } protected boolean processCustomApproveDocumentBusinessRules(MaintenanceDocument document) { LOG.info("processCustomApproveDocumentBusinessRules called"); this.setupConvenienceObjects(); boolean success = this.checkForDuplicate(); return success && super.processCustomApproveDocumentBusinessRules(document); } protected boolean processCustomRouteDocumentBusinessRules(MaintenanceDocument document) { LOG.info("processCustomRouteDocumentBusinessRules called"); this.setupConvenienceObjects(); boolean success = this.checkForDuplicate(); return success && super.processCustomRouteDocumentBusinessRules(document); } protected boolean processCustomSaveDocumentBusinessRules(MaintenanceDocument document) { LOG.info("processCustomSaveDocumentBusinessRules called"); this.setupConvenienceObjects(); boolean success = this.checkForDuplicate(); return success && super.processCustomSaveDocumentBusinessRules(document); } protected boolean checkForDuplicate() { LOG.info("checkForDuplicate called"); boolean success = true; Map fieldValues = new HashMap(); fieldValues.put("purchaseOrderQuoteLanguageDescription", newQuoteLanguage.getPurchaseOrderQuoteLanguageDescription()); fieldValues.put("purchaseOrderQuoteLanguageCreateDate", newQuoteLanguage.getPurchaseOrderQuoteLanguageCreateDate()); if (oldQuoteLanguage != null && newQuoteLanguage != null && newQuoteLanguage.getPurchaseOrderQuoteLanguageIdentifier() != null && oldQuoteLanguage.getPurchaseOrderQuoteLanguageIdentifier() != null && newQuoteLanguage.getPurchaseOrderQuoteLanguageCreateDate() != null && oldQuoteLanguage.getPurchaseOrderQuoteLanguageCreateDate() != null && StringUtils.equalsIgnoreCase(newQuoteLanguage.getPurchaseOrderQuoteLanguageDescription(),oldQuoteLanguage.getPurchaseOrderQuoteLanguageDescription()) && newQuoteLanguage.getPurchaseOrderQuoteLanguageIdentifier().equals(oldQuoteLanguage.getPurchaseOrderQuoteLanguageIdentifier()) && newQuoteLanguage.getPurchaseOrderQuoteLanguageCreateDate().equals(oldQuoteLanguage.getPurchaseOrderQuoteLanguageCreateDate())){ success = true; }else if (boService.countMatching(newQuoteLanguage.getClass(), fieldValues) != 0) { success &= false; putGlobalError(PurapKeyConstants.PURAP_GENERAL_POTENTIAL_DUPLICATE); } return success; } }
apache-2.0
xjtu3c/GranuleJ
GOP/GranuleJIDE/example/Log2/src/gEncrypt.java
763
granule gEncrypt(SysLogGenerator){ external double safetyIndex; { if(safetyIndex <= 0.3) return true; else return false; } } class SysLogGenerator within gEncrypt{ public LogItem generate() { seed.checkStatus(); seed.produceLog(); seed.setMsg(encrypt(seed.getMsg())); System.out.println("safety index is low, now incrypt the log ..."); return seed.generate(); } public String encrypt(String msg) { msg = msg.substring(msg.length() - 1) + msg.substring(0, msg.length() - 1); return msg; } public static void printA() { System.out.println("da hua hua ti shi first in gEncrypt!"); } public static void main(String[] args){ printA(); } }
apache-2.0
nandosola/json-schema-validator
src/test/java/eu/vahlas/json/schema/impl/validators/EnumValidatorTest.java
1805
/** * Copyright (C) 2010 Nicolas Vahlas <nico@vahlas.eu> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.vahlas.json.schema.impl.validators; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import java.util.List; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Test; import eu.vahlas.json.schema.impl.JSONValidator; public class EnumValidatorTest { private final String schema = "{" + "\"type\" : \"number\"," + "\"enum\": [1,2,3,4,5]" + "}"; private final String json1 = "3"; private final String json2 = "10"; private ObjectMapper mapper; private EnumValidator v; public EnumValidatorTest() throws Exception { mapper = new ObjectMapper(); v = new EnumValidator(mapper.readTree(schema).get(EnumValidator.PROPERTY)); } @Test public void testValidateSuccess() throws Exception{ List<String> errors = v.validate(mapper.readTree(json1), JSONValidator.AT_ROOT); assertThat(errors.size(), is(0)); } @Test public void testValidateFailure() throws Exception { List<String> errors = v.validate(mapper.readTree(json2), JSONValidator.AT_ROOT); assertThat(errors.size(), is(1)); assertThat(errors.get(0), is("$: does not have a value in the enumeration [1, 2, 3, 4, 5]")); } }
apache-2.0
AlanJager/zstack
plugin/loadBalancer/src/main/java/org/zstack/network/service/lb/LoadBalancerListenerVO.java
4129
package org.zstack.network.service.lb; import org.zstack.header.identity.OwnedByAccount; import org.zstack.header.vo.BaseResource; import org.zstack.header.vo.EntityGraph; import org.zstack.header.vo.ForeignKey; import org.zstack.header.vo.ForeignKey.ReferenceOption; import org.zstack.header.vo.NoView; import org.zstack.header.vo.ResourceVO; import javax.persistence.*; import java.sql.Timestamp; import java.util.HashSet; import java.util.Set; /** * Created by frank on 8/8/2015. */ @Entity @Table @BaseResource @EntityGraph( parents = { @EntityGraph.Neighbour(type = LoadBalancerVO.class, myField = "loadBalancerUuid", targetField = "uuid"), @EntityGraph.Neighbour(type = LoadBalancerListenerVmNicRefVO.class, myField = "uuid", targetField = "listenerUuid"), @EntityGraph.Neighbour(type = LoadBalancerListenerCertificateRefVO.class, myField = "uuid", targetField = "listenerUuid") } ) public class LoadBalancerListenerVO extends ResourceVO implements OwnedByAccount { @Column @ForeignKey(parentEntityClass = LoadBalancerVO.class, parentKey = "uuid", onDeleteAction = ReferenceOption.RESTRICT) private String loadBalancerUuid; @Column private String name; @Column private String description; @Column private int instancePort; @Column private int loadBalancerPort; @Column private String protocol; @OneToMany(fetch=FetchType.EAGER) @JoinColumn(name="listenerUuid", insertable=false, updatable=false) @NoView private Set<LoadBalancerListenerVmNicRefVO> vmNicRefs = new HashSet<LoadBalancerListenerVmNicRefVO>(); @OneToMany(fetch=FetchType.EAGER) @JoinColumn(name="listenerUuid", insertable=false, updatable=false) @NoView private Set<LoadBalancerListenerCertificateRefVO> certificateRefs; @Column private Timestamp createDate; @Column private Timestamp lastOpDate; @Transient private String accountUuid; @Override public String getAccountUuid() { return accountUuid; } @Override public void setAccountUuid(String accountUuid) { this.accountUuid = accountUuid; } @PreUpdate private void preUpdate() { lastOpDate = null; } public Set<LoadBalancerListenerVmNicRefVO> getVmNicRefs() { return vmNicRefs; } public void setVmNicRefs(Set<LoadBalancerListenerVmNicRefVO> vmNicRefs) { this.vmNicRefs = vmNicRefs; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getInstancePort() { return instancePort; } public void setInstancePort(int instancePort) { this.instancePort = instancePort; } public int getLoadBalancerPort() { return loadBalancerPort; } public void setLoadBalancerPort(int loadBalancerPort) { this.loadBalancerPort = loadBalancerPort; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public Timestamp getCreateDate() { return createDate; } public void setCreateDate(Timestamp createDate) { this.createDate = createDate; } public Timestamp getLastOpDate() { return lastOpDate; } public void setLastOpDate(Timestamp lastOpDate) { this.lastOpDate = lastOpDate; } public String getLoadBalancerUuid() { return loadBalancerUuid; } public void setLoadBalancerUuid(String loadBalancerUuid) { this.loadBalancerUuid = loadBalancerUuid; } public Set<LoadBalancerListenerCertificateRefVO> getCertificateRefs() { return certificateRefs; } public void setCertificateRefs(Set<LoadBalancerListenerCertificateRefVO> certificateRefs) { this.certificateRefs = certificateRefs; } }
apache-2.0
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202105/StringFormatError.java
2303
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.api.ads.admanager.jaxws.v202105; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * * A list of error code for reporting invalid content of input strings. * * * <p>Java class for StringFormatError complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="StringFormatError"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v202105}ApiError"> * &lt;sequence> * &lt;element name="reason" type="{https://www.google.com/apis/ads/publisher/v202105}StringFormatError.Reason" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "StringFormatError", propOrder = { "reason" }) public class StringFormatError extends ApiError { @XmlSchemaType(name = "string") protected StringFormatErrorReason reason; /** * Gets the value of the reason property. * * @return * possible object is * {@link StringFormatErrorReason } * */ public StringFormatErrorReason getReason() { return reason; } /** * Sets the value of the reason property. * * @param value * allowed object is * {@link StringFormatErrorReason } * */ public void setReason(StringFormatErrorReason value) { this.reason = value; } }
apache-2.0
hortonworks/cloudbreak
core/src/test/java/com/sequenceiq/cloudbreak/service/freeipa/FreeIpaConfigProviderTest.java
6582
package com.sequenceiq.cloudbreak.service.freeipa; import static com.sequenceiq.freeipa.api.v1.freeipa.stack.model.common.instance.InstanceStatus.CREATED; import static com.sequenceiq.freeipa.api.v1.freeipa.stack.model.common.instance.InstanceStatus.REQUESTED; import static com.sequenceiq.freeipa.api.v1.freeipa.stack.model.common.instance.InstanceStatus.TERMINATED; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import com.sequenceiq.freeipa.api.v1.freeipa.stack.model.common.instance.InstanceGroupResponse; import com.sequenceiq.freeipa.api.v1.freeipa.stack.model.common.instance.InstanceMetaDataResponse; import com.sequenceiq.freeipa.api.v1.freeipa.stack.model.common.instance.InstanceMetadataType; import com.sequenceiq.freeipa.api.v1.freeipa.stack.model.common.instance.InstanceStatus; import com.sequenceiq.freeipa.api.v1.freeipa.stack.model.describe.DescribeFreeIpaResponse; @ExtendWith(MockitoExtension.class) class FreeIpaConfigProviderTest { public static final String ENVIRONMENT_CRN = "ENV_CRN"; @Mock private FreeipaClientService freeipaClient; @InjectMocks private FreeIpaConfigProvider underTest; @Test public void testCreatedChoosen() { DescribeFreeIpaResponse freeIpaResponse = new DescribeFreeIpaResponse(); InstanceGroupResponse instanceGroupResponse = new InstanceGroupResponse(); instanceGroupResponse.setMetaData(Set.of(createInstanceMetadata("b", TERMINATED), createInstanceMetadata("a", REQUESTED), createInstanceMetadata("f", CREATED), createInstanceMetadata("c", CREATED))); freeIpaResponse.setInstanceGroups(List.of(instanceGroupResponse)); when(freeipaClient.findByEnvironmentCrn(ENVIRONMENT_CRN)).thenReturn(Optional.of(freeIpaResponse)); Map<String, Object> result = underTest.createFreeIpaConfig(ENVIRONMENT_CRN); assertEquals(1, result.size()); assertEquals("c", result.get("host")); } @Test public void testNonCreatedChoosen() { DescribeFreeIpaResponse freeIpaResponse = new DescribeFreeIpaResponse(); InstanceGroupResponse instanceGroupResponse = new InstanceGroupResponse(); instanceGroupResponse.setMetaData(Set.of(createInstanceMetadata("b", TERMINATED), createInstanceMetadata("a", REQUESTED))); freeIpaResponse.setInstanceGroups(List.of(instanceGroupResponse)); when(freeipaClient.findByEnvironmentCrn(ENVIRONMENT_CRN)).thenReturn(Optional.of(freeIpaResponse)); Map<String, Object> result = underTest.createFreeIpaConfig(ENVIRONMENT_CRN); assertEquals(1, result.size()); assertEquals("a", result.get("host")); } @Test public void testNoChoosenIfInsanceMetadataEmpty() { DescribeFreeIpaResponse freeIpaResponse = new DescribeFreeIpaResponse(); InstanceGroupResponse instanceGroupResponse = new InstanceGroupResponse(); instanceGroupResponse.setMetaData(Set.of()); freeIpaResponse.setInstanceGroups(List.of(instanceGroupResponse)); when(freeipaClient.findByEnvironmentCrn(ENVIRONMENT_CRN)).thenReturn(Optional.of(freeIpaResponse)); Map<String, Object> result = underTest.createFreeIpaConfig(ENVIRONMENT_CRN); assertTrue(result.isEmpty()); } @Test public void testNoChoosenIfInsanceGroupEmpty() { DescribeFreeIpaResponse freeIpaResponse = new DescribeFreeIpaResponse(); freeIpaResponse.setInstanceGroups(List.of()); when(freeipaClient.findByEnvironmentCrn(ENVIRONMENT_CRN)).thenReturn(Optional.of(freeIpaResponse)); Map<String, Object> result = underTest.createFreeIpaConfig(ENVIRONMENT_CRN); assertTrue(result.isEmpty()); } @Test public void testNoChoosenIfResponseMissing() { when(freeipaClient.findByEnvironmentCrn(ENVIRONMENT_CRN)).thenReturn(Optional.empty()); Map<String, Object> result = underTest.createFreeIpaConfig(ENVIRONMENT_CRN); assertTrue(result.isEmpty()); } @Test public void testPgwChosen() { DescribeFreeIpaResponse freeIpaResponse = new DescribeFreeIpaResponse(); InstanceGroupResponse instanceGroupResponse = new InstanceGroupResponse(); InstanceMetaDataResponse pgw = createInstanceMetadata("d", CREATED); pgw.setInstanceType(InstanceMetadataType.GATEWAY_PRIMARY); instanceGroupResponse.setMetaData(Set.of(createInstanceMetadata("b", TERMINATED), createInstanceMetadata("a", REQUESTED), createInstanceMetadata("f", CREATED), pgw, createInstanceMetadata("c", CREATED))); freeIpaResponse.setInstanceGroups(List.of(instanceGroupResponse)); when(freeipaClient.findByEnvironmentCrn(ENVIRONMENT_CRN)).thenReturn(Optional.of(freeIpaResponse)); Map<String, Object> result = underTest.createFreeIpaConfig(ENVIRONMENT_CRN); assertEquals(1, result.size()); assertEquals("d", result.get("host")); } @Test public void testPgwNotChosenIfNotCreated() { DescribeFreeIpaResponse freeIpaResponse = new DescribeFreeIpaResponse(); InstanceGroupResponse instanceGroupResponse = new InstanceGroupResponse(); InstanceMetaDataResponse pgw = createInstanceMetadata("d", TERMINATED); pgw.setInstanceType(InstanceMetadataType.GATEWAY_PRIMARY); instanceGroupResponse.setMetaData(Set.of(createInstanceMetadata("b", TERMINATED), createInstanceMetadata("a", REQUESTED), createInstanceMetadata("f", CREATED), pgw, createInstanceMetadata("c", CREATED))); freeIpaResponse.setInstanceGroups(List.of(instanceGroupResponse)); when(freeipaClient.findByEnvironmentCrn(ENVIRONMENT_CRN)).thenReturn(Optional.of(freeIpaResponse)); Map<String, Object> result = underTest.createFreeIpaConfig(ENVIRONMENT_CRN); assertEquals(1, result.size()); assertEquals("c", result.get("host")); } private InstanceMetaDataResponse createInstanceMetadata(String fqdn, InstanceStatus status) { InstanceMetaDataResponse response = new InstanceMetaDataResponse(); response.setDiscoveryFQDN(fqdn); response.setInstanceStatus(status); return response; } }
apache-2.0
fpompermaier/onvif
onvif-ws-client/src/main/java/org/onvif/ver10/network/wsdl/DiscoveryLookupPort.java
1199
package org.onvif.ver10.network.wsdl; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.xml.bind.annotation.XmlSeeAlso; /** * This class was generated by Apache CXF 3.3.2 * Generated source version: 3.3.2 * */ @WebService(targetNamespace = "http://www.onvif.org/ver10/network/wsdl", name = "DiscoveryLookupPort") @XmlSeeAlso({org.xmlsoap.schemas.ws._2005._04.discovery.ObjectFactory.class, ObjectFactory.class, org.xmlsoap.schemas.ws._2004._08.addressing.ObjectFactory.class}) @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE) public interface DiscoveryLookupPort { @WebMethod(operationName = "Probe", action = "http://www.onvif.org/ver10/network/wsdl/Probe") @WebResult(name = "ProbeResponse", targetNamespace = "http://www.onvif.org/ver10/network/wsdl", partName = "parameters") public org.xmlsoap.schemas.ws._2005._04.discovery.ProbeMatchesType probe( @WebParam(partName = "parameters", name = "Probe", targetNamespace = "http://www.onvif.org/ver10/network/wsdl") org.xmlsoap.schemas.ws._2005._04.discovery.ProbeType parameters ); }
apache-2.0
jbee/silk
src/test.integration/test/java/test/integration/bind/TestPrimitiveBinds.java
3338
package test.integration.bind; import org.junit.Test; import se.jbee.inject.Injector; import se.jbee.inject.lang.Type; import se.jbee.inject.UnresolvableDependency.NoResourceForDependency; import se.jbee.inject.binder.BinderModule; import se.jbee.inject.bootstrap.Bootstrap; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static se.jbee.inject.Name.named; /** * In Silk primitives and wrapper {@link Class}es are the same {@link Type}. * * @author Jan Bernitt (jan@jbee.se) * */ public class TestPrimitiveBinds { private static class PrimitiveBindsModule extends BinderModule { @Override protected void declare() { bind(int.class).to(42); bind(boolean.class).to(true); bind(long.class).to(132L); bind(named("pi"), float.class).to(3.1415f); bind(named("e"), double.class).to(2.71828d); bind(PrimitiveBindsBean.class).toConstructor(); } } public static class PrimitiveBindsBean { final int i; final float f; final boolean b; final Integer bigI; final Float bigF; final Boolean bigB; public PrimitiveBindsBean(int i, float f, boolean b, Integer bigI, Float bigF, Boolean bigB) { this.i = i; this.f = f; this.b = b; this.bigI = bigI; this.bigF = bigF; this.bigB = bigB; } } private final Injector injector = Bootstrap.injector( PrimitiveBindsModule.class); @Test public void thatIntPrimitivesWorkAsWrapperClasses() { assertEquals(42, injector.resolve(Integer.class).intValue()); assertEquals(42, injector.resolve(int.class).intValue()); } @Test public void thatLongPrimitivesWorkAsWrapperClasses() { assertEquals(132L, injector.resolve(Long.class).longValue()); assertEquals(132L, injector.resolve(long.class).longValue()); } @Test public void thatBooleanPrimitivesWorkAsWrapperClasses() { assertEquals(true, injector.resolve(Boolean.class)); assertEquals(true, injector.resolve(boolean.class)); } @Test public void thatFloatPrimitivesWorkAsWrapperClasses() { assertEquals(3.1415f, injector.resolve("pi", Float.class).floatValue(), 0.01f); assertEquals(3.1415f, injector.resolve("pi", float.class).floatValue(), 0.01f); } @Test public void thatDoublePrimitivesWorkAsWrapperClasses() { assertEquals(2.71828d, injector.resolve("e", Double.class), 0.01d); assertEquals(2.71828d, injector.resolve("e", double.class), 0.01d); } /** * To allow such a automatic conversion a bridge could be bound for each of * the primitives. Such a bind would look like this. * * <pre> * bind(int[].class).to(new IntToIntergerArrayBridgeSupplier()); * </pre> * * The stated bridge class is not a part of Silk but easy to do. Still a * loot of code for all the primitives for a little benefit. */ @Test(expected = NoResourceForDependency.class) public void thatPrimitiveArrayNotWorkAsWrapperArrayClasses() { assertArrayEquals(new int[42], injector.resolve(int[].class)); } @Test public void thatPrimitivesWorkAsPrimitiveOrWrapperClassesWhenInjected() { PrimitiveBindsBean bean = injector.resolve(PrimitiveBindsBean.class); assertEquals(42, bean.i); assertEquals(3.1415f, bean.f, 0.01f); assertEquals(true, bean.b); assertEquals(42, bean.bigI.intValue()); assertEquals(3.1415f, bean.bigF, 0.01f); assertEquals(true, bean.bigB); } }
apache-2.0
Java8-CNAPI-Team/Java8CN
org/omg/PortableInterceptor/INACTIVE.java
549
package org.omg.PortableInterceptor; /** * org/omg/PortableInterceptor/INACTIVE.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from c:/workspace/8-2-build-windows-amd64-cygwin/jdk8u65/4987/corba/src/share/classes/org/omg/PortableInterceptor/Interceptors.idl * Tuesday, October 6, 2015 4:40:34 PM PDT */ public interface INACTIVE { /** Object adapter state that causes all requests to be discarded. * This state indicates that the adapter is shutting down. */ public static final short value = (short)(3); }
apache-2.0
consulo/consulo-groovy
groovy-psi/src/main/java/org/jetbrains/plugins/groovy/lang/psi/dataFlow/types/TypesSemilattice.java
787
package org.jetbrains.plugins.groovy.lang.psi.dataFlow.types; import java.util.ArrayList; import org.jetbrains.plugins.groovy.lang.psi.dataFlow.Semilattice; import com.intellij.psi.PsiManager; /** * @author ven */ public class TypesSemilattice implements Semilattice<TypeDfaState> { private final PsiManager myManager; public TypesSemilattice(PsiManager manager) { myManager = manager; } public TypeDfaState join(ArrayList<TypeDfaState> ins) { if (ins.size() == 0) return new TypeDfaState(); TypeDfaState result = new TypeDfaState(ins.get(0)); for (int i = 1; i < ins.size(); i++) { result.joinState(ins.get(i), myManager); } return result; } public boolean eq(TypeDfaState e1, TypeDfaState e2) { return e1.contentsEqual(e2); } }
apache-2.0
Groostav/CMPT880-term-project
randoop/src/test/java/randoop/test/vmerrors/VMErrors.java
204
package randoop.test.vmerrors; public class VMErrors { public void throwStackOverflow() { throwStackOverflow(); } @Override public String toString() { return "VMErrors instance"; } }
apache-2.0
LorenzReinhart/ONOSnew
drivers/lisp/src/test/java/org/onosproject/drivers/lisp/extensions/LispNatAddressTest.java
5210
/* * Copyright 2017-present Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.drivers.lisp.extensions; import com.google.common.collect.ImmutableList; import com.google.common.testing.EqualsTester; import org.junit.Before; import org.junit.Test; import org.onlab.packet.IpPrefix; import org.onosproject.mapping.addresses.MappingAddress; import org.onosproject.mapping.addresses.MappingAddresses; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /** * Unit tests for LispNatAddress extension class. */ public class LispNatAddressTest { private static final IpPrefix IP_ADDRESS_1 = IpPrefix.valueOf("1.2.3.4/24"); private static final IpPrefix IP_ADDRESS_2 = IpPrefix.valueOf("5.6.7.8/24"); private static final IpPrefix RTR_ADDRESS_11 = IpPrefix.valueOf("10.1.1.1/24"); private static final IpPrefix RTR_ADDRESS_12 = IpPrefix.valueOf("10.1.1.2/24"); private static final IpPrefix RTR_ADDRESS_21 = IpPrefix.valueOf("10.1.2.1/24"); private static final IpPrefix RTR_ADDRESS_22 = IpPrefix.valueOf("10.1.2.2/24"); private static final short MS_UDP_PORT_NUMBER = 80; private static final short ETR_UDP_PORT_NUMBER = 100; private LispNatAddress address1; private LispNatAddress sameAsAddress1; private LispNatAddress address2; @Before public void setUp() { MappingAddress ma1 = MappingAddresses.ipv4MappingAddress(IP_ADDRESS_1); MappingAddress rtr11 = MappingAddresses.ipv4MappingAddress(RTR_ADDRESS_11); MappingAddress rtr12 = MappingAddresses.ipv4MappingAddress(RTR_ADDRESS_12); List<MappingAddress> rtrRlocs1 = ImmutableList.of(rtr11, rtr12); address1 = new LispNatAddress.Builder() .withMsUdpPortNumber(MS_UDP_PORT_NUMBER) .withEtrUdpPortNumber(ETR_UDP_PORT_NUMBER) .withGlobalEtrRlocAddress(ma1) .withMsRlocAddress(ma1) .withPrivateEtrRlocAddress(ma1) .withRtrRlocAddresses(rtrRlocs1) .build(); sameAsAddress1 = new LispNatAddress.Builder() .withMsUdpPortNumber(MS_UDP_PORT_NUMBER) .withEtrUdpPortNumber(ETR_UDP_PORT_NUMBER) .withGlobalEtrRlocAddress(ma1) .withMsRlocAddress(ma1) .withPrivateEtrRlocAddress(ma1) .withRtrRlocAddresses(rtrRlocs1) .build(); MappingAddress ma2 = MappingAddresses.ipv4MappingAddress(IP_ADDRESS_2); MappingAddress rtr21 = MappingAddresses.ipv4MappingAddress(RTR_ADDRESS_21); MappingAddress rtr22 = MappingAddresses.ipv4MappingAddress(RTR_ADDRESS_22); List<MappingAddress> rtrRlocs2 = ImmutableList.of(rtr21, rtr22); address2 = new LispNatAddress.Builder() .withMsUdpPortNumber(MS_UDP_PORT_NUMBER) .withEtrUdpPortNumber(ETR_UDP_PORT_NUMBER) .withGlobalEtrRlocAddress(ma2) .withMsRlocAddress(ma2) .withPrivateEtrRlocAddress(ma2) .withRtrRlocAddresses(rtrRlocs2) .build(); } @Test public void testEquality() { new EqualsTester() .addEqualityGroup(address1, sameAsAddress1) .addEqualityGroup(address2).testEquals(); } @Test public void testConstruction() { LispNatAddress address = address1; MappingAddress ma = MappingAddresses.ipv4MappingAddress(IP_ADDRESS_1); assertThat(address.getMsUdpPortNumber(), is(MS_UDP_PORT_NUMBER)); assertThat(address.getEtrUdpPortNumber(), is(ETR_UDP_PORT_NUMBER)); assertThat(address.getGlobalEtrRlocAddress(), is(ma)); assertThat(address.getMsRlocAddress(), is(ma)); assertThat(address.getPrivateEtrRlocAddress(), is(ma)); } @Test public void testSerialization() { LispNatAddress other = new LispNatAddress(); other.deserialize(address1.serialize()); new EqualsTester() .addEqualityGroup(address1, other) .testEquals(); } }
apache-2.0
emersonmello/UAF
fidouaf/src/main/java/org/ebayopensource/fidouaf/res/util/ProcessResponse.java
2516
/* * Copyright 2015 eBay Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ebayopensource.fidouaf.res.util; import br.edu.ifsc.mello.res.StorageMySQLImpl; import org.ebayopensource.fido.uaf.msg.AuthenticationResponse; import org.ebayopensource.fido.uaf.msg.RegistrationResponse; import org.ebayopensource.fido.uaf.ops.AuthenticationResponseProcessing; import org.ebayopensource.fido.uaf.ops.RegistrationResponseProcessing; import org.ebayopensource.fido.uaf.storage.AuthenticatorRecord; import org.ebayopensource.fido.uaf.storage.RegistrationRecord; public class ProcessResponse { private static final int SERVER_DATA_EXPIRY_IN_MS = 5 * 60 * 1000; // Gson gson = new Gson (); public AuthenticatorRecord[] processAuthResponse(AuthenticationResponse resp) { AuthenticatorRecord[] result = null; try { // result = new AuthenticationResponseProcessing( // SERVER_DATA_EXPIRY_IN_MS, NotaryImpl.getInstance()).verify( // resp, StorageImpl.getInstance()); result = new AuthenticationResponseProcessing( SERVER_DATA_EXPIRY_IN_MS, NotaryImpl.getInstance()).verify( resp, StorageMySQLImpl.getInstance()); } catch (Exception e) { System.out.println("Error process Auth Response: " + e.getMessage()); result = new AuthenticatorRecord[1]; result[0] = new AuthenticatorRecord(); result[0].status = e.getMessage(); } return result; } public RegistrationRecord[] processRegResponse(RegistrationResponse resp) { RegistrationRecord[] result = null; try { result = new RegistrationResponseProcessing( SERVER_DATA_EXPIRY_IN_MS, NotaryImpl.getInstance()) .processResponse(resp); } catch (Exception e) { System.out.println("Error processRegResponse: " + e.getMessage()); result = new RegistrationRecord[1]; result[0] = new RegistrationRecord(); result[0].status = e.getMessage(); } return result; } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/transform/GetUICustomizationRequestProtocolMarshaller.java
2774
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.cognitoidp.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.cognitoidp.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * GetUICustomizationRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class GetUICustomizationRequestProtocolMarshaller implements Marshaller<Request<GetUICustomizationRequest>, GetUICustomizationRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("AWSCognitoIdentityProviderService.GetUICustomization").serviceName("AWSCognitoIdentityProvider").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public GetUICustomizationRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<GetUICustomizationRequest> marshall(GetUICustomizationRequest getUICustomizationRequest) { if (getUICustomizationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<GetUICustomizationRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, getUICustomizationRequest); protocolMarshaller.startMarshalling(); GetUICustomizationRequestMarshaller.getInstance().marshall(getUICustomizationRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
decoit/decomap
src/main/java/de/simu/decomap/component/mapping/SnortEventMapper.java
8853
/* * Copyright 2015 DECOIT GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.simu.decomap.component.mapping; import de.hshannover.f4.trust.ifmapj.metadata.EventType; import de.hshannover.f4.trust.ifmapj.metadata.Significance; import de.simu.decomap.config.interfaces.GeneralConfig; import de.simu.decomap.config.interfaces.mapping.SnortEventMappingConfig; import de.simu.decomap.util.Toolbox; import java.util.HashMap; /** * Abstract Base class for all Snort related Mapping-Classes using IFMAPJ * Implements the Mapping-Interface and provides some basic values that are * required for mapping Snort log-entries to IF-MAP-Results * * @author Dennis Dunekacke, DECOIT GmbH */ public abstract class SnortEventMapper extends EventMapper { // mapping between snort and IFMAP values private HashMap<String, String> eventMap; private HashMap<String, String> significanceMap; // flags for determine which events should be processed private boolean logP2P = true; private boolean logCVE = true; private boolean logBotnetInfection = true; private boolean logWormInfection = true; private boolean logExcessiveFlows = true; private boolean logOther = true; private boolean logBehavioralChange = true; private boolean logPolicyViolation = true; /** * Constructor * * @param mainConfig * the main Configuration-Object */ @Override public void init(final GeneralConfig mainConfig) { super.init(mainConfig); SnortEventMappingConfig snortMappingConfiguration = (SnortEventMappingConfig) Toolbox.loadConfig( mainConfig.mappingComponentConfigPath(), SnortEventMappingConfig.class); eventMap = combineEventArrays(snortMappingConfiguration.behavioralChange(), snortMappingConfiguration.botnetInfection(), snortMappingConfiguration.cve(), snortMappingConfiguration.excessiveFlows(), snortMappingConfiguration.other(), snortMappingConfiguration.p2p(), snortMappingConfiguration.policyViolation(), snortMappingConfiguration.wormInfection()); HashMap<String, String> significance = combineSignificanceArrays(snortMappingConfiguration.significanceCritical(), snortMappingConfiguration.significanceInformational(), snortMappingConfiguration.significanceImportant()); if (significance != null && significance.size() > 0) { significanceMap = significance; } logBehavioralChange = snortMappingConfiguration.logBehavioralChange(); logBotnetInfection = snortMappingConfiguration.logBotnetInfection(); logCVE = snortMappingConfiguration.logCVE(); logExcessiveFlows = snortMappingConfiguration.logExcessiveFlows(); logOther = snortMappingConfiguration.logOther(); logP2P = snortMappingConfiguration.logP2P(); logPolicyViolation = snortMappingConfiguration.logPolicyViolation(); logWormInfection = snortMappingConfiguration.logWormInfection(); } /** * combines * * @param critical * @param informational * @param important * @return */ private HashMap<String, String> combineSignificanceArrays(final String[] critical, final String[] informational, final String[] important) { HashMap<String, String> significanceMap = new HashMap<String, String>(); for (String current : critical) { significanceMap.put(current, "critical"); } for (String current : informational) { significanceMap.put(current, "informational"); } for (String current : important) { significanceMap.put(current, "important"); } return significanceMap; } /** * combines * * @param behavioralChange * @param botnetInfection * @param cve * @param excessiveFlows * @param other * @param p2p * @param policyViolation * @param wormInfection * @return */ private HashMap<String, String> combineEventArrays(final String[] behavioralChange, final String[] botnetInfection, final String[] cve, final String[] excessiveFlows, final String[] other, final String[] p2p, final String[] policyViolation, final String[] wormInfection) { // build new event-map from event-arrays HashMap<String, String> eventMap = new HashMap<String, String>(); if (behavioralChange != null) { for (String current : wormInfection) { eventMap.put(current, "behavioral change"); } } if (botnetInfection != null) { for (String current : botnetInfection) { eventMap.put(current, "botnet infection"); } } if (cve != null) { for (String current : cve) { eventMap.put(current, "cve"); } } if (excessiveFlows != null) { for (String current : excessiveFlows) { eventMap.put(current, "excessive flows"); } } if (other != null) { for (String current : other) { eventMap.put(current, "other"); } } if (p2p != null) { for (String current : p2p) { eventMap.put(current, "p2p"); } } if (policyViolation != null) { for (String current : policyViolation) { eventMap.put(current, "policy violation"); } } if (wormInfection != null) { for (String current : wormInfection) { eventMap.put(current, "worm infection"); } } return eventMap; } /** * get the IF-MAP significance value for passed in snort-priority-value * * @param int snortPriorityValue * * @return significance value as string */ protected Significance getSignificanceValue(final int snortPriorityValue) { String sigValue = null; Significance sign = Significance.informational; // default! if (significanceMap.containsKey(new Integer(snortPriorityValue).toString())) { sigValue = significanceMap.get(new Integer(snortPriorityValue).toString()); } if (sigValue != null && sigValue.length() > 0) { if (sigValue.startsWith("important")) { sign = Significance.important; } else if (sigValue.startsWith("informational")) { sign = Significance.informational; } else if (sigValue.startsWith("critical")) { sign = Significance.critical; } } return sign; } /** * get the IF-MAP Event name for passed in Snort-Signature-Name (see * config/snort/mapping.properties) * * @param sigName * snort signature name * @return corresponding IF-MAP Signature Name */ protected EventType getEventMappingForSignatureName(final String sigName) { String mappedEvent = null; if (eventMap.containsKey(sigName)) { mappedEvent = eventMap.get(sigName); } else { mappedEvent = "other"; } EventType evntype = EventType.other; // default if (mappedEvent != null && mappedEvent.length() > 0) { if (mappedEvent.startsWith("behavioral change")) { evntype = EventType.behavioralChange; } else if (mappedEvent.startsWith("botnet infection")) { evntype = EventType.botnetInfection; } else if (mappedEvent.startsWith("cve")) { evntype = EventType.cve; } else if (mappedEvent.startsWith("excessive flows")) { evntype = EventType.excessiveFlows; } else if (mappedEvent.startsWith("p2p")) { evntype = EventType.p2p; } else if (mappedEvent.startsWith("policy violation")) { evntype = EventType.policyViolation; } else if (mappedEvent.startsWith("worm infection")) { evntype = EventType.wormInfection; } else { evntype = EventType.other; } } return evntype; } /** * get event type from passed in string and decide if current message should * be converted to IF-MAP Events, depending on Properties from Settings in * config/snort/mapping.properties * * @param eventType * type of the event * * @return flag indicating whether the message should be convertet or not */ protected boolean doConvert(final EventType eventType) { // map snort-event-type to if map event if (eventType == EventType.behavioralChange && !logBehavioralChange) { return false; } else if (eventType == EventType.botnetInfection && !logBotnetInfection) { return false; } else if (eventType == EventType.botnetInfection && !logCVE) { return false; } else if (eventType == EventType.excessiveFlows && !logExcessiveFlows) { return false; } else if (eventType == EventType.other && !logOther) { return false; } else if (eventType == EventType.p2p && !logP2P) { return false; } else if (eventType == EventType.policyViolation && !logPolicyViolation) { return false; } else if (eventType == EventType.wormInfection && !logWormInfection) { return false; } else { return true; } } }
apache-2.0
ebayopensource/turmeric-monitoring
turmeric-monitoring-cassandra-storage-provider/src/main/java/org/ebayopensource/turmeric/monitoring/cassandra/storage/dao/impl/MetricsServiceOperationByIpDAOImpl.java
4485
/******************************************************************************* * Copyright (c) 2006-2010 eBay Inc. 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 *******************************************************************************/ package org.ebayopensource.turmeric.monitoring.cassandra.storage.dao.impl; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.ebayopensource.turmeric.monitoring.cassandra.storage.model.BasicModel; import org.ebayopensource.turmeric.monitoring.cassandra.storage.model.SuperModel; import org.ebayopensource.turmeric.utils.cassandra.dao.AbstractSuperColumnFamilyDao; import edu.emory.mathcs.backport.java.util.Collections; // TODO: Auto-generated Javadoc /** * The Class MetricsServiceOperationByIpDAOImpl. * * @param <SK> * the generic type * @param <K> * the key type * @author jamuguerza */ public class MetricsServiceOperationByIpDAOImpl<SK, K> extends AbstractSuperColumnFamilyDao<SK, SuperModel, String, BasicModel> { /** * Instantiates a new metrics error values dao impl. * * @param clusterName * the cluster name * @param host * the host * @param s_keyspace * the s_keyspace * @param columnFamilyName * the column family name * @param sKTypeClass * the s k type class * @param kTypeClass * the k type class */ public MetricsServiceOperationByIpDAOImpl(String clusterName, String host, String s_keyspace, String columnFamilyName, final Class<SK> sKTypeClass, final Class<K> kTypeClass) { super(clusterName, host, s_keyspace, sKTypeClass, SuperModel.class, String.class, BasicModel.class, columnFamilyName); } /** * {@inheritDoc} */ public List<String> findMetricOperationNames(final List<String> serviceAdminNames) { List<String> resultList = new ArrayList<String>(); if (serviceAdminNames == null || serviceAdminNames.isEmpty()) { return resultList; } Set<String> resultSet = new TreeSet<String>(); List<SK> keys = new ArrayList<SK>(); keys.add((SK) "All"); String[] serviceNames = new String[serviceAdminNames.size()]; serviceNames = serviceAdminNames.toArray(serviceNames); Map<SK, SuperModel> findItems = findItems(keys, serviceNames); for (Map.Entry<SK, SuperModel> findItem : findItems.entrySet()) { SK key = findItem.getKey(); // IP, in this case ALL SuperModel superModel = findItem.getValue(); if (superModel != null) { Map<String, BasicModel> columns = superModel.getColumns(); for (String column : columns.keySet()) { String serviceName = column; BasicModel<?> operations = columns.get(column); Set<String> keySet = operations.getColumns().keySet(); for (String operationName : keySet) { resultSet.add(serviceName + "." + operationName); } } } } resultList.addAll(resultSet); Collections.sort(resultList); return resultList; } /** * {@inheritDoc} */ public List<String> findMetricServiceAdminNames(final List<String> serviceAdminNames) { Set<String> resultSet = new TreeSet<String>(); List<SK> keys = new ArrayList<SK>(); keys.add((SK) "All"); String[] serviceNames = new String[serviceAdminNames.size()]; serviceNames = serviceAdminNames.toArray(serviceNames); Map<SK, SuperModel> findItems = findItems(keys, serviceNames); for (Map.Entry<SK, SuperModel> findItem : findItems.entrySet()) { SK key = findItem.getKey(); // IP, in this case ALL SuperModel superModel = findItem.getValue(); if (superModel != null) { Map<String, BasicModel> columns = superModel.getColumns(); for (String serviceName : columns.keySet()) { resultSet.add(serviceName); } } } List<String> resultList = new ArrayList<String>(resultSet); Collections.sort(resultList); return resultList; } }
apache-2.0
jbertram/activemq-artemis-old
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/DeadLetterAddressTest.java
22286
/** * 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.client; import org.apache.activemq.artemis.api.core.ActiveMQException; import org.junit.Before; import org.junit.Test; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.apache.activemq.artemis.api.core.Message; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.ClientConsumer; import org.apache.activemq.artemis.api.core.client.ClientMessage; 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.ActiveMQClient; import org.apache.activemq.artemis.api.core.client.MessageHandler; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger; import org.apache.activemq.artemis.tests.util.RandomUtil; import org.apache.activemq.artemis.tests.util.ServiceTestBase; import org.apache.activemq.artemis.tests.util.UnitTestCase; public class DeadLetterAddressTest extends ServiceTestBase { private static final IntegrationTestLogger log = IntegrationTestLogger.LOGGER; private ActiveMQServer server; private ClientSession clientSession; private ServerLocator locator; @Test public void testBasicSend() throws Exception { SimpleString dla = new SimpleString("DLA"); SimpleString qName = new SimpleString("q1"); SimpleString adName = new SimpleString("ad1"); AddressSettings addressSettings = new AddressSettings(); addressSettings.setMaxDeliveryAttempts(1); addressSettings.setDeadLetterAddress(dla); server.getAddressSettingsRepository().addMatch(adName.toString(), addressSettings); SimpleString dlq = new SimpleString("DLQ1"); clientSession.createQueue(dla, dlq, null, false); clientSession.createQueue(adName, qName, null, false); ClientProducer producer = clientSession.createProducer(adName); producer.send(createTextMessage(clientSession, "heyho!")); clientSession.start(); ClientConsumer clientConsumer = clientSession.createConsumer(qName); ClientMessage m = clientConsumer.receive(500); m.acknowledge(); Assert.assertNotNull(m); Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!"); // force a cancel clientSession.rollback(); m = clientConsumer.receiveImmediate(); Assert.assertNull(m); clientConsumer.close(); clientConsumer = clientSession.createConsumer(dlq); m = clientConsumer.receive(500); Assert.assertNotNull(m); assertEquals("q1", m.getStringProperty(Message.HDR_ORIGINAL_QUEUE)); assertEquals("ad1", m.getStringProperty(Message.HDR_ORIGINAL_ADDRESS)); Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!"); } // HORNETQ- 1084 @Test public void testBasicSendWithDLAButNoBinding() throws Exception { SimpleString dla = new SimpleString("DLA"); SimpleString qName = new SimpleString("q1"); AddressSettings addressSettings = new AddressSettings(); addressSettings.setMaxDeliveryAttempts(1); addressSettings.setDeadLetterAddress(dla); server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings); //SimpleString dlq = new SimpleString("DLQ1"); //clientSession.createQueue(dla, dlq, null, false); clientSession.createQueue(qName, qName, null, false); ClientProducer producer = clientSession.createProducer(qName); producer.send(createTextMessage(clientSession, "heyho!")); clientSession.start(); ClientConsumer clientConsumer = clientSession.createConsumer(qName); ClientMessage m = clientConsumer.receive(500); m.acknowledge(); Assert.assertNotNull(m); Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!"); // force a cancel clientSession.rollback(); m = clientConsumer.receiveImmediate(); Assert.assertNull(m); clientConsumer.close(); Queue q = (Queue)server.getPostOffice().getBinding(qName).getBindable(); Assert.assertEquals(0, q.getDeliveringCount()); } @Test public void testBasicSend2times() throws Exception { SimpleString dla = new SimpleString("DLA"); SimpleString qName = new SimpleString("q1"); AddressSettings addressSettings = new AddressSettings(); addressSettings.setMaxDeliveryAttempts(2); addressSettings.setDeadLetterAddress(dla); server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings); SimpleString dlq = new SimpleString("DLQ1"); clientSession.createQueue(dla, dlq, null, false); clientSession.createQueue(qName, qName, null, false); ClientProducer producer = clientSession.createProducer(qName); producer.send(createTextMessage(clientSession, "heyho!")); clientSession.start(); ClientConsumer clientConsumer = clientSession.createConsumer(qName); ClientMessage m = clientConsumer.receive(5000); m.acknowledge(); Assert.assertNotNull(m); Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!"); // force a cancel clientSession.rollback(); clientSession.start(); m = clientConsumer.receive(5000); m.acknowledge(); Assert.assertNotNull(m); Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!"); // force a cancel clientSession.rollback(); m = clientConsumer.receiveImmediate(); Assert.assertNull(m); clientConsumer.close(); clientConsumer = clientSession.createConsumer(dlq); m = clientConsumer.receive(5000); Assert.assertNotNull(m); Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!"); } @Test public void testReceiveWithListeners() throws Exception { SimpleString dla = new SimpleString("DLA"); SimpleString qName = new SimpleString("q1"); AddressSettings addressSettings = new AddressSettings(); addressSettings.setMaxDeliveryAttempts(2); addressSettings.setDeadLetterAddress(dla); server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings); SimpleString dlq = new SimpleString("DLQ1"); clientSession.createQueue(dla, dlq, null, false); clientSession.createQueue(qName, qName, null, false); ClientProducer producer = clientSession.createProducer(qName); producer.send(createTextMessage(clientSession, "heyho!")); ClientConsumer clientConsumer = clientSession.createConsumer(qName); final CountDownLatch latch = new CountDownLatch(2); TestHandler handler = new TestHandler(latch, clientSession); clientConsumer.setMessageHandler(handler); clientSession.start(); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertEquals(handler.count, 2); clientConsumer = clientSession.createConsumer(dlq); Message m = clientConsumer.receive(5000); Assert.assertNotNull(m); Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!"); } class TestHandler implements MessageHandler { private final CountDownLatch latch; int count = 0; private final ClientSession clientSession; public TestHandler(CountDownLatch latch, ClientSession clientSession) { this.latch = latch; this.clientSession = clientSession; } public void onMessage(ClientMessage message) { count++; latch.countDown(); try { clientSession.rollback(true); } catch (ActiveMQException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } throw new RuntimeException(); } } @Test public void testBasicSendToMultipleQueues() throws Exception { SimpleString dla = new SimpleString("DLA"); SimpleString qName = new SimpleString("q1"); AddressSettings addressSettings = new AddressSettings(); addressSettings.setMaxDeliveryAttempts(1); addressSettings.setDeadLetterAddress(dla); server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings); SimpleString dlq = new SimpleString("DLQ1"); SimpleString dlq2 = new SimpleString("DLQ2"); clientSession.createQueue(dla, dlq, null, false); clientSession.createQueue(dla, dlq2, null, false); clientSession.createQueue(qName, qName, null, false); ClientProducer producer = clientSession.createProducer(qName); producer.send(createTextMessage(clientSession, "heyho!")); clientSession.start(); ClientConsumer clientConsumer = clientSession.createConsumer(qName); ClientMessage m = clientConsumer.receive(500); m.acknowledge(); Assert.assertNotNull(m); Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!"); // force a cancel clientSession.rollback(); m = clientConsumer.receiveImmediate(); Assert.assertNull(m); clientConsumer.close(); clientConsumer = clientSession.createConsumer(dlq); m = clientConsumer.receive(500); Assert.assertNotNull(m); m.acknowledge(); Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!"); clientConsumer.close(); clientConsumer = clientSession.createConsumer(dlq2); m = clientConsumer.receive(500); Assert.assertNotNull(m); m.acknowledge(); Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!"); clientConsumer.close(); } @Test public void testBasicSendToNoQueue() throws Exception { SimpleString qName = new SimpleString("q1"); AddressSettings addressSettings = new AddressSettings(); addressSettings.setMaxDeliveryAttempts(1); server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings); clientSession.createQueue(qName, qName, null, false); ClientProducer producer = clientSession.createProducer(qName); producer.send(createTextMessage(clientSession, "heyho!")); clientSession.start(); ClientConsumer clientConsumer = clientSession.createConsumer(qName); ClientMessage m = clientConsumer.receive(500); m.acknowledge(); Assert.assertNotNull(m); Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!"); // force a cancel clientSession.rollback(); m = clientConsumer.receiveImmediate(); Assert.assertNull(m); clientConsumer.close(); } @Test public void testHeadersSet() throws Exception { final int MAX_DELIVERIES = 16; final int NUM_MESSAGES = 5; SimpleString dla = new SimpleString("DLA"); SimpleString qName = new SimpleString("q1"); AddressSettings addressSettings = new AddressSettings(); addressSettings.setMaxDeliveryAttempts(MAX_DELIVERIES); addressSettings.setDeadLetterAddress(dla); server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings); SimpleString dlq = new SimpleString("DLQ1"); clientSession.createQueue(dla, dlq, null, false); clientSession.createQueue(qName, qName, null, false); ServerLocator locator = createInVMNonHALocator(); ClientSessionFactory sessionFactory = createSessionFactory(locator); ClientSession sendSession = sessionFactory.createSession(false, true, true); ClientProducer producer = sendSession.createProducer(qName); Map<String, Long> origIds = new HashMap<String, Long>(); for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage tm = createTextMessage(clientSession, "Message:" + i); producer.send(tm); } ClientConsumer clientConsumer = clientSession.createConsumer(qName); clientSession.start(); for (int i = 0; i < MAX_DELIVERIES; i++) { for (int j = 0; j < NUM_MESSAGES; j++) { ClientMessage tm = clientConsumer.receive(1000); Assert.assertNotNull(tm); tm.acknowledge(); if (i == 0) { origIds.put("Message:" + j, tm.getMessageID()); } Assert.assertEquals("Message:" + j, tm.getBodyBuffer().readString()); } clientSession.rollback(); } long timeout = System.currentTimeMillis() + 5000; // DLA transfer is asynchronous fired on the rollback while (System.currentTimeMillis() < timeout && getMessageCount(((Queue)server.getPostOffice().getBinding(qName).getBindable())) != 0) { Thread.sleep(1); } Assert.assertEquals(0, getMessageCount(((Queue)server.getPostOffice().getBinding(qName).getBindable()))); ClientMessage m = clientConsumer.receiveImmediate(); Assert.assertNull(m); // All the messages should now be in the DLQ ClientConsumer cc3 = clientSession.createConsumer(dlq); for (int i = 0; i < NUM_MESSAGES; i++) { ClientMessage tm = cc3.receive(1000); Assert.assertNotNull(tm); String text = tm.getBodyBuffer().readString(); Assert.assertEquals("Message:" + i, text); // Check the headers SimpleString origDest = (SimpleString)tm.getObjectProperty(Message.HDR_ORIGINAL_ADDRESS); Long origMessageId = (Long)tm.getObjectProperty(Message.HDR_ORIG_MESSAGE_ID); Assert.assertEquals(qName, origDest); Long origId = origIds.get(text); Assert.assertEquals(origId, origMessageId); } sendSession.close(); } @Test public void testDeadlLetterAddressWithDefaultAddressSettings() throws Exception { int deliveryAttempt = 3; SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); SimpleString deadLetterAddress = RandomUtil.randomSimpleString(); SimpleString deadLetterQueue = RandomUtil.randomSimpleString(); AddressSettings addressSettings = new AddressSettings(); addressSettings.setMaxDeliveryAttempts(deliveryAttempt); addressSettings.setDeadLetterAddress(deadLetterAddress); server.getAddressSettingsRepository().setDefault(addressSettings); clientSession.createQueue(address, queue, false); clientSession.createQueue(deadLetterAddress, deadLetterQueue, false); ClientProducer producer = clientSession.createProducer(address); ClientMessage clientMessage = createTextMessage(clientSession, "heyho!"); producer.send(clientMessage); clientSession.start(); ClientConsumer clientConsumer = clientSession.createConsumer(queue); for (int i = 0; i < deliveryAttempt; i++) { ClientMessage m = clientConsumer.receive(500); Assert.assertNotNull(m); DeadLetterAddressTest.log.info("i is " + i); DeadLetterAddressTest.log.info("delivery cout is " + m.getDeliveryCount()); Assert.assertEquals(i + 1, m.getDeliveryCount()); m.acknowledge(); clientSession.rollback(); } ClientMessage m = clientConsumer.receive(500); Assert.assertNull("not expecting a message", m); clientConsumer.close(); clientConsumer = clientSession.createConsumer(deadLetterQueue); m = clientConsumer.receive(500); Assert.assertNotNull(m); Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!"); } @Test public void testDeadlLetterAddressWithWildcardAddressSettings() throws Exception { int deliveryAttempt = 3; SimpleString address = RandomUtil.randomSimpleString(); SimpleString queue = RandomUtil.randomSimpleString(); SimpleString deadLetterAddress = RandomUtil.randomSimpleString(); SimpleString deadLetterQueue = RandomUtil.randomSimpleString(); AddressSettings addressSettings = new AddressSettings(); addressSettings.setMaxDeliveryAttempts(deliveryAttempt); addressSettings.setDeadLetterAddress(deadLetterAddress); server.getAddressSettingsRepository().addMatch("*", addressSettings); clientSession.createQueue(address, queue, false); clientSession.createQueue(deadLetterAddress, deadLetterQueue, false); ClientProducer producer = clientSession.createProducer(address); ClientMessage clientMessage = createTextMessage(clientSession, "heyho!"); producer.send(clientMessage); clientSession.start(); ClientConsumer clientConsumer = clientSession.createConsumer(queue); for (int i = 0; i < deliveryAttempt; i++) { ClientMessage m = clientConsumer.receive(500); Assert.assertNotNull(m); Assert.assertEquals(i + 1, m.getDeliveryCount()); m.acknowledge(); clientSession.rollback(); } ClientMessage m = clientConsumer.receiveImmediate(); Assert.assertNull(m); clientConsumer.close(); clientConsumer = clientSession.createConsumer(deadLetterQueue); m = clientConsumer.receive(500); Assert.assertNotNull(m); Assert.assertEquals(m.getBodyBuffer().readString(), "heyho!"); } @Test public void testDeadLetterAddressWithOverridenSublevelAddressSettings() throws Exception { int defaultDeliveryAttempt = 3; int specificeDeliveryAttempt = defaultDeliveryAttempt + 1; SimpleString address = new SimpleString("prefix.address"); SimpleString queue = RandomUtil.randomSimpleString(); SimpleString defaultDeadLetterAddress = RandomUtil.randomSimpleString(); SimpleString defaultDeadLetterQueue = RandomUtil.randomSimpleString(); SimpleString specificDeadLetterAddress = RandomUtil.randomSimpleString(); SimpleString specificDeadLetterQueue = RandomUtil.randomSimpleString(); AddressSettings defaultAddressSettings = new AddressSettings(); defaultAddressSettings.setMaxDeliveryAttempts(defaultDeliveryAttempt); defaultAddressSettings.setDeadLetterAddress(defaultDeadLetterAddress); server.getAddressSettingsRepository().addMatch("*", defaultAddressSettings); AddressSettings specificAddressSettings = new AddressSettings(); specificAddressSettings.setMaxDeliveryAttempts(specificeDeliveryAttempt); specificAddressSettings.setDeadLetterAddress(specificDeadLetterAddress); server.getAddressSettingsRepository().addMatch(address.toString(), specificAddressSettings); clientSession.createQueue(address, queue, false); clientSession.createQueue(defaultDeadLetterAddress, defaultDeadLetterQueue, false); clientSession.createQueue(specificDeadLetterAddress, specificDeadLetterQueue, false); ClientProducer producer = clientSession.createProducer(address); ClientMessage clientMessage = createTextMessage(clientSession, "heyho!"); producer.send(clientMessage); clientSession.start(); ClientConsumer clientConsumer = clientSession.createConsumer(queue); ClientConsumer defaultDeadLetterConsumer = clientSession.createConsumer(defaultDeadLetterQueue); ClientConsumer specificDeadLetterConsumer = clientSession.createConsumer(specificDeadLetterQueue); for (int i = 0; i < defaultDeliveryAttempt; i++) { ClientMessage m = clientConsumer.receive(500); Assert.assertNotNull(m); Assert.assertEquals(i + 1, m.getDeliveryCount()); m.acknowledge(); clientSession.rollback(); } Assert.assertNull(defaultDeadLetterConsumer.receiveImmediate()); Assert.assertNull(specificDeadLetterConsumer.receiveImmediate()); // one more redelivery attempt: ClientMessage m = clientConsumer.receive(500); Assert.assertNotNull(m); Assert.assertEquals(specificeDeliveryAttempt, m.getDeliveryCount()); m.acknowledge(); clientSession.rollback(); Assert.assertNull(defaultDeadLetterConsumer.receiveImmediate()); Assert.assertNotNull(specificDeadLetterConsumer.receive(500)); } @Override @Before public void setUp() throws Exception { super.setUp(); TransportConfiguration transportConfig = new TransportConfiguration(UnitTestCase.INVM_ACCEPTOR_FACTORY); Configuration configuration = createDefaultConfig() .setSecurityEnabled(false) .addAcceptorConfiguration(transportConfig); server = addServer(ActiveMQServers.newActiveMQServer(configuration, false)); // start the server server.start(); // then we create a client as normal locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration( UnitTestCase.INVM_CONNECTOR_FACTORY))); ClientSessionFactory sessionFactory = createSessionFactory(locator); clientSession = addClientSession(sessionFactory.createSession(false, true, false)); } }
apache-2.0
kkhatua/drill
metastore/metastore-api/src/main/java/org/apache/drill/metastore/components/tables/TableMetadataUnit.java
19138
/* * 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.drill.metastore.components.tables; import org.apache.drill.metastore.MetastoreFieldDefinition; import org.apache.drill.metastore.exceptions.MetastoreException; import org.apache.drill.metastore.metadata.MetadataType; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.StringJoiner; import static org.apache.drill.metastore.metadata.MetadataType.ALL; import static org.apache.drill.metastore.metadata.MetadataType.FILE; import static org.apache.drill.metastore.metadata.MetadataType.PARTITION; import static org.apache.drill.metastore.metadata.MetadataType.ROW_GROUP; import static org.apache.drill.metastore.metadata.MetadataType.SEGMENT; import static org.apache.drill.metastore.metadata.MetadataType.TABLE; /** * Class that represents one row in Drill Metastore Tables which is a generic representation of metastore metadata * suitable to any metastore table metadata type (table, segment, file, row group, partition). * Is used to read and write data from / to Drill Metastore Tables implementation. * * Note: changing field order and adding new fields may break backward compatibility in existing * Metastore implementations. It is recommended to add new information into {@link #additionalMetadata} * field instead. */ public class TableMetadataUnit { public static final Schema SCHEMA = Schema.of(TableMetadataUnit.class, Builder.class); @MetastoreFieldDefinition(scopes = {ALL}) private final String storagePlugin; @MetastoreFieldDefinition(scopes = {ALL}) private final String workspace; @MetastoreFieldDefinition(scopes = {ALL}) private final String tableName; @MetastoreFieldDefinition(scopes = {TABLE}) private final String owner; @MetastoreFieldDefinition(scopes = {TABLE}) private final String tableType; @MetastoreFieldDefinition(scopes = {ALL}) private final String metadataType; @MetastoreFieldDefinition(scopes = {ALL}) private final String metadataKey; @MetastoreFieldDefinition(scopes = {TABLE, SEGMENT, FILE, ROW_GROUP}) private final String location; @MetastoreFieldDefinition(scopes = {TABLE}) private final List<String> interestingColumns; @MetastoreFieldDefinition(scopes = {ALL}) private final String schema; @MetastoreFieldDefinition(scopes = {ALL}) private final Map<String, String> columnsStatistics; @MetastoreFieldDefinition(scopes = {ALL}) private final List<String> metadataStatistics; @MetastoreFieldDefinition(scopes = {ALL}) private final Long lastModifiedTime; @MetastoreFieldDefinition(scopes = {TABLE}) private final Map<String, String> partitionKeys; @MetastoreFieldDefinition(scopes = {ALL}) private final String additionalMetadata; @MetastoreFieldDefinition(scopes = {SEGMENT, FILE, ROW_GROUP, PARTITION}) private final String metadataIdentifier; @MetastoreFieldDefinition(scopes = {SEGMENT, PARTITION}) private final String column; @MetastoreFieldDefinition(scopes = {SEGMENT, PARTITION}) private final List<String> locations; @MetastoreFieldDefinition(scopes = {SEGMENT, PARTITION}) private final List<String> partitionValues; @MetastoreFieldDefinition(scopes = {SEGMENT, FILE, ROW_GROUP}) private final String path; @MetastoreFieldDefinition(scopes = {ROW_GROUP}) private final Integer rowGroupIndex; @MetastoreFieldDefinition(scopes = {ROW_GROUP}) private final Map<String, Float> hostAffinity; private TableMetadataUnit(Builder builder) { this.storagePlugin = builder.storagePlugin; this.workspace = builder.workspace; this.tableName = builder.tableName; this.owner = builder.owner; this.tableType = builder.tableType; this.metadataType = builder.metadataType; this.metadataKey = builder.metadataKey; this.location = builder.location; this.interestingColumns = builder.interestingColumns; this.schema = builder.schema; this.columnsStatistics = builder.columnsStatistics; this.metadataStatistics = builder.metadataStatistics; this.lastModifiedTime = builder.lastModifiedTime; this.partitionKeys = builder.partitionKeys; this.additionalMetadata = builder.additionalMetadata; this.metadataIdentifier = builder.metadataIdentifier; this.column = builder.column; this.locations = builder.locations; this.partitionValues = builder.partitionValues; this.path = builder.path; this.rowGroupIndex = builder.rowGroupIndex; this.hostAffinity = builder.hostAffinity; } public static Builder builder() { return new Builder(); } public String storagePlugin() { return storagePlugin; } public String workspace() { return workspace; } public String tableName() { return tableName; } public String owner() { return owner; } public String tableType() { return tableType; } public String metadataType() { return metadataType; } public String metadataKey() { return metadataKey; } public String location() { return location; } public List<String> interestingColumns() { return interestingColumns; } public String schema() { return schema; } public Map<String, String> columnsStatistics() { return columnsStatistics; } public List<String> metadataStatistics() { return metadataStatistics; } public Long lastModifiedTime() { return lastModifiedTime; } public Map<String, String> partitionKeys() { return partitionKeys; } public String additionalMetadata() { return additionalMetadata; } public String metadataIdentifier() { return metadataIdentifier; } public String column() { return column; } public List<String> locations() { return locations; } public List<String> partitionValues() { return partitionValues; } public String path() { return path; } public Integer rowGroupIndex() { return rowGroupIndex; } public Map<String, Float> hostAffinity() { return hostAffinity; } public Builder toBuilder() { return TableMetadataUnit.builder() .storagePlugin(storagePlugin) .workspace(workspace) .tableName(tableName) .owner(owner) .tableType(tableType) .metadataType(metadataType) .metadataKey(metadataKey) .location(location) .interestingColumns(interestingColumns) .schema(schema) .columnsStatistics(columnsStatistics) .metadataStatistics(metadataStatistics) .lastModifiedTime(lastModifiedTime) .partitionKeys(partitionKeys) .additionalMetadata(additionalMetadata) .metadataIdentifier(metadataIdentifier) .column(column) .locations(locations) .partitionValues(partitionValues) .path(path) .rowGroupIndex(rowGroupIndex) .hostAffinity(hostAffinity); } @Override public int hashCode() { return Objects.hash(storagePlugin, workspace, tableName, owner, tableType, metadataType, metadataKey, location, interestingColumns, schema, columnsStatistics, metadataStatistics, lastModifiedTime, partitionKeys, additionalMetadata, metadataIdentifier, column, locations, partitionValues, path, rowGroupIndex, hostAffinity); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TableMetadataUnit that = (TableMetadataUnit) o; return Objects.equals(storagePlugin, that.storagePlugin) && Objects.equals(workspace, that.workspace) && Objects.equals(tableName, that.tableName) && Objects.equals(owner, that.owner) && Objects.equals(tableType, that.tableType) && Objects.equals(metadataType, that.metadataType) && Objects.equals(metadataKey, that.metadataKey) && Objects.equals(location, that.location) && Objects.equals(interestingColumns, that.interestingColumns) && Objects.equals(schema, that.schema) && Objects.equals(columnsStatistics, that.columnsStatistics) && Objects.equals(metadataStatistics, that.metadataStatistics) && Objects.equals(lastModifiedTime, that.lastModifiedTime) && Objects.equals(partitionKeys, that.partitionKeys) && Objects.equals(additionalMetadata, that.additionalMetadata) && Objects.equals(metadataIdentifier, that.metadataIdentifier) && Objects.equals(column, that.column) && Objects.equals(locations, that.locations) && Objects.equals(partitionValues, that.partitionValues) && Objects.equals(path, that.path) && Objects.equals(rowGroupIndex, that.rowGroupIndex) && Objects.equals(hostAffinity, that.hostAffinity); } @Override public String toString() { return new StringJoiner(",\n", TableMetadataUnit.class.getSimpleName() + "[", "]") .add("storagePlugin=" + storagePlugin) .add("workspace=" + workspace) .add("tableName=" + tableName) .add("owner=" + owner) .add("tableType=" + tableType) .add("metadataType=" + metadataType) .add("metadataKey=" + metadataKey) .add("location=" + location) .add("interestingColumns=" + interestingColumns) .add("schema=" + schema) .add("columnsStatistics=" + columnsStatistics) .add("metadataStatistics=" + metadataStatistics) .add("lastModifiedTime=" + lastModifiedTime) .add("partitionKeys=" + partitionKeys) .add("additionalMetadata=" + additionalMetadata) .add("metadataIdentifier=" + metadataIdentifier) .add("column=" + column) .add("locations=" + locations) .add("partitionValues=" + partitionValues) .add("path=" + path) .add("rowGroupIndex=" + rowGroupIndex) .add("hostAffinity=" + hostAffinity) .toString(); } public static class Builder { private String storagePlugin; private String workspace; private String tableName; private String owner; private String tableType; private String metadataType; private String metadataKey; private String location; private List<String> interestingColumns; private String schema; private Map<String, String> columnsStatistics; private List<String> metadataStatistics; private Long lastModifiedTime; private Map<String, String> partitionKeys; private String additionalMetadata; private String metadataIdentifier; private String column; private List<String> locations; private List<String> partitionValues; private String path; private Integer rowGroupIndex; private Map<String, Float> hostAffinity; public Builder storagePlugin(String storagePlugin) { this.storagePlugin = storagePlugin; return this; } public Builder workspace(String workspace) { this.workspace = workspace; return this; } public Builder tableName(String tableName) { this.tableName = tableName; return this; } public Builder owner(String owner) { this.owner = owner; return this; } public Builder tableType(String tableType) { this.tableType = tableType; return this; } public Builder metadataType(String metadataType) { this.metadataType = metadataType; return this; } public Builder metadataKey(String metadataKey) { this.metadataKey = metadataKey; return this; } public Builder location(String location) { this.location = location; return this; } public Builder interestingColumns(List<String> interestingColumns) { this.interestingColumns = interestingColumns; return this; } public Builder schema(String schema) { this.schema = schema; return this; } public Builder columnsStatistics(Map<String, String> columnsStatistics) { this.columnsStatistics = columnsStatistics; return this; } public Builder metadataStatistics(List<String> metadataStatistics) { this.metadataStatistics = metadataStatistics; return this; } public Builder lastModifiedTime(Long lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; return this; } public Builder partitionKeys(Map<String, String> partitionKeys) { this.partitionKeys = partitionKeys; return this; } public Builder additionalMetadata(String additionalMetadata) { this.additionalMetadata = additionalMetadata; return this; } public Builder metadataIdentifier(String metadataIdentifier) { this.metadataIdentifier = metadataIdentifier; return this; } public Builder column(String column) { this.column = column; return this; } public Builder locations(List<String> locations) { this.locations = locations; return this; } public Builder partitionValues(List<String> partitionValues) { this.partitionValues = partitionValues; return this; } public Builder path(String path) { this.path = path; return this; } public Builder rowGroupIndex(Integer rowGroupIndex) { this.rowGroupIndex = rowGroupIndex; return this; } public Builder hostAffinity(Map<String, Float> hostAffinity) { this.hostAffinity = hostAffinity; return this; } public TableMetadataUnit build() { return new TableMetadataUnit(this); } } /** * Contains schema metadata, including lists of columns which belong to table, segment, file, row group * or partition. Also provides unit class getters and its builder setters method handlers * to optimize reflection calls. */ public static class Schema { private final List<String> tableColumns; private final List<String> segmentColumns; private final List<String> fileColumns; private final List<String> rowGroupColumns; private final List<String> partitionColumns; private final Map<String, MethodHandle> unitGetters; private final Map<String, MethodHandle> unitBuilderSetters; private Schema(List<String> tableColumns, List<String> segmentColumns, List<String> fileColumns, List<String> rowGroupColumns, List<String> partitionColumns, Map<String, MethodHandle> unitGetters, Map<String, MethodHandle> unitBuilderSetters) { this.tableColumns = tableColumns; this.segmentColumns = segmentColumns; this.fileColumns = fileColumns; this.rowGroupColumns = rowGroupColumns; this.partitionColumns = partitionColumns; this.unitGetters = unitGetters; this.unitBuilderSetters = unitBuilderSetters; } /** * Obtains field information for the given unit class and its builder. * Traverses through the list of unit class fields which are annotated with {@link MetastoreFieldDefinition} * and creates instance of {@link Schema} class that holds unit class schema metadata. * Assumes that given unit class and its builder getters and setters method names * are the same as annotated fields names. */ public static Schema of(Class<?> unitClass, Class<?> builderClass) { List<String> tableColumns = new ArrayList<>(); List<String> segmentColumns = new ArrayList<>(); List<String> fileColumns = new ArrayList<>(); List<String> rowGroupColumns = new ArrayList<>(); List<String> partitionColumns = new ArrayList<>(); Map<String, MethodHandle> unitGetters = new HashMap<>(); Map<String, MethodHandle> unitBuilderSetters = new HashMap<>(); MethodHandles.Lookup gettersLookup = MethodHandles.publicLookup().in(unitClass); MethodHandles.Lookup settersLookup = MethodHandles.publicLookup().in(builderClass); for (Field field : unitClass.getDeclaredFields()) { MetastoreFieldDefinition definition = field.getAnnotation(MetastoreFieldDefinition.class); if (definition == null) { continue; } String name = field.getName(); for (MetadataType scope : definition.scopes()) { switch (scope) { case TABLE: tableColumns.add(name); break; case SEGMENT: segmentColumns.add(name); break; case FILE: fileColumns.add(name); break; case ROW_GROUP: rowGroupColumns.add(name); break; case PARTITION: partitionColumns.add(name); break; case ALL: tableColumns.add(name); segmentColumns.add(name); fileColumns.add(name); rowGroupColumns.add(name); partitionColumns.add(name); break; } } Class<?> type = field.getType(); try { MethodHandle getter = gettersLookup.findVirtual(unitClass, name, MethodType.methodType(type)); unitGetters.put(name, getter); MethodHandle setter = settersLookup.findVirtual(builderClass, name, MethodType.methodType(builderClass, type)); unitBuilderSetters.put(name, setter); } catch (ReflectiveOperationException e) { throw new MetastoreException(String.format("Unable to init unit setter / getter method handlers " + "for unit [%s] and its builder [%s] classes", unitClass.getSimpleName(), builderClass.getSimpleName()), e); } } return new Schema(tableColumns, segmentColumns, fileColumns, rowGroupColumns, partitionColumns, unitGetters, unitBuilderSetters); } public List<String> tableColumns() { return tableColumns; } public List<String> segmentColumns() { return segmentColumns; } public List<String> fileColumns() { return fileColumns; } public List<String> rowGroupColumns() { return rowGroupColumns; } public List<String> partitionColumns() { return partitionColumns; } public Map<String, MethodHandle> unitGetters() { return unitGetters; } public Map<String, MethodHandle> unitBuilderSetters() { return unitBuilderSetters; } } }
apache-2.0
Pingsh/Mix
app/src/main/java/com/example/sphinx/mix/utils/GradientDrawableUtils.java
13159
package com.example.sphinx.mix.utils; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.os.Build; import android.support.v4.graphics.ColorUtils; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.lang.reflect.Field; public class GradientDrawableUtils extends DrawableUtils { private static Field sPaddingField; private static Field sStPaddingField; private static Field sStGradientPositions; private static Field sStGradientAngle; @Override protected Drawable inflateDrawable(Context context, XmlPullParser parser, AttributeSet attrs) throws XmlPullParserException, IOException { GradientDrawable gradientDrawable = new GradientDrawable(); inflateGradientRootElement(context, attrs, gradientDrawable); int type; final int innerDepth = parser.getDepth() + 1; int depth; while ((type = parser.next()) != XmlPullParser.END_DOCUMENT && ((depth = parser.getDepth()) >= innerDepth || type != XmlPullParser.END_TAG)) { if (type != XmlPullParser.START_TAG) { continue; } if (depth > innerDepth) { continue; } String name = parser.getName(); if (name.equals("size")) { final int width = getAttrDimensionPixelSize(context, attrs, android.R.attr.width); final int height = getAttrDimensionPixelSize(context, attrs, android.R.attr.height); gradientDrawable.setSize(width, height); } else if (name.equals("gradient") && Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { final float centerX = getAttrFloatOrFraction(context, attrs, android.R.attr.centerX, 0.5f, 1.0f, 1.0f); final float centerY = getAttrFloatOrFraction(context, attrs, android.R.attr.centerY, 0.5f, 1.0f, 1.0f); gradientDrawable.setGradientCenter(centerX, centerY); final boolean useLevel = getAttrBoolean(context, attrs, android.R.attr.useLevel, false); gradientDrawable.setUseLevel(useLevel); final int gradientType = getAttrInt(context, attrs, android.R.attr.type, 0); gradientDrawable.setGradientType(gradientType); final int startColor = getAttrColor(context, attrs, android.R.attr.startColor, Color.TRANSPARENT); final int centerColor = getAttrColor(context, attrs, android.R.attr.centerColor, Color.TRANSPARENT); final int endColor = getAttrColor(context, attrs, android.R.attr.endColor, Color.TRANSPARENT); if (!getAttrHasValue(context, attrs, android.R.attr.centerColor)) { gradientDrawable.setColors(new int[]{startColor, endColor}); } else { gradientDrawable.setColors(new int[]{startColor, centerColor, endColor}); setStGradientPositions(gradientDrawable.getConstantState(), 0.0f, centerX != 0.5f ? centerX : centerY, 1f); } if (gradientType == GradientDrawable.LINEAR_GRADIENT) { int angle = (int) getAttrFloat(context, attrs, android.R.attr.angle, 0.0f); angle %= 360; if (angle % 45 != 0) { throw new XmlPullParserException("<gradient> tag requires" + "'angle' attribute to " + "be a multiple of 45"); } setStGradientAngle(gradientDrawable.getConstantState(), angle); switch (angle) { case 0: gradientDrawable.setOrientation(GradientDrawable.Orientation.LEFT_RIGHT); break; case 45: gradientDrawable.setOrientation(GradientDrawable.Orientation.BL_TR); break; case 90: gradientDrawable.setOrientation(GradientDrawable.Orientation.BOTTOM_TOP); break; case 135: gradientDrawable.setOrientation(GradientDrawable.Orientation.BR_TL); break; case 180: gradientDrawable.setOrientation(GradientDrawable.Orientation.RIGHT_LEFT); break; case 225: gradientDrawable.setOrientation(GradientDrawable.Orientation.TR_BL); break; case 270: gradientDrawable.setOrientation(GradientDrawable.Orientation.TOP_BOTTOM); break; case 315: gradientDrawable.setOrientation(GradientDrawable.Orientation.TL_BR); break; } } else { setGradientRadius(context, attrs, gradientDrawable, gradientType); } } else if (name.equals("solid")) { int color = getAttrColor(context, attrs, android.R.attr.color, Color.TRANSPARENT); gradientDrawable.setColor(getAlphaColor(color, getAttrFloat(context, attrs, android.R.attr.alpha, 1.0f))); } else if (name.equals("stroke")) { final float alphaMod = getAttrFloat(context, attrs, android.R.attr.alpha, 1.0f); final int strokeColor = getAttrColor(context, attrs, android.R.attr.color, Color.TRANSPARENT); final int strokeWidth = getAttrDimensionPixelSize(context, attrs, android.R.attr.width); final float dashWidth = getAttrDimension(context, attrs, android.R.attr.dashWidth); if (dashWidth != 0.0f) { final float dashGap = getAttrDimension(context, attrs, android.R.attr.dashGap); gradientDrawable.setStroke(strokeWidth, getAlphaColor(strokeColor, alphaMod), dashWidth, dashGap); } else { gradientDrawable.setStroke(strokeWidth, getAlphaColor(strokeColor, alphaMod)); } } else if (name.equals("corners")) { final int radius = getAttrDimensionPixelSize(context, attrs, android.R.attr.radius); gradientDrawable.setCornerRadius(radius); final int topLeftRadius = getAttrDimensionPixelSize(context, attrs, android.R.attr.topLeftRadius, radius); final int topRightRadius = getAttrDimensionPixelSize(context, attrs, android.R.attr.topRightRadius, radius); final int bottomLeftRadius = getAttrDimensionPixelSize(context, attrs, android.R.attr.bottomLeftRadius, radius); final int bottomRightRadius = getAttrDimensionPixelSize(context, attrs, android.R.attr.bottomRightRadius, radius); if (topLeftRadius != radius || topRightRadius != radius || bottomLeftRadius != radius || bottomRightRadius != radius) { // The corner radii are specified in clockwise order (see Path.addRoundRect()) gradientDrawable.setCornerRadii(new float[]{ topLeftRadius, topLeftRadius, topRightRadius, topRightRadius, bottomRightRadius, bottomRightRadius, bottomLeftRadius, bottomLeftRadius }); } } else if (name.equals("padding")) { final int paddingLeft = getAttrDimensionPixelOffset(context, attrs, android.R.attr.left); final int paddingTop = getAttrDimensionPixelOffset(context, attrs, android.R.attr.top); final int paddingRight = getAttrDimensionPixelOffset(context, attrs, android.R.attr.right); final int paddingBottom = getAttrDimensionPixelOffset(context, attrs, android.R.attr.bottom); if (paddingLeft != 0 || paddingTop != 0 || paddingRight != 0 || paddingBottom != 0) { final Rect pad = new Rect(); pad.set(paddingLeft, paddingTop, paddingRight, paddingBottom); try { if (sPaddingField == null) { sPaddingField = GradientDrawable.class.getDeclaredField("mPadding"); sPaddingField.setAccessible(true); } sPaddingField.set(gradientDrawable, pad); if (sStPaddingField == null) { sStPaddingField = Class.forName("android.graphics.drawable.GradientDrawable$GradientState").getDeclaredField("mPadding"); sStPaddingField.setAccessible(true); } sStPaddingField.set(gradientDrawable.getConstantState(), pad); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } else { Log.w("drawable", "Bad element under <shape>: " + name); } } return gradientDrawable; } void inflateGradientRootElement(Context context, AttributeSet attrs, GradientDrawable gradientDrawable) { int shape = getAttrInt(context, attrs, android.R.attr.shape, GradientDrawable.RECTANGLE); gradientDrawable.setShape(shape); boolean dither = getAttrBoolean(context, attrs, android.R.attr.dither, false); gradientDrawable.setDither(dither); } void setGradientRadius(Context context, AttributeSet attrs, GradientDrawable drawable, int gradientType) throws XmlPullParserException { TypedArray a = obtainAttributes(context.getResources(), context.getTheme(), attrs, new int[]{android.R.attr.gradientRadius}); TypedValue value = a.peekValue(0); if (value != null) { boolean radiusRel = value.type == TypedValue.TYPE_FRACTION; drawable.setGradientRadius(radiusRel ? value.getFraction(1.0f, 1.0f) : value.getFloat()); } else if (gradientType == GradientDrawable.RADIAL_GRADIENT) { throw new XmlPullParserException( "<gradient> tag requires 'gradientRadius' " + "attribute with radial type"); } a.recycle(); } void setStGradientAngle(Drawable.ConstantState constantState, int angle) { try { if (sStGradientAngle == null) { sStGradientAngle = Class.forName("android.graphics.drawable.GradientDrawable$GradientState").getDeclaredField("mAngle"); sStGradientAngle.setAccessible(true); } sStGradientAngle.set(constantState, angle); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } void setStGradientPositions(Drawable.ConstantState constantState, float... positions) { try { if (sStGradientPositions == null) { sStGradientPositions = Class.forName("android.graphics.drawable.GradientDrawable$GradientState").getDeclaredField("mPositions"); sStGradientPositions.setAccessible(true); } sStGradientPositions.set(constantState, positions); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } float getAttrFloatOrFraction(Context context, AttributeSet attrs, int attr, float defaultValue, float base, float pbase) { TypedArray a = obtainAttributes(context.getResources(), context.getTheme(), attrs, new int[]{attr}); TypedValue tv = a.peekValue(0); float v = defaultValue; if (tv != null) { boolean isFraction = tv.type == TypedValue.TYPE_FRACTION; v = isFraction ? tv.getFraction(base, pbase) : tv.getFloat(); } a.recycle(); return v; } int getAlphaColor(int baseColor, float alpha) { return alpha != 1.0f ? ColorUtils.setAlphaComponent(baseColor, Math.round(Color.alpha(baseColor) * alpha)) : baseColor; } }
apache-2.0
MarcGuiot/globsframework
src/main/java/org/globsframework/metamodel/fields/FieldVisitorWithContext.java
4639
package org.globsframework.metamodel.fields; import org.globsframework.metamodel.Field; public interface FieldVisitorWithContext<C> { void visitInteger(IntegerField field, C context) throws Exception; void visitIntegerArray(IntegerArrayField field, C context) throws Exception; void visitDouble(DoubleField field, C context) throws Exception; void visitDoubleArray(DoubleArrayField field, C context) throws Exception; void visitString(StringField field, C context) throws Exception; void visitStringArray(StringArrayField field, C context) throws Exception; void visitBoolean(BooleanField field, C context) throws Exception; void visitBooleanArray(BooleanArrayField field, C context) throws Exception; void visitBigDecimal(BigDecimalField field, C context) throws Exception; void visitBigDecimalArray(BigDecimalArrayField field, C context) throws Exception; void visitLong(LongField field, C context) throws Exception; void visitLongArray(LongArrayField field, C context) throws Exception; void visitDate(DateField field, C context) throws Exception; void visitDateTime(DateTimeField field, C context) throws Exception; void visitBlob(BlobField field, C context) throws Exception; void visitGlob(GlobField field, C context) throws Exception; void visitGlobArray(GlobArrayField field, C context) throws Exception; void visitUnionGlob(GlobUnionField field, C context) throws Exception; void visitUnionGlobArray(GlobArrayUnionField field, C context) throws Exception; class AbstractFieldVisitor<C> implements FieldVisitorWithContext<C> { public void visitInteger(IntegerField field, C context) throws Exception { notManaged(field, context); } public void visitIntegerArray(IntegerArrayField field, C context) throws Exception { notManaged(field, context); } public void visitDouble(DoubleField field, C context) throws Exception { notManaged(field, context); } public void visitDoubleArray(DoubleArrayField field, C context) throws Exception { notManaged(field, context); } public void visitString(StringField field, C context) throws Exception { notManaged(field, context); } public void visitStringArray(StringArrayField field, C context) throws Exception { notManaged(field, context); } public void visitBoolean(BooleanField field, C context) throws Exception { notManaged(field, context); } public void visitBooleanArray(BooleanArrayField field, C context) throws Exception { notManaged(field, context); } public void visitBigDecimal(BigDecimalField field, C context) throws Exception { notManaged(field, context); } public void visitBigDecimalArray(BigDecimalArrayField field, C context) throws Exception { notManaged(field, context); } public void visitLong(LongField field, C context) throws Exception { notManaged(field, context); } public void visitLongArray(LongArrayField field, C context) throws Exception { notManaged(field, context); } public void visitDate(DateField field, C context) throws Exception { notManaged(field, context); } public void visitDateTime(DateTimeField field, C context) throws Exception { notManaged(field, context); } public void visitBlob(BlobField field, C context) throws Exception { notManaged(field, context); } public void visitGlob(GlobField field, C context) throws Exception { notManaged(field, context); } public void visitGlobArray(GlobArrayField field, C context) throws Exception { notManaged(field, context); } public void visitUnionGlob(GlobUnionField field, C context) throws Exception { notManaged(field, context); } public void visitUnionGlobArray(GlobArrayUnionField field, C context) throws Exception { notManaged(field, context); } public void notManaged(Field field, C context) throws Exception { } } class AbstractWithErrorVisitor<C> extends AbstractFieldVisitor<C> { public void notManaged(Field field, C context) throws Exception { throw new RuntimeException(field.getFullName() + " of type " + field.getDataType() + " not managed on " + getClass().getName()); } } }
apache-2.0
java110/MicroCommunity
service-api/src/main/java/com/java110/api/bmo/ownerRepair/IOwnerRepairBMO.java
1663
package com.java110.api.bmo.ownerRepair; import com.alibaba.fastjson.JSONObject; import com.java110.api.bmo.IApiBaseBMO; import com.java110.core.context.DataFlowContext; /** * @ClassName IOwnerRepairBMO * @Description TODO * @Author wuxw * @Date 2020/3/9 23:19 * @Version 1.0 * add by wuxw 2020/3/9 **/ public interface IOwnerRepairBMO extends IApiBaseBMO { public void modifyBusinessRepairUser(JSONObject paramInJson, DataFlowContext dataFlowContext); public void modifyBusinessRepair(JSONObject paramInJson, DataFlowContext dataFlowContext); /** * 添加小区信息 * * @param paramInJson 接口调用放传入入参 * @param dataFlowContext 数据上下文 * @return 订单服务能够接受的报文 */ public void deleteOwnerRepair(JSONObject paramInJson, DataFlowContext dataFlowContext); public void addBusinessRepairUser(JSONObject paramInJson, DataFlowContext dataFlowContext); public void modifyBusinessRepairDispatch(JSONObject paramInJson, DataFlowContext dataFlowContext,String state); /** * 添加小区信息 * * @param paramInJson 接口调用放传入入参 * @param dataFlowContext 数据上下文 * @return 订单服务能够接受的报文 */ public void addOwnerRepair(JSONObject paramInJson, DataFlowContext dataFlowContext); /** * 添加业主报修信息 * * @param paramInJson 接口调用放传入入参 * @param dataFlowContext 数据上下文 * @return 订单服务能够接受的报文 */ public void updateOwnerRepair(JSONObject paramInJson, DataFlowContext dataFlowContext); }
apache-2.0
gspandy/divconq
divconq.web/src/main/java/divconq/http/multipart/MemoryAttribute.java
4636
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package divconq.http.multipart; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelException; import io.netty.handler.codec.http.HttpConstants; import java.io.IOException; import java.nio.charset.Charset; import static io.netty.buffer.Unpooled.*; /** * Memory implementation of Attributes */ public class MemoryAttribute extends AbstractMemoryHttpData implements Attribute { public MemoryAttribute(String name) { this(name, HttpConstants.DEFAULT_CHARSET); } public MemoryAttribute(String name, Charset charset) { super(name, charset, 0); } public MemoryAttribute(String name, String value) throws IOException { this(name, value, HttpConstants.DEFAULT_CHARSET); // Attribute have no default size } public MemoryAttribute(String name, String value, Charset charset) throws IOException { super(name, charset, 0); // Attribute have no default size setValue(value); } @Override public HttpDataType getHttpDataType() { return HttpDataType.Attribute; } @Override public String getValue() { return getByteBuf().toString(getCharset()); } @Override public void setValue(String value) throws IOException { if (value == null) { throw new NullPointerException("value"); } byte [] bytes = value.getBytes(getCharset()); checkSize(bytes.length); ByteBuf buffer = wrappedBuffer(bytes); if (definedSize > 0) { definedSize = buffer.readableBytes(); } setContent(buffer); } @Override public void addContent(ByteBuf buffer, boolean last) throws IOException { int localsize = buffer.readableBytes(); checkSize(size + localsize); if (definedSize > 0 && definedSize < size + localsize) { definedSize = size + localsize; } super.addContent(buffer, last); } @Override public int hashCode() { return getName().hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof Attribute)) { return false; } Attribute attribute = (Attribute) o; return getName().equalsIgnoreCase(attribute.getName()); } @Override public int compareTo(InterfaceHttpData other) { if (!(other instanceof Attribute)) { throw new ClassCastException("Cannot compare " + getHttpDataType() + " with " + other.getHttpDataType()); } return compareTo((Attribute) other); } public int compareTo(Attribute o) { return getName().compareToIgnoreCase(o.getName()); } @Override public String toString() { return getName() + '=' + getValue(); } @Override public Attribute copy() { MemoryAttribute attr = new MemoryAttribute(getName()); attr.setCharset(getCharset()); ByteBuf content = content(); if (content != null) { try { attr.setContent(content.copy()); } catch (IOException e) { throw new ChannelException(e); } } return attr; } @Override public Attribute duplicate() { MemoryAttribute attr = new MemoryAttribute(getName()); attr.setCharset(getCharset()); ByteBuf content = content(); if (content != null) { try { attr.setContent(content.duplicate()); } catch (IOException e) { throw new ChannelException(e); } } return attr; } @Override public Attribute retain() { super.retain(); return this; } @Override public Attribute retain(int increment) { super.retain(increment); return this; } }
apache-2.0
lcamilo15/hapi-fhir
hapi-fhir-structures-hl7org-dstu2/src/main/java/org/hl7/fhir/instance/model/valuesets/ClassificationOrContextEnumFactory.java
2561
package org.hl7.fhir.instance.model.valuesets; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Generated on Tue, Jul 14, 2015 17:35-0400 for FHIR v0.5.0 import org.hl7.fhir.instance.model.EnumFactory; public class ClassificationOrContextEnumFactory implements EnumFactory<ClassificationOrContext> { public ClassificationOrContext fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) return null; if ("classification".equals(codeString)) return ClassificationOrContext.CLASSIFICATION; if ("context".equals(codeString)) return ClassificationOrContext.CONTEXT; throw new IllegalArgumentException("Unknown ClassificationOrContext code '"+codeString+"'"); } public String toCode(ClassificationOrContext code) { if (code == ClassificationOrContext.CLASSIFICATION) return "classification"; if (code == ClassificationOrContext.CONTEXT) return "context"; return "?"; } }
apache-2.0
thomasjungblut/thomasjungblut-common
src/main/java/de/jungblut/distance/HaversineDistance.java
1260
package de.jungblut.distance; import de.jungblut.math.DoubleVector; import org.apache.commons.math3.util.FastMath; import java.util.Arrays; /** * Haversine distance implementation that picks up lat/lng in degrees at * array/vector index 0 and 1 and returns the distance in meters between those * two vectors. * * @author thomas.jungblut */ public final class HaversineDistance implements DistanceMeasurer { private static final double EARTH_RADIUS_IN_METERS = 6372797.560856; @Override public final double measureDistance(double[] a, double[] b) { // lat must be on index 0 and lng on index 1 a = Arrays.copyOf(a, 2); b = Arrays.copyOf(b, 2); // first convert them to radians a[0] = a[0] / 180.0 * Math.PI; a[1] = a[1] / 180.0 * Math.PI; b[0] = b[0] / 180.0 * Math.PI; b[1] = b[1] / 180.0 * Math.PI; return FastMath.acos(FastMath.sin(a[0]) * FastMath.sin(b[0]) + FastMath.cos(a[0]) * FastMath.cos(b[0]) * FastMath.cos(a[1] - b[1])) * EARTH_RADIUS_IN_METERS; } @Override public final double measureDistance(DoubleVector vec1, DoubleVector vec2) { return measureDistance(vec1.toArray(), vec2.toArray()); } }
apache-2.0
Beshelmek/SimpleMineCraftLauncher
SimpleMinecraftLauncher1/src/ru/er_log/components/Frame.java
19582
package ru.er_log.components; import com.sun.awt.AWTUtilities; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionAdapter; import java.awt.image.BufferedImage; import java.io.File; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPasswordField; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import ru.er_log.Settings; import ru.er_log.Starter; import static ru.er_log.components.Guard.StartGuard; import static ru.er_log.components.Launcher.checkLauncher; import static ru.er_log.components.startMinecraft.appletMinecraft; import static ru.er_log.components.startMinecraft.startMinecraft; import ru.er_log.splash.SplashFrame; import ru.er_log.utils.BaseUtils; import static ru.er_log.utils.BaseUtils.*; import ru.er_log.utils.GuardUtils; import ru.er_log.utils.ImageUtils; import static ru.er_log.utils.StartUtils.CheckLauncherPach; import ru.er_log.utils.StreamUtils; import ru.er_log.utils.ThemeUtils; /** * * @author Goodvise * */ public class Frame extends JFrame implements FocusListener, KeyListener { public static String[] authData = null; public static String[] onlineData = null; private static int debLine = 1; public JButton turn = new JButton(); public JButton close = new JButton(); private int X = 0, Y = 0; public static Frame frame; public GuardUtils gu = new GuardUtils(); public Panel panel = new Panel(); public JLabel logotype = new JLabel(new ImageIcon(Panel.logotype)); public ComboBox serversList = new ComboBox(null, 324, null); public JTextPane news_pane = new JTextPane(); public JScrollPane newsScPane = new JScrollPane(news_pane); public JTextField login = new JTextField(); public JPasswordField password = new JPasswordField(); public JButton toGame = new JButton("В игру"); public JButton take = new JButton("Продолжить"); public JButton exit = new JButton("Выход"); public JButton upd_take = new JButton("Обновить"); public JButton doAuth = new JButton("Войти"); public JButton settings = new JButton("Настройки"); public JButton set_cancel = new JButton("Отмена"); public JButton set_take = new JButton("Принять"); public JCheckBox set_remember = new JCheckBox("Запомнить логин и пароль"); public JCheckBox set_update = new JCheckBox("Перекачать клиент игры"); public JCheckBox set_full = new JCheckBox("Полноэкранный режим"); public JCheckBox set_offline = new JCheckBox("Оффлайн режим"); public JTextField set_memory = new JTextField("32".equals(System.getProperty("sun.arch.data.model")) ? "512" : "1024"); public Frame() { if (getPlatform() != 0) { this.setUndecorated(true); AWTUtilities.setWindowOpaque(this, false); this.setPreferredSize(new Dimension(Settings.frame_width, Settings.frame_height)); } else this.setPreferredSize(new Dimension(Settings.frame_width + Settings.linux_frame_w, Settings.frame_height + Settings.linux_frame_h)); this.setSize(this.getPreferredSize()); this.setTitle(Settings.title + " :: " + Settings.version); this.setResizable(false); this.setLocationRelativeTo(null); this.setLayout(new BorderLayout()); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setIconImage(Panel.favicon); mouseListener(); try { ThemeUtils.updateStyle(this); } catch(Exception e) {} login.setText(Settings.login_text); login.addActionListener(null); login.addFocusListener(this); password.setText(Settings.pass_text); password.addActionListener(null); password.addFocusListener(this); news_pane.setOpaque(false); news_pane.setBorder(null); news_pane.setContentType("text/html"); news_pane.setEditable(false); news_pane.setFocusable(false); news_pane.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) openLink(e.getURL().toString()); } }); newsScPane.setOpaque(false); newsScPane.getViewport().setOpaque(false); newsScPane.setBorder(null); newsScPane.setBounds(Settings.frame_width + 25, 10 + 35, Panel.news_back.getWidth() - 25 * 2, 430 - 35 * 2); if (Settings.use_monitoring) serversList.addMouseListener(new MouseListener() { public void mouseReleased(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseClicked(MouseEvent e) { if(!serversList.error) { if (serversList.getPressed() || e.getButton() != MouseEvent.BUTTON1) return; if (serversList.getSelectValue()) { panel.waitIcon(true, 0); StreamUtils.getServerOnline(); } } } }); logotype.setBounds((Settings.frame_width - Panel.logotype.getWidth()) / 2, Settings.logo_indent, Panel.logotype.getWidth(), Panel.logotype.getHeight()); if (Settings.use_logo_as_url) logotype.addMouseListener(new MouseListener() { public void mouseReleased(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseExited(MouseEvent e) { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } public void mouseEntered(MouseEvent e) { setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } public void mouseClicked(MouseEvent e) { openLink("http://" + (Settings.logo_url.isEmpty() ? Settings.domain : Settings.logo_url)); } }); panel.addKeyListener(this); login.addKeyListener(this); password.addKeyListener(this); addFrameElements(false); addAuthElements(false); this.setContentPane(panel); } public static void beforeStart(SplashFrame sframe) throws Exception { report("Запуск лаунчера: " + Settings.version); try { if (sframe!= null) sframe.setStatus("установка системного LnF..."); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); report("Установка системного LnF успешно завершена"); } catch (Exception e) { report("Не удалось установить системный LnF"); } if (sframe!= null) sframe.setStatus("Идет загрузка настроек..."); onlineData = baseUtils.loadOnlineSettings(); if (sframe!= null) sframe.setStatus("Идет проверка..."); setTheme(); if(BaseUtils.getPlatform() == 2){ if(Settings.test_mode != true){ StartGuard(); Frame.report("Запуск версии для системы: Windows."); }else{ Frame.report("Запуск тестовой версии лаунчера."); checkLauncher(); } }else{ Frame.report("Запуск версии для системы: Mac, Linux."); checkLauncher(); } } public static void start(final SplashFrame sframe) throws Exception { frame = new Frame(); frame.panel.setAuthState(); boolean Internet_connected = checkInternetConnection(); readConfig(frame); if (Settings.use_loading_news) { Color c = ThemeElements.staticThemeColor; StreamUtils.loadNewsPage(getURLSc("jcr_news.php?color=rgb(" + c.getRed() + "," + c.getGreen() + "," + c.getBlue() + ")")); } if (GuardUtils.use_process_check) { if (GuardUtils.checkProcesses()) { frame.elEnabled(false); frame.setAlert("Завершите сторонние процессы", 3, 0); reportErr("В системе обнаружены запрещенные запущенные процессы"); return; } if (GuardUtils.use_process_check_timer) { new Timer(GuardUtils.time_for_process_check * 1000, new ActionListener() { public void actionPerformed(ActionEvent e) { startMinecraft(); appletMinecraft(); File smcguard = new File(BaseUtils.getClientDirectory() + File.separator + "bin" + File.separator + "minecraft1.jar"); File smcguard1 = new File(BaseUtils.getClientDirectory() + File.separator + "bin" + File.separator + "forge1.jar"); File smcguard2 = new File(BaseUtils.getClientDirectory() + File.separator + "bin" + File.separator + "minecraft2.jar"); if(smcguard.exists()){ if(smcguard.delete()){; Runtime.getRuntime().exit(1); } } if(smcguard1.exists()){ if(smcguard1.delete()){ Runtime.getRuntime().exit(1); } } if(smcguard2.exists()){ if(smcguard2.delete()){ Runtime.getRuntime().exit(1); } } if (GuardUtils.checkProcesses()) { reportErr("В системе обнаружены запрещенные запущенные процессы"); reportErr("Завершение работы программы..."); System.exit(1); } } }).start(); } } if (Settings.use_update_mon && Internet_connected) { frame.panel.waitIcon(true, 0); StreamUtils.getServerOnline(); } SwingUtilities.invokeLater(new Runnable() { public void run() { if (sframe != null) sframe.dispose(); } }); frame.show(); } private void mouseListener() { if (getPlatform() == 0) return; this.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { setLocation(getX() + e.getX() - X, getY() + e.getY() - Y); } }); this.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { X = e.getX(); Y = e.getY(); } }); } public void elEnabled(boolean enable) { serversList.setEnabled(enable); login.setEnabled(enable); password.setEnabled(enable); doAuth.setEnabled(enable); take.setEnabled(enable); settings.setEnabled(enable); // exit.setEnabled(enable); upd_take.setEnabled(enable); set_cancel.setEnabled(enable); set_take.setEnabled(enable); set_remember.setEnabled(enable); set_update.setEnabled(enable); set_full.setEnabled(enable); set_offline.setEnabled(enable); set_memory.setEnabled(enable); login.setEnabled(enable); password.setEnabled(enable); } public void toXFrame(int type) { BufferedImage min = ImageUtils.takePicture(panel).getSubimage(0, 0, panel.getWidth(), panel.getHeight()); panel.removeAll(); Panel.animation.paneAttenuation(min, type); panel.hideAlerts(true); addFrameElements(false); repaint(); } public void paneState(int goTo) { switch (goTo) { case 1: panel.setAuthState(); break; case 2: panel.setSettings(); break; case 3: panel.setUpdateState(); break; case 4: panel.setGameUpdateState(); break; case 5: panel.setPersonalState(); break; case 6: panel.setAlertState(); break; } } public void afterFilling(final int aF, boolean remove) { switch (aF) { case 1: addAuthElements(remove); break; case 2: addSettingsElements(remove); break; case 3: addUpdateElements(remove); break; case 4: break; case 5: addPersonalElements(remove); break; case 6: addAlertPaneElements(remove); break; } } protected final void addFrameElements(boolean remove) { if(!remove) { panel.add(turn); panel.add(close); } else { panel.remove(turn); panel.remove(close); } } protected final void addAuthElements(boolean remove) { if(!remove) { panel.add(logotype); panel.add(serversList); panel.add(doAuth); panel.add(settings); panel.add(login); panel.add(password); } else { panel.remove(logotype); panel.remove(serversList); panel.remove(doAuth); panel.remove(settings); panel.remove(login); panel.remove(password); } } protected void addSettingsElements(boolean remove) { if(!remove) { panel.add(set_cancel); panel.add(set_take); panel.add(set_remember); panel.add(set_update); panel.add(set_full); panel.add(set_offline); panel.add(set_memory); } else { panel.remove(set_cancel); panel.remove(set_take); panel.remove(set_remember); panel.remove(set_update); panel.remove(set_full); panel.remove(set_offline); panel.remove(set_memory); } } protected void addUpdateElements(boolean remove) { if(!remove) { panel.add(exit); panel.add(upd_take); } else { panel.remove(exit); panel.remove(upd_take); } } protected void addPersonalElements(boolean remove) { if(!remove) { panel.add(exit); panel.add(toGame); } else { panel.remove(exit); panel.remove(toGame); } } protected void addAlertPaneElements(boolean remove) { if(!remove) { panel.add(exit); panel.add(take); } else { panel.remove(exit); panel.remove(take); } } public void setAlert(String alert, int type, int in_frame) { panel.alertIcons(alert, type, in_frame); } public void setAlert(String alert, int type, int y, int in_frame) { panel.alertIcons(alert, type, y, in_frame); } public static void report(String mes) { if(Settings.use_debugging) { String num = null; if(Integer.toString(debLine).length() == 1) num = "00" + debLine + ": "; else if(Integer.toString(debLine).length() == 2) num = "0" + debLine + ": "; else if(Integer.toString(debLine).length() == 3) num = debLine + ": "; else num = "999: "; System.out.println((Starter.isStarted() ? "" : num) + mes); debLine++; } } public static void reportErr(String errMes) { if(Settings.use_debugging) { String num = null; if(Integer.toString(debLine).length() == 1) num = "00" + debLine + ": "; else if(Integer.toString(debLine).length() == 2) num = "0" + debLine + ": "; else if(Integer.toString(debLine).length() == 3) num = debLine + ": "; else num = "999: "; System.err.println((Starter.isStarted() ? "" : num) + errMes); debLine++; } } public void focusGained(FocusEvent e) { if(e.getSource() == login && login.getText().equals(Settings.login_text)) login.setText(""); if(e.getSource() == password && new String(password.getPassword()).equals(Settings.pass_text)) password.setText(""); } public void focusLost(FocusEvent e) { if(e.getSource() == login && login.getText().equals("")) login.setText(Settings.login_text); if(e.getSource() == password && new String(password.getPassword()).equals("")) password.setText(Settings.pass_text); } public void keyTyped(KeyEvent e) {} public void keyPressed(KeyEvent e) {} public void keyReleased(KeyEvent e) { if (e.getKeyText(e.getKeyCode()).equals("Enter")) { if (panel.unit == 0) doAuth.doClick(); else if (panel.unit == 4) toGame.doClick(); } } }
apache-2.0
maxpowa/irc-api
src/main/java/com/ircclouds/irc/api/domain/messages/UserPing.java
260
package com.ircclouds.irc.api.domain.messages; public class UserPing extends UserCTCP { public UserPing(AbstractMessage message) { super(message); } @Override public String getText() { return super.getText().replaceFirst("(?i)PING", "").trim(); } }
apache-2.0
anand1st/sshd-shell-spring-boot
sshd-shell-spring-boot-starter/src/test/java/sshd/shell/springboot/autoconfiguration/SshdShellAutoConfigurationAuthProviderInvalidAuthTypeTest.java
1286
/* * Copyright 2017 anand. * * 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 sshd.shell.springboot.autoconfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; /** * * @author anand */ @SpringBootTest(classes = ConfigTest.class, properties = { "sshd.shell.auth.authType=AUTH_PROVIDER", "sshd.shell.username=bob", "sshd.shell.password=bob", "sshd.shell.auth.authProviderBeanName=authProvider", "spring.flyway.baseline-on-migrate=true", "spring.main.allow-circular-references=true" }) @DirtiesContext public class SshdShellAutoConfigurationAuthProviderInvalidAuthTypeTest extends SshdShellAutoConfigurationAuthProviderTest { }
apache-2.0
vadopolski/ignite
modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java
144225
/* * 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.ignite.internal.processors.cache; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import javax.management.MBeanServer; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteSystemProperties; import org.apache.ignite.cache.CacheExistsException; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.cache.CacheRebalanceMode; import org.apache.ignite.cache.QueryEntity; import org.apache.ignite.cache.affinity.AffinityFunction; import org.apache.ignite.cache.affinity.AffinityFunctionContext; import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction; import org.apache.ignite.cache.store.CacheStore; import org.apache.ignite.cache.store.CacheStoreSessionListener; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.DeploymentMode; import org.apache.ignite.configuration.FileSystemConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.configuration.MemoryConfiguration; import org.apache.ignite.configuration.NearCacheConfiguration; import org.apache.ignite.configuration.TransactionConfiguration; import org.apache.ignite.events.EventType; import org.apache.ignite.internal.GridKernalContext; import org.apache.ignite.internal.IgniteClientDisconnectedCheckedException; import org.apache.ignite.internal.IgniteComponentType; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.IgniteNodeAttributes; import org.apache.ignite.internal.IgniteTransactionsEx; import org.apache.ignite.internal.binary.BinaryContext; import org.apache.ignite.internal.binary.BinaryMarshaller; import org.apache.ignite.internal.binary.GridBinaryMarshaller; import org.apache.ignite.internal.managers.discovery.DiscoveryCustomMessage; import org.apache.ignite.internal.pagemem.store.IgnitePageStoreManager; import org.apache.ignite.internal.pagemem.wal.IgniteWriteAheadLogManager; import org.apache.ignite.internal.processors.GridProcessorAdapter; import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion; import org.apache.ignite.internal.processors.affinity.GridAffinityAssignmentCache; import org.apache.ignite.internal.processors.cache.CacheJoinNodeDiscoveryData.CacheInfo; import org.apache.ignite.internal.processors.cache.binary.CacheObjectBinaryProcessorImpl; import org.apache.ignite.internal.processors.cache.datastructures.CacheDataStructuresManager; import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtCache; import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtCacheAdapter; import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtLocalPartition; import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionTopology; import org.apache.ignite.internal.processors.cache.distributed.dht.atomic.GridDhtAtomicCache; import org.apache.ignite.internal.processors.cache.distributed.dht.colocated.GridDhtColocatedCache; import org.apache.ignite.internal.processors.cache.distributed.near.GridNearAtomicCache; import org.apache.ignite.internal.processors.cache.distributed.near.GridNearTransactionalCache; import org.apache.ignite.internal.processors.cache.dr.GridCacheDrManager; import org.apache.ignite.internal.processors.cache.jta.CacheJtaManagerAdapter; import org.apache.ignite.internal.processors.cache.local.GridLocalCache; import org.apache.ignite.internal.processors.cache.local.atomic.GridLocalAtomicCache; import org.apache.ignite.internal.processors.cache.persistence.GridCacheDatabaseSharedManager; import org.apache.ignite.internal.processors.cache.persistence.IgniteCacheDatabaseSharedManager; import org.apache.ignite.internal.processors.cache.persistence.MemoryPolicy; import org.apache.ignite.internal.processors.cache.persistence.file.FilePageStoreManager; import org.apache.ignite.internal.processors.cache.persistence.freelist.FreeList; import org.apache.ignite.internal.processors.cache.persistence.snapshot.IgniteCacheSnapshotManager; import org.apache.ignite.internal.processors.cache.persistence.snapshot.SnapshotDiscoveryMessage; import org.apache.ignite.internal.processors.cache.persistence.tree.reuse.ReuseList; import org.apache.ignite.internal.processors.cache.persistence.wal.FileWriteAheadLogManager; import org.apache.ignite.internal.processors.cache.query.GridCacheDistributedQueryManager; import org.apache.ignite.internal.processors.cache.query.GridCacheLocalQueryManager; import org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager; import org.apache.ignite.internal.processors.cache.query.continuous.CacheContinuousQueryManager; import org.apache.ignite.internal.processors.cache.store.CacheStoreManager; import org.apache.ignite.internal.processors.cache.transactions.IgniteTransactionsImpl; import org.apache.ignite.internal.processors.cache.transactions.IgniteTxManager; import org.apache.ignite.internal.processors.cache.version.GridCacheVersionManager; import org.apache.ignite.internal.processors.cacheobject.IgniteCacheObjectProcessor; import org.apache.ignite.internal.processors.cluster.ChangeGlobalStateFinishMessage; import org.apache.ignite.internal.processors.cluster.ChangeGlobalStateMessage; import org.apache.ignite.internal.processors.cluster.DiscoveryDataClusterState; import org.apache.ignite.internal.processors.datastructures.DataStructuresProcessor; import org.apache.ignite.internal.processors.plugin.CachePluginManager; import org.apache.ignite.internal.processors.query.QuerySchema; import org.apache.ignite.internal.processors.query.QueryUtils; import org.apache.ignite.internal.processors.query.schema.SchemaExchangeWorkerTask; import org.apache.ignite.internal.processors.query.schema.SchemaNodeLeaveExchangeWorkerTask; import org.apache.ignite.internal.processors.query.schema.message.SchemaAbstractDiscoveryMessage; import org.apache.ignite.internal.processors.query.schema.message.SchemaProposeDiscoveryMessage; import org.apache.ignite.internal.processors.timeout.GridTimeoutObject; import org.apache.ignite.internal.suggestions.GridPerformanceSuggestions; import org.apache.ignite.internal.util.F0; import org.apache.ignite.internal.util.future.GridCompoundFuture; import org.apache.ignite.internal.util.future.GridFinishedFuture; import org.apache.ignite.internal.util.future.GridFutureAdapter; import org.apache.ignite.internal.util.lang.IgniteOutClosureX; import org.apache.ignite.internal.util.tostring.GridToStringInclude; import org.apache.ignite.internal.util.typedef.CIX1; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.T2; import org.apache.ignite.internal.util.typedef.X; import org.apache.ignite.internal.util.typedef.internal.A; import org.apache.ignite.internal.util.typedef.internal.CU; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteBiTuple; import org.apache.ignite.lang.IgniteClosure; import org.apache.ignite.lang.IgniteFuture; import org.apache.ignite.lang.IgnitePredicate; import org.apache.ignite.lang.IgniteUuid; import org.apache.ignite.lifecycle.LifecycleAware; import org.apache.ignite.marshaller.Marshaller; import org.apache.ignite.marshaller.MarshallerUtils; import org.apache.ignite.mxbean.IgniteMBeanAware; import org.apache.ignite.spi.IgniteNodeValidationResult; import org.apache.ignite.spi.discovery.DiscoveryDataBag; import org.apache.ignite.spi.discovery.DiscoveryDataBag.GridDiscoveryData; import org.apache.ignite.spi.discovery.DiscoveryDataBag.JoiningNodeDiscoveryData; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import static org.apache.ignite.IgniteSystemProperties.IGNITE_CACHE_REMOVED_ENTRIES_TTL; import static org.apache.ignite.IgniteSystemProperties.IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK; import static org.apache.ignite.IgniteSystemProperties.getBoolean; import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC; import static org.apache.ignite.cache.CacheMode.LOCAL; import static org.apache.ignite.cache.CacheMode.PARTITIONED; import static org.apache.ignite.cache.CacheMode.REPLICATED; import static org.apache.ignite.cache.CacheRebalanceMode.SYNC; import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_ASYNC; import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC; import static org.apache.ignite.configuration.DeploymentMode.CONTINUOUS; import static org.apache.ignite.configuration.DeploymentMode.ISOLATED; import static org.apache.ignite.configuration.DeploymentMode.PRIVATE; import static org.apache.ignite.configuration.DeploymentMode.SHARED; import static org.apache.ignite.internal.GridComponent.DiscoveryDataExchangeType.CACHE_PROC; import static org.apache.ignite.internal.IgniteComponentType.JTA; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_CONSISTENCY_CHECK_SKIPPED; import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_TX_CONFIG; import static org.apache.ignite.internal.processors.cache.GridCacheUtils.isNearEnabled; /** * Cache processor. */ @SuppressWarnings({"unchecked", "TypeMayBeWeakened", "deprecation"}) public class GridCacheProcessor extends GridProcessorAdapter { /** */ private final boolean startClientCaches = IgniteSystemProperties.getBoolean(IgniteSystemProperties.IGNITE_START_CACHES_ON_JOIN, false); /** Shared cache context. */ private GridCacheSharedContext<?, ?> sharedCtx; /** */ private final ConcurrentMap<Integer, CacheGroupContext> cacheGrps = new ConcurrentHashMap<>(); /** */ private final Map<String, GridCacheAdapter<?, ?>> caches; /** Caches stopped from onKernalStop callback. */ private final Map<String, GridCacheAdapter> stoppedCaches = new ConcurrentHashMap<>(); /** Map of proxies. */ private final ConcurrentHashMap<String, IgniteCacheProxyImpl<?, ?>> jCacheProxies; /** Caches stop sequence. */ private final Deque<String> stopSeq; /** Transaction interface implementation. */ private IgniteTransactionsImpl transactions; /** Pending cache starts. */ private ConcurrentMap<UUID, IgniteInternalFuture> pendingFuts = new ConcurrentHashMap<>(); /** Template configuration add futures. */ private ConcurrentMap<String, IgniteInternalFuture> pendingTemplateFuts = new ConcurrentHashMap<>(); /** */ private ClusterCachesInfo cachesInfo; /** */ private IdentityHashMap<CacheStore, ThreadLocal> sesHolders = new IdentityHashMap<>(); /** Must use JDK marsh since it is used by discovery to fire custom events. */ private final Marshaller marsh; /** Count down latch for caches. */ private final CountDownLatch cacheStartedLatch = new CountDownLatch(1); /** Internal cache names. */ private final Set<String> internalCaches; /** * @param ctx Kernal context. */ public GridCacheProcessor(GridKernalContext ctx) { super(ctx); caches = new ConcurrentHashMap<>(); jCacheProxies = new ConcurrentHashMap<>(); stopSeq = new LinkedList<>(); internalCaches = new HashSet<>(); marsh = MarshallerUtils.jdkMarshaller(ctx.igniteInstanceName()); } /** * @param cfg Initializes cache configuration with proper defaults. * @param cacheObjCtx Cache object context. * @throws IgniteCheckedException If configuration is not valid. */ private void initialize(CacheConfiguration cfg, CacheObjectContext cacheObjCtx) throws IgniteCheckedException { CU.initializeConfigDefaults(log, cfg, cacheObjCtx); ctx.igfsHelper().preProcessCacheConfiguration(cfg); } /** * @param cfg Configuration to check for possible performance issues. * @param hasStore {@code True} if store is configured. */ private void suggestOptimizations(CacheConfiguration cfg, boolean hasStore) { GridPerformanceSuggestions perf = ctx.performance(); String msg = "Disable eviction policy (remove from configuration)"; if (cfg.getEvictionPolicy() != null) perf.add(msg, false); else perf.add(msg, true); if (cfg.getCacheMode() == PARTITIONED) { perf.add("Disable near cache (set 'nearConfiguration' to null)", cfg.getNearConfiguration() == null); if (cfg.getAffinity() != null) perf.add("Decrease number of backups (set 'backups' to 0)", cfg.getBackups() == 0); } // Suppress warning if at least one ATOMIC cache found. perf.add("Enable ATOMIC mode if not using transactions (set 'atomicityMode' to ATOMIC)", cfg.getAtomicityMode() == ATOMIC); // Suppress warning if at least one non-FULL_SYNC mode found. perf.add("Disable fully synchronous writes (set 'writeSynchronizationMode' to PRIMARY_SYNC or FULL_ASYNC)", cfg.getWriteSynchronizationMode() != FULL_SYNC); if (hasStore && cfg.isWriteThrough()) perf.add("Enable write-behind to persistent store (set 'writeBehindEnabled' to true)", cfg.isWriteBehindEnabled()); } /** * Create exchange worker task for custom discovery message. * * @param msg Custom discovery message. * @return Task or {@code null} if message doesn't require any special processing. */ public CachePartitionExchangeWorkerTask exchangeTaskForCustomDiscoveryMessage(DiscoveryCustomMessage msg) { if (msg instanceof SchemaAbstractDiscoveryMessage) { SchemaAbstractDiscoveryMessage msg0 = (SchemaAbstractDiscoveryMessage)msg; if (msg0.exchange()) return new SchemaExchangeWorkerTask(msg0); } else if (msg instanceof ClientCacheChangeDummyDiscoveryMessage) { ClientCacheChangeDummyDiscoveryMessage msg0 = (ClientCacheChangeDummyDiscoveryMessage)msg; return msg0; } return null; } /** * Process custom exchange task. * * @param task Task. */ void processCustomExchangeTask(CachePartitionExchangeWorkerTask task) { if (task instanceof SchemaExchangeWorkerTask) { SchemaAbstractDiscoveryMessage msg = ((SchemaExchangeWorkerTask)task).message(); if (msg instanceof SchemaProposeDiscoveryMessage) { SchemaProposeDiscoveryMessage msg0 = (SchemaProposeDiscoveryMessage)msg; ctx.query().onSchemaPropose(msg0); } else U.warn(log, "Unsupported schema discovery message: " + msg); } else if (task instanceof SchemaNodeLeaveExchangeWorkerTask) { SchemaNodeLeaveExchangeWorkerTask task0 = (SchemaNodeLeaveExchangeWorkerTask)task; ctx.query().onNodeLeave(task0.node()); } else if (task instanceof ClientCacheChangeDummyDiscoveryMessage) { ClientCacheChangeDummyDiscoveryMessage task0 = (ClientCacheChangeDummyDiscoveryMessage)task; sharedCtx.affinity().processClientCachesChanges(task0); } else if (task instanceof ClientCacheUpdateTimeout) { ClientCacheUpdateTimeout task0 = (ClientCacheUpdateTimeout)task; sharedCtx.affinity().sendClientCacheChangesMessage(task0); } else U.warn(log, "Unsupported custom exchange task: " + task); } /** * @param c Ignite Configuration. * @param cc Cache Configuration. * @return {@code true} if cache is starting on client node and this node is affinity node for the cache. */ private boolean storesLocallyOnClient(IgniteConfiguration c, CacheConfiguration cc) { if (c.isClientMode() && c.getMemoryConfiguration() == null) { if (cc.getCacheMode() == LOCAL) return true; return ctx.discovery().cacheAffinityNode(ctx.discovery().localNode(), cc.getName()); } else return false; } /** * @param c Ignite configuration. * @param cc Configuration to validate. * @param cacheType Cache type. * @param cfgStore Cache store. * @throws IgniteCheckedException If failed. */ private void validate(IgniteConfiguration c, CacheConfiguration cc, CacheType cacheType, @Nullable CacheStore cfgStore) throws IgniteCheckedException { assertParameter(cc.getName() != null && !cc.getName().isEmpty(), "name is null or empty"); if (cc.getCacheMode() == REPLICATED) { if (cc.getNearConfiguration() != null && ctx.discovery().cacheAffinityNode(ctx.discovery().localNode(), cc.getName())) { U.warn(log, "Near cache cannot be used with REPLICATED cache, " + "will be ignored [cacheName=" + U.maskName(cc.getName()) + ']'); cc.setNearConfiguration(null); } } if (storesLocallyOnClient(c, cc)) throw new IgniteCheckedException("MemoryPolicy for client caches must be explicitly configured " + "on client node startup. Use MemoryConfiguration to configure MemoryPolicy."); if (cc.getCacheMode() == LOCAL && !cc.getAffinity().getClass().equals(LocalAffinityFunction.class)) U.warn(log, "AffinityFunction configuration parameter will be ignored for local cache [cacheName=" + U.maskName(cc.getName()) + ']'); if (cc.getAffinity().partitions() > CacheConfiguration.MAX_PARTITIONS_COUNT) throw new IgniteCheckedException("Cannot have more than " + CacheConfiguration.MAX_PARTITIONS_COUNT + " partitions [cacheName=" + cc.getName() + ", partitions=" + cc.getAffinity().partitions() + ']'); if (cc.getRebalanceMode() != CacheRebalanceMode.NONE) assertParameter(cc.getRebalanceBatchSize() > 0, "rebalanceBatchSize > 0"); if (cc.getCacheMode() == PARTITIONED || cc.getCacheMode() == REPLICATED) { if (cc.getAtomicityMode() == ATOMIC && cc.getWriteSynchronizationMode() == FULL_ASYNC) U.warn(log, "Cache write synchronization mode is set to FULL_ASYNC. All single-key 'put' and " + "'remove' operations will return 'null', all 'putx' and 'removex' operations will return" + " 'true' [cacheName=" + U.maskName(cc.getName()) + ']'); } DeploymentMode depMode = c.getDeploymentMode(); if (c.isPeerClassLoadingEnabled() && (depMode == PRIVATE || depMode == ISOLATED) && !CU.isSystemCache(cc.getName()) && !(c.getMarshaller() instanceof BinaryMarshaller)) throw new IgniteCheckedException("Cache can be started in PRIVATE or ISOLATED deployment mode only when" + " BinaryMarshaller is used [depMode=" + ctx.config().getDeploymentMode() + ", marshaller=" + c.getMarshaller().getClass().getName() + ']'); if (cc.getAffinity().partitions() > CacheConfiguration.MAX_PARTITIONS_COUNT) throw new IgniteCheckedException("Affinity function must return at most " + CacheConfiguration.MAX_PARTITIONS_COUNT + " partitions [actual=" + cc.getAffinity().partitions() + ", affFunction=" + cc.getAffinity() + ", cacheName=" + cc.getName() + ']'); if (cc.isWriteBehindEnabled()) { if (cfgStore == null) throw new IgniteCheckedException("Cannot enable write-behind (writer or store is not provided) " + "for cache: " + U.maskName(cc.getName())); assertParameter(cc.getWriteBehindBatchSize() > 0, "writeBehindBatchSize > 0"); assertParameter(cc.getWriteBehindFlushSize() >= 0, "writeBehindFlushSize >= 0"); assertParameter(cc.getWriteBehindFlushFrequency() >= 0, "writeBehindFlushFrequency >= 0"); assertParameter(cc.getWriteBehindFlushThreadCount() > 0, "writeBehindFlushThreadCount > 0"); if (cc.getWriteBehindFlushSize() == 0 && cc.getWriteBehindFlushFrequency() == 0) throw new IgniteCheckedException("Cannot set both 'writeBehindFlushFrequency' and " + "'writeBehindFlushSize' parameters to 0 for cache: " + U.maskName(cc.getName())); } if (cc.isReadThrough() && cfgStore == null) throw new IgniteCheckedException("Cannot enable read-through (loader or store is not provided) " + "for cache: " + U.maskName(cc.getName())); if (cc.isWriteThrough() && cfgStore == null) throw new IgniteCheckedException("Cannot enable write-through (writer or store is not provided) " + "for cache: " + U.maskName(cc.getName())); long delay = cc.getRebalanceDelay(); if (delay != 0) { if (cc.getCacheMode() != PARTITIONED) U.warn(log, "Rebalance delay is supported only for partitioned caches (will ignore): " + (cc.getName()), "Will ignore rebalance delay for cache: " + U.maskName(cc.getName())); else if (cc.getRebalanceMode() == SYNC) { if (delay < 0) { U.warn(log, "Ignoring SYNC rebalance mode with manual rebalance start (node will not wait for " + "rebalancing to be finished): " + U.maskName(cc.getName()), "Node will not wait for rebalance in SYNC mode: " + U.maskName(cc.getName())); } else { U.warn(log, "Using SYNC rebalance mode with rebalance delay (node will wait until rebalancing is " + "initiated for " + delay + "ms) for cache: " + U.maskName(cc.getName()), "Node will wait until rebalancing is initiated for " + delay + "ms for cache: " + U.maskName(cc.getName())); } } } ctx.igfsHelper().validateCacheConfiguration(cc); if (cc.getAtomicityMode() == ATOMIC) assertParameter(cc.getTransactionManagerLookupClassName() == null, "transaction manager can not be used with ATOMIC cache"); if (cc.getEvictionPolicy() != null && !cc.isOnheapCacheEnabled()) throw new IgniteCheckedException("Onheap cache must be enabled if eviction policy is configured [cacheName=" + U.maskName(cc.getName()) + "]"); if (cacheType != CacheType.DATA_STRUCTURES && DataStructuresProcessor.isDataStructureCache(cc.getName())) throw new IgniteCheckedException("Using cache names reserved for datastructures is not allowed for " + "other cache types [cacheName=" + cc.getName() + ", cacheType=" + cacheType + "]"); if (cacheType != CacheType.DATA_STRUCTURES && DataStructuresProcessor.isReservedGroup(cc.getGroupName())) throw new IgniteCheckedException("Using cache group names reserved for datastructures is not allowed for " + "other cache types [cacheName=" + cc.getName() + ", groupName=" + cc.getGroupName() + ", cacheType=" + cacheType + "]"); } /** * @param ctx Context. * @return DHT managers. */ private List<GridCacheManager> dhtManagers(GridCacheContext ctx) { return F.asList(ctx.store(), ctx.events(), ctx.evicts(), ctx.queries(), ctx.continuousQueries(), ctx.dr()); } /** * @param ctx Context. * @return Managers present in both, DHT and Near caches. */ @SuppressWarnings("IfMayBeConditional") private Collection<GridCacheManager> dhtExcludes(GridCacheContext ctx) { if (ctx.config().getCacheMode() == LOCAL || !isNearEnabled(ctx)) return Collections.emptyList(); else return F.asList(ctx.queries(), ctx.continuousQueries(), ctx.store()); } /** * @param cfg Configuration. * @param objs Extra components. * @throws IgniteCheckedException If failed to inject. */ private void prepare(CacheConfiguration cfg, Collection<Object> objs) throws IgniteCheckedException { prepare(cfg, cfg.getEvictionPolicy(), false); prepare(cfg, cfg.getAffinity(), false); prepare(cfg, cfg.getAffinityMapper(), false); prepare(cfg, cfg.getEvictionFilter(), false); prepare(cfg, cfg.getInterceptor(), false); NearCacheConfiguration nearCfg = cfg.getNearConfiguration(); if (nearCfg != null) prepare(cfg, nearCfg.getNearEvictionPolicy(), true); for (Object obj : objs) prepare(cfg, obj, false); } /** * @param cfg Cache configuration. * @param rsrc Resource. * @param near Near flag. * @throws IgniteCheckedException If failed. */ private void prepare(CacheConfiguration cfg, @Nullable Object rsrc, boolean near) throws IgniteCheckedException { if (rsrc != null) { ctx.resource().injectGeneric(rsrc); ctx.resource().injectCacheName(rsrc, cfg.getName()); registerMbean(rsrc, cfg.getName(), near); } } /** * @param cctx Cache context. */ private void cleanup(GridCacheContext cctx) { CacheConfiguration cfg = cctx.config(); cleanup(cfg, cfg.getEvictionPolicy(), false); cleanup(cfg, cfg.getAffinity(), false); cleanup(cfg, cfg.getAffinityMapper(), false); cleanup(cfg, cfg.getEvictionFilter(), false); cleanup(cfg, cfg.getInterceptor(), false); cleanup(cfg, cctx.store().configuredStore(), false); if (!CU.isUtilityCache(cfg.getName()) && !CU.isSystemCache(cfg.getName())) { unregisterMbean(cctx.cache().localMxBean(), cfg.getName(), false); unregisterMbean(cctx.cache().clusterMxBean(), cfg.getName(), false); } NearCacheConfiguration nearCfg = cfg.getNearConfiguration(); if (nearCfg != null) cleanup(cfg, nearCfg.getNearEvictionPolicy(), true); cctx.cleanup(); } /** * @param grp Cache group. */ private void cleanup(CacheGroupContext grp) { CacheConfiguration cfg = grp.config(); for (Object obj : grp.configuredUserObjects()) cleanup(cfg, obj, false); } /** * @param cfg Cache configuration. * @param rsrc Resource. * @param near Near flag. */ private void cleanup(CacheConfiguration cfg, @Nullable Object rsrc, boolean near) { if (rsrc != null) { unregisterMbean(rsrc, cfg.getName(), near); try { ctx.resource().cleanupGeneric(rsrc); } catch (IgniteCheckedException e) { U.error(log, "Failed to cleanup resource: " + rsrc, e); } } } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) @Override public void start() throws IgniteCheckedException { cachesInfo = new ClusterCachesInfo(ctx); DeploymentMode depMode = ctx.config().getDeploymentMode(); if (!F.isEmpty(ctx.config().getCacheConfiguration())) { if (depMode != CONTINUOUS && depMode != SHARED) U.warn(log, "Deployment mode for cache is not CONTINUOUS or SHARED " + "(it is recommended that you change deployment mode and restart): " + depMode, "Deployment mode for cache is not CONTINUOUS or SHARED."); } initializeInternalCacheNames(); Collection<CacheStoreSessionListener> sessionListeners = CU.startStoreSessionListeners(ctx, ctx.config().getCacheStoreSessionListenerFactories()); sharedCtx = createSharedContext(ctx, sessionListeners); transactions = new IgniteTransactionsImpl(sharedCtx); // Start shared managers. for (GridCacheSharedManager mgr : sharedCtx.managers()) mgr.start(sharedCtx); if (!ctx.isDaemon()) { Map<String, CacheInfo> caches = new HashMap<>(); Map<String, CacheInfo> templates = new HashMap<>(); addCacheOnJoinFromConfig(caches, templates); CacheJoinNodeDiscoveryData discoData = new CacheJoinNodeDiscoveryData( IgniteUuid.randomUuid(), caches, templates, startAllCachesOnClientStart() ); cachesInfo.onStart(discoData); if (log.isDebugEnabled()) log.debug("Started cache processor."); } ctx.state().cacheProcessorStarted(); } /** * @param cfg Cache configuration. * @param sql SQL flag. * @param caches Caches map. * @param templates Templates map. * @throws IgniteCheckedException If failed. */ private void addCacheOnJoin(CacheConfiguration<?, ?> cfg, boolean sql, Map<String, CacheInfo> caches, Map<String, CacheInfo> templates) throws IgniteCheckedException { String cacheName = cfg.getName(); CU.validateCacheName(cacheName); cloneCheckSerializable(cfg); CacheObjectContext cacheObjCtx = ctx.cacheObjects().contextForCache(cfg); // Initialize defaults. initialize(cfg, cacheObjCtx); StoredCacheData cacheData = new StoredCacheData(cfg); cacheData.sql(sql); boolean template = cacheName.endsWith("*"); if (!template) { if (caches.containsKey(cacheName)) { throw new IgniteCheckedException("Duplicate cache name found (check configuration and " + "assign unique name to each cache): " + cacheName); } CacheType cacheType = cacheType(cacheName); if (cacheType != CacheType.USER && cfg.getMemoryPolicyName() == null) cfg.setMemoryPolicyName(sharedCtx.database().systemMemoryPolicyName()); if (!cacheType.userCache()) stopSeq.addLast(cacheName); else stopSeq.addFirst(cacheName); caches.put(cacheName, new CacheJoinNodeDiscoveryData.CacheInfo(cacheData, cacheType, cacheData.sql(), 0)); } else templates.put(cacheName, new CacheJoinNodeDiscoveryData.CacheInfo(cacheData, CacheType.USER, false, 0)); } /** * @param caches Caches map. * @param templates Templates map. * @throws IgniteCheckedException If failed. */ private void addCacheOnJoinFromConfig( Map<String, CacheInfo> caches, Map<String, CacheInfo> templates ) throws IgniteCheckedException { assert !ctx.config().isDaemon(); CacheConfiguration[] cfgs = ctx.config().getCacheConfiguration(); for (int i = 0; i < cfgs.length; i++) { CacheConfiguration<?, ?> cfg = new CacheConfiguration(cfgs[i]); // Replace original configuration value. cfgs[i] = cfg; addCacheOnJoin(cfg, false, caches, templates); } } /** * Initialize internal cache names */ private void initializeInternalCacheNames() { FileSystemConfiguration[] igfsCfgs = ctx.grid().configuration().getFileSystemConfiguration(); if (igfsCfgs != null) { for (FileSystemConfiguration igfsCfg : igfsCfgs) { internalCaches.add(igfsCfg.getMetaCacheConfiguration().getName()); internalCaches.add(igfsCfg.getDataCacheConfiguration().getName()); } } if (IgniteComponentType.HADOOP.inClassPath()) internalCaches.add(CU.SYS_CACHE_HADOOP_MR); } /** * @param grpId Group ID. * @return Cache group. */ @Nullable public CacheGroupContext cacheGroup(int grpId) { return cacheGrps.get(grpId); } /** * @return Cache groups. */ public Collection<CacheGroupContext> cacheGroups() { return cacheGrps.values(); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void onKernalStart(boolean active) throws IgniteCheckedException { if (ctx.isDaemon()) return; try { boolean checkConsistency = !getBoolean(IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK); if (checkConsistency) checkConsistency(); cachesInfo.onKernalStart(checkConsistency); ctx.query().onCacheKernalStart(); sharedCtx.exchange().onKernalStart(active, false); } finally { cacheStartedLatch.countDown(); } if (!ctx.clientNode()) addRemovedItemsCleanupTask(Long.getLong(IGNITE_CACHE_REMOVED_ENTRIES_TTL, 10_000)); // Escape if cluster inactive. if (!active) return; ctx.service().onUtilityCacheStarted(); final AffinityTopologyVersion startTopVer = ctx.discovery().localJoin().joinTopologyVersion(); final List<IgniteInternalFuture> syncFuts = new ArrayList<>(caches.size()); sharedCtx.forAllCaches(new CIX1<GridCacheContext>() { @Override public void applyx(GridCacheContext cctx) { CacheConfiguration cfg = cctx.config(); if (cctx.affinityNode() && cfg.getRebalanceMode() == SYNC && startTopVer.equals(cctx.startTopologyVersion())) { CacheMode cacheMode = cfg.getCacheMode(); if (cacheMode == REPLICATED || (cacheMode == PARTITIONED && cfg.getRebalanceDelay() >= 0)) // Need to wait outside to avoid a deadlock syncFuts.add(cctx.preloader().syncFuture()); } } }); for (int i = 0, size = syncFuts.size(); i < size; i++) syncFuts.get(i).get(); } /** * @param timeout Cleanup timeout. */ private void addRemovedItemsCleanupTask(long timeout) { ctx.timeout().addTimeoutObject(new RemovedItemsCleanupTask(timeout)); } /** * @throws IgniteCheckedException if check failed. */ private void checkConsistency() throws IgniteCheckedException { for (ClusterNode n : ctx.discovery().remoteNodes()) { if (Boolean.TRUE.equals(n.attribute(ATTR_CONSISTENCY_CHECK_SKIPPED))) continue; checkTransactionConfiguration(n); checkMemoryConfiguration(n); DeploymentMode locDepMode = ctx.config().getDeploymentMode(); DeploymentMode rmtDepMode = n.attribute(IgniteNodeAttributes.ATTR_DEPLOYMENT_MODE); CU.checkAttributeMismatch(log, null, n.id(), "deploymentMode", "Deployment mode", locDepMode, rmtDepMode, true); } } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void stop(boolean cancel) throws IgniteCheckedException { stopCaches(cancel); List<? extends GridCacheSharedManager<?, ?>> mgrs = sharedCtx.managers(); for (ListIterator<? extends GridCacheSharedManager<?, ?>> it = mgrs.listIterator(mgrs.size()); it.hasPrevious(); ) { GridCacheSharedManager<?, ?> mgr = it.previous(); mgr.stop(cancel); } CU.stopStoreSessionListeners(ctx, sharedCtx.storeSessionListeners()); sharedCtx.cleanup(); if (log.isDebugEnabled()) log.debug("Stopped cache processor."); } /** * @param cancel Cancel. */ public void stopCaches(boolean cancel) { for (String cacheName : stopSeq) { GridCacheAdapter<?, ?> cache = stoppedCaches.remove(cacheName); if (cache != null) stopCache(cache, cancel, false); } for (GridCacheAdapter<?, ?> cache : stoppedCaches.values()) { if (cache == stoppedCaches.remove(cache.name())) stopCache(cache, cancel, false); } for (CacheGroupContext grp : cacheGrps.values()) stopCacheGroup(grp.groupId()); } /** * Blocks all available gateways */ public void blockGateways() { for (IgniteCacheProxy<?, ?> proxy : jCacheProxies.values()) proxy.context().gate().onStopped(); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public void onKernalStop(boolean cancel) { cacheStartedLatch.countDown(); GridCachePartitionExchangeManager<Object, Object> exch = context().exchange(); // Stop exchange manager first so that we call onKernalStop on all caches. // No new caches should be added after this point. exch.onKernalStop(cancel); sharedCtx.mvcc().onStop(); for (CacheGroupContext grp : cacheGrps.values()) grp.onKernalStop(); onKernalStopCaches(cancel); cancelFutures(); List<? extends GridCacheSharedManager<?, ?>> sharedMgrs = sharedCtx.managers(); for (ListIterator<? extends GridCacheSharedManager<?, ?>> it = sharedMgrs.listIterator(sharedMgrs.size()); it.hasPrevious(); ) { GridCacheSharedManager<?, ?> mgr = it.previous(); if (mgr != exch) mgr.onKernalStop(cancel); } } /** * @param cancel Cancel. */ public void onKernalStopCaches(boolean cancel) { IgniteCheckedException affErr = new IgniteCheckedException("Failed to wait for topology update, node is stopping."); for (CacheGroupContext grp : cacheGrps.values()) { GridAffinityAssignmentCache aff = grp.affinity(); aff.cancelFutures(affErr); } for (String cacheName : stopSeq) { GridCacheAdapter<?, ?> cache = caches.remove(cacheName); if (cache != null) { stoppedCaches.put(cacheName, cache); onKernalStop(cache, cancel); } } for (Map.Entry<String, GridCacheAdapter<?, ?>> entry : caches.entrySet()) { GridCacheAdapter<?, ?> cache = entry.getValue(); if (cache == caches.remove(entry.getKey())) { stoppedCaches.put(entry.getKey(), cache); onKernalStop(entry.getValue(), cancel); } } } /** {@inheritDoc} */ @Override public void onDisconnected(IgniteFuture<?> reconnectFut) throws IgniteCheckedException { IgniteClientDisconnectedCheckedException err = new IgniteClientDisconnectedCheckedException( ctx.cluster().clientReconnectFuture(), "Failed to execute dynamic cache change request, client node disconnected."); for (IgniteInternalFuture fut : pendingFuts.values()) ((GridFutureAdapter)fut).onDone(err); for (IgniteInternalFuture fut : pendingTemplateFuts.values()) ((GridFutureAdapter)fut).onDone(err); for (CacheGroupContext grp : cacheGrps.values()) grp.onDisconnected(reconnectFut); for (GridCacheAdapter cache : caches.values()) { GridCacheContext cctx = cache.context(); cctx.gate().onDisconnected(reconnectFut); List<GridCacheManager> mgrs = cache.context().managers(); for (ListIterator<GridCacheManager> it = mgrs.listIterator(mgrs.size()); it.hasPrevious(); ) { GridCacheManager mgr = it.previous(); mgr.onDisconnected(reconnectFut); } } sharedCtx.onDisconnected(reconnectFut); cachesInfo.onDisconnected(); } /** * @param cctx Cache context. * @param stoppedCaches List where stopped cache should be added. */ private void stopCacheOnReconnect(GridCacheContext cctx, List<GridCacheAdapter> stoppedCaches) { cctx.gate().reconnected(true); sharedCtx.removeCacheContext(cctx); caches.remove(cctx.name()); jCacheProxies.remove(cctx.name()); stoppedCaches.add(cctx.cache()); } /** {@inheritDoc} */ @Override public IgniteInternalFuture<?> onReconnected(boolean clusterRestarted) throws IgniteCheckedException { List<GridCacheAdapter> reconnected = new ArrayList<>(caches.size()); DiscoveryDataClusterState state = ctx.state().clusterState(); boolean active = state.active() && !state.transition(); ClusterCachesReconnectResult reconnectRes = cachesInfo.onReconnected(active, state.transition()); final List<GridCacheAdapter> stoppedCaches = new ArrayList<>(); for (final GridCacheAdapter cache : caches.values()) { boolean stopped = reconnectRes.stoppedCacheGroups().contains(cache.context().groupId()) || reconnectRes.stoppedCaches().contains(cache.name()); if (stopped) stopCacheOnReconnect(cache.context(), stoppedCaches); else { cache.onReconnected(); reconnected.add(cache); if (cache.context().userCache()) { // Re-create cache structures inside indexing in order to apply recent schema changes. GridCacheContext cctx = cache.context(); DynamicCacheDescriptor desc = cacheDescriptor(cctx.name()); assert desc != null : cctx.name(); ctx.query().onCacheStop0(cctx.name(), false); ctx.query().onCacheStart0(cctx, desc.schema()); } } } final Set<Integer> stoppedGrps = reconnectRes.stoppedCacheGroups(); for (CacheGroupContext grp : cacheGrps.values()) { if (stoppedGrps.contains(grp.groupId())) cacheGrps.remove(grp.groupId()); else grp.onReconnected(); } sharedCtx.onReconnected(active); for (GridCacheAdapter cache : reconnected) cache.context().gate().reconnected(false); IgniteInternalFuture<?> stopFut = null; if (!stoppedCaches.isEmpty()) { stopFut = ctx.closure().runLocalSafe(new Runnable() { @Override public void run() { for (GridCacheAdapter cache : stoppedCaches) { CacheGroupContext grp = cache.context().group(); onKernalStop(cache, true); stopCache(cache, true, false); if (!grp.hasCaches()) stopCacheGroup(grp); } } }); } return stopFut; } /** * @param cache Cache to start. * @param schema Cache schema. * @throws IgniteCheckedException If failed to start cache. */ @SuppressWarnings({"TypeMayBeWeakened", "unchecked"}) private void startCache(GridCacheAdapter<?, ?> cache, QuerySchema schema) throws IgniteCheckedException { GridCacheContext<?, ?> cacheCtx = cache.context(); CacheConfiguration cfg = cacheCtx.config(); // Intentionally compare Boolean references using '!=' below to check if the flag has been explicitly set. if (cfg.isStoreKeepBinary() && cfg.isStoreKeepBinary() != CacheConfiguration.DFLT_STORE_KEEP_BINARY && !(ctx.config().getMarshaller() instanceof BinaryMarshaller)) U.warn(log, "CacheConfiguration.isStoreKeepBinary() configuration property will be ignored because " + "BinaryMarshaller is not used"); // Start managers. for (GridCacheManager mgr : F.view(cacheCtx.managers(), F.notContains(dhtExcludes(cacheCtx)))) mgr.start(cacheCtx); cacheCtx.initConflictResolver(); if (cfg.getCacheMode() != LOCAL && GridCacheUtils.isNearEnabled(cfg)) { GridCacheContext<?, ?> dhtCtx = cacheCtx.near().dht().context(); // Start DHT managers. for (GridCacheManager mgr : dhtManagers(dhtCtx)) mgr.start(dhtCtx); dhtCtx.initConflictResolver(); // Start DHT cache. dhtCtx.cache().start(); if (log.isDebugEnabled()) log.debug("Started DHT cache: " + dhtCtx.cache().name()); } ctx.continuous().onCacheStart(cacheCtx); cacheCtx.cache().start(); ctx.query().onCacheStart(cacheCtx, schema); cacheCtx.onStarted(); String memPlcName = cfg.getMemoryPolicyName(); if (memPlcName == null && ctx.config().getMemoryConfiguration() != null) memPlcName = ctx.config().getMemoryConfiguration().getDefaultMemoryPolicyName(); if (log.isInfoEnabled()) { log.info("Started cache [name=" + cfg.getName() + (cfg.getGroupName() != null ? ", group=" + cfg.getGroupName() : "") + ", memoryPolicyName=" + memPlcName + ", mode=" + cfg.getCacheMode() + ", atomicity=" + cfg.getAtomicityMode() + ']'); } } /** * @param cache Cache to stop. * @param cancel Cancel flag. */ @SuppressWarnings({"TypeMayBeWeakened", "unchecked"}) private void stopCache(GridCacheAdapter<?, ?> cache, boolean cancel, boolean destroy) { GridCacheContext ctx = cache.context(); if (!cache.isNear() && ctx.shared().wal() != null) { try { ctx.shared().wal().fsync(null); } catch (IgniteCheckedException e) { U.error(log, "Failed to flush write-ahead log on cache stop " + "[cache=" + ctx.name() + "]", e); } } sharedCtx.removeCacheContext(ctx); cache.stop(); ctx.kernalContext().query().onCacheStop(ctx, destroy); if (isNearEnabled(ctx)) { GridDhtCacheAdapter dht = ctx.near().dht(); // Check whether dht cache has been started. if (dht != null) { dht.stop(); GridCacheContext<?, ?> dhtCtx = dht.context(); List<GridCacheManager> dhtMgrs = dhtManagers(dhtCtx); for (ListIterator<GridCacheManager> it = dhtMgrs.listIterator(dhtMgrs.size()); it.hasPrevious(); ) { GridCacheManager mgr = it.previous(); mgr.stop(cancel, destroy); } } } List<GridCacheManager> mgrs = ctx.managers(); Collection<GridCacheManager> excludes = dhtExcludes(ctx); // Reverse order. for (ListIterator<GridCacheManager> it = mgrs.listIterator(mgrs.size()); it.hasPrevious(); ) { GridCacheManager mgr = it.previous(); if (!excludes.contains(mgr)) mgr.stop(cancel, destroy); } ctx.kernalContext().continuous().onCacheStop(ctx); ctx.kernalContext().cache().context().snapshot().onCacheStop(ctx); ctx.group().stopCache(ctx, destroy); U.stopLifecycleAware(log, lifecycleAwares(ctx.group(), cache.configuration(), ctx.store().configuredStore())); if (log.isInfoEnabled()) { if (ctx.group().sharedGroup()) log.info("Stopped cache [cacheName=" + cache.name() + ", group=" + ctx.group().name() + ']'); else log.info("Stopped cache [cacheName=" + cache.name() + ']'); } cleanup(ctx); } /** * @throws IgniteCheckedException If failed to wait. */ public void awaitStarted() throws IgniteCheckedException { U.await(cacheStartedLatch); } /** * @param cache Cache. * @throws IgniteCheckedException If failed. */ @SuppressWarnings("unchecked") private void onKernalStart(GridCacheAdapter<?, ?> cache) throws IgniteCheckedException { GridCacheContext<?, ?> ctx = cache.context(); // Start DHT cache as well. if (isNearEnabled(ctx)) { GridDhtCacheAdapter dht = ctx.near().dht(); GridCacheContext<?, ?> dhtCtx = dht.context(); for (GridCacheManager mgr : dhtManagers(dhtCtx)) mgr.onKernalStart(); dht.onKernalStart(); if (log.isDebugEnabled()) log.debug("Executed onKernalStart() callback for DHT cache: " + dht.name()); } for (GridCacheManager mgr : F.view(ctx.managers(), F0.notContains(dhtExcludes(ctx)))) mgr.onKernalStart(); cache.onKernalStart(); if (ctx.events().isRecordable(EventType.EVT_CACHE_STARTED)) ctx.events().addEvent(EventType.EVT_CACHE_STARTED); if (log.isDebugEnabled()) log.debug("Executed onKernalStart() callback for cache [name=" + cache.name() + ", mode=" + cache.configuration().getCacheMode() + ']'); } /** * @param cache Cache to stop. * @param cancel Cancel flag. */ @SuppressWarnings("unchecked") private void onKernalStop(GridCacheAdapter<?, ?> cache, boolean cancel) { GridCacheContext ctx = cache.context(); if (isNearEnabled(ctx)) { GridDhtCacheAdapter dht = ctx.near().dht(); if (dht != null) { GridCacheContext<?, ?> dhtCtx = dht.context(); for (GridCacheManager mgr : dhtManagers(dhtCtx)) mgr.onKernalStop(cancel); dht.onKernalStop(); } } List<GridCacheManager> mgrs = ctx.managers(); Collection<GridCacheManager> excludes = dhtExcludes(ctx); // Reverse order. for (ListIterator<GridCacheManager> it = mgrs.listIterator(mgrs.size()); it.hasPrevious(); ) { GridCacheManager mgr = it.previous(); if (!excludes.contains(mgr)) mgr.onKernalStop(cancel); } cache.onKernalStop(); if (ctx.events().isRecordable(EventType.EVT_CACHE_STOPPED)) ctx.events().addEvent(EventType.EVT_CACHE_STOPPED); } /** * @param cfg Cache configuration to use to create cache. * @param grp Cache group. * @param pluginMgr Cache plugin manager. * @param desc Cache descriptor. * @param locStartTopVer Current topology version. * @param cacheObjCtx Cache object context. * @param affNode {@code True} if local node affinity node. * @param updatesAllowed Updates allowed flag. * @return Cache context. * @throws IgniteCheckedException If failed to create cache. */ private GridCacheContext createCache(CacheConfiguration<?, ?> cfg, CacheGroupContext grp, @Nullable CachePluginManager pluginMgr, DynamicCacheDescriptor desc, AffinityTopologyVersion locStartTopVer, CacheObjectContext cacheObjCtx, boolean affNode, boolean updatesAllowed) throws IgniteCheckedException { assert cfg != null; if (cfg.getCacheStoreFactory() instanceof GridCacheLoaderWriterStoreFactory) { GridCacheLoaderWriterStoreFactory factory = (GridCacheLoaderWriterStoreFactory)cfg.getCacheStoreFactory(); prepare(cfg, factory.loaderFactory(), false); prepare(cfg, factory.writerFactory(), false); } else prepare(cfg, cfg.getCacheStoreFactory(), false); CacheStore cfgStore = cfg.getCacheStoreFactory() != null ? cfg.getCacheStoreFactory().create() : null; validate(ctx.config(), cfg, desc.cacheType(), cfgStore); if (pluginMgr == null) pluginMgr = new CachePluginManager(ctx, cfg); pluginMgr.validate(); sharedCtx.jta().registerCache(cfg); // Skip suggestions for internal caches. if (desc.cacheType().userCache()) suggestOptimizations(cfg, cfgStore != null); Collection<Object> toPrepare = new ArrayList<>(); if (cfgStore instanceof GridCacheLoaderWriterStore) { toPrepare.add(((GridCacheLoaderWriterStore)cfgStore).loader()); toPrepare.add(((GridCacheLoaderWriterStore)cfgStore).writer()); } else toPrepare.add(cfgStore); prepare(cfg, toPrepare); U.startLifecycleAware(lifecycleAwares(grp, cfg, cfgStore)); boolean nearEnabled = GridCacheUtils.isNearEnabled(cfg); GridCacheAffinityManager affMgr = new GridCacheAffinityManager(); GridCacheEventManager evtMgr = new GridCacheEventManager(); CacheEvictionManager evictMgr = (nearEnabled || cfg.isOnheapCacheEnabled()) ? new GridCacheEvictionManager() : new CacheOffheapEvictionManager(); GridCacheQueryManager qryMgr = queryManager(cfg); CacheContinuousQueryManager contQryMgr = new CacheContinuousQueryManager(); CacheDataStructuresManager dataStructuresMgr = new CacheDataStructuresManager(); GridCacheTtlManager ttlMgr = new GridCacheTtlManager(); CacheConflictResolutionManager rslvrMgr = pluginMgr.createComponent(CacheConflictResolutionManager.class); GridCacheDrManager drMgr = pluginMgr.createComponent(GridCacheDrManager.class); CacheStoreManager storeMgr = pluginMgr.createComponent(CacheStoreManager.class); storeMgr.initialize(cfgStore, sesHolders); GridCacheContext<?, ?> cacheCtx = new GridCacheContext( ctx, sharedCtx, cfg, grp, desc.cacheType(), locStartTopVer, affNode, updatesAllowed, /* * Managers in starting order! * =========================== */ evtMgr, storeMgr, evictMgr, qryMgr, contQryMgr, dataStructuresMgr, ttlMgr, drMgr, rslvrMgr, pluginMgr, affMgr ); cacheCtx.cacheObjectContext(cacheObjCtx); GridCacheAdapter cache = null; switch (cfg.getCacheMode()) { case LOCAL: { switch (cfg.getAtomicityMode()) { case TRANSACTIONAL: { cache = new GridLocalCache(cacheCtx); break; } case ATOMIC: { cache = new GridLocalAtomicCache(cacheCtx); break; } default: { assert false : "Invalid cache atomicity mode: " + cfg.getAtomicityMode(); } } break; } case PARTITIONED: case REPLICATED: { if (nearEnabled) { switch (cfg.getAtomicityMode()) { case TRANSACTIONAL: { cache = new GridNearTransactionalCache(cacheCtx); break; } case ATOMIC: { cache = new GridNearAtomicCache(cacheCtx); break; } default: { assert false : "Invalid cache atomicity mode: " + cfg.getAtomicityMode(); } } } else { switch (cfg.getAtomicityMode()) { case TRANSACTIONAL: { cache = cacheCtx.affinityNode() ? new GridDhtColocatedCache(cacheCtx) : new GridDhtColocatedCache(cacheCtx, new GridNoStorageCacheMap()); break; } case ATOMIC: { cache = cacheCtx.affinityNode() ? new GridDhtAtomicCache(cacheCtx) : new GridDhtAtomicCache(cacheCtx, new GridNoStorageCacheMap()); break; } default: { assert false : "Invalid cache atomicity mode: " + cfg.getAtomicityMode(); } } } break; } default: { assert false : "Invalid cache mode: " + cfg.getCacheMode(); } } cacheCtx.cache(cache); GridCacheContext<?, ?> ret = cacheCtx; /* * Create DHT cache. * ================ */ if (cfg.getCacheMode() != LOCAL && nearEnabled) { /* * Specifically don't create the following managers * here and reuse the one from Near cache: * 1. GridCacheVersionManager * 2. GridCacheIoManager * 3. GridCacheDeploymentManager * 4. GridCacheQueryManager (note, that we start it for DHT cache though). * 5. CacheContinuousQueryManager (note, that we start it for DHT cache though). * 6. GridCacheDgcManager * 7. GridCacheTtlManager. * =============================================== */ evictMgr = cfg.isOnheapCacheEnabled() ? new GridCacheEvictionManager() : new CacheOffheapEvictionManager(); evtMgr = new GridCacheEventManager(); pluginMgr = new CachePluginManager(ctx, cfg); drMgr = pluginMgr.createComponent(GridCacheDrManager.class); cacheCtx = new GridCacheContext( ctx, sharedCtx, cfg, grp, desc.cacheType(), locStartTopVer, affNode, true, /* * Managers in starting order! * =========================== */ evtMgr, storeMgr, evictMgr, qryMgr, contQryMgr, dataStructuresMgr, ttlMgr, drMgr, rslvrMgr, pluginMgr, affMgr ); cacheCtx.cacheObjectContext(cacheObjCtx); GridDhtCacheAdapter dht = null; switch (cfg.getAtomicityMode()) { case TRANSACTIONAL: { assert cache instanceof GridNearTransactionalCache; GridNearTransactionalCache near = (GridNearTransactionalCache)cache; GridDhtCache dhtCache = cacheCtx.affinityNode() ? new GridDhtCache(cacheCtx) : new GridDhtCache(cacheCtx, new GridNoStorageCacheMap()); dhtCache.near(near); near.dht(dhtCache); dht = dhtCache; break; } case ATOMIC: { assert cache instanceof GridNearAtomicCache; GridNearAtomicCache near = (GridNearAtomicCache)cache; GridDhtAtomicCache dhtCache = cacheCtx.affinityNode() ? new GridDhtAtomicCache(cacheCtx) : new GridDhtAtomicCache(cacheCtx, new GridNoStorageCacheMap()); dhtCache.near(near); near.dht(dhtCache); dht = dhtCache; break; } default: { assert false : "Invalid cache atomicity mode: " + cfg.getAtomicityMode(); } } cacheCtx.cache(dht); } if (!CU.isUtilityCache(cache.name()) && !CU.isSystemCache(cache.name())) { registerMbean(cache.localMxBean(), cache.name(), false); registerMbean(cache.clusterMxBean(), cache.name(), false); } return ret; } /** * Gets a collection of currently started caches. * * @return Collection of started cache names. */ public Collection<String> cacheNames() { return F.viewReadOnly(cacheDescriptors().values(), new IgniteClosure<DynamicCacheDescriptor, String>() { @Override public String apply(DynamicCacheDescriptor desc) { return desc.cacheConfiguration().getName(); } }); } /** * Gets public cache that can be used for query execution. * If cache isn't created on current node it will be started. * * @param start Start cache. * @param inclLoc Include local caches. * @return Cache or {@code null} if there is no suitable cache. */ public IgniteCacheProxy<?, ?> getOrStartPublicCache(boolean start, boolean inclLoc) throws IgniteCheckedException { // Try to find started cache first. for (Map.Entry<String, GridCacheAdapter<?, ?>> e : caches.entrySet()) { if (!e.getValue().context().userCache()) continue; CacheConfiguration ccfg = e.getValue().configuration(); String cacheName = ccfg.getName(); if ((inclLoc || ccfg.getCacheMode() != LOCAL)) return publicJCache(cacheName); } if (start) { for (Map.Entry<String, DynamicCacheDescriptor> e : cachesInfo.registeredCaches().entrySet()) { DynamicCacheDescriptor desc = e.getValue(); if (!desc.cacheType().userCache()) continue; CacheConfiguration ccfg = desc.cacheConfiguration(); if (ccfg.getCacheMode() != LOCAL) { dynamicStartCache(null, ccfg.getName(), null, false, true, true).get(); return publicJCache(ccfg.getName()); } } } return null; } /** * Gets a collection of currently started public cache names. * * @return Collection of currently started public cache names */ public Collection<String> publicCacheNames() { return F.viewReadOnly(cacheDescriptors().values(), new IgniteClosure<DynamicCacheDescriptor, String>() { @Override public String apply(DynamicCacheDescriptor desc) { return desc.cacheConfiguration().getName(); } }, new IgnitePredicate<DynamicCacheDescriptor>() { @Override public boolean apply(DynamicCacheDescriptor desc) { return desc.cacheType().userCache(); } } ); } /** * Gets cache mode. * * @param cacheName Cache name to check. * @return Cache mode. */ public CacheMode cacheMode(String cacheName) { assert cacheName != null; DynamicCacheDescriptor desc = cacheDescriptor(cacheName); return desc != null ? desc.cacheConfiguration().getCacheMode() : null; } /** * @return Caches to be started when this node starts. */ @NotNull public List<T2<DynamicCacheDescriptor, NearCacheConfiguration>> cachesToStartOnLocalJoin() { return cachesInfo.cachesToStartOnLocalJoin(); } /** * @param caches Caches to start. * @param exchTopVer Current exchange version. * @throws IgniteCheckedException If failed. */ public void startCachesOnLocalJoin(List<T2<DynamicCacheDescriptor, NearCacheConfiguration>> caches, AffinityTopologyVersion exchTopVer) throws IgniteCheckedException { if (!F.isEmpty(caches)) { for (T2<DynamicCacheDescriptor, NearCacheConfiguration> t : caches) { DynamicCacheDescriptor desc = t.get1(); prepareCacheStart( desc.cacheConfiguration(), desc, t.get2(), exchTopVer ); } } } /** * @param node Joined node. * @return {@code True} if there are new caches received from joined node. */ boolean hasCachesReceivedFromJoin(ClusterNode node) { return cachesInfo.hasCachesReceivedFromJoin(node.id()); } /** * Starts statically configured caches received from remote nodes during exchange. * * @param nodeId Joining node ID. * @param exchTopVer Current exchange version. * @return Started caches descriptors. * @throws IgniteCheckedException If failed. */ public Collection<DynamicCacheDescriptor> startReceivedCaches(UUID nodeId, AffinityTopologyVersion exchTopVer) throws IgniteCheckedException { List<DynamicCacheDescriptor> started = cachesInfo.cachesReceivedFromJoin(nodeId); for (DynamicCacheDescriptor desc : started) { IgnitePredicate<ClusterNode> filter = desc.groupDescriptor().config().getNodeFilter(); if (CU.affinityNode(ctx.discovery().localNode(), filter)) { prepareCacheStart( desc.cacheConfiguration(), desc, null, exchTopVer ); } } return started; } /** * @param startCfg Cache configuration to use. * @param desc Cache descriptor. * @param reqNearCfg Near configuration if specified for client cache start request. * @param exchTopVer Current exchange version. * @throws IgniteCheckedException If failed. */ void prepareCacheStart( CacheConfiguration startCfg, DynamicCacheDescriptor desc, @Nullable NearCacheConfiguration reqNearCfg, AffinityTopologyVersion exchTopVer ) throws IgniteCheckedException { assert !caches.containsKey(startCfg.getName()) : startCfg.getName(); CacheConfiguration ccfg = new CacheConfiguration(startCfg); IgniteCacheProxyImpl<?, ?> proxy = jCacheProxies.get(ccfg.getName()); boolean proxyRestart = proxy != null && proxy.isRestarting() && !caches.containsKey(ccfg.getName()); CacheObjectContext cacheObjCtx = ctx.cacheObjects().contextForCache(ccfg); boolean affNode; if (ccfg.getCacheMode() == LOCAL) { affNode = true; ccfg.setNearConfiguration(null); } else if (CU.affinityNode(ctx.discovery().localNode(), desc.groupDescriptor().config().getNodeFilter())) affNode = true; else { affNode = false; ccfg.setNearConfiguration(reqNearCfg); } StoredCacheData cacheData = toStoredData(desc); if (sharedCtx.pageStore() != null && affNode) sharedCtx.pageStore().initializeForCache(desc.groupDescriptor(), cacheData); String grpName = startCfg.getGroupName(); CacheGroupContext grp = null; if (grpName != null) { for (CacheGroupContext grp0 : cacheGrps.values()) { if (grp0.sharedGroup() && grpName.equals(grp0.name())) { grp = grp0; break; } } if (grp == null) { grp = startCacheGroup(desc.groupDescriptor(), desc.cacheType(), affNode, cacheObjCtx, exchTopVer); } } else { grp = startCacheGroup(desc.groupDescriptor(), desc.cacheType(), affNode, cacheObjCtx, exchTopVer); } GridCacheContext cacheCtx = createCache(ccfg, grp, null, desc, exchTopVer, cacheObjCtx, affNode, true); cacheCtx.dynamicDeploymentId(desc.deploymentId()); GridCacheAdapter cache = cacheCtx.cache(); sharedCtx.addCacheContext(cacheCtx); caches.put(cacheCtx.name(), cache); startCache(cache, desc.schema() != null ? desc.schema() : new QuerySchema()); grp.onCacheStarted(cacheCtx); onKernalStart(cache); if (proxyRestart) proxy.onRestarted(cacheCtx, cache); } /** * @param desc Group descriptor. * @param cacheType Cache type. * @param affNode Affinity node flag. * @param cacheObjCtx Cache object context. * @param exchTopVer Current topology version. * @return Started cache group. * @throws IgniteCheckedException If failed. */ private CacheGroupContext startCacheGroup( CacheGroupDescriptor desc, CacheType cacheType, boolean affNode, CacheObjectContext cacheObjCtx, AffinityTopologyVersion exchTopVer) throws IgniteCheckedException { CacheConfiguration cfg = new CacheConfiguration(desc.config()); String memPlcName = cfg.getMemoryPolicyName(); MemoryPolicy memPlc = sharedCtx.database().memoryPolicy(memPlcName); FreeList freeList = sharedCtx.database().freeList(memPlcName); ReuseList reuseList = sharedCtx.database().reuseList(memPlcName); CacheGroupContext grp = new CacheGroupContext(sharedCtx, desc.groupId(), desc.receivedFrom(), cacheType, cfg, affNode, memPlc, cacheObjCtx, freeList, reuseList, exchTopVer); for (Object obj : grp.configuredUserObjects()) prepare(cfg, obj, false); U.startLifecycleAware(grp.configuredUserObjects()); grp.start(); CacheGroupContext old = cacheGrps.put(desc.groupId(), grp); assert old == null : old.name(); return grp; } /** * @param cacheName Cache name. * @param stop {@code True} for stop cache, {@code false} for close cache. * @param restart Restart flag. */ void blockGateway(String cacheName, boolean stop, boolean restart) { // Break the proxy before exchange future is done. IgniteCacheProxyImpl<?, ?> proxy = jCacheProxies.get(cacheName); if (proxy != null) { if (stop) { if (restart) proxy.restart(); proxy.context().gate().stopped(); } else proxy.closeProxy(); } } /** * @param req Request. */ private void stopGateway(DynamicCacheChangeRequest req) { assert req.stop() : req; IgniteCacheProxyImpl<?, ?> proxy; // Break the proxy before exchange future is done. if (req.restart()) { proxy = jCacheProxies.get(req.cacheName()); if (proxy != null) proxy.restart(); } else proxy = jCacheProxies.remove(req.cacheName()); if (proxy != null) proxy.context().gate().onStopped(); } /** * @param cacheName Cache name. * @param destroy Cache destroy flag. * @return Stopped cache context. */ private GridCacheContext<?, ?> prepareCacheStop(String cacheName, boolean destroy) { GridCacheAdapter<?, ?> cache = caches.remove(cacheName); if (cache != null) { GridCacheContext<?, ?> ctx = cache.context(); sharedCtx.removeCacheContext(ctx); onKernalStop(cache, true); stopCache(cache, true, destroy); return ctx; } return null; } /** * @param startTopVer Cache start version. * @param err Cache start error if any. */ void initCacheProxies(AffinityTopologyVersion startTopVer, @Nullable Throwable err) { for (GridCacheAdapter<?, ?> cache : caches.values()) { GridCacheContext<?, ?> cacheCtx = cache.context(); if (cacheCtx.startTopologyVersion().equals(startTopVer) ) { if (!jCacheProxies.containsKey(cacheCtx.name())) jCacheProxies.putIfAbsent(cacheCtx.name(), new IgniteCacheProxyImpl(cache.context(), cache, false)); if (cacheCtx.preloader() != null) cacheCtx.preloader().onInitialExchangeComplete(err); } } } /** * @param cachesToClose Caches to close. * @param retClientCaches {@code True} if return IDs of closed client caches. * @return Closed client caches' IDs. */ Set<Integer> closeCaches(Set<String> cachesToClose, boolean retClientCaches) { Set<Integer> ids = null; boolean locked = false; try { for (String cacheName : cachesToClose) { blockGateway(cacheName, false, false); GridCacheContext ctx = sharedCtx.cacheContext(CU.cacheId(cacheName)); if (ctx == null) continue; if (retClientCaches && !ctx.affinityNode()) { if (ids == null) ids = U.newHashSet(cachesToClose.size()); ids.add(ctx.cacheId()); } if (!ctx.affinityNode() && !locked) { // Do not close client cache while requests processing is in progress. sharedCtx.io().writeLock(); locked = true; } if (!ctx.affinityNode() && ctx.transactional()) sharedCtx.tm().rollbackTransactionsForCache(ctx.cacheId()); closeCache(ctx, false); } return ids; } finally { if (locked) sharedCtx.io().writeUnlock(); } } /** * @param cctx Cache context. * @param destroy Destroy flag. */ private void closeCache(GridCacheContext cctx, boolean destroy) { if (cctx.affinityNode()) { GridCacheAdapter<?, ?> cache = caches.get(cctx.name()); assert cache != null : cctx.name(); jCacheProxies.put(cctx.name(), new IgniteCacheProxyImpl(cache.context(), cache, false)); } else { jCacheProxies.remove(cctx.name()); cctx.gate().onStopped(); prepareCacheStop(cctx.name(), destroy); if (!cctx.group().hasCaches()) stopCacheGroup(cctx.group().groupId()); } } /** * Callback invoked when first exchange future for dynamic cache is completed. * * @param cacheStartVer Started caches version to create proxy for. * @param exchActions Change requests. * @param err Error. */ @SuppressWarnings("unchecked") public void onExchangeDone( AffinityTopologyVersion cacheStartVer, @Nullable ExchangeActions exchActions, @Nullable Throwable err ) { initCacheProxies(cacheStartVer, err); if (exchActions == null) return; if (exchActions.systemCachesStarting() && exchActions.stateChangeRequest() == null) { ctx.dataStructures().restoreStructuresState(ctx); ctx.service().updateUtilityCache(); } if (err == null) { // Force checkpoint if there is any cache stop request if (exchActions.cacheStopRequests().size() > 0) { try { sharedCtx.database().waitForCheckpoint("caches stop"); } catch (IgniteCheckedException e) { U.error(log, "Failed to wait for checkpoint finish during cache stop.", e); } } for (ExchangeActions.CacheActionData action : exchActions.cacheStopRequests()) { CacheGroupContext gctx = cacheGrps.get(action.descriptor().groupId()); // Cancel all operations blocking gateway if (gctx != null) { final String msg = "Failed to wait for topology update, cache group is stopping."; // If snapshot operation in progress we must throw CacheStoppedException // for correct cache proxy restart. For more details see // IgniteCacheProxy.cacheException() gctx.affinity().cancelFutures(new CacheStoppedException(msg)); } stopGateway(action.request()); sharedCtx.database().checkpointReadLock(); try { prepareCacheStop(action.request().cacheName(), action.request().destroy()); } finally { sharedCtx.database().checkpointReadUnlock(); } } List<IgniteBiTuple<CacheGroupContext, Boolean>> stoppedGroups = new ArrayList<>(); for (ExchangeActions.CacheGroupActionData action : exchActions.cacheGroupsToStop()) { Integer groupId = action.descriptor().groupId(); if (cacheGrps.containsKey(groupId)) { stoppedGroups.add(F.t(cacheGrps.get(groupId), action.destroy())); stopCacheGroup(groupId); } } if (!sharedCtx.kernalContext().clientNode()) sharedCtx.database().onCacheGroupsStopped(stoppedGroups); if (exchActions.deactivate()) sharedCtx.deactivate(); } } /** * @param grpId Group ID. */ private void stopCacheGroup(int grpId) { CacheGroupContext grp = cacheGrps.remove(grpId); if (grp != null) stopCacheGroup(grp); } /** * @param grp Cache group. */ private void stopCacheGroup(CacheGroupContext grp) { grp.stopGroup(); U.stopLifecycleAware(log, grp.configuredUserObjects()); cleanup(grp); } /** * @param cacheName Cache name. * @param deploymentId Future deployment ID. */ void completeTemplateAddFuture(String cacheName, IgniteUuid deploymentId) { GridCacheProcessor.TemplateConfigurationFuture fut = (GridCacheProcessor.TemplateConfigurationFuture)pendingTemplateFuts.get(cacheName); if (fut != null && fut.deploymentId().equals(deploymentId)) fut.onDone(); } /** * @param req Request to complete future for. * @param success Future result. * @param err Error if any. */ void completeCacheStartFuture(DynamicCacheChangeRequest req, boolean success, @Nullable Throwable err) { if (ctx.localNodeId().equals(req.initiatingNodeId())) { DynamicCacheStartFuture fut = (DynamicCacheStartFuture)pendingFuts.get(req.requestId()); if (fut != null) fut.onDone(success, err); } } /** * @param reqId Request ID. * @param err Error if any. */ void completeClientCacheChangeFuture(UUID reqId, @Nullable Exception err) { DynamicCacheStartFuture fut = (DynamicCacheStartFuture)pendingFuts.get(reqId); if (fut != null) fut.onDone(false, err); } /** * Creates shared context. * * @param kernalCtx Kernal context. * @param storeSesLsnrs Store session listeners. * @return Shared context. * @throws IgniteCheckedException If failed. */ @SuppressWarnings("unchecked") private GridCacheSharedContext createSharedContext(GridKernalContext kernalCtx, Collection<CacheStoreSessionListener> storeSesLsnrs) throws IgniteCheckedException { IgniteTxManager tm = new IgniteTxManager(); GridCacheMvccManager mvccMgr = new GridCacheMvccManager(); GridCacheVersionManager verMgr = new GridCacheVersionManager(); GridCacheDeploymentManager depMgr = new GridCacheDeploymentManager(); GridCachePartitionExchangeManager exchMgr = new GridCachePartitionExchangeManager(); IgniteCacheDatabaseSharedManager dbMgr; IgnitePageStoreManager pageStoreMgr = null; IgniteWriteAheadLogManager walMgr = null; if (ctx.config().isPersistentStoreEnabled() && !ctx.clientNode()) { if (ctx.clientNode()) { U.warn(log, "Persistent Store is not supported on client nodes (Persistent Store's" + " configuration will be ignored)."); } dbMgr = new GridCacheDatabaseSharedManager(ctx); pageStoreMgr = new FilePageStoreManager(ctx); walMgr = new FileWriteAheadLogManager(ctx); } else dbMgr = new IgniteCacheDatabaseSharedManager(); IgniteCacheSnapshotManager snpMgr = ctx.plugins().createComponent(IgniteCacheSnapshotManager.class); if (snpMgr == null) snpMgr = new IgniteCacheSnapshotManager(); GridCacheIoManager ioMgr = new GridCacheIoManager(); CacheAffinitySharedManager topMgr = new CacheAffinitySharedManager(); GridCacheSharedTtlCleanupManager ttl = new GridCacheSharedTtlCleanupManager(); CacheJtaManagerAdapter jta = JTA.createOptional(); return new GridCacheSharedContext( kernalCtx, tm, verMgr, mvccMgr, pageStoreMgr, walMgr, dbMgr, snpMgr, depMgr, exchMgr, topMgr, ioMgr, ttl, jta, storeSesLsnrs ); } /** {@inheritDoc} */ @Nullable @Override public DiscoveryDataExchangeType discoveryDataType() { return CACHE_PROC; } /** {@inheritDoc} */ @Override public void collectJoiningNodeData(DiscoveryDataBag dataBag) { cachesInfo.collectJoiningNodeData(dataBag); } /** {@inheritDoc} */ @Override public void collectGridNodeData(DiscoveryDataBag dataBag) { cachesInfo.collectGridNodeData(dataBag); } /** {@inheritDoc} */ @Override public void onJoiningNodeDataReceived(JoiningNodeDiscoveryData data) { cachesInfo.onJoiningNodeDataReceived(data); } /** {@inheritDoc} */ @Override public void onGridDataReceived(GridDiscoveryData data) { cachesInfo.onGridDataReceived(data); } /** * @param msg Message. */ public void onStateChangeFinish(ChangeGlobalStateFinishMessage msg) { cachesInfo.onStateChangeFinish(msg); } /** * @param msg Message. * @param topVer Current topology version. * @throws IgniteCheckedException If configuration validation failed. * @return Exchange actions. */ public ExchangeActions onStateChangeRequest(ChangeGlobalStateMessage msg, AffinityTopologyVersion topVer) throws IgniteCheckedException { return cachesInfo.onStateChangeRequest(msg, topVer); } /** * @return {@code True} if need locally start all existing caches on client node start. */ private boolean startAllCachesOnClientStart() { return startClientCaches && ctx.clientNode(); } /** * Dynamically starts cache using template configuration. * * @param cacheName Cache name. * @return Future that will be completed when cache is deployed. */ public IgniteInternalFuture<?> createFromTemplate(String cacheName) { try { CacheConfiguration cfg = getOrCreateConfigFromTemplate(cacheName); return dynamicStartCache(cfg, cacheName, null, true, true, true); } catch (IgniteCheckedException e) { throw U.convertException(e); } } /** * Dynamically starts cache using template configuration. * * @param cacheName Cache name. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Future that will be completed when cache is deployed. */ public IgniteInternalFuture<?> getOrCreateFromTemplate(String cacheName, boolean checkThreadTx) { assert cacheName != null; try { if (publicJCache(cacheName, false, checkThreadTx) != null) // Cache with given name already started. return new GridFinishedFuture<>(); CacheConfiguration cfg = getOrCreateConfigFromTemplate(cacheName); return dynamicStartCache(cfg, cacheName, null, false, true, checkThreadTx); } catch (IgniteCheckedException e) { return new GridFinishedFuture<>(e); } } /** * @param cacheName Cache name. * @return Cache configuration, or {@code null} if no template with matching name found. * @throws IgniteCheckedException If failed. */ public CacheConfiguration getConfigFromTemplate(String cacheName) throws IgniteCheckedException { CacheConfiguration cfgTemplate = null; CacheConfiguration dfltCacheCfg = null; List<CacheConfiguration> wildcardNameCfgs = null; for (DynamicCacheDescriptor desc : cachesInfo.registeredTemplates().values()) { assert desc.template(); CacheConfiguration cfg = desc.cacheConfiguration(); assert cfg != null; if (F.eq(cacheName, cfg.getName())) { cfgTemplate = cfg; break; } if (cfg.getName() != null) { if (cfg.getName().endsWith("*")) { if (cfg.getName().length() > 1) { if (wildcardNameCfgs == null) wildcardNameCfgs = new ArrayList<>(); wildcardNameCfgs.add(cfg); } else dfltCacheCfg = cfg; // Template with name '*'. } } else if (dfltCacheCfg == null) dfltCacheCfg = cfg; } if (cfgTemplate == null && cacheName != null && wildcardNameCfgs != null) { Collections.sort(wildcardNameCfgs, new Comparator<CacheConfiguration>() { @Override public int compare(CacheConfiguration cfg1, CacheConfiguration cfg2) { Integer len1 = cfg1.getName() != null ? cfg1.getName().length() : 0; Integer len2 = cfg2.getName() != null ? cfg2.getName().length() : 0; return len2.compareTo(len1); } }); for (CacheConfiguration cfg : wildcardNameCfgs) { if (cacheName.startsWith(cfg.getName().substring(0, cfg.getName().length() - 1))) { cfgTemplate = cfg; break; } } } if (cfgTemplate == null) cfgTemplate = dfltCacheCfg; if (cfgTemplate == null) return null; cfgTemplate = cloneCheckSerializable(cfgTemplate); CacheConfiguration cfg = new CacheConfiguration(cfgTemplate); cfg.setName(cacheName); return cfg; } /** * @param cacheName Cache name. * @return Cache configuration. * @throws IgniteCheckedException If failed. */ private CacheConfiguration getOrCreateConfigFromTemplate(String cacheName) throws IgniteCheckedException { CacheConfiguration cfg = getConfigFromTemplate(cacheName); return cfg != null ? cfg : new CacheConfiguration(cacheName); } /** * Dynamically starts cache. * * @param ccfg Cache configuration. * @param cacheName Cache name. * @param nearCfg Near cache configuration. * @param failIfExists Fail if exists flag. * @param failIfNotStarted If {@code true} fails if cache is not started. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Future that will be completed when cache is deployed. */ @SuppressWarnings("IfMayBeConditional") public IgniteInternalFuture<Boolean> dynamicStartCache( @Nullable CacheConfiguration ccfg, String cacheName, @Nullable NearCacheConfiguration nearCfg, boolean failIfExists, boolean failIfNotStarted, boolean checkThreadTx ) { return dynamicStartCache(ccfg, cacheName, nearCfg, CacheType.USER, false, failIfExists, failIfNotStarted, checkThreadTx); } /** * Dynamically starts cache as a result of SQL {@code CREATE TABLE} command. * * @param ccfg Cache configuration. */ @SuppressWarnings("IfMayBeConditional") public IgniteInternalFuture<Boolean> dynamicStartSqlCache( CacheConfiguration ccfg ) { A.notNull(ccfg, "ccfg"); return dynamicStartCache(ccfg, ccfg.getName(), ccfg.getNearConfiguration(), CacheType.USER, true, false, true, true); } /** * Dynamically starts cache. * * @param ccfg Cache configuration. * @param cacheName Cache name. * @param nearCfg Near cache configuration. * @param cacheType Cache type. * @param sql If the cache needs to be created as the result of SQL {@code CREATE TABLE} command. * @param failIfExists Fail if exists flag. * @param failIfNotStarted If {@code true} fails if cache is not started. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Future that will be completed when cache is deployed. */ @SuppressWarnings("IfMayBeConditional") public IgniteInternalFuture<Boolean> dynamicStartCache( @Nullable CacheConfiguration ccfg, String cacheName, @Nullable NearCacheConfiguration nearCfg, CacheType cacheType, boolean sql, boolean failIfExists, boolean failIfNotStarted, boolean checkThreadTx ) { assert cacheName != null; if (checkThreadTx) checkEmptyTransactions(); try { DynamicCacheChangeRequest req = prepareCacheChangeRequest( ccfg, cacheName, nearCfg, cacheType, sql, failIfExists, failIfNotStarted); if (req != null) { if (req.clientStartOnly()) return startClientCacheChange(F.asMap(req.cacheName(), req), null); return F.first(initiateCacheChanges(F.asList(req))); } else return new GridFinishedFuture<>(); } catch (Exception e) { return new GridFinishedFuture<>(e); } } /** * @param startReqs Start requests. * @param cachesToClose Cache tp close. * @return Future for cache change operation. */ private IgniteInternalFuture<Boolean> startClientCacheChange( @Nullable Map<String, DynamicCacheChangeRequest> startReqs, @Nullable Set<String> cachesToClose) { assert startReqs != null ^ cachesToClose != null; DynamicCacheStartFuture fut = new DynamicCacheStartFuture(UUID.randomUUID()); IgniteInternalFuture old = pendingFuts.put(fut.id, fut); assert old == null : old; ctx.discovery().clientCacheStartEvent(fut.id, startReqs, cachesToClose); IgniteCheckedException err = checkNodeState(); if (err != null) fut.onDone(err); return fut; } /** * Dynamically starts multiple caches. * * @param ccfgList Collection of cache configuration. * @param failIfExists Fail if exists flag. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Future that will be completed when all caches are deployed. */ public IgniteInternalFuture<?> dynamicStartCaches(Collection<CacheConfiguration> ccfgList, boolean failIfExists, boolean checkThreadTx) { return dynamicStartCaches(ccfgList, null, failIfExists, checkThreadTx); } /** * Dynamically starts multiple caches. * * @param ccfgList Collection of cache configuration. * @param cacheType Cache type. * @param failIfExists Fail if exists flag. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Future that will be completed when all caches are deployed. */ private IgniteInternalFuture<?> dynamicStartCaches( Collection<CacheConfiguration> ccfgList, CacheType cacheType, boolean failIfExists, boolean checkThreadTx ) { if (checkThreadTx) checkEmptyTransactions(); List<DynamicCacheChangeRequest> srvReqs = null; Map<String, DynamicCacheChangeRequest> clientReqs = null; try { for (CacheConfiguration ccfg : ccfgList) { CacheType ct = cacheType; if (ct == null) { if (CU.isUtilityCache(ccfg.getName())) ct = CacheType.UTILITY; else if (internalCaches.contains(ccfg.getName())) ct = CacheType.INTERNAL; else ct = CacheType.USER; } DynamicCacheChangeRequest req = prepareCacheChangeRequest( ccfg, ccfg.getName(), null, ct, false, failIfExists, true ); if (req != null) { if (req.clientStartOnly()) { if (clientReqs == null) clientReqs = U.newLinkedHashMap(ccfgList.size()); clientReqs.put(req.cacheName(), req); } else { if (srvReqs == null) srvReqs = new ArrayList<>(ccfgList.size()); srvReqs.add(req); } } } } catch (Exception e) { return new GridFinishedFuture<>(e); } if (srvReqs != null || clientReqs != null) { if (clientReqs != null && srvReqs == null) return startClientCacheChange(clientReqs, null); GridCompoundFuture<?, ?> compoundFut = new GridCompoundFuture<>(); for (DynamicCacheStartFuture fut : initiateCacheChanges(srvReqs)) compoundFut.add((IgniteInternalFuture)fut); if (clientReqs != null) { IgniteInternalFuture<Boolean> clientStartFut = startClientCacheChange(clientReqs, null); compoundFut.add((IgniteInternalFuture)clientStartFut); } compoundFut.markInitialized(); return compoundFut; } else return new GridFinishedFuture<>(); } /** * @param cacheName Cache name to destroy. * @param sql If the cache needs to be destroyed only if it was created as the result of SQL {@code CREATE TABLE} * command. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Future that will be completed when cache is destroyed. */ public IgniteInternalFuture<Boolean> dynamicDestroyCache(String cacheName, boolean sql, boolean checkThreadTx, boolean restart) { assert cacheName != null; if (checkThreadTx) checkEmptyTransactions(); DynamicCacheChangeRequest req = DynamicCacheChangeRequest.stopRequest(ctx, cacheName, sql, true); req.stop(true); req.destroy(true); req.restart(restart); return F.first(initiateCacheChanges(F.asList(req))); } /** * @param cacheNames Collection of cache names to destroy. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Future that will be completed when cache is destroyed. */ public IgniteInternalFuture<?> dynamicDestroyCaches(Collection<String> cacheNames, boolean checkThreadTx, boolean restart) { return dynamicDestroyCaches(cacheNames, checkThreadTx, restart, true); } /** * @param cacheNames Collection of cache names to destroy. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Future that will be completed when cache is destroyed. */ public IgniteInternalFuture<?> dynamicDestroyCaches(Collection<String> cacheNames, boolean checkThreadTx, boolean restart, boolean destroy) { if (checkThreadTx) checkEmptyTransactions(); List<DynamicCacheChangeRequest> reqs = new ArrayList<>(cacheNames.size()); for (String cacheName : cacheNames) { DynamicCacheChangeRequest req = DynamicCacheChangeRequest.stopRequest(ctx, cacheName, false, true); req.stop(true); req.destroy(destroy); req.restart(restart); reqs.add(req); } GridCompoundFuture<?, ?> compoundFut = new GridCompoundFuture<>(); for (DynamicCacheStartFuture fut : initiateCacheChanges(reqs)) compoundFut.add((IgniteInternalFuture)fut); compoundFut.markInitialized(); return compoundFut; } /** * @param cacheName Cache name to close. * @return Future that will be completed when cache is closed. */ IgniteInternalFuture<?> dynamicCloseCache(String cacheName) { assert cacheName != null; IgniteCacheProxy<?, ?> proxy = jCacheProxies.get(cacheName); if (proxy == null || proxy.isProxyClosed()) return new GridFinishedFuture<>(); // No-op. checkEmptyTransactions(); if (proxy.context().isLocal()) return dynamicDestroyCache(cacheName, false, true, false); return startClientCacheChange(null, Collections.singleton(cacheName)); } /** * Resets cache state after the cache has been moved to recovery state. * * @param cacheNames Cache names. * @return Future that will be completed when state is changed for all caches. */ public IgniteInternalFuture<?> resetCacheState(Collection<String> cacheNames) { checkEmptyTransactions(); if (F.isEmpty(cacheNames)) cacheNames = cachesInfo.registeredCaches().keySet(); Collection<DynamicCacheChangeRequest> reqs = new ArrayList<>(cacheNames.size()); for (String cacheName : cacheNames) { DynamicCacheDescriptor desc = cacheDescriptor(cacheName); if (desc == null) { U.warn(log, "Failed to find cache for reset lost partition request, cache does not exist: " + cacheName); continue; } DynamicCacheChangeRequest req = DynamicCacheChangeRequest.resetLostPartitions(ctx, cacheName); reqs.add(req); } GridCompoundFuture fut = new GridCompoundFuture(); for (DynamicCacheStartFuture f : initiateCacheChanges(reqs)) fut.add(f); fut.markInitialized(); return fut; } public CacheType cacheType(String cacheName ) { if (CU.isUtilityCache(cacheName)) return CacheType.UTILITY; else if (internalCaches.contains(cacheName)) return CacheType.INTERNAL; else if (DataStructuresProcessor.isDataStructureCache(cacheName)) return CacheType.DATA_STRUCTURES; else return CacheType.USER; } /** * Form a {@link StoredCacheData} with all data to correctly restore cache params when its configuration * is read from page store. Essentially, this method takes from {@link DynamicCacheDescriptor} all that's * needed to start cache correctly, leaving out everything else. * * @param desc Cache descriptor to process. * @return {@link StoredCacheData} based on {@code desc}. */ private static StoredCacheData toStoredData(DynamicCacheDescriptor desc) { A.notNull(desc, "desc"); StoredCacheData res = new StoredCacheData(desc.cacheConfiguration()); res.queryEntities(desc.schema() == null ? Collections.<QueryEntity>emptyList() : desc.schema().entities()); res.sql(desc.sql()); return res; } /** * @param reqs Requests. * @return Collection of futures. */ @SuppressWarnings("TypeMayBeWeakened") private Collection<DynamicCacheStartFuture> initiateCacheChanges( Collection<DynamicCacheChangeRequest> reqs ) { Collection<DynamicCacheStartFuture> res = new ArrayList<>(reqs.size()); Collection<DynamicCacheChangeRequest> sndReqs = new ArrayList<>(reqs.size()); for (DynamicCacheChangeRequest req : reqs) { DynamicCacheStartFuture fut = new DynamicCacheStartFuture(req.requestId()); try { if (req.stop()) { DynamicCacheDescriptor desc = cacheDescriptor(req.cacheName()); if (desc == null) // No-op. fut.onDone(false); } if (req.start() && req.startCacheConfiguration() != null) { CacheConfiguration ccfg = req.startCacheConfiguration(); try { cachesInfo.validateStartCacheConfiguration(ccfg); } catch (IgniteCheckedException e) { fut.onDone(e); } } if (fut.isDone()) continue; DynamicCacheStartFuture old = (DynamicCacheStartFuture)pendingFuts.putIfAbsent( req.requestId(), fut); assert old == null; if (fut.isDone()) continue; sndReqs.add(req); } catch (Exception e) { fut.onDone(e); } finally { res.add(fut); } } Exception err = null; if (!sndReqs.isEmpty()) { try { ctx.discovery().sendCustomEvent(new DynamicCacheChangeBatch(sndReqs)); err = checkNodeState(); } catch (IgniteCheckedException e) { err = e; } } if (err != null) { for (DynamicCacheStartFuture fut : res) fut.onDone(err); } return res; } /** * @return Non null exception if node is stopping or disconnected. */ @Nullable private IgniteCheckedException checkNodeState() { if (ctx.isStopping()) { return new IgniteCheckedException("Failed to execute dynamic cache change request, " + "node is stopping."); } else if (ctx.clientDisconnected()) { return new IgniteClientDisconnectedCheckedException(ctx.cluster().clientReconnectFuture(), "Failed to execute dynamic cache change request, client node disconnected."); } return null; } /** * @param type Event type. * @param customMsg Custom message instance. * @param node Event node. * @param topVer Topology version. * @param state Cluster state. */ public void onDiscoveryEvent(int type, @Nullable DiscoveryCustomMessage customMsg, ClusterNode node, AffinityTopologyVersion topVer, DiscoveryDataClusterState state) { cachesInfo.onDiscoveryEvent(type, node, topVer); sharedCtx.affinity().onDiscoveryEvent(type, customMsg, node, topVer, state); } /** * Callback invoked from discovery thread when discovery custom message is received. * * @param msg Customer message. * @param topVer Current topology version. * @param node Node sent message. * @return {@code True} if minor topology version should be increased. */ public boolean onCustomEvent(DiscoveryCustomMessage msg, AffinityTopologyVersion topVer, ClusterNode node) { if (msg instanceof SchemaAbstractDiscoveryMessage) { ctx.query().onDiscovery((SchemaAbstractDiscoveryMessage)msg); return false; } if (msg instanceof CacheAffinityChangeMessage) return sharedCtx.affinity().onCustomEvent(((CacheAffinityChangeMessage)msg)); if (msg instanceof SnapshotDiscoveryMessage && ((SnapshotDiscoveryMessage)msg).needExchange()) return true; if (msg instanceof DynamicCacheChangeBatch) return cachesInfo.onCacheChangeRequested((DynamicCacheChangeBatch)msg, topVer); if (msg instanceof ClientCacheChangeDiscoveryMessage) cachesInfo.onClientCacheChange((ClientCacheChangeDiscoveryMessage)msg, node); return false; } /** * Checks that preload-order-dependant caches has SYNC or ASYNC preloading mode. * * @param cfgs Caches. * @return Maximum detected preload order. * @throws IgniteCheckedException If validation failed. */ private int validatePreloadOrder(CacheConfiguration[] cfgs) throws IgniteCheckedException { int maxOrder = 0; for (CacheConfiguration cfg : cfgs) { int rebalanceOrder = cfg.getRebalanceOrder(); if (rebalanceOrder > 0) { if (cfg.getCacheMode() == LOCAL) throw new IgniteCheckedException("Rebalance order set for local cache (fix configuration and restart the " + "node): " + U.maskName(cfg.getName())); if (cfg.getRebalanceMode() == CacheRebalanceMode.NONE) throw new IgniteCheckedException("Only caches with SYNC or ASYNC rebalance mode can be set as rebalance " + "dependency for other caches [cacheName=" + U.maskName(cfg.getName()) + ", rebalanceMode=" + cfg.getRebalanceMode() + ", rebalanceOrder=" + cfg.getRebalanceOrder() + ']'); maxOrder = Math.max(maxOrder, rebalanceOrder); } else if (rebalanceOrder < 0) throw new IgniteCheckedException("Rebalance order cannot be negative for cache (fix configuration and restart " + "the node) [cacheName=" + cfg.getName() + ", rebalanceOrder=" + rebalanceOrder + ']'); } return maxOrder; } /** {@inheritDoc} */ @Nullable @Override public IgniteNodeValidationResult validateNode(ClusterNode node) { IgniteNodeValidationResult res = validateHashIdResolvers(node); if (res == null) res = validateRestartingCaches(node); return res; } /** * Reset restarting caches. */ public void resetRestartingCaches(){ cachesInfo.restartingCaches().clear(); } /** * @param node Joining node to validate. * @return Node validation result if there was an issue with the joining node, {@code null} otherwise. */ private IgniteNodeValidationResult validateRestartingCaches(ClusterNode node) { if (cachesInfo.hasRestartingCaches()) { String msg = "Joining node during caches restart is not allowed [joiningNodeId=" + node.id() + ", restartingCaches=" + new HashSet<>(cachesInfo.restartingCaches()) + ']'; return new IgniteNodeValidationResult(node.id(), msg, msg); } return null; } /** * @param node Joining node. * @return Validation result or {@code null} in case of success. */ @Nullable private IgniteNodeValidationResult validateHashIdResolvers(ClusterNode node) { if (!node.isClient()) { for (DynamicCacheDescriptor desc : cacheDescriptors().values()) { CacheConfiguration cfg = desc.cacheConfiguration(); if (cfg.getAffinity() instanceof RendezvousAffinityFunction) { RendezvousAffinityFunction aff = (RendezvousAffinityFunction)cfg.getAffinity(); Object nodeHashObj = aff.resolveNodeHash(node); for (ClusterNode topNode : ctx.discovery().allNodes()) { Object topNodeHashObj = aff.resolveNodeHash(topNode); if (nodeHashObj.hashCode() == topNodeHashObj.hashCode()) { String errMsg = "Failed to add node to topology because it has the same hash code for " + "partitioned affinity as one of existing nodes [cacheName=" + cfg.getName() + ", existingNodeId=" + topNode.id() + ']'; String sndMsg = "Failed to add node to topology because it has the same hash code for " + "partitioned affinity as one of existing nodes [cacheName=" + cfg.getName() + ", existingNodeId=" + topNode.id() + ']'; return new IgniteNodeValidationResult(topNode.id(), errMsg, sndMsg); } } } } } return null; } /** * @param rmt Remote node to check. * @throws IgniteCheckedException If check failed. */ private void checkTransactionConfiguration(ClusterNode rmt) throws IgniteCheckedException { TransactionConfiguration txCfg = rmt.attribute(ATTR_TX_CONFIG); if (txCfg != null) { TransactionConfiguration locTxCfg = ctx.config().getTransactionConfiguration(); if (locTxCfg.isTxSerializableEnabled() != txCfg.isTxSerializableEnabled()) throw new IgniteCheckedException("Serializable transactions enabled mismatch " + "(fix txSerializableEnabled property or set -D" + IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK + "=true " + "system property) [rmtNodeId=" + rmt.id() + ", locTxSerializableEnabled=" + locTxCfg.isTxSerializableEnabled() + ", rmtTxSerializableEnabled=" + txCfg.isTxSerializableEnabled() + ']'); } } /** * @param rmt Remote node to check. * @throws IgniteCheckedException If check failed. */ private void checkMemoryConfiguration(ClusterNode rmt) throws IgniteCheckedException { ClusterNode locNode = ctx.discovery().localNode(); if (ctx.config().isClientMode() || locNode.isDaemon() || rmt.isClient() || rmt.isDaemon()) return; MemoryConfiguration memCfg = rmt.attribute(IgniteNodeAttributes.ATTR_MEMORY_CONFIG); if (memCfg != null) { MemoryConfiguration locMemCfg = ctx.config().getMemoryConfiguration(); if (memCfg.getPageSize() != locMemCfg.getPageSize()) { throw new IgniteCheckedException("Memory configuration mismatch (fix configuration or set -D" + IGNITE_SKIP_CONFIGURATION_CONSISTENCY_CHECK + "=true system property) [rmtNodeId=" + rmt.id() + ", locPageSize = " + locMemCfg.getPageSize() + ", rmtPageSize = " + memCfg.getPageSize() + "]"); } } } /** * @param cfg Cache configuration. * @return Query manager. */ private GridCacheQueryManager queryManager(CacheConfiguration cfg) { return cfg.getCacheMode() == LOCAL ? new GridCacheLocalQueryManager() : new GridCacheDistributedQueryManager(); } /** * @return Last data version. */ public long lastDataVersion() { long max = 0; for (GridCacheAdapter<?, ?> cache : caches.values()) { GridCacheContext<?, ?> ctx = cache.context(); if (ctx.versions().last().order() > max) max = ctx.versions().last().order(); if (ctx.isNear()) { ctx = ctx.near().dht().context(); if (ctx.versions().last().order() > max) max = ctx.versions().last().order(); } } return max; } /** * @param name Cache name. * @param <K> type of keys. * @param <V> type of values. * @return Cache instance for given name. */ @SuppressWarnings("unchecked") public <K, V> IgniteInternalCache<K, V> cache(String name) { assert name != null; if (log.isDebugEnabled()) log.debug("Getting cache for name: " + name); IgniteCacheProxy<K, V> jcache = (IgniteCacheProxy<K, V>)jCacheProxies.get(name); return jcache == null ? null : jcache.internalProxy(); } /** * @param name Cache name. * @return Cache instance for given name. * @throws IgniteCheckedException If failed. */ @SuppressWarnings("unchecked") public <K, V> IgniteInternalCache<K, V> getOrStartCache(String name) throws IgniteCheckedException { return getOrStartCache(name, null); } /** * @param name Cache name. * @return Cache instance for given name. * @throws IgniteCheckedException If failed. */ @SuppressWarnings("unchecked") public <K, V> IgniteInternalCache<K, V> getOrStartCache(String name, CacheConfiguration ccfg) throws IgniteCheckedException { assert name != null; if (log.isDebugEnabled()) log.debug("Getting cache for name: " + name); IgniteCacheProxy<?, ?> cache = jCacheProxies.get(name); if (cache == null) { dynamicStartCache(ccfg, name, null, false, ccfg == null, true).get(); cache = jCacheProxies.get(name); } return cache == null ? null : (IgniteInternalCache<K, V>)cache.internalProxy(); } /** * @return All configured cache instances. */ public Collection<IgniteInternalCache<?, ?>> caches() { return F.viewReadOnly(jCacheProxies.values(), new IgniteClosure<IgniteCacheProxy<?, ?>, IgniteInternalCache<?, ?>>() { @Override public IgniteInternalCache<?, ?> apply(IgniteCacheProxy<?, ?> entries) { return entries.internalProxy(); } }); } /** * @return All configured cache instances. */ public Collection<IgniteCacheProxy<?, ?>> jcaches() { return F.viewReadOnly(jCacheProxies.values(), new IgniteClosure<IgniteCacheProxyImpl<?, ?>, IgniteCacheProxy<?, ?>>() { @Override public IgniteCacheProxy<?, ?> apply(IgniteCacheProxyImpl<?, ?> proxy) { return proxy.gatewayWrapper(); } }); } /** * Gets utility cache. * * @return Utility cache. */ public <K, V> IgniteInternalCache<K, V> utilityCache() { return internalCacheEx(CU.UTILITY_CACHE_NAME); } /** * @param name Cache name. * @return Cache. */ private <K, V> IgniteInternalCache<K, V> internalCacheEx(String name) { if (ctx.discovery().localNode().isClient()) { IgniteCacheProxy<K, V> proxy = (IgniteCacheProxy<K, V>)jCacheProxies.get(name); if (proxy == null) { GridCacheAdapter<?, ?> cacheAdapter = caches.get(name); if (cacheAdapter != null) proxy = new IgniteCacheProxyImpl(cacheAdapter.context(), cacheAdapter, false); } assert proxy != null : name; return proxy.internalProxy(); } return internalCache(name); } /** * @param name Cache name. * @param <K> type of keys. * @param <V> type of values. * @return Cache instance for given name. */ @SuppressWarnings("unchecked") public <K, V> IgniteInternalCache<K, V> publicCache(String name) { assert name != null; if (log.isDebugEnabled()) log.debug("Getting public cache for name: " + name); DynamicCacheDescriptor desc = cacheDescriptor(name); if (desc == null) throw new IllegalArgumentException("Cache is not started: " + name); if (!desc.cacheType().userCache()) throw new IllegalStateException("Failed to get cache because it is a system cache: " + name); IgniteCacheProxy<K, V> jcache = (IgniteCacheProxy<K, V>)jCacheProxies.get(name); if (jcache == null) throw new IllegalArgumentException("Cache is not started: " + name); return jcache.internalProxy(); } /** * @param cacheName Cache name. * @param <K> type of keys. * @param <V> type of values. * @return Cache instance for given name. * @throws IgniteCheckedException If failed. */ public <K, V> IgniteCacheProxy<K, V> publicJCache(String cacheName) throws IgniteCheckedException { return publicJCache(cacheName, true, true); } /** * @param cacheName Cache name. * @param failIfNotStarted If {@code true} throws {@link IllegalArgumentException} if cache is not started, * otherwise returns {@code null} in this case. * @param checkThreadTx If {@code true} checks that current thread does not have active transactions. * @return Cache instance for given name. * @throws IgniteCheckedException If failed. */ @SuppressWarnings({"unchecked", "ConstantConditions"}) @Nullable public <K, V> IgniteCacheProxy<K, V> publicJCache(String cacheName, boolean failIfNotStarted, boolean checkThreadTx) throws IgniteCheckedException { assert cacheName != null; if (log.isDebugEnabled()) log.debug("Getting public cache for name: " + cacheName); DynamicCacheDescriptor desc = cacheDescriptor(cacheName); if (desc != null && !desc.cacheType().userCache()) throw new IllegalStateException("Failed to get cache because it is a system cache: " + cacheName); IgniteCacheProxyImpl<?, ?> cache = jCacheProxies.get(cacheName); // Try to start cache, there is no guarantee that cache will be instantiated. if (cache == null) { dynamicStartCache(null, cacheName, null, false, failIfNotStarted, checkThreadTx).get(); cache = jCacheProxies.get(cacheName); } return cache != null ? (IgniteCacheProxy<K, V>) cache.gatewayWrapper() : null; } /** * Get configuration for the given cache. * * @param name Cache name. * @return Cache configuration. */ public CacheConfiguration cacheConfiguration(String name) { assert name != null; DynamicCacheDescriptor desc = cacheDescriptor(name); if (desc == null) throw new IllegalStateException("Cache doesn't exist: " + name); else return desc.cacheConfiguration(); } /** * Get registered cache descriptor. * * @param name Name. * @return Descriptor. */ public DynamicCacheDescriptor cacheDescriptor(String name) { return cachesInfo.registeredCaches().get(name); } /** * @return Cache descriptors. */ public Map<String, DynamicCacheDescriptor> cacheDescriptors() { return cachesInfo.registeredCaches(); } /** * @return Cache group descriptors. */ public Map<Integer, CacheGroupDescriptor> cacheGroupDescriptors() { return cachesInfo.registeredCacheGroups(); } /** * @param cacheId Cache ID. * @return Cache descriptor. */ @Nullable public DynamicCacheDescriptor cacheDescriptor(int cacheId) { for (DynamicCacheDescriptor cacheDesc : cacheDescriptors().values()) { CacheConfiguration ccfg = cacheDesc.cacheConfiguration(); assert ccfg != null : cacheDesc; if (CU.cacheId(ccfg.getName()) == cacheId) return cacheDesc; } return null; } /** * @param cacheCfg Cache configuration template. * @throws IgniteCheckedException If failed. */ public void addCacheConfiguration(CacheConfiguration cacheCfg) throws IgniteCheckedException { assert cacheCfg.getName() != null; String name = cacheCfg.getName(); DynamicCacheDescriptor desc = cachesInfo.registeredTemplates().get(name); if (desc != null) return; DynamicCacheChangeRequest req = DynamicCacheChangeRequest.addTemplateRequest(ctx, cacheCfg); TemplateConfigurationFuture fut = new TemplateConfigurationFuture(req.cacheName(), req.deploymentId()); TemplateConfigurationFuture old = (TemplateConfigurationFuture)pendingTemplateFuts.putIfAbsent(cacheCfg.getName(), fut); if (old != null) fut = old; Exception err = null; try { ctx.discovery().sendCustomEvent(new DynamicCacheChangeBatch(Collections.singleton(req))); if (ctx.isStopping()) { err = new IgniteCheckedException("Failed to execute dynamic cache change request, " + "node is stopping."); } else if (ctx.clientDisconnected()) { err = new IgniteClientDisconnectedCheckedException(ctx.cluster().clientReconnectFuture(), "Failed to execute dynamic cache change request, client node disconnected."); } } catch (IgniteCheckedException e) { err = e; } if (err != null) fut.onDone(err); fut.get(); } /** * @param name Cache name. * @return Cache instance for given name. */ @SuppressWarnings("unchecked") public <K, V> IgniteCacheProxy<K, V> jcache(String name) { assert name != null; IgniteCacheProxy<K, V> cache = (IgniteCacheProxy<K, V>) jCacheProxies.get(name); if (cache == null) throw new IllegalArgumentException("Cache is not configured: " + name); return cache; } /** * @param name Cache name. * @return Cache proxy. */ @Nullable public IgniteCacheProxy jcacheProxy(String name) { return jCacheProxies.get(name); } /** * @return All configured public cache instances. */ public Collection<IgniteCacheProxy<?, ?>> publicCaches() { Collection<IgniteCacheProxy<?, ?>> res = new ArrayList<>(jCacheProxies.size()); for (IgniteCacheProxyImpl<?, ?> proxy : jCacheProxies.values()) { if (proxy.context().userCache()) res.add(proxy.gatewayWrapper()); } return res; } /** * @param name Cache name. * @param <K> type of keys. * @param <V> type of values. * @return Cache instance for given name. */ @SuppressWarnings("unchecked") public <K, V> GridCacheAdapter<K, V> internalCache(String name) { assert name != null; if (log.isDebugEnabled()) log.debug("Getting internal cache adapter: " + name); return (GridCacheAdapter<K, V>)caches.get(name); } /** * Cancel all user operations. */ private void cancelFutures() { sharedCtx.mvcc().onStop(); Exception err = new IgniteCheckedException("Operation has been cancelled (node is stopping)."); for (IgniteInternalFuture fut : pendingFuts.values()) ((GridFutureAdapter)fut).onDone(err); for (IgniteInternalFuture fut : pendingTemplateFuts.values()) ((GridFutureAdapter)fut).onDone(err); } /** * @return All internal cache instances. */ public Collection<GridCacheAdapter<?, ?>> internalCaches() { return caches.values(); } /** * @param name Cache name. * @return {@code True} if specified cache is system, {@code false} otherwise. */ public boolean systemCache(String name) { assert name != null; DynamicCacheDescriptor desc = cacheDescriptor(name); return desc != null && !desc.cacheType().userCache(); } /** {@inheritDoc} */ @Override public void printMemoryStats() { X.println(">>> "); for (GridCacheAdapter c : caches.values()) { X.println(">>> Cache memory stats [igniteInstanceName=" + ctx.igniteInstanceName() + ", cache=" + c.name() + ']'); c.context().printMemoryStats(); } } /** * Callback invoked by deployment manager for whenever a class loader gets undeployed. * * @param ldr Class loader. */ public void onUndeployed(ClassLoader ldr) { if (!ctx.isStopping()) { for (GridCacheAdapter<?, ?> cache : caches.values()) { // Do not notify system caches and caches for which deployment is disabled. if (cache.context().userCache() && cache.context().deploymentEnabled()) cache.onUndeploy(ldr); } } } /** * @return Shared context. */ public <K, V> GridCacheSharedContext<K, V> context() { return (GridCacheSharedContext<K, V>)sharedCtx; } /** * @return Transactions interface implementation. */ public IgniteTransactionsEx transactions() { return transactions; } /** * Starts client caches that do not exist yet. * * @throws IgniteCheckedException In case of error. */ public void createMissingQueryCaches() throws IgniteCheckedException { for (Map.Entry<String, DynamicCacheDescriptor> e : cachesInfo.registeredCaches().entrySet()) { DynamicCacheDescriptor desc = e.getValue(); if (isMissingQueryCache(desc)) dynamicStartCache(null, desc.cacheConfiguration().getName(), null, false, true, true).get(); } } /** * Whether cache defined by provided descriptor is not yet started and has queries enabled. * * @param desc Descriptor. * @return {@code True} if this is missing query cache. */ private boolean isMissingQueryCache(DynamicCacheDescriptor desc) { CacheConfiguration ccfg = desc.cacheConfiguration(); return !caches.containsKey(ccfg.getName()) && QueryUtils.isEnabled(ccfg); } /** * Registers MBean for cache components. * * @param obj Cache component. * @param cacheName Cache name. * @param near Near flag. * @throws IgniteCheckedException If registration failed. */ @SuppressWarnings("unchecked") private void registerMbean(Object obj, @Nullable String cacheName, boolean near) throws IgniteCheckedException { if(U.IGNITE_MBEANS_DISABLED) return; assert obj != null; MBeanServer srvr = ctx.config().getMBeanServer(); assert srvr != null; cacheName = U.maskName(cacheName); cacheName = near ? cacheName + "-near" : cacheName; final Object mbeanImpl = (obj instanceof IgniteMBeanAware) ? ((IgniteMBeanAware)obj).getMBean() : obj; for (Class<?> itf : mbeanImpl.getClass().getInterfaces()) { if (itf.getName().endsWith("MBean") || itf.getName().endsWith("MXBean")) { try { U.registerCacheMBean(srvr, ctx.igniteInstanceName(), cacheName, obj.getClass().getName(), mbeanImpl, (Class<Object>)itf); } catch (Throwable e) { throw new IgniteCheckedException("Failed to register MBean for component: " + obj, e); } break; } } } /** * Unregisters MBean for cache components. * * @param o Cache component. * @param cacheName Cache name. * @param near Near flag. */ private void unregisterMbean(Object o, @Nullable String cacheName, boolean near) { if(U.IGNITE_MBEANS_DISABLED) return; assert o != null; MBeanServer srvr = ctx.config().getMBeanServer(); assert srvr != null; cacheName = U.maskName(cacheName); cacheName = near ? cacheName + "-near" : cacheName; boolean needToUnregister = o instanceof IgniteMBeanAware; if (!needToUnregister) { for (Class<?> itf : o.getClass().getInterfaces()) { if (itf.getName().endsWith("MBean") || itf.getName().endsWith("MXBean")) { needToUnregister = true; break; } } } if (needToUnregister) { try { srvr.unregisterMBean(U.makeCacheMBeanName(ctx.igniteInstanceName(), cacheName, o.getClass().getName())); } catch (Throwable e) { U.error(log, "Failed to unregister MBean for component: " + o, e); } } } /** * @param grp Cache group. * @param ccfg Cache configuration. * @param objs Extra components. * @return Components provided in cache configuration which can implement {@link LifecycleAware} interface. */ private Iterable<Object> lifecycleAwares(CacheGroupContext grp, CacheConfiguration ccfg, Object... objs) { Collection<Object> ret = new ArrayList<>(7 + objs.length); if (grp.affinityFunction() != ccfg.getAffinity()) ret.add(ccfg.getAffinity()); ret.add(ccfg.getAffinityMapper()); ret.add(ccfg.getEvictionFilter()); ret.add(ccfg.getEvictionPolicy()); ret.add(ccfg.getInterceptor()); NearCacheConfiguration nearCfg = ccfg.getNearConfiguration(); if (nearCfg != null) ret.add(nearCfg.getNearEvictionPolicy()); Collections.addAll(ret, objs); return ret; } /** * @throws IgniteException If transaction exist. */ private void checkEmptyTransactions() throws IgniteException { if (transactions().tx() != null || sharedCtx.lockedTopologyVersion(null) != null) throw new IgniteException("Cannot start/stop cache within lock or transaction."); } /** * @param val Object to check. * @return Configuration copy. * @throws IgniteCheckedException If validation failed. */ private CacheConfiguration cloneCheckSerializable(final CacheConfiguration val) throws IgniteCheckedException { if (val == null) return null; return withBinaryContext(new IgniteOutClosureX<CacheConfiguration>() { @Override public CacheConfiguration applyx() throws IgniteCheckedException { if (val.getCacheStoreFactory() != null) { try { ClassLoader ldr = ctx.config().getClassLoader(); if (ldr == null) ldr = val.getCacheStoreFactory().getClass().getClassLoader(); U.unmarshal(marsh, U.marshal(marsh, val.getCacheStoreFactory()), U.resolveClassLoader(ldr, ctx.config())); } catch (IgniteCheckedException e) { throw new IgniteCheckedException("Failed to validate cache configuration. " + "Cache store factory is not serializable. Cache name: " + U.maskName(val.getName()), e); } } try { return U.unmarshal(marsh, U.marshal(marsh, val), U.resolveClassLoader(ctx.config())); } catch (IgniteCheckedException e) { throw new IgniteCheckedException("Failed to validate cache configuration " + "(make sure all objects in cache configuration are serializable): " + U.maskName(val.getName()), e); } } }); } /** * @param c Closure. * @return Closure result. * @throws IgniteCheckedException If failed. */ private <T> T withBinaryContext(IgniteOutClosureX<T> c) throws IgniteCheckedException { IgniteCacheObjectProcessor objProc = ctx.cacheObjects(); BinaryContext oldCtx = null; if (objProc instanceof CacheObjectBinaryProcessorImpl) { GridBinaryMarshaller binMarsh = ((CacheObjectBinaryProcessorImpl)objProc).marshaller(); oldCtx = binMarsh == null ? null : binMarsh.pushContext(); } try { return c.applyx(); } finally { if (objProc instanceof CacheObjectBinaryProcessorImpl) GridBinaryMarshaller.popContext(oldCtx); } } /** * Prepares DynamicCacheChangeRequest for cache creation. * * @param ccfg Cache configuration * @param cacheName Cache name * @param nearCfg Near cache configuration * @param cacheType Cache type * @param sql Whether the cache needs to be created as the result of SQL {@code CREATE TABLE} command. * @param failIfExists Fail if exists flag. * @param failIfNotStarted If {@code true} fails if cache is not started. * @return Request or {@code null} if cache already exists. * @throws IgniteCheckedException if some of pre-checks failed * @throws CacheExistsException if cache exists and failIfExists flag is {@code true} */ private DynamicCacheChangeRequest prepareCacheChangeRequest( @Nullable CacheConfiguration ccfg, String cacheName, @Nullable NearCacheConfiguration nearCfg, CacheType cacheType, boolean sql, boolean failIfExists, boolean failIfNotStarted ) throws IgniteCheckedException { DynamicCacheDescriptor desc = cacheDescriptor(cacheName); DynamicCacheChangeRequest req = new DynamicCacheChangeRequest(UUID.randomUUID(), cacheName, ctx.localNodeId()); req.sql(sql); req.failIfExists(failIfExists); if (ccfg != null) { cloneCheckSerializable(ccfg); if (desc != null) { if (failIfExists) { throw new CacheExistsException("Failed to start cache " + "(a cache with the same name is already started): " + cacheName); } else { CacheConfiguration descCfg = desc.cacheConfiguration(); // Check if we were asked to start a near cache. if (nearCfg != null) { if (CU.affinityNode(ctx.discovery().localNode(), descCfg.getNodeFilter())) { // If we are on a data node and near cache was enabled, return success, else - fail. if (descCfg.getNearConfiguration() != null) return null; else throw new IgniteCheckedException("Failed to start near " + "cache (local node is an affinity node for cache): " + cacheName); } else // If local node has near cache, return success. req.clientStartOnly(true); } else req.clientStartOnly(true); req.deploymentId(desc.deploymentId()); req.startCacheConfiguration(descCfg); req.schema(desc.schema()); } } else { req.deploymentId(IgniteUuid.randomUuid()); CacheConfiguration cfg = new CacheConfiguration(ccfg); CacheObjectContext cacheObjCtx = ctx.cacheObjects().contextForCache(cfg); initialize(cfg, cacheObjCtx); req.startCacheConfiguration(cfg); req.schema(new QuerySchema(cfg.getQueryEntities())); } } else { req.clientStartOnly(true); if (desc != null) ccfg = desc.cacheConfiguration(); if (ccfg == null) { if (failIfNotStarted) { throw new CacheExistsException("Failed to start client cache " + "(a cache with the given name is not started): " + cacheName); } else return null; } req.deploymentId(desc.deploymentId()); req.startCacheConfiguration(ccfg); req.schema(desc.schema()); } if (nearCfg != null) req.nearCacheConfiguration(nearCfg); req.cacheType(cacheType); return req; } /** * @param obj Object to clone. * @return Object copy. * @throws IgniteCheckedException If failed. */ public <T> T clone(final T obj) throws IgniteCheckedException { return withBinaryContext(new IgniteOutClosureX<T>() { @Override public T applyx() throws IgniteCheckedException { return U.unmarshal(marsh, U.marshal(marsh, obj), U.resolveClassLoader(ctx.config())); } }); } /** * */ @SuppressWarnings("ExternalizableWithoutPublicNoArgConstructor") private class DynamicCacheStartFuture extends GridFutureAdapter<Boolean> { /** */ private UUID id; /** * @param id Future ID. */ private DynamicCacheStartFuture(UUID id) { this.id = id; } /** {@inheritDoc} */ @Override public boolean onDone(@Nullable Boolean res, @Nullable Throwable err) { // Make sure to remove future before completion. pendingFuts.remove(id, this); return super.onDone(res, err); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(DynamicCacheStartFuture.class, this); } } /** * */ @SuppressWarnings("ExternalizableWithoutPublicNoArgConstructor") private class TemplateConfigurationFuture extends GridFutureAdapter<Object> { /** Start ID. */ @GridToStringInclude private IgniteUuid deploymentId; /** Cache name. */ private String cacheName; /** * @param cacheName Cache name. * @param deploymentId Deployment ID. */ private TemplateConfigurationFuture(String cacheName, IgniteUuid deploymentId) { this.deploymentId = deploymentId; this.cacheName = cacheName; } /** * @return Start ID. */ public IgniteUuid deploymentId() { return deploymentId; } /** {@inheritDoc} */ @Override public boolean onDone(@Nullable Object res, @Nullable Throwable err) { // Make sure to remove future before completion. pendingTemplateFuts.remove(cacheName, this); return super.onDone(res, err); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(TemplateConfigurationFuture.class, this); } } /** * */ static class LocalAffinityFunction implements AffinityFunction { /** */ private static final long serialVersionUID = 0L; /** {@inheritDoc} */ @Override public List<List<ClusterNode>> assignPartitions(AffinityFunctionContext affCtx) { ClusterNode locNode = null; for (ClusterNode n : affCtx.currentTopologySnapshot()) { if (n.isLocal()) { locNode = n; break; } } if (locNode == null) throw new IgniteException("Local node is not included into affinity nodes for 'LOCAL' cache"); List<List<ClusterNode>> res = new ArrayList<>(partitions()); for (int part = 0; part < partitions(); part++) res.add(Collections.singletonList(locNode)); return Collections.unmodifiableList(res); } /** {@inheritDoc} */ @Override public void reset() { // No-op. } /** {@inheritDoc} */ @Override public int partitions() { return 1; } /** {@inheritDoc} */ @Override public int partition(Object key) { return 0; } /** {@inheritDoc} */ @Override public void removeNode(UUID nodeId) { // No-op. } } /** * */ private class RemovedItemsCleanupTask implements GridTimeoutObject { /** */ private final IgniteUuid id = IgniteUuid.randomUuid(); /** */ private final long endTime; /** */ private final long timeout; /** * @param timeout Timeout. */ RemovedItemsCleanupTask(long timeout) { this.timeout = timeout; endTime = U.currentTimeMillis() + timeout; } /** {@inheritDoc} */ @Override public IgniteUuid timeoutId() { return id; } /** {@inheritDoc} */ @Override public long endTime() { return endTime; } /** {@inheritDoc} */ @Override public void onTimeout() { ctx.closure().runLocalSafe(new Runnable() { @Override public void run() { try { for (CacheGroupContext grp : sharedCtx.cache().cacheGroups()) { if (!grp.isLocal() && grp.affinityNode()) { GridDhtPartitionTopology top = null; try { top = grp.topology(); } catch (IllegalStateException ignore) { // Cache stopped. } if (top != null) { for (GridDhtLocalPartition part : top.currentLocalPartitions()) part.cleanupRemoveQueue(); } if (ctx.isStopping()) return; } } } catch (Exception e) { U.error(log, "Failed to cleanup removed cache items: " + e, e); } if (ctx.isStopping()) return; addRemovedItemsCleanupTask(timeout); } }, true); } } }
apache-2.0
fengyanjava/msb-android
app/src/main/java/com/mianshibang/main/ui/FavoriteDetail.java
6620
package com.mianshibang.main.ui; import java.util.ArrayList; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.ListView; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener; import com.handmark.pulltorefresh.library.PullToRefreshListView; import com.mianshibang.main.R; import com.mianshibang.main.adapter.QuestionViewProvider; import com.mianshibang.main.adapter.RequestAdapter; import com.mianshibang.main.adapter.RequestAdapter.ArrayDelegate; import com.mianshibang.main.adapter.RequestAdapter.Loader; import com.mianshibang.main.adapter.RequestAdapter.LoaderListener; import com.mianshibang.main.api.FavoriteApis; import com.mianshibang.main.http.ResponseHandler; import com.mianshibang.main.model.MData; import com.mianshibang.main.model.MFavoriteFolder; import com.mianshibang.main.model.dto.FavoriteFolderDetail; import com.mianshibang.main.model.dto.IdResult; import com.mianshibang.main.utils.EventBusUtils; import com.mianshibang.main.utils.ToastUtils; import com.mianshibang.main.utils.UIUtils; import com.mianshibang.main.widget.FavoriteDetailHeaderView; import com.mianshibang.main.widget.PageView; import com.mianshibang.main.widget.TitleBar; import com.mianshibang.main.widget.dialog.AlertDialog; import com.mianshibang.main.widget.dialog.CreateFavoriteFolderDialog; import com.mianshibang.main.widget.dialog.FolderMorePopupWindow; import com.mianshibang.main.widget.dialog.ProgressDialog; public class FavoriteDetail extends Base implements OnClickListener, OnRefreshListener<ListView> { public static final String FolderId = "folder_id"; private TitleBar mTitleBar; private PageView mPageView; private FavoriteDetailHeaderView mDetailHeader; private PullToRefreshListView mListView; private RequestAdapter mAdapter; private String mFolderId; private MFavoriteFolder mFolder; private ProgressDialog mProgressDialog; @Override public int getContentLayout() { return R.layout.favorite_detail; } @Override public void findViews() { mTitleBar = (TitleBar) findViewById(R.id.title_bar); mListView = (PullToRefreshListView) findViewById(R.id.list); mPageView = (PageView) findViewById(R.id.page_view); mPageView.setContentView(mListView); } @Override public void setListeners() { mListView.setOnRefreshListener(this); mPageView.subscribRefreshEvent(this); } @Override public void process() { setTitleBarStyle(); mFolderId = getIntent().getStringExtra(FolderId); checkParameter(); initListView(); mAdapter.loadData(); } private void initListView() { mDetailHeader = new FavoriteDetailHeaderView(this); mListView.getRefreshableView().addHeaderView(mDetailHeader); mAdapter = new RequestAdapter(mLoader, new QuestionViewProvider(this)); mListView.setAdapter(mAdapter); } private void checkParameter() { if (TextUtils.isEmpty(mFolderId)) { throw new IllegalArgumentException("Come to .ui.FavoriteDetail but folder_id is null"); } } private void setTitleBarStyle() { mTitleBar.setTitleText(R.string.favorite_detail_title); mTitleBar.setRightButtonIcon(R.drawable.icon_title_bar_favorite_more); mTitleBar.setRightButtonClick(this); } public void onEventErrorRefresh() { mAdapter.refresh(); } @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) { mAdapter.refresh(); } @Override public void onClick(View v) { switch (v.getId()) { case TitleBar.RIGHT_BUTTON_ID: showMorePopupWindow(v); break; default: break; } } public void onEventEditFolder() { // 点击编辑 if (mFolder == null) { return; } CreateFavoriteFolderDialog dialog = new CreateFavoriteFolderDialog(this, mFolder); dialog.subscribeEvent(this); dialog.show(); } public void onEventFolderUpdate() { // 完成编辑 refreshHeaderView(mFolder); } public void onEventDeleteFolder() { // 点击删除 showDeleteHintDialog(); } private void showDeleteHintDialog() { AlertDialog dialog = new AlertDialog(this); dialog.setTitleEx(R.string.delete_favorite_folder); dialog.setMessage(R.string.delete_favorite_folder_hint); dialog.setNegativeButton(true, null, null); dialog.setPositiveButton(true, R.string.delete, new OnClickListener() { @Override public void onClick(View v) { realDeleteFolder(); } }); dialog.show(); } private void realDeleteFolder() { if (mProgressDialog == null) { mProgressDialog = new ProgressDialog(this); } mProgressDialog.show(R.string.delete_favorite_folder); FavoriteApis.deleteFavoriteFolder(mFolderId, new ResponseHandler<IdResult>() { @Override public void onSuccess(IdResult data) { if (data.isSucceeded()) { mProgressDialog.dismiss(); ToastUtils.show("删除成功"); EventBusUtils.postFolderEvent(mFolderId); finish(); } } @Override public void onFinish() { mProgressDialog.dismiss(); } }); } private void showMorePopupWindow(View anchor) { FolderMorePopupWindow popupWindow = new FolderMorePopupWindow(this); popupWindow.subscribeEvent(this); int yOffset = UIUtils.dip2px(12); popupWindow.showAsDropDown(anchor, 0, -yOffset); } private void refreshHeaderView(MFavoriteFolder folder) { mDetailHeader.show(folder); } private Loader mLoader = new Loader() { @Override protected void beforeLoadData() { mPageView.showLoading(); } @Override protected void loadDataDone(ArrayList<? extends MData> downloaded) { mPageView.showContent(); mAdapter.notifyDataSetChanged(); } @Override public void requestRefresh(LoaderListener listener) { FavoriteApis.requestFavoriteDetail(mFolderId, new Delegate(listener)); } @Override protected void refreshDone(ArrayList<? extends MData> downloaded) { loadDataDone(downloaded); } @Override public void requestLoadMore(LoaderListener listener, String beforeId) { } @Override protected void handleFailure(Throwable e) { if (mAdapter.isEmpty()) { mPageView.showNetworkError(); } } @Override public void handleFinish() { mPageView.hideLoading(); mListView.onRefreshComplete(); } }; private class Delegate extends ArrayDelegate<FavoriteFolderDetail> { public Delegate(LoaderListener listener) { super(listener); } @Override protected ArrayList<? extends MData> getArray(FavoriteFolderDetail data) { mFolder = data.folder; refreshHeaderView(mFolder); return data != null && data.isSucceeded() ? data.folder.questions : null; } } }
apache-2.0
pengrad/java-telegram-bot-api
library/src/main/java/com/pengrad/telegrambot/request/AnswerInlineQuery.java
1083
package com.pengrad.telegrambot.request; import com.pengrad.telegrambot.model.request.InlineQueryResult; import com.pengrad.telegrambot.response.BaseResponse; /** * stas * 5/2/16. */ public class AnswerInlineQuery extends BaseRequest<AnswerInlineQuery, BaseResponse> { public AnswerInlineQuery(String inlineQueryId, InlineQueryResult<?>... results) { super(BaseResponse.class); add("inline_query_id", inlineQueryId).add("results", results); } public AnswerInlineQuery cacheTime(int cacheTime) { return add("cache_time", cacheTime); } public AnswerInlineQuery isPersonal(boolean isPersonal) { return add("is_personal", isPersonal); } public AnswerInlineQuery nextOffset(String nextOffset) { return add("next_offset", nextOffset); } public AnswerInlineQuery switchPmText(String switchPmText) { return add("switch_pm_text", switchPmText); } public AnswerInlineQuery switchPmParameter(String switchPmParameter) { return add("switch_pm_parameter", switchPmParameter); } }
apache-2.0
sveintl/Multilib
multilib-api/src/main/java/com/siriusit/spezg/multilib/service/BinaryAttachmentService.java
1373
/** * 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.siriusit.spezg.multilib.service; import com.siriusit.spezg.multilib.domain.BinaryAttachment; import com.siriusit.spezg.multilib.domain.Unit; /** * Created by IntelliJ IDEA. * User: landssve * Date: 09.sep.2010 * Time: 07:07:50 * To change this template use File | Settings | File Templates. */ public interface BinaryAttachmentService { public BinaryAttachment storeBinaryAttachment(Unit unit, String type, String mimeType, byte[] contents); public BinaryAttachment findBinaryAttachmentByUnit(Unit unit); }
apache-2.0
vishalaksh/BootupApp
src/com/vishalaksh/bootupapp/util/SystemUiHiderBase.java
2019
package com.vishalaksh.bootupapp.util; import android.app.Activity; import android.view.View; import android.view.WindowManager; /** * A base implementation of {@link SystemUiHider}. Uses APIs available in all * API levels to show and hide the status bar. */ public class SystemUiHiderBase extends SystemUiHider { /** * Whether or not the system UI is currently visible. This is a cached value * from calls to {@link #hide()} and {@link #show()}. */ private boolean mVisible = true; /** * Constructor not intended to be called by clients. Use * {@link SystemUiHider#getInstance} to obtain an instance. */ protected SystemUiHiderBase(Activity activity, View anchorView, int flags) { super(activity, anchorView, flags); } @Override public void setup() { if ((mFlags & FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES) == 0) { mActivity.getWindow().setFlags( WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } } @Override public boolean isVisible() { return mVisible; } @Override public void hide() { if ((mFlags & FLAG_FULLSCREEN) != 0) { mActivity.getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } mOnVisibilityChangeListener.onVisibilityChange(false); mVisible = false; } @Override public void show() { if ((mFlags & FLAG_FULLSCREEN) != 0) { mActivity.getWindow().setFlags( 0, WindowManager.LayoutParams.FLAG_FULLSCREEN); } mOnVisibilityChangeListener.onVisibilityChange(true); mVisible = true; } }
apache-2.0
Netflix/photon
src/main/java/com/netflix/imflibrary/st0377/header/EssenceContainerData.java
8714
/* * * Copyright 2015 Netflix, 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.netflix.imflibrary.st0377.header; import com.netflix.imflibrary.IMFErrorLogger; import com.netflix.imflibrary.utils.ByteProvider; import com.netflix.imflibrary.annotations.MXFProperty; import com.netflix.imflibrary.KLVPacket; import com.netflix.imflibrary.MXFUID; import javax.annotation.concurrent.Immutable; import java.io.IOException; import java.util.Map; /** * Object model corresponding to EssenceContainerData structural metadata set defined in st377-1:2011 */ @Immutable public final class EssenceContainerData extends InterchangeObject { private static final String ERROR_DESCRIPTION_PREFIX = "MXF Header Partition: " + EssenceContainerData.class.getSimpleName() + " : "; private final EssenceContainerDataBO essenceContainerDataBO; private final GenericPackage genericPackage; /** * Instantiates a new EssenceContainerData object * * @param essenceContainerDataBO the parsed EssenceContainerData object * @param genericPackage the generic package referenced by this EssenceContainerData object */ public EssenceContainerData(EssenceContainerDataBO essenceContainerDataBO, GenericPackage genericPackage) { this.essenceContainerDataBO = essenceContainerDataBO; this.genericPackage = genericPackage; } /** * Getter for the generic package referenced by this EssenceContainerData object * @return returns the generic package referenced by this Essence Container Data object */ public GenericPackage getLinkedPackage() { return this.genericPackage; } /** * Getter for the instance UID corresponding to this EssenceContainerData set in the MXF file * @return returns the instanceUID corresponding to this Essence Container data object */ public MXFUID getInstanceUID() { return new MXFUID(this.essenceContainerDataBO.instance_uid); } /** * Getter for the identifier of the package linked to this EssenceContainerData set * @return returns the identified of the package linked to this Essence Container data */ public MXFUID getLinkedPackageUID() { return new MXFUID(this.essenceContainerDataBO.linked_package_uid); } /** * Getter for the ID of the Index Table linked to this EssenceContainerData set * @return returns the ID of the Index Table linked with this Essence Container data */ public long getIndexSID() { return this.essenceContainerDataBO.index_sid; } /** * Getter for the ID of the Essence Container to which this EssenceContainerData set is linked * @return returns the ID of the essence container liked to this Essence Container data */ public long getBodySID() { return this.essenceContainerDataBO.body_sid; } /** * A method that returns a string representation of an EssenceContainerData object * * @return string representing the object */ public String toString() { return this.essenceContainerDataBO.toString(); } /** * Object corresponding to parsed EssenceContainerData structural metadata set defined in st377-1:2011 */ @Immutable @SuppressWarnings({"PMD.FinalFieldCouldBeStatic"}) public static final class EssenceContainerDataBO extends InterchangeObjectBO { @MXFProperty(size=32, depends=true) private final byte[] linked_package_uid = null; //PackageRef type @MXFProperty(size=4) private final Long index_sid = null; @MXFProperty(size=4) private final Long body_sid = null; /** * Instantiates a new parsed EssenceContainerData object by virtue of parsing the MXF file bitstream * * @param header the parsed header (K and L fields from the KLV packet) * @param byteProvider the input stream corresponding to the MXF file * @param localTagToUIDMap mapping from local tag to element UID as provided by the Primer Pack defined in st377-1:2011 * @param imfErrorLogger logger for recording any parsing errors * @throws IOException - any I/O related error will be exposed through an IOException */ public EssenceContainerDataBO(KLVPacket.Header header, ByteProvider byteProvider, Map<Integer, MXFUID> localTagToUIDMap, IMFErrorLogger imfErrorLogger) throws IOException { super(header); long numBytesToRead = this.header.getVSize(); StructuralMetadata.populate(this, byteProvider, numBytesToRead, localTagToUIDMap); if (this.instance_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, EssenceContainerData.ERROR_DESCRIPTION_PREFIX + "instance_uid is null"); } if (this.linked_package_uid == null) { imfErrorLogger.addError(IMFErrorLogger.IMFErrors.ErrorCodes.IMF_ESSENCE_METADATA_ERROR, IMFErrorLogger.IMFErrors.ErrorLevels.NON_FATAL, EssenceContainerData.ERROR_DESCRIPTION_PREFIX + "linked_package_uid is null"); } } /** * Getter for the identifier of the package to which this EssenceContainerData set is linked * @return returns the identifier of the package linked to this Essence container data */ public MXFUID getLinkedPackageUID() { return new MXFUID(this.linked_package_uid); } /** * A method that returns a string representation of an EssenceContainerDataBO object * * @return string representing the object */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("================== EssenceContainerData ======================\n"); sb.append(this.header.toString()); sb.append(String.format("instance_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.instance_uid[0], this.instance_uid[1], this.instance_uid[2], this.instance_uid[3], this.instance_uid[4], this.instance_uid[5], this.instance_uid[6], this.instance_uid[7], this.instance_uid[8], this.instance_uid[9], this.instance_uid[10], this.instance_uid[11], this.instance_uid[12], this.instance_uid[13], this.instance_uid[14], this.instance_uid[15])); sb.append(String.format("linked_package_uid = 0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%n", this.linked_package_uid[0], this.linked_package_uid[1], this.linked_package_uid[2], this.linked_package_uid[3], this.linked_package_uid[4], this.linked_package_uid[5], this.linked_package_uid[6], this.linked_package_uid[7], this.linked_package_uid[8], this.linked_package_uid[9], this.linked_package_uid[10], this.linked_package_uid[11], this.linked_package_uid[12], this.linked_package_uid[13], this.linked_package_uid[14], this.linked_package_uid[15], this.linked_package_uid[16], this.linked_package_uid[17], this.linked_package_uid[18], this.linked_package_uid[19], this.linked_package_uid[20], this.linked_package_uid[21], this.linked_package_uid[22], this.linked_package_uid[23], this.linked_package_uid[24], this.linked_package_uid[25], this.linked_package_uid[26], this.linked_package_uid[27], this.linked_package_uid[28], this.linked_package_uid[29], this.linked_package_uid[30], this.linked_package_uid[31])); sb.append(String.format("index_sid = 0x%x(%d)%n", this.index_sid, this.index_sid)); sb.append(String.format("body_sid = 0x%x(%d)%n", this.body_sid, this.body_sid)); return sb.toString(); } } }
apache-2.0
ernestp/consulo
platform/editor-ui-ex/src/com/intellij/openapi/editor/ex/util/LayerDescriptor.java
1742
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.editor.ex.util; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author max */ public class LayerDescriptor { private final SyntaxHighlighter myLayerHighlighter; private final String myTokenSeparator; private final TextAttributesKey myBackground; public LayerDescriptor(@NotNull SyntaxHighlighter layerHighlighter, @NotNull String tokenSeparator, @Nullable TextAttributesKey background) { myBackground = background; myLayerHighlighter = layerHighlighter; myTokenSeparator = tokenSeparator; } public LayerDescriptor(@NotNull SyntaxHighlighter layerHighlighter, @NotNull String tokenSeparator) { this(layerHighlighter, tokenSeparator, null); } @NotNull public SyntaxHighlighter getLayerHighlighter() { return myLayerHighlighter; } @NotNull public String getTokenSeparator() { return myTokenSeparator; } @Nullable public TextAttributesKey getBackgroundKey() { return myBackground; } }
apache-2.0
krestenkrab/hotruby
modules/vm-loaded/src/com/trifork/hotruby/classes/RubyClassObject.java
8405
package com.trifork.hotruby.classes; import com.trifork.hotruby.callable.PublicMethod; import com.trifork.hotruby.callable.PublicMethod0; import com.trifork.hotruby.callable.PublicMethod1; import com.trifork.hotruby.objects.IRubyModule; import com.trifork.hotruby.objects.IRubyObject; import com.trifork.hotruby.objects.RubyClass; import com.trifork.hotruby.objects.RubyModule; import com.trifork.hotruby.objects.RubyString; import com.trifork.hotruby.runtime.LoadedRubyRuntime; import com.trifork.hotruby.runtime.MetaClass; import com.trifork.hotruby.runtime.MetaModule; import com.trifork.hotruby.runtime.PublicMethodN; import com.trifork.hotruby.runtime.RubyBlock; import com.trifork.hotruby.runtime.RubyMethod; import com.trifork.hotruby.runtime.Selector; public class RubyClassObject extends RubyBaseClassObject { @Override public void init(final MetaClass meta) { super.init(meta); final Selector call_to_s = getRuntime().getSelector(meta, "to_s"); final Selector call_eq2 = getRuntime().getSelector(meta, "=="); meta.register_instance_method("freeze", new PublicMethod0() { @Override public IRubyObject call(IRubyObject receiver, RubyBlock block) { receiver.setFrozen(true); return receiver; } }); meta.register_instance_method("__id__", new PublicMethod0() { @Override public IRubyObject call(IRubyObject receiver, RubyBlock block) { return meta.getRuntime().get_object_id(receiver); } }); meta.register_instance_method("__send__", new PublicMethodN() { @Override public IRubyObject call(IRubyObject receiver, IRubyObject[] args, RubyBlock block) { if (args.length < 1) { throw wrongArgs(receiver, args.length); } IRubyObject sym = args[0]; IRubyObject[] call_args = new IRubyObject[args.length-1]; System.arraycopy(args, 1, call_args, 0, call_args.length); com.trifork.hotruby.objects.RubyMethod m = (com.trifork.hotruby.objects.RubyMethod) receiver.get_meta_module().method(receiver, sym.fast_to_s(call_to_s).asSymbol()); return m.call(call_args, block); } @Override public int getArity() { return -2; } }); meta.alias_instance_method("send", "__send__"); meta.register_instance_method("method", new PublicMethod1() { @Override public IRubyObject call(IRubyObject receiver, IRubyObject arg, RubyBlock block) { return receiver.get_meta_module().method(receiver, arg.fast_to_s(call_to_s).asSymbol()); }}); meta.register_instance_method("respond_to?", new PublicMethodN() { @Override public IRubyObject call(IRubyObject receiver, IRubyObject[] args, RubyBlock block) { if (args.length < 1 || args.length > 2) { wrongArgs(receiver, args.length); } String msg = args[0].fast_to_s(call_to_s).asSymbol(); boolean includePriv = (args.length == 2 ? args[1].isTrue() : false); return bool(receiver.get_meta_module().respond_to_p(msg, includePriv, receiver instanceof IRubyModule)); } @Override public int getArity() { return -2; } }); meta.register_instance_method("instance_of?", new PublicMethod1() { @Override public IRubyObject call(IRubyObject receiver, IRubyObject arg, RubyBlock block) { if (arg instanceof RubyClass) { RubyClass self_type = (RubyClass) receiver.get_class(); boolean isa = self_type.get_meta_class().is_subclass_of( ((RubyClass) arg).get_meta_class()); return bool(isa); } return bool(false); } }); meta.register_instance_method("kind_of?", new PublicMethod1() { @Override public IRubyObject call(IRubyObject receiver, IRubyObject arg, RubyBlock block) { if (arg instanceof RubyModule) { RubyClass self_type = (RubyClass) receiver.get_class(); boolean isa = self_type.get_meta_class().is_kind_of( ((RubyModule) arg).get_meta_module()); return bool(isa); } return bool(false); } }); meta.alias_instance_method("is_a?", "kind_of?"); meta.register_instance_method("==", new PublicMethod1() { @Override public IRubyObject call(IRubyObject receiver, IRubyObject arg, RubyBlock block) { return bool(receiver == arg); } }); meta.register_instance_method("===", new PublicMethod1() { @Override public IRubyObject call(IRubyObject receiver, IRubyObject arg, RubyBlock block) { return receiver.fast_eq2(arg, call_eq2); } }); // meta.alias_instance_method("===", "=="); meta.register_instance_method("class", new PublicMethod0() { @Override public IRubyObject call(IRubyObject receiver, RubyBlock block) { return receiver.get_class(); } }); meta.register_instance_method("p", new PublicMethodN() { @Override public IRubyObject call(IRubyObject receiver, IRubyObject[] args, RubyBlock block) { for (int i = 0; i < args.length; i++) { System.out.println(args[i] == null ? "NULL" : args[i].inspect()); } return LoadedRubyRuntime.NIL; } }); meta.register_instance_method("to_s", new PublicMethod0() { @Override public IRubyObject call(IRubyObject receiver, RubyBlock block) { return new RubyString("#<" + receiver.get_class().get_meta_class().getName() + ":0x" + Integer .toHexString(System.identityHashCode(receiver)) + ">"); } }); meta.register_instance_method("inspect", new PublicMethod0() { @Override public IRubyObject call(IRubyObject receiver, RubyBlock block) { return new RubyString("#<" + receiver.get_class().get_meta_class().getName() + ":0x" + Integer .toHexString(System.identityHashCode(receiver)) + ">"); } }); meta.register_instance_method("initialize", new RubyMethod() { @Override public IRubyObject call(IRubyObject receiver, RubyBlock block) { return receiver; } @Override public IRubyObject call(IRubyObject receiver, IRubyObject arg, RubyBlock block) { return receiver; } @Override public IRubyObject call(IRubyObject receiver, IRubyObject arg1, IRubyObject arg2, RubyBlock block) { return receiver; } @Override public IRubyObject call(IRubyObject receiver, IRubyObject[] args, RubyBlock block) { return receiver; } @Override public int getArity() { return -1; } }); meta.register_instance_method("missing_method", new PublicMethod() { @Override public IRubyObject call(IRubyObject receiver, IRubyObject name, RubyBlock block) { throw getRuntime().newNoMethodError( "cannot find method " + name + " in " + receiver.inspect() + " (a " + receiver.get_class() + ")"); } @Override public IRubyObject call(IRubyObject receiver, RubyBlock block) { throw getRuntime().newNoMethodError( "cannot find method in " + receiver.inspect() + " (a " + receiver.get_class() + ")"); } @Override public IRubyObject call(IRubyObject receiver, IRubyObject name, IRubyObject arg2, RubyBlock block) { throw getRuntime().newNoMethodError( "cannot find method " + name + " in " + receiver.inspect() + " (a " + receiver.get_class() + ")"); } @Override public IRubyObject call(IRubyObject receiver, IRubyObject[] args, RubyBlock block) { throw getRuntime().newNoMethodError( "cannot find method " + (args.length > 0 ? args[0] : "?") + " in " + receiver.inspect() + " (a " + receiver.get_class() + ")"); } @Override public int getArity() { return -2; } }); meta.register_instance_method("extend", new PublicMethodN() { @Override public IRubyObject call(IRubyObject receiver, IRubyObject[] args, RubyBlock block) { MetaModule mm; boolean receiver_is_module; if (receiver instanceof IRubyModule) { mm = ((IRubyModule)receiver).get_meta_module(); receiver_is_module = true; } else { mm = receiver.get_singleton_meta_class(); receiver_is_module = false; } for (int i = 0; i < args.length; i++) { if (args[i] instanceof IRubyModule) { MetaModule being_added_from = ((IRubyModule)args[i]).get_meta_module(); being_added_from.copy_methods_to(mm, receiver_is_module); } else { throw getRuntime().newArgumentError("argument not a module"); } } return receiver; }}); } }
apache-2.0
equella/Equella
Source/Plugins/Core/com.equella.admin/src/com/tle/admin/workflow/editor/NotificationsTab.java
6655
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Apache License, * Version 2.0, (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tle.admin.workflow.editor; import static com.tle.common.security.SecurityConstants.Recipient.GROUP; import static com.tle.common.security.SecurityConstants.Recipient.USER; import static com.tle.common.security.SecurityConstants.getRecipient; import static com.tle.common.security.SecurityConstants.getRecipientType; import static com.tle.common.security.SecurityConstants.getRecipientValue; import com.dytech.gui.ChangeDetector; import com.dytech.gui.TableLayout; import com.tle.admin.helper.GroupBox; import com.tle.common.applet.gui.AppletGuiUtils; import com.tle.common.i18n.CurrentLocale; import com.tle.common.recipientselector.MultipleFinderControl; import com.tle.common.recipientselector.RecipientFilter; import com.tle.common.workflow.node.ScriptNode; import com.tle.core.remoting.RemoteUserService; import java.awt.GridLayout; import java.awt.Rectangle; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.*; public class NotificationsTab extends JPanel { private static final long serialVersionUID = 1L; private GroupBox notifyOnCompletionGroupBox; private MultipleFinderControl notifyOnCompletionFinder; private MultipleFinderControl notifyOnErrorFinder; private static String keyPfx = "com.tle.admin.workflow.editor.scripteditor.nofificationstab."; public NotificationsTab(ChangeDetector changeDetector, RemoteUserService userService) { setupGui(userService); setupChangeDetector(changeDetector); } private void setupGui(RemoteUserService userService) { notifyOnCompletionFinder = new MultipleFinderControl(userService, RecipientFilter.USERS, RecipientFilter.GROUPS); notifyOnCompletionGroupBox = GroupBox.withCheckBox(CurrentLocale.get(keyPfx + "completed.groupbox"), false); notifyOnCompletionGroupBox.getInnerPanel().setLayout(new GridLayout(1, 1)); notifyOnCompletionGroupBox.add(notifyOnCompletionFinder); notifyOnErrorFinder = new MultipleFinderControl(userService, RecipientFilter.USERS, RecipientFilter.GROUPS); final int[] rows = { TableLayout.FILL, TableLayout.FILL, }; final int[] cols = { TableLayout.FILL, }; setLayout(new TableLayout(rows, cols)); setBorder(AppletGuiUtils.DEFAULT_BORDER); JPanel errorPanel = new JPanel(); JLabel errorLabel = new JLabel(CurrentLocale.get(keyPfx + "error.label")); errorPanel.setLayout( new TableLayout( new int[] {errorLabel.getPreferredSize().height, TableLayout.FILL}, new int[] {TableLayout.FILL})); errorPanel.add(errorLabel, new Rectangle(0, 0, 1, 1)); errorPanel.add(notifyOnErrorFinder, new Rectangle(0, 1, 1, 1)); add(errorPanel, new Rectangle(0, 0, 1, 1)); add(notifyOnCompletionGroupBox, new Rectangle(0, 1, 1, 1)); } private void setupChangeDetector(ChangeDetector changeDetector) { notifyOnCompletionFinder.watch(changeDetector); notifyOnErrorFinder.watch(changeDetector); } public void load(ScriptNode node) { notifyOnCompletionGroupBox.setSelected(node.isNotifyOnCompletion()); List<String> notifyOnCompletionList = new ArrayList<String>(); if (node.getUsersNotifyOnCompletion() != null) { for (String user : node.getUsersNotifyOnCompletion()) { notifyOnCompletionList.add(getRecipient(USER, user)); } } if (node.getGroupsNotifyOnCompletion() != null) { for (String grp : node.getGroupsNotifyOnCompletion()) { notifyOnCompletionList.add(getRecipient(GROUP, grp)); } } notifyOnCompletionFinder.load(notifyOnCompletionList); List<String> notifyOnErrorList = new ArrayList<String>(); if (node.getUsersNotifyOnError() != null) { for (String user : node.getUsersNotifyOnError()) { notifyOnErrorList.add(getRecipient(USER, user)); } } if (node.getGroupsNotifyOnError() != null) { for (String grp : node.getGroupsNotifyOnError()) { notifyOnErrorList.add(getRecipient(GROUP, grp)); } } notifyOnErrorFinder.load(notifyOnErrorList); } public void save(ScriptNode node) { node.setUsersNotifyOnCompletion(null); node.setGroupsNotifyOnCompletion(null); node.setUsersNotifyOnError(null); node.setGroupsNotifyOnError(null); node.setNotifyOnCompletion(false); if (notifyOnCompletionGroupBox.isSelected()) { Set<String> users = new HashSet<String>(); Set<String> groups = new HashSet<String>(); for (String result : notifyOnCompletionFinder.save()) { String value = getRecipientValue(result); switch (getRecipientType(result)) { case USER: users.add(value); break; case GROUP: groups.add(value); break; default: throw new IllegalStateException("We should never reach here"); } } if (users.isEmpty()) { users = null; } if (groups.isEmpty()) { groups = null; } node.setNotifyOnCompletion(true); node.setUsersNotifyOnCompletion(users); node.setGroupsNotifyOnCompletion(groups); } Set<String> users = new HashSet<String>(); Set<String> groups = new HashSet<String>(); for (String result : notifyOnErrorFinder.save()) { String value = getRecipientValue(result); switch (getRecipientType(result)) { case USER: users.add(value); break; case GROUP: groups.add(value); break; default: throw new IllegalStateException("We should never reach here"); } } if (users.isEmpty()) { users = null; } if (groups.isEmpty()) { groups = null; } node.setUsersNotifyOnError(users); node.setGroupsNotifyOnError(groups); } }
apache-2.0
JNCC-dev-team/nbn-importer
crud/target/generated-sources/annotations/uk/org/nbn/nbnv/jpa/nbncore/TaxonObservationFilterElement_.java
1723
package uk.org.nbn.nbnv.jpa.nbncore; import java.util.Date; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; import uk.org.nbn.nbnv.jpa.nbncore.SiteBoundary; import uk.org.nbn.nbnv.jpa.nbncore.Taxon; import uk.org.nbn.nbnv.jpa.nbncore.TaxonDataset; import uk.org.nbn.nbnv.jpa.nbncore.TaxonObservationFilter; import uk.org.nbn.nbnv.jpa.nbncore.TaxonObservationFilterElementType; @Generated(value="EclipseLink-2.3.0.v20110604-r9504", date="2012-11-05T12:01:58") @StaticMetamodel(TaxonObservationFilterElement.class) public class TaxonObservationFilterElement_ { public static volatile SingularAttribute<TaxonObservationFilterElement, Integer> id; public static volatile SingularAttribute<TaxonObservationFilterElement, Date> filterDateStart; public static volatile SingularAttribute<TaxonObservationFilterElement, Integer> filterSensitive; public static volatile SingularAttribute<TaxonObservationFilterElement, TaxonDataset> taxonDataset; public static volatile SingularAttribute<TaxonObservationFilterElement, TaxonObservationFilterElementType> taxonObservationFilterElementType; public static volatile SingularAttribute<TaxonObservationFilterElement, Date> filterDateEnd; public static volatile SingularAttribute<TaxonObservationFilterElement, SiteBoundary> siteBoundary; public static volatile SingularAttribute<TaxonObservationFilterElement, Integer> filterSiteBoundaryMatch; public static volatile SingularAttribute<TaxonObservationFilterElement, TaxonObservationFilter> taxonObservationFilter; public static volatile SingularAttribute<TaxonObservationFilterElement, Taxon> taxon; }
apache-2.0
deepakalur/acre
impl/grappa/GrappaFrame.java
8426
/** * Copyright 2004-2005 Sun Microsystems, 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.acre.visualizer.grappa; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.StringBufferInputStream; import java.net.URL; import java.net.URLConnection; public class GrappaFrame { // implements GrappaConstants { public GrappaUI frame = null; public final static String SCRIPT = "/devel/SalsaVizV1/formatDemo.sh"; public static void main(String[] args) { InputStream input = System.in; if (args.length > 1) { System.err.println("USAGE: java GrappaFrame [input_graph_file]"); System.exit(1); } else if (args.length == 1) { if (args[0].equals("-")) { input = System.in; } else { try { input = new FileInputStream(args[0]); } catch (FileNotFoundException fnf) { System.err.println(fnf.toString()); System.exit(1); } } } GrappaFrame demo = new GrappaFrame(); demo.build(input); } public GrappaFrame() { } public JPanel getPanel() { if (frame != null) { return frame.getPanel(); } else { return null; } } public void build(InputStream input) { build(input, true, true); } public void build(String input, boolean visible, boolean extraUI) { build(new StringBufferInputStream(input), visible, extraUI); } public void build(InputStream input, boolean visible, boolean extraUI) { frame = new GrappaUI(GrappaUtilities.buildGraph(input), extraUI); frame.setVisible(visible); } class GrappaUI extends JFrame implements ActionListener { GrappaPanel gp; Graph graph = null; JButton layout = null; JButton printer = null; JButton draw = null; JButton quit = null; JPanel panel = null; private final boolean extraUI; public GrappaUI(Graph graph) { this(graph, true); } public GrappaUI(Graph graph, boolean _extraUI) { super("GrappaUI"); this.extraUI = _extraUI; this.graph = graph; setSize(1000, 1000); setLocation(50, 50); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent wev) { Window w = wev.getWindow(); w.setVisible(false); w.dispose(); if (extraUI) { System.exit(0); } } }); JScrollPane jsp = new JScrollPane(); gp = GrappaUtilities.createGrappaPanel(graph); gp.addGrappaListener(new GrappaAdapter()); GridBagLayout gbl = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.anchor = GridBagConstraints.NORTHWEST; panel = new JPanel(); panel.setLayout(gbl); if (extraUI) { draw = new JButton("Redraw"); gbl.setConstraints(draw, gbc); panel.add(draw); draw.addActionListener(this); layout = new JButton("Layout"); gbl.setConstraints(layout, gbc); panel.add(layout); layout.addActionListener(this); printer = new JButton("Print"); gbl.setConstraints(printer, gbc); panel.add(printer); printer.addActionListener(this); quit = new JButton("Close"); gbl.setConstraints(quit, gbc); panel.add(quit); quit.addActionListener(this); } getContentPane().add("Center", jsp); if (extraUI) { getContentPane().add("West", panel); } setVisible(true); jsp.setViewportView(gp); } public JPanel getPanel() { return panel; } public void actionPerformed(ActionEvent evt) { if (evt.getSource() instanceof JButton) { JButton tgt = (JButton) evt.getSource(); if (tgt == draw) { graph.repaint(); } else if (tgt == quit) { System.exit(0); } else if (tgt == printer) { graph.printGraph(System.out); System.out.flush(); } else if (tgt == layout) { Object connector = null; try { //connector = Runtime.getRuntime().exec(GrappaFrame.SCRIPT); //connector = null; //connector = Runtime.getRuntime().exec("/Applications/GraphViz.app/Contents/MacOS/dot /devel/grappa/DEMO/crazy.dot"); } catch (Exception ex) { System.err.println("Exception while setting up Process: " + ex.getMessage() + "\nTrying URLConnection..."); connector = null; } if (connector == null) { try { connector = (new URL("http://www.research.att.com/~john/cgi-bin/format-graph")).openConnection(); URLConnection urlConn = (URLConnection) connector; urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } catch (Exception ex) { System.err.println("Exception while setting up URLConnection: " + ex.getMessage() + "\nLayout not performed."); connector = null; } } if (connector != null) { if (!GrappaSupport.filterGraph(graph, connector)) { System.err.println("ERROR: somewhere in filterGraph"); } if (connector instanceof Process) { try { int code = ((Process) connector).waitFor(); if (code != 0) { System.err.println("WARNING: proc exit code is: " + code); } } catch (InterruptedException ex) { System.err.println("Exception while closing down proc: " + ex.getMessage()); ex.printStackTrace(System.err); } } connector = null; } graph.repaint(); } } } } }
apache-2.0
ualerts-org/push-android-library
push-library/src/edu/vt/alerts/android/library/api/RegistrationService.java
4991
/* * File created on Feb 24, 2014 * * Copyright 2008-2013 Virginia Polytechnic Institute and State University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package edu.vt.alerts.android.library.api; import java.io.InputStream; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import edu.vt.alerts.android.library.callbacks.CancelRegistrationCallback; import edu.vt.alerts.android.library.callbacks.RegistrationCallback; import edu.vt.alerts.android.library.callbacks.TermsOfServiceCallback; import edu.vt.alerts.android.library.callbacks.VerifyCallback; import edu.vt.alerts.android.library.tasks.CancelRegistrationTask; import edu.vt.alerts.android.library.tasks.RegistrationTask; import edu.vt.alerts.android.library.tasks.TermsOfServiceTask; import edu.vt.alerts.android.library.tasks.VerificationTask; import edu.vt.alerts.android.library.util.PreferenceUtil; /** * An Alerts service that is used to register users to the VT Alerts Push * Notification System. * * All method calls to this service are supported using AsyncTasks. Therefore, * methods will return almost immediately. Callbacks are then used to * communicate results back to the calling code. It is safe to assume that all * method callbacks occur on the UI thread, rather than the background thread * for the AsyncTask. * * @author Michael Irwin */ public class RegistrationService { private final Environment environment; /** * Create a new instance of the service. By default, it uses the PRODUCTION * environment. */ public RegistrationService() { this(Environment.PRODUCTION); } /** * Creates a new instance of the service that is configured for the specified * environment. * @param environment The environment to use for the service. */ public RegistrationService(Environment environment) { this.environment = environment; } /** * Start the registration process for the current device. The provided * callback is used to communicate results of the registration process * @param context The application context * @param gcmSenderId The GCM sender ID for the application * @param installerCert An inputStream for the installer's certificate * provided during VT-APNS application registration * @param callback A callback used to communicate registration * results. */ public void performRegistration(final Context context, final String gcmSenderId, final InputStream installerCert, final RegistrationCallback callback) { TermsOfServiceTask tosTask = new TermsOfServiceTask(context, environment, callback, new TermsOfServiceCallback() { public void termsAccepted() { PreferenceUtil.setAcceptedTerms(context, environment, true); Log.i("registrationService", "Terms of service were accepted"); RegistrationTask registrationTask = new RegistrationTask( environment, callback, gcmSenderId, installerCert, context); registrationTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Void[0]); } public void termsRejected() { PreferenceUtil.setAcceptedTerms(context, environment, false); Log.i("registrationService", "Terms of service were rejected"); callback.registrationAborted(); } }); tosTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Void[0]); } /** * Cancel the subscription for the current device in the configured * environment. * @param context The application context * @param callback A callback to be used to notify of completion */ public void cancelRegistration(final Context context, final CancelRegistrationCallback callback) { CancelRegistrationTask task = new CancelRegistrationTask(context, environment, callback); task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Void[0]); } /** * Verify the current device's subscription to the VT-APNS system. * @param context The application context * @param callback A callback to notify of verification results */ public void verifyRegistration(final Context context, final VerifyCallback callback) { VerificationTask task = new VerificationTask(context, environment, callback); task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Void[0]); } }
apache-2.0
benjchristensen/RxJava
src/test/java/io/reactivex/completable/CompletableTimerTest.java
1577
/** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.completable; import org.junit.Test; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import io.reactivex.Completable; import io.reactivex.functions.Action; import io.reactivex.schedulers.TestScheduler; import static org.junit.Assert.assertEquals; public class CompletableTimerTest { @Test public void timer() { final TestScheduler testScheduler = new TestScheduler(); final AtomicLong atomicLong = new AtomicLong(); Completable.timer(2, TimeUnit.SECONDS, testScheduler).subscribe(new Action() { @Override public void run() throws Exception { atomicLong.incrementAndGet(); } }); assertEquals(0, atomicLong.get()); testScheduler.advanceTimeBy(1, TimeUnit.SECONDS); assertEquals(0, atomicLong.get()); testScheduler.advanceTimeBy(1, TimeUnit.SECONDS); assertEquals(1, atomicLong.get()); } }
apache-2.0
mcada/syndesis-qe
ui-tests/src/test/java/io/syndesis/qe/pages/integrations/editor/apiprovider/ApiProviderToolbar.java
2336
package io.syndesis.qe.pages.integrations.editor.apiprovider; import static com.codeborne.selenide.Condition.enabled; import static com.codeborne.selenide.Condition.visible; import static com.codeborne.selenide.Selenide.$; import static com.codeborne.selenide.Selenide.$$; import io.syndesis.qe.pages.SyndesisPageObject; import org.openqa.selenium.By; import com.codeborne.selenide.Condition; import com.codeborne.selenide.SelenideElement; import lombok.extern.slf4j.Slf4j; @Slf4j public class ApiProviderToolbar extends SyndesisPageObject { private static final class Element { public static final By ROOT = By.cssSelector(".pf-c-page__main-breadcrumb"); public static final By OPERATIONS_DROPDOWN = By.cssSelector(".operations-dropdown"); public static final By GO_TO_OPERATION_LIST_BUTTON = By.xpath("//button[normalize-space()='Go to Operation List']"); public static final By EDIT_OPENAPI_DEFINITION = By.xpath("//a[normalize-space()='View/Edit API Definition']"); } private static final class Button { public static final By PUBLISH = By.xpath("//button[text()[contains(.,'Publish')]]"); } @Override public SelenideElement getRootElement() { return $(Element.ROOT).shouldBe(visible); } @Override public boolean validate() { return getRootElement().is(visible); } public void goToOperation(String operationName) { getRootElement().$(Element.OPERATIONS_DROPDOWN).click(); getRootElement().$(Element.OPERATIONS_DROPDOWN) .$$(By.cssSelector("a strong")) .filter(Condition.text(operationName)) .shouldHaveSize(1) .get(0) .click(); } public void goToOperationList() { getRootElement().$(Element.OPERATIONS_DROPDOWN).click(); if ($(Element.GO_TO_OPERATION_LIST_BUTTON).exists()) { getRootElement().$(Element.GO_TO_OPERATION_LIST_BUTTON).shouldBe(visible).click(); } else { $$(By.className("pf-c-breadcrumb__item")).get(1).click(); } } public void editOpenApi() { getRootElement().$(Element.EDIT_OPENAPI_DEFINITION).shouldBe(visible).click(); } public void publish() { this.getRootElement().$(Button.PUBLISH).shouldBe(visible, enabled).click(); } }
apache-2.0
iraupph/tictactoe-android
AndEngineGLES2/src/org/andengine/util/TimeUtils.java
1858
package org.andengine.util; import org.andengine.util.time.TimeConstants; /** * (c) 2010 Nicolas Gramlich (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:48:49 - 04.04.2011 */ public final class TimeUtils implements TimeConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== public static final String formatSeconds(final int pSecondsTotal) { return formatSeconds(pSecondsTotal, new StringBuilder()); } public static final String formatSeconds(final int pSecondsTotal, final StringBuilder pStringBuilder) { final int minutes = pSecondsTotal / SECONDS_PER_MINUTE; final int seconds = pSecondsTotal % SECONDS_PER_MINUTE; pStringBuilder.append(minutes); pStringBuilder.append(':'); if (seconds < 10) { pStringBuilder.append('0'); } pStringBuilder.append(seconds); return pStringBuilder.toString(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
apache-2.0
tianylgithub/coolweather
app/src/main/java/com/coolweather/android/ChooseAreaFragment.java
9492
package com.coolweather.android; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.coolweather.android.db.City; import com.coolweather.android.db.County; import com.coolweather.android.db.Province; import com.coolweather.android.gson.Weather; import com.coolweather.android.util.HttpUtil; import com.coolweather.android.util.Utility; import org.litepal.crud.DataSupport; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; /** * Created by TYL on 2017/5/22. */ public class ChooseAreaFragment extends Fragment { public static final int LEVEL_PROVINCE = 0; public static final int LEVEL_CITY = 1; public static final int LEVEL_COUNTY = 2; private ProgressDialog progressDialog; private TextView titleText; private Button backButton; private ListView listView; private ArrayAdapter<String> adapter; private List<String> dataList = new ArrayList<>(); /** * 省市县列表 */ private List<Province> provinceList; private List<City> cityList; private List<County> countyList; /** * 选中的省市列表 */ private Province selectedProvince; private City selectedCity; /** * 当前选中的级别 */ private int currentLevel; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.choose_area, container, false); titleText=(TextView) view.findViewById(R.id.title_text); backButton = (Button) view.findViewById(R.id.back_button); listView = (ListView) view.findViewById(R.id.list_view); adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList); listView.setAdapter(adapter); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (currentLevel==LEVEL_PROVINCE) { selectedProvince = provinceList.get(position); queryCities(); } else if (currentLevel == LEVEL_CITY) { selectedCity = cityList.get(position); queryCounties(); } else if (currentLevel == LEVEL_COUNTY) { String weatherId = countyList.get(position).getWeatherId(); if(getActivity()instanceof MainActivity){ Intent intent = new Intent(getActivity(), WeatherActivity.class); intent.putExtra("weather_id", weatherId); startActivity(intent); getActivity().finish(); } else if (getActivity()instanceof WeatherActivity) { WeatherActivity activity = (WeatherActivity) getActivity(); activity.drawerLayout.closeDrawers(); activity.swipeRefresh.setRefreshing(true); activity.requestWeather(weatherId); } } } }); backButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if (currentLevel == LEVEL_COUNTY) { queryCities(); } else if (currentLevel==LEVEL_CITY) { queryProvinces(); } } }); queryProvinces(); } /** * 查询全国所有的省,优先从数据库查询,如果没有查询到再去服务器上查询 */ private void queryProvinces() { titleText.setText("中国"); backButton.setVisibility(View.GONE); provinceList = DataSupport.findAll(Province.class); if (provinceList.size() > 0) { dataList.clear(); for (Province province : provinceList) { dataList.add(province.getProvinceName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_PROVINCE; } else { String address = "http://guolin.tech/api/china"; queryFromServer(address, "province"); } } /** * 查询选中省内所有的市,优先从数据库查询,如果没有查询到再去服务器上查询 */ private void queryCities(){ titleText.setText(selectedProvince.getProvinceName()); backButton.setVisibility(View.VISIBLE); cityList = DataSupport.where("provinceid=?", String.valueOf(selectedProvince.getId())).find(City.class); if (cityList.size() > 0) { dataList.clear(); for (City city : cityList) { dataList.add(city.getCityName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_CITY; } else { int provinceCode = selectedProvince.getProvinceCode(); String address = "http://guolin.tech/api/china/"+provinceCode; queryFromServer(address, "city"); } } /** * 查询选中市内所有的县,优先从数据库查询,如果没有查询到再去服务器上查询 */ private void queryCounties() { titleText.setText(selectedCity.getCityName()); backButton.setVisibility(View.VISIBLE); countyList = DataSupport.where("cityid= ?", String.valueOf(selectedCity.getId())).find(County.class); if (countyList.size() > 0) { dataList.clear(); for (County county : countyList) { dataList.add(county.getCountyName()); } adapter.notifyDataSetChanged(); listView.setSelection(0); currentLevel = LEVEL_COUNTY; } else { int provinceCode = selectedProvince.getProvinceCode(); int cityCode = selectedCity.getCityCode(); String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode; queryFromServer(address,"county"); } } /** *根据传入的地址和类型从服务器上查询省市县数据 */ private void queryFromServer(String address, final String type) { showProgressDialog(); HttpUtil.sendOkHttpRequest(address, new Callback() { @Override public void onFailure(Call call, IOException e) { //通过runOnUiThread()方法回到主线程处理逻辑 getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); Toast.makeText(getContext(),"加载失败",Toast.LENGTH_SHORT).show(); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String responseText = response.body().string(); boolean result = false; if ("province".equals(type)) { result = Utility.handleProvinceResponse(responseText); } else if ("city".equals(type)) { result = Utility.handleCityResponse(responseText, selectedProvince.getId()); }else if("county".equals(type)){ result = Utility.handleCountyResponse(responseText, selectedCity.getId()); } if (result) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { closeProgressDialog(); if ("province".equals(type)) { queryProvinces(); } else if ("city".equals(type)) { queryCities(); } else if ("county".equals(type)) { queryCounties(); } } }); } } }); } /** * 显示进度对话框 */ private void showProgressDialog() { if (progressDialog == null) { progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage("正在加载.."); progressDialog.setCanceledOnTouchOutside(false); } progressDialog.show(); } /** * 关闭进度对话框 */ private void closeProgressDialog() { if (progressDialog != null) { progressDialog.dismiss(); } } }
apache-2.0
tudarmstadt-lt/topicrawler
lt.seg/src/main/java/de/tudarmstadt/lt/seg/token/rules/RuleSet.java
5493
/* * Copyright (c) 2016 * * 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.tudarmstadt.lt.seg.token.rules; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.*; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * Created by Steffen Remus. */ public class RuleSet { private final static Map<String, RuleSet> RULE_SETS = new HashMap<String, RuleSet>(); public final static RuleSet DEFAULT_RULESET = new RuleSet(); static{ for(String lang : __getAvailable__()) RULE_SETS.put(lang, null); } private RuleSet(){ _base_tokenizer = BaseTokenizer.DEFAULT; _lookahead_list = LookaheadList.DEFAULT; _lookahead_rules = LookaheadRules.DEFAULT; _name = "default"; RULE_SETS.put(_name, this); } private RuleSet(String name, URL basetokenizer_file_location, URL lookahead_list_file_location, URL lookahead_rules_file_location){ this(name, basetokenizer_file_location, lookahead_list_file_location, lookahead_rules_file_location, Charset.defaultCharset()); } private RuleSet(String name, URL basetokenizer_file_location, URL lookahead_list_file_location, URL lookahead_rules_file_location, Charset cs){ try{ _base_tokenizer = basetokenizer_file_location == null ? null /*BoundaryList.DEFAULT*/ : null /*load tokenizer*/; }catch(Exception e){ throw new IllegalArgumentException(e); } try{ _lookahead_list = lookahead_list_file_location == null ? LookaheadList.DEFAULT : new LookaheadList(lookahead_list_file_location, cs); }catch(Exception e){ throw new IllegalArgumentException(e); } try{ _lookahead_rules = lookahead_rules_file_location == null ? LookaheadRules.DEFAULT : new LookaheadRules(lookahead_rules_file_location, cs); }catch(Exception e){ throw new IllegalArgumentException(e); } _name = name; RULE_SETS.put(_name, this); } private RuleSet(String name, BaseTokenizer base_tokenizer, LookaheadList lookahead_list, LookaheadRules lookahead_rules){ _name = name; _base_tokenizer = base_tokenizer; _lookahead_list = lookahead_list; _lookahead_rules = lookahead_rules; RULE_SETS.put(_name, this); } public final String _name; public final BaseTokenizer _base_tokenizer; public final LookaheadList _lookahead_list; public final LookaheadRules _lookahead_rules; public static RuleSet get(String name){ RuleSet r = RULE_SETS.get(name); if(r != null) return r; if(!getAvailable().contains(name)) return DEFAULT_RULESET; String basedir = "rulesets/token/" + name + "/"; r = newRuleSet( name, Thread.currentThread().getContextClassLoader().getResource(basedir + "tokenizer.txt"), Thread.currentThread().getContextClassLoader().getResource(basedir + "lookahead-list.txt"), Thread.currentThread().getContextClassLoader().getResource(basedir + "lookahead-rules.txt")); return r; } public static Set<String> getAvailable(){ return RULE_SETS.keySet(); } private static Set<String> __getAvailable__(){ Set<String> r = Collections.emptySet(); try { URI uri = Thread.currentThread().getContextClassLoader().getResource("rulesets/token").toURI(); Path myPath; FileSystem jarFileSystem = null; if (uri.getScheme().equals("jar")){ jarFileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap()); myPath = jarFileSystem.getPath("/rulesets/token"); } else { myPath = Paths.get(uri); } r = Files.walk(myPath, 1).map(x -> x.getFileName().toString().replace("/", "")).filter(s -> !(s.equals("token"))).collect(Collectors.toSet()); if(jarFileSystem != null) jarFileSystem.close(); } catch (URISyntaxException | IOException e) { e.printStackTrace(); } return r; } public static RuleSet newRuleSet(String name, URL base_tokenizer_file_location, URL lookahead_list_file_location, URL lookahead_rules_file_location){ return newRuleSet(name, base_tokenizer_file_location, lookahead_list_file_location, lookahead_rules_file_location, Charset.defaultCharset()); } public static RuleSet newRuleSet(String name, URL base_tokenizer_file_location, URL lookahead_list_file_location, URL lookahead_rules_file_location, Charset cs){ RuleSet r = RULE_SETS.get(name); if(r != null) return r; r = new RuleSet(name, base_tokenizer_file_location, lookahead_list_file_location, lookahead_rules_file_location, cs); return r; } }
apache-2.0
nspilka/robotFrameworkDebugger
src/test/java/com/bandofyetis/robotframeworkdebugger/RobotFrameworkDebuggerTest.java
22840
package com.bandofyetis.robotframeworkdebugger; import static org.junit.Assert.*; import java.io.IOException; import java.io.StringWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.Vector; import org.apache.log4j.Appender; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.WriterAppender; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.bandofyetis.robotframeworkdebugger.RobotFrameworkDebugContext; import com.bandofyetis.robotframeworkdebugger.RobotFrameworkDebugger; import com.bandofyetis.robotframeworkdebugger.RobotFrameworkDebugContext.ContextType; import com.bandofyetis.robotframeworkdebugger.RobotFrameworkDebugger.StepMode; public class RobotFrameworkDebuggerTest { private static final int [] unsortedArray = {7,5,2,14,3,6}; private static final int [] sortedArray = {2,3,5,6,7,14}; private static Vector<Appender> appenders; private static StringWriter writer; private RobotFrameworkDebugger debugger; private boolean additivity; @BeforeClass public static void setUpOnce() { appenders = new Vector<Appender>(2); // 1. just a printout appender: appenders.add(new ConsoleAppender(new PatternLayout("%d [%t] %-5p %c - %m%n"))); // 2. the appender to test against: writer = new StringWriter(); appenders.add(new WriterAppender(new PatternLayout("%p, %m%n"),writer)); } @Before public void setUp() throws InterruptedException, IOException { // Unit Under Test: debugger = new RobotFrameworkDebugger(false); // setting test appenders: for (Appender appender : appenders) { RobotFrameworkDebugger.log.addAppender(appender); } // saving additivity and turning it off: additivity = RobotFrameworkDebugger.log.getAdditivity(); RobotFrameworkDebugger.log.setAdditivity(false); } @After public void tearDown() { debugger = null; for (Appender appender : appenders) { RobotFrameworkDebugger.log.removeAppender(appender); } RobotFrameworkDebugger.log.setAdditivity(additivity); } @Test public void testStartSuite() throws InterruptedException, IOException { debugger.getContextStack().clear(); RobotFrameworkDebugContext rootContext = new RobotFrameworkDebugContext(); rootContext.setContextType(ContextType.TEST_SUITE); rootContext.setItemName("testSuite"); debugger.getContextStack().push(rootContext); debugger.startSuite("mySuite", null); Stack<RobotFrameworkDebugContext> ctxtStack = debugger.getContextStack(); assertEquals(2,ctxtStack.size()); RobotFrameworkDebugContext kdc = ctxtStack.pop(); assertTrue(kdc.getContextType() == ContextType.TEST_CASE); kdc = ctxtStack.pop(); assertTrue(kdc.getContextType() == ContextType.TEST_SUITE); assertEquals("mySuite", kdc.getItemName()); } @Test public void testStartSuiteNotValid() throws InterruptedException, IOException { // zero the log trap writer.getBuffer().setLength(0); RobotFrameworkDebugContext rootContext = new RobotFrameworkDebugContext(); rootContext.setContextType(ContextType.TEST_CASE); debugger.getContextStack().push(rootContext); debugger.startSuite("suite2",null); assertTrue(writer.toString(), writer.toString().contains(RobotFrameworkDebugger.LOG_EXPECTED_TEST_SUITE_OBJECT)); writer.getBuffer().setLength(0); } @Test public void testStartTest() throws InterruptedException, IOException { RobotFrameworkDebugContext rootContext = new RobotFrameworkDebugContext(); rootContext.setContextType(ContextType.TEST_CASE); rootContext.setItemName("test1"); rootContext.getVariables().put("var1", "val1"); assertTrue(rootContext.getVariables().size() > 0); debugger.getContextStack().push(rootContext); debugger.startTest("test2",null); RobotFrameworkDebugContext kwContext = debugger.getContextStack().pop(); RobotFrameworkDebugContext tcContext = debugger.getContextStack().pop(); assertEquals(ContextType.KEYWORD, kwContext.getContextType()); assertEquals(0, tcContext.getVariables().size()); assertNull(tcContext.getItemAttribs()); assertEquals("test2", tcContext.getItemName()); } @Test public void testStartTestNotValid() throws InterruptedException, IOException { // zero the log trap writer.getBuffer().setLength(0); RobotFrameworkDebugContext rootContext = new RobotFrameworkDebugContext(); rootContext.setContextType(ContextType.KEYWORD); debugger.getContextStack().push(rootContext); debugger.startTest("test2",null); assertTrue(writer.toString(), writer.toString().contains(RobotFrameworkDebugger.LOG_EXPECTED_TEST_CASE_OBJECT)); writer.getBuffer().setLength(0); } @Test public void testEndTestNoStopAtTestEnd() throws InterruptedException, IOException { debugger.stopAtTestEnd = false; debugger.getContextStack().clear(); Map<String,Object> attrs = new HashMap<String, Object>(); attrs.put("status", "PASS"); RobotFrameworkDebugContext rootContext = new RobotFrameworkDebugContext(); rootContext.setContextType(ContextType.TEST_CASE); rootContext.setItemName("test1"); debugger.getContextStack().push(rootContext); RobotFrameworkDebugContext kwContext = new RobotFrameworkDebugContext(); kwContext.setContextType(ContextType.KEYWORD); kwContext.setItemName("kw1"); debugger.getContextStack().push(kwContext); debugger.endTest("test1", attrs); assertEquals(-1, debugger.getCurrentBreakpointIndex()); assertEquals(1,debugger.getContextStack().size()); assertEquals("test1", debugger.getContextStack().peek().getItemName()); assertEquals(ContextType.TEST_CASE, debugger.getContextStack().peek().getContextType()); } @Test public void testEndTestNoStopAtTestEndNotValid() throws InterruptedException, IOException { debugger.stopAtTestEnd = false; debugger.getContextStack().clear(); Map<String,Object> attrs = new HashMap<String, Object>(); attrs.put("status", "PASS"); RobotFrameworkDebugContext rootContext = new RobotFrameworkDebugContext(); rootContext.setContextType(ContextType.TEST_CASE); rootContext.setItemName("test1"); debugger.getContextStack().push(rootContext); RobotFrameworkDebugContext kwContext = new RobotFrameworkDebugContext(); kwContext.setContextType(ContextType.TEST_CASE); kwContext.setItemName("kw1"); debugger.getContextStack().push(kwContext); debugger.endTest("test1", attrs); assertTrue(writer.toString(), writer.toString().contains(RobotFrameworkDebugger.LOG_EXPECTED_KEYWORD_OBJECT)); } @Test public void testEndTestStopAtTestEnd() throws InterruptedException, IOException { debugger.getContextStack().clear(); debugger.stopAtTestEnd = true; Map<String,Object> attrs = new HashMap<String, Object>(); attrs.put("status", "PASS"); RobotFrameworkDebugContext rootContext = new RobotFrameworkDebugContext(); rootContext.setContextType(ContextType.TEST_CASE); rootContext.setItemName("test2"); debugger.getContextStack().push(rootContext); RobotFrameworkDebugContext kwContext = new RobotFrameworkDebugContext(); kwContext.setContextType(ContextType.KEYWORD); kwContext.setItemName("kw1"); debugger.getContextStack().push(kwContext); debugger.endTest("test2", attrs); assertEquals(-1, debugger.getCurrentBreakpointIndex()); assertEquals(1,debugger.getContextStack().size()); assertEquals("test2", debugger.getContextStack().peek().getItemName()); assertEquals(ContextType.TEST_CASE, debugger.getContextStack().peek().getContextType()); assertEquals(StepMode.STEP_INTO, debugger.getStepMode()); assertNull(debugger.getStepTarget()); } @Test public void testEndSuite() throws InterruptedException, IOException { debugger.getContextStack().clear(); RobotFrameworkDebugContext rootContext = new RobotFrameworkDebugContext(); rootContext.setContextType(ContextType.TEST_SUITE); rootContext.setItemName("testSuite"); debugger.getContextStack().push(rootContext); RobotFrameworkDebugContext childContext = new RobotFrameworkDebugContext(); childContext.setContextType(ContextType.TEST_CASE); childContext.setItemName("testCase"); debugger.getContextStack().push(childContext); assertEquals(2,debugger.getContextStack().size()); debugger.endSuite("testSuite", null); assertEquals(1, debugger.getContextStack().size()); } @Test public void testEndSuiteNotValid() throws InterruptedException, IOException { debugger.getContextStack().clear(); RobotFrameworkDebugContext rootContext = new RobotFrameworkDebugContext(); rootContext.setContextType(ContextType.TEST_SUITE); rootContext.setItemName("testSuite"); debugger.getContextStack().push(rootContext); RobotFrameworkDebugContext childContext = new RobotFrameworkDebugContext(); childContext.setContextType(ContextType.KEYWORD); childContext.setItemName("testCase"); debugger.getContextStack().push(childContext); assertEquals(2,debugger.getContextStack().size()); debugger.endSuite("testSuite", null); assertTrue(writer.toString(), writer.toString().contains(RobotFrameworkDebugger.LOG_EXPECTED_TEST_CASE_OBJECT)); } @Test public void testStartKeyword() throws InterruptedException, IOException { debugger.getContextStack().clear(); RobotFrameworkDebugContext rootContext = new RobotFrameworkDebugContext(); rootContext.setContextType(ContextType.KEYWORD); rootContext.setItemName("rootKW1"); debugger.getContextStack().push(rootContext); assertEquals(1,debugger.getContextStack().size()); assertEquals(0, rootContext.getLineNumber()); debugger.startKeyword("rootKW2", null); assertEquals(2, debugger.getContextStack().size()); assertEquals(-1, debugger.getCurrentBreakpointIndex()); RobotFrameworkDebugContext childKW = debugger.getContextStack().pop(); RobotFrameworkDebugContext rootKW = debugger.getContextStack().pop(); assertEquals(ContextType.KEYWORD, childKW.getContextType()); assertEquals(ContextType.KEYWORD, rootKW.getContextType()); assertNull(rootKW.getItemAttribs()); assertEquals("rootKW2", rootKW.getItemName()); assertEquals(1, rootKW.getLineNumber()); } @Test public void testStartKeywordNotValid() throws InterruptedException, IOException { debugger.getContextStack().clear(); RobotFrameworkDebugContext rootContext = new RobotFrameworkDebugContext(); rootContext.setContextType(ContextType.TEST_CASE); rootContext.setItemName("rootKW1"); debugger.getContextStack().push(rootContext); assertEquals(1,debugger.getContextStack().size()); assertEquals(0, rootContext.getLineNumber()); debugger.startKeyword("rootKW2", null); assertTrue(writer.toString(), writer.toString().contains(RobotFrameworkDebugger.LOG_EXPECTED_KEYWORD_OBJECT)); } @Test public void testEndKeywordNoStepOver() throws InterruptedException, IOException { debugger.stopAtTestEnd = false; debugger.getContextStack().clear(); RobotFrameworkDebugContext rootContext = new RobotFrameworkDebugContext(); rootContext.setContextType(ContextType.KEYWORD); rootContext.setItemName("rootKeyword"); debugger.getContextStack().push(rootContext); RobotFrameworkDebugContext kwContext = new RobotFrameworkDebugContext(); kwContext.setContextType(ContextType.KEYWORD); kwContext.setItemName("kw1"); debugger.getContextStack().push(kwContext); debugger.endKeyword("rootKeyword", null); assertEquals(1, debugger.getContextStack().size()); assertEquals("rootKeyword", debugger.getContextStack().peek().getItemName()); } @Test public void testEndKeywordNoStepOverNotValid() throws InterruptedException, IOException { debugger.stopAtTestEnd = false; debugger.getContextStack().clear(); RobotFrameworkDebugContext rootContext = new RobotFrameworkDebugContext(); rootContext.setContextType(ContextType.KEYWORD); rootContext.setItemName("rootKeyword"); debugger.getContextStack().push(rootContext); RobotFrameworkDebugContext kwContext = new RobotFrameworkDebugContext(); kwContext.setContextType(ContextType.TEST_CASE); kwContext.setItemName("kw1"); debugger.getContextStack().push(kwContext); debugger.endKeyword("rootKeyword", null); assertTrue(writer.toString(), writer.toString().contains(RobotFrameworkDebugger.LOG_EXPECTED_KEYWORD_OBJECT)); } @Test public void testEndKeywordStepOver() throws InterruptedException, IOException { debugger.stopAtTestEnd = false; debugger.getContextStack().clear(); RobotFrameworkDebugContext rootContext = new RobotFrameworkDebugContext(); rootContext.setContextType(ContextType.KEYWORD); rootContext.setItemName("rootKeyword"); debugger.getContextStack().push(rootContext); debugger.setStepOver(); assertEquals("rootKeyword",debugger.getStepTarget()); RobotFrameworkDebugContext kwContext = new RobotFrameworkDebugContext(); kwContext.setContextType(ContextType.KEYWORD); kwContext.setItemName("kw1"); debugger.getContextStack().push(kwContext); debugger.endKeyword("rootKeyword", null); assertEquals(1, debugger.getContextStack().size()); assertEquals("rootKeyword", debugger.getContextStack().peek().getItemName()); assertEquals(StepMode.STEP_INTO, debugger.getStepMode()); assertNull(debugger.getStepTarget()); } @Test public void testLogMessage() throws InterruptedException, IOException { RobotFrameworkDebugContext rootContext = new RobotFrameworkDebugContext(); rootContext.setContextType(ContextType.KEYWORD); rootContext.setItemName("rootKW"); debugger.getContextStack().push(rootContext); RobotFrameworkDebugContext childContext = new RobotFrameworkDebugContext(); childContext.setContextType(ContextType.KEYWORD); childContext.setItemName("testKW"); debugger.getContextStack().push(childContext); // Not a variable, so should leave nothing in variable list Map<String,Object> msg = new HashMap<String,Object>(); msg.put("message","Not a var"); debugger.logMessage(msg); assertEquals(0, debugger.getContextStack().peek().getVariables().size()); // a list variable, so should be in variable list msg = new HashMap<String,Object>(); msg.put("message","@{test1}=[1,2,3]"); debugger.logMessage(msg); // pop off the child context debugger.getContextStack().pop(); Map<String,String> vars = debugger.getContextStack().peek().getVariables(); assertEquals(1,vars.size()); assertTrue(vars.containsKey("@{test1}")); assertEquals("[1,2,3]", vars.get("@{test1}")); // push child context back debugger.getContextStack().push(childContext); // a scalar variable, so should be in variable list msg = new HashMap<String,Object>(); msg.put("message","${test2}=value2"); debugger.logMessage(msg); // pop off the child context debugger.getContextStack().pop(); vars = debugger.getContextStack().peek().getVariables(); assertEquals(2,vars.size()); assertTrue(vars.containsKey("@{test1}")); assertEquals("[1,2,3]", vars.get("@{test1}")); assertTrue(vars.containsKey("${test2}")); assertEquals("value2", vars.get("${test2}")); } @Test public void testSetStepOver() throws InterruptedException, IOException { // With empty stack should give us STEP_INTO debugger.setStepOver(); assertEquals(RobotFrameworkDebugger.StepMode.STEP_INTO, debugger.getStepMode()); assertNull(debugger.getStepTarget()); // With stack with unnamed keyword, should give us STEP_INTO RobotFrameworkDebugContext childContext = new RobotFrameworkDebugContext(); childContext.setContextType(ContextType.KEYWORD); debugger.getContextStack().push(childContext); debugger.setStepOver(); assertEquals(RobotFrameworkDebugger.StepMode.STEP_INTO, debugger.getStepMode()); assertNull(debugger.getStepTarget()); // With non-keyword on stack should give us STEP_INTO debugger.getContextStack().clear(); RobotFrameworkDebugContext childContext2 = new RobotFrameworkDebugContext(); childContext2.setContextType(ContextType.TEST_CASE); debugger.getContextStack().push(childContext2); debugger.setStepOver(); assertEquals(RobotFrameworkDebugger.StepMode.STEP_INTO, debugger.getStepMode()); assertNull(debugger.getStepTarget()); // with keyord on stack with name, should give us STEP_OVER debugger.getContextStack().clear(); RobotFrameworkDebugContext childContext3 = new RobotFrameworkDebugContext(); childContext3.setContextType(ContextType.KEYWORD); childContext3.setItemName("testKW"); debugger.getContextStack().push(childContext3); debugger.setStepOver(); assertEquals(RobotFrameworkDebugger.StepMode.STEP_OVER, debugger.getStepMode()); assertEquals("testKW",debugger.getStepTarget()); } @Test public void testSetStepInto() throws InterruptedException, IOException { debugger.setStepInto(); assertEquals(RobotFrameworkDebugger.StepMode.STEP_INTO, debugger.getStepMode()); assertNull(debugger.getStepTarget()); } @Test public void testSetRunToBreakpoint() throws InterruptedException, IOException { debugger.setRunToBreakpoint(); assertEquals(RobotFrameworkDebugger.StepMode.RUN_TO_BREAKPOINT, debugger.getStepMode()); assertNull(debugger.getStepTarget()); } @Test public void testGetBreakpoints() throws InterruptedException, IOException { List<String> breakpoints = debugger.getBreakpoints(); assertEquals (0, breakpoints.size()); debugger.addBreakpoint("aa"); debugger.addBreakpoint("bp1"); debugger.addBreakpoint("cp1"); List<String> breakpoints2 = debugger.getBreakpoints(); assertEquals (3, breakpoints2.size()); assertTrue(breakpoints2.contains("aa")); assertTrue(breakpoints2.contains("bp1")); assertTrue(breakpoints2.contains("cp1")); assertFalse(breakpoints2.contains("dp1")); } @Test public void testGetCurrentBreakpointAsString() throws InterruptedException, IOException { assertNull (debugger.getCurrentBreakpointAsString()); debugger.addBreakpoint("aa"); debugger.addBreakpoint("bp1"); debugger.addBreakpoint("cp1"); debugger.setCurrentBreakpointIndex(1); assertEquals("bp1", debugger.getCurrentBreakpointAsString()); debugger.setCurrentBreakpointIndex(-1); assertNull (debugger.getCurrentBreakpointAsString()); } @Test(expected=IndexOutOfBoundsException.class) public void testSetAndGetCurrentBreakpointIndexWithOOBException() throws InterruptedException, IOException, IndexOutOfBoundsException { assertEquals(-1,debugger.getCurrentBreakpointIndex()); debugger.setCurrentBreakpointIndex(-4); } @Test(expected=IndexOutOfBoundsException.class) public void testSetAndGetCurrentBreakpointIndexWithOOBException2() throws InterruptedException, IOException, IndexOutOfBoundsException { assertEquals(-1,debugger.getCurrentBreakpointIndex()); debugger.setCurrentBreakpointIndex(13); assertEquals(-1,debugger.getCurrentBreakpointIndex()); } @Test(expected=IndexOutOfBoundsException.class) public void testSetAndGetCurrentBreakpointIndexWithOOBException3() throws InterruptedException, IOException, IndexOutOfBoundsException { assertEquals(-1,debugger.getCurrentBreakpointIndex()); debugger.addBreakpoint("aa"); debugger.addBreakpoint("bp1"); debugger.addBreakpoint("cp1"); debugger.setCurrentBreakpointIndex(4); assertEquals(-1, debugger.getCurrentBreakpointIndex()); } @Test public void testSetAndGetCurrentBreakpointIndex() throws InterruptedException, IOException, IndexOutOfBoundsException { assertEquals(-1,debugger.getCurrentBreakpointIndex()); debugger.addBreakpoint("aa"); debugger.addBreakpoint("bp1"); debugger.addBreakpoint("cp1"); debugger.setCurrentBreakpointIndex(1); assertEquals(1, debugger.getCurrentBreakpointIndex()); debugger.setCurrentBreakpointIndex(2); assertEquals(2, debugger.getCurrentBreakpointIndex()); } @Test public void testAddAndFindBreakpoint() throws InterruptedException, IOException { debugger.addBreakpoint("bp1"); debugger.addBreakpoint("cp1"); assert(debugger.findBreakpoint("bp1") >= 0); assert(debugger.findBreakpoint("cp1") > debugger.findBreakpoint("bp1")); assert(debugger.findBreakpoint("aaa") == -1); } @Test(expected=IllegalArgumentException.class) public void testRemoveBreakpointWithDuplicateIndices() throws InterruptedException, IOException, IndexOutOfBoundsException { assertEquals(-1,debugger.getCurrentBreakpointIndex()); debugger.addBreakpoint("aa"); debugger.addBreakpoint("bp1"); debugger.addBreakpoint("cp1"); int[] indices = {1,0,1,2}; debugger.removeBreakpoints(indices); } @Test public void testRemoveAndFindBreakpoints() throws InterruptedException, IOException { debugger.addBreakpoint("aa"); debugger.addBreakpoint("bp1"); debugger.addBreakpoint("cp1"); assertEquals(0, debugger.findBreakpoint("aa")); int [] indices = {0}; debugger.removeBreakpoints(indices); assertEquals(-1, debugger.findBreakpoint("aa")); int [] indices2 = {0,1}; debugger.removeBreakpoints(indices2); assertEquals (0,debugger.getBreakpoints().size()); debugger.addBreakpoint("aa"); debugger.addBreakpoint("bp1"); debugger.addBreakpoint("cp1"); debugger.addBreakpoint("dp1"); debugger.addBreakpoint("ep1"); int [] indices3 = {1,3}; debugger.removeBreakpoints(indices3); assertEquals(-1,debugger.findBreakpoint("bp1")); assertEquals(-1,debugger.findBreakpoint("dp1")); assertEquals(0,debugger.findBreakpoint("aa")); assertEquals(1,debugger.findBreakpoint("cp1")); assertEquals(2,debugger.findBreakpoint("ep1")); } @Test public void testSort() throws InterruptedException, IOException { int[] testArray = new int[unsortedArray.length]; System.arraycopy (unsortedArray, 0, testArray, 0, unsortedArray.length); debugger.sort(testArray); for (int i=0; i<testArray.length; i++){ assertEquals(sortedArray[i], testArray[i]); } } }
apache-2.0
google/schemaorg-java
src/main/java/com/google/schemaorg/core/impl/BeachImpl.java
19506
/* * Copyright 2016 Google Inc. 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.schemaorg.core; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import com.google.schemaorg.SchemaOrgTypeImpl; import com.google.schemaorg.ValueType; import com.google.schemaorg.core.datatype.Text; import com.google.schemaorg.core.datatype.URL; import com.google.schemaorg.goog.GoogConstants; import com.google.schemaorg.goog.PopularityScoreSpecification; /** Implementation of {@link Beach}. */ public class BeachImpl extends CivicStructureImpl implements Beach { private static final ImmutableSet<String> PROPERTY_SET = initializePropertySet(); private static ImmutableSet<String> initializePropertySet() { ImmutableSet.Builder<String> builder = ImmutableSet.builder(); builder.add(CoreConstants.PROPERTY_ADDITIONAL_PROPERTY); builder.add(CoreConstants.PROPERTY_ADDITIONAL_TYPE); builder.add(CoreConstants.PROPERTY_ADDRESS); builder.add(CoreConstants.PROPERTY_AGGREGATE_RATING); builder.add(CoreConstants.PROPERTY_ALTERNATE_NAME); builder.add(CoreConstants.PROPERTY_BRANCH_CODE); builder.add(CoreConstants.PROPERTY_CONTAINED_IN); builder.add(CoreConstants.PROPERTY_CONTAINED_IN_PLACE); builder.add(CoreConstants.PROPERTY_CONTAINS_PLACE); builder.add(CoreConstants.PROPERTY_DESCRIPTION); builder.add(CoreConstants.PROPERTY_EVENT); builder.add(CoreConstants.PROPERTY_EVENTS); builder.add(CoreConstants.PROPERTY_FAX_NUMBER); builder.add(CoreConstants.PROPERTY_GEO); builder.add(CoreConstants.PROPERTY_GLOBAL_LOCATION_NUMBER); builder.add(CoreConstants.PROPERTY_HAS_MAP); builder.add(CoreConstants.PROPERTY_IMAGE); builder.add(CoreConstants.PROPERTY_ISIC_V4); builder.add(CoreConstants.PROPERTY_LOGO); builder.add(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE); builder.add(CoreConstants.PROPERTY_MAP); builder.add(CoreConstants.PROPERTY_MAPS); builder.add(CoreConstants.PROPERTY_NAME); builder.add(CoreConstants.PROPERTY_OPENING_HOURS); builder.add(CoreConstants.PROPERTY_OPENING_HOURS_SPECIFICATION); builder.add(CoreConstants.PROPERTY_PHOTO); builder.add(CoreConstants.PROPERTY_PHOTOS); builder.add(CoreConstants.PROPERTY_POTENTIAL_ACTION); builder.add(CoreConstants.PROPERTY_REVIEW); builder.add(CoreConstants.PROPERTY_REVIEWS); builder.add(CoreConstants.PROPERTY_SAME_AS); builder.add(CoreConstants.PROPERTY_TELEPHONE); builder.add(CoreConstants.PROPERTY_URL); builder.add(GoogConstants.PROPERTY_DETAILED_DESCRIPTION); builder.add(GoogConstants.PROPERTY_POPULARITY_SCORE); return builder.build(); } static final class BuilderImpl extends SchemaOrgTypeImpl.BuilderImpl<Beach.Builder> implements Beach.Builder { @Override public Beach.Builder addAdditionalProperty(PropertyValue value) { return addProperty(CoreConstants.PROPERTY_ADDITIONAL_PROPERTY, value); } @Override public Beach.Builder addAdditionalProperty(PropertyValue.Builder value) { return addProperty(CoreConstants.PROPERTY_ADDITIONAL_PROPERTY, value.build()); } @Override public Beach.Builder addAdditionalProperty(String value) { return addProperty(CoreConstants.PROPERTY_ADDITIONAL_PROPERTY, Text.of(value)); } @Override public Beach.Builder addAdditionalType(URL value) { return addProperty(CoreConstants.PROPERTY_ADDITIONAL_TYPE, value); } @Override public Beach.Builder addAdditionalType(String value) { return addProperty(CoreConstants.PROPERTY_ADDITIONAL_TYPE, Text.of(value)); } @Override public Beach.Builder addAddress(PostalAddress value) { return addProperty(CoreConstants.PROPERTY_ADDRESS, value); } @Override public Beach.Builder addAddress(PostalAddress.Builder value) { return addProperty(CoreConstants.PROPERTY_ADDRESS, value.build()); } @Override public Beach.Builder addAddress(Text value) { return addProperty(CoreConstants.PROPERTY_ADDRESS, value); } @Override public Beach.Builder addAddress(String value) { return addProperty(CoreConstants.PROPERTY_ADDRESS, Text.of(value)); } @Override public Beach.Builder addAggregateRating(AggregateRating value) { return addProperty(CoreConstants.PROPERTY_AGGREGATE_RATING, value); } @Override public Beach.Builder addAggregateRating(AggregateRating.Builder value) { return addProperty(CoreConstants.PROPERTY_AGGREGATE_RATING, value.build()); } @Override public Beach.Builder addAggregateRating(String value) { return addProperty(CoreConstants.PROPERTY_AGGREGATE_RATING, Text.of(value)); } @Override public Beach.Builder addAlternateName(Text value) { return addProperty(CoreConstants.PROPERTY_ALTERNATE_NAME, value); } @Override public Beach.Builder addAlternateName(String value) { return addProperty(CoreConstants.PROPERTY_ALTERNATE_NAME, Text.of(value)); } @Override public Beach.Builder addBranchCode(Text value) { return addProperty(CoreConstants.PROPERTY_BRANCH_CODE, value); } @Override public Beach.Builder addBranchCode(String value) { return addProperty(CoreConstants.PROPERTY_BRANCH_CODE, Text.of(value)); } @Override public Beach.Builder addContainedIn(Place value) { return addProperty(CoreConstants.PROPERTY_CONTAINED_IN, value); } @Override public Beach.Builder addContainedIn(Place.Builder value) { return addProperty(CoreConstants.PROPERTY_CONTAINED_IN, value.build()); } @Override public Beach.Builder addContainedIn(String value) { return addProperty(CoreConstants.PROPERTY_CONTAINED_IN, Text.of(value)); } @Override public Beach.Builder addContainedInPlace(Place value) { return addProperty(CoreConstants.PROPERTY_CONTAINED_IN_PLACE, value); } @Override public Beach.Builder addContainedInPlace(Place.Builder value) { return addProperty(CoreConstants.PROPERTY_CONTAINED_IN_PLACE, value.build()); } @Override public Beach.Builder addContainedInPlace(String value) { return addProperty(CoreConstants.PROPERTY_CONTAINED_IN_PLACE, Text.of(value)); } @Override public Beach.Builder addContainsPlace(Place value) { return addProperty(CoreConstants.PROPERTY_CONTAINS_PLACE, value); } @Override public Beach.Builder addContainsPlace(Place.Builder value) { return addProperty(CoreConstants.PROPERTY_CONTAINS_PLACE, value.build()); } @Override public Beach.Builder addContainsPlace(String value) { return addProperty(CoreConstants.PROPERTY_CONTAINS_PLACE, Text.of(value)); } @Override public Beach.Builder addDescription(Text value) { return addProperty(CoreConstants.PROPERTY_DESCRIPTION, value); } @Override public Beach.Builder addDescription(String value) { return addProperty(CoreConstants.PROPERTY_DESCRIPTION, Text.of(value)); } @Override public Beach.Builder addEvent(Event value) { return addProperty(CoreConstants.PROPERTY_EVENT, value); } @Override public Beach.Builder addEvent(Event.Builder value) { return addProperty(CoreConstants.PROPERTY_EVENT, value.build()); } @Override public Beach.Builder addEvent(String value) { return addProperty(CoreConstants.PROPERTY_EVENT, Text.of(value)); } @Override public Beach.Builder addEvents(Event value) { return addProperty(CoreConstants.PROPERTY_EVENTS, value); } @Override public Beach.Builder addEvents(Event.Builder value) { return addProperty(CoreConstants.PROPERTY_EVENTS, value.build()); } @Override public Beach.Builder addEvents(String value) { return addProperty(CoreConstants.PROPERTY_EVENTS, Text.of(value)); } @Override public Beach.Builder addFaxNumber(Text value) { return addProperty(CoreConstants.PROPERTY_FAX_NUMBER, value); } @Override public Beach.Builder addFaxNumber(String value) { return addProperty(CoreConstants.PROPERTY_FAX_NUMBER, Text.of(value)); } @Override public Beach.Builder addGeo(GeoCoordinates value) { return addProperty(CoreConstants.PROPERTY_GEO, value); } @Override public Beach.Builder addGeo(GeoCoordinates.Builder value) { return addProperty(CoreConstants.PROPERTY_GEO, value.build()); } @Override public Beach.Builder addGeo(GeoShape value) { return addProperty(CoreConstants.PROPERTY_GEO, value); } @Override public Beach.Builder addGeo(GeoShape.Builder value) { return addProperty(CoreConstants.PROPERTY_GEO, value.build()); } @Override public Beach.Builder addGeo(String value) { return addProperty(CoreConstants.PROPERTY_GEO, Text.of(value)); } @Override public Beach.Builder addGlobalLocationNumber(Text value) { return addProperty(CoreConstants.PROPERTY_GLOBAL_LOCATION_NUMBER, value); } @Override public Beach.Builder addGlobalLocationNumber(String value) { return addProperty(CoreConstants.PROPERTY_GLOBAL_LOCATION_NUMBER, Text.of(value)); } @Override public Beach.Builder addHasMap(Map value) { return addProperty(CoreConstants.PROPERTY_HAS_MAP, value); } @Override public Beach.Builder addHasMap(Map.Builder value) { return addProperty(CoreConstants.PROPERTY_HAS_MAP, value.build()); } @Override public Beach.Builder addHasMap(URL value) { return addProperty(CoreConstants.PROPERTY_HAS_MAP, value); } @Override public Beach.Builder addHasMap(String value) { return addProperty(CoreConstants.PROPERTY_HAS_MAP, Text.of(value)); } @Override public Beach.Builder addImage(ImageObject value) { return addProperty(CoreConstants.PROPERTY_IMAGE, value); } @Override public Beach.Builder addImage(ImageObject.Builder value) { return addProperty(CoreConstants.PROPERTY_IMAGE, value.build()); } @Override public Beach.Builder addImage(URL value) { return addProperty(CoreConstants.PROPERTY_IMAGE, value); } @Override public Beach.Builder addImage(String value) { return addProperty(CoreConstants.PROPERTY_IMAGE, Text.of(value)); } @Override public Beach.Builder addIsicV4(Text value) { return addProperty(CoreConstants.PROPERTY_ISIC_V4, value); } @Override public Beach.Builder addIsicV4(String value) { return addProperty(CoreConstants.PROPERTY_ISIC_V4, Text.of(value)); } @Override public Beach.Builder addLogo(ImageObject value) { return addProperty(CoreConstants.PROPERTY_LOGO, value); } @Override public Beach.Builder addLogo(ImageObject.Builder value) { return addProperty(CoreConstants.PROPERTY_LOGO, value.build()); } @Override public Beach.Builder addLogo(URL value) { return addProperty(CoreConstants.PROPERTY_LOGO, value); } @Override public Beach.Builder addLogo(String value) { return addProperty(CoreConstants.PROPERTY_LOGO, Text.of(value)); } @Override public Beach.Builder addMainEntityOfPage(CreativeWork value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value); } @Override public Beach.Builder addMainEntityOfPage(CreativeWork.Builder value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value.build()); } @Override public Beach.Builder addMainEntityOfPage(URL value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value); } @Override public Beach.Builder addMainEntityOfPage(String value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, Text.of(value)); } @Override public Beach.Builder addMap(URL value) { return addProperty(CoreConstants.PROPERTY_MAP, value); } @Override public Beach.Builder addMap(String value) { return addProperty(CoreConstants.PROPERTY_MAP, Text.of(value)); } @Override public Beach.Builder addMaps(URL value) { return addProperty(CoreConstants.PROPERTY_MAPS, value); } @Override public Beach.Builder addMaps(String value) { return addProperty(CoreConstants.PROPERTY_MAPS, Text.of(value)); } @Override public Beach.Builder addName(Text value) { return addProperty(CoreConstants.PROPERTY_NAME, value); } @Override public Beach.Builder addName(String value) { return addProperty(CoreConstants.PROPERTY_NAME, Text.of(value)); } @Override public Beach.Builder addOpeningHours(Text value) { return addProperty(CoreConstants.PROPERTY_OPENING_HOURS, value); } @Override public Beach.Builder addOpeningHours(String value) { return addProperty(CoreConstants.PROPERTY_OPENING_HOURS, Text.of(value)); } @Override public Beach.Builder addOpeningHoursSpecification(OpeningHoursSpecification value) { return addProperty(CoreConstants.PROPERTY_OPENING_HOURS_SPECIFICATION, value); } @Override public Beach.Builder addOpeningHoursSpecification(OpeningHoursSpecification.Builder value) { return addProperty(CoreConstants.PROPERTY_OPENING_HOURS_SPECIFICATION, value.build()); } @Override public Beach.Builder addOpeningHoursSpecification(String value) { return addProperty(CoreConstants.PROPERTY_OPENING_HOURS_SPECIFICATION, Text.of(value)); } @Override public Beach.Builder addPhoto(ImageObject value) { return addProperty(CoreConstants.PROPERTY_PHOTO, value); } @Override public Beach.Builder addPhoto(ImageObject.Builder value) { return addProperty(CoreConstants.PROPERTY_PHOTO, value.build()); } @Override public Beach.Builder addPhoto(Photograph value) { return addProperty(CoreConstants.PROPERTY_PHOTO, value); } @Override public Beach.Builder addPhoto(Photograph.Builder value) { return addProperty(CoreConstants.PROPERTY_PHOTO, value.build()); } @Override public Beach.Builder addPhoto(String value) { return addProperty(CoreConstants.PROPERTY_PHOTO, Text.of(value)); } @Override public Beach.Builder addPhotos(ImageObject value) { return addProperty(CoreConstants.PROPERTY_PHOTOS, value); } @Override public Beach.Builder addPhotos(ImageObject.Builder value) { return addProperty(CoreConstants.PROPERTY_PHOTOS, value.build()); } @Override public Beach.Builder addPhotos(Photograph value) { return addProperty(CoreConstants.PROPERTY_PHOTOS, value); } @Override public Beach.Builder addPhotos(Photograph.Builder value) { return addProperty(CoreConstants.PROPERTY_PHOTOS, value.build()); } @Override public Beach.Builder addPhotos(String value) { return addProperty(CoreConstants.PROPERTY_PHOTOS, Text.of(value)); } @Override public Beach.Builder addPotentialAction(Action value) { return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, value); } @Override public Beach.Builder addPotentialAction(Action.Builder value) { return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, value.build()); } @Override public Beach.Builder addPotentialAction(String value) { return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, Text.of(value)); } @Override public Beach.Builder addReview(Review value) { return addProperty(CoreConstants.PROPERTY_REVIEW, value); } @Override public Beach.Builder addReview(Review.Builder value) { return addProperty(CoreConstants.PROPERTY_REVIEW, value.build()); } @Override public Beach.Builder addReview(String value) { return addProperty(CoreConstants.PROPERTY_REVIEW, Text.of(value)); } @Override public Beach.Builder addReviews(Review value) { return addProperty(CoreConstants.PROPERTY_REVIEWS, value); } @Override public Beach.Builder addReviews(Review.Builder value) { return addProperty(CoreConstants.PROPERTY_REVIEWS, value.build()); } @Override public Beach.Builder addReviews(String value) { return addProperty(CoreConstants.PROPERTY_REVIEWS, Text.of(value)); } @Override public Beach.Builder addSameAs(URL value) { return addProperty(CoreConstants.PROPERTY_SAME_AS, value); } @Override public Beach.Builder addSameAs(String value) { return addProperty(CoreConstants.PROPERTY_SAME_AS, Text.of(value)); } @Override public Beach.Builder addTelephone(Text value) { return addProperty(CoreConstants.PROPERTY_TELEPHONE, value); } @Override public Beach.Builder addTelephone(String value) { return addProperty(CoreConstants.PROPERTY_TELEPHONE, Text.of(value)); } @Override public Beach.Builder addUrl(URL value) { return addProperty(CoreConstants.PROPERTY_URL, value); } @Override public Beach.Builder addUrl(String value) { return addProperty(CoreConstants.PROPERTY_URL, Text.of(value)); } @Override public Beach.Builder addDetailedDescription(Article value) { return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, value); } @Override public Beach.Builder addDetailedDescription(Article.Builder value) { return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, value.build()); } @Override public Beach.Builder addDetailedDescription(String value) { return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, Text.of(value)); } @Override public Beach.Builder addPopularityScore(PopularityScoreSpecification value) { return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, value); } @Override public Beach.Builder addPopularityScore(PopularityScoreSpecification.Builder value) { return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, value.build()); } @Override public Beach.Builder addPopularityScore(String value) { return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, Text.of(value)); } @Override public Beach build() { return new BeachImpl(properties, reverseMap); } } public BeachImpl(Multimap<String, ValueType> properties, Multimap<String, Thing> reverseMap) { super(properties, reverseMap); } @Override public String getFullTypeName() { return CoreConstants.TYPE_BEACH; } @Override public boolean includesProperty(String property) { return PROPERTY_SET.contains(CoreConstants.NAMESPACE + property) || PROPERTY_SET.contains(GoogConstants.NAMESPACE + property) || PROPERTY_SET.contains(property); } }
apache-2.0
luucasAlbuq/doto
SeuDotoRest/src/br/com/restful/exception/ProfissionalSaudeException.java
362
package br.com.restful.exception; import br.com.restful.util.MensagemExcessao; public class ProfissionalSaudeException extends Exception { /** * */ private static final long serialVersionUID = 1L; public ProfissionalSaudeException(String msg){ super(msg); } public ProfissionalSaudeException(){ super(MensagemExcessao.ERRO.toString()); } }
apache-2.0
HubSpot/jinjava
src/test/java/com/hubspot/jinjava/lib/filter/UnixTimestampFilterTest.java
847
package com.hubspot.jinjava.lib.filter; import static org.assertj.core.api.Assertions.assertThat; import com.hubspot.jinjava.BaseInterpretingTest; import java.time.ZonedDateTime; import org.junit.After; import org.junit.Before; import org.junit.Test; public class UnixTimestampFilterTest extends BaseInterpretingTest { private final ZonedDateTime d = ZonedDateTime.parse( "2013-11-06T14:22:00.000+00:00[UTC]" ); private final String timestamp = Long.toString(d.toEpochSecond() * 1000); @Before public void setup() { interpreter.getContext().put("d", d); } @After public void tearDown() throws Exception { assertThat(interpreter.getErrorsCopy()).isEmpty(); } @Test public void itRendersFromDate() throws Exception { assertThat(interpreter.renderFlat("{{ d|unixtimestamp }}")).isEqualTo(timestamp); } }
apache-2.0
aiyanbo/restful-hub
src/main/java/org/jmotor/restful/provider/mapper/EntityExistsExceptionMapper.java
906
package org.jmotor.restful.provider.mapper; import org.jmotor.restful.response.ErrorBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityExistsException; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; /** * Component: * Description: * Date: 14-5-13 * * @author Andy Ai */ public class EntityExistsExceptionMapper implements ExceptionMapper<EntityExistsException> { private static final Logger LOGGER = LoggerFactory.getLogger(EntityExistsExceptionMapper.class); @Override public Response toResponse(EntityExistsException exception) { LOGGER.error(exception.getLocalizedMessage(), exception); return ErrorBuilder.newBuilder().message("Entity Already Exists") .error("entity_already_exists", exception.getLocalizedMessage()) .build(Response.Status.CONFLICT); } }
apache-2.0
codemogroup/siddhi
modules/siddhi-core/src/main/java/org/wso2/siddhi/core/executor/condition/compare/CompareConditionExpressionExecutor.java
2090
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.siddhi.core.executor.condition.compare; import org.wso2.siddhi.core.event.ComplexEvent; import org.wso2.siddhi.core.executor.ExpressionExecutor; import org.wso2.siddhi.core.executor.condition.ConditionExpressionExecutor; /** * Parent Executor class for Compare conditions. common evaluation logic is implemented within executor. */ public abstract class CompareConditionExpressionExecutor extends ConditionExpressionExecutor { protected ExpressionExecutor leftExpressionExecutor; protected ExpressionExecutor rightExpressionExecutor; public CompareConditionExpressionExecutor(ExpressionExecutor leftExpressionExecutor, ExpressionExecutor rightExpressionExecutor) { this.leftExpressionExecutor = leftExpressionExecutor; this.rightExpressionExecutor = rightExpressionExecutor; } public Boolean execute(ComplexEvent event) { Object left = leftExpressionExecutor.execute(event); Object right = rightExpressionExecutor.execute(event); return !(left == null || right == null) && execute(left, right); } protected abstract Boolean execute(Object left, Object right); public ExpressionExecutor getLeftExpressionExecutor() { return leftExpressionExecutor; } public ExpressionExecutor getRightExpressionExecutor() { return rightExpressionExecutor; } }
apache-2.0
jvg637upv/TrivialAndroid
app/src/main/java/com/trivial/upv/android/helper/ParcelableHelper.java
1731
/* * Copyright 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trivial.upv.android.helper; import android.os.Parcel; /** * Collection of shared methods ease parcellation of special types. */ public class ParcelableHelper { private ParcelableHelper() { //no instance } /** * Writes a single boolean to a {@link android.os.Parcel}. * * @param dest Destination of the value. * @param toWrite Value to write. * @see ParcelableHelper#readBoolean(android.os.Parcel) */ public static void writeBoolean(Parcel dest, boolean toWrite) { dest.writeInt(toWrite ? 0 : 1); } /** * Retrieves a single boolean from a Parcel. * * @param in The source containing the stored boolean. * @see ParcelableHelper#writeBoolean(android.os.Parcel, boolean) */ public static boolean readBoolean(Parcel in) { return 0 == in.readInt(); } /** * Allows memory efficient parcelation of enums. * * @param dest Destination of the value. * @param e Value to write. */ public static void writeEnumValue(Parcel dest, Enum e) { dest.writeInt(e.ordinal()); } }
apache-2.0
aparod/jonix
jonix-common/src/main/java/com/tectonica/jonix/struct/JonixTextItemIdentifier.java
1218
/* * Copyright (C) 2012 Zach Melamed * * Latest version available online at https://github.com/zach-m/jonix * Contact me at zach@tectonica.co.il * * 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.tectonica.jonix.struct; import java.io.Serializable; import com.tectonica.jonix.codelist.TextItemIdentifierTypes; /* * NOTE: THIS IS AN AUTO-GENERATED FILE, DON'T EDIT MANUALLY */ @SuppressWarnings("serial") public class JonixTextItemIdentifier implements Serializable { /** * The key of this struct */ public TextItemIdentifierTypes textItemIDType; /** * (type: dt.NonEmptyString) */ public String idTypeName; /** * (type: dt.NonEmptyString) */ public String idValue; }
apache-2.0
Sage-Bionetworks/Synapse-Repository-Services
lib/lib-table-query/src/test/java/org/sagebionetworks/table/query/model/JoinConditionTest.java
737
package org.sagebionetworks.table.query.model; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.sagebionetworks.table.query.ParseException; import org.sagebionetworks.table.query.TableQueryParser; class JoinConditionTest { @Test public void testJoinCondition() throws ParseException { JoinCondition joinCondition = new TableQueryParser("on t1.foo = t2.foo").joinCondition(); assertEquals("ON t1.foo = t2.foo", joinCondition.toSql()); } @Test public void testJoinConditionWithPerenteses() throws ParseException { JoinCondition joinCondition = new TableQueryParser("on (t1.foo = t2.foo)").joinCondition(); assertEquals("ON ( t1.foo = t2.foo )", joinCondition.toSql()); } }
apache-2.0
dbeaver/dbeaver
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/impl/struct/AbstractTable.java
3162
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2022 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.model.impl.struct; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.model.DBPDataSource; import org.jkiss.dbeaver.model.DBPEvaluationContext; import org.jkiss.dbeaver.model.DBPNamedObject2; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.meta.Property; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.DBSEntity; import org.jkiss.dbeaver.model.struct.DBSEntityType; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.dbeaver.model.struct.rdb.DBSTable; import org.jkiss.dbeaver.model.struct.rdb.DBSTrigger; import java.util.List; /** * AbstractTable */ public abstract class AbstractTable< DATASOURCE extends DBPDataSource, CONTAINER extends DBSObject> implements DBSTable, DBPNamedObject2 { private CONTAINER container; private String tableName; protected AbstractTable(CONTAINER container) { this.container = container; this.tableName = ""; } // Copy constructor protected AbstractTable(CONTAINER container, DBSEntity source) { this(container); this.tableName = source.getName(); } protected AbstractTable(CONTAINER container, String tableName) { this(container); this.tableName = tableName; } public CONTAINER getContainer() { return container; } @NotNull @Override public DBSEntityType getEntityType() { return DBUtils.isView(this) ? DBSEntityType.VIEW : DBSEntityType.TABLE; } @NotNull @Override @Property(viewable = true, editable = true, order = 1) public String getName() { return tableName; } @Override public void setName(String tableName) { this.tableName = tableName; } @NotNull @Override @SuppressWarnings("unchecked") public DATASOURCE getDataSource() { return (DATASOURCE) container.getDataSource(); } @Override public boolean isPersisted() { return true; } @Override public CONTAINER getParentObject() { return container; } public String toString() { return getFullyQualifiedName(DBPEvaluationContext.UI); } @Nullable @Override public List<? extends DBSTrigger> getTriggers(@NotNull DBRProgressMonitor monitor) throws DBException { return null; } }
apache-2.0
pmk2429/investickation
app/src/main/java/com/sfsu/controllers/GoogleMapController.java
11295
package com.sfsu.controllers; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.location.Location; import android.support.v4.app.Fragment; import android.util.Log; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import com.sfsu.entities.Observation; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Controller to perform all the Google Maps related operations including setting up GoogleMaps in MapView, setting the * InfoWindow on the location etc. * <p/> * A GoogleMaps Controller to setup and initialize all the Google Map related operations and processes. LocationController * provides methods to setup Google Maps, display and render, verify the API KEY registered in the Google Dev Console and so on. * <p/> * Created by Pavitra on 11/16/2015. */ public class GoogleMapController implements GoogleMap.OnMarkerClickListener , GoogleMap.OnInfoWindowClickListener , OnMapReadyCallback { Map<Marker, Observation> markerObservationMap; private Context mContext; private String TAG = "~!@#$GMapCtrl :"; private GoogleMap mGoogleMap; private LatLng mCurrentLatLng; private Location mLocation; private IMarkerClickCallBack mInterface; /** * Setting the Location change listener for the Maps */ private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() { @Override public void onMyLocationChange(Location location) { mLocation = location; mCurrentLatLng = new LatLng(location.getLatitude(), location.getLongitude()); moveCameraToPosition(mCurrentLatLng); } }; /** * Constructor overloading for setting up LocationController in Fragment. * * @param mContext * @param fragment */ public GoogleMapController(Context mContext, Fragment fragment) { try { this.mContext = mContext; mInterface = (IMarkerClickCallBack) fragment; // build GoogleApiClient markerObservationMap = new HashMap<>(); } catch (Exception e) { } } /** * Default constructor * * @param mContext */ public GoogleMapController(Context mContext) { try { this.mContext = mContext; markerObservationMap = new HashMap<>(); } catch (Exception e) { Log.i(TAG, e.getMessage()); } } /** * Constructor overloading for using LocationController in Activity * * @param mContext * @param activity */ public GoogleMapController(Context mContext, Activity activity) { try { this.mContext = mContext; markerObservationMap = new HashMap<>(); } catch (Exception e) { Log.i(TAG, e.getMessage()); } } /** * Sets up the Google Map and locates the current Account Location. */ public void setupGoogleMap(MapView mapView) { if (mapView != null) { // Gets to GoogleMap from the MapView and does initialization stuff mapView.getMapAsync(this); } } @Override public void onMapReady(GoogleMap googleMap) { mGoogleMap = googleMap; if (mGoogleMap != null) { // Needs to call MapsInitializer before doing any CameraUpdateFactory calls try { initializeGoogleMap(); MapsInitializer.initialize(mContext); } catch (Exception e) { e.printStackTrace(); } mGoogleMap.setOnMyLocationChangeListener(myLocationChangeListener); } else { Log.i(TAG, "MapView is NULL"); } } public void initializeGoogleMap() { // enabled all the settings mGoogleMap.setMyLocationEnabled(true); mGoogleMap.getUiSettings().setZoomControlsEnabled(true); mGoogleMap.getUiSettings().setCompassEnabled(true); mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true); mGoogleMap.getUiSettings().setRotateGesturesEnabled(true); mGoogleMap.getUiSettings().setScrollGesturesEnabled(true); mGoogleMap.getUiSettings().setTiltGesturesEnabled(true); mGoogleMap.getUiSettings().setZoomGesturesEnabled(true); } /** * Instantiates a new Polyline object on {@link GoogleMap} and adds points to define a rectangle. * * @param latLngs Array of {@link LatLng} */ public void setUpPolylineOnMap(LatLng[] latLngs) { moveCameraToPosition(latLngs[2]); PolylineOptions drawOptions = new PolylineOptions().width(7).color(Color.BLUE).geodesic(true); for (int i = 0; i < latLngs.length; i++) { drawOptions.add(latLngs[i]); } // Get back the mutable Polyline mGoogleMap.addPolyline(drawOptions); showMarker(latLngs); } /** * Instantiates a new Polyline object on {@link GoogleMap} and adds points to define a rectangle. * * @param latLngs Array of {@link LatLng} */ public void setUpPolylineOnMap(ArrayList<Observation> mObservationsList) { try { // build LatLngs array from ObservationListFragment LatLng[] mLatLngs = getLatLngArray(mObservationsList); moveCameraToPosition(mLatLngs[0]); PolylineOptions drawOptions = new PolylineOptions().width(7).color(Color.BLUE).geodesic(true); for (int i = 0; i < mLatLngs.length; i++) { drawOptions.add(mLatLngs[i]); } // Get back the mutable Polyline mGoogleMap.addPolyline(drawOptions); // finally show marker showMarker(mObservationsList); } catch (Exception e) { } } /** * Get LatLng Array from ArrayList of Observations * * @param mObservationsList * @return */ private LatLng[] getLatLngArray(ArrayList<Observation> mObservationsList) { LatLng[] mLatLngs = new LatLng[mObservationsList.size()]; for (int i = 0; i < mObservationsList.size(); i++) { mLatLngs[i] = new LatLng(mObservationsList.get(i).getLocation().getLatitude(), mObservationsList.get(i) .getLocation().getLongitude()); } return mLatLngs; } /** * Method to display marker on GoogleMaps for the {@link LatLng} specified. */ public void showMarker(LatLng[] latLngs) { MarkerOptions mMarkerOptions = new MarkerOptions(); if (latLngs != null || latLngs.length > 0) { for (int i = 0; i < latLngs.length; i++) { mMarkerOptions.position(latLngs[i]); // once the Markers are all set, display the title and the snippet. mMarkerOptions.title(i + "Random Text").snippet(""); Marker mMarker = mGoogleMap.addMarker(mMarkerOptions); } } else { mMarkerOptions.position(mCurrentLatLng); // once the Markers are all set, display the title and the snippet. mMarkerOptions.title("It works") .snippet("Population: 20,000"); Marker mMarker = mGoogleMap.addMarker(mMarkerOptions); } } /** * Method to display marker on GoogleMaps for all the {@link Observation}. It is used to display all the * {@link com.sfsu.entities.Observation} of an {@link com.sfsu.entities.Activities}. */ public void showMarker(List<Observation> mObservationsList) { MarkerOptions mMarkerOptions = new MarkerOptions(); if (mObservationsList != null || mObservationsList.size() > 0) { for (int i = 0; i < mObservationsList.size(); i++) { // get the Observation Observation mObservation = mObservationsList.get(i); LatLng mLatLng = new LatLng(mObservation.getLocation().getLatitude(), mObservation.getLocation().getLongitude()); mMarkerOptions.position(mLatLng); // once the Markers are all set, display the title and the snippet. mMarkerOptions.title(mObservation.getTickName()).snippet(mObservation.getGeoLocation()); Marker mMarker = mGoogleMap.addMarker(mMarkerOptions); // add Marker and Observation to HashMap markerObservationMap.put(mMarker, mObservation); Log.i(TAG, markerObservationMap.size() + ""); //mGoogleMap.setOnInfoWindowClickListener(this); mGoogleMap.setOnMarkerClickListener(this); } } else { mMarkerOptions.position(mCurrentLatLng); // once the Markers are all set, display the title and the snippet. mMarkerOptions.title("You are here").snippet("No data"); Marker mMarker = mGoogleMap.addMarker(mMarkerOptions); } } /** * Helper method to move the camera to the position passed as param. When this method is called, OnMyLocationChangeListener * is set to null. * * @param mLatLng */ private void moveCameraToPosition(LatLng mLatLng) { mGoogleMap.setMyLocationEnabled(false); mGoogleMap.setOnMyLocationChangeListener(null); mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mLatLng, 14.0f)); } /** * Helper method to clear all the resources; GoogleMap, GoogleMapController and everything. */ public void clear() { this.mGoogleMap = null; this.mContext = null; this.myLocationChangeListener = null; } @Override public boolean onMarkerClick(Marker marker) { try { // when the user clicks the Marker, get the Observation and pass it on to Callback //mInterface.onMarkerClickListener(marker); Observation mObservation = markerObservationMap.get(marker); mInterface.onMarkerClickObservationListener(mObservation); } catch (NullPointerException e) { } catch (Exception e) { } return true; } @Override public void onInfoWindowClick(Marker marker) { } /** * Callback interface for {@link Marker} onClick Listener. */ public interface IMarkerClickCallBack { void onMarkerClickListener(Marker marker); void onMarkerClickObservationListener(Observation mObservation); } }
apache-2.0
wangzijian777/contentManager
content/src/java/cn/com/hy369/resourcetype/web/ResourceTypeAction.java
4430
package cn.com.hy369.resourcetype.web; import java.util.List; import cn.com.hy369.model.NoCode; import cn.com.hy369.model.Resource; import cn.com.hy369.model.ResourceType; import cn.com.hy369.noCode.service.facade.NoCodeService; import cn.com.hy369.resource.service.facade.ResourceService; import cn.com.hy369.resourcetype.service.facade.ResourceTypeService; import ins.framework.common.QueryRule; import ins.framework.exception.BusinessException; import ins.framework.web.Struts2Action; @SuppressWarnings("serial") public class ResourceTypeAction extends Struts2Action{ // 一些页面用到的变量 private String resourceTypeContent; private String actionType; // 用来确定是更新还是新增的 private ResourceType resourceType; // 一些需要载入的service private ResourceTypeService resourceTypeService ; private ResourceService resourceService; private NoCodeService noCodeService; public String prepareQueryResourceType(){ return SUCCESS; } /** * 绘出菜单部分 * @return */ public String queryResourceTypeTree(){ resourceTypeContent = resourceTypeService.showResourceType(); return SUCCESS; } /** * 准备增加,会获取一分部分页面信息来进行初始化的 * @return */ public String prepareAddResourceType(){ actionType = "add"; resourceType.setSystemCode("hy369"); resourceType.setValidStatus("1"); return SUCCESS; } public String addResourceType(){ // 如果是顶级的菜单就用369+单位数,如果是刺激菜单就是上一级菜单加上双位数。 String tableName = "typelevel" + resourceType.getTypeLevel(); int maxNo = noCodeService.findMaxNo(tableName); if("1".equals(resourceType.getUpperTypeID())){ resourceType.setTypeID("369" + maxNo++); }else{ resourceType.setTypeID(resourceType.getUpperTypeID() + maxNo++); } // 保存最大号 NoCode noCode = new NoCode(); noCode.setMaxNo(maxNo); noCode.setTableName(tableName); noCodeService.deleteNoCode(tableName); noCodeService.addNoCode(noCode); resourceTypeService.addResourceType(resourceType); return SUCCESS; } public String queryResourceTypeMenu(){ return SUCCESS; } public String resourceTypeManager(){ String typeID = resourceType.getTypeID(); resourceType = resourceTypeService.findResourceTypeUnion(typeID); return SUCCESS; } public String prepareUpdateResourceType(){ actionType = "update"; String typeID = resourceType.getTypeID(); resourceType = resourceTypeService.findResourceTypeUnion(typeID); return SUCCESS; } public String updateResourceType(){ resourceTypeService.updateResourceType(resourceType); return SUCCESS; } public String deleteResourceType(){ String typeID = resourceType.getTypeID(); QueryRule queryRule = QueryRule.getInstance(); queryRule.addEqual("typeID", typeID); List<Resource> resourceList = resourceService.findResourceByRule(queryRule); if(resourceList != null && !resourceList.isEmpty()){ throw new BusinessException("存在下级资源不能进行删除",true); } resourceTypeService.deleteTypeID(typeID); return SUCCESS; } //------------------------------------华丽的分割线----------------------------- public String getResourceTypeContent() { return resourceTypeContent; } public void setResourceTypeContent(String resourceTypeContent) { this.resourceTypeContent = resourceTypeContent; } public ResourceTypeService getResourceTypeService() { return resourceTypeService; } public void setResourceTypeService(ResourceTypeService resourceTypeService) { this.resourceTypeService = resourceTypeService; } public String getActionType() { return actionType; } public void setActionType(String actionType) { this.actionType = actionType; } public ResourceType getResourceType() { return resourceType; } public void setResourceType(ResourceType resourceType) { this.resourceType = resourceType; } public ResourceService getResourceService() { return resourceService; } public void setResourceService(ResourceService resourceService) { this.resourceService = resourceService; } public NoCodeService getNoCodeService() { return noCodeService; } public void setNoCodeService(NoCodeService noCodeService) { this.noCodeService = noCodeService; } }
apache-2.0
ra0077/jmeter
src/core/org/apache/jmeter/gui/action/LoggerPanelEnableDisable.java
2641
/* * 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.jmeter.gui.action; import java.awt.event.ActionEvent; import java.util.HashSet; import java.util.Set; import javax.swing.JSplitPane; import javax.swing.UIManager; import org.apache.jmeter.gui.GuiPackage; /** * Hide / unhide LoggerPanel. * */ public class LoggerPanelEnableDisable extends AbstractAction { private static final Set<String> commands = new HashSet<>(); static { commands.add(ActionNames.LOGGER_PANEL_ENABLE_DISABLE); } /** * Constructor for object. */ public LoggerPanelEnableDisable() { } /** * Gets the ActionNames attribute of the action * * @return the ActionNames value */ @Override public Set<String> getActionNames() { return commands; } /** * This method performs the actual command processing. * * @param e the generic UI action event */ @Override public void doAction(ActionEvent e) { if (ActionNames.LOGGER_PANEL_ENABLE_DISABLE.equals(e.getActionCommand())) { GuiPackage guiInstance = GuiPackage.getInstance(); JSplitPane splitPane = (JSplitPane) guiInstance.getLoggerPanel().getParent(); if (!guiInstance.getLoggerPanel().isVisible()) { splitPane.setDividerSize(UIManager.getInt("SplitPane.dividerSize")); guiInstance.getLoggerPanel().setVisible(true); splitPane.setDividerLocation(0.8); guiInstance.getMenuItemLoggerPanel().getModel().setSelected(true); } else { guiInstance.getLoggerPanel().clear(); guiInstance.getLoggerPanel().setVisible(false); splitPane.setDividerSize(0); guiInstance.getMenuItemLoggerPanel().getModel().setSelected(false); } } } }
apache-2.0
cocoatomo/asakusafw
mapreduce/compiler/core/src/main/java/com/asakusafw/compiler/flow/DataClassRepository.java
1312
/** * Copyright 2011-2017 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.compiler.flow; /** * Repository of {@link DataClass}. * <p> * Adding data model kinds to Flow DSL compiler, clients can implement this and put the class name in * {@code META-INF/services/com.asakusafw.compiler.flow.DataClassRepository}. * </p> */ public interface DataClassRepository extends FlowCompilingEnvironment.Initializable { /** * Loads a mirror of data model class. * @param type the target type * @return the corresponded data model mirror, or {@code null} if the target type is not a valid data model class * @throws IllegalArgumentException if the parameter is {@code null} */ DataClass load(java.lang.reflect.Type type); }
apache-2.0
not-my-name/ExperimentsRerun
src/main/java/za/redbridge/simulator/Utils.java
5858
package za.redbridge.simulator; import org.jbox2d.common.MathUtils; import org.jbox2d.common.Vec2; import java.util.Random; import ec.util.MersenneTwisterFast; import sim.util.Double2D; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import za.redbridge.simulator.Simulation; import za.redbridge.simulator.factories.SimulationFactory; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.InetAddress; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by jamie on 2014/08/01. */ public final class Utils { public static final double TWO_PI = Math.PI * 2; public static final double EPSILON = 1e-6; public static final Random RANDOM = new Random(); private static final Logger log = LoggerFactory.getLogger(Utils.class); private static String directoryName; private Utils() { } public static void setDirectoryName(String newDirName) { directoryName = newDirName; } public static double randomRange(MersenneTwisterFast rand, double from, double to) { if (from >= to) { throw new IllegalArgumentException("`from` must be less than `to`"); } double range = to - from; return rand.nextDouble() * range + from; } public static float randomRange(MersenneTwisterFast rand, float from, float to) { if (from >= to) { throw new IllegalArgumentException("`from` must be less than `to`"); } float range = to - from; return rand.nextFloat() * range + from; } public static float randomUniformRange(float from, float to) { Random rand = new Random(); if (from >= to) { throw new IllegalArgumentException("`from` must be less than `to`"); } float range = to - from; return rand.nextFloat() * range + from; } public static Vec2 toVec2(Double2D double2D) { return new Vec2((float) double2D.x, (float) double2D.y); } public static Double2D toDouble2D(Vec2 vec2) { return new Double2D(vec2.x, vec2.y); } /** Wrap an angle between (-PI, PI] */ public static double wrapAngle(double angle) { angle %= TWO_PI; if (angle > Math.PI) { angle -= TWO_PI; } else if (angle <= -Math.PI) { angle += TWO_PI; } return angle; } public static boolean isNearlyZero(double x) { return x > -EPSILON && x < EPSILON; } public static Vec2 jitter(Vec2 vec, float magnitude) { if (vec != null) { vec.x += magnitude * RANDOM.nextFloat() - magnitude / 2; vec.y += magnitude * RANDOM.nextFloat() - magnitude / 2; return vec; } return null; } /** Get a random angle in the range [-PI / 2, PI / 2] */ public static float randomAngle(MersenneTwisterFast random) { return MathUtils.TWOPI * random.nextFloat() - MathUtils.PI; } /** Check if a String is either null or empty. */ public static boolean isBlank(String s) { return s == null || s.isEmpty(); } /** * Reads a serialized object instance from a file. * @param filepath the String representation of the path to the file * @return the deserialized object, or null if the object could not be deserialised */ public static Object readObjectFromFile(String filepath) { Path path = Paths.get(filepath); Object object = null; try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(path))) { object = in.readObject(); } catch (IOException | ClassNotFoundException e) { log.error("Unable to load object from file", e); } return object; } public static void saveObjectToFile(Serializable object, String filepath) { Path path = Paths.get(filepath); saveObjectToFile(object, path); } public static void saveObjectToFile(Serializable object, Path path) { try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(path))) { out.writeObject(object); } catch (IOException e) { log.error("Unable to save object to file", e); } } public static Path getLoggingDirectory() { String hostname = getLocalHostName(); if (hostname == null) { hostname = "unknown"; } // String date = new SimpleDateFormat("yyyyMMdd'T'HHmm").format(new Date()); // // String method = "NEAT"; // //return Paths.get("results", hostname + "-" + date); // String HexArrayCounter = System.getenv().get("PBS_ARRAYID"); // return Paths.get("results", "Hex" + "-" + date + "_" + HexArrayCounter+"_"+Main.RES_CONFIG+"_"+method); return Paths.get("results", directoryName); } public static Path getParamLoggingDirectory(String params) { String hostname = getLocalHostName(); if (hostname == null) { hostname = "unknown"; } String date = new SimpleDateFormat("yyyyMMdd'T'HHmm").format(new Date()); String method = "NEAT"; //return Paths.get("results", hostname + "-" + date); String HexArrayCounter = System.getenv().get("PBS_ARRAYID"); return Paths.get("paramTuning/results/" + params, "Hex" + "-" + date + "_" + HexArrayCounter+"_"+Main.RES_CONFIG+"_"+method); } public static String getLocalHostName() { try { return InetAddress.getLocalHost().getHostName(); } catch (IOException e) { log.error("Unable to query host name", e); } return null; } }
apache-2.0
bigbugbb/iTracker
app/src/main/java/com/itracker/android/service/download/DownloadTaskComparator.java
233
package com.itracker.android.service.download; import java.util.Comparator; class DownloadTaskComparator implements Comparator<Runnable> { @Override public int compare(Runnable lhs, Runnable rhs) { return 0; } }
apache-2.0
shiguang1120/c2d-engine
c2d/src/info/u250/c2d/engine/tools/CrackTextureAtlasTool.java
3717
package info.u250.c2d.engine.tools; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Transparency; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.g2d.TextureAtlas.TextureAtlasData; import com.badlogic.gdx.graphics.g2d.TextureAtlas.TextureAtlasData.Region; /** * <pre> public class ExportPackerTool extends ApplicationAdapter{ @Override public void create() { try { ExportTextureAtlasTool.decode("E:/codes/dig/digs-desktop/assets/data/all.atlas","C:/Users/Administrator/Desktop/test/"); } catch (Exception e) { e.printStackTrace(); } super.create(); } public static void main(String args[]){ LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.width = 10; config.height= 10; new LwjglApplication(new ExportPackerTool(),config); } } * </pre> * */ public class CrackTextureAtlasTool{ //absolute path public static void crack(String srcAtlas,String dstDir) throws Exception{ FileHandle fh = Gdx.files.absolute(srcAtlas); TextureAtlasData data = new TextureAtlasData(fh, fh.parent(),false); File dir = new File(dstDir); if(!dir.exists()){ dir.mkdirs(); System.out.println("mkdirs:"+dstDir); } for(Region region:data.getRegions()){ File file = region.page.textureFile.file(); BufferedImage root = ImageIO.read(file); String fileName = region.name ; int sizeWidth = region.originalWidth; int sizeHeight= region.originalHeight; int width = region.width; int height= region.height; int x = region.left ; int y = region.top ; int offsetX = (int)region.offsetX; int offsetY = (int)region.offsetY; BufferedImage canvas = null; if(region.rotate){ canvas = new BufferedImage(height, width, BufferedImage.TYPE_INT_ARGB); canvas.getGraphics().drawImage(root, 0, 0, height, width, x, y, x+height, y+width, null); }else{ canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); canvas.getGraphics().drawImage(root, 0, 0, width, height, x, y, x+width, y+height, null); } if(offsetX!=0 || offsetY!=0){ BufferedImage canvas2 = canvas; canvas = new BufferedImage(sizeWidth, sizeHeight, BufferedImage.TYPE_INT_ARGB); canvas.getGraphics().drawImage(canvas2, offsetX, offsetY, width, height, 0, 0, width, height, null); } if(region.rotate){ canvas = rotate(canvas, Math.toRadians(90)); } ImageIO.write(canvas, "png", new File(dstDir+fileName+".png")); System.out.println("Proccess to "+dstDir+fileName +".png" + " offsetX:"+region.offsetX+",offsetY:"+region.offsetY +" rotate:"+region.rotate); } } private static BufferedImage rotate(BufferedImage image, double angle) { double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle)); int w = image.getWidth(), h = image.getHeight(); int neww = (int)Math.floor(w*cos+h*sin), newh = (int)Math.floor(h*cos+w*sin); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] gd = ge.getScreenDevices(); GraphicsConfiguration gc = gd[0].getDefaultConfiguration(); BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT); Graphics2D g = result.createGraphics(); g.translate((neww-w)/2, (newh-h)/2); g.rotate(angle, w/2, h/2); g.drawRenderedImage(image, null); g.dispose(); return result; } }
apache-2.0
ebyhr/presto
core/trino-main/src/main/java/io/trino/operator/aggregation/AbstractMinMaxAggregationFunction.java
14499
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.operator.aggregation; import com.google.common.collect.ImmutableList; import io.trino.annotation.UsedByGeneratedCode; import io.trino.metadata.AggregationFunctionMetadata; import io.trino.metadata.BoundSignature; import io.trino.metadata.FunctionDependencies; import io.trino.metadata.FunctionDependencyDeclaration; import io.trino.metadata.FunctionMetadata; import io.trino.metadata.FunctionNullability; import io.trino.metadata.Signature; import io.trino.metadata.SqlAggregationFunction; import io.trino.operator.aggregation.AggregationFunctionAdapter.AggregationParameterKind; import io.trino.operator.aggregation.AggregationMetadata.AccumulatorStateDescriptor; import io.trino.operator.aggregation.state.BlockPositionState; import io.trino.operator.aggregation.state.BlockPositionStateSerializer; import io.trino.operator.aggregation.state.GenericBooleanState; import io.trino.operator.aggregation.state.GenericBooleanStateSerializer; import io.trino.operator.aggregation.state.GenericDoubleState; import io.trino.operator.aggregation.state.GenericDoubleStateSerializer; import io.trino.operator.aggregation.state.GenericLongState; import io.trino.operator.aggregation.state.GenericLongStateSerializer; import io.trino.operator.aggregation.state.StateCompiler; import io.trino.spi.block.Block; import io.trino.spi.block.BlockBuilder; import io.trino.spi.function.InvocationConvention; import io.trino.spi.type.Type; import io.trino.spi.type.TypeSignature; import java.lang.invoke.MethodHandle; import java.util.List; import java.util.Optional; import static io.trino.metadata.FunctionKind.AGGREGATE; import static io.trino.metadata.Signature.orderableTypeParameter; import static io.trino.operator.aggregation.AggregationFunctionAdapter.AggregationParameterKind.BLOCK_INDEX; import static io.trino.operator.aggregation.AggregationFunctionAdapter.AggregationParameterKind.BLOCK_INPUT_CHANNEL; import static io.trino.operator.aggregation.AggregationFunctionAdapter.AggregationParameterKind.INPUT_CHANNEL; import static io.trino.operator.aggregation.AggregationFunctionAdapter.AggregationParameterKind.STATE; import static io.trino.operator.aggregation.AggregationFunctionAdapter.normalizeInputMethod; import static io.trino.spi.function.InvocationConvention.InvocationArgumentConvention.BLOCK_POSITION; import static io.trino.spi.function.InvocationConvention.InvocationArgumentConvention.NEVER_NULL; import static io.trino.spi.function.InvocationConvention.InvocationReturnConvention.FAIL_ON_NULL; import static io.trino.spi.function.InvocationConvention.simpleConvention; import static io.trino.util.Failures.internalError; import static io.trino.util.MinMaxCompare.getMinMaxCompare; import static io.trino.util.MinMaxCompare.getMinMaxCompareFunctionDependencies; import static io.trino.util.Reflection.methodHandle; public abstract class AbstractMinMaxAggregationFunction extends SqlAggregationFunction { private static final MethodHandle LONG_INPUT_FUNCTION = methodHandle(AbstractMinMaxAggregationFunction.class, "input", MethodHandle.class, GenericLongState.class, long.class); private static final MethodHandle DOUBLE_INPUT_FUNCTION = methodHandle(AbstractMinMaxAggregationFunction.class, "input", MethodHandle.class, GenericDoubleState.class, double.class); private static final MethodHandle BOOLEAN_INPUT_FUNCTION = methodHandle(AbstractMinMaxAggregationFunction.class, "input", MethodHandle.class, GenericBooleanState.class, boolean.class); private static final MethodHandle BLOCK_POSITION_INPUT_FUNCTION = methodHandle(AbstractMinMaxAggregationFunction.class, "input", MethodHandle.class, BlockPositionState.class, Block.class, int.class); private static final MethodHandle LONG_OUTPUT_FUNCTION = methodHandle(GenericLongState.class, "write", Type.class, GenericLongState.class, BlockBuilder.class); private static final MethodHandle DOUBLE_OUTPUT_FUNCTION = methodHandle(GenericDoubleState.class, "write", Type.class, GenericDoubleState.class, BlockBuilder.class); private static final MethodHandle BOOLEAN_OUTPUT_FUNCTION = methodHandle(GenericBooleanState.class, "write", Type.class, GenericBooleanState.class, BlockBuilder.class); private static final MethodHandle BLOCK_POSITION_OUTPUT_FUNCTION = methodHandle(BlockPositionState.class, "write", Type.class, BlockPositionState.class, BlockBuilder.class); private static final MethodHandle LONG_COMBINE_FUNCTION = methodHandle(AbstractMinMaxAggregationFunction.class, "combine", MethodHandle.class, GenericLongState.class, GenericLongState.class); private static final MethodHandle DOUBLE_COMBINE_FUNCTION = methodHandle(AbstractMinMaxAggregationFunction.class, "combine", MethodHandle.class, GenericDoubleState.class, GenericDoubleState.class); private static final MethodHandle BOOLEAN_COMBINE_FUNCTION = methodHandle(AbstractMinMaxAggregationFunction.class, "combine", MethodHandle.class, GenericBooleanState.class, GenericBooleanState.class); private static final MethodHandle BLOCK_POSITION_COMBINE_FUNCTION = methodHandle(AbstractMinMaxAggregationFunction.class, "combine", MethodHandle.class, BlockPositionState.class, BlockPositionState.class); private final boolean min; protected AbstractMinMaxAggregationFunction(String name, boolean min, String description) { super( new FunctionMetadata( new Signature( name, ImmutableList.of(orderableTypeParameter("E")), ImmutableList.of(), new TypeSignature("E"), ImmutableList.of(new TypeSignature("E")), false), new FunctionNullability(true, ImmutableList.of(false)), false, true, description, AGGREGATE), new AggregationFunctionMetadata( false, new TypeSignature("E"))); this.min = min; } @Override public FunctionDependencyDeclaration getFunctionDependencies() { return getMinMaxCompareFunctionDependencies(new TypeSignature("E"), min); } @Override public AggregationMetadata specialize(BoundSignature boundSignature, FunctionDependencies functionDependencies) { Type type = boundSignature.getArgumentTypes().get(0); InvocationConvention invocationConvention; if (type.getJavaType().isPrimitive()) { invocationConvention = simpleConvention(FAIL_ON_NULL, NEVER_NULL, NEVER_NULL); } else { invocationConvention = simpleConvention(FAIL_ON_NULL, BLOCK_POSITION, BLOCK_POSITION); } MethodHandle compareMethodHandle = getMinMaxCompare(functionDependencies, type, invocationConvention, min); MethodHandle inputFunction; MethodHandle combineFunction; MethodHandle outputFunction; AccumulatorStateDescriptor<?> accumulatorStateDescriptor; if (type.getJavaType() == long.class) { accumulatorStateDescriptor = new AccumulatorStateDescriptor<>( GenericLongState.class, new GenericLongStateSerializer(type), StateCompiler.generateStateFactory(GenericLongState.class)); inputFunction = LONG_INPUT_FUNCTION.bindTo(compareMethodHandle); combineFunction = LONG_COMBINE_FUNCTION.bindTo(compareMethodHandle); outputFunction = LONG_OUTPUT_FUNCTION.bindTo(type); } else if (type.getJavaType() == double.class) { accumulatorStateDescriptor = new AccumulatorStateDescriptor<>( GenericDoubleState.class, new GenericDoubleStateSerializer(type), StateCompiler.generateStateFactory(GenericDoubleState.class)); inputFunction = DOUBLE_INPUT_FUNCTION.bindTo(compareMethodHandle); combineFunction = DOUBLE_COMBINE_FUNCTION.bindTo(compareMethodHandle); outputFunction = DOUBLE_OUTPUT_FUNCTION.bindTo(type); } else if (type.getJavaType() == boolean.class) { accumulatorStateDescriptor = new AccumulatorStateDescriptor<>( GenericBooleanState.class, new GenericBooleanStateSerializer(type), StateCompiler.generateStateFactory(GenericBooleanState.class)); inputFunction = BOOLEAN_INPUT_FUNCTION.bindTo(compareMethodHandle); combineFunction = BOOLEAN_COMBINE_FUNCTION.bindTo(compareMethodHandle); outputFunction = BOOLEAN_OUTPUT_FUNCTION.bindTo(type); } else { // native container type is Object accumulatorStateDescriptor = new AccumulatorStateDescriptor<>( BlockPositionState.class, new BlockPositionStateSerializer(type), StateCompiler.generateStateFactory(BlockPositionState.class)); inputFunction = BLOCK_POSITION_INPUT_FUNCTION.bindTo(compareMethodHandle); combineFunction = BLOCK_POSITION_COMBINE_FUNCTION.bindTo(compareMethodHandle); outputFunction = BLOCK_POSITION_OUTPUT_FUNCTION.bindTo(type); } inputFunction = normalizeInputMethod(inputFunction, boundSignature, createInputParameterKinds(type)); return new AggregationMetadata( inputFunction, Optional.empty(), Optional.of(combineFunction), outputFunction, ImmutableList.of(accumulatorStateDescriptor)); } private static List<AggregationParameterKind> createInputParameterKinds(Type type) { if (type.getJavaType().isPrimitive()) { return ImmutableList.of( STATE, INPUT_CHANNEL); } else { return ImmutableList.of( STATE, BLOCK_INPUT_CHANNEL, BLOCK_INDEX); } } @UsedByGeneratedCode public static void input(MethodHandle methodHandle, GenericDoubleState state, double value) { compareAndUpdateState(methodHandle, state, value); } @UsedByGeneratedCode public static void input(MethodHandle methodHandle, GenericLongState state, long value) { compareAndUpdateState(methodHandle, state, value); } @UsedByGeneratedCode public static void input(MethodHandle methodHandle, GenericBooleanState state, boolean value) { compareAndUpdateState(methodHandle, state, value); } @UsedByGeneratedCode public static void input(MethodHandle methodHandle, BlockPositionState state, Block block, int position) { compareAndUpdateState(methodHandle, state, block, position); } @UsedByGeneratedCode public static void combine(MethodHandle methodHandle, GenericLongState state, GenericLongState otherState) { compareAndUpdateState(methodHandle, state, otherState.getValue()); } @UsedByGeneratedCode public static void combine(MethodHandle methodHandle, GenericDoubleState state, GenericDoubleState otherState) { compareAndUpdateState(methodHandle, state, otherState.getValue()); } @UsedByGeneratedCode public static void combine(MethodHandle methodHandle, GenericBooleanState state, GenericBooleanState otherState) { compareAndUpdateState(methodHandle, state, otherState.getValue()); } @UsedByGeneratedCode public static void combine(MethodHandle methodHandle, BlockPositionState state, BlockPositionState otherState) { compareAndUpdateState(methodHandle, state, otherState.getBlock(), otherState.getPosition()); } private static void compareAndUpdateState(MethodHandle methodHandle, GenericLongState state, long value) { if (state.isNull()) { state.setNull(false); state.setValue(value); return; } try { if ((boolean) methodHandle.invokeExact(value, state.getValue())) { state.setValue(value); } } catch (Throwable t) { throw internalError(t); } } private static void compareAndUpdateState(MethodHandle methodHandle, GenericDoubleState state, double value) { if (state.isNull()) { state.setNull(false); state.setValue(value); return; } try { if ((boolean) methodHandle.invokeExact(value, state.getValue())) { state.setValue(value); } } catch (Throwable t) { throw internalError(t); } } private static void compareAndUpdateState(MethodHandle methodHandle, GenericBooleanState state, boolean value) { if (state.isNull()) { state.setNull(false); state.setValue(value); return; } try { if ((boolean) methodHandle.invokeExact(value, state.getValue())) { state.setValue(value); } } catch (Throwable t) { throw internalError(t); } } private static void compareAndUpdateState(MethodHandle methodHandle, BlockPositionState state, Block block, int position) { if (state.isNull()) { state.setBlock(block); state.setPosition(position); return; } try { if ((boolean) methodHandle.invokeExact(block, position, state.getBlock(), state.getPosition())) { state.setBlock(block); state.setPosition(position); } } catch (Throwable t) { throw internalError(t); } } }
apache-2.0
openwide-java/owsi-core-parent
owsi-core/owsi-core-components/owsi-core-component-rest-jersey/src/test/java/fr/openwide/test/core/rest/jersey/RestTestApplication.java
247
package fr.openwide.test.core.rest.jersey; import fr.openwide.core.rest.jersey.AbstractRestApplication; public class RestTestApplication extends AbstractRestApplication { public RestTestApplication() { super(RestTestApplication.class); } }
apache-2.0